diff --git a/.gitignore b/.gitignore index 9a5aced..f30195a 100644 --- a/.gitignore +++ b/.gitignore @@ -25,12 +25,6 @@ coverage # nyc test coverage .nyc_output -# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Bower dependency directory (https://bower.io/) -bower_components - # node-waf configuration .lock-wscript @@ -41,12 +35,6 @@ build/Release node_modules/ jspm_packages/ -# Snowpack dependency directory (https://snowpack.dev/) -web_modules/ - -# TypeScript cache -*.tsbuildinfo - # Optional npm cache directory .npm @@ -62,78 +50,17 @@ web_modules/ # Output of 'npm pack' *.tgz -# Yarn Integrity file -.yarn-integrity - # dotenv environment variable files .env .env.* !.env.example -# parcel-bundler cache (https://parceljs.org/) -.cache -.parcel-cache - -# Next.js build output -.next -out - -# Nuxt.js build / generate output -.nuxt -dist - -# Gatsby files -.cache/ -# Comment in the public line in if your project uses Gatsby and not Next.js -# https://nextjs.org/blog/next-9-1#public-directory-support -# public - -# vuepress build output -.vuepress/dist - -# vuepress v2.x temp and cache directory -.temp -.cache - -# Sveltekit cache directory -.svelte-kit/ - -# vitepress build output -**/.vitepress/dist - -# vitepress cache directory -**/.vitepress/cache - -# Docusaurus cache and generated files -.docusaurus - # Serverless directories .serverless/ -# FuseBox cache -.fusebox/ - -# DynamoDB Local files -.dynamodb/ - -# Firebase cache directory -.firebase/ - -# TernJS port file -.tern-port - # Stores VSCode versions used for testing VSCode extensions .vscode-test -# yarn v3 -.pnp.* -.yarn/* -!.yarn/patches -!.yarn/plugins -!.yarn/releases -!.yarn/sdks -!.yarn/versions - -# Vite logs files -vite.config.js.timestamp-* -vite.config.ts.timestamp-* + +playwright-report/ +test-results/ \ No newline at end of file diff --git a/README.md b/README.md index e140bc9..ab49302 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,132 @@ # veri-good -web component for verifying Verifiable Credentials + +A [Web Component](https://developer.mozilla.org/en-US/docs/Web/API/Web_components) for verifying [Verifiable Credentials](https://www.w3.org/TR/vc-data-model-2.0/). + +Web components are custom HTML tags that work natively with all modern browsers, and can therefore be dropped into any HTML page, which you'd do like so for the veri-good element: + +``` + + + + + veri-good! + + +
+
+ +
+ + + +``` + +You'll therefore need to have saved that bundle.js (which is in the dist directory of this repository) to your server. + +If you are using a bundler (webpack, rollup, etc.) import the module which we've published to npm: + +`import '@digitalcredentials/veri-good'` + +The import automagically registers the component with the browser. Use the tag wherever you like. + +We also provide a separate package that wraps the web component in a react element: + +* [@digitalcredentials/veri-good-react github repo](https://github.com/digitalcredentials/veri-good-react) +* [@digitalcredentials/veri-good-react npm package](https://github.com/digitalcredentials/veri-good-react) + +TODO: fix above links to react packages once published + +### Issuer List + + The signing DID for each credential is looked up in the issuer list. For the moment it defaults to the above list, i.e., + + ```https://digitalcredentials.github.io/dcc-known-registries/known-did-registries.json``` + +You can look at that list as an example of how to build your own. + +You set the issuer list in a template inside the `veri-good` tag like so: + + ``` + + + + + + + ``` + +Use the same json structure for your own list. + +The issuerName and url are displayed when verifying a credential issued by that DID. + +### Programmatic Verification + +You can programmatically set the VC to be verified by calling the 'verify' method on the element, like so: + + ``` + + + + + + ``` + +Notice that we have to wait for the web component to finish intializing, and fire the 'veri-good-is-ready' event before we can call the 'verify' method on it. + +You can of course also (and more likely) directly use the call in your own javascript that you bundle up with webpack or the like. + +You might use the 'verify' call for cases like: + +* immediately verifying a credential whose url has been passed in as a request parameter on your html page. +* verifying a credential that the end user selects from a list of credentials on the page, like say in a web wallet + +### Customization + +#### Slots + +There are three 'slots' in the web component into which you can place custom html content: + +* header +* wasAwarded +* awardedBy + +Use them by including your custom content inside the `` tag like so: + +``` + +
+
University of Wonderful
+
Course Credential Verification
+
+
earned
+
awarded byyyy
+
+``` + +The slots map into the verifier like so: + +TODO: add image of verifier with slots circled, arrows pointing to each with a label. + +You'll of course likely have to play with the css on your slots. + +If you don't provide content for the slots, the defaults will be used which look like so: + +TODO: add image with default content. + + diff --git a/dist/9ba6079676d33402e654.jsonld b/dist/9ba6079676d33402e654.jsonld new file mode 100644 index 0000000..8a91639 --- /dev/null +++ b/dist/9ba6079676d33402e654.jsonld @@ -0,0 +1,301 @@ +{ + "@context": { + "@protected": true, + "id": "@id", + "type": "@type", + "description": "https://schema.org/description", + "digestMultibase": { + "@id": "https://w3id.org/security#digestMultibase", + "@type": "https://w3id.org/security#multibase" + }, + "digestSRI": { + "@id": "https://www.w3.org/2018/credentials#digestSRI", + "@type": "https://www.w3.org/2018/credentials#sriString" + }, + "mediaType": { + "@id": "https://schema.org/encodingFormat" + }, + "name": "https://schema.org/name", + "VerifiableCredential": { + "@id": "https://www.w3.org/2018/credentials#VerifiableCredential", + "@context": { + "@protected": true, + "id": "@id", + "type": "@type", + "confidenceMethod": { + "@id": "https://www.w3.org/2018/credentials#confidenceMethod", + "@type": "@id" + }, + "credentialSchema": { + "@id": "https://www.w3.org/2018/credentials#credentialSchema", + "@type": "@id" + }, + "credentialStatus": { + "@id": "https://www.w3.org/2018/credentials#credentialStatus", + "@type": "@id" + }, + "credentialSubject": { + "@id": "https://www.w3.org/2018/credentials#credentialSubject", + "@type": "@id" + }, + "description": "https://schema.org/description", + "evidence": { + "@id": "https://www.w3.org/2018/credentials#evidence", + "@type": "@id" + }, + "issuer": { + "@id": "https://www.w3.org/2018/credentials#issuer", + "@type": "@id" + }, + "name": "https://schema.org/name", + "proof": { + "@id": "https://w3id.org/security#proof", + "@type": "@id", + "@container": "@graph" + }, + "refreshService": { + "@id": "https://www.w3.org/2018/credentials#refreshService", + "@type": "@id" + }, + "relatedResource": { + "@id": "https://www.w3.org/2018/credentials#relatedResource", + "@type": "@id" + }, + "renderMethod": { + "@id": "https://www.w3.org/2018/credentials#renderMethod", + "@type": "@id" + }, + "termsOfUse": { + "@id": "https://www.w3.org/2018/credentials#termsOfUse", + "@type": "@id" + }, + "validFrom": { + "@id": "https://www.w3.org/2018/credentials#validFrom", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + }, + "validUntil": { + "@id": "https://www.w3.org/2018/credentials#validUntil", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + } + } + }, + "EnvelopedVerifiableCredential": "https://www.w3.org/2018/credentials#EnvelopedVerifiableCredential", + "VerifiablePresentation": { + "@id": "https://www.w3.org/2018/credentials#VerifiablePresentation", + "@context": { + "@protected": true, + "id": "@id", + "type": "@type", + "holder": { + "@id": "https://www.w3.org/2018/credentials#holder", + "@type": "@id" + }, + "proof": { + "@id": "https://w3id.org/security#proof", + "@type": "@id", + "@container": "@graph" + }, + "termsOfUse": { + "@id": "https://www.w3.org/2018/credentials#termsOfUse", + "@type": "@id" + }, + "verifiableCredential": { + "@id": "https://www.w3.org/2018/credentials#verifiableCredential", + "@type": "@id", + "@container": "@graph", + "@context": null + } + } + }, + "EnvelopedVerifiablePresentation": "https://www.w3.org/2018/credentials#EnvelopedVerifiablePresentation", + "JsonSchemaCredential": "https://www.w3.org/2018/credentials#JsonSchemaCredential", + "JsonSchema": { + "@id": "https://www.w3.org/2018/credentials#JsonSchema", + "@context": { + "@protected": true, + "id": "@id", + "type": "@type", + "jsonSchema": { + "@id": "https://www.w3.org/2018/credentials#jsonSchema", + "@type": "@json" + } + } + }, + "BitstringStatusListCredential": "https://www.w3.org/ns/credentials/status#BitstringStatusListCredential", + "BitstringStatusList": { + "@id": "https://www.w3.org/ns/credentials/status#BitstringStatusList", + "@context": { + "@protected": true, + "id": "@id", + "type": "@type", + "encodedList": { + "@id": "https://www.w3.org/ns/credentials/status#encodedList", + "@type": "https://w3id.org/security#multibase" + }, + "statusPurpose": "https://www.w3.org/ns/credentials/status#statusPurpose", + "ttl": "https://www.w3.org/ns/credentials/status#ttl" + } + }, + "BitstringStatusListEntry": { + "@id": "https://www.w3.org/ns/credentials/status#BitstringStatusListEntry", + "@context": { + "@protected": true, + "id": "@id", + "type": "@type", + "statusListCredential": { + "@id": "https://www.w3.org/ns/credentials/status#statusListCredential", + "@type": "@id" + }, + "statusListIndex": "https://www.w3.org/ns/credentials/status#statusListIndex", + "statusPurpose": "https://www.w3.org/ns/credentials/status#statusPurpose", + "statusMessage": { + "@id": "https://www.w3.org/ns/credentials/status#statusMessage", + "@context": { + "@protected": true, + "id": "@id", + "type": "@type", + "message": "https://www.w3.org/ns/credentials/status#message", + "status": "https://www.w3.org/ns/credentials/status#status" + } + }, + "statusReference": { + "@id": "https://www.w3.org/ns/credentials/status#statusReference", + "@type": "@id" + }, + "statusSize": { + "@id": "https://www.w3.org/ns/credentials/status#statusSize", + "@type": "https://www.w3.org/2001/XMLSchema#integer" + } + } + }, + "DataIntegrityProof": { + "@id": "https://w3id.org/security#DataIntegrityProof", + "@context": { + "@protected": true, + "id": "@id", + "type": "@type", + "challenge": "https://w3id.org/security#challenge", + "created": { + "@id": "http://purl.org/dc/terms/created", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + }, + "cryptosuite": { + "@id": "https://w3id.org/security#cryptosuite", + "@type": "https://w3id.org/security#cryptosuiteString" + }, + "domain": "https://w3id.org/security#domain", + "expires": { + "@id": "https://w3id.org/security#expiration", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + }, + "nonce": "https://w3id.org/security#nonce", + "previousProof": { + "@id": "https://w3id.org/security#previousProof", + "@type": "@id" + }, + "proofPurpose": { + "@id": "https://w3id.org/security#proofPurpose", + "@type": "@vocab", + "@context": { + "@protected": true, + "id": "@id", + "type": "@type", + "assertionMethod": { + "@id": "https://w3id.org/security#assertionMethod", + "@type": "@id", + "@container": "@set" + }, + "authentication": { + "@id": "https://w3id.org/security#authenticationMethod", + "@type": "@id", + "@container": "@set" + }, + "capabilityDelegation": { + "@id": "https://w3id.org/security#capabilityDelegationMethod", + "@type": "@id", + "@container": "@set" + }, + "capabilityInvocation": { + "@id": "https://w3id.org/security#capabilityInvocationMethod", + "@type": "@id", + "@container": "@set" + }, + "keyAgreement": { + "@id": "https://w3id.org/security#keyAgreementMethod", + "@type": "@id", + "@container": "@set" + } + } + }, + "proofValue": { + "@id": "https://w3id.org/security#proofValue", + "@type": "https://w3id.org/security#multibase" + }, + "verificationMethod": { + "@id": "https://w3id.org/security#verificationMethod", + "@type": "@id" + } + } + }, + "...": { + "@id": "https://www.iana.org/assignments/jwt#..." + }, + "_sd": { + "@id": "https://www.iana.org/assignments/jwt#_sd", + "@type": "@json" + }, + "_sd_alg": { + "@id": "https://www.iana.org/assignments/jwt#_sd_alg" + }, + "aud": { + "@id": "https://www.iana.org/assignments/jwt#aud", + "@type": "@id" + }, + "cnf": { + "@id": "https://www.iana.org/assignments/jwt#cnf", + "@context": { + "@protected": true, + "kid": { + "@id": "https://www.iana.org/assignments/jwt#kid", + "@type": "@id" + }, + "jwk": { + "@id": "https://www.iana.org/assignments/jwt#jwk", + "@type": "@json" + } + } + }, + "exp": { + "@id": "https://www.iana.org/assignments/jwt#exp", + "@type": "https://www.w3.org/2001/XMLSchema#nonNegativeInteger" + }, + "iat": { + "@id": "https://www.iana.org/assignments/jwt#iat", + "@type": "https://www.w3.org/2001/XMLSchema#nonNegativeInteger" + }, + "iss": { + "@id": "https://www.iana.org/assignments/jose#iss", + "@type": "@id" + }, + "jku": { + "@id": "https://www.iana.org/assignments/jose#jku", + "@type": "@id" + }, + "kid": { + "@id": "https://www.iana.org/assignments/jose#kid", + "@type": "@id" + }, + "nbf": { + "@id": "https://www.iana.org/assignments/jwt#nbf", + "@type": "https://www.w3.org/2001/XMLSchema#nonNegativeInteger" + }, + "sub": { + "@id": "https://www.iana.org/assignments/jose#sub", + "@type": "@id" + }, + "x5u": { + "@id": "https://www.iana.org/assignments/jose#x5u", + "@type": "@id" + } + } +} diff --git a/dist/bundle.js b/dist/bundle.js new file mode 100644 index 0000000..08dec21 --- /dev/null +++ b/dist/bundle.js @@ -0,0 +1,41517 @@ +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ "./node_modules/@digitalbazaar/bitstring/lib/assertions.js" +/*!*****************************************************************!*\ + !*** ./node_modules/@digitalbazaar/bitstring/lib/assertions.js ***! + \*****************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ isBoolean: () => (/* binding */ isBoolean), +/* harmony export */ isNonNegativeInteger: () => (/* binding */ isNonNegativeInteger), +/* harmony export */ isNumber: () => (/* binding */ isNumber), +/* harmony export */ isPositiveInteger: () => (/* binding */ isPositiveInteger), +/* harmony export */ isString: () => (/* binding */ isString), +/* harmony export */ isUint8Array: () => (/* binding */ isUint8Array) +/* harmony export */ }); +/*! + * Copyright (c) 2020 Digital Bazaar, Inc. All rights reserved. + */ +function isNumber(value, name) { + if(typeof value !== 'number') { + throw new TypeError(`"${name}" must be number.`); + } +} + +function isPositiveInteger(value, name) { + if(!(Number.isInteger(value) && value > 0)) { + throw new TypeError(`"${name}" must be a positive integer.`); + } +} + +function isString(value, name) { + if(typeof value !== 'string') { + throw new TypeError(`"${name}" must be a string.`); + } +} + +function isBoolean(value, name) { + if(typeof value !== 'boolean') { + throw new TypeError(`"${name}" must be a boolean.`); + } +} + +function isNonNegativeInteger(value, name) { + if(!(Number.isInteger(value) && value >= 0)) { + throw new TypeError(`"${name}" must be a non-negative integer.`); + } +} + +function isUint8Array(value, name) { + if(!(value instanceof Uint8Array)) { + throw new TypeError(`"${name}" must be a Uint8Array.`); + } +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/bitstring/lib/index.js" +/*!************************************************************!*\ + !*** ./node_modules/@digitalbazaar/bitstring/lib/index.js ***! + \************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Bitstring: () => (/* binding */ Bitstring) +/* harmony export */ }); +/* harmony import */ var _assertions_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./assertions.js */ "./node_modules/@digitalbazaar/bitstring/lib/assertions.js"); +/* harmony import */ var base64url_universal__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! base64url-universal */ "./node_modules/base64url-universal/lib/browser.js"); +/* harmony import */ var pako__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! pako */ "./node_modules/pako/dist/pako.esm.mjs"); +/*! + * Copyright (c) 2020-2023 Digital Bazaar, Inc. All rights reserved. + */ + + + + +class Bitstring { + /** + * Creates a new Bitstring instance. + * + * @param {object} options - The options to use. + * @param {number} [options.length] - The length of the bitstring in bits; + * either this or `buffer` must be given, but not both. + * @param {Uint8Array} [options.buffer] - The bitstring as a buffer of bytes + * where the bytes are always in big endian order (left most byte or most + * significant byte in the buffer will be the least significant and lowest + * index byte in the bitstring) and where the bit order + * is also little endian by default but may be specified as big endian + * by passing `leftToRightIndexing: false`; either this parameter or + * `length` must be given but not both. + * @param {boolean} [options.leftToRightIndexing=true] - Whether the bit + * order (NOT the byte order, which is *always* first byte in the buffer is + * the first byte-index into the bitstring, i.e., left to right) is left to + * right or not; the default is left to right, which matches what the byte + * order always is and, specifically, means that `0x80` or `0b1000000` + * means the first bit index is set in a given byte. + * @param {boolean} [options.littleEndianBits] - Deprecated; use + * `leftToRightIndexing` instead. + */ + constructor({ + length, buffer, leftToRightIndexing, littleEndianBits + } = {}) { + if(length && buffer) { + throw new Error('Only one of "length" or "buffer" must be given.'); + } + if(length !== undefined) { + _assertions_js__WEBPACK_IMPORTED_MODULE_0__.isPositiveInteger(length, 'length'); + } else { + _assertions_js__WEBPACK_IMPORTED_MODULE_0__.isUint8Array(buffer, 'buffer'); + } + // backwards compatibility for deprecated name `littleEndianBits` + if(littleEndianBits !== undefined) { + if(leftToRightIndexing !== undefined) { + throw new Error( + 'Using both "littleEndianBits" and "leftToRightIndexing" ' + + 'is not allowed.'); + } + _assertions_js__WEBPACK_IMPORTED_MODULE_0__.isBoolean(littleEndianBits, 'littleEndianBits'); + leftToRightIndexing = littleEndianBits; + } + if(leftToRightIndexing === undefined) { + leftToRightIndexing = true; + } else { + _assertions_js__WEBPACK_IMPORTED_MODULE_0__.isBoolean(leftToRightIndexing, 'leftToRightIndexing'); + } + if(length) { + this.bits = new Uint8Array(Math.ceil(length / 8)); + this.length = length; + } else { + this.bits = new Uint8Array(buffer.buffer); + this.length = buffer.length * 8; + } + this.leftToRightIndexing = leftToRightIndexing; + } + + set(position, on) { + _assertions_js__WEBPACK_IMPORTED_MODULE_0__.isNumber(position, 'position'); + _assertions_js__WEBPACK_IMPORTED_MODULE_0__.isBoolean(on, 'on'); + const {length, leftToRightIndexing} = this; + const {index, bit} = _parsePosition(position, length, leftToRightIndexing); + if(on) { + this.bits[index] |= bit; + } else { + this.bits[index] &= 0xFF ^ bit; + } + } + + get(position) { + _assertions_js__WEBPACK_IMPORTED_MODULE_0__.isNumber(position, 'position'); + const {length, leftToRightIndexing} = this; + const {index, bit} = _parsePosition(position, length, leftToRightIndexing); + return !!(this.bits[index] & bit); + } + + async encodeBits() { + return base64url_universal__WEBPACK_IMPORTED_MODULE_1__.encode((0,pako__WEBPACK_IMPORTED_MODULE_2__.gzip)(this.bits)); + } + + static async decodeBits({encoded}) { + _assertions_js__WEBPACK_IMPORTED_MODULE_0__.isString(encoded, 'encoded'); + return (0,pako__WEBPACK_IMPORTED_MODULE_2__.ungzip)(base64url_universal__WEBPACK_IMPORTED_MODULE_1__.decode(encoded)); + } + + async compressBits() { + return (0,pako__WEBPACK_IMPORTED_MODULE_2__.gzip)(this.bits); + } + + static async uncompressBits({compressed}) { + _assertions_js__WEBPACK_IMPORTED_MODULE_0__.isUint8Array(compressed, 'compressed'); + return (0,pako__WEBPACK_IMPORTED_MODULE_2__.ungzip)(compressed); + } +} + +function _parsePosition(position, length, leftToRightIndexing) { + _assertions_js__WEBPACK_IMPORTED_MODULE_0__.isNonNegativeInteger(position, 'position'); + _assertions_js__WEBPACK_IMPORTED_MODULE_0__.isPositiveInteger(length, 'length'); + _assertions_js__WEBPACK_IMPORTED_MODULE_0__.isBoolean(leftToRightIndexing, 'leftToRightIndexing'); + + if(position >= length) { + throw new Error( + `Position "${position}" is out of range "0-${length - 1}".`); + } + const index = Math.floor(position / 8); + const rem = position % 8; + const shift = leftToRightIndexing ? (7 - rem) : rem; + const bit = 1 << shift; + return {index, bit}; +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/credentials-context/contexts/undefined-terms-v2.jsonld" +/*!********************************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/credentials-context/contexts/undefined-terms-v2.jsonld ***! + \********************************************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +module.exports = __webpack_require__.p + "d7838d6427ff9d685c3a.jsonld"; + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/credentials-context/contexts/v1.jsonld" +/*!****************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/credentials-context/contexts/v1.jsonld ***! + \****************************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +module.exports = __webpack_require__.p + "c8a7970305ef972dad4c.jsonld"; + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/credentials-context/contexts/v2.jsonld" +/*!****************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/credentials-context/contexts/v2.jsonld ***! + \****************************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +module.exports = __webpack_require__.p + "9ba6079676d33402e654.jsonld"; + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/credentials-context/lib/index.js" +/*!**********************************************************************!*\ + !*** ./node_modules/@digitalbazaar/credentials-context/lib/index.js ***! + \**********************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ contexts: () => (/* binding */ contexts), +/* harmony export */ metadata: () => (/* binding */ metadata), +/* harmony export */ named: () => (/* binding */ named) +/* harmony export */ }); +/* harmony import */ var _undefined_terms_v2_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./undefined-terms-v2.js */ "./node_modules/@digitalbazaar/credentials-context/lib/undefined-terms-v2.js"); +/* harmony import */ var _v1_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./v1.js */ "./node_modules/@digitalbazaar/credentials-context/lib/v1.js"); +/* harmony import */ var _v2_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./v2.js */ "./node_modules/@digitalbazaar/credentials-context/lib/v2.js"); +/*! + * Copyright (c) 2021-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + + +// map of context id to context +const contexts = new Map(); +// map of context id to context metadata +const metadata = new Map(); +// map of short names to context metadata +const named = new Map(); + +function setExportsFromMetadata({ + contextsMap, metadataMap, namedMap, metadata +}) { + contextsMap.set(metadata.id, metadata.context); + metadataMap.set(metadata.id, metadata); + namedMap.set(metadata.shortName, metadata); +} + +setExportsFromMetadata({ + contextsMap: contexts, metadataMap: metadata, namedMap: named, + metadata: { + id: 'https://www.w3.org/ns/credentials/undefined-terms/v2', + type: 'ContextMetadata', + shortName: 'undefined-terms-v2', + url: new URL(/* asset import */ __webpack_require__(/*! ../contexts/undefined-terms-v2.jsonld */ "./node_modules/@digitalbazaar/credentials-context/contexts/undefined-terms-v2.jsonld"), __webpack_require__.b), + context: _undefined_terms_v2_js__WEBPACK_IMPORTED_MODULE_0__["default"] + } +}); +setExportsFromMetadata({ + contextsMap: contexts, metadataMap: metadata, namedMap: named, + metadata: { + id: 'https://www.w3.org/2018/credentials/v1', + type: 'ContextMetadata', + shortName: 'v1', + url: new URL(/* asset import */ __webpack_require__(/*! ../contexts/v1.jsonld */ "./node_modules/@digitalbazaar/credentials-context/contexts/v1.jsonld"), __webpack_require__.b), + context: _v1_js__WEBPACK_IMPORTED_MODULE_1__["default"] + } +}); +setExportsFromMetadata({ + contextsMap: contexts, metadataMap: metadata, namedMap: named, + metadata: { + id: 'https://www.w3.org/ns/credentials/v2', + type: 'ContextMetadata', + shortName: 'v2', + url: new URL(/* asset import */ __webpack_require__(/*! ../contexts/v2.jsonld */ "./node_modules/@digitalbazaar/credentials-context/contexts/v2.jsonld"), __webpack_require__.b), + context: _v2_js__WEBPACK_IMPORTED_MODULE_2__["default"] + } +}); + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/credentials-context/lib/undefined-terms-v2.js" +/*!***********************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/credentials-context/lib/undefined-terms-v2.js ***! + \***********************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/*! + * Copyright (c) 2023-2024 Digital Bazaar, Inc. All rights reserved. + */ +// Use JSON style for context +/* eslint quotes: ['error', 'double'] */ +/* eslint quote-props: ['error', 'always'] */ +/* eslint-disable max-len */ + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (/* context-url: https://www.w3.org/ns/credentials/undefined-terms/v2 *//* context-begin */{ + "@context": { + "@vocab": "https://www.w3.org/ns/credentials/undefined-term#" + } +}); + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/credentials-context/lib/v1.js" +/*!*******************************************************************!*\ + !*** ./node_modules/@digitalbazaar/credentials-context/lib/v1.js ***! + \*******************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/*! + * Copyright (c) 2021-2024 Digital Bazaar, Inc. All rights reserved. + */ +// Use JSON style for context +/* eslint quotes: ['error', 'double'] */ +/* eslint quote-props: ['error', 'always'] */ +/* eslint-disable max-len */ + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (/* context-url: https://www.w3.org/2018/credentials/v1 *//* context-begin */{ + "@context": { + "@version": 1.1, + "@protected": true, + + "id": "@id", + "type": "@type", + + "VerifiableCredential": { + "@id": "https://www.w3.org/2018/credentials#VerifiableCredential", + "@context": { + "@version": 1.1, + "@protected": true, + + "id": "@id", + "type": "@type", + + "cred": "https://www.w3.org/2018/credentials#", + "sec": "https://w3id.org/security#", + "xsd": "http://www.w3.org/2001/XMLSchema#", + + "credentialSchema": { + "@id": "cred:credentialSchema", + "@type": "@id", + "@context": { + "@version": 1.1, + "@protected": true, + + "id": "@id", + "type": "@type", + + "cred": "https://www.w3.org/2018/credentials#", + + "JsonSchemaValidator2018": "cred:JsonSchemaValidator2018" + } + }, + "credentialStatus": {"@id": "cred:credentialStatus", "@type": "@id"}, + "credentialSubject": {"@id": "cred:credentialSubject", "@type": "@id"}, + "evidence": {"@id": "cred:evidence", "@type": "@id"}, + "expirationDate": {"@id": "cred:expirationDate", "@type": "xsd:dateTime"}, + "holder": {"@id": "cred:holder", "@type": "@id"}, + "issued": {"@id": "cred:issued", "@type": "xsd:dateTime"}, + "issuer": {"@id": "cred:issuer", "@type": "@id"}, + "issuanceDate": {"@id": "cred:issuanceDate", "@type": "xsd:dateTime"}, + "proof": {"@id": "sec:proof", "@type": "@id", "@container": "@graph"}, + "refreshService": { + "@id": "cred:refreshService", + "@type": "@id", + "@context": { + "@version": 1.1, + "@protected": true, + + "id": "@id", + "type": "@type", + + "cred": "https://www.w3.org/2018/credentials#", + + "ManualRefreshService2018": "cred:ManualRefreshService2018" + } + }, + "termsOfUse": {"@id": "cred:termsOfUse", "@type": "@id"}, + "validFrom": {"@id": "cred:validFrom", "@type": "xsd:dateTime"}, + "validUntil": {"@id": "cred:validUntil", "@type": "xsd:dateTime"} + } + }, + + "VerifiablePresentation": { + "@id": "https://www.w3.org/2018/credentials#VerifiablePresentation", + "@context": { + "@version": 1.1, + "@protected": true, + + "id": "@id", + "type": "@type", + + "cred": "https://www.w3.org/2018/credentials#", + "sec": "https://w3id.org/security#", + + "holder": {"@id": "cred:holder", "@type": "@id"}, + "proof": {"@id": "sec:proof", "@type": "@id", "@container": "@graph"}, + "verifiableCredential": {"@id": "cred:verifiableCredential", "@type": "@id", "@container": "@graph"} + } + }, + + "EcdsaSecp256k1Signature2019": { + "@id": "https://w3id.org/security#EcdsaSecp256k1Signature2019", + "@context": { + "@version": 1.1, + "@protected": true, + + "id": "@id", + "type": "@type", + + "sec": "https://w3id.org/security#", + "xsd": "http://www.w3.org/2001/XMLSchema#", + + "challenge": "sec:challenge", + "created": {"@id": "http://purl.org/dc/terms/created", "@type": "xsd:dateTime"}, + "domain": "sec:domain", + "expires": {"@id": "sec:expiration", "@type": "xsd:dateTime"}, + "jws": "sec:jws", + "nonce": "sec:nonce", + "proofPurpose": { + "@id": "sec:proofPurpose", + "@type": "@vocab", + "@context": { + "@version": 1.1, + "@protected": true, + + "id": "@id", + "type": "@type", + + "sec": "https://w3id.org/security#", + + "assertionMethod": {"@id": "sec:assertionMethod", "@type": "@id", "@container": "@set"}, + "authentication": {"@id": "sec:authenticationMethod", "@type": "@id", "@container": "@set"} + } + }, + "proofValue": "sec:proofValue", + "verificationMethod": {"@id": "sec:verificationMethod", "@type": "@id"} + } + }, + + "EcdsaSecp256r1Signature2019": { + "@id": "https://w3id.org/security#EcdsaSecp256r1Signature2019", + "@context": { + "@version": 1.1, + "@protected": true, + + "id": "@id", + "type": "@type", + + "sec": "https://w3id.org/security#", + "xsd": "http://www.w3.org/2001/XMLSchema#", + + "challenge": "sec:challenge", + "created": {"@id": "http://purl.org/dc/terms/created", "@type": "xsd:dateTime"}, + "domain": "sec:domain", + "expires": {"@id": "sec:expiration", "@type": "xsd:dateTime"}, + "jws": "sec:jws", + "nonce": "sec:nonce", + "proofPurpose": { + "@id": "sec:proofPurpose", + "@type": "@vocab", + "@context": { + "@version": 1.1, + "@protected": true, + + "id": "@id", + "type": "@type", + + "sec": "https://w3id.org/security#", + + "assertionMethod": {"@id": "sec:assertionMethod", "@type": "@id", "@container": "@set"}, + "authentication": {"@id": "sec:authenticationMethod", "@type": "@id", "@container": "@set"} + } + }, + "proofValue": "sec:proofValue", + "verificationMethod": {"@id": "sec:verificationMethod", "@type": "@id"} + } + }, + + "Ed25519Signature2018": { + "@id": "https://w3id.org/security#Ed25519Signature2018", + "@context": { + "@version": 1.1, + "@protected": true, + + "id": "@id", + "type": "@type", + + "sec": "https://w3id.org/security#", + "xsd": "http://www.w3.org/2001/XMLSchema#", + + "challenge": "sec:challenge", + "created": {"@id": "http://purl.org/dc/terms/created", "@type": "xsd:dateTime"}, + "domain": "sec:domain", + "expires": {"@id": "sec:expiration", "@type": "xsd:dateTime"}, + "jws": "sec:jws", + "nonce": "sec:nonce", + "proofPurpose": { + "@id": "sec:proofPurpose", + "@type": "@vocab", + "@context": { + "@version": 1.1, + "@protected": true, + + "id": "@id", + "type": "@type", + + "sec": "https://w3id.org/security#", + + "assertionMethod": {"@id": "sec:assertionMethod", "@type": "@id", "@container": "@set"}, + "authentication": {"@id": "sec:authenticationMethod", "@type": "@id", "@container": "@set"} + } + }, + "proofValue": "sec:proofValue", + "verificationMethod": {"@id": "sec:verificationMethod", "@type": "@id"} + } + }, + + "RsaSignature2018": { + "@id": "https://w3id.org/security#RsaSignature2018", + "@context": { + "@version": 1.1, + "@protected": true, + + "challenge": "sec:challenge", + "created": {"@id": "http://purl.org/dc/terms/created", "@type": "xsd:dateTime"}, + "domain": "sec:domain", + "expires": {"@id": "sec:expiration", "@type": "xsd:dateTime"}, + "jws": "sec:jws", + "nonce": "sec:nonce", + "proofPurpose": { + "@id": "sec:proofPurpose", + "@type": "@vocab", + "@context": { + "@version": 1.1, + "@protected": true, + + "id": "@id", + "type": "@type", + + "sec": "https://w3id.org/security#", + + "assertionMethod": {"@id": "sec:assertionMethod", "@type": "@id", "@container": "@set"}, + "authentication": {"@id": "sec:authenticationMethod", "@type": "@id", "@container": "@set"} + } + }, + "proofValue": "sec:proofValue", + "verificationMethod": {"@id": "sec:verificationMethod", "@type": "@id"} + } + }, + + "proof": {"@id": "https://w3id.org/security#proof", "@type": "@id", "@container": "@graph"} + } +}); + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/credentials-context/lib/v2.js" +/*!*******************************************************************!*\ + !*** ./node_modules/@digitalbazaar/credentials-context/lib/v2.js ***! + \*******************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/*! + * Copyright (c) 2023-2024 Digital Bazaar, Inc. All rights reserved. + */ +// Use JSON style for context +/* eslint quotes: ['error', 'double'] */ +/* eslint quote-props: ['error', 'always'] */ +/* eslint-disable max-len */ + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (/* context-url: https://www.w3.org/ns/credentials/v2 *//* context-begin */{ + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "description": "https://schema.org/description", + "digestMultibase": { + "@id": "https://w3id.org/security#digestMultibase", + "@type": "https://w3id.org/security#multibase" + }, + "digestSRI": { + "@id": "https://www.w3.org/2018/credentials#digestSRI", + "@type": "https://www.w3.org/2018/credentials#sriString" + }, + "mediaType": { + "@id": "https://schema.org/encodingFormat" + }, + "name": "https://schema.org/name", + + "VerifiableCredential": { + "@id": "https://www.w3.org/2018/credentials#VerifiableCredential", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "confidenceMethod": { + "@id": "https://www.w3.org/2018/credentials#confidenceMethod", + "@type": "@id" + }, + "credentialSchema": { + "@id": "https://www.w3.org/2018/credentials#credentialSchema", + "@type": "@id" + }, + "credentialStatus": { + "@id": "https://www.w3.org/2018/credentials#credentialStatus", + "@type": "@id" + }, + "credentialSubject": { + "@id": "https://www.w3.org/2018/credentials#credentialSubject", + "@type": "@id" + }, + "description": "https://schema.org/description", + "evidence": { + "@id": "https://www.w3.org/2018/credentials#evidence", + "@type": "@id" + }, + "issuer": { + "@id": "https://www.w3.org/2018/credentials#issuer", + "@type": "@id" + }, + "name": "https://schema.org/name", + "proof": { + "@id": "https://w3id.org/security#proof", + "@type": "@id", + "@container": "@graph" + }, + "refreshService": { + "@id": "https://www.w3.org/2018/credentials#refreshService", + "@type": "@id" + }, + "relatedResource": { + "@id": "https://www.w3.org/2018/credentials#relatedResource", + "@type": "@id" + }, + "renderMethod": { + "@id": "https://www.w3.org/2018/credentials#renderMethod", + "@type": "@id" + }, + "termsOfUse": { + "@id": "https://www.w3.org/2018/credentials#termsOfUse", + "@type": "@id" + }, + "validFrom": { + "@id": "https://www.w3.org/2018/credentials#validFrom", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + }, + "validUntil": { + "@id": "https://www.w3.org/2018/credentials#validUntil", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + } + } + }, + + "EnvelopedVerifiableCredential": + "https://www.w3.org/2018/credentials#EnvelopedVerifiableCredential", + + "VerifiablePresentation": { + "@id": "https://www.w3.org/2018/credentials#VerifiablePresentation", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "holder": { + "@id": "https://www.w3.org/2018/credentials#holder", + "@type": "@id" + }, + "proof": { + "@id": "https://w3id.org/security#proof", + "@type": "@id", + "@container": "@graph" + }, + "termsOfUse": { + "@id": "https://www.w3.org/2018/credentials#termsOfUse", + "@type": "@id" + }, + "verifiableCredential": { + "@id": "https://www.w3.org/2018/credentials#verifiableCredential", + "@type": "@id", + "@container": "@graph", + "@context": null + } + } + }, + + "EnvelopedVerifiablePresentation": + "https://www.w3.org/2018/credentials#EnvelopedVerifiablePresentation", + + "JsonSchemaCredential": + "https://www.w3.org/2018/credentials#JsonSchemaCredential", + + "JsonSchema": { + "@id": "https://www.w3.org/2018/credentials#JsonSchema", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "jsonSchema": { + "@id": "https://www.w3.org/2018/credentials#jsonSchema", + "@type": "@json" + } + } + }, + + "BitstringStatusListCredential": + "https://www.w3.org/ns/credentials/status#BitstringStatusListCredential", + + "BitstringStatusList": { + "@id": "https://www.w3.org/ns/credentials/status#BitstringStatusList", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "encodedList": { + "@id": "https://www.w3.org/ns/credentials/status#encodedList", + "@type": "https://w3id.org/security#multibase" + }, + "statusPurpose": + "https://www.w3.org/ns/credentials/status#statusPurpose", + "ttl": "https://www.w3.org/ns/credentials/status#ttl" + } + }, + + "BitstringStatusListEntry": { + "@id": + "https://www.w3.org/ns/credentials/status#BitstringStatusListEntry", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "statusListCredential": { + "@id": + "https://www.w3.org/ns/credentials/status#statusListCredential", + "@type": "@id" + }, + "statusListIndex": + "https://www.w3.org/ns/credentials/status#statusListIndex", + "statusPurpose": + "https://www.w3.org/ns/credentials/status#statusPurpose", + "statusMessage": { + "@id": "https://www.w3.org/ns/credentials/status#statusMessage", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "message": "https://www.w3.org/ns/credentials/status#message", + "status": "https://www.w3.org/ns/credentials/status#status" + } + }, + "statusReference": { + "@id": "https://www.w3.org/ns/credentials/status#statusReference", + "@type": "@id" + }, + "statusSize": { + "@id": "https://www.w3.org/ns/credentials/status#statusSize", + "@type": "https://www.w3.org/2001/XMLSchema#integer" + } + } + }, + + "DataIntegrityProof": { + "@id": "https://w3id.org/security#DataIntegrityProof", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "challenge": "https://w3id.org/security#challenge", + "created": { + "@id": "http://purl.org/dc/terms/created", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + }, + "cryptosuite": { + "@id": "https://w3id.org/security#cryptosuite", + "@type": "https://w3id.org/security#cryptosuiteString" + }, + "domain": "https://w3id.org/security#domain", + "expires": { + "@id": "https://w3id.org/security#expiration", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + }, + "nonce": "https://w3id.org/security#nonce", + "previousProof": { + "@id": "https://w3id.org/security#previousProof", + "@type": "@id" + }, + "proofPurpose": { + "@id": "https://w3id.org/security#proofPurpose", + "@type": "@vocab", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "assertionMethod": { + "@id": "https://w3id.org/security#assertionMethod", + "@type": "@id", + "@container": "@set" + }, + "authentication": { + "@id": "https://w3id.org/security#authenticationMethod", + "@type": "@id", + "@container": "@set" + }, + "capabilityDelegation": { + "@id": "https://w3id.org/security#capabilityDelegationMethod", + "@type": "@id", + "@container": "@set" + }, + "capabilityInvocation": { + "@id": "https://w3id.org/security#capabilityInvocationMethod", + "@type": "@id", + "@container": "@set" + }, + "keyAgreement": { + "@id": "https://w3id.org/security#keyAgreementMethod", + "@type": "@id", + "@container": "@set" + } + } + }, + "proofValue": { + "@id": "https://w3id.org/security#proofValue", + "@type": "https://w3id.org/security#multibase" + }, + "verificationMethod": { + "@id": "https://w3id.org/security#verificationMethod", + "@type": "@id" + } + } + }, + + "...": { + "@id": "https://www.iana.org/assignments/jwt#..." + }, + "_sd": { + "@id": "https://www.iana.org/assignments/jwt#_sd", + "@type": "@json" + }, + "_sd_alg": { + "@id": "https://www.iana.org/assignments/jwt#_sd_alg" + }, + "aud": { + "@id": "https://www.iana.org/assignments/jwt#aud", + "@type": "@id" + }, + "cnf": { + "@id": "https://www.iana.org/assignments/jwt#cnf", + "@context": { + "@protected": true, + + "kid": { + "@id": "https://www.iana.org/assignments/jwt#kid", + "@type": "@id" + }, + "jwk": { + "@id": "https://www.iana.org/assignments/jwt#jwk", + "@type": "@json" + } + } + }, + "exp": { + "@id": "https://www.iana.org/assignments/jwt#exp", + "@type": "https://www.w3.org/2001/XMLSchema#nonNegativeInteger" + }, + "iat": { + "@id": "https://www.iana.org/assignments/jwt#iat", + "@type": "https://www.w3.org/2001/XMLSchema#nonNegativeInteger" + }, + "iss": { + "@id": "https://www.iana.org/assignments/jose#iss", + "@type": "@id" + }, + "jku": { + "@id": "https://www.iana.org/assignments/jose#jku", + "@type": "@id" + }, + "kid": { + "@id": "https://www.iana.org/assignments/jose#kid", + "@type": "@id" + }, + "nbf": { + "@id": "https://www.iana.org/assignments/jwt#nbf", + "@type": "https://www.w3.org/2001/XMLSchema#nonNegativeInteger" + }, + "sub": { + "@id": "https://www.iana.org/assignments/jose#sub", + "@type": "@id" + }, + "x5u": { + "@id": "https://www.iana.org/assignments/jose#x5u", + "@type": "@id" + } + } +}); + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/data-integrity-context/dist/context.esm.js" +/*!********************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/data-integrity-context/dist/context.esm.js ***! + \********************************************************************************/ +(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CONTEXT: () => (/* binding */ context_3), +/* harmony export */ CONTEXT_URL: () => (/* binding */ context_4), +/* harmony export */ DATA_INTEGRITY_CONTEXT_V1_URL: () => (/* binding */ context_6), +/* harmony export */ DATA_INTEGRITY_CONTEXT_V2_URL: () => (/* binding */ context_7), +/* harmony export */ appContextMap: () => (/* binding */ context_5), +/* harmony export */ constants: () => (/* binding */ context_2), +/* harmony export */ contexts: () => (/* binding */ context_1), +/* harmony export */ "default": () => (/* binding */ context$1) +/* harmony export */ }); +function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var context = createCommonjsModule(function (module, exports) { +/*! For license information please see context.js.LICENSE.txt */ +(()=>{var t={188:t=>{t.exports={CONTEXT_FILENAME_V1:"data-integrity-v1.jsonld",CONTEXT_FILENAME_V2:"data-integrity-v2.jsonld",DATA_INTEGRITY_CONTEXT_V1_URL:"https://w3id.org/security/data-integrity/v1",DATA_INTEGRITY_CONTEXT_V2_URL:"https://w3id.org/security/data-integrity/v2",CONTEXT_URL:"https://w3id.org/security/data-integrity/v2",CBORLD_VALUE_V1:48,CBORLD_VALUE:51};},249:t=>{t.exports={"@context":{id:"@id",type:"@type","@protected":!0,proof:{"@id":"https://w3id.org/security#proof","@type":"@id","@container":"@graph"},DataIntegrityProof:{"@id":"https://w3id.org/security#DataIntegrityProof","@context":{"@protected":!0,id:"@id",type:"@type",challenge:"https://w3id.org/security#challenge",created:{"@id":"http://purl.org/dc/terms/created","@type":"http://www.w3.org/2001/XMLSchema#dateTime"},domain:"https://w3id.org/security#domain",expires:{"@id":"https://w3id.org/security#expiration","@type":"http://www.w3.org/2001/XMLSchema#dateTime"},nonce:"https://w3id.org/security#nonce",proofPurpose:{"@id":"https://w3id.org/security#proofPurpose","@type":"@vocab","@context":{"@protected":!0,id:"@id",type:"@type",assertionMethod:{"@id":"https://w3id.org/security#assertionMethod","@type":"@id","@container":"@set"},authentication:{"@id":"https://w3id.org/security#authenticationMethod","@type":"@id","@container":"@set"},capabilityInvocation:{"@id":"https://w3id.org/security#capabilityInvocationMethod","@type":"@id","@container":"@set"},capabilityDelegation:{"@id":"https://w3id.org/security#capabilityDelegationMethod","@type":"@id","@container":"@set"},keyAgreement:{"@id":"https://w3id.org/security#keyAgreementMethod","@type":"@id","@container":"@set"}}},cryptosuite:"https://w3id.org/security#cryptosuite",proofValue:{"@id":"https://w3id.org/security#proofValue","@type":"https://w3id.org/security#multibase"},verificationMethod:{"@id":"https://w3id.org/security#verificationMethod","@type":"@id"}}}}};},976:t=>{t.exports={"@context":{id:"@id",type:"@type","@protected":!0,proof:{"@id":"https://w3id.org/security#proof","@type":"@id","@container":"@graph"},DataIntegrityProof:{"@id":"https://w3id.org/security#DataIntegrityProof","@context":{"@protected":!0,id:"@id",type:"@type",challenge:"https://w3id.org/security#challenge",created:{"@id":"http://purl.org/dc/terms/created","@type":"http://www.w3.org/2001/XMLSchema#dateTime"},domain:"https://w3id.org/security#domain",expires:{"@id":"https://w3id.org/security#expiration","@type":"http://www.w3.org/2001/XMLSchema#dateTime"},nonce:"https://w3id.org/security#nonce",previousProof:{"@id":"https://w3id.org/security#previousProof","@type":"@id"},proofPurpose:{"@id":"https://w3id.org/security#proofPurpose","@type":"@vocab","@context":{"@protected":!0,id:"@id",type:"@type",assertionMethod:{"@id":"https://w3id.org/security#assertionMethod","@type":"@id","@container":"@set"},authentication:{"@id":"https://w3id.org/security#authenticationMethod","@type":"@id","@container":"@set"},capabilityInvocation:{"@id":"https://w3id.org/security#capabilityInvocationMethod","@type":"@id","@container":"@set"},capabilityDelegation:{"@id":"https://w3id.org/security#capabilityDelegationMethod","@type":"@id","@container":"@set"},keyAgreement:{"@id":"https://w3id.org/security#keyAgreementMethod","@type":"@id","@container":"@set"}}},cryptosuite:{"@id":"https://w3id.org/security#cryptosuite","@type":"https://w3id.org/security#cryptosuiteString"},proofValue:{"@id":"https://w3id.org/security#proofValue","@type":"https://w3id.org/security#multibase"},verificationMethod:{"@id":"https://w3id.org/security#verificationMethod","@type":"@id"}}}}};},845:(t,e,i)=>{const o=i(249),r=i(976),p=i(188),{CONTEXT_URL:d,DATA_INTEGRITY_CONTEXT_V1_URL:s,DATA_INTEGRITY_CONTEXT_V2_URL:c,CBORLD_VALUE:a}=p,n=new Map;n.set(s,o),n.set(c,r);const y=new Map;y.set(d,a),t.exports={constants:p,contexts:n,appContextMap:y,DATA_INTEGRITY_CONTEXT_V1_URL:s,DATA_INTEGRITY_CONTEXT_V2_URL:c,CONTEXT_URL:d,CONTEXT:r};}},e={},i=function i(o){var r=e[o];if(void 0!==r)return r.exports;var p=e[o]={exports:{}};return t[o](p,p.exports,i),p.exports}(845),o=exports;for(var r in i)o[r]=i[r];i.__esModule&&Object.defineProperty(o,"__esModule",{value:!0});})(); +}); + +var context$1 = unwrapExports(context); +var context_1 = context.contexts; +var context_2 = context.constants; +var context_3 = context.CONTEXT; +var context_4 = context.CONTEXT_URL; +var context_5 = context.appContextMap; +var context_6 = context.DATA_INTEGRITY_CONTEXT_V1_URL; +var context_7 = context.DATA_INTEGRITY_CONTEXT_V2_URL; + + + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/data-integrity/lib/DataIntegrityProof.js" +/*!******************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/data-integrity/lib/DataIntegrityProof.js ***! + \******************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ DataIntegrityProof: () => (/* binding */ DataIntegrityProof) +/* harmony export */ }); +/* harmony import */ var base58_universal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! base58-universal */ "./node_modules/base58-universal/lib/index.js"); +/* harmony import */ var base64url_universal__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! base64url-universal */ "./node_modules/base64url-universal/lib/browser.js"); +/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./util.js */ "./node_modules/@digitalbazaar/data-integrity/lib/util.js"); +/* harmony import */ var jsonld_signatures__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! jsonld-signatures */ "./node_modules/jsonld-signatures/lib/jsonld-signatures.js"); +/* harmony import */ var _sha256digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sha256digest.js */ "./node_modules/@digitalbazaar/data-integrity/lib/sha256digest-browser.js"); +/*! + * Copyright (c) 2022-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + + + + +const {suites: {LinkedDataProof}} = jsonld_signatures__WEBPACK_IMPORTED_MODULE_3__; + +// multibase base58-btc header +const MULTIBASE_BASE58BTC_HEADER = 'z'; +// multibase base64url no pad header +const MULTIBASE_BASE64URL_HEADER = 'u'; +const DATA_INTEGRITY_CONTEXT_V2 = 'https://w3id.org/security/data-integrity/v2'; +const DATA_INTEGRITY_CONTEXT_V1 = 'https://w3id.org/security/data-integrity/v1'; +const PROOF_TYPE = 'DataIntegrityProof'; +// VCDM 2.0 core context +const VC_2_0_CONTEXT = 'https://www.w3.org/ns/credentials/v2'; + +class DataIntegrityProof extends LinkedDataProof { + /** + * The constructor for the DataIntegrityProof Class. + * + * @param {object} options - Options for the Class. + * @param {object} [options.signer] - A signer for the suite. + * @param {string|Date|number} [options.date] - A date to use for `created`. + * @param {object} options.cryptosuite - A compliant cryptosuite. + * @param {boolean} [options.legacyContext = false] - Toggles between + * the current DI context and a legacy DI context. + */ + constructor({signer, date, cryptosuite, legacyContext = false} = {}) { + super({type: PROOF_TYPE}); + const { + canonize, createVerifier, name, requiredAlgorithm, + derive, createProofValue, createVerifyData + } = cryptosuite; + // `createVerifier` is required + if(!(createVerifier && typeof createVerifier === 'function')) { + throw new TypeError( + '"cryptosuite.createVerifier" must be a function.'); + } + // assert optional functions + if(derive && typeof derive !== 'function') { + throw new TypeError( + '"cryptosuite.derive" must be a function.'); + } + if(createProofValue && typeof createProofValue !== 'function') { + throw new TypeError( + '"cryptosuite.createProofValue" must be a function.'); + } + if(createVerifyData && typeof createVerifyData !== 'function') { + throw new TypeError( + '"cryptosuite.createVerifyData" must be a function.'); + } + this.contextUrl = DATA_INTEGRITY_CONTEXT_V2; + if(legacyContext) { + this.contextUrl = DATA_INTEGRITY_CONTEXT_V1; + } + this.canonize = canonize; + this.createVerifier = createVerifier; + this.cryptosuite = name; + // save internal reference to cryptosuite instance + this._cryptosuite = cryptosuite; + this.requiredAlgorithm = requiredAlgorithm; + if(date) { + this.date = new Date(date); + if(isNaN(this.date)) { + throw TypeError(`"date" "${date}" is not a valid date.`); + } + } else if(date === null) { + this.date = null; + } + + const vm = _processSignatureParams({signer, requiredAlgorithm}); + this.verificationMethod = vm.verificationMethod; + this.signer = vm.signer; + } + + /** + * Adds a signature (proofValue) field to the proof object. Called by + * LinkedDataSignature.createProof(). + * + * @param {object} options - The options to use. + * @param {Uint8Array|object} options.verifyData - Data to be signed + * (extracted from document, according to the suite's spec). + * @param {object} options.proof - Proof object (containing the proofPurpose, + * verificationMethod, etc). + * + * @returns {Promise} Resolves with the proof containing the signature + * value. + */ + async sign({verifyData, proof}) { + if(!(this.signer && typeof this.signer.sign === 'function')) { + throw new Error('A signer API has not been specified.'); + } + + const signatureBytes = await this.signer.sign({data: verifyData}); + proof.proofValue = + MULTIBASE_BASE58BTC_HEADER + base58_universal__WEBPACK_IMPORTED_MODULE_0__.encode(signatureBytes); + + return proof; + } + + /** + * Verifies the proof signature against the given data. + * + * @param {object} options - The options to use. + * @param {Uint8Array|object} options.verifyData - Verify data as produced + * from `createVerifyData`. + * @param {object} options.verificationMethod - Key object. + * @param {object} options.proof - The proof to be verified. + * + * @returns {Promise} Resolves with the verification result. + */ + async verifySignature({verifyData, verificationMethod, proof}) { + const verifier = await this.createVerifier({verificationMethod}); + const isSupportedAlgorithm = Array.isArray(this.requiredAlgorithm) ? + this.requiredAlgorithm.includes(verifier.algorithm) : + this.requiredAlgorithm === verifier.algorithm; + + if(!isSupportedAlgorithm) { + const supportedAlgorithms = Array.isArray(this.requiredAlgorithm) ? + this.requiredAlgorithm.join(', ') : this.requiredAlgorithm; + const messageSuffix = Array.isArray(this.requiredAlgorithm) ? + `is not a supported algorithm for the cryptosuite. The supported ` + + `algorithms are: "${supportedAlgorithms}".` : + `does not match the required algorithm for the cryptosuite ` + + `"${supportedAlgorithms}".`; + const message = `The verifier's algorithm "${verifier.algorithm}" ` + + `${messageSuffix}`; + throw new Error(message); + } + + const {proofValue} = proof; + if(!(proofValue && typeof proofValue === 'string')) { + throw new TypeError( + 'The proof does not include a valid "proofValue" property.'); + } + const multibaseHeader = proofValue[0]; + let signature; + if(multibaseHeader === MULTIBASE_BASE58BTC_HEADER) { + signature = base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(proofValue.slice(1)); + } else if(multibaseHeader === MULTIBASE_BASE64URL_HEADER) { + signature = base64url_universal__WEBPACK_IMPORTED_MODULE_1__.decode(proofValue.slice(1)); + } else { + throw new Error( + 'Only base58btc or base64url multibase encoding is supported.'); + } + return verifier.verify({data: verifyData, signature}); + } + + /** + * @param {object} options - The options to use. + * @param {object} options.document - The document to create a proof for. + * @param {object} options.purpose - The `ProofPurpose` instance to use. + * @param {Array} options.proofSet - Any existing proof set. + * @param {Function} options.documentLoader - The document loader to use. + * + * @returns {Promise} Resolves with the created proof object. + */ + async createProof({document, purpose, proofSet, documentLoader}) { + // build proof (currently known as `signature options` in spec) + let proof; + if(this.proof) { + // shallow copy + proof = {...this.proof}; + } else { + // create proof JSON-LD document + proof = {}; + } + + // ensure proof type is set + proof.type = this.type; + + // set default `now` date if not given in `proof` or `options` + let date = this.date; + if(proof.created === undefined && date === undefined) { + date = new Date(); + } + + // ensure date is in string format + if(date && typeof date !== 'string') { + date = _util_js__WEBPACK_IMPORTED_MODULE_2__.w3cDate(date); + } + + // add API overrides + if(date) { + proof.created = date; + } + proof.verificationMethod = this.verificationMethod; + proof.cryptosuite = this.cryptosuite; + + // add any extensions to proof (mostly for legacy support) + proof = await this.updateProof({ + document, proof, purpose, proofSet, documentLoader + }); + + // allow purpose to update the proof; any terms added to `proof` must have + // be compatible with its context + proof = await purpose.update( + proof, {document, suite: this, documentLoader}); + + // create data to sign + let verifyData; + // use custom cryptosuite `createVerifyData` if available + if(this._cryptosuite.createVerifyData) { + verifyData = await this._cryptosuite.createVerifyData({ + cryptosuite: this._cryptosuite, + document, proof, proofSet, documentLoader, + dataIntegrityProof: this + }); + } else { + verifyData = await this.createVerifyData( + {document, proof, proofSet, documentLoader}); + } + + // use custom `createProofValue` if available + if(this._cryptosuite.createProofValue) { + proof.proofValue = await this._cryptosuite.createProofValue({ + cryptosuite: this._cryptosuite, + verifyData, document, proof, proofSet, + documentLoader, dataIntegrityProof: this + }); + } else { + // default to simple signing of data + proof = await this.sign( + {verifyData, document, proof, proofSet, documentLoader}); + } + + return proof; + } + + /** + * @param {object} options - The options to use. + * @param {object} options.document - The document to derive from. + * @param {object} options.purpose - The `ProofPurpose` instance to use. + * @param {Array} options.proofSet - Any existing proof set. + * @param {Function} options.documentLoader - The document loader to use. + * + * @returns {Promise} Resolves with the new document with a new + * `proof` field. + */ + async derive({document, purpose, proofSet, documentLoader}) { + // delegate entirely to cryptosuite instance + if(!this._cryptosuite.derive) { + throw new Error('"cryptosuite.derive" not provided.'); + } + return this._cryptosuite.derive({ + cryptosuite: this._cryptosuite, document, purpose, proofSet, + documentLoader, dataIntegrityProof: this + }); + } + + /** + * @param {object} options - The options to use. + * @param {object} options.proof - The proof to update. + * + * @returns {Promise} Resolves with the created proof object. + */ + async updateProof({proof}) { + return proof; + } + + /** + * @param {object} options - The options to use. + * @param {object} options.proof - The proof to verify. + * @param {Array} options.proofSet - Any existing proof set. + * @param {object} options.document - The document to create a proof for. + * @param {Function} options.documentLoader - The document loader to use. + * + * @returns {Promise<{object}>} Resolves with the verification result. + */ + async verifyProof({proof, proofSet, document, documentLoader}) { + try { + // fetch verification method + const verificationMethod = await this.getVerificationMethod({ + proof, documentLoader + }); + + // create data to verify + let verifyData; + // use custom cryptosuite `createVerifyData` if available + if(this._cryptosuite.createVerifyData) { + verifyData = await this._cryptosuite.createVerifyData({ + cryptosuite: this._cryptosuite, + document, proof, proofSet, documentLoader, + dataIntegrityProof: this, + verificationMethod + }); + } else { + verifyData = await this.createVerifyData({ + document, proof, proofSet, documentLoader, verificationMethod + }); + } + + // verify signature on data + const verified = await this.verifySignature({ + verifyData, verificationMethod, proof + }); + if(!verified) { + throw new Error('Invalid signature.'); + } + if(proof.created !== undefined) { + if(!_util_js__WEBPACK_IMPORTED_MODULE_2__.isW3cDate(proof.created)) { + throw new Error( + `"proof.created" ("${proof.created}") ` + + 'must be an XSD dateTimeStamp.'); + } + } + if(proof.expires !== undefined) { + if(!_util_js__WEBPACK_IMPORTED_MODULE_2__.isW3cDate(proof.expires)) { + throw new Error( + `"proof.expires" ("${proof.expires}") ` + + 'must be an XSD dateTimeStamp.'); + } + } + return {verified: true, verificationMethod}; + } catch(error) { + return {verified: false, error}; + } + } + + /** + * @param {object} options - The options to use. + * @param {object} options.document - The document to create verify data for. + * @param {object} options.proof - The proof to create verify data for. + * @param {Function} options.documentLoader - The document loader to use. + * + * @returns {Promise} Resolves to the verify data to + * be passed to `sign` or `verifySignature`. + */ + async createVerifyData({document, proof, documentLoader}) { + // get cached document hash + let cachedDocHash; + const {_hashCache} = this; + if(_hashCache && _hashCache.document === document) { + cachedDocHash = _hashCache.hash; + } else { + this._hashCache = { + document, + // canonize and hash document + hash: cachedDocHash = + this.canonize(document, {documentLoader, base: null, safe: true}) + .then(c14nDocument => (0,_sha256digest_js__WEBPACK_IMPORTED_MODULE_4__.sha256digest)({string: c14nDocument})) + }; + } + + // await both c14n proof hash and c14n document hash + const [proofHash, docHash] = await Promise.all([ + // canonize and hash proof + this.canonizeProof(proof, {document, documentLoader}) + .then(c14nProofOptions => (0,_sha256digest_js__WEBPACK_IMPORTED_MODULE_4__.sha256digest)({string: c14nProofOptions})), + cachedDocHash + ]); + // concatenate hash of c14n proof options and hash of c14n document + return _util_js__WEBPACK_IMPORTED_MODULE_2__.concat(proofHash, docHash); + } + + /** + * @param {object} options - The options to use. + * @param {object} options.proof - The proof for which to get the + * verification method. + * @param {Function} options.documentLoader - The document loader to use. + * + * @returns {object} - The verificationMethod. + */ + async getVerificationMethod({proof, documentLoader}) { + let {verificationMethod} = proof; + + if(typeof verificationMethod === 'object') { + verificationMethod = verificationMethod.id; + } + + if(!verificationMethod) { + throw new Error('No "verificationMethod" found in proof.'); + } + + const result = await documentLoader(verificationMethod); + if(!result) { + throw new Error( + `Unable to load verification method "${verificationMethod}".`); + } + + const {document} = result; + verificationMethod = typeof document === 'string' ? + JSON.parse(document) : document; + return verificationMethod; + } + + async canonizeProof(proof, {documentLoader, document}) { + // `proofValue` must not be included in the proof options + proof = { + '@context': document['@context'], + ...proof + }; + this.ensureSuiteContext({document: proof, addSuiteContext: true}); + delete proof.proofValue; + return this.canonize(proof, { + documentLoader, + safe: true, + base: null, + skipExpansion: false + }); + } + + /** + * Checks whether a given proof exists in the document. + * + * @param {object} options - The options to use. + * @param {object} options.proof - The proof to match. + * + * @returns {Promise} Whether a match for the proof was found. + */ + async matchProof({ + proof /*, document, purpose, documentLoader, expansionMap */ + }) { + const {type, cryptosuite} = proof; + return type === this.type && cryptosuite === this.cryptosuite; + } + + /** + * Ensures the document to be signed contains the required signature suite + * specific `@context`, by either adding it (if `addSuiteContext` is true), + * or throwing an error if it's missing. + * + * @param {object} options - Options hashmap. + * @param {object} options.document - JSON-LD document to be signed. + * @param {boolean} options.addSuiteContext - Add suite context? + */ + ensureSuiteContext({document, addSuiteContext}) { + const {contextUrl} = this; + + if(_includesContext({document, contextUrl}) || + _includesContext({document, contextUrl: VC_2_0_CONTEXT})) { + // document already includes the required context + return; + } + + if(!addSuiteContext) { + throw new TypeError( + `The document to be signed must contain this suite's @context, ` + + `"${contextUrl}".`); + } + + // enforce the suite's context by adding it to the document + const existingContext = document['@context'] || []; + + document['@context'] = Array.isArray(existingContext) ? + [...existingContext, contextUrl] : [existingContext, contextUrl]; + } +} + +/** + * Tests whether a provided JSON-LD document includes a context URL in its + * `@context` property. + * + * @param {object} options - Options hashmap. + * @param {object} options.document - A JSON-LD document. + * @param {string} options.contextUrl - A context URL. + * + * @returns {boolean} Returns true if document includes context. + */ +function _includesContext({document, contextUrl}) { + const context = document['@context']; + return context === contextUrl || + (Array.isArray(context) && context.includes(contextUrl)); +} + +/** + * See constructor docstring for param details. + * + * @param {object} options - The options to use. + * @param {object} options.signer - The signer to use. + * @param {Array|string} options.requiredAlgorithm - The required algorithm. + * @returns {{verificationMethod: string + * signer: {sign: Function, id: string, algorithm: string}}}} - Validated and + * initialized signature-related parameters. + */ +function _processSignatureParams({signer, requiredAlgorithm}) { + const vm = { + verificationMethod: undefined, + signer: undefined + }; + + if(!signer) { + return vm; + } + + if(typeof signer.sign !== 'function') { + throw new TypeError('A signer API has not been specified.'); + } + const isSupportedAlgorithm = Array.isArray(requiredAlgorithm) ? + requiredAlgorithm.includes(signer.algorithm) : + requiredAlgorithm === signer.algorithm; + + if(!isSupportedAlgorithm) { + const supportedAlgorithms = Array.isArray(requiredAlgorithm) ? + requiredAlgorithm.join(', ') : requiredAlgorithm; + const messageSuffix = Array.isArray(requiredAlgorithm) ? + `is not a supported algorithm for the cryptosuite. The supported ` + + `algorithms are: "${supportedAlgorithms}".` : + `does not match the required algorithm for the cryptosuite ` + + `"${supportedAlgorithms}".`; + const message = `The signer's algorithm "${signer.algorithm}" ` + + `${messageSuffix}`; + throw new Error(message); + } + + vm.signer = signer; + vm.verificationMethod = signer.id; + + return vm; +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/data-integrity/lib/index.js" +/*!*****************************************************************!*\ + !*** ./node_modules/@digitalbazaar/data-integrity/lib/index.js ***! + \*****************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ DataIntegrityProof: () => (/* reexport safe */ _DataIntegrityProof_js__WEBPACK_IMPORTED_MODULE_0__.DataIntegrityProof) +/* harmony export */ }); +/* harmony import */ var _DataIntegrityProof_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DataIntegrityProof.js */ "./node_modules/@digitalbazaar/data-integrity/lib/DataIntegrityProof.js"); +/*! + * Copyright (c) 2022 Digital Bazaar, Inc. All rights reserved. + */ + + + + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/data-integrity/lib/sha256digest-browser.js" +/*!********************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/data-integrity/lib/sha256digest-browser.js ***! + \********************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ sha256digest: () => (/* binding */ sha256digest) +/* harmony export */ }); +/* + * Copyright (c) 2022 Digital Bazaar, Inc. All rights reserved. + */ +/* eslint-env browser */ +const crypto = self && (self.crypto || self.msCrypto); + +/** + * Hashes a string of data using SHA-256. + * + * @param {string} string - The string to hash. + * + * @returns {Uint8Array} The hash digest. + */ +async function sha256digest({string}) { + const bytes = new TextEncoder().encode(string); + return new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)); +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/data-integrity/lib/util.js" +/*!****************************************************************!*\ + !*** ./node_modules/@digitalbazaar/data-integrity/lib/util.js ***! + \****************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ XMLDateTimeRegExp: () => (/* binding */ XMLDateTimeRegExp), +/* harmony export */ concat: () => (/* binding */ concat), +/* harmony export */ convertTimeStamp: () => (/* binding */ convertTimeStamp), +/* harmony export */ isW3cDate: () => (/* binding */ isW3cDate), +/* harmony export */ timezoneOffset: () => (/* binding */ timezoneOffset), +/* harmony export */ w3cDate: () => (/* binding */ w3cDate) +/* harmony export */ }); +/*! + * Copyright (c) 2022-2023 Digital Bazaar, Inc. All rights reserved. + */ + +/** + * Converts the given date into W3C datetime format (eg: 2011-03-09T21:55:41Z). + * + * @param {Date|number|string} date - The date to convert. + * + * @returns {string} The date in W3C datetime format. + */ +const w3cDate = date => { + if(date === undefined || date === null) { + date = new Date(); + } else if(typeof date === 'number' || typeof date === 'string') { + date = new Date(date); + } + const str = date.toISOString(); + return str.slice(0, - 5) + 'Z'; +}; + +const timezoneOffset = new RegExp( + '(Z|(\\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))$'); + +// Z and T must be uppercase +// xml schema date time RegExp +// @see https://www.w3.org/TR/xmlschema11-2/#dateTime +const XMLDateTimeRegExp = new RegExp( + '-?([1-9][0-9]{3,}|0[0-9]{3})' + + '-(0[1-9]|1[0-2])' + + '-(0[1-9]|[12][0-9]|3[01])' + + 'T(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))' + + '(Z|(\\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?'); +const isW3cDate = timeStamp => XMLDateTimeRegExp.test(timeStamp); + +const convertTimeStamp = timestamp => { + if(!timestamp) { + throw new Error(`Unexpected timestamp ("${timestamp}") received.`); + } + if(!timezoneOffset.test(timestamp)) { + return new Date(`${timestamp}Z`); + } + return new Date(timestamp); +}; + +/** + * Concatenates two Uint8Arrays. + * + * @param {Uint8Array} b1 - The first buffer to concat. + * @param {Uint8Array} b2 - The second buffer to concat. + * + * @returns {Uint8Array} The result. + */ +const concat = (b1, b2) => { + const rval = new Uint8Array(b1.length + b2.length); + rval.set(b1, 0); + rval.set(b2, b1.length); + return rval; +}; + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-multikey/lib/constants.js" +/*!***********************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-multikey/lib/constants.js ***! + \***********************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ ED25519_SIGNATURE_2018_V1_URL: () => (/* binding */ ED25519_SIGNATURE_2018_V1_URL), +/* harmony export */ ED25519_SIGNATURE_2020_V1_URL: () => (/* binding */ ED25519_SIGNATURE_2020_V1_URL), +/* harmony export */ MULTIBASE_BASE58BTC_HEADER: () => (/* binding */ MULTIBASE_BASE58BTC_HEADER), +/* harmony export */ MULTICODEC_PRIV_HEADER: () => (/* binding */ MULTICODEC_PRIV_HEADER), +/* harmony export */ MULTICODEC_PUB_HEADER: () => (/* binding */ MULTICODEC_PUB_HEADER), +/* harmony export */ MULTIKEY_CONTEXT_V1_URL: () => (/* binding */ MULTIKEY_CONTEXT_V1_URL), +/* harmony export */ PUBLIC_KEY_SIZE: () => (/* binding */ PUBLIC_KEY_SIZE), +/* harmony export */ SECRET_KEY_SIZE: () => (/* binding */ SECRET_KEY_SIZE) +/* harmony export */ }); +/*! + * Copyright (c) 2022-2024 Digital Bazaar, Inc. All rights reserved. + */ + +// Ed25519 Signature 2018 Context v1 URL +const ED25519_SIGNATURE_2018_V1_URL = + 'https://w3id.org/security/suites/ed25519-2018/v1'; +// Ed25519 Signature 2020 Context v1 URL +const ED25519_SIGNATURE_2020_V1_URL = + 'https://w3id.org/security/suites/ed25519-2020/v1'; +// multibase base58-btc header +const MULTIBASE_BASE58BTC_HEADER = 'z'; +// multicodec ed25519-pub header as varint +const MULTICODEC_PUB_HEADER = new Uint8Array([0xed, 0x01]); +// multicodec ed25519-priv header as varint +const MULTICODEC_PRIV_HEADER = new Uint8Array([0x80, 0x26]); +// multikey context v1 url +const MULTIKEY_CONTEXT_V1_URL = 'https://w3id.org/security/multikey/v1'; +// Ed25519 public key size in bytes +const PUBLIC_KEY_SIZE = 32; +// Ed25519 secret key size in bytes +const SECRET_KEY_SIZE = 32; + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-multikey/lib/ed25519-browser.js" +/*!*****************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-multikey/lib/ed25519-browser.js ***! + \*****************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair), +/* harmony export */ generateKeyPairFromSeed: () => (/* binding */ generateKeyPairFromSeed), +/* harmony export */ sha256digest: () => (/* binding */ sha256digest), +/* harmony export */ sign: () => (/* binding */ sign), +/* harmony export */ verify: () => (/* binding */ verify) +/* harmony export */ }); +/* harmony import */ var _noble_ed25519__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @noble/ed25519 */ "./node_modules/@noble/ed25519/lib/esm/index.js"); +/* harmony import */ var _validators_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./validators.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/validators.js"); +/*! + * Copyright (c) 2020-2022 Digital Bazaar, Inc. All rights reserved. + */ + + + +// browser MUST provide "crypto.getRandomValues" +const crypto = globalThis.crypto; +if(!crypto.getRandomValues) { + throw new Error('Browser does not provide "crypto.getRandomValues".'); +} + +async function generateKeyPairFromSeed(seed) { + (0,_validators_js__WEBPACK_IMPORTED_MODULE_1__.assertKeyBytes)({ + bytes: seed, + expectedLength: 32, + }); + const publicKey = await _noble_ed25519__WEBPACK_IMPORTED_MODULE_0__.getPublicKey(seed); + const secretKey = new Uint8Array(64); + secretKey.set(seed); + secretKey.set(publicKey, seed.length); + return { + publicKey, + secretKey + }; +} + +async function generateKeyPair() { + const seed = new Uint8Array(32); + crypto.getRandomValues(seed); + const keyPair = await generateKeyPairFromSeed(seed); + seed.fill(0); + return keyPair; +} + +async function sign(secretKey, data) { + return _noble_ed25519__WEBPACK_IMPORTED_MODULE_0__.sign(data, secretKey.slice(0, 32)); +} + +async function verify(publicKey, data, signature) { + return _noble_ed25519__WEBPACK_IMPORTED_MODULE_0__.verify(signature, data, publicKey); +} + +async function sha256digest({data}) { + return crypto.subtle.digest('SHA-256', data); +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-multikey/lib/factory.js" +/*!*********************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-multikey/lib/factory.js ***! + \*********************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ createSigner: () => (/* binding */ createSigner), +/* harmony export */ createVerifier: () => (/* binding */ createVerifier) +/* harmony export */ }); +/* harmony import */ var _ed25519_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ed25519.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/ed25519-browser.js"); +/*! + * Copyright (c) 2022 Digital Bazaar, Inc. All rights reserved. + */ + + +const ALGORITHM = 'Ed25519'; + +function createSigner({id, secretKey}) { + if(!secretKey) { + throw new Error('A secret key is not available for signing.'); + } + return { + algorithm: ALGORITHM, + id, + async sign({data}) { + return _ed25519_js__WEBPACK_IMPORTED_MODULE_0__.sign(secretKey, data); + }, + }; +} + +function createVerifier({id, publicKey}) { + if(!publicKey) { + throw new Error('A public key is not available for verifying.'); + } + return { + algorithm: ALGORITHM, + id, + async verify({data, signature}) { + return _ed25519_js__WEBPACK_IMPORTED_MODULE_0__.verify(publicKey, data, signature); + }, + }; +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-multikey/lib/helpers.js" +/*!*********************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-multikey/lib/helpers.js ***! + \*********************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ mbDecodeKeyPair: () => (/* binding */ mbDecodeKeyPair), +/* harmony export */ mbEncodeKeyPair: () => (/* binding */ mbEncodeKeyPair) +/* harmony export */ }); +/* harmony import */ var base58_universal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! base58-universal */ "./node_modules/base58-universal/lib/index.js"); +/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/constants.js"); +/*! + * Copyright (c) 2020-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + +function mbEncodeKeyPair({keyPair}) { + const result = {}; + if(keyPair.publicKey) { + result.publicKeyMultibase = _encodeMbKey( + _constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTICODEC_PUB_HEADER, keyPair.publicKey); + } + if(keyPair.secretKey) { + result.secretKeyMultibase = _encodeMbKey( + _constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTICODEC_PRIV_HEADER, keyPair.secretKey); + } + return result; +} + +function mbDecodeKeyPair({publicKeyMultibase, secretKeyMultibase}) { + if(!(publicKeyMultibase && typeof publicKeyMultibase === 'string' && + publicKeyMultibase[0] === 'z')) { + throw new Error( + '"publicKeyMultibase" must be a multibase, base58-encoded string.'); + } + // remove multibase header + const publicKeyMulticodec = base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(publicKeyMultibase.substr(1)); + // remove multicodec header + const publicKey = publicKeyMulticodec.slice(_constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTICODEC_PUB_HEADER.length); + + let secretKey; + if(secretKeyMultibase) { + if(!(typeof secretKeyMultibase === 'string' && + secretKeyMultibase[0] === 'z')) { + throw new Error( + '"secretKeyMultibase" must be a multibase, base58-encoded string.'); + } + // remove multibase header + const secretKeyMulticodec = base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(secretKeyMultibase.substr(1)); + // remove multicodec header + secretKey = secretKeyMulticodec.slice(_constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTICODEC_PRIV_HEADER.length); + } + + return { + publicKey, + secretKey + }; +} + +// encode a multibase base58-btc multicodec key +function _encodeMbKey(header, key) { + const mbKey = new Uint8Array(header.length + key.length); + + mbKey.set(header); + mbKey.set(key, header.length); + + return _constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTIBASE_BASE58BTC_HEADER + base58_universal__WEBPACK_IMPORTED_MODULE_0__.encode(mbKey); +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-multikey/lib/index.js" +/*!*******************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-multikey/lib/index.js ***! + \*******************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ from: () => (/* binding */ from), +/* harmony export */ fromJwk: () => (/* binding */ fromJwk), +/* harmony export */ generate: () => (/* binding */ generate), +/* harmony export */ toJwk: () => (/* binding */ toJwk) +/* harmony export */ }); +/* harmony import */ var base64url_universal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! base64url-universal */ "./node_modules/base64url-universal/lib/browser.js"); +/* harmony import */ var _ed25519_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ed25519.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/ed25519-browser.js"); +/* harmony import */ var _factory_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./factory.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/factory.js"); +/* harmony import */ var _serialize_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./serialize.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/serialize.js"); +/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./constants.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/constants.js"); +/* harmony import */ var _helpers_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./helpers.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/helpers.js"); +/* harmony import */ var _keyPairTranslator_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./keyPairTranslator.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/keyPairTranslator.js"); +/*! + * Copyright (c) 2020-2023 Digital Bazaar, Inc. All rights reserved. + */ + + + + + + + + +async function generate({id, controller, seed} = {}) { + let key; + if(seed) { + key = await _ed25519_js__WEBPACK_IMPORTED_MODULE_1__.generateKeyPairFromSeed(seed); + } else { + key = await _ed25519_js__WEBPACK_IMPORTED_MODULE_1__.generateKeyPair(); + } + + const {publicKeyMultibase, secretKeyMultibase} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_5__.mbEncodeKeyPair)({ + keyPair: key + }); + if(controller && !id) { + id = `${controller}#${publicKeyMultibase}`; + } + const keyPair = { + id, + controller, + publicKeyMultibase, + secretKeyMultibase, + ...key, + }; + return _createKeyPairInterface({keyPair}); +} + +// import key pair from JSON Multikey +async function from(key) { + let multikey = {...key}; + if(multikey.type !== 'Multikey') { + // attempt loading from JWK if `publicKeyJwk` is present + if(multikey.publicKeyJwk) { + let id; + let controller; + if(multikey.type === 'JsonWebKey' || multikey.type === 'JsonWebKey2020') { + ({id, controller} = multikey); + } + return fromJwk({ + jwk: multikey.publicKeyJwk, secretKey: false, id, controller + }); + } + if(multikey.type) { + multikey = await (0,_keyPairTranslator_js__WEBPACK_IMPORTED_MODULE_6__.toMultikey)({keyPair: multikey}); + return _createKeyPairInterface({keyPair: multikey}); + } + } + if(!multikey.type) { + multikey.type = 'Multikey'; + } + if(!multikey['@context']) { + multikey['@context'] = _constants_js__WEBPACK_IMPORTED_MODULE_4__.MULTIKEY_CONTEXT_V1_URL; + } + + _assertMultikey(multikey); + return _createKeyPairInterface({keyPair: multikey}); +} + +// imports key pair from JWK +async function fromJwk({jwk, secretKey = false, id, controller} = {}) { + const multikey = { + '@context': _constants_js__WEBPACK_IMPORTED_MODULE_4__.MULTIKEY_CONTEXT_V1_URL, + type: 'Multikey', + publicKeyMultibase: (0,_serialize_js__WEBPACK_IMPORTED_MODULE_3__.jwkToPublicKeyMultibase)({jwk}) + }; + if(typeof id === 'string') { + multikey.id = id; + } + if(typeof controller === 'string') { + multikey.controller = controller; + } + if(secretKey && jwk.d) { + multikey.secretKeyMultibase = (0,_serialize_js__WEBPACK_IMPORTED_MODULE_3__.jwkToSecretKeyMultibase)({jwk}); + } + return from(multikey); +} + +// converts key pair to JWK +async function toJwk({keyPair, secretKey = false} = {}) { + const jwk = { + kty: 'OKP', + crv: 'Ed25519', + x: base64url_universal__WEBPACK_IMPORTED_MODULE_0__.encode(keyPair.publicKey) + }; + const useSecretKey = secretKey && !!keyPair.secretKey; + if(useSecretKey) { + jwk.d = base64url_universal__WEBPACK_IMPORTED_MODULE_0__.encode(keyPair.secretKey); + } + return jwk; +} + +async function _createKeyPairInterface({keyPair}) { + if(!keyPair.publicKey) { + keyPair = await (0,_serialize_js__WEBPACK_IMPORTED_MODULE_3__.importKeyPair)(keyPair); + } + keyPair = { + ...keyPair, + async export({ + publicKey = true, secretKey = false, includeContext = true, raw = false, + canonicalize = false + } = {}) { + if(raw) { + const {publicKey, secretKey} = keyPair; + const result = {}; + if(publicKey) { + result.publicKey = publicKey.slice(); + } + if(secretKey) { + if(canonicalize && secretKey.length > _constants_js__WEBPACK_IMPORTED_MODULE_4__.SECRET_KEY_SIZE) { + result.secretKey = secretKey.subarray(0, _constants_js__WEBPACK_IMPORTED_MODULE_4__.SECRET_KEY_SIZE).slice(); + } else { + result.secretKey = secretKey; + } + } + return result; + } + return (0,_serialize_js__WEBPACK_IMPORTED_MODULE_3__.exportKeyPair)({ + keyPair, publicKey, secretKey, includeContext, canonicalize + }); + }, + signer() { + const {id, secretKey} = keyPair; + return (0,_factory_js__WEBPACK_IMPORTED_MODULE_2__.createSigner)({id, secretKey}); + }, + verifier() { + const {id, publicKey} = keyPair; + return (0,_factory_js__WEBPACK_IMPORTED_MODULE_2__.createVerifier)({id, publicKey}); + } + }; + + return keyPair; +} + +function _assertMultikey(key) { + if(!(key && typeof key === 'object')) { + throw new TypeError('"key" must be an object.'); + } + if(key.type !== 'Multikey') { + throw new Error('"key" must be a Multikey with type "Multikey".'); + } + if(!(key['@context'] === _constants_js__WEBPACK_IMPORTED_MODULE_4__.MULTIKEY_CONTEXT_V1_URL || + (Array.isArray(key['@context']) && + key['@context'].includes(_constants_js__WEBPACK_IMPORTED_MODULE_4__.MULTIKEY_CONTEXT_V1_URL)))) { + throw new TypeError( + '"key" must be a Multikey with context ' + + `"${_constants_js__WEBPACK_IMPORTED_MODULE_4__.MULTIKEY_CONTEXT_V1_URL}".`); + } +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-multikey/lib/keyPairTranslationMap.js" +/*!***********************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-multikey/lib/keyPairTranslationMap.js ***! + \***********************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ keyPairTranslationMap: () => (/* binding */ keyPairTranslationMap) +/* harmony export */ }); +/* harmony import */ var base58_universal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! base58-universal */ "./node_modules/base58-universal/lib/index.js"); +/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/constants.js"); +/* harmony import */ var _helpers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./helpers.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/helpers.js"); +/*! + * Copyright (c) 2022-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + + +const keyPairTranslationMap = new Map([ + ['Ed25519VerificationKey2020', { + contextUrl: _constants_js__WEBPACK_IMPORTED_MODULE_1__.ED25519_SIGNATURE_2020_V1_URL, + translationFn: _translateEd25519VerificationKey2020 + }], + ['Ed25519VerificationKey2018', { + contextUrl: _constants_js__WEBPACK_IMPORTED_MODULE_1__.ED25519_SIGNATURE_2018_V1_URL, + translationFn: _translateEd25519VerificationKey2018 + }] +]); + +async function _translateEd25519VerificationKey2020({keyPair}) { + return { + ...keyPair, + type: 'Multikey', + '@context': _constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTIKEY_CONTEXT_V1_URL, + secretKeyMultibase: keyPair.privateKeyMultibase + }; +} + +async function _translateEd25519VerificationKey2018({keyPair}) { + const key = { + publicKey: base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(keyPair.publicKeyBase58), + secretKey: undefined + }; + + if(keyPair.privateKeyBase58) { + key.secretKey = base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(keyPair.privateKeyBase58); + } + + const {publicKeyMultibase, secretKeyMultibase} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_2__.mbEncodeKeyPair)({ + keyPair: key + }); + + return { + '@context': _constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTIKEY_CONTEXT_V1_URL, + id: keyPair.id, + type: 'Multikey', + controller: keyPair.controller, + revoked: keyPair.revoked, + publicKeyMultibase, + secretKeyMultibase, + }; +} + + + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-multikey/lib/keyPairTranslator.js" +/*!*******************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-multikey/lib/keyPairTranslator.js ***! + \*******************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ toMultikey: () => (/* binding */ toMultikey) +/* harmony export */ }); +/* harmony import */ var _keyPairTranslationMap_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./keyPairTranslationMap.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/keyPairTranslationMap.js"); +/*! + * Copyright (c) 2022 Digital Bazaar, Inc. All rights reserved. + */ + + +async function toMultikey({keyPair}) { + const translationResult = _keyPairTranslationMap_js__WEBPACK_IMPORTED_MODULE_0__.keyPairTranslationMap.get(keyPair.type); + if(!translationResult) { + throw new Error(`Unsupported key type "${keyPair.type}".`); + } + + const {contextUrl, translationFn} = translationResult; + if(!keyPair['@context']) { + keyPair['@context'] = contextUrl; + } + if(!_includesContext({document: keyPair, contextUrl})) { + throw new Error(`Context not supported "${keyPair['@context']}".`); + } + + return translationFn({keyPair}); +} + +function _includesContext({document, contextUrl}) { + const context = document['@context']; + return context === contextUrl || + (Array.isArray(context) && context.includes(contextUrl)); +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-multikey/lib/serialize.js" +/*!***********************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-multikey/lib/serialize.js ***! + \***********************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ exportKeyPair: () => (/* binding */ exportKeyPair), +/* harmony export */ importKeyPair: () => (/* binding */ importKeyPair), +/* harmony export */ jwkToPublicKeyBytes: () => (/* binding */ jwkToPublicKeyBytes), +/* harmony export */ jwkToPublicKeyMultibase: () => (/* binding */ jwkToPublicKeyMultibase), +/* harmony export */ jwkToSecretKeyBytes: () => (/* binding */ jwkToSecretKeyBytes), +/* harmony export */ jwkToSecretKeyMultibase: () => (/* binding */ jwkToSecretKeyMultibase), +/* harmony export */ rawToPublicKeyMultibase: () => (/* binding */ rawToPublicKeyMultibase), +/* harmony export */ rawToSecretKeyMultibase: () => (/* binding */ rawToSecretKeyMultibase) +/* harmony export */ }); +/* harmony import */ var base64url_universal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! base64url-universal */ "./node_modules/base64url-universal/lib/browser.js"); +/* harmony import */ var _helpers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./helpers.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/helpers.js"); +/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants.js */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/constants.js"); +/*! + * Copyright (c) 2022-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + + +const LEGACY_SECRET_KEY_SIZE = _constants_js__WEBPACK_IMPORTED_MODULE_2__.SECRET_KEY_SIZE + _constants_js__WEBPACK_IMPORTED_MODULE_2__.PUBLIC_KEY_SIZE; + +async function exportKeyPair({ + keyPair, secretKey, publicKey, includeContext, canonicalize = false +} = {}) { + if(!(publicKey || secretKey)) { + throw new TypeError( + 'Export requires specifying either "publicKey" or "secretKey".'); + } + + const useSecretKey = secretKey && !!keyPair.secretKey; + + // export as Multikey + const exported = {}; + if(includeContext) { + exported['@context'] = _constants_js__WEBPACK_IMPORTED_MODULE_2__.MULTIKEY_CONTEXT_V1_URL; + } + exported.id = keyPair.id; + exported.type = 'Multikey'; + exported.controller = keyPair.controller; + + if(publicKey) { + exported.publicKeyMultibase = rawToPublicKeyMultibase(keyPair); + } + if(useSecretKey) { + exported.secretKeyMultibase = rawToSecretKeyMultibase({ + ...keyPair, canonicalize + }); + } + + if(keyPair.revoked) { + exported.revoked = keyPair.revoked; + } + + return exported; +} + +async function importKeyPair({ + id, controller, secretKeyMultibase, publicKeyMultibase, revoked +}) { + if(!publicKeyMultibase) { + throw new TypeError('The "publicKeyMultibase" property is required.'); + } + + const { + publicKey, secretKey + } = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.mbDecodeKeyPair)({publicKeyMultibase, secretKeyMultibase}); + + if(controller && !id) { + id = `${controller}#${publicKeyMultibase}`; + } + + return { + id, + controller, + publicKey, + secretKey, + publicKeyMultibase, + secretKeyMultibase, + revoked, + }; +} + +function jwkToPublicKeyBytes({jwk} = {}) { + const {kty, crv, x} = jwk; + if(kty !== 'OKP') { + throw new TypeError('"jwk.kty" must be "OKP".'); + } + if(crv !== 'Ed25519') { + throw new TypeError('"jwk.crv" must be "Ed25519".'); + } + if(typeof x !== 'string') { + throw new TypeError('"jwk.x" must be a string.'); + } + const publicKey = base64url_universal__WEBPACK_IMPORTED_MODULE_0__.decode(jwk.x); + if(publicKey.length !== _constants_js__WEBPACK_IMPORTED_MODULE_2__.PUBLIC_KEY_SIZE) { + throw new Error( + `Invalid public key size (${publicKey.length}); ` + + `expected ${_constants_js__WEBPACK_IMPORTED_MODULE_2__.PUBLIC_KEY_SIZE}.`); + } + return publicKey; +} + +function jwkToPublicKeyMultibase({jwk} = {}) { + const publicKey = jwkToPublicKeyBytes({jwk}); + const {publicKeyMultibase} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.mbEncodeKeyPair)({ + keyPair: {publicKey} + }); + return publicKeyMultibase; +} + +function jwkToSecretKeyBytes({jwk} = {}) { + const {kty, crv, d} = jwk; + if(kty !== 'OKP') { + throw new TypeError('"jwk.kty" must be "OKP".'); + } + if(crv !== 'Ed25519') { + throw new TypeError('"jwk.crv" must be "Ed25519".'); + } + if(typeof d !== 'string') { + throw new TypeError('"jwk.d" must be a string.'); + } + const secretKey = Uint8Array.from(base64url_universal__WEBPACK_IMPORTED_MODULE_0__.decode(jwk.d)); + if(secretKey.length !== _constants_js__WEBPACK_IMPORTED_MODULE_2__.SECRET_KEY_SIZE) { + throw new Error( + `Invalid secret key size (${secretKey.length}); ` + + `expected ${_constants_js__WEBPACK_IMPORTED_MODULE_2__.SECRET_KEY_SIZE}.`); + } + return secretKey; +} + +function jwkToSecretKeyMultibase({jwk} = {}) { + const secretKey = jwkToSecretKeyBytes({jwk}); + const {secretKeyMultibase} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.mbEncodeKeyPair)({ + keyPair: {secretKey} + }); + return secretKeyMultibase; +} + +function rawToPublicKeyMultibase({publicKey} = {}) { + if(publicKey.length !== _constants_js__WEBPACK_IMPORTED_MODULE_2__.PUBLIC_KEY_SIZE) { + throw new Error( + `Invalid public key size (${publicKey.length}); ` + + `expected ${_constants_js__WEBPACK_IMPORTED_MODULE_2__.PUBLIC_KEY_SIZE}.`); + } + const {publicKeyMultibase} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.mbEncodeKeyPair)({ + keyPair: {publicKey} + }); + return publicKeyMultibase; +} + +function rawToSecretKeyMultibase({ + secretKey, canonicalize = false +} = {}) { + if(secretKey.length !== _constants_js__WEBPACK_IMPORTED_MODULE_2__.SECRET_KEY_SIZE) { + if(secretKey.length !== LEGACY_SECRET_KEY_SIZE) { + throw new Error( + `Invalid secret key size (${secretKey.length}); ` + + `expected ${_constants_js__WEBPACK_IMPORTED_MODULE_2__.SECRET_KEY_SIZE}.`); + } + // handle legacy concatenated (secret key + public key) + if(canonicalize) { + secretKey = secretKey.subarray(0, _constants_js__WEBPACK_IMPORTED_MODULE_2__.SECRET_KEY_SIZE); + } + } + const {secretKeyMultibase} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.mbEncodeKeyPair)({ + keyPair: {secretKey} + }); + return secretKeyMultibase; +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-multikey/lib/validators.js" +/*!************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-multikey/lib/validators.js ***! + \************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ assertKeyBytes: () => (/* binding */ assertKeyBytes) +/* harmony export */ }); +/*! + * Copyright (c) 2022 Digital Bazaar, Inc. All rights reserved. + */ + +/** + * Asserts that key bytes have a type of Uint8Array and a specific length. + * + * @throws {TypeError|SyntaxError} - Throws a Type or Syntax error. + * + * @param {object} options - Options to use. + * @param {Uint8Array} options.bytes - The bytes being checked. + * @param {number} [options.expectedLength=32] - The expected bytes length. + * @param {string} [options.code] - An optional code for the error. + * + * @returns {undefined} Returns on success throws on error. + */ +function assertKeyBytes({bytes, expectedLength = 32, code}) { + if(!(bytes instanceof Uint8Array)) { + throw new TypeError('"bytes" must be a Uint8Array.'); + } + if(bytes.length !== expectedLength) { + const error = new Error( + `"bytes" must be a ${expectedLength}-byte Uint8Array.`); + // we need DataError for invalid byte length + error.name = 'DataError'; + // add the error code from the did:key spec if provided + if(code) { + error.code = code; + } + throw error; + } +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-signature-2020/lib/Ed25519Signature2020.js" +/*!****************************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-signature-2020/lib/Ed25519Signature2020.js ***! + \****************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Ed25519Signature2020: () => (/* binding */ Ed25519Signature2020) +/* harmony export */ }); +/* harmony import */ var base58_universal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! base58-universal */ "./node_modules/base58-universal/lib/index.js"); +/* harmony import */ var _digitalbazaar_ed25519_multikey__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @digitalbazaar/ed25519-multikey */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/index.js"); +/* harmony import */ var _digitalbazaar_ed25519_verification_key_2020__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @digitalbazaar/ed25519-verification-key-2020 */ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/lib/index.js"); +/* harmony import */ var jsonld_signatures__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! jsonld-signatures */ "./node_modules/jsonld-signatures/lib/jsonld-signatures.js"); +/* harmony import */ var ed25519_signature_2020_context__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ed25519-signature-2020-context */ "./node_modules/ed25519-signature-2020-context/dist/context.esm.js"); +/*! + * Copyright (c) 2020-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + + +const {suites: {LinkedDataSignature}} = jsonld_signatures__WEBPACK_IMPORTED_MODULE_3__; + + +// 'https://w3id.org/security/suites/ed25519-2020/v1' +const SUITE_CONTEXT_URL = ed25519_signature_2020_context__WEBPACK_IMPORTED_MODULE_4__["default"].constants.CONTEXT_URL; + +// multibase base58-btc header +const MULTIBASE_BASE58BTC_HEADER = 'z'; + +class Ed25519Signature2020 extends LinkedDataSignature { + /** + * @param {object} options - Options hashmap. + * + * Either a `key` OR at least one of `signer`/`verifier` is required: + * + * @param {object} [options.key] - An optional key object (containing an + * `id` property, and either `signer` or `verifier`, depending on the + * intended operation. Useful for when the application is managing keys + * itself (when using a KMS, you never have access to the private key, + * and so should use the `signer` param instead). + * @param {Function} [options.signer] - Signer function that returns an + * object with an async sign() method. This is useful when interfacing + * with a KMS (since you don't get access to the private key and its + * `signer()`, the KMS client gives you only the signer function to use). + * @param {Function} [options.verifier] - Verifier function that returns + * an object with an async `verify()` method. Useful when working with a + * KMS-provided verifier function. + * + * Advanced optional parameters and overrides: + * + * @param {object} [options.proof] - A JSON-LD document with options to use + * for the `proof` node (e.g. any other custom fields can be provided here + * using a context different from security-v2). + * @param {string|Date} [options.date] - Signing date to use if not passed. + * @param {boolean} [options.useNativeCanonize] - Whether to use a native + * canonize algorithm. + * @param {object} [options.canonizeOptions] - Options to pass to + * canonize algorithm. + */ + constructor({ + key, signer, verifier, proof, date, useNativeCanonize, canonizeOptions + } = {}) { + super({ + type: 'Ed25519Signature2020', LDKeyClass: _digitalbazaar_ed25519_verification_key_2020__WEBPACK_IMPORTED_MODULE_2__.Ed25519VerificationKey2020, + contextUrl: SUITE_CONTEXT_URL, + key, signer, verifier, proof, date, useNativeCanonize, + canonizeOptions + }); + // some operations may be performed with `Ed25519VerificationKey2018` or + // `Multikey`; so, `Ed25519VerificationKey2020` is recommended, but not + // strictly required + this.requiredKeyType = 'Ed25519VerificationKey2020'; + } + + /** + * Adds a signature (proofValue) field to the proof object. Called by + * LinkedDataSignature.createProof(). + * + * @param {object} options - The options to use. + * @param {Uint8Array} options.verifyData - Data to be signed (extracted + * from document, according to the suite's spec). + * @param {object} options.proof - Proof object (containing the proofPurpose, + * verificationMethod, etc). + * + * @returns {Promise} Resolves with the proof containing the signature + * value. + */ + async sign({verifyData, proof}) { + if(!(this.signer && typeof this.signer.sign === 'function')) { + throw new Error('A signer API has not been specified.'); + } + + const signatureBytes = await this.signer.sign({data: verifyData}); + proof.proofValue = + MULTIBASE_BASE58BTC_HEADER + base58_universal__WEBPACK_IMPORTED_MODULE_0__.encode(signatureBytes); + + return proof; + } + + /** + * Verifies the proof signature against the given data. + * + * @param {object} options - The options to use. + * @param {Uint8Array} options.verifyData - Canonicalized hashed data. + * @param {object} options.verificationMethod - Key object. + * @param {object} options.proof - The proof to be verified. + * + * @returns {Promise} Resolves with the verification result. + */ + async verifySignature({verifyData, verificationMethod, proof}) { + const {proofValue} = proof; + if(!(proofValue && typeof proofValue === 'string')) { + throw new TypeError( + 'The proof does not include a valid "proofValue" property.'); + } + if(proofValue[0] !== MULTIBASE_BASE58BTC_HEADER) { + throw new Error('Only base58btc multibase encoding is supported.'); + } + const signatureBytes = base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(proofValue.substr(1)); + + let {verifier} = this; + if(!verifier) { + const key = await _digitalbazaar_ed25519_multikey__WEBPACK_IMPORTED_MODULE_1__.from(verificationMethod); + verifier = key.verifier(); + } + return verifier.verify({data: verifyData, signature: signatureBytes}); + } + + async assertVerificationMethod({verificationMethod}) { + let contextUrl; + if(verificationMethod.type === 'Ed25519VerificationKey2020') { + contextUrl = SUITE_CONTEXT_URL; + } else { + throw new Error(`Unsupported key type "${verificationMethod.type}".`); + } + if(!_includesContext({document: verificationMethod, contextUrl})) { + // For DID Documents, since keys do not have their own contexts, + // the suite context is usually provided by the documentLoader logic + throw new TypeError( + `The verification method (key) must contain "${contextUrl}" context.` + ); + } + + // ensure verification method has not been revoked + if(verificationMethod.revoked !== undefined) { + throw new Error('The verification method has been revoked.'); + } + } + + async getVerificationMethod({proof, documentLoader}) { + if(this.key) { + // This happens most often during sign() operations. For verify(), + // the expectation is that the verification method will be fetched + // by the documentLoader (below), not provided as a `key` parameter. + return this.key.export({publicKey: true}); + } + + let {verificationMethod} = proof; + + if(typeof verificationMethod === 'object') { + verificationMethod = verificationMethod.id; + } + + if(!verificationMethod) { + throw new Error('No "verificationMethod" found in proof.'); + } + + const {document} = await documentLoader(verificationMethod); + + verificationMethod = typeof document === 'string' ? + JSON.parse(document) : document; + + // for maximum compatibility, import using multikey library and convert to + // type `Ed25519Signature2020` + const key = await _digitalbazaar_ed25519_multikey__WEBPACK_IMPORTED_MODULE_1__.from(verificationMethod); + verificationMethod = { + ...await key.export({publicKey: true, includeContext: true}), + '@context': SUITE_CONTEXT_URL, + type: 'Ed25519VerificationKey2020' + }; + await this.assertVerificationMethod({verificationMethod}); + + return verificationMethod; + } + + async matchProof({proof, document, purpose, documentLoader}) { + if(!_includesContext({document, contextUrl: SUITE_CONTEXT_URL})) { + return false; + } + + if(!await super.matchProof({proof, document, purpose, documentLoader})) { + return false; + } + if(!this.key) { + // no key specified, so assume this suite matches and it can be retrieved + return true; + } + + const {verificationMethod} = proof; + + // only match if the key specified matches the one in the proof + if(typeof verificationMethod === 'object') { + return verificationMethod.id === this.key.id; + } + return verificationMethod === this.key.id; + } +} + +/** + * Tests whether a provided JSON-LD document includes a context url in its + * `@context` property. + * + * @param {object} options - Options hashmap. + * @param {object} options.document - A JSON-LD document. + * @param {string} options.contextUrl - A context url. + * + * @returns {boolean} Returns true if document includes context. + */ +function _includesContext({document, contextUrl}) { + const context = document['@context']; + return context === contextUrl || + (Array.isArray(context) && context.includes(contextUrl)); +} + +Ed25519Signature2020.CONTEXT_URL = SUITE_CONTEXT_URL; +Ed25519Signature2020.CONTEXT = ed25519_signature_2020_context__WEBPACK_IMPORTED_MODULE_4__["default"].contexts.get(SUITE_CONTEXT_URL); + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-signature-2020/lib/index.js" +/*!*************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-signature-2020/lib/index.js ***! + \*************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Ed25519Signature2020: () => (/* reexport safe */ _Ed25519Signature2020_js__WEBPACK_IMPORTED_MODULE_1__.Ed25519Signature2020), +/* harmony export */ suiteContext: () => (/* reexport safe */ ed25519_signature_2020_context__WEBPACK_IMPORTED_MODULE_0__["default"]) +/* harmony export */ }); +/* harmony import */ var ed25519_signature_2020_context__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ed25519-signature-2020-context */ "./node_modules/ed25519-signature-2020-context/dist/context.esm.js"); +/* harmony import */ var _Ed25519Signature2020_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Ed25519Signature2020.js */ "./node_modules/@digitalbazaar/ed25519-signature-2020/lib/Ed25519Signature2020.js"); +/*! + * Copyright (c) 2020-2021 Digital Bazaar, Inc. All rights reserved. + */ + + + + + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/lib/Ed25519VerificationKey2020.js" +/*!*****************************************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-verification-key-2020/lib/Ed25519VerificationKey2020.js ***! + \*****************************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Ed25519VerificationKey2020: () => (/* binding */ Ed25519VerificationKey2020) +/* harmony export */ }); +/* harmony import */ var base58_universal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! base58-universal */ "./node_modules/base58-universal/lib/index.js"); +/* harmony import */ var base64url_universal__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! base64url-universal */ "./node_modules/base64url-universal/lib/browser.js"); +/* harmony import */ var _validators_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./validators.js */ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/lib/validators.js"); +/* harmony import */ var _ed25519_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ed25519.js */ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/lib/ed25519-browser.js"); +/* harmony import */ var crypto_ld__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! crypto-ld */ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/node_modules/crypto-ld/lib/index.js"); +/*! + * Copyright (c) 2021-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + + + + +const SUITE_ID = 'Ed25519VerificationKey2020'; +// multibase base58-btc header +const MULTIBASE_BASE58BTC_HEADER = 'z'; +// multicodec ed25519-pub header as varint +const MULTICODEC_ED25519_PUB_HEADER = new Uint8Array([0xed, 0x01]); +// multicodec ed25519-priv header as varint +const MULTICODEC_ED25519_PRIV_HEADER = new Uint8Array([0x80, 0x26]); + +class Ed25519VerificationKey2020 extends crypto_ld__WEBPACK_IMPORTED_MODULE_4__.LDKeyPair { + /** + * An implementation of the Ed25519VerificationKey2020 spec, for use with + * Linked Data Proofs. + * + * @see https://w3c-ccg.github.io/lds-ed25519-2020/#ed25519verificationkey2020 + * @see https://github.com/digitalbazaar/jsonld-signatures + * + * @param {object} options - Options hashmap. + * @param {string} options.controller - Controller DID or document url. + * @param {string} [options.id] - The key ID. If not provided, will be + * composed of controller and key fingerprint as hash fragment. + * @param {string} options.publicKeyMultibase - Multibase encoded public key + * with a multicodec ed25519-pub varint header [0xed, 0x01]. + * @param {string} [options.privateKeyMultibase] - Multibase private key + * with a multicodec ed25519-priv varint header [0x80, 0x26]. + * @param {string} [options.revoked] - Timestamp of when the key has been + * revoked, in RFC3339 format. If not present, the key itself is considered + * not revoked. Note that this mechanism is slightly different than DID + * Document key revocation, where a DID controller can revoke a key from + * that DID by removing it from the DID Document. + */ + constructor(options = {}) { + super(options); + this.type = SUITE_ID; + const {publicKeyMultibase, privateKeyMultibase} = options; + + if(!publicKeyMultibase) { + throw new TypeError('The "publicKeyMultibase" property is required.'); + } + + if(!publicKeyMultibase || !_isValidKeyHeader( + publicKeyMultibase, MULTICODEC_ED25519_PUB_HEADER)) { + throw new Error( + '"publicKeyMultibase" has invalid header bytes: ' + + `"${publicKeyMultibase}".`); + } + + if(privateKeyMultibase && !_isValidKeyHeader( + privateKeyMultibase, MULTICODEC_ED25519_PRIV_HEADER)) { + throw new Error('"privateKeyMultibase" has invalid header bytes.'); + } + + // assign valid key values + this.publicKeyMultibase = publicKeyMultibase; + this.privateKeyMultibase = privateKeyMultibase; + + // set key identifier if controller is provided + if(this.controller && !this.id) { + this.id = `${this.controller}#${this.fingerprint()}`; + } + // check that the passed in keyBytes are 32 bytes + (0,_validators_js__WEBPACK_IMPORTED_MODULE_2__.assertKeyBytes)({ + bytes: this._publicKeyBuffer, + code: 'invalidPublicKeyLength', + expectedLength: 32 + }); + } + + /** + * Creates an Ed25519 Key Pair from an existing serialized key pair. + * + * @param {object} options - Key pair options (see constructor). + * @example + * > const keyPair = await Ed25519VerificationKey2020.from({ + * controller: 'did:ex:1234', + * type: 'Ed25519VerificationKey2020', + * publicKeyMultibase, + * privateKeyMultibase + * }); + * + * @returns {Promise} An Ed25519 Key Pair. + */ + static async from(options) { + if(options.type === 'Ed25519VerificationKey2018') { + return Ed25519VerificationKey2020.fromEd25519VerificationKey2018(options); + } + if(options.type === 'JsonWebKey' || options.type === 'JsonWebKey2020') { + return Ed25519VerificationKey2020.fromJsonWebKey(options); + } + return new Ed25519VerificationKey2020(options); + } + + /** + * Instance creation method for backwards compatibility with the + * `Ed25519VerificationKey2018` key suite. + * + * @see https://github.com/digitalbazaar/ed25519-verification-key-2018 + * @typedef {object} Ed25519VerificationKey2018 + * @param {Ed25519VerificationKey2018} keyPair - Ed25519 2018 suite key pair. + * + * @returns {Ed25519VerificationKey2020} - 2020 suite instance. + */ + static fromEd25519VerificationKey2018({keyPair} = {}) { + const publicKeyMultibase = _encodeMbKey( + MULTICODEC_ED25519_PUB_HEADER, base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(keyPair.publicKeyBase58)); + const keyPair2020 = new Ed25519VerificationKey2020({ + id: keyPair.id, + controller: keyPair.controller, + publicKeyMultibase + }); + + if(keyPair.privateKeyBase58) { + keyPair2020.privateKeyMultibase = _encodeMbKey( + MULTICODEC_ED25519_PRIV_HEADER, + base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(keyPair.privateKeyBase58)); + } + + return keyPair2020; + } + + /** + * Creates a key pair instance (public key only) from a JsonWebKey2020 + * object. + * + * @see https://w3c-ccg.github.io/lds-jws2020/#json-web-key-2020 + * + * @param {object} options - Options hashmap. + * @param {string} options.id - Key id. + * @param {string} options.type - Key suite type. + * @param {string} options.controller - Key controller. + * @param {object} options.publicKeyJwk - JWK object. + * + * @returns {Promise} Resolves with key pair. + */ + static fromJsonWebKey2020({id, type, controller, publicKeyJwk} = {}) { + if(type !== 'JsonWebKey2020') { + throw new TypeError(`Invalid key type: "${type}".`); + } + return Ed25519VerificationKey2020.fromJsonWebKey({ + id, type, controller, publicKeyJwk + }); + } + + /** + * Creates a key pair instance (public key only) from a JsonWebKey object. + * + * @param {object} options - Options hashmap. + * @param {string} options.id - Key id. + * @param {string} options.type - Key suite type. + * @param {string} options.controller - Key controller. + * @param {object} options.publicKeyJwk - JWK object. + * + * @returns {Promise} Resolves with key pair. + */ + static fromJsonWebKey({id, type, controller, publicKeyJwk} = {}) { + if(!(type === 'JsonWebKey' || type === 'JsonWebKey2020')) { + throw new TypeError(`Invalid key type: "${type}".`); + } + if(!publicKeyJwk) { + throw new TypeError('"publicKeyJwk" property is required.'); + } + const {kty, crv} = publicKeyJwk; + if(kty !== 'OKP') { + throw new TypeError('"kty" is required to be "OKP".'); + } + if(crv !== 'Ed25519') { + throw new TypeError('"crv" is required to be "Ed25519".'); + } + const {x: publicKeyBase64Url} = publicKeyJwk; + const publicKeyMultibase = _encodeMbKey( + MULTICODEC_ED25519_PUB_HEADER, + base64url_universal__WEBPACK_IMPORTED_MODULE_1__.decode(publicKeyBase64Url)); + + return Ed25519VerificationKey2020.from({ + id, controller, publicKeyMultibase + }); + } + + /** + * Generates a KeyPair with an optional deterministic seed. + * + * @param {object} [options={}] - Options hashmap. + * @param {Uint8Array} [options.seed] - A 32-byte array seed for a + * deterministic key. + * + * @returns {Promise} Resolves with generated + * public/private key pair. + */ + static async generate({seed, ...keyPairOptions} = {}) { + let keyObject; + if(seed) { + keyObject = await _ed25519_js__WEBPACK_IMPORTED_MODULE_3__["default"].generateKeyPairFromSeed(seed); + } else { + keyObject = await _ed25519_js__WEBPACK_IMPORTED_MODULE_3__["default"].generateKeyPair(); + } + const publicKeyMultibase = + _encodeMbKey(MULTICODEC_ED25519_PUB_HEADER, keyObject.publicKey); + + const privateKeyMultibase = + _encodeMbKey(MULTICODEC_ED25519_PRIV_HEADER, keyObject.secretKey); + + return new Ed25519VerificationKey2020({ + publicKeyMultibase, + privateKeyMultibase, + ...keyPairOptions + }); + } + + /** + * Creates an instance of Ed25519VerificationKey2020 from a key fingerprint. + * + * @param {object} options - Options hashmap. + * @param {string} options.fingerprint - Multibase encoded key fingerprint. + * + * @returns {Ed25519VerificationKey2020} Returns key pair instance (with + * public key only). + */ + static fromFingerprint({fingerprint} = {}) { + return new Ed25519VerificationKey2020({publicKeyMultibase: fingerprint}); + } + + /** + * @returns {Uint8Array} Public key bytes. + */ + get _publicKeyBuffer() { + if(!this.publicKeyMultibase) { + return; + } + // remove multibase header + const publicKeyMulticodec = + base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(this.publicKeyMultibase.substr(1)); + // remove multicodec header + const publicKeyBytes = + publicKeyMulticodec.slice(MULTICODEC_ED25519_PUB_HEADER.length); + + return publicKeyBytes; + } + + /** + * @returns {Uint8Array} Private key bytes. + */ + get _privateKeyBuffer() { + if(!this.privateKeyMultibase) { + return; + } + // remove multibase header + const privateKeyMulticodec = + base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(this.privateKeyMultibase.substr(1)); + // remove multicodec header + const privateKeyBytes = + privateKeyMulticodec.slice(MULTICODEC_ED25519_PRIV_HEADER.length); + + return privateKeyBytes; + } + + /** + * Generates and returns a multiformats encoded + * ed25519 public key fingerprint (for use with cryptonyms, for example). + * + * @see https://github.com/multiformats/multicodec + * + * @returns {string} The fingerprint. + */ + fingerprint() { + return this.publicKeyMultibase; + } + + /** + * Exports the serialized representation of the KeyPair + * and other information that JSON-LD Signatures can use to form a proof. + * + * @param {object} [options={}] - Options hashmap. + * @param {boolean} [options.publicKey] - Export public key material? + * @param {boolean} [options.privateKey] - Export private key material? + * @param {boolean} [options.includeContext] - Include JSON-LD context? + * + * @returns {object} A plain js object that's ready for serialization + * (to JSON, etc), for use in DIDs, Linked Data Proofs, etc. + */ + export({publicKey = false, privateKey = false, includeContext = false} = {}) { + if(!(publicKey || privateKey)) { + throw new TypeError( + 'Export requires specifying either "publicKey" or "privateKey".'); + } + const exportedKey = { + id: this.id, + type: this.type + }; + if(includeContext) { + exportedKey['@context'] = Ed25519VerificationKey2020.SUITE_CONTEXT; + } + if(this.controller) { + exportedKey.controller = this.controller; + } + if(publicKey) { + exportedKey.publicKeyMultibase = this.publicKeyMultibase; + } + if(privateKey) { + exportedKey.privateKeyMultibase = this.privateKeyMultibase; + } + if(this.revoked) { + exportedKey.revoked = this.revoked; + } + return exportedKey; + } + + /** + * Returns the JWK representation of this key pair. + * + * @see https://datatracker.ietf.org/doc/html/rfc8037 + * + * @param {object} [options={}] - Options hashmap. + * @param {boolean} [options.publicKey] - Include public key? + * @param {boolean} [options.privateKey] - Include private key? + * + * @returns {{kty: string, crv: string, x: string, d: string}} JWK + * representation. + */ + toJwk({publicKey = true, privateKey = false} = {}) { + if(!(publicKey || privateKey)) { + throw TypeError('Either a "publicKey" or a "privateKey" is required.'); + } + const jwk = {crv: 'Ed25519', kty: 'OKP'}; + if(publicKey) { + jwk.x = base64url_universal__WEBPACK_IMPORTED_MODULE_1__.encode(this._publicKeyBuffer); + } + if(privateKey) { + jwk.d = base64url_universal__WEBPACK_IMPORTED_MODULE_1__.encode(this._privateKeyBuffer); + } + return jwk; + } + + /** + * @see https://datatracker.ietf.org/doc/html/rfc8037#appendix-A.3 + * + * @returns {Promise} JWK Thumbprint. + */ + async jwkThumbprint() { + const publicKey = base64url_universal__WEBPACK_IMPORTED_MODULE_1__.encode(this._publicKeyBuffer); + const serialized = `{"crv":"Ed25519","kty":"OKP","x":"${publicKey}"}`; + const data = new TextEncoder().encode(serialized); + return base64url_universal__WEBPACK_IMPORTED_MODULE_1__.encode( + new Uint8Array(await _ed25519_js__WEBPACK_IMPORTED_MODULE_3__["default"].sha256digest({data}))); + } + + /** + * Returns the JsonWebKey representation of this key pair. + * + * @returns {Promise} JsonWebKey representation. + */ + async toJsonWebKey() { + return { + '@context': 'https://w3id.org/security/jwk/v1', + id: this.controller + '#' + await this.jwkThumbprint(), + type: 'JsonWebKey', + controller: this.controller, + publicKeyJwk: this.toJwk({publicKey: true}) + }; + } + + /** + * Returns the JsonWebKey2020 representation of this key pair. + * + * @see https://w3c-ccg.github.io/lds-jws2020/#json-web-key-2020 + * + * @returns {Promise} JsonWebKey2020 representation. + */ + async toJsonWebKey2020() { + return { + '@context': 'https://w3id.org/security/jws/v1', + id: this.controller + '#' + await this.jwkThumbprint(), + type: 'JsonWebKey2020', + controller: this.controller, + publicKeyJwk: this.toJwk({publicKey: true}) + }; + } + + /** + * Tests whether the fingerprint was generated from a given key pair. + * + * @example + * > edKeyPair.verifyFingerprint({fingerprint: 'z6Mk2S2Q...6MkaFJewa'}); + * {valid: true}; + * + * @param {object} options - Options hashmap. + * @param {string} options.fingerprint - A public key fingerprint. + * + * @returns {{valid: boolean, error: *}} Result of verification. + */ + verifyFingerprint({fingerprint} = {}) { + // fingerprint should have multibase base58-btc header + if(!(typeof fingerprint === 'string' && + fingerprint[0] === MULTIBASE_BASE58BTC_HEADER)) { + return { + error: new Error('"fingerprint" must be a multibase encoded string.'), + valid: false + }; + } + let fingerprintBuffer; + try { + fingerprintBuffer = base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(fingerprint.substr(1)); + if(!fingerprintBuffer) { + throw new TypeError('Invalid encoding of fingerprint.'); + } + } catch(e) { + return {error: e, valid: false}; + } + + const buffersEqual = _isEqualBuffer(this._publicKeyBuffer, + fingerprintBuffer.slice(2)); + + // validate the first two multicodec bytes + const valid = + fingerprintBuffer[0] === MULTICODEC_ED25519_PUB_HEADER[0] && + fingerprintBuffer[1] === MULTICODEC_ED25519_PUB_HEADER[1] && + buffersEqual; + if(!valid) { + return { + error: new Error('The fingerprint does not match the public key.'), + valid: false + }; + } + return {valid}; + } + + signer() { + const privateKeyBuffer = this._privateKeyBuffer; + + return { + async sign({data}) { + if(!privateKeyBuffer) { + throw new Error('A private key is not available for signing.'); + } + return _ed25519_js__WEBPACK_IMPORTED_MODULE_3__["default"].sign(privateKeyBuffer, data); + }, + id: this.id + }; + } + + verifier() { + const publicKeyBuffer = this._publicKeyBuffer; + + return { + async verify({data, signature}) { + if(!publicKeyBuffer) { + throw new Error('A public key is not available for verifying.'); + } + return _ed25519_js__WEBPACK_IMPORTED_MODULE_3__["default"].verify(publicKeyBuffer, data, signature); + }, + id: this.id + }; + } +} +// Used by CryptoLD harness for dispatching. +Ed25519VerificationKey2020.suite = SUITE_ID; +// Used by CryptoLD harness's fromKeyId() method. +Ed25519VerificationKey2020.SUITE_CONTEXT = + 'https://w3id.org/security/suites/ed25519-2020/v1'; + +// check to ensure that two buffers are byte-for-byte equal +// WARNING: this function must only be used to check public information as +// timing attacks can be used for non-constant time checks on +// secret information. +function _isEqualBuffer(buf1, buf2) { + if(buf1.length !== buf2.length) { + return false; + } + for(let i = 0; i < buf1.length; i++) { + if(buf1[i] !== buf2[i]) { + return false; + } + } + return true; +} + +// check a multibase key for an expected header +function _isValidKeyHeader(multibaseKey, expectedHeader) { + if(!(typeof multibaseKey === 'string' && + multibaseKey[0] === MULTIBASE_BASE58BTC_HEADER)) { + return false; + } + + const keyBytes = base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(multibaseKey.slice(1)); + return expectedHeader.every((val, i) => keyBytes[i] === val); +} + +// encode a multibase base58-btc multicodec key +function _encodeMbKey(header, key) { + const mbKey = new Uint8Array(header.length + key.length); + + mbKey.set(header); + mbKey.set(key, header.length); + + return MULTIBASE_BASE58BTC_HEADER + base58_universal__WEBPACK_IMPORTED_MODULE_0__.encode(mbKey); +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/lib/ed25519-browser.js" +/*!******************************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-verification-key-2020/lib/ed25519-browser.js ***! + \******************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _validators_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./validators.js */ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/lib/validators.js"); +/* harmony import */ var _noble_ed25519__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/ed25519 */ "./node_modules/@noble/ed25519/lib/esm/index.js"); +/*! + * Copyright (c) 2020-2022 Digital Bazaar, Inc. All rights reserved. + */ + + + +// browser MUST provide "crypto.getRandomValues" +const crypto = globalThis.crypto; +if(!crypto.getRandomValues) { + throw new Error('Browser does not provide "crypto.getRandomValues".'); +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ + async generateKeyPair() { + const seed = new Uint8Array(32); + crypto.getRandomValues(seed); + const keyPair = await generateKeyPairFromSeed(seed); + seed.fill(0); + return keyPair; + }, + generateKeyPairFromSeed, + async sign(secretKey, data) { + return _noble_ed25519__WEBPACK_IMPORTED_MODULE_1__.sign(data, secretKey.slice(0, 32)); + }, + async verify(publicKey, data, signature) { + return _noble_ed25519__WEBPACK_IMPORTED_MODULE_1__.verify(signature, data, publicKey); + }, + async sha256digest({data}) { + return crypto.subtle.digest('SHA-256', data); + } +}); + +async function generateKeyPairFromSeed(seed) { + (0,_validators_js__WEBPACK_IMPORTED_MODULE_0__.assertKeyBytes)({ + bytes: seed, + expectedLength: 32, + }); + const publicKey = await _noble_ed25519__WEBPACK_IMPORTED_MODULE_1__.getPublicKey(seed); + const secretKey = new Uint8Array(64); + secretKey.set(seed); + secretKey.set(publicKey, seed.length); + return { + publicKey, + secretKey + }; +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/lib/index.js" +/*!********************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-verification-key-2020/lib/index.js ***! + \********************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Ed25519VerificationKey2020: () => (/* reexport safe */ _Ed25519VerificationKey2020_js__WEBPACK_IMPORTED_MODULE_0__.Ed25519VerificationKey2020) +/* harmony export */ }); +/* harmony import */ var _Ed25519VerificationKey2020_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Ed25519VerificationKey2020.js */ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/lib/Ed25519VerificationKey2020.js"); +/*! + * Copyright (c) 2020 Digital Bazaar, Inc. All rights reserved. + */ + + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/lib/validators.js" +/*!*************************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-verification-key-2020/lib/validators.js ***! + \*************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ assertKeyBytes: () => (/* binding */ assertKeyBytes) +/* harmony export */ }); +/*! + * Copyright (c) 2022 Digital Bazaar, Inc. All rights reserved. + */ + +/** + * Asserts that key bytes have a type of Uint8Array and a specific length. + * + * @throws {TypeError|SyntaxError} - Throws a Type or Syntax error. + * + * @param {object} options - Options to use. + * @param {Uint8Array} options.bytes - The bytes being checked. + * @param {number} [options.expectedLength=32] - The expected bytes length. + * @param {string} [options.code] - An optional code for the error. + * + * @returns {undefined} Returns on success throws on error. + */ +function assertKeyBytes({bytes, expectedLength = 32, code}) { + if(!(bytes instanceof Uint8Array)) { + throw new TypeError('"bytes" must be a Uint8Array.'); + } + if(bytes.length !== expectedLength) { + const error = new Error( + `"bytes" must be a ${expectedLength}-byte Uint8Array.`); + // we need DataError for invalid byte length + error.name = 'DataError'; + // add the error code from the did:key spec if provided + if(code) { + error.code = code; + } + throw error; + } +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/node_modules/crypto-ld/lib/CryptoLD.js" +/*!**********************************************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-verification-key-2020/node_modules/crypto-ld/lib/CryptoLD.js ***! + \**********************************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CryptoLD: () => (/* binding */ CryptoLD) +/* harmony export */ }); +/*! + * Copyright (c) 2020-2022 Digital Bazaar, Inc. All rights reserved. + */ + +/** + * General purpose key generation driver for Linked Data cryptographic key + * pairs. + * + * @param {Map} [suites] - Optional map of supported suites, by suite id. + */ +class CryptoLD { + constructor({suites} = {}) { + this.suites = suites || new Map(); + } + + /** + * Installs support for a key type (suite). + * + * @param {LDKeyPair} keyPairLib - Conforming key pair library for a suite. + */ + use(keyPairLib) { + this.suites.set(keyPairLib.suite, keyPairLib); + } + + /** + * Generates a public/private LDKeyPair. + * + * @param {object} options - Suite-specific key options. + * @param {string} options.type - Key suite id (for example, + * 'Ed25519VerificationKey2020'). + * @param {string} [options.controller] - Controller DID or URL for the + * generated key pair. If present, used to auto-initialize the key.id. + * + * @returns {Promise} Generated key pair. + */ + async generate(options = {}) { + const Suite = this._suiteForType(options); + return Suite.generate(options); + } + + /** + * Imports a public/private key pair from serialized data. + * + * @param {object} serialized - Serialized key object. + * + * @throws {Error} - On missing or invalid serialized key data. + * + * @returns {Promise} Imported key pair. + */ + async from(serialized = {}) { + const Suite = this._suiteForType(serialized); + + if(serialized['@context']) { + // presume this may be an untrusted (fetched, etc) key document + return Suite.fromKeyDocument({document: serialized}); + } + + return Suite.from(serialized); + } + + /** + * Imports a key pair instance from a provided externally fetched key + * document (fetched via a secure JSON-LD `documentLoader` or via + * `cryptoLd.fromKeyId()`), optionally checking it for revocation and required + * context. + * + * @param {object} options - Options hashmap. + * @param {string} options.document - Externally fetched key document. + * @param {boolean} [options.checkContext=true] - Whether to check that the + * fetched key document contains the context required by the key's crypto + * suite. + * @param {boolean} [options.checkRevoked=true] - Whether to check the key + * object for the presence of the `revoked` timestamp. + * + * @returns {Promise} Resolves with the resulting key pair + * instance. + */ + async fromKeyDocument({ + document, checkContext = true, checkRevoked = true + } = {}) { + if(!document) { + throw new TypeError('The "document" parameter is required.'); + } + const Suite = this._suiteForType(document); + + return Suite.fromKeyDocument({document, checkContext, checkRevoked}); + } + + /** + * Imports a key pair instance via the provided `documentLoader` function, + * optionally checking it for revocation and required context. + * + * @param {object} options - Options hashmap. + * @param {string} options.id - Key ID or URI. + * @param {Function} options.documentLoader - JSON-LD Document Loader. + * @param {boolean} [options.checkContext=true] - Whether to check that the + * fetched key document contains the context required by the key's crypto + * suite. + * @param {boolean} [options.checkRevoked=true] - Whether to check the key + * object for the presence of the `revoked` timestamp. + * + * @returns {Promise} Resolves with the appropriate key pair + * instance. + */ + async fromKeyId({ + id, documentLoader, checkContext = true, checkRevoked = true + } = {}) { + if(!id) { + throw new TypeError('The "id" parameter is required.'); + } + if(!documentLoader) { + throw new TypeError('The "documentLoader" parameter is required.'); + } + let keyDocument; + try { + ({document: keyDocument} = await documentLoader(id)); + // the supplied documentLoader may not be properly implemented + if(!keyDocument) { + throw new Error( + 'The "documentLoader" function must return a "document" object.'); + } + } catch(e) { + const error = new Error('Error fetching document: ' + e.message); + error.cause = e; + throw error; + } + const fetchedType = keyDocument.type; + if(!fetchedType) { + throw new Error('Key suite type not found in fetched document.'); + } + const keySuite = this.suites.get(fetchedType); + if(!keySuite) { + throw new Error(`Support for suite "${fetchedType}" is not installed.`); + } + + return keySuite.fromKeyDocument({document: keyDocument, checkContext, + checkRevoked}); + } + + /** + * Tests if a given key type is currently installed. + * + * @param {string} [type] - Key suite id ('Ed25519VerificationKey2020'). + * @private + * + * @returns {boolean} True if key type installed. + */ + _installed({type}) { + return this.suites.has(type); + } + + /** + * Returns the installed crypto suite class for a given document's type. + * + * @param {object} document - A serialized key document (or options document). + * @param {string} document.type - Key suite id (for example, + * 'Ed25519VerificationKey2020'). + * + * @returns {object} LDKeyPair (crypto suite) class. + */ + _suiteForType(document) { + const type = document && document.type; + + if(!type) { + throw new TypeError('Missing key type.'); + } + if(!this._installed({type})) { + throw new Error(`Support for key type "${type}" is not installed.`); + } + + return this.suites.get(type); + } +} + +/** + * @typedef LDKeyPair + */ + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/node_modules/crypto-ld/lib/LDKeyPair.js" +/*!***********************************************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-verification-key-2020/node_modules/crypto-ld/lib/LDKeyPair.js ***! + \***********************************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ LDKeyPair: () => (/* binding */ LDKeyPair) +/* harmony export */ }); +/*! + * Copyright (c) 2018-2022 Digital Bazaar, Inc. All rights reserved. + */ + +/** + * When adding support for a new suite type for `crypto-ld`, developers should + * do the following: + * + * 1. Create their own npm package / github repo, such as `example-key-pair`. + * 2. Subclass LDKeyPair. + * 3. Override relevant methods (such as `export()` and `fingerprint()`). + * 4. Add to the key type table in the `crypto-ld` README.md (that's this repo). + */ +class LDKeyPair { + /* eslint-disable jsdoc/require-description-complete-sentence */ + /** + * Creates a public/private key pair instance. This is an abstract base class, + * actual key material and suite-specific methods are handled in the subclass. + * + * To generate or import a key pair, use the `cryptoLd` instance. + * + * @see CryptoLD.js + * + * @param {object} options - The options to use. + * @param {string} options.id - The key id, typically composed of controller + * URL and key fingerprint as hash fragment. + * @param {string} options.controller - DID/URL of the person/entity + * controlling this key. + * @param {string} [options.revoked] - Timestamp of when the key has been + * revoked, in RFC3339 format. If not present, the key itself is + * considered not revoked. (Note that this mechanism is slightly different + * than DID Document key revocation, where a DID controller can revoke a + * key from that DID by removing it from the DID Document.) + */ + /* eslint-enable */ + constructor({id, controller, revoked} = {}) { + this.id = id; + this.controller = controller; + this.revoked = revoked; + // this.type is set in subclass constructor + } + + /* eslint-disable jsdoc/check-param-names */ + /** + * Generates a new public/private key pair instance. + * Note that this method is not typically called directly by client code, + * but instead is used through a `cryptoLd` instance. + * + * @param {object} options - Suite-specific options for the KeyPair. For + * common options, see the `LDKeyPair.constructor()` docstring. + * + * @returns {Promise} An LDKeyPair instance. + */ + /* eslint-enable */ + static async generate(/* options */) { + throw new Error('Abstract method, must be implemented in subclass.'); + } + + /** + * Imports a key pair instance from a provided externally fetched key + * document (fetched via a secure JSON-LD `documentLoader` or via + * `cryptoLd.fromKeyId()`), optionally checking it for revocation and required + * context. + * + * @param {object} options - Options hashmap. + * @param {string} options.document - Externally fetched key document. + * @param {boolean} [options.checkContext=true] - Whether to check that the + * fetched key document contains the context required by the key's crypto + * suite. + * @param {boolean} [options.checkRevoked=true] - Whether to check the key + * object for the presence of the `revoked` timestamp. + * + * @returns {Promise} Resolves with the resulting key pair + * instance. + */ + static async fromKeyDocument({ + document, checkContext = true, checkRevoked = true + } = {}) { + if(!document) { + throw new TypeError('The "document" parameter is required.'); + } + + if(checkContext) { + const fetchedDocContexts = [].concat(document['@context']); + if(!fetchedDocContexts.includes(this.SUITE_CONTEXT)) { + throw new Error('Key document does not contain required context "' + + this.SUITE_CONTEXT + '".'); + } + } + if(checkRevoked && document.revoked) { + throw new Error(`Key has been revoked since: "${document.revoked}".`); + } + return this.from(document); + } + + /* eslint-disable jsdoc/check-param-names */ + /** + * Generates a KeyPair from some options. + * + * @param {object} options - Will generate a key pair in multiple different + * formats. + * @example + * > const options = { + * type: 'Ed25519VerificationKey2020' + * }; + * > const edKeyPair = await LDKeyPair.from(options); + * + * @returns {Promise} A LDKeyPair. + * @throws Unsupported Key Type. + */ + /* eslint-enable */ + static async from(/* options */) { + throw new Error('Abstract method from() must be implemented in subclass.'); + } + + /** + * Exports the serialized representation of the KeyPair + * and other information that json-ld Signatures can use to form a proof. + * + * NOTE: Subclasses MUST override this method (and add the exporting of + * their public and private key material). + * + * @param {object} [options={}] - Options hashmap. + * @param {boolean} [options.publicKey] - Export public key material? + * @param {boolean} [options.privateKey] - Export private key material? + * + * @returns {object} A public key object + * information used in verification methods by signatures. + */ + export({publicKey = false, privateKey = false} = {}) { + if(!publicKey && !privateKey) { + throw new Error( + 'Export requires specifying either "publicKey" or "privateKey".'); + } + const key = { + id: this.id, + type: this.type, + controller: this.controller + }; + if(this.revoked) { + key.revoked = this.revoked; + } + + return key; + } + + /** + * Returns the public key fingerprint, multibase+multicodec encoded. The + * specific fingerprint method is determined by the key suite, and is often + * either a hash of the public key material (such as with RSA), or the + * full encoded public key (for key types with sufficiently short + * representations, such as ed25519). + * This is frequently used in initializing the key id, or generating some + * types of cryptonym DIDs. + * + * @returns {string} The fingerprint. + */ + fingerprint() { + throw new Error('Abstract method, must be implemented in subclass.'); + } + + /* eslint-disable jsdoc/check-param-names */ + /** + * Verifies that a given key fingerprint matches the public key material + * belonging to this key pair. + * + * @param {string} fingerprint - Public key fingerprint. + * + * @returns {{verified: boolean}} An object with verified flag. + */ + /* eslint-enable */ + verifyFingerprint(/* {fingerprint} */) { + throw new Error('Abstract method, must be implemented in subclass.'); + } + + /* eslint-disable max-len */ + /** + * Returns a signer object for use with + * [jsonld-signatures]{@link https://github.com/digitalbazaar/jsonld-signatures}. + * NOTE: Applies only to verifier type keys (like ed25519). + * + * @example + * > const signer = keyPair.signer(); + * > signer + * { sign: [AsyncFunction: sign] } + * > signer.sign({data}); + * + * @returns {{sign: Function}} A signer for json-ld usage. + */ + /* eslint-enable */ + signer() { + return { + async sign({/* data */}) { + throw new Error('Abstract method, must be implemented in subclass.'); + } + }; + } + + /* eslint-disable max-len */ + /** + * Returns a verifier object for use with + * [jsonld-signatures]{@link https://github.com/digitalbazaar/jsonld-signatures}. + * NOTE: Applies only to verifier type keys (like ed25519). + * + * @example + * > const verifier = keyPair.verifier(); + * > verifier + * { verify: [AsyncFunction: verify] } + * > verifier.verify(key); + * + * @returns {{verify: Function}} Used to verify jsonld-signatures. + */ + /* eslint-enable */ + verifier() { + return { + async verify({/* data, signature */}) { + throw new Error('Abstract method, must be implemented in subclass.'); + } + }; + } +} + +// Implementers must override this in subclasses +LDKeyPair.SUITE_CONTEXT = 'INVALID LDKeyPair CONTEXT'; + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/node_modules/crypto-ld/lib/index.js" +/*!*******************************************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/ed25519-verification-key-2020/node_modules/crypto-ld/lib/index.js ***! + \*******************************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CryptoLD: () => (/* reexport safe */ _CryptoLD_js__WEBPACK_IMPORTED_MODULE_0__.CryptoLD), +/* harmony export */ LDKeyPair: () => (/* reexport safe */ _LDKeyPair_js__WEBPACK_IMPORTED_MODULE_1__.LDKeyPair) +/* harmony export */ }); +/* harmony import */ var _CryptoLD_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CryptoLD.js */ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/node_modules/crypto-ld/lib/CryptoLD.js"); +/* harmony import */ var _LDKeyPair_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./LDKeyPair.js */ "./node_modules/@digitalbazaar/ed25519-verification-key-2020/node_modules/crypto-ld/lib/LDKeyPair.js"); +/* + * Copyright (c) 2018-2022 Digital Bazaar, Inc. All rights reserved. + */ + + + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/canonize.js" +/*!*********************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/canonize.js ***! + \*********************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ canonize: () => (/* binding */ canonize) +/* harmony export */ }); +/* harmony import */ var rdf_canonize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rdf-canonize */ "./node_modules/rdf-canonize/index.js"); +/* harmony import */ var jsonld__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jsonld */ "./node_modules/jsonld/lib/jsonld.js"); +/*! + * Copyright (c) 2023-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + +async function canonize(input, options) { + // convert to RDF dataset and do canonicalization + options = { + algorithm: 'RDFC-1.0', + format: 'application/n-quads', + base: null, + safe: true, + ...options + }; + const opts = { + rdfDirection: 'i18n-datatype', ...options, produceGeneralizedRdf: false, + }; + delete opts.format; + const dataset = await jsonld__WEBPACK_IMPORTED_MODULE_1__.toRDF(input, opts); + return rdf_canonize__WEBPACK_IMPORTED_MODULE_0__.canonize(dataset, options); +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/createVerifier.js" +/*!***************************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/createVerifier.js ***! + \***************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ createVerifier: () => (/* binding */ createVerifier) +/* harmony export */ }); +/* harmony import */ var _digitalbazaar_ed25519_multikey__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @digitalbazaar/ed25519-multikey */ "./node_modules/@digitalbazaar/ed25519-multikey/lib/index.js"); +/*! + * Copyright (c) 2023 Digital Bazaar, Inc. All rights reserved. + */ + + +async function createVerifier({verificationMethod}) { + const key = await _digitalbazaar_ed25519_multikey__WEBPACK_IMPORTED_MODULE_0__.from(verificationMethod); + const verifier = key.verifier(); + return verifier; +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/index.js" +/*!******************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/index.js ***! + \******************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ cryptosuite: () => (/* binding */ cryptosuite) +/* harmony export */ }); +/* harmony import */ var _canonize_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./canonize.js */ "./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/canonize.js"); +/* harmony import */ var _createVerifier_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./createVerifier.js */ "./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/createVerifier.js"); +/* harmony import */ var _name_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./name.js */ "./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/name.js"); +/* harmony import */ var _requiredAlgorithm_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./requiredAlgorithm.js */ "./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/requiredAlgorithm.js"); +/*! + * Copyright (c) 2023 Digital Bazaar, Inc. All rights reserved. +*/ + + + + + +const cryptosuite = { + canonize: _canonize_js__WEBPACK_IMPORTED_MODULE_0__.canonize, + createVerifier: _createVerifier_js__WEBPACK_IMPORTED_MODULE_1__.createVerifier, + name: _name_js__WEBPACK_IMPORTED_MODULE_2__.name, + requiredAlgorithm: _requiredAlgorithm_js__WEBPACK_IMPORTED_MODULE_3__.requiredAlgorithm, +}; + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/name.js" +/*!*****************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/name.js ***! + \*****************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ name: () => (/* binding */ name) +/* harmony export */ }); +/*! + * Copyright (c) 2023 Digital Bazaar, Inc. All rights reserved. + */ +const name = 'eddsa-rdfc-2022'; + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/requiredAlgorithm.js" +/*!******************************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/lib/requiredAlgorithm.js ***! + \******************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ requiredAlgorithm: () => (/* binding */ requiredAlgorithm) +/* harmony export */ }); +/*! + * Copyright (c) 2023 Digital Bazaar, Inc. All rights reserved. + */ +const requiredAlgorithm = 'Ed25519'; + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/security-context/dist/context.esm.js" +/*!**************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/security-context/dist/context.esm.js ***! + \**************************************************************************/ +(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CONTEXT: () => (/* binding */ context_3), +/* harmony export */ CONTEXT_URL: () => (/* binding */ context_4), +/* harmony export */ SECURITY_CONTEXT_V1_URL: () => (/* binding */ context_5), +/* harmony export */ SECURITY_CONTEXT_V2_URL: () => (/* binding */ context_6), +/* harmony export */ constants: () => (/* binding */ context_2), +/* harmony export */ contexts: () => (/* binding */ context_1), +/* harmony export */ "default": () => (/* binding */ context$1) +/* harmony export */ }); +function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var context = createCommonjsModule(function (module, exports) { +!function(e,t){for(var i in t)e[i]=t[i];}(exports,function(e){var t={};function i(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,i),a.l=!0,a.exports}return i.m=e,i.c=t,i.d=function(e,t,r){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r});},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0});},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(i.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)i.d(r,a,function(t){return e[t]}.bind(null,a));return r},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=0)}([function(e,t,i){/*! + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */const r=i(1),a=i(2),c=i(3),{CONTEXT_URL:n,SECURITY_CONTEXT_V1_URL:o,SECURITY_CONTEXT_V2_URL:s}=c,p=new Map;p.set(o,r),p.set(s,a),e.exports={constants:c,contexts:p,SECURITY_CONTEXT_V1_URL:o,SECURITY_CONTEXT_V2_URL:s,CONTEXT_URL:n,CONTEXT:a};},function(e,t,i){/*! + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */e.exports={"@context":{id:"@id",type:"@type",dc:"http://purl.org/dc/terms/",sec:"https://w3id.org/security#",xsd:"http://www.w3.org/2001/XMLSchema#",EcdsaKoblitzSignature2016:"sec:EcdsaKoblitzSignature2016",Ed25519Signature2018:"sec:Ed25519Signature2018",EncryptedMessage:"sec:EncryptedMessage",GraphSignature2012:"sec:GraphSignature2012",LinkedDataSignature2015:"sec:LinkedDataSignature2015",LinkedDataSignature2016:"sec:LinkedDataSignature2016",CryptographicKey:"sec:Key",authenticationTag:"sec:authenticationTag",canonicalizationAlgorithm:"sec:canonicalizationAlgorithm",cipherAlgorithm:"sec:cipherAlgorithm",cipherData:"sec:cipherData",cipherKey:"sec:cipherKey",created:{"@id":"dc:created","@type":"xsd:dateTime"},creator:{"@id":"dc:creator","@type":"@id"},digestAlgorithm:"sec:digestAlgorithm",digestValue:"sec:digestValue",domain:"sec:domain",encryptionKey:"sec:encryptionKey",expiration:{"@id":"sec:expiration","@type":"xsd:dateTime"},expires:{"@id":"sec:expiration","@type":"xsd:dateTime"},initializationVector:"sec:initializationVector",iterationCount:"sec:iterationCount",nonce:"sec:nonce",normalizationAlgorithm:"sec:normalizationAlgorithm",owner:{"@id":"sec:owner","@type":"@id"},password:"sec:password",privateKey:{"@id":"sec:privateKey","@type":"@id"},privateKeyPem:"sec:privateKeyPem",publicKey:{"@id":"sec:publicKey","@type":"@id"},publicKeyBase58:"sec:publicKeyBase58",publicKeyPem:"sec:publicKeyPem",publicKeyWif:"sec:publicKeyWif",publicKeyService:{"@id":"sec:publicKeyService","@type":"@id"},revoked:{"@id":"sec:revoked","@type":"xsd:dateTime"},salt:"sec:salt",signature:"sec:signature",signatureAlgorithm:"sec:signingAlgorithm",signatureValue:"sec:signatureValue"}};},function(e,t,i){/*! + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */e.exports={"@context":[{"@version":1.1},"https://w3id.org/security/v1",{AesKeyWrappingKey2019:"sec:AesKeyWrappingKey2019",DeleteKeyOperation:"sec:DeleteKeyOperation",DeriveSecretOperation:"sec:DeriveSecretOperation",EcdsaSecp256k1Signature2019:"sec:EcdsaSecp256k1Signature2019",EcdsaSecp256r1Signature2019:"sec:EcdsaSecp256r1Signature2019",EcdsaSecp256k1VerificationKey2019:"sec:EcdsaSecp256k1VerificationKey2019",EcdsaSecp256r1VerificationKey2019:"sec:EcdsaSecp256r1VerificationKey2019",Ed25519Signature2018:"sec:Ed25519Signature2018",Ed25519VerificationKey2018:"sec:Ed25519VerificationKey2018",EquihashProof2018:"sec:EquihashProof2018",ExportKeyOperation:"sec:ExportKeyOperation",GenerateKeyOperation:"sec:GenerateKeyOperation",KmsOperation:"sec:KmsOperation",RevokeKeyOperation:"sec:RevokeKeyOperation",RsaSignature2018:"sec:RsaSignature2018",RsaVerificationKey2018:"sec:RsaVerificationKey2018",Sha256HmacKey2019:"sec:Sha256HmacKey2019",SignOperation:"sec:SignOperation",UnwrapKeyOperation:"sec:UnwrapKeyOperation",VerifyOperation:"sec:VerifyOperation",WrapKeyOperation:"sec:WrapKeyOperation",X25519KeyAgreementKey2019:"sec:X25519KeyAgreementKey2019",allowedAction:"sec:allowedAction",assertionMethod:{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},authentication:{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"},capability:{"@id":"sec:capability","@type":"@id"},capabilityAction:"sec:capabilityAction",capabilityChain:{"@id":"sec:capabilityChain","@type":"@id","@container":"@list"},capabilityDelegation:{"@id":"sec:capabilityDelegationMethod","@type":"@id","@container":"@set"},capabilityInvocation:{"@id":"sec:capabilityInvocationMethod","@type":"@id","@container":"@set"},caveat:{"@id":"sec:caveat","@type":"@id","@container":"@set"},challenge:"sec:challenge",ciphertext:"sec:ciphertext",controller:{"@id":"sec:controller","@type":"@id"},delegator:{"@id":"sec:delegator","@type":"@id"},equihashParameterK:{"@id":"sec:equihashParameterK","@type":"xsd:integer"},equihashParameterN:{"@id":"sec:equihashParameterN","@type":"xsd:integer"},invocationTarget:{"@id":"sec:invocationTarget","@type":"@id"},invoker:{"@id":"sec:invoker","@type":"@id"},jws:"sec:jws",keyAgreement:{"@id":"sec:keyAgreementMethod","@type":"@id","@container":"@set"},kmsModule:{"@id":"sec:kmsModule"},parentCapability:{"@id":"sec:parentCapability","@type":"@id"},plaintext:"sec:plaintext",proof:{"@id":"sec:proof","@type":"@id","@container":"@graph"},proofPurpose:{"@id":"sec:proofPurpose","@type":"@vocab"},proofValue:"sec:proofValue",referenceId:"sec:referenceId",unwrappedKey:"sec:unwrappedKey",verificationMethod:{"@id":"sec:verificationMethod","@type":"@id"},verifyData:"sec:verifyData",wrappedKey:"sec:wrappedKey"}]};},function(e,t,i){/*! + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */e.exports={SECURITY_CONTEXT_V1_URL:"https://w3id.org/security/v1",SECURITY_CONTEXT_V2_URL:"https://w3id.org/security/v2",CONTEXT_URL:"https://w3id.org/security/v2"};}])); +}); + +var context$1 = unwrapExports(context); +var context_1 = context.contexts; +var context_2 = context.constants; +var context_3 = context.CONTEXT; +var context_4 = context.CONTEXT_URL; +var context_5 = context.SECURITY_CONTEXT_V1_URL; +var context_6 = context.SECURITY_CONTEXT_V2_URL; + + + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/vc-bitstring-status-list-context/js/context.js" +/*!************************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/vc-bitstring-status-list-context/js/context.js ***! + \************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/*! + * Copyright (c) 2024 Digital Bazaar, Inc. All rights reserved. + */ +// Use JSON style for context +/* eslint quotes: ['error', 'double'] */ +/* eslint quote-props: ['error', 'always'] */ +/* eslint-disable max-len */ + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "BitstringStatusListCredential": "https://www.w3.org/ns/credentials/status#BitstringStatusListCredential", + + "BitstringStatusList": { + "@id": "https://www.w3.org/ns/credentials/status#BitstringStatusList", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "encodedList": { + "@id": "https://www.w3.org/ns/credentials/status#encodedList", + "@type": "https://w3id.org/security#multibase" + }, + "statusPurpose": + "https://www.w3.org/ns/credentials/status#statusPurpose", + "ttl": "https://www.w3.org/ns/credentials/status#ttl" + } + }, + + "BitstringStatusListEntry": { + "@id": + "https://www.w3.org/ns/credentials/status#BitstringStatusListEntry", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "statusListCredential": { + "@id": + "https://www.w3.org/ns/credentials/status#statusListCredential", + "@type": "@id" + }, + "statusListIndex": + "https://www.w3.org/ns/credentials/status#statusListIndex", + "statusPurpose": + "https://www.w3.org/ns/credentials/status#statusPurpose", + "statusMessage": { + "@id": "https://www.w3.org/ns/credentials/status#statusMessage", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "message": "https://www.w3.org/ns/credentials/status#message", + "status": "https://www.w3.org/ns/credentials/status#status" + } + }, + "statusReference": { + "@id": "https://www.w3.org/ns/credentials/status#statusReference", + "@type": "@id" + }, + "statusSize": { + "@id": "https://www.w3.org/ns/credentials/status#statusSize", + "@type": "https://www.w3.org/2001/XMLSchema#integer" + } + } + } + } +}); + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/vc-bitstring-status-list-context/js/index.js" +/*!**********************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/vc-bitstring-status-list-context/js/index.js ***! + \**********************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CONTEXT: () => (/* binding */ CONTEXT), +/* harmony export */ CONTEXT_URL: () => (/* binding */ CONTEXT_URL), +/* harmony export */ appContextMap: () => (/* binding */ appContextMap), +/* harmony export */ constants: () => (/* binding */ constants), +/* harmony export */ contexts: () => (/* binding */ contexts) +/* harmony export */ }); +/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./context.js */ "./node_modules/@digitalbazaar/vc-bitstring-status-list-context/js/context.js"); +/*! + * Copyright (c) 2024 Digital Bazaar, Inc. All rights reserved. + */ + + +const constants = { + // default context output filename under ./contexts/ + CONTEXT_FILENAME: 'vc-bitstring-status-list-v1.jsonld', + // default context well known URL id + CONTEXT_URL: 'https://www.w3.org/ns/credentials/status/v1', + // default context CBOR-LD codec id + // value between 0x0 and 0x7FFF for globally registered term codec values + // or >= 0x8000 for app-specific local terms + CBORLD_VALUE: 0x0 +}; + +// map of all context URLs to context data +const contexts = new Map(); +contexts.set(constants.CONTEXT_URL, _context_js__WEBPACK_IMPORTED_MODULE_0__["default"]); + +// map of all context URLs to CBOR-LD codec ids +const appContextMap = new Map(); +appContextMap.set(constants.CONTEXT_URL, constants.CBORLD_VALUE); + +const CONTEXT = _context_js__WEBPACK_IMPORTED_MODULE_0__["default"]; +const CONTEXT_URL = constants.CONTEXT_URL; + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/vc-bitstring-status-list/lib/BitstringStatusList.js" +/*!*****************************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/vc-bitstring-status-list/lib/BitstringStatusList.js ***! + \*****************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ BitstringStatusList: () => (/* binding */ BitstringStatusList) +/* harmony export */ }); +/* harmony import */ var _digitalbazaar_bitstring__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @digitalbazaar/bitstring */ "./node_modules/@digitalbazaar/bitstring/lib/index.js"); +/*! + * Copyright (c) 2024 Digital Bazaar, Inc. All rights reserved. + */ + + +class BitstringStatusList { + constructor({length, buffer} = {}) { + this.bitstring = new _digitalbazaar_bitstring__WEBPACK_IMPORTED_MODULE_0__.Bitstring({length, buffer}); + this.length = this.bitstring.length; + } + + setStatus(index, status) { + if(typeof status !== 'boolean') { + throw new TypeError('"status" must be a boolean.'); + } + return this.bitstring.set(index, status); + } + + getStatus(index) { + return this.bitstring.get(index); + } + + async encode() { + return 'u' + await this.bitstring.encodeBits(); + } + + static async decode({encodedList}) { + try { + if(encodedList[0] !== 'u') { + throw '"encodedList" must start with the character "u".'; + } + const buffer = await _digitalbazaar_bitstring__WEBPACK_IMPORTED_MODULE_0__.Bitstring.decodeBits({ + encoded: encodedList.slice(1) + }); + return new BitstringStatusList({buffer}); + } catch(e) { + if(e instanceof Error) { + throw e; + } + throw new Error( + `Could not decode encoded status list; reason: ${e}`); + } + } +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/vc-bitstring-status-list/lib/index.js" +/*!***************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/vc-bitstring-status-list/lib/index.js ***! + \***************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ BitstringStatusList: () => (/* reexport safe */ _BitstringStatusList_js__WEBPACK_IMPORTED_MODULE_0__.BitstringStatusList), +/* harmony export */ VC_BSL_VC_V1_CONTEXT: () => (/* binding */ VC_BSL_VC_V1_CONTEXT), +/* harmony export */ VC_BSL_VC_V2_CONTEXT: () => (/* binding */ VC_BSL_VC_V2_CONTEXT), +/* harmony export */ assertBitstringStatusListContext: () => (/* binding */ assertBitstringStatusListContext), +/* harmony export */ checkStatus: () => (/* binding */ checkStatus), +/* harmony export */ createCredential: () => (/* binding */ createCredential), +/* harmony export */ createList: () => (/* binding */ createList), +/* harmony export */ decodeList: () => (/* binding */ decodeList), +/* harmony export */ getCredentialStatus: () => (/* binding */ getCredentialStatus), +/* harmony export */ statusTypeMatches: () => (/* binding */ statusTypeMatches) +/* harmony export */ }); +/* harmony import */ var _BitstringStatusList_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitstringStatusList.js */ "./node_modules/@digitalbazaar/vc-bitstring-status-list/lib/BitstringStatusList.js"); +/* harmony import */ var _digitalbazaar_vc_bitstring_status_list_context__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @digitalbazaar/vc-bitstring-status-list-context */ "./node_modules/@digitalbazaar/vc-bitstring-status-list-context/js/index.js"); +/* harmony import */ var _digitalbazaar_credentials_context__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @digitalbazaar/credentials-context */ "./node_modules/@digitalbazaar/credentials-context/lib/index.js"); +/* harmony import */ var _digitalbazaar_vc__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @digitalbazaar/vc */ "./node_modules/@digitalbazaar/vc/lib/index.js"); +/*! + * Copyright (c) 2022-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + + + +const VC_V1_CONTEXT_URL = _digitalbazaar_credentials_context__WEBPACK_IMPORTED_MODULE_2__.named.get('v1').id; +const VC_V2_CONTEXT_URL = _digitalbazaar_credentials_context__WEBPACK_IMPORTED_MODULE_2__.named.get('v2').id; + +const VC_BSL_VC_V1_CONTEXT = [VC_V1_CONTEXT_URL, _digitalbazaar_vc_bitstring_status_list_context__WEBPACK_IMPORTED_MODULE_1__.CONTEXT_URL]; +const VC_BSL_VC_V2_CONTEXT = [VC_V2_CONTEXT_URL]; + + + +async function createList({length}) { + return new _BitstringStatusList_js__WEBPACK_IMPORTED_MODULE_0__.BitstringStatusList({length}); +} + +async function decodeList({encodedList}) { + return _BitstringStatusList_js__WEBPACK_IMPORTED_MODULE_0__.BitstringStatusList.decode({encodedList}); +} + +/** + * Creates a BitstringStatusList Credential. + * + * @param {object} options - Options to use. + * @param {string} options.id - The id for BitstringStatusList Credential. + * @param {BitstringStatusList} options.list - An instance of + * BitstringStatusList. + * @param {string} options.statusPurpose - The purpose of the status entry. + * @param {Array.string} options.context - The context(s) to use for the + * credential. + * + * @returns {object} The resulting `BitstringStatusList Credential`. + */ +async function createCredential({id, list, statusPurpose, context}) { + if(!(id && typeof id === 'string')) { + throw new TypeError('"id" is required.'); + } + if(!(list && typeof list.encode === 'function')) { + throw new TypeError('"list" is required.'); + } + if(!(statusPurpose && typeof statusPurpose === 'string')) { + throw new TypeError('"statusPurpose" is required.'); + } + if(!context) { + context = [...VC_BSL_VC_V2_CONTEXT]; + } else if( + !(context.every((e, i) => e === VC_BSL_VC_V1_CONTEXT[i]) || + context.every((e, i) => e === VC_BSL_VC_V2_CONTEXT[i]))) { + throw new TypeError( + `"context" must be either "${VC_BSL_VC_V1_CONTEXT}" ` + + `or "${VC_BSL_VC_V2_CONTEXT}".`); + } + const encodedList = await list.encode(); + return { + '@context': context, + id, + type: ['VerifiableCredential', 'BitstringStatusListCredential'], + credentialSubject: { + id: `${id}#list`, + type: 'BitstringStatusList', + encodedList, + statusPurpose + } + }; +} + +async function checkStatus({ + credential, + documentLoader, + suite, + verifyBitstringStatusListCredential = true, + verifyMatchingIssuers = true +} = {}) { + let result; + try { + result = await _checkStatuses({ + credential, + documentLoader, + suite, + verifyBitstringStatusListCredential, + verifyMatchingIssuers, + }); + } catch(error) { + result = { + verified: false, + error, + }; + } + return result; +} + +function statusTypeMatches({credential} = {}) { + _isObject({credential}); + // check for expected contexts + const {'@context': contexts} = credential; + if(!Array.isArray(contexts)) { + throw new TypeError('"@context" must be an array.'); + } + const isVC2 = contexts[0] === VC_V2_CONTEXT_URL; + if(!(isVC2 || contexts[0] === VC_V1_CONTEXT_URL)) { + throw new TypeError( + `The first "@context" value must be "${VC_V1_CONTEXT_URL}" or ` + + `"${VC_V2_CONTEXT_URL}".`); + } + const {credentialStatus} = credential; + if(!credentialStatus) { + // no status; no match + return false; + } + if(typeof credentialStatus !== 'object') { + // bad status + throw new Error('"credentialStatus" is invalid.'); + } + if(!(isVC2 || contexts.includes(_digitalbazaar_vc_bitstring_status_list_context__WEBPACK_IMPORTED_MODULE_1__.CONTEXT_URL))) { + // required context not present, no match + return false; + } + const credentialStatuses = _getStatuses({credential}); + return credentialStatuses.length > 0; +} + +function assertBitstringStatusListContext({credential} = {}) { + _isObject({credential}); + // check for expected contexts + const {'@context': contexts} = credential; + if(!Array.isArray(contexts)) { + throw new TypeError('"@context" must be an array.'); + } + if(contexts[0] === VC_V2_CONTEXT_URL) { + return; + } + if(contexts[0] !== VC_V1_CONTEXT_URL) { + throw new TypeError( + `The first "@context" value must be "${VC_V1_CONTEXT_URL}".`); + } + if(!contexts.includes(_digitalbazaar_vc_bitstring_status_list_context__WEBPACK_IMPORTED_MODULE_1__.CONTEXT_URL)) { + throw new TypeError(`"@context" must include "${_digitalbazaar_vc_bitstring_status_list_context__WEBPACK_IMPORTED_MODULE_1__.CONTEXT_URL}".`); + } +} + +/** + * Gets the `credentialStatus` of a credential based on its status purpose + * (`statusPurpose`). + * + * @param {object} options - Options to use. + * @param {object} options.credential - A VC. + * @param {'revocation'|'suspension'} options.statusPurpose - A + * `statusPurpose`. + * + * @throws If the `credentialStatus` is invalid or missing. + * + * @returns {object} The resulting `credentialStatus`. + */ +function getCredentialStatus({credential, statusPurpose} = {}) { + _isObject({credential}); + assertBitstringStatusListContext({credential}); + if(!(statusPurpose && typeof statusPurpose === 'string')) { + throw new TypeError('"statusPurpose" must be a string.'); + } + // get and validate status + if(!(credential.credentialStatus && + typeof credential.credentialStatus === 'object')) { + throw new Error('"credentialStatus" is missing or invalid.'); + } + const credentialStatuses = _getStatuses({credential}); + if(credentialStatuses.length === 0) { + throw new Error( + '"credentialStatus" with type "BitstringStatusListEntry" ' + + `and status purpose "${statusPurpose}" not found.`); + } + const result = credentialStatuses.filter( + credentialStatus => _validateStatus({credentialStatus})).find( + // check for matching `statusPurpose` + cs => cs.statusPurpose === statusPurpose); + if(!result) { + throw new Error( + '"credentialStatus" with type "BitstringStatusListEntry" ' + + `and status purpose "${statusPurpose}" not found.`); + } + return result; +} + +async function _checkStatus({ + credential, + credentialStatus, + verifyBitstringStatusListCredential, + verifyMatchingIssuers, + suite, + documentLoader +}) { + // get SL position + const {statusListIndex} = credentialStatus; + const index = parseInt(statusListIndex, 10); + // retrieve SL VC + let slCredential; + try { + ({document: slCredential} = await documentLoader( + credentialStatus.statusListCredential)); + } catch(e) { + const err = new Error( + 'Could not load "BitstringStatusListCredential"; ' + + `reason: ${e.message}`); + err.cause = e; + throw err; + } + const {statusPurpose: credentialStatusPurpose} = credentialStatus; + const {statusPurpose: slCredentialStatusPurpose} = + slCredential.credentialSubject; + if(slCredentialStatusPurpose !== credentialStatusPurpose) { + throw new Error( + `The status purpose "${slCredentialStatusPurpose}" of the status ` + + `list credential does not match the status purpose ` + + `"${credentialStatusPurpose}" in the credential.`); + } + // verify SL VC + if(verifyBitstringStatusListCredential) { + const verifyResult = await (0,_digitalbazaar_vc__WEBPACK_IMPORTED_MODULE_3__.verifyCredential)({ + credential: slCredential, + suite, + documentLoader + }); + if(!verifyResult.verified) { + const {error: e} = verifyResult; + let msg = '"BitstringStatusListCredential" not verified'; + if(e) { + msg += `; reason: ${e.message}`; + } else { + msg += '.'; + } + const err = new Error(msg); + if(e) { + err.cause = verifyResult.error; + } + throw err; + } + } + + // ensure that the issuer of the verifiable credential matches + // the issuer of the statusListCredential + if(verifyMatchingIssuers) { + // covers both the URI and object cases + const credentialIssuer = + typeof credential.issuer === 'object' ? + credential.issuer.id : credential.issuer; + const statusListCredentialIssuer = + typeof slCredential.issuer === 'object' ? + slCredential.issuer.id : slCredential.issuer; + + if(!(credentialIssuer && statusListCredentialIssuer) || + (credentialIssuer !== statusListCredentialIssuer)) { + throw new Error( + 'Issuers of the status list credential and verifiable ' + + 'credential do not match.'); + } + } + if(!slCredential.type.includes('BitstringStatusListCredential')) { + throw new Error( + 'Status list credential type must include ' + + '"BitstringStatusListCredential".'); + } + + // get JSON BitstringStatusList + const {credentialSubject: sl} = slCredential; + + if(sl.type !== 'BitstringStatusList') { + throw new Error('Status list type must be "BitstringStatusList".'); + } + + // decode list from SL VC + const {encodedList} = sl; + const list = await decodeList({encodedList}); + + // return the status value at index + const status = list.getStatus(index); + return {verified: true, credentialStatus, status}; +} + +async function _checkStatuses({ + credential, + documentLoader, + suite, + verifyBitstringStatusListCredential, + verifyMatchingIssuers +}) { + _isObject({credential}); + if(typeof documentLoader !== 'function') { + throw new TypeError('"documentLoader" must be a function.'); + } + if(verifyBitstringStatusListCredential && !(suite && ( + isArrayOfObjects(suite) || + (!Array.isArray(suite) && typeof suite === 'object')))) { + throw new TypeError('"suite" must be an object or an array of objects.'); + } + const credentialStatuses = _getStatuses({credential}); + if(credentialStatuses.length === 0) { + throw new Error( + '"credentialStatus.type" must be "BitstringStatusListEntry".'); + } + credentialStatuses.forEach( + credentialStatus => _validateStatus({credentialStatus})); + const results = await Promise.all(credentialStatuses.map( + credentialStatus => _checkStatus({ + credential, + credentialStatus, + suite, + documentLoader, + verifyBitstringStatusListCredential, + verifyMatchingIssuers + }))); + const verified = results.every( + ({verified = false} = {}) => verified === true); + return {verified, results}; +} + +/** + * Takes in a credentialStatus an ensures it meets the + * normative statements from the Bitstring Status List spec. + * + * @see https://www.w3.org/TR/vc-bitstring-status-list/ + * + * @param {object} options - Options to use. + * @param {object} options.credentialStatus - A credentialStatus. + * + * @throws - An error if the credentialStatus is non-normative. + * + * @returns {object} A credentialStatus. + */ +function _validateStatus({credentialStatus}) { + if(credentialStatus.type !== 'BitstringStatusListEntry') { + throw new Error( + '"credentialStatus.type" must be "BitstringStatusListEntry".'); + } + if(typeof credentialStatus.statusPurpose !== 'string') { + throw new TypeError( + '"credentialStatus.statusPurpose" must be a string.'); + } + if(credentialStatus.id && typeof credentialStatus.id !== 'string') { + throw new TypeError('"credentialStatus.id" must be a string.'); + } + if(typeof credentialStatus.statusListCredential !== 'string') { + throw new TypeError( + '"credentialStatus.statusListCredential" must be a string.'); + } + const index = parseInt(credentialStatus.statusListIndex, 10); + if(isNaN(index)) { + throw new TypeError('"statusListIndex" must be an integer.'); + } + if(credentialStatus.id === credentialStatus.statusListCredential) { + throw new Error('"credentialStatus.id" must not be ' + + '"credentialStatus.statusListCredential".'); + } + return credentialStatus; +} + +/** + * Checks if a credential is not falsey and an object. + * + * @param {object} options - Options to use. + * @param {object} [options.credential] - A potential VC. + * + * @throws - Throws if the credential is falsey or not an object. + * + * @returns {undefined} + */ +function _isObject({credential}) { + if(!(credential && typeof credential === 'object')) { + throw new TypeError('"credential" must be an object.'); + } +} + +/** + * Gets the statuses of a credential. + * + * @param {object} options - Options to use. + * @param {object} options.credential - A VC with a credentialStatus. + * + * @returns {Array} An array of statuses with type + * "BitstringStatusListEntry" or an empty array if there are no matching + * types. + */ +function _getStatuses({credential}) { + const {credentialStatus} = credential; + if(Array.isArray(credentialStatus)) { + return credentialStatus.filter( + cs => cs.type === 'BitstringStatusListEntry'); + } + if(credentialStatus && credentialStatus.type === 'BitstringStatusListEntry') { + return [credentialStatus]; + } + return []; +} + +function isArrayOfObjects(x) { + return Array.isArray(x) && x.length > 0 && + x.every(x => x && typeof x === 'object'); +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/vc-status-list-context/dist/context.esm.js" +/*!********************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/vc-status-list-context/dist/context.esm.js ***! + \********************************************************************************/ +(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CONTEXT_URL_V1: () => (/* binding */ context_4), +/* harmony export */ CONTEXT_V1: () => (/* binding */ context_3), +/* harmony export */ appContextMap: () => (/* binding */ context_5), +/* harmony export */ constants: () => (/* binding */ context_2), +/* harmony export */ contexts: () => (/* binding */ context_1), +/* harmony export */ "default": () => (/* binding */ context$1) +/* harmony export */ }); +function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var context = createCommonjsModule(function (module, exports) { +/*! For license information please see context.js.LICENSE.txt */ +(()=>{var t={380:t=>{t.exports={CONTEXT_FILENAME:"vc-status-list-v1.jsonld",CONTEXT_URL_V1:"https://w3id.org/vc/status-list/2021/v1",CBORLD_VALUE:32};},592:t=>{t.exports={"@context":{"@protected":!0,StatusList2021Credential:{"@id":"https://w3id.org/vc/status-list#StatusList2021Credential","@context":{"@protected":!0,id:"@id",type:"@type",description:"http://schema.org/description",name:"http://schema.org/name"}},StatusList2021:{"@id":"https://w3id.org/vc/status-list#StatusList2021","@context":{"@protected":!0,id:"@id",type:"@type",statusPurpose:"https://w3id.org/vc/status-list#statusPurpose",encodedList:"https://w3id.org/vc/status-list#encodedList"}},StatusList2021Entry:{"@id":"https://w3id.org/vc/status-list#StatusList2021Entry","@context":{"@protected":!0,id:"@id",type:"@type",statusPurpose:"https://w3id.org/vc/status-list#statusPurpose",statusListIndex:"https://w3id.org/vc/status-list#statusListIndex",statusListCredential:{"@id":"https://w3id.org/vc/status-list#statusListCredential","@type":"@id"}}}}};},588:(t,s,e)=>{const i=e(592),o=e(380),{CONTEXT_URL_V1:r,CBORLD_VALUE:a}=o,p=new Map;p.set(r,i);const d=new Map;d.set(r,a),t.exports={constants:o,contexts:p,appContextMap:d,CONTEXT_URL_V1:r,CONTEXT_V1:i};}},s={},e=function e(i){var o=s[i];if(void 0!==o)return o.exports;var r=s[i]={exports:{}};return t[i](r,r.exports,e),r.exports}(588),i=exports;for(var o in e)i[o]=e[o];e.__esModule&&Object.defineProperty(i,"__esModule",{value:!0});})(); +}); + +var context$1 = unwrapExports(context); +var context_1 = context.contexts; +var context_2 = context.constants; +var context_3 = context.CONTEXT_V1; +var context_4 = context.CONTEXT_URL_V1; +var context_5 = context.appContextMap; + + + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/vc/lib/CredentialIssuancePurpose.js" +/*!*************************************************************************!*\ + !*** ./node_modules/@digitalbazaar/vc/lib/CredentialIssuancePurpose.js ***! + \*************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CredentialIssuancePurpose: () => (/* binding */ CredentialIssuancePurpose) +/* harmony export */ }); +/* harmony import */ var jsonld_signatures__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jsonld-signatures */ "./node_modules/jsonld-signatures/lib/jsonld-signatures.js"); +/* harmony import */ var jsonld__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! jsonld */ "./node_modules/jsonld/lib/jsonld.js"); +/*! + * Copyright (c) 2019-2023 Digital Bazaar, Inc. All rights reserved. + */ + + + +const {purposes: {AssertionProofPurpose}} = jsonld_signatures__WEBPACK_IMPORTED_MODULE_0__; + +/** + * Creates a proof purpose that will validate whether or not the verification + * method in a proof was authorized by its declared controller for the + * proof's purpose. + */ +class CredentialIssuancePurpose extends AssertionProofPurpose { + /** + * @param {object} options - The options to use. + * @param {object} [options.controller] - The description of the controller, + * if it is not to be dereferenced via a `documentLoader`. + * @param {string|Date|number} [options.date] - The expected date for + * the creation of the proof. + * @param {number} [options.maxTimestampDelta=Infinity] - A maximum number + * of seconds that the date on the signature can deviate from. + */ + constructor({controller, date, maxTimestampDelta} = {}) { + super({controller, date, maxTimestampDelta}); + } + + /** + * Validates the purpose of a proof. This method is called during + * proof verification, after the proof value has been checked against the + * given verification method (in the case of a digital signature, the + * signature has been cryptographically verified against the public key). + * + * @param {object} proof - The proof to validate. + * @param {object} options - The options to use. + * @param {object} options.document - The document whose signature is + * being verified. + * @param {object} options.suite - Signature suite used in + * the proof. + * @param {string} options.verificationMethod - Key id URL to the paired + * public key. + * @param {object} [options.documentLoader] - A document loader. + * + * @throws {Error} If verification method not authorized by controller. + * @throws {Error} If proof's created timestamp is out of range. + * + * @returns {Promise<{valid: boolean, error: Error}>} Resolves on completion. + */ + async validate(proof, { + document, suite, verificationMethod, documentLoader + }) { + try { + const result = await super.validate(proof, { + document, suite, verificationMethod, documentLoader + }); + + if(!result.valid) { + throw result.error; + } + + const issuer = jsonld__WEBPACK_IMPORTED_MODULE_1__.getValues(document, 'issuer'); + + if(!issuer || issuer.length === 0) { + throw new Error('Credential issuer is required.'); + } + + const issuerId = typeof issuer[0] === 'string' ? issuer[0] : issuer[0].id; + + if(result.controller.id !== issuerId) { + throw new Error( + 'Credential issuer must match the verification method controller.'); + } + + return {valid: true}; + } catch(error) { + return {valid: false, error}; + } + } +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/vc/lib/contexts/index.js" +/*!**************************************************************!*\ + !*** ./node_modules/@digitalbazaar/vc/lib/contexts/index.js ***! + \**************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ contexts: () => (/* binding */ contexts) +/* harmony export */ }); +/* harmony import */ var _digitalbazaar_credentials_context__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @digitalbazaar/credentials-context */ "./node_modules/@digitalbazaar/credentials-context/lib/index.js"); +/*! + * Copyright (c) 2019-2024 Digital Bazaar, Inc. All rights reserved. + */ + + +const contexts = new Map([ + ..._digitalbazaar_credentials_context__WEBPACK_IMPORTED_MODULE_0__.contexts +]); + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/vc/lib/documentLoader.js" +/*!**************************************************************!*\ + !*** ./node_modules/@digitalbazaar/vc/lib/documentLoader.js ***! + \**************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ documentLoader: () => (/* binding */ documentLoader) +/* harmony export */ }); +/* harmony import */ var _contexts_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./contexts/index.js */ "./node_modules/@digitalbazaar/vc/lib/contexts/index.js"); +/*! + * Copyright (c) 2019-2023 Digital Bazaar, Inc. All rights reserved. + */ +// load locally embedded contexts + + +async function documentLoader(url) { + const context = _contexts_index_js__WEBPACK_IMPORTED_MODULE_0__.contexts.get(url); + if(context !== undefined) { + return { + contextUrl: null, + documentUrl: url, + document: context + }; + } + throw new Error(`Document loader unable to load URL "${url}".`); +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/vc/lib/helpers.js" +/*!*******************************************************!*\ + !*** ./node_modules/@digitalbazaar/vc/lib/helpers.js ***! + \*******************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ assertCredentialContext: () => (/* binding */ assertCredentialContext), +/* harmony export */ assertDateString: () => (/* binding */ assertDateString), +/* harmony export */ checkContextVersion: () => (/* binding */ checkContextVersion), +/* harmony export */ compareTime: () => (/* binding */ compareTime), +/* harmony export */ dateRegex: () => (/* binding */ dateRegex), +/* harmony export */ getContextForVersion: () => (/* binding */ getContextForVersion) +/* harmony export */ }); +/* harmony import */ var _digitalbazaar_credentials_context__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @digitalbazaar/credentials-context */ "./node_modules/@digitalbazaar/credentials-context/lib/index.js"); +/*! + * Copyright (c) 2023 Digital Bazaar, Inc. All rights reserved. + */ + + +// Z and T must be uppercase +// xml schema date time RegExp +// @see https://www.w3.org/TR/xmlschema11-2/#dateTime +const dateRegex = new RegExp( + '-?([1-9][0-9]{3,}|0[0-9]{3})' + + '-(0[1-9]|1[0-2])' + + '-(0[1-9]|[12][0-9]|3[01])' + + 'T(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?|(24:00:00(\.0+)?))' + + '(Z|(\\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?'); + +const CREDENTIALS_CONTEXT_V1_URL = _digitalbazaar_credentials_context__WEBPACK_IMPORTED_MODULE_0__.named.get('v1').id; +const CREDENTIALS_CONTEXT_V2_URL = _digitalbazaar_credentials_context__WEBPACK_IMPORTED_MODULE_0__.named.get('v2').id; + +// mappings between credentials contexts and version numbers +const credentialsContextUrlToVersion = new Map([ + [CREDENTIALS_CONTEXT_V1_URL, 1.0], + [CREDENTIALS_CONTEXT_V2_URL, 2.0] +]); +const credentialsVersionToContextUrl = new Map([ + [1.0, CREDENTIALS_CONTEXT_V1_URL], + [2.0, CREDENTIALS_CONTEXT_V2_URL] +]); + +/** + * Asserts that a context array's first item is a credentials context. + * + * @param {object} options - Options. + * @param {Array} options.context - An array of contexts. + * + * @throws {Error} - Throws if the first context + * is not a credentials context. + * + * @returns {undefined} + */ +function assertCredentialContext({context}) { + // ensure first context is credentials context url + if(!credentialsContextUrlToVersion.has(context[0])) { + // throw if the first context is not a credentials context + throw new Error( + `"${CREDENTIALS_CONTEXT_V1_URL}" or "${CREDENTIALS_CONTEXT_V2_URL}"` + + ' needs to be first in the list of contexts.'); + } +} + +/** + * Throws if a Date is not in the correct format. + * + * @param {object} options - Options. + * @param {object} options.credential - A VC. + * @param {string} options.prop - A prop in the object. + * + * @throws {Error} Throws if the date is not a proper date string. + * @returns {undefined} + */ +function assertDateString({credential, prop}) { + const value = credential[prop]; + if(!dateRegex.test(value)) { + throw new Error(`"${prop}" must be a valid date: ${value}`); + } +} + +/** + * Turns the first context in a VC into a numbered version. + * + * @param {object} options - Options. + * @param {object} options.credential - A VC. + * + * @returns {number} A number representing the version. + */ +function getContextVersion({credential} = {}) { + const firstContext = credential?.['@context']?.[0]; + return credentialsContextUrlToVersion.get(firstContext); +} + +/** + * Turns the first context in a VC into a numbered version. + * + * @param {object} options - Options. + * @param {number} options.version - A credentials context version. + * + * @returns {number} A number representing the version. + */ +function getContextForVersion({version}) { + return credentialsVersionToContextUrl.get(version); +} + +/** + * Checks if a VC is using a specific context version. + * + * @param {object} options - Options. + * @param {object} options.credential - A VC. + * @param {number} options.version - A VC Context version + * + * @returns {boolean} If the first context matches the version. + */ +function checkContextVersion({credential, version}) { + return getContextVersion({credential}) === version; +} + +/** + * Compares two times with consideration of max clock skew + * + * @param {object} options - Options. + * @param {number} options.t1 - time 1 + * @param {number} options.t2 - time 2 + * @param {number} options.maxClockSkew - number of seconds + * @returns {number} - A number greater or less than zero + */ +function compareTime({t1, t2, maxClockSkew}) { + // `maxClockSkew` is in seconds, so transform to milliseconds + if(Math.abs(t1 - t2) < (maxClockSkew * 1000)) { + // times are equal within the max clock skew + return 0; + } + return t1 < t2 ? -1 : 1; +} + + +/***/ }, + +/***/ "./node_modules/@digitalbazaar/vc/lib/index.js" +/*!*****************************************************!*\ + !*** ./node_modules/@digitalbazaar/vc/lib/index.js ***! + \*****************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CredentialIssuancePurpose: () => (/* reexport safe */ _CredentialIssuancePurpose_js__WEBPACK_IMPORTED_MODULE_2__.CredentialIssuancePurpose), +/* harmony export */ _checkCredential: () => (/* binding */ _checkCredential), +/* harmony export */ _checkPresentation: () => (/* binding */ _checkPresentation), +/* harmony export */ createPresentation: () => (/* binding */ createPresentation), +/* harmony export */ dateRegex: () => (/* reexport safe */ _helpers_js__WEBPACK_IMPORTED_MODULE_0__.dateRegex), +/* harmony export */ defaultDocumentLoader: () => (/* binding */ defaultDocumentLoader), +/* harmony export */ derive: () => (/* binding */ derive), +/* harmony export */ issue: () => (/* binding */ issue), +/* harmony export */ signPresentation: () => (/* binding */ signPresentation), +/* harmony export */ verify: () => (/* binding */ verify), +/* harmony export */ verifyCredential: () => (/* binding */ verifyCredential) +/* harmony export */ }); +/* harmony import */ var _helpers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./helpers.js */ "./node_modules/@digitalbazaar/vc/lib/helpers.js"); +/* harmony import */ var _documentLoader_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./documentLoader.js */ "./node_modules/@digitalbazaar/vc/lib/documentLoader.js"); +/* harmony import */ var _CredentialIssuancePurpose_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CredentialIssuancePurpose.js */ "./node_modules/@digitalbazaar/vc/lib/CredentialIssuancePurpose.js"); +/* harmony import */ var jsonld_signatures__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! jsonld-signatures */ "./node_modules/jsonld-signatures/lib/jsonld-signatures.js"); +/* harmony import */ var jsonld__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! jsonld */ "./node_modules/jsonld/lib/jsonld.js"); +/** + * A JavaScript implementation of Verifiable Credentials. + * + * @author Dave Longley + * @author David I. Lehn + * + * @license BSD 3-Clause License + * Copyright (c) 2017-2025 Digital Bazaar, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of the Digital Bazaar, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + + + + + +const {AssertionProofPurpose, AuthenticationProofPurpose} = jsonld_signatures__WEBPACK_IMPORTED_MODULE_3__.purposes; + +const defaultDocumentLoader = jsonld_signatures__WEBPACK_IMPORTED_MODULE_3__.extendContextLoader(_documentLoader_js__WEBPACK_IMPORTED_MODULE_1__.documentLoader); + + +/** + * @typedef {object} LinkedDataSignature + */ + +/** + * @typedef {object} Presentation + */ + +/** + * @typedef {object} ProofPurpose + */ + +/** + * @typedef {object} VerifiableCredential + */ + +/** + * @typedef {object} VerifiablePresentation + */ + +/** + * @typedef {object} VerifyPresentationResult + * @property {boolean} verified - True if verified, false if not. + * @property {object} presentationResult + * @property {Array} credentialResults + * @property {object} error + */ + +/** + * @typedef {object} VerifyCredentialResult + * @property {boolean} verified - True if verified, false if not. + * @property {object} statusResult + * @property {Array} results + * @property {object} error + */ + +/** + * Issues a verifiable credential (by taking a base credential document, + * and adding a digital signature to it). + * + * @param {object} [options={}] - The options to use. + * + * @param {object} options.credential - Base credential document. + * @param {LinkedDataSignature} options.suite - Signature suite (with private + * key material or an API to use it), passed in to sign(). + * + * @param {ProofPurpose} [options.purpose] - A ProofPurpose. If not specified, + * a default purpose will be created. + * + * Other optional params passed to `sign()`: + * @param {object} [options.documentLoader] - A document loader. + * @param {string|Date} [options.now] - A string representing date time in + * ISO 8601 format or an instance of Date. Defaults to current date time. + * @param {number} [options.maxClockSkew=300] - A maximum number of seconds + * that clocks may be skewed when checking capability expiration date-times + * against `date` and when comparing invocation proof creation time against + * delegation proof creation time. + * + * @throws {Error} If missing required properties. + * + * @returns {Promise} Resolves on completion. + */ +async function issue({ + credential, suite, + purpose = new _CredentialIssuancePurpose_js__WEBPACK_IMPORTED_MODULE_2__.CredentialIssuancePurpose(), + documentLoader = defaultDocumentLoader, + now, + maxClockSkew = 300 +} = {}) { + // check to make sure the `suite` has required params + // Note: verificationMethod defaults to publicKey.id, in suite constructor + if(!suite) { + throw new TypeError('"suite" parameter is required for issuing.'); + } + if(!suite.verificationMethod) { + throw new TypeError('"suite.verificationMethod" property is required.'); + } + + if(!credential) { + throw new TypeError('"credential" parameter is required for issuing.'); + } + if((0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.checkContextVersion)({ + credential, + version: 1.0 + }) && !credential.issuanceDate) { + const now = (new Date()).toJSON(); + credential.issuanceDate = `${now.slice(0, now.length - 5)}Z`; + } + + // run common credential checks + _checkCredential({credential, now, mode: 'issue', maxClockSkew}); + + return jsonld_signatures__WEBPACK_IMPORTED_MODULE_3__.sign(credential, {purpose, documentLoader, suite}); +} + +/** + * Derives a proof from the given verifiable credential, resulting in a new + * verifiable credential. This method is usually used to generate selective + * disclosure and / or unlinkable proofs. + * + * @param {object} [options={}] - The options to use. + * + * @param {object} options.verifiableCredential - The verifiable credential + * containing a base proof to derive another proof from. + * @param {LinkedDataSignature} options.suite - Derived proof signature suite. + * + * Other optional params passed to `derive()`: + * @param {object} [options.documentLoader] - A document loader. + * + * @throws {Error} If missing required properties. + * + * @returns {Promise} Resolves on completion. + */ +async function derive({ + verifiableCredential, suite, + documentLoader = defaultDocumentLoader +} = {}) { + if(!verifiableCredential) { + throw new TypeError( + '"verifiableCredential" parameter is required for deriving.'); + } + if(!suite) { + throw new TypeError('"suite" parameter is required for deriving.'); + } + + // run common credential checks + _checkCredential({credential: verifiableCredential, mode: 'issue'}); + + return jsonld_signatures__WEBPACK_IMPORTED_MODULE_3__.derive(verifiableCredential, { + purpose: new AssertionProofPurpose(), + documentLoader, + suite + }); +} + +/** + * Verifies a verifiable presentation: + * - Checks that the presentation is well-formed + * - Checks the proofs (for example, checks digital signatures against the + * provided public keys). + * + * @param {object} [options={}] - The options to use. + * + * @param {VerifiablePresentation} options.presentation - Verifiable + * presentation, signed or unsigned, that may contain within it a + * verifiable credential. + * + * @param {LinkedDataSignature|LinkedDataSignature[]} options.suite - One or + * more signature suites that are supported by the caller's use case. This is + * an explicit design decision -- the calling code must specify which + * signature types (ed25519, RSA, etc) are allowed. + * Although it is expected that the secure resolution/fetching of the public + * key material (to verify against) is to be handled by the documentLoader, + * the suite param can optionally include the key directly. + * + * @param {boolean} [options.unsignedPresentation=false] - By default, this + * function assumes that a presentation is signed (and will return an error if + * a `proof` section is missing). Set this to `true` if you're using an + * unsigned presentation. + * + * Either pass in a proof purpose, + * @param {AuthenticationProofPurpose} [options.presentationPurpose] - Optional + * proof purpose (a default one will be created if not passed in). + * + * or a default purpose will be created with params: + * @param {string} [options.challenge] - Required if purpose is not passed in. + * @param {string} [options.controller] - A controller. + * @param {string} [options.domain] - A domain. + * + * @param {Function} [options.documentLoader] - A document loader. + * @param {Function} [options.checkStatus] - Optional function for checking + * credential status if `credentialStatus` is present on the credential. + * @param {string|Date} [options.now] - A string representing date time in + * ISO 8601 format or an instance of Date. Defaults to current date time. + * @param {number} [options.maxClockSkew=300] - A maximum number of seconds + * that clocks may be skewed when checking capability expiration date-times + * against `date` and when comparing invocation proof creation time against + * delegation proof creation time. + * @param {boolean} [options.includeCredentials=false] - Set to `true` to + * include the credentials in the credential results. + * + * @returns {Promise} The verification result. + */ +async function verify(options = {}) { + const {presentation} = options; + try { + if(!presentation) { + throw new TypeError( + 'A "presentation" property is required for verifying.'); + } + return _verifyPresentation(options); + } catch(error) { + return { + verified: false, + results: [{presentation, verified: false, error}], + error + }; + } +} + +/** + * Verifies a verifiable credential: + * - Checks that the credential is well-formed + * - Checks the proofs (for example, checks digital signatures against the + * provided public keys). + * + * @param {object} [options={}] - The options. + * + * @param {object} options.credential - Verifiable credential. + * + * @param {LinkedDataSignature|LinkedDataSignature[]} options.suite - One or + * more signature suites that are supported by the caller's use case. This is + * an explicit design decision -- the calling code must specify which + * signature types (ed25519, RSA, etc) are allowed. + * Although it is expected that the secure resolution/fetching of the public + * key material (to verify against) is to be handled by the documentLoader, + * the suite param can optionally include the key directly. + * + * @param {CredentialIssuancePurpose} [options.purpose] - Optional + * proof purpose (a default one will be created if not passed in). + * @param {Function} [options.documentLoader] - A document loader. + * @param {Function} [options.checkStatus] - Optional function for checking + * credential status if `credentialStatus` is present on the credential. + * @param {string|Date} [options.now] - A string representing date time in + * ISO 8601 format or an instance of Date. Defaults to current date time. + * @param {number} [options.maxClockSkew=300] - A maximum number of seconds + * that clocks may be skewed when checking capability expiration date-times + * against `date` and when comparing invocation proof creation time against + * delegation proof creation time. + * + * @returns {Promise} The verification result. + */ +async function verifyCredential(options = {}) { + const {credential} = options; + try { + if(!credential) { + throw new TypeError( + 'A "credential" property is required for verifying.'); + } + return await _verifyCredential(options); + } catch(error) { + return { + verified: false, + results: [{credential, verified: false, error}], + error + }; + } +} + +/** + * Verifies a verifiable credential. + * + * @private + * @param {object} [options={}] - The options. + * + * @param {object} options.credential - Verifiable credential. + * @param {LinkedDataSignature|LinkedDataSignature[]} options.suite - See the + * definition in the `verify()` docstring, for this param. + * @param {string|Date} [options.now] - A string representing date time in + * ISO 8601 format or an instance of Date. Defaults to current date time. + * @param {number} [options.maxClockSkew=300] - A maximum number of seconds + * that clocks may be skewed when checking capability expiration date-times + * against `date` and when comparing invocation proof creation time against + * delegation proof creation time. + * + * @throws {Error} If required parameters are missing (in `_checkCredential`). + * + * @param {CredentialIssuancePurpose} [options.purpose] - A purpose. + * @param {Function} [options.documentLoader] - A document loader. + * @param {Function} [options.checkStatus] - Optional function for checking + * credential status if `credentialStatus` is present on the credential. + * + * @returns {Promise} The verification result. + */ +async function _verifyCredential(options = {}) { + const {credential, checkStatus, now, maxClockSkew} = options; + + // run common credential checks + _checkCredential({credential, now, maxClockSkew}); + + // if credential status is provided, a `checkStatus` function must be given + if(credential.credentialStatus && typeof options.checkStatus !== 'function') { + throw new TypeError( + 'A "checkStatus" function must be given to verify credentials with ' + + '"credentialStatus".'); + } + + const documentLoader = options.documentLoader || defaultDocumentLoader; + + const {controller} = options; + const purpose = options.purpose || new _CredentialIssuancePurpose_js__WEBPACK_IMPORTED_MODULE_2__.CredentialIssuancePurpose({ + controller + }); + + const result = await jsonld_signatures__WEBPACK_IMPORTED_MODULE_3__.verify( + credential, {...options, purpose, documentLoader}); + + // if verification has already failed, skip status check + if(!result.verified) { + return result; + } + + if(credential.credentialStatus) { + result.statusResult = await checkStatus(options); + if(!result.statusResult.verified) { + result.verified = false; + } + } + return result; +} + +/** + * Creates an unsigned presentation from a given verifiable credential. + * + * @param {object} options - Options to use. + * @param {object|Array} [options.verifiableCredential] - One or more + * verifiable credential. + * @param {string} [options.id] - Optional VP id. + * @param {string} [options.holder] - Optional presentation holder url. + * @param {string|Date} [options.now] - A string representing date time in + * ISO 8601 format or an instance of Date. Defaults to current date time. + * @param {number} [options.maxClockSkew=300] - A maximum number of seconds + * that clocks may be skewed when checking capability expiration date-times + * against `date` and when comparing invocation proof creation time against + * delegation proof creation time. + * @param {number} [options.version = 2.0] - The VC context version to use. + * + * @throws {TypeError} If verifiableCredential param is missing. + * @throws {Error} If the credential (or the presentation params) are missing + * required properties. + * + * @returns {Presentation} The credential wrapped inside of a + * VerifiablePresentation. + */ +function createPresentation({ + verifiableCredential, id, holder, now, version = 2.0, maxClockSkew = 300 +} = {}) { + const initialContext = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.getContextForVersion)({version}); + const presentation = { + '@context': [initialContext], + type: ['VerifiablePresentation'] + }; + if(verifiableCredential) { + const credentials = [].concat(verifiableCredential); + // ensure all credentials are valid + for(const credential of credentials) { + _checkCredential({credential, now, maxClockSkew}); + } + presentation.verifiableCredential = credentials; + } + if(id) { + presentation.id = id; + } + if(holder) { + presentation.holder = holder; + } + + _checkPresentation(presentation); + + return presentation; +} + +/** + * Signs a given presentation. + * + * @param {object} [options={}] - Options to use. + * + * Required: + * @param {Presentation} options.presentation - A presentation. + * @param {LinkedDataSignature} options.suite - passed in to sign() + * + * Either pass in a ProofPurpose, or a default one will be created with params: + * @param {ProofPurpose} [options.purpose] - A ProofPurpose. If not specified, + * a default purpose will be created with the domain and challenge options. + * + * @param {string} [options.domain] - A domain. + * @param {string} options.challenge - A required challenge. + * + * @param {Function} [options.documentLoader] - A document loader. + * + * @returns {Promise<{VerifiablePresentation}>} A VerifiablePresentation with + * a proof. + */ +async function signPresentation(options = {}) { + const {presentation, domain, challenge} = options; + const purpose = options.purpose || new AuthenticationProofPurpose({ + domain, + challenge + }); + + const documentLoader = options.documentLoader || defaultDocumentLoader; + + return jsonld_signatures__WEBPACK_IMPORTED_MODULE_3__.sign(presentation, {...options, purpose, documentLoader}); +} + +/** + * Verifies that the VerifiablePresentation is well formed, and checks the + * proof signature if it's present. Also verifies all the VerifiableCredentials + * that are present in the presentation, if any. + * + * @param {object} [options={}] - The options. + * @param {VerifiablePresentation} options.presentation - A + * VerifiablePresentation. + * + * @param {LinkedDataSignature|LinkedDataSignature[]} options.suite - See the + * definition in the `verify()` docstring, for this param. + * + * @param {boolean} [options.unsignedPresentation=false] - By default, this + * function assumes that a presentation is signed (and will return an error if + * a `proof` section is missing). Set this to `true` if you're using an + * unsigned presentation. + * + * Either pass in a proof purpose, + * @param {AuthenticationProofPurpose} [options.presentationPurpose] - A + * ProofPurpose. If not specified, a default purpose will be created with + * the challenge, controller, and domain options. + * + * @param {string} [options.challenge] - A challenge. Required if purpose is + * not passed in. + * @param {string} [options.controller] - A controller. Required if purpose is + * not passed in. + * @param {string} [options.domain] - A domain. Required if purpose is not + * passed in. + * + * @param {Function} [options.documentLoader] - A document loader. + * @param {Function} [options.checkStatus] - Optional function for checking + * credential status if `credentialStatus` is present on the credential. + * @param {string|Date} [options.now] - A string representing date time in + * ISO 8601 format or an instance of Date. Defaults to current date time. + * @param {number} [options.maxClockSkew=300] - A maximum number of seconds + * that clocks may be skewed when checking capability expiration date-times + * against `date` and when comparing invocation proof creation time against + * delegation proof creation time. + * + * @throws {Error} If presentation is missing required params. + * + * @returns {Promise} The verification result. + */ +async function _verifyPresentation(options = {}) { + const {presentation, unsignedPresentation, includeCredentials} = options; + + _checkPresentation(presentation); + + const documentLoader = options.documentLoader || defaultDocumentLoader; + + // FIXME: verify presentation first, then each individual credential + // only if that proof is verified + + // if verifiableCredentials are present, verify them, individually + let credentialResults; + let verified = true; + const credentials = jsonld__WEBPACK_IMPORTED_MODULE_4__.getValues(presentation, 'verifiableCredential'); + if(credentials.length > 0) { + // verify every credential in `verifiableCredential` + credentialResults = await Promise.all(credentials.map(credential => { + return verifyCredential({...options, credential, documentLoader}); + })); + + for(const [i, credentialResult] of credentialResults.entries()) { + const credential = credentials[i]; + credentialResult.credentialId = credential.id; + if(includeCredentials) { + credentialResult.credential = credential; + } + } + + const allCredentialsVerified = credentialResults.every(r => r.verified); + if(!allCredentialsVerified) { + verified = false; + } + } + + if(unsignedPresentation) { + // No need to verify the proof section of this presentation + return {verified, results: [presentation], credentialResults}; + } + + const {controller, domain, challenge} = options; + if(!options.presentationPurpose && !challenge) { + throw new Error( + 'A "challenge" param is required for AuthenticationProofPurpose.'); + } + + const purpose = options.presentationPurpose || + new AuthenticationProofPurpose({controller, domain, challenge}); + + const presentationResult = await jsonld_signatures__WEBPACK_IMPORTED_MODULE_3__.verify( + presentation, {...options, purpose, documentLoader}); + + return { + presentationResult, + verified: verified && presentationResult.verified, + credentialResults, + error: presentationResult.error + }; +} + +/** + * @param {string|object} obj - Either an object with an id property + * or a string that is an id. + * @returns {string|undefined} Either an id or undefined. + * @private + */ +function _getId(obj) { + if(typeof obj === 'string') { + return obj; + } + + if(!('id' in obj)) { + return; + } + + return obj.id; +} + +// export for testing +/** + * @param {object} presentation - An object that could be a presentation. + * + * @throws {Error} + * @private + */ +function _checkPresentation(presentation) { + // normalize to an array to allow the common case of context being a string + const context = Array.isArray(presentation['@context']) ? + presentation['@context'] : [presentation['@context']]; + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.assertCredentialContext)({context}); + + const types = jsonld__WEBPACK_IMPORTED_MODULE_4__.getValues(presentation, 'type'); + + // check type presence + if(!types.includes('VerifiablePresentation')) { + throw new Error('"type" must include "VerifiablePresentation".'); + } +} + +// these props of a VC must be an object with a type +// if present in a VC or VP +const mustHaveType = [ + 'proof', + 'credentialStatus', + 'termsOfUse', + 'evidence' +]; + +// export for testing +/** + * @param {object} options - The options. + * @param {object} options.credential - An object that could be a + * VerifiableCredential. + * @param {string|Date} [options.now] - A string representing date time in + * ISO 8601 format or an instance of Date. Defaults to current date time. + * @param {number} [options.maxClockSkew=300] - A maximum number of seconds + * that clocks may be skewed when checking capability expiration date-times + * against `date` and when comparing invocation proof creation time against + * delegation proof creation time. + * @param {string} [options.mode] - The mode of operation for this + * validation function, either `issue` or `verify`. + * + * @throws {Error} + * @private + */ +function _checkCredential({ + credential, now = new Date(), mode = 'verify', maxClockSkew = 300 +} = {}) { + if(typeof now === 'string') { + now = new Date(now); + } + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.assertCredentialContext)({context: credential['@context']}); + + // check type presence and cardinality + if(!credential.type) { + throw new Error('"type" property is required.'); + } + + if(!jsonld__WEBPACK_IMPORTED_MODULE_4__.getValues(credential, 'type').includes('VerifiableCredential')) { + throw new Error('"type" must include `VerifiableCredential`.'); + } + + _checkCredentialSubjects({credential}); + + if(!credential.issuer) { + throw new Error('"issuer" property is required.'); + } + if((0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.checkContextVersion)({credential, version: 1.0})) { + // check issuanceDate exists + if(!credential.issuanceDate) { + throw new Error('"issuanceDate" property is required.'); + } + // check issuanceDate format on issue + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.assertDateString)({credential, prop: 'issuanceDate'}); + + // check issuanceDate cardinality + if(jsonld__WEBPACK_IMPORTED_MODULE_4__.getValues(credential, 'issuanceDate').length > 1) { + throw new Error('"issuanceDate" property can only have one value.'); + } + // optionally check expirationDate + if('expirationDate' in credential) { + // check if `expirationDate` property is a date + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.assertDateString)({credential, prop: 'expirationDate'}); + if(mode === 'verify') { + // check if `now` is after `expirationDate` + const expirationDate = new Date(credential.expirationDate); + if((0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.compareTime)({t1: now, t2: expirationDate, maxClockSkew}) > 0) { + throw new Error('Credential has expired.'); + } + } + } + // check if `now` is before `issuanceDate` on verification + if(mode === 'verify') { + const issuanceDate = new Date(credential.issuanceDate); + if((0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.compareTime)({t1: issuanceDate, t2: now, maxClockSkew}) > 0) { + throw new Error( + `The current date time (${now.toISOString()}) is before the ` + + `"issuanceDate" (${credential.issuanceDate}).`); + } + } + } + if((0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.checkContextVersion)({credential, version: 2.0})) { + // check if 'validUntil' and 'validFrom' + let {validUntil, validFrom} = credential; + if(validUntil) { + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.assertDateString)({credential, prop: 'validUntil'}); + if(mode === 'verify') { + validUntil = new Date(credential.validUntil); + if((0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.compareTime)({t1: now, t2: validUntil, maxClockSkew}) > 0) { + throw new Error( + `The current date time (${now.toISOString()}) is after ` + + `"validUntil" (${credential.validUntil}).`); + } + } + } + if(validFrom) { + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.assertDateString)({credential, prop: 'validFrom'}); + if(mode === 'verify') { + // check if `now` is before `validFrom` + validFrom = new Date(credential.validFrom); + if((0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.compareTime)({t1: validFrom, t2: now, maxClockSkew}) > 0) { + throw new Error( + `The current date time (${now.toISOString()}) is before ` + + `"validFrom" (${credential.validFrom}).`); + } + } + } + } + // check issuer cardinality + if(jsonld__WEBPACK_IMPORTED_MODULE_4__.getValues(credential, 'issuer').length > 1) { + throw new Error('"issuer" property can only have one value.'); + } + + // check issuer is a URL + if('issuer' in credential) { + const issuer = _getId(credential.issuer); + if(!issuer) { + throw new Error(`"issuer" id is required.`); + } + _validateUriId({id: issuer, propertyName: 'issuer'}); + } + + // check credentialStatus + jsonld__WEBPACK_IMPORTED_MODULE_4__.getValues(credential, 'credentialStatus').forEach(cs => { + // check if optional "id" is a URL + if('id' in cs) { + _validateUriId({id: cs.id, propertyName: 'credentialStatus.id'}); + } + + // check "type" present + if(!cs.type) { + throw new Error('"credentialStatus" must include a type.'); + } + }); + + // check evidences are URLs + jsonld__WEBPACK_IMPORTED_MODULE_4__.getValues(credential, 'evidence').forEach(evidence => { + const evidenceId = _getId(evidence); + if(evidenceId) { + _validateUriId({id: evidenceId, propertyName: 'evidence'}); + } + }); + + // check if properties that require a type are + // defined, objects, and objects with types + for(const prop of mustHaveType) { + if(prop in credential) { + const _value = credential[prop]; + if(Array.isArray(_value)) { + _value.forEach(entry => _checkTypedObject(entry, prop)); + continue; + } + _checkTypedObject(_value, prop); + } + } +} + +/** + * @private + * Checks that a property is non-empty object with + * property type. + * + * @param {object} obj - A potential object. + * @param {string} name - The name of the property. + * + * @throws {Error} if the property is not an object with a type. + * + * @returns {undefined} - Returns on success. + */ +function _checkTypedObject(obj, name) { + if(!isObject(obj)) { + throw new Error(`property "${name}" must be an object.`); + } + if(_emptyObject(obj)) { + throw new Error(`property "${name}" can not be an empty object.`); + } + if(!('type' in obj)) { + throw new Error(`property "${name}" must have property type.`); + } +} + +/** + * @private + * Takes in a credential and checks the credentialSubject(s) + * + * @param {object} options - Options. + * @param {object} options.credential - The credential to check. + * + * @throws {Error} error - Throws on errors in the credential subject. + * + * @returns {undefined} - Returns on success. +*/ +function _checkCredentialSubjects({credential}) { + if(!credential?.credentialSubject) { + throw new Error('"credentialSubject" property is required.'); + } + if(Array.isArray(credential?.credentialSubject)) { + return credential?.credentialSubject.map( + subject => _checkCredentialSubject({subject})); + } + return _checkCredentialSubject({subject: credential?.credentialSubject}); +} + +/** + * @private + * + * Checks a credential subject is valid. + * + * @param {object} options - Options. + * @param {object} options.subject - A potential credential subject. + * + * @throws {Error} If the credentialSubject is not valid. + * + * @returns {undefined} Returns on success. + */ +function _checkCredentialSubject({subject}) { + if(isObject(subject) === false) { + throw new Error('"credentialSubject" must be a non-null object.'); + } + if(_emptyObject(subject)) { + throw new Error('"credentialSubject" must make a claim.'); + } + // If credentialSubject.id is present and is not a URI, reject it + if(subject.id) { + _validateUriId({ + id: subject.id, propertyName: 'credentialSubject.id' + }); + } +} + +/** + * @private + * Checks if parameter is an object. + * + * @param {object} obj - A potential object. + * + * @returns {boolean} - Returns false if not an object or null. + */ +function isObject(obj) { + // return false for null even though it has type object + if(obj === null) { + return false; + } + // if something has type object and is not null return true + if((typeof obj) === 'object') { + return true; + } + // return false for strings, symbols, etc. + return false; +} + +/** + * @private + * Is it an empty object? + * + * @param {object} obj - A potential object. + * + * @returns {boolean} - Is it empty? + */ +function _emptyObject(obj) { + // if the parameter is not an object return true + // as a non-object is an empty object + if(!isObject(obj)) { + return true; + } + return Object.keys(obj).length === 0; +} + +/** + * @private + * + * Validates if an ID is a URL. + * + * @param {object} options - Options. + * @param {string} options.id - the id. + * @param {string} options.propertyName - The property name. + * + * @throws {Error} Throws if an id is not a URL. + * + * @returns {undefined} Returns on success. + */ +function _validateUriId({id, propertyName}) { + let parsed; + try { + parsed = new URL(id); + } catch(e) { + const error = new TypeError(`"${propertyName}" must be a URI: "${id}".`); + error.cause = e; + throw error; + } + + if(!parsed.protocol) { + throw new TypeError(`"${propertyName}" must be a URI: "${id}".`); + } +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/base58-universal/dist/baseN.js" +/*!*************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/base58-universal/dist/baseN.js ***! + \*************************************************************************/ +(__unused_webpack_module, exports) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +/** + * Base-N/Base-X encoding/decoding functions. + * + * Original implementation from base-x: + * https://github.com/cryptocoinjs/base-x + * + * Which is MIT licensed: + * + * The MIT License (MIT) + * + * Copyright base-x contributors (c) 2016 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +// base58 characters (Bitcoin alphabet) +const BASE58_BTC = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + +// baseN alphabet indexes +const _reverseAlphabets = {}; + +/** + * BaseN-encodes a Uint8Array using the given alphabet. + * + * @param {Uint8Array} input the bytes to encode in a Uint8Array. + * @param {number} maxline the maximum number of encoded characters per line to + * use, defaults to none. + * + * @return {string} the baseN-encoded output string. + */ +function encode(input, maxline, alphabet = BASE58_BTC) { + if(!(input instanceof Uint8Array)) { + throw new TypeError('"input" must be a Uint8Array.'); + } + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + if(maxline !== undefined && typeof maxline !== 'number') { + throw new TypeError('"maxline" must be a number.'); + } + if(input.length === 0) { + return ''; + } + + let output = ''; + + let i = 0; + const base = alphabet.length; + const first = alphabet.charAt(0); + const digits = [0]; + for(i = 0; i < input.length; ++i) { + let carry = input[i]; + for(let j = 0; j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + + while(carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + + // deal with leading zeros + for(i = 0; input[i] === 0 && i < input.length - 1; ++i) { + output += first; + } + // convert digits to a string + for(i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + + if(maxline) { + const regex = new RegExp('.{1,' + maxline + '}', 'g'); + output = output.match(regex).join('\r\n'); + } + + return output; +} + +/** + * Decodes a baseN-encoded (using the given alphabet) string to a + * Uint8Array. + * + * @param {string} input the baseN-encoded input string. + * + * @return {Uint8Array} the decoded bytes in a Uint8Array. + */ +function decode(input, alphabet = BASE58_BTC) { + if(typeof input !== 'string') { + throw new TypeError('"input" must be a string.'); + } + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + if(input.length === 0) { + return new Uint8Array(); + } + + let table = _reverseAlphabets[alphabet]; + if(!table) { + // compute reverse alphabet + table = _reverseAlphabets[alphabet] = []; + for(let i = 0; i < alphabet.length; ++i) { + table[alphabet.charCodeAt(i)] = i; + } + } + + // remove whitespace characters + input = input.replace(/\s/g, ''); + + const base = alphabet.length; + const first = alphabet.charAt(0); + const bytes = [0]; + for(let i = 0; i < input.length; i++) { + const value = table[input.charCodeAt(i)]; + if(value === undefined) { + return; + } + + let carry = value; + for(let j = 0; j < bytes.length; ++j) { + carry += bytes[j] * base; + bytes[j] = carry & 0xff; + carry >>= 8; + } + + while(carry > 0) { + bytes.push(carry & 0xff); + carry >>= 8; + } + } + + // deal with leading zeros + for(let k = 0; input[k] === first && k < input.length - 1; ++k) { + bytes.push(0); + } + + return new Uint8Array(bytes.reverse()); +} + +exports.decode = decode; +exports.encode = encode; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/base58-universal/dist/index.js" +/*!*************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/base58-universal/dist/index.js ***! + \*************************************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var baseN = __webpack_require__(/*! ./baseN.js */ "./node_modules/@digitalcredentials/base58-universal/dist/baseN.js"); + + + +exports.decode = baseN.decode; +exports.encode = baseN.encode; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/credentials-v2-context/js/context.js" +/*!*******************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/credentials-v2-context/js/context.js ***! + \*******************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/*! + * Copyright (c) 2023-2024 Digital Bazaar, Inc. All rights reserved. + */ +// Use JSON style for context +/* eslint quotes: ['error', 'double'] */ +/* eslint quote-props: ['error', 'always'] */ +/* eslint-disable max-len */ + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (/* context-url: https://www.w3.org/ns/credentials/v2 *//* context-begin */{ + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "description": "https://schema.org/description", + "digestMultibase": { + "@id": "https://w3id.org/security#digestMultibase", + "@type": "https://w3id.org/security#multibase" + }, + "digestSRI": { + "@id": "https://www.w3.org/2018/credentials#digestSRI", + "@type": "https://www.w3.org/2018/credentials#sriString" + }, + "mediaType": { + "@id": "https://schema.org/encodingFormat" + }, + "name": "https://schema.org/name", + + "VerifiableCredential": { + "@id": "https://www.w3.org/2018/credentials#VerifiableCredential", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "confidenceMethod": { + "@id": "https://www.w3.org/2018/credentials#confidenceMethod", + "@type": "@id" + }, + "credentialSchema": { + "@id": "https://www.w3.org/2018/credentials#credentialSchema", + "@type": "@id" + }, + "credentialStatus": { + "@id": "https://www.w3.org/2018/credentials#credentialStatus", + "@type": "@id" + }, + "credentialSubject": { + "@id": "https://www.w3.org/2018/credentials#credentialSubject", + "@type": "@id" + }, + "description": "https://schema.org/description", + "evidence": { + "@id": "https://www.w3.org/2018/credentials#evidence", + "@type": "@id" + }, + "issuer": { + "@id": "https://www.w3.org/2018/credentials#issuer", + "@type": "@id" + }, + "name": "https://schema.org/name", + "proof": { + "@id": "https://w3id.org/security#proof", + "@type": "@id", + "@container": "@graph" + }, + "refreshService": { + "@id": "https://www.w3.org/2018/credentials#refreshService", + "@type": "@id" + }, + "relatedResource": { + "@id": "https://www.w3.org/2018/credentials#relatedResource", + "@type": "@id" + }, + "renderMethod": { + "@id": "https://www.w3.org/2018/credentials#renderMethod", + "@type": "@id" + }, + "termsOfUse": { + "@id": "https://www.w3.org/2018/credentials#termsOfUse", + "@type": "@id" + }, + "validFrom": { + "@id": "https://www.w3.org/2018/credentials#validFrom", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + }, + "validUntil": { + "@id": "https://www.w3.org/2018/credentials#validUntil", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + } + } + }, + + "EnvelopedVerifiableCredential": + "https://www.w3.org/2018/credentials#EnvelopedVerifiableCredential", + + "VerifiablePresentation": { + "@id": "https://www.w3.org/2018/credentials#VerifiablePresentation", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "holder": { + "@id": "https://www.w3.org/2018/credentials#holder", + "@type": "@id" + }, + "proof": { + "@id": "https://w3id.org/security#proof", + "@type": "@id", + "@container": "@graph" + }, + "termsOfUse": { + "@id": "https://www.w3.org/2018/credentials#termsOfUse", + "@type": "@id" + }, + "verifiableCredential": { + "@id": "https://www.w3.org/2018/credentials#verifiableCredential", + "@type": "@id", + "@container": "@graph", + "@context": null + } + } + }, + + "EnvelopedVerifiablePresentation": + "https://www.w3.org/2018/credentials#EnvelopedVerifiablePresentation", + + "JsonSchemaCredential": + "https://www.w3.org/2018/credentials#JsonSchemaCredential", + + "JsonSchema": { + "@id": "https://www.w3.org/2018/credentials#JsonSchema", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "jsonSchema": { + "@id": "https://www.w3.org/2018/credentials#jsonSchema", + "@type": "@json" + } + } + }, + + "BitstringStatusListCredential": + "https://www.w3.org/ns/credentials/status#BitstringStatusListCredential", + + "BitstringStatusList": { + "@id": "https://www.w3.org/ns/credentials/status#BitstringStatusList", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "encodedList": { + "@id": "https://www.w3.org/ns/credentials/status#encodedList", + "@type": "https://w3id.org/security#multibase" + }, + "statusPurpose": + "https://www.w3.org/ns/credentials/status#statusPurpose", + "ttl": "https://www.w3.org/ns/credentials/status#ttl" + } + }, + + "BitstringStatusListEntry": { + "@id": + "https://www.w3.org/ns/credentials/status#BitstringStatusListEntry", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "statusListCredential": { + "@id": + "https://www.w3.org/ns/credentials/status#statusListCredential", + "@type": "@id" + }, + "statusListIndex": + "https://www.w3.org/ns/credentials/status#statusListIndex", + "statusPurpose": + "https://www.w3.org/ns/credentials/status#statusPurpose", + "statusMessage": { + "@id": "https://www.w3.org/ns/credentials/status#statusMessage", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "message": "https://www.w3.org/ns/credentials/status#message", + "status": "https://www.w3.org/ns/credentials/status#status" + } + }, + "statusReference": { + "@id": "https://www.w3.org/ns/credentials/status#statusReference", + "@type": "@id" + }, + "statusSize": { + "@id": "https://www.w3.org/ns/credentials/status#statusSize", + "@type": "https://www.w3.org/2001/XMLSchema#integer" + } + } + }, + + "DataIntegrityProof": { + "@id": "https://w3id.org/security#DataIntegrityProof", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "challenge": "https://w3id.org/security#challenge", + "created": { + "@id": "http://purl.org/dc/terms/created", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + }, + "cryptosuite": { + "@id": "https://w3id.org/security#cryptosuite", + "@type": "https://w3id.org/security#cryptosuiteString" + }, + "domain": "https://w3id.org/security#domain", + "expires": { + "@id": "https://w3id.org/security#expiration", + "@type": "http://www.w3.org/2001/XMLSchema#dateTime" + }, + "nonce": "https://w3id.org/security#nonce", + "previousProof": { + "@id": "https://w3id.org/security#previousProof", + "@type": "@id" + }, + "proofPurpose": { + "@id": "https://w3id.org/security#proofPurpose", + "@type": "@vocab", + "@context": { + "@protected": true, + + "id": "@id", + "type": "@type", + + "assertionMethod": { + "@id": "https://w3id.org/security#assertionMethod", + "@type": "@id", + "@container": "@set" + }, + "authentication": { + "@id": "https://w3id.org/security#authenticationMethod", + "@type": "@id", + "@container": "@set" + }, + "capabilityDelegation": { + "@id": "https://w3id.org/security#capabilityDelegationMethod", + "@type": "@id", + "@container": "@set" + }, + "capabilityInvocation": { + "@id": "https://w3id.org/security#capabilityInvocationMethod", + "@type": "@id", + "@container": "@set" + }, + "keyAgreement": { + "@id": "https://w3id.org/security#keyAgreementMethod", + "@type": "@id", + "@container": "@set" + } + } + }, + "proofValue": { + "@id": "https://w3id.org/security#proofValue", + "@type": "https://w3id.org/security#multibase" + }, + "verificationMethod": { + "@id": "https://w3id.org/security#verificationMethod", + "@type": "@id" + } + } + }, + + "...": { + "@id": "https://www.iana.org/assignments/jwt#..." + }, + "_sd": { + "@id": "https://www.iana.org/assignments/jwt#_sd", + "@type": "@json" + }, + "_sd_alg": { + "@id": "https://www.iana.org/assignments/jwt#_sd_alg" + }, + "aud": { + "@id": "https://www.iana.org/assignments/jwt#aud", + "@type": "@id" + }, + "cnf": { + "@id": "https://www.iana.org/assignments/jwt#cnf", + "@context": { + "@protected": true, + + "kid": { + "@id": "https://www.iana.org/assignments/jwt#kid", + "@type": "@id" + }, + "jwk": { + "@id": "https://www.iana.org/assignments/jwt#jwk", + "@type": "@json" + } + } + }, + "exp": { + "@id": "https://www.iana.org/assignments/jwt#exp", + "@type": "https://www.w3.org/2001/XMLSchema#nonNegativeInteger" + }, + "iat": { + "@id": "https://www.iana.org/assignments/jwt#iat", + "@type": "https://www.w3.org/2001/XMLSchema#nonNegativeInteger" + }, + "iss": { + "@id": "https://www.iana.org/assignments/jose#iss", + "@type": "@id" + }, + "jku": { + "@id": "https://www.iana.org/assignments/jose#jku", + "@type": "@id" + }, + "kid": { + "@id": "https://www.iana.org/assignments/jose#kid", + "@type": "@id" + }, + "nbf": { + "@id": "https://www.iana.org/assignments/jwt#nbf", + "@type": "https://www.w3.org/2001/XMLSchema#nonNegativeInteger" + }, + "sub": { + "@id": "https://www.iana.org/assignments/jose#sub", + "@type": "@id" + }, + "x5u": { + "@id": "https://www.iana.org/assignments/jose#x5u", + "@type": "@id" + } + } +}); + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/credentials-v2-context/js/index.js" +/*!*****************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/credentials-v2-context/js/index.js ***! + \*****************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CONTEXT: () => (/* binding */ CONTEXT), +/* harmony export */ CONTEXT_URL: () => (/* binding */ CONTEXT_URL), +/* harmony export */ appContextMap: () => (/* binding */ appContextMap), +/* harmony export */ constants: () => (/* binding */ constants), +/* harmony export */ contexts: () => (/* binding */ contexts) +/* harmony export */ }); +/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./context.js */ "./node_modules/@digitalcredentials/credentials-v2-context/js/context.js"); +/*! + * Copyright (c) 2023-2024 Digital Bazaar, Inc. All rights reserved. + */ + + +const constants = { + // default context output filename under ./contexts/ + CONTEXT_FILENAME: 'credentials-v2.jsonld', + // default context well known URL id + CONTEXT_URL: 'https://www.w3.org/ns/credentials/v2', + // default context CBOR-LD codec id + // value between 0x0 and 0x7FFF for globally registered term codec values + // or >= 0x8000 for app-specific local terms + CBORLD_VALUE: 0x0 +}; + +// map of all context URLs to context data +const contexts = new Map(); +contexts.set(constants.CONTEXT_URL, _context_js__WEBPACK_IMPORTED_MODULE_0__["default"]); + +// map of all context URLs to CBOR-LD codec ids +const appContextMap = new Map(); +appContextMap.set(constants.CONTEXT_URL, constants.CBORLD_VALUE); + +const CONTEXT = _context_js__WEBPACK_IMPORTED_MODULE_0__["default"]; +const CONTEXT_URL = constants.CONTEXT_URL; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/dcc-context/js/constants.js" +/*!**********************************************************************!*\ + !*** ./node_modules/@digitalcredentials/dcc-context/js/constants.js ***! + \**********************************************************************/ +(module) { + +"use strict"; + + +module.exports = { + CONTEXT_FILENAME: 'dcc-context-v1.json', + CONTEXT_URL_V1: 'https://w3id.org/dcc/v1', + // value between 0x0 and 0x7FFF for globally registered term codec values + // or >= 0x8000 for app-specific local terms + CBORLD_VALUE: 0x8001 +}; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/dcc-context/js/context.js" +/*!********************************************************************!*\ + !*** ./node_modules/@digitalcredentials/dcc-context/js/context.js ***! + \********************************************************************/ +(module) { + +"use strict"; + + +module.exports = { + '@context': { + '@protected': true, + id: '@id', + type: '@type', + + EducationalOccupationalCredential: 'http://schema.org/EducationalOccupationalCredential', + EducationalOccupationalProgram: 'http://schema.org/EducationalOccupationalProgram', + Course: 'http://schema.org/Course', + CourseInstance: 'http://schema.org/CourseInstance', + Person: 'http://schema.org/Person', + name: 'http://schema.org/name', + url: 'http://schema.org/url', + identifier: 'http://schema.org/identifier', + courseCode: 'http://schema.org/courseCode', + numberOfCredits: 'http://schema.org/numberOfCredits', + startDate: 'http://schema.org/startDate', + endDate: 'http://schema.org/endDate', + value: 'http://schema.org/value', + educationalCredentialAwarded: 'http://schema.org/educationalCredentialAwarded', + hasCourseInstance: 'http://schema.org/hasCourseInstance', + + description: { + '@id': 'http://schema.org/description' + }, + image: { + '@id': 'http://schema.org/image', + '@type': '@id' + }, + + awardedOnCompletionOf: { + '@reverse': 'http://schema.org/educationalCredentialAwarded' + }, + + competencyRequired: 'http://schema.org/EducationalOccupationalCredential#competencyRequired', + credentialCategory: 'http://schema.org/EducationalOccupationalCredential#credentialCategory', + + hasCredential: 'http://schema.org/hasCredential', + assertion: 'https://w3id.org/dcc/v1#assertion', + Issuer: 'https://w3id.org/openbadges#Issuer', + + ProgramCompletionCredential: 'https://w3id.org/dcc/v1#ProgramCompletionCredential', + CourseCompletionCredential: 'https://w3id.org/dcc/v1#CourseCompletionCredential', + LearningCredential: 'https://w3id.org/dcc/v1#LearningCredential', + Assertion: 'https://w3id.org/dcc/v1#Assertion' + } +}; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/dcc-context/js/index.js" +/*!******************************************************************!*\ + !*** ./node_modules/@digitalcredentials/dcc-context/js/index.js ***! + \******************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; + + +const context = __webpack_require__(/*! ./context */ "./node_modules/@digitalcredentials/dcc-context/js/context.js"); +const constants = __webpack_require__(/*! ./constants */ "./node_modules/@digitalcredentials/dcc-context/js/constants.js"); +const {CONTEXT_URL_V1, CBORLD_VALUE} = constants; + +const contexts = new Map(); +contexts.set(CONTEXT_URL_V1, context); + +const appContextMap = new Map(); +appContextMap.set(CONTEXT_URL_V1, CBORLD_VALUE); + +module.exports = { + constants, + contexts, + appContextMap, + CONTEXT_URL_V1, + CONTEXT_V1: context +}; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-io/dist/CachedResolver.js" +/*!************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-io/dist/CachedResolver.js ***! + \************************************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var didIo = __webpack_require__(/*! ./did-io.js */ "./node_modules/@digitalcredentials/did-io/dist/did-io.js"); +var lruMemoize = __webpack_require__(/*! @digitalcredentials/lru-memoize */ "./node_modules/@digitalcredentials/lru-memoize/dist/index.js"); + +/*! + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */ + +class CachedResolver { + /** + * @param {object} [options={}] - Options hashmap. + * @param {number} [options.max=100] - Max number of items in the cache. + * @param {number} [options.maxAge=5000] - Max age of a cache item, in ms. + * @param {boolean} [options.updateAgeOnGet=false] - When using time-expiring + * entries with `maxAge`, setting this to true will make each entry's + * effective time update to the current time whenever it is retrieved from + * cache, thereby extending the expiration date of the entry. + * @param {object} [options.cacheOptions] - Additional `lru-cache` options. + */ + constructor({max = 100, maxAge = 5000, updateAgeOnGet = false, + ...cacheOptions} = {}) { + this._cache = new lruMemoize.LruCache({max, maxAge, updateAgeOnGet, ...cacheOptions}); + this._methods = new Map(); + } + + use(driver) { + const methodName = driver.method; + this._methods.set(methodName, driver); + } + + /** + * Gets the DID Document, by selecting a registered driver based on the DID + * prefix (DID method). + * Either `did` or `url` param is required. + * + * @param {object} options - Options hashmap. + * @param {string} [options.did] - DID uri. + * @param {string} [options.url] - Typically, a key ID or other DID-related + * url. This is used to improve code readability. + * @param {object} [options.getOptions] - Options passed through to the + * driver's get() operation. + * + * @returns {Promise} Resolves with fetched DID Document. + */ + async get({did, url, ...getOptions} = {}) { + did = did || url; + if(!did) { + throw new TypeError('A string "did" or "url" parameter is required.'); + } + + const method = this._methodForDid(did); + + return this._cache.memoize({ + key: did, + fn: () => method.get({did, ...getOptions}) + }); + } + + /** + * @param {string} did - DID uri. + * + * @returns {object} - DID Method driver. + * @private + */ + _methodForDid(did) { + const {prefix} = didIo.parseDid({did}); + const method = this._methods.get(prefix); + if(!method) { + throw new Error(`Driver for DID ${did} not found.`); + } + return method; + } +} + +exports.CachedResolver = CachedResolver; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-io/dist/constants.js" +/*!*******************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-io/dist/constants.js ***! + \*******************************************************************/ +(__unused_webpack_module, exports) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +/*! + * Copyright (c) 2021 Digital Bazaar. All rights reserved. + */ +/** + * A verification relationship expresses the relationship between the DID + * subject and a verification method (such as a cryptographic public key). + * Different verification relationships enable the associated verification + * methods to be used for different purposes. + * + * @see https://w3c.github.io/did-core/#verification-relationships + * @type {Set} + */ +const VERIFICATION_RELATIONSHIPS = new Set([ + 'assertionMethod', + 'authentication', + 'capabilityDelegation', + 'capabilityInvocation', + 'keyAgreement' +]); + +exports.VERIFICATION_RELATIONSHIPS = VERIFICATION_RELATIONSHIPS; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-io/dist/did-io.js" +/*!****************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-io/dist/did-io.js ***! + \****************************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var constants = __webpack_require__(/*! ./constants.js */ "./node_modules/@digitalcredentials/did-io/dist/constants.js"); + +/*! + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */ + +/** + * Tests whether this DID Document contains a verification relationship + * between the subject and a method id, for a given purpose. + * + * @example + * didDocument.approvesMethodFor({ + * methodId: 'did:ex:1234#abcd', purpose: 'authentication' + * }); + * // -> true + * @example + * didDocument.approvesMethodFor({ + * methodId: 'did:ex:1234#abcd', purpose: 'assertionMethod' + * }); + * // -> false + * + * @param {object} options - Options hashmap. + * @param {object} options.doc - DID Document. + * @param {string} options.methodId - Verification method id (a uri). + * @param {string} options.purpose - E.g. 'authentication', etc. + * + * @returns {boolean} Returns whether a method id is authorized for purpose. + */ +function approvesMethodFor({doc, methodId, purpose}) { + if(!(methodId && purpose)) { + throw new Error('A method id and purpose is required.'); + } + const method = _methodById({doc, methodId}); + if(!method) { + return false; + } + const methods = doc[purpose] || []; + return !!methods.find(method => { + return (typeof method === 'string' && method === methodId) || + (typeof method === 'object' && method.id === methodId); + }); +} + +/** + * Initializes the DID Document's keys/proof methods. + * + * @example + * didDocument.id = 'did:ex:123'; + * const {keyPairs} = await initKeys({ + * cryptoLd, + * keyMap: { + * capabilityInvocation: someExistingKey, + * authentication: 'Ed25519VerificationKey2020', + * assertionMethod: 'Ed25519VerificationKey2020', + * keyAgreement: 'X25519KeyAgreementKey2019' + * } + * });. + * + * @param {object} options - Options hashmap. + * @param {object} options.doc - DID Document. + * @typedef {object} CryptoLD + * @param {CryptoLD} [options.cryptoLd] - CryptoLD driver instance, + * initialized with the key types this DID Document intends to support. + * @param {object} [options.keyMap] - Map of keys (or key types) by purpose. + * + * @returns {Promise<{keyPairs: object}>} A hashmap of public/private key + * pairs, by key id. + */ +async function initKeys({doc, cryptoLd, keyMap = {}} = {}) { + if(!doc.id) { + throw new TypeError( + 'DID Document "id" property is required to initialize keys.'); + } + + const keyPairs = {}; + + // Set the defaults for the created keys (if needed) + const options = {controller: doc.id}; + + for(const purpose in keyMap) { + if(!constants.VERIFICATION_RELATIONSHIPS.has(purpose)) { + throw new Error(`Unsupported key purpose: "${purpose}".`); + } + + let key; + if(typeof keyMap[purpose] === 'string') { + if(!cryptoLd) { + throw new Error('Please provide an initialized CryptoLD instance.'); + } + key = await cryptoLd.generate({type: keyMap[purpose], ...options}); + } else { + // An existing key has been provided + key = keyMap[purpose]; + } + + this[purpose] = [key.export({publicKey: true})]; + keyPairs[key.id] = key; + } + + return {keyPairs}; +} + +/** + * Finds a verification method for a given methodId or purpose. + * + * If a method id is given, returns the object for that method (for example, + * returns the public key definition for that id). + * + * If a purpose (verification relationship) is given, returns the first + * available verification method for that purpose. + * + * If no method is found (for the given id or purpose), returns undefined. + * + * @example + * findVerificationMethod({doc, methodId: 'did:ex:123#abcd'}); + * // -> + * { + * id: 'did:ex:123#abcd', + * controller: 'did:ex:123', + * type: 'Ed25519VerificationKey2020', + * publicKeyMultibase: '...' + * } + * @example + * didDocument.findVerificationMethod({doc, purpose: 'authentication'}); + * // -> + * { + * id: 'did:ex:123#abcd', + * controller: 'did:ex:123', + * type: 'Ed25519VerificationKey2020', + * publicKeyMultibase: '...' + * } + * @param {object} options - Options hashmap. + * @param {object} options.doc - DID Document. + * + * One of the following is required. + * @param {string} [options.methodId] - Verification method id. + * @param {string} [options.purpose] - Method purpose (verification + * relationship). + * + * @returns {object} Returns the verification method, or undefined if not found. + */ +function findVerificationMethod({doc, methodId, purpose} = {}) { + if(!doc) { + throw new TypeError('A DID Document is required.'); + } + if(!(methodId || purpose)) { + throw new TypeError('A method id or purpose is required.'); + } + + if(methodId) { + return _methodById({doc, methodId}); + } + + // Id not given, find the first method by purpose + const [method] = doc[purpose] || []; + if(method && typeof method === 'string') { + // This is a reference, not the full method, attempt to find it + return _methodById({doc, methodId: method}); + } + + return method; +} + +/** + * Finds a verification method for a given id and returns it. + * + * @param {object} options - Options hashmap. + * @param {object} options.doc - DID Document. + * @param {string} options.methodId - Verification method id. + * + * @returns {object} Returns the verification method. + */ +function _methodById({doc, methodId}) { + let result; + + // First, check the 'verificationMethod' bucket, see if it's listed there + if(doc.verificationMethod) { + result = doc.verificationMethod.find(method => method.id === methodId); + } + + for(const purpose of constants.VERIFICATION_RELATIONSHIPS) { + const methods = doc[purpose] || []; + // Iterate through each verification method in 'authentication', etc. + for(const method of methods) { + // Only return it if the method is defined, not referenced + if(typeof method === 'object' && method.id === methodId) { + result = method; + break; + } + } + if(result) { + return result; + } + } +} + +/** + * Parses the DID into various component (currently, only cares about prefix). + * + * @example + * parseDid({did: 'did:v1:test:nym'}); + * // -> {prefix: 'v1'} + * + * @param {string} did - DID uri. + * + * @returns {{prefix: string}} Returns the method prefix (without `did:`). + */ +function parseDid({did}) { + if(!did) { + throw new TypeError('DID cannot be empty.'); + } + + const prefix = did.split(':').slice(1, 2).join(':'); + + return {prefix}; +} + +exports._methodById = _methodById; +exports.approvesMethodFor = approvesMethodFor; +exports.findVerificationMethod = findVerificationMethod; +exports.initKeys = initKeys; +exports.parseDid = parseDid; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-io/dist/esm/index.js" +/*!*******************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-io/dist/esm/index.js ***! + \*******************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CachedResolver: () => (/* binding */ CachedResolver), +/* harmony export */ VERIFICATION_RELATIONSHIPS: () => (/* binding */ VERIFICATION_RELATIONSHIPS), +/* harmony export */ approvesMethodFor: () => (/* binding */ approvesMethodFor), +/* harmony export */ findVerificationMethod: () => (/* binding */ findVerificationMethod), +/* harmony export */ initKeys: () => (/* binding */ initKeys), +/* harmony export */ parseDid: () => (/* binding */ parseDid) +/* harmony export */ }); +/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index.js */ "./node_modules/@digitalcredentials/did-io/dist/index.js"); + +const approvesMethodFor = _index_js__WEBPACK_IMPORTED_MODULE_0__.approvesMethodFor; +const findVerificationMethod = _index_js__WEBPACK_IMPORTED_MODULE_0__.findVerificationMethod; +const initKeys = _index_js__WEBPACK_IMPORTED_MODULE_0__.initKeys; +const parseDid = _index_js__WEBPACK_IMPORTED_MODULE_0__.parseDid; +const CachedResolver = _index_js__WEBPACK_IMPORTED_MODULE_0__.CachedResolver; +const VERIFICATION_RELATIONSHIPS = _index_js__WEBPACK_IMPORTED_MODULE_0__.VERIFICATION_RELATIONSHIPS; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-io/dist/index.js" +/*!***************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-io/dist/index.js ***! + \***************************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var didIo = __webpack_require__(/*! ./did-io.js */ "./node_modules/@digitalcredentials/did-io/dist/did-io.js"); +var CachedResolver = __webpack_require__(/*! ./CachedResolver.js */ "./node_modules/@digitalcredentials/did-io/dist/CachedResolver.js"); +var constants = __webpack_require__(/*! ./constants.js */ "./node_modules/@digitalcredentials/did-io/dist/constants.js"); + + + +exports.approvesMethodFor = didIo.approvesMethodFor; +exports.findVerificationMethod = didIo.findVerificationMethod; +exports.initKeys = didIo.initKeys; +exports.parseDid = didIo.parseDid; +exports.CachedResolver = CachedResolver.CachedResolver; +exports.VERIFICATION_RELATIONSHIPS = constants.VERIFICATION_RELATIONSHIPS; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-key/lib/DidKeyDriver.js" +/*!*****************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-key/lib/DidKeyDriver.js ***! + \*****************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ DidKeyDriver: () => (/* binding */ DidKeyDriver) +/* harmony export */ }); +/* harmony import */ var _digitalcredentials_did_io__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @digitalcredentials/did-io */ "./node_modules/@digitalcredentials/did-io/dist/esm/index.js"); +/* harmony import */ var _helpers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./helpers.js */ "./node_modules/@digitalcredentials/did-method-key/lib/helpers.js"); +/*! + * Copyright (c) 2021-2023 Digital Bazaar, Inc. All rights reserved. + */ + + + +const DID_CONTEXT_URL = 'https://www.w3.org/ns/did/v1'; + +class DidKeyDriver { + constructor() { + // used by did-io to register drivers + this.method = 'key'; + this._allowedKeyTypes = new Map(); + } + + /** + * Registers a multibase-multikey header and a multibase-multikey + * deserializer that is allowed to handle data using that header. + * + * @param {object} options - Options hashmap. + * + * @param {string} options.multibaseMultikeyHeader - The multibase-multikey + * header to register. + * @param {Function} options.fromMultibase - A function that converts a + * `{publicKeyMultibase}` value into a key pair interface. + */ + use({multibaseMultikeyHeader, fromMultibase} = {}) { + if(!(multibaseMultikeyHeader && + typeof multibaseMultikeyHeader === 'string')) { + throw new TypeError('"multibaseMultikeyHeader" must be a string.'); + } + if(typeof fromMultibase !== 'function') { + throw new TypeError('"fromMultibase" must be a function.'); + } + this._allowedKeyTypes.set(multibaseMultikeyHeader, fromMultibase); + } + + /** + * Generates a DID `key` (`did:key`) method DID Document from a KeyPair. + * + * @param {object} options - Options hashmap. + * + * @param {object} [options.verificationKeyPair] - A verification KeyPair. + * @param {object} [options.keyAgreementKeyPair] - A keyAgreement KeyPair. + * + * @returns {Promise<{didDocument: object, keyPairs: Map, + * methodFor: Function}>} Resolves with the generated DID Document, along + * with the corresponding key pairs used to generate it (for storage in a + * KMS). + */ + async fromKeyPair({verificationKeyPair, keyAgreementKeyPair} = {}) { + if(!(verificationKeyPair || keyAgreementKeyPair)) { + throw new TypeError( + '"verificationKeyPair" or "keyAgreementKeyPair" must be an object.'); + } + // keyPairs is a map of keyId to key pair instance, that includes the + // verificationKeyPair above and the keyAgreementKey pair that is + // optionally passed or derived from the passed verification key pair + const {didDocument, keyPairs} = await this._keyPairToDidDocument( + {keyPair: verificationKeyPair, keyAgreementKeyPair}); + + // convenience function that returns the public/private key pair instance + // for a given purpose (authentication, assertionMethod, keyAgreement, etc). + const methodFor = ({purpose}) => { + const {id: methodId} = this.publicMethodFor({ + didDocument, purpose + }); + return keyPairs.get(methodId); + }; + return {didDocument, keyPairs, methodFor}; + } + + /** + * Returns the public key (verification method) object for a given DID + * Document and purpose. Useful in conjunction with a `.get()` call. + * + * @example + * const didDocument = await didKeyDriver.get({did}); + * const authKeyData = didDriver.publicMethodFor({ + * didDocument, purpose: 'authentication' + * }); + * // You can then create a suite instance object to verify signatures etc. + * const authPublicKey = await cryptoLd.from(authKeyData); + * const {verify} = authPublicKey.verifier(); + * + * @param {object} options - Options hashmap. + * @param {object} options.didDocument - DID Document (retrieved via a + * `.get()` or from some other source). + * @param {string} options.purpose - Verification method purpose, such as + * 'authentication', 'assertionMethod', 'keyAgreement' and so on. + * + * @returns {object} Returns the public key object (obtained from the DID + * Document), without a `@context`. + */ + publicMethodFor({didDocument, purpose} = {}) { + if(!didDocument) { + throw new TypeError('The "didDocument" parameter is required.'); + } + if(!purpose) { + throw new TypeError('The "purpose" parameter is required.'); + } + + const method = _digitalcredentials_did_io__WEBPACK_IMPORTED_MODULE_0__.findVerificationMethod({doc: didDocument, purpose}); + if(!method) { + throw new Error(`No verification method found for purpose "${purpose}"`); + } + return method; + } + + /** + * Returns a `did:key` method DID Document for a given DID, or a key document + * for a given DID URL (key id). + * Either a `did` or `url` param is required. + * + * @example + * await resolver.get({did}); // -> did document + * await resolver.get({url: keyId}); // -> public key node + * + * @param {object} options - Options hashmap. + * @param {string} [options.did] - DID URL or a key id (either an ed25519 key + * or an x25519 key-agreement key id). + * @param {string} [options.url] - Alias for the `did` url param, supported + * for better readability of invoking code. + * + * @returns {Promise} Resolves to a DID Document or a + * public key node with context. + */ + async get({did, url} = {}) { + did = did || url; + if(!did) { + throw new TypeError('"did" must be a string.'); + } + const [didAuthority, keyIdFragment] = did.split('#'); + const publicKeyMultibase = didAuthority.substring('did:key:'.length); + // get the multikey header from the public key value + const multibaseMultikeyHeader = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.getMultibaseMultikeyHeader)({ + value: publicKeyMultibase + }); + + const fromMultibase = + this._allowedKeyTypes.get(multibaseMultikeyHeader); + if(!fromMultibase) { + throw new Error( + `Unsupported "multibaseMultikeyHeader", "${multibaseMultikeyHeader}".`); + } + const {keyAgreementKeyPair, keyPair} = await (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.getKeyPair)({ + fromMultibase, publicKeyMultibase + }); + const {didDocument} = await this._keyPairToDidDocument({ + keyPair, keyAgreementKeyPair + }); + + if(keyIdFragment) { + // resolve an individual key + return (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.getKey)({didDocument, keyIdFragment}); + } + // Resolve the full DID Document + return didDocument; + } + + /** + * Converts a public key object to a `did:key` method DID Document. + * Note that unlike `generate()`, a `keyPairs` map is not returned. Use + * `publicMethodFor()` to fetch keys for particular proof purposes. + * + * @param {object} options - Options hashmap. + * @param {object} options.publicKeyDescription - Public key object + * used to generate the DID document (either an LDKeyPair instance + * containing public key material, or a "key description" plain object + * (such as that generated from a KMS)). + * + * @returns {Promise} Resolves with the generated DID Document. + */ + async publicKeyToDidDoc({publicKeyDescription} = {}) { + const { + keyPair, keyAgreementKeyPair + } = await (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.getKeyPair)({publicKeyDescription}); + const {didDocument} = await this._keyPairToDidDocument({ + keyPair, keyAgreementKeyPair + }); + return {didDocument}; + } + + /** + * Converts an Ed25519KeyPair object to a `did:key` method DID Document. + * + * @param {object} options - Options hashmap. + * @param {object} options.keyPair - Key used to generate the DID + * document (either an LDKeyPair instance containing public key material, + * or a "key description" plain object (such as that generated from a KMS)). + * @param {object} [options.keyAgreementKeyPair] - Optional + * keyAgreement key pair for generating did for keyAgreement. + * @returns {Promise<{didDocument: object, keyPairs: Map}>} + * Resolves with the generated DID Document, along with the corresponding + * key pairs used to generate it (for storage in a KMS). + */ + async _keyPairToDidDocument({keyPair, keyAgreementKeyPair} = {}) { + const keyPairs = new Map(); + let didDocument; + let publicDhKey; + const contexts = [DID_CONTEXT_URL]; + if(!keyPair && keyAgreementKeyPair) { + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.addKeyAgreementKeyContext)({contexts, keyAgreementKeyPair}); + const did = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.getDid)({keyPair: keyAgreementKeyPair}); + keyAgreementKeyPair.controller = did; + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.setKeyPairId)({keyPair: keyAgreementKeyPair, did}); + publicDhKey = await keyAgreementKeyPair.export({publicKey: true}); + keyPairs.set(keyAgreementKeyPair.id, keyAgreementKeyPair); + didDocument = { + '@context': contexts, + id: did, + keyAgreement: [publicDhKey] + }; + return {didDocument, keyPairs}; + } + let {publicKeyMultibase} = keyPair; + + if(!publicKeyMultibase && keyPair.publicKeyBase58) { + // handle backwards compatibility w/older key pair interfaces + publicKeyMultibase = await keyPair.fingerprint(); + } + // get the multibaseMultikeyHeader from the public key value + const multibaseMultikeyHeader = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.getMultibaseMultikeyHeader)({ + value: publicKeyMultibase + }); + const fromMultibase = this._allowedKeyTypes.get(multibaseMultikeyHeader); + if(!fromMultibase) { + throw new Error( + `Unsupported "multibaseMultikeyHeader", "${multibaseMultikeyHeader}".`); + } + const verificationKeyPair = await fromMultibase({publicKeyMultibase}); + const did = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.getDid)({keyPair: verificationKeyPair}); + verificationKeyPair.controller = did; + // Now set the source key's id + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.setKeyPairId)({keyPair: verificationKeyPair, did}); + // get the public components of verification keypair + const verificationPublicKey = await verificationKeyPair.export({ + publicKey: true, + includeContext: true + }); + + contexts.push(verificationPublicKey['@context']); + // delete context from verificationPublicKey + delete verificationPublicKey['@context']; + // get the keyAgreement keypair + if(!keyAgreementKeyPair) { + ({keyAgreementKeyPair} = await (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.getKeyAgreementKeyPair)({ + contexts, verificationPublicKey + })); + } + + // get the public components of keyAgreement keypair + if(keyAgreementKeyPair) { + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.addKeyAgreementKeyContext)({contexts, keyAgreementKeyPair}); + const did = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.getDid)({keyPair: keyAgreementKeyPair}); + if(!keyAgreementKeyPair.controller) { + keyAgreementKeyPair.controller = did; + } + if(!keyAgreementKeyPair.id) { + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.setKeyPairId)({keyPair: keyAgreementKeyPair, did}); + } + publicDhKey = await keyAgreementKeyPair.export({publicKey: true}); + } + + // Compose the DID Document + didDocument = { + // Note that did:key does not have its own method-specific context, + // and only uses the general DID Core context, and key-specific contexts. + '@context': contexts, + id: did, + verificationMethod: [verificationPublicKey], + authentication: [verificationPublicKey.id], + assertionMethod: [verificationPublicKey.id], + capabilityDelegation: [verificationPublicKey.id], + capabilityInvocation: [verificationPublicKey.id], + }; + if(publicDhKey) { + didDocument.keyAgreement = [publicDhKey]; + } + // create the key pairs map + keyPairs.set(verificationKeyPair.id, verificationKeyPair); + if(keyAgreementKeyPair) { + keyPairs.set(keyAgreementKeyPair.id, keyAgreementKeyPair); + } + + return {didDocument, keyPairs}; + } + + /** + * Computes and returns the id of a given key pair. Used by `did-io` drivers. + * + * @param {object} options - Options hashmap. + * @param {object} options.keyPair - The key pair used when computing the + * identifier. + * + * @returns {string} Returns the key's id. + */ + async computeId({keyPair}) { + return `did:key:${keyPair.fingerprint()}#${keyPair.fingerprint()}`; + } +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-key/lib/helpers.js" +/*!************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-key/lib/helpers.js ***! + \************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ addKeyAgreementKeyContext: () => (/* binding */ addKeyAgreementKeyContext), +/* harmony export */ getDid: () => (/* binding */ getDid), +/* harmony export */ getKey: () => (/* binding */ getKey), +/* harmony export */ getKeyAgreementKeyPair: () => (/* binding */ getKeyAgreementKeyPair), +/* harmony export */ getKeyPair: () => (/* binding */ getKeyPair), +/* harmony export */ getMultibaseMultikeyHeader: () => (/* binding */ getMultibaseMultikeyHeader), +/* harmony export */ setKeyPairId: () => (/* binding */ setKeyPairId) +/* harmony export */ }); +/* harmony import */ var _digitalcredentials_x25519_key_agreement_key_2020__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @digitalcredentials/x25519-key-agreement-key-2020 */ "./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/esm/index.js"); +/*! + * Copyright (c) 2023 Digital Bazaar, Inc. All rights reserved. + */ + + +const ED25519_KEY_2020_CONTEXT_URL = + 'https://w3id.org/security/suites/ed25519-2020/v1'; +const MULTIKEY_CONTEXT_V1_URL = 'https://w3id.org/security/multikey/v1'; + +const contextsBySuite = new Map([ + ['Ed25519VerificationKey2020', ED25519_KEY_2020_CONTEXT_URL], + ['Multikey', MULTIKEY_CONTEXT_V1_URL], + [_digitalcredentials_x25519_key_agreement_key_2020__WEBPACK_IMPORTED_MODULE_0__.X25519KeyAgreementKey2020.suite, _digitalcredentials_x25519_key_agreement_key_2020__WEBPACK_IMPORTED_MODULE_0__.X25519KeyAgreementKey2020.SUITE_CONTEXT] +]); + +/** + * Returns the public key object for a given key id fragment. + * + * @param {object} options - Options hashmap. + * @param {object} options.didDocument - The DID Document to use when generating + * the id. + * @param {string} options.keyIdFragment - The key identifier fragment. + * + * @returns {object} Returns the public key node, with `@context`. + */ +function getKey({didDocument, keyIdFragment}) { + // Determine if the key id fragment belongs to the "main" public key, + // or the keyAgreement key + const keyId = didDocument.id + '#' + keyIdFragment; + let publicKey; + if(didDocument.verificationMethod?.[0].id === keyId) { + // Return the public key node for the main public key + publicKey = didDocument.verificationMethod[0]; + } else { + // Return the public key node for the X25519 key-agreement key + publicKey = didDocument.keyAgreement[0]; + } + + return { + '@context': contextsBySuite.get(publicKey.type), + ...publicKey + }; +} + +function getDid({keyPair}) { + return keyPair.fingerprint ? `did:key:${keyPair.fingerprint()}` : + `did:key:${keyPair.publicKeyMultibase}`; +} + +function setKeyPairId({keyPair, did}) { + keyPair.id = keyPair.fingerprint ? `${did}#${keyPair.fingerprint()}` : + `${did}#${keyPair.publicKeyMultibase}`; +} + +function getKeyAgreementKeyPair({contexts, verificationPublicKey}) { + // The KAK pair will use the source key's controller, but may generate + // its own .id + let keyAgreementKeyPair; + + switch(verificationPublicKey.type) { + case 'Ed25519VerificationKey2020': { + keyAgreementKeyPair = _digitalcredentials_x25519_key_agreement_key_2020__WEBPACK_IMPORTED_MODULE_0__.X25519KeyAgreementKey2020 + .fromEd25519VerificationKey2020({keyPair: verificationPublicKey}); + contexts.push(_digitalcredentials_x25519_key_agreement_key_2020__WEBPACK_IMPORTED_MODULE_0__.X25519KeyAgreementKey2020.SUITE_CONTEXT); + break; + } + case 'Multikey': { + // FIXME: Add keyAgreementKeyPair interface for Multikey. + break; + } + default: { + throw new Error( + `Cannot derive key agreement key from verification key type + "${verificationPublicKey.type}".`); + } + } + return {keyAgreementKeyPair}; +} + +function getMultibaseMultikeyHeader({value}) { + if(!value) { + throw new TypeError('"publicKeyMultibase" must be a string.'); + } + return value.slice(0, 4); +} + +function addKeyAgreementKeyContext({contexts, keyAgreementKeyPair}) { + const {type} = keyAgreementKeyPair; + switch(type) { + case 'X25519KeyAgreementKey2020': { + if(!contexts.includes(_digitalcredentials_x25519_key_agreement_key_2020__WEBPACK_IMPORTED_MODULE_0__.X25519KeyAgreementKey2020.SUITE_CONTEXT)) { + contexts.push(_digitalcredentials_x25519_key_agreement_key_2020__WEBPACK_IMPORTED_MODULE_0__.X25519KeyAgreementKey2020.SUITE_CONTEXT); + } + break; + } + default: { + throw new Error(`Unsupported key agreement key type, "${type}".`); + } + } +} + +async function getKeyPair({ + fromMultibase, publicKeyMultibase, publicKeyDescription +} = {}) { + let keyPair; + if(fromMultibase && publicKeyMultibase) { + keyPair = await fromMultibase({publicKeyMultibase}); + } else { + keyPair = publicKeyDescription; + } + const {type} = keyPair; + let keyAgreementKeyPair; + if(type === 'X25519KeyAgreementKey2020') { + keyAgreementKeyPair = keyPair; + keyPair = null; + } + return {keyPair, keyAgreementKeyPair}; +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-key/lib/index.js" +/*!**********************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-key/lib/index.js ***! + \**********************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ DidKeyDriver: () => (/* reexport safe */ _DidKeyDriver_js__WEBPACK_IMPORTED_MODULE_1__.DidKeyDriver), +/* harmony export */ createFromMultibase: () => (/* reexport safe */ _util_js__WEBPACK_IMPORTED_MODULE_0__.createFromMultibase), +/* harmony export */ driver: () => (/* binding */ driver) +/* harmony export */ }); +/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util.js */ "./node_modules/@digitalcredentials/did-method-key/lib/util.js"); +/* harmony import */ var _DidKeyDriver_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DidKeyDriver.js */ "./node_modules/@digitalcredentials/did-method-key/lib/DidKeyDriver.js"); +/*! + * Copyright (c) 2021-2023 Digital Bazaar, Inc. All rights reserved. + */ + + + +/** + * Helper method to match the `.driver()` API of other `did-io` plugins. + * + * @returns {DidKeyDriver} Returns an instance of a did:key resolver driver. + */ +function driver() { + return new _DidKeyDriver_js__WEBPACK_IMPORTED_MODULE_1__.DidKeyDriver(); +} + + + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-key/lib/util.js" +/*!*********************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-key/lib/util.js ***! + \*********************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ createFromMultibase: () => (/* binding */ createFromMultibase) +/* harmony export */ }); +/*! + * Copyright (c) 2023 Digital Bazaar, Inc. All rights reserved. + */ + +/** + * A utility function to create a multibase-multikey deserializer function. + * + * @param {object} options - Options hashmap. + * @param {Function} options.fromFingerprint - A method that creates a KeyPair + * from a key fingerprint. + * + * @returns {Function} - Multibase-multikey deserializer. + */ +function createFromMultibase({fromFingerprint}) { + return async function fromMultibase({publicKeyMultibase}) { + return fromFingerprint({fingerprint: publicKeyMultibase}); + }; +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/X25519KeyAgreementKey2020.js" +/*!**********************************************************************************************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/X25519KeyAgreementKey2020.js ***! + \**********************************************************************************************************************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var cryptoLd = __webpack_require__(/*! crypto-ld */ "./node_modules/crypto-ld/lib/index.js"); +var ed2curve = __webpack_require__(/*! ed2curve */ "./node_modules/ed2curve/ed2curve.js"); +var base58btc = __webpack_require__(/*! @digitalcredentials/base58-universal */ "./node_modules/@digitalcredentials/base58-universal/dist/index.js"); +var crypto = __webpack_require__(/*! ./crypto.js */ "./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/crypto-browser.js"); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { + return e[k]; + } + }); + } + }); + } + n['default'] = e; + return Object.freeze(n); +} + +var ed2curve__default = /*#__PURE__*/_interopDefaultLegacy(ed2curve); +var base58btc__namespace = /*#__PURE__*/_interopNamespace(base58btc); + +/*! + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */ + +const SUITE_ID = 'X25519KeyAgreementKey2020'; +// multibase base58-btc header +const MULTIBASE_BASE58BTC_HEADER = 'z'; +// multicodec ed25519-pub header as varint +const MULTICODEC_ED25519_PUB_HEADER = new Uint8Array([0xed, 0x01]); +// multicodec ed25519-priv header as varint +const MULTICODEC_ED25519_PRIV_HEADER = new Uint8Array([0x80, 0x26]); +// multicodec x25519-pub header as varint +const MULTICODEC_X25519_PUB_HEADER = new Uint8Array([0xec, 0x01]); +// multicodec x25519-priv header as varint +const MULTICODEC_X25519_PRIV_HEADER = new Uint8Array([0x82, 0x26]); + +class X25519KeyAgreementKey2020 extends cryptoLd.LDKeyPair { + /** + * @param {object} options - Options hashmap. + * @param {string} options.controller - Controller DID or document url. + * @param {string} [options.id] - Key ID, typically composed of controller + * URL and key fingerprint as hash fragment. + * @param {string} options.publicKeyMultibase - Multibase encoded public key. + * @param {string} [options.privateKeyMultibase] - Multibase private key. + * @param {string} [options.revoked] - Timestamp of when the key has been + * revoked, in RFC3339 format. If not present, the key itself is considered + * not revoked. Note that this mechanism is slightly different than DID + * Document key revocation, where a DID controller can revoke a key from + * that DID by removing it from the DID Document. + */ + constructor(options = {}) { + super(options); + this.type = SUITE_ID; + const {publicKeyMultibase, privateKeyMultibase} = options; + + if(!publicKeyMultibase) { + throw new TypeError('The "publicKeyMultibase" property is required.'); + } + + if(!publicKeyMultibase || !_isValidKeyHeader( + publicKeyMultibase, MULTICODEC_X25519_PUB_HEADER)) { + throw new Error( + '"publicKeyMultibase" has invalid header bytes: ' + + `"${publicKeyMultibase}".`); + } + + if(privateKeyMultibase && !_isValidKeyHeader( + privateKeyMultibase, MULTICODEC_X25519_PRIV_HEADER)) { + throw new Error('"privateKeyMultibase" has invalid header bytes.'); + } + + // assign valid key values + this.publicKeyMultibase = publicKeyMultibase; + this.privateKeyMultibase = privateKeyMultibase; + + if(this.controller && !this.id) { + this.id = `${this.controller}#${this.fingerprint()}`; + } + } + + /** + * Generates a new public/private X25519 Key Pair. + * + * @param {object} [options={}] - Keypair options (see controller docstring). + * + * @returns {Promise} Generated key pair. + */ + static async generate(options = {}) { + const {publicKey, privateKey} = await crypto.generateKeyPair(); + + return new X25519KeyAgreementKey2020({ + publicKeyMultibase: + _multibaseEncode(MULTICODEC_X25519_PUB_HEADER, publicKey), + privateKeyMultibase: + _multibaseEncode(MULTICODEC_X25519_PRIV_HEADER, privateKey), + ...options + }); + } + + /** + * Creates an X25519KeyAgreementKey2020 Key Pair from an existing key + * (constructor method). + * + * @param {object} [options={}] - Keypair options (see controller docstring). + * + * @returns {X25519KeyAgreementKey2020} An X25519 Key Pair. + */ + static async from(options = {}) { + // Check to see if this is an X25519KeyAgreementKey2019 + if(options.publicKeyBase58) { + // Convert it to a 2020 key pair instance + return this.fromX25519KeyAgreementKey2019(options); + } + return new X25519KeyAgreementKey2020(options); + } + + /** + * Creates an X25519KeyAgreementKey2020 Key Pair from an existing 2019 key + * (backwards compatibility method). + * + * @param {object} [options={}] - Options hashmap. + * @param {string} options.publicKeyBase58 - Base58btc encoded public key. + * @param {string} [options.privateKeyBase58] - Base58btc encoded private key. + * @param {object} [options.keyPairOptions] - Other options. + * + * @returns {Promise} 2020 Crypto suite key pair. + */ + static async fromX25519KeyAgreementKey2019({ + publicKeyBase58, privateKeyBase58, ...keyPairOptions + } = {}) { + let publicKeyMultibase; + let privateKeyMultibase; + + if(publicKeyBase58) { + // prefix with `z` to indicate multi-base base58btc encoding + publicKeyMultibase = _multibaseEncode( + MULTICODEC_X25519_PUB_HEADER, base58btc__namespace.decode(publicKeyBase58)); + } + if(privateKeyBase58) { + // prefix with `z` to indicate multi-base base58btc encoding + privateKeyMultibase = _multibaseEncode( + MULTICODEC_X25519_PRIV_HEADER, base58btc__namespace.decode(privateKeyBase58)); + } + return new X25519KeyAgreementKey2020({ + publicKeyMultibase, privateKeyMultibase, ...keyPairOptions + }); + } + + /** + * Converts a keypair instance of type Ed25519VerificationKey2020 to an + * instance of this class. + * + * @see https://github.com/digitalbazaar/ed25519-verification-key-2020 + * + * @param {object} [options={}] - Options hashmap. + * + * @typedef {object} Ed25519VerificationKey2020 + * @param {Ed25519VerificationKey2020} options.keyPair - Source key pair. + * + * @returns {X25519KeyAgreementKey2020} A derived/converted key agreement + * key pair. + */ + static fromEd25519VerificationKey2020({keyPair} = {}) { + if(!keyPair.publicKeyMultibase) { + throw new Error('Source public key is required to convert.'); + } + + if(!keyPair.publicKeyMultibase.startsWith(MULTIBASE_BASE58BTC_HEADER)) { + throw new TypeError( + 'Expecting "publicKeyMultibase" value to be multibase base58btc ' + + 'encoded (must start with "z").' + ); + } + + const xKey = new X25519KeyAgreementKey2020({ + controller: keyPair.controller, + publicKeyMultibase: X25519KeyAgreementKey2020 + .convertFromEdPublicKey(keyPair) + }); + + if(keyPair.privateKeyMultibase) { + if(!keyPair.privateKeyMultibase.startsWith(MULTIBASE_BASE58BTC_HEADER)) { + throw new TypeError( + 'Expecting "privateKeyMultibase" value to be multibase base58btc ' + + 'encoded (must start with "z").' + ); + } + + xKey.privateKeyMultibase = X25519KeyAgreementKey2020 + .convertFromEdPrivateKey(keyPair); + } + + return xKey; + } + + /** + * @param {object} [options={}] - Options hashmap. + * @param {string} options.publicKeyMultibase - Multibase encoded Ed25519 + * public key. + * + * @returns {string} Multibase encoded converted X25519 Public key. + */ + static convertFromEdPublicKey({publicKeyMultibase} = {}) { + if(!publicKeyMultibase) { + throw new Error('Source public key is required to convert.'); + } + + const edPubkeyBytes = + _multibaseDecode(MULTICODEC_ED25519_PUB_HEADER, publicKeyMultibase); + + // Converts a 32-byte Ed25519 public key into a 32-byte Curve25519 key + // Returns null if the given public key in not a valid Ed25519 public key. + const dhPubkeyBytes = ed2curve__default['default'].convertPublicKey(edPubkeyBytes); + if(!dhPubkeyBytes) { + throw new Error( + 'Error converting to X25519; Invalid Ed25519 public key.'); + } + return _multibaseEncode(MULTICODEC_X25519_PUB_HEADER, dhPubkeyBytes); + } + + /** + * @param {object} [options={}] - Options hashmap. + * @param {string} options.privateKeyMultibase - Multibase encoded Ed25519 + * private key. + * + * @returns {string} Multibase encoded converted X25519 Private key. + */ + static convertFromEdPrivateKey({privateKeyMultibase} = {}) { + if(!privateKeyMultibase) { + throw new Error('Source private key is required to convert.'); + } + + const edPrivkeyBytes = + _multibaseDecode(MULTICODEC_ED25519_PRIV_HEADER, privateKeyMultibase); + // Converts a 64-byte Ed25519 secret key (or just the first 32-byte part of + // it, which is the secret value) into a 32-byte Curve25519 secret key + const dhPrivkeyBytes = ed2curve__default['default'].convertSecretKey(edPrivkeyBytes); + if(!dhPrivkeyBytes) { + throw new Error( + 'Error converting to X25519; Invalid Ed25519 private key.'); + } + return _multibaseEncode(MULTICODEC_X25519_PRIV_HEADER, dhPrivkeyBytes); + } + + /** + * Exports the serialized representation of the KeyPair. + * + * @param {object} [options={}] - Options hashmap. + * @param {boolean} [options.publicKey] - Export public key material? + * @param {boolean} [options.privateKey] - Export private key material? + * @param {boolean} [options.includeContext] - Include JSON-LD context? + * + * @returns {object} A plain js object that's ready for serialization + * (to JSON, etc), for use in DIDs etc. + */ + export({publicKey = false, privateKey = false, includeContext = false} = {}) { + if(!(publicKey || privateKey)) { + throw new TypeError( + 'Export requires specifying either "publicKey" or "privateKey".'); + } + const exportedKey = { + id: this.id, + type: this.type + }; + if(includeContext) { + exportedKey['@context'] = X25519KeyAgreementKey2020.SUITE_CONTEXT; + } + if(this.controller) { + exportedKey.controller = this.controller; + } + if(publicKey) { + exportedKey.publicKeyMultibase = this.publicKeyMultibase; + } + if(privateKey) { + exportedKey.privateKeyMultibase = this.privateKeyMultibase; + } + if(this.revoked) { + exportedKey.revoked = this.revoked; + } + return exportedKey; + } + + /** + * Generates and returns a base58btc multibase encoded value of a multicodec + * X25519 public key fingerprint (for use with cryptonyms, for example). + * + * @see https://github.com/multiformats/multicodec + * @see https://github.com/multiformats/multibase + * + * @param {object} [options={}] - Options hashmap. + * @param {string} options.publicKeyMultibase - Multibase encoded public key. + * + * @returns {string} The fingerprint. + */ + static fingerprintFromPublicKey({publicKeyMultibase} = {}) { + if(!publicKeyMultibase) { + throw new Error('Source public key is required.'); + } + + return publicKeyMultibase; + } + + /** + * Creates an instance of X25519KeyAgreementKey2020 from a key fingerprint. + * + * @param {object} [options={}] - Options hashmap. + * @param {string} options.fingerprint - Public key fingerprint. + * + * @returns {X25519KeyAgreementKey2020} Key pair instance (public key material + * only) created from the fingerprint. + */ + static fromFingerprint({fingerprint} = {}) { + return new X25519KeyAgreementKey2020({ + publicKeyMultibase: fingerprint + }); + } + + /** + * Derives a shared secret via a given public key, typically for use + * as one parameter for computing a shared key. It should not be used as + * a shared key itself, but rather as an input into a key derivation function + * (KDF) to produce a shared key. + * + * @param {object} [options={}] - Options hashmap. + * @param {LDKeyPair} options.publicKey - Remote key pair. + * + * @returns {Promise} Derived secret. + */ + async deriveSecret({publicKey}) { + const remotePublicKey = _multibaseDecode( + MULTICODEC_X25519_PUB_HEADER, publicKey.publicKeyMultibase); + const privateKey = _multibaseDecode( + MULTICODEC_X25519_PRIV_HEADER, this.privateKeyMultibase); + + return crypto.deriveSecret({privateKey, remotePublicKey}); + } + + /** + * Generates and returns a multiformats encoded + * X25519 public key fingerprint (for use with cryptonyms, for example). + * + * @see https://github.com/multiformats/multicodec + * + * @returns {string} The fingerprint. + */ + fingerprint() { + return this.publicKeyMultibase; + } + + /** + * Tests whether the fingerprint was generated from a given key pair. + * + * @example + * xKeyPair.verifyFingerprint('...'); + * // {valid: true}; + * + * @param {object} [options={}] - Options hashmap. + * @param {string} options.fingerprint - An x25519 key fingerprint (typically + * from a key id). + * + * @returns {object} An object indicating valid is true or false. + */ + verifyFingerprint({fingerprint} = {}) { + // fingerprint should have `z` prefix indicating + // that it's base58btc multibase encoded + if(!_isValidKeyHeader(fingerprint, MULTICODEC_X25519_PUB_HEADER)) { + throw new Error( + `"fingerprint" has invalid header bytes: "${fingerprint}".`); + } + + return {valid: true}; + } +} + +// Used by CryptoLD harness for dispatching. +X25519KeyAgreementKey2020.suite = SUITE_ID; +// Used by CryptoLD harness's fromKeyId() method. +X25519KeyAgreementKey2020.SUITE_CONTEXT = + 'https://w3id.org/security/suites/x25519-2020/v1'; + +/** + * Checks to see if the given value is a valid multibase encoded key. + * + * @param {Uint8Array} multibaseKey - The multibase-encoded key value. + * @param {Uint8Array} expectedHeader - The expected header for the key value. + * @returns {boolean} Returns true if the header is valid, false otherwise. + */ +function _isValidKeyHeader(multibaseKey, expectedHeader) { + if(!(typeof multibaseKey === 'string' && + multibaseKey[0] === MULTIBASE_BASE58BTC_HEADER)) { + return false; + } + + const keyBytes = base58btc__namespace.decode(multibaseKey.slice(1)); + return expectedHeader.every((val, i) => keyBytes[i] === val); +} + +/** + * Encodes a given Uint8Array to multibase-encoded string. + * + * @param {Uint8Array} header - Multicodec header to prepend to the bytes. + * @param {Uint8Array} bytes - Bytes to encode. + * @returns {string} Multibase-encoded string. + */ +function _multibaseEncode(header, bytes) { + const mcBytes = new Uint8Array(header.length + bytes.length); + + mcBytes.set(header); + mcBytes.set(bytes, header.length); + + return MULTIBASE_BASE58BTC_HEADER + base58btc__namespace.encode(mcBytes); +} + +/** + * Decodes a given string as a multibase-encoded multicodec value. + * + * @param {Uint8Array} header - Expected header bytes for the multicodec value. + * @param {string} text - Multibase encoded string to decode. + * @returns {Uint8Array} Decoded bytes. + */ +function _multibaseDecode(header, text) { + const mcValue = base58btc__namespace.decode(text.substr(1)); + + if(!header.every((val, i) => mcValue[i] === val)) { + throw new Error('Multibase value does not have expected header.'); + } + + return mcValue.slice(header.length); +} + +exports.X25519KeyAgreementKey2020 = X25519KeyAgreementKey2020; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/crypto-browser.js" +/*!***********************************************************************************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/crypto-browser.js ***! + \***********************************************************************************************************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var cryptoNacl = __webpack_require__(/*! ./crypto-nacl.js */ "./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/crypto-nacl.js"); + + + +exports.deriveSecret = cryptoNacl.deriveSecret; +exports.generateKeyPair = cryptoNacl.generateKeyPair; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/crypto-nacl.js" +/*!********************************************************************************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/crypto-nacl.js ***! + \********************************************************************************************************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var nacl = __webpack_require__(/*! tweetnacl */ "./node_modules/tweetnacl/nacl-fast.js"); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var nacl__default = /*#__PURE__*/_interopDefaultLegacy(nacl); + +/*! + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */ + +/** + * Note: The following two functions are async to match the signature of + * their native Node.js counterparts (see './crypto.js'). + */ + +async function deriveSecret({privateKey, remotePublicKey}) { + return nacl__default['default'].scalarMult(privateKey, remotePublicKey); +} + +async function generateKeyPair() { + // Each is a Uint8Array with 32-byte key + const {publicKey, secretKey: privateKey} = nacl__default['default'].box.keyPair(); + return {publicKey, privateKey}; +} + +exports.deriveSecret = deriveSecret; +exports.generateKeyPair = generateKeyPair; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/esm/index.js" +/*!******************************************************************************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/esm/index.js ***! + \******************************************************************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ X25519KeyAgreementKey2020: () => (/* binding */ X25519KeyAgreementKey2020) +/* harmony export */ }); +/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index.js */ "./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/index.js"); + +const X25519KeyAgreementKey2020 = _index_js__WEBPACK_IMPORTED_MODULE_0__.X25519KeyAgreementKey2020; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/index.js" +/*!**************************************************************************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/index.js ***! + \**************************************************************************************************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var X25519KeyAgreementKey2020 = __webpack_require__(/*! ./X25519KeyAgreementKey2020.js */ "./node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020/dist/X25519KeyAgreementKey2020.js"); + + + +exports.X25519KeyAgreementKey2020 = X25519KeyAgreementKey2020.X25519KeyAgreementKey2020; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-web/lib/DidWebDriver.js" +/*!*****************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-web/lib/DidWebDriver.js ***! + \*****************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ DidWebDriver: () => (/* binding */ DidWebDriver) +/* harmony export */ }); +/* harmony import */ var _digitalcredentials_did_io__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @digitalcredentials/did-io */ "./node_modules/@digitalcredentials/did-io/dist/esm/index.js"); +/* harmony import */ var _helpers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./helpers.js */ "./node_modules/@digitalcredentials/did-method-web/lib/helpers.js"); +/* harmony import */ var _assertions_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./assertions.js */ "./node_modules/@digitalcredentials/did-method-web/lib/assertions.js"); +/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constants.js */ "./node_modules/@digitalcredentials/did-method-web/lib/constants.js"); +/* harmony import */ var _digitalcredentials_did_method_key__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @digitalcredentials/did-method-key */ "./node_modules/@digitalcredentials/did-method-key/lib/index.js"); +/* harmony import */ var _digitalcredentials_http_client__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @digitalcredentials/http-client */ "./node_modules/@digitalcredentials/http-client/dist/esm/index.js"); +/*! + * Copyright (c) 2023-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + + + + + +class DidWebDriver { + /** + * @param {object} options - Options object. + * @param {object} [options.fetchOptions = defaultFetchOptions] - Options for + * the http client requests. + * @param {Array} [options.allowList = []] - A list of allowed + * domains. + */ + constructor({ + fetchOptions = _constants_js__WEBPACK_IMPORTED_MODULE_3__.defaultFetchOptions, + allowList = [] + } = {}) { + // used by did-io to register drivers + this.method = 'web'; + this.fetchOptions = fetchOptions; + this.allowList = allowList; + this.didKeyDriver = (0,_digitalcredentials_did_method_key__WEBPACK_IMPORTED_MODULE_4__.driver)(); + } + + /** + * Registers a multibase-multikey header and a multibase-multikey + * deserializer that is allowed to handle data using that header. + * + * @param {object} options - Options hashmap. + * + * @param {string} options.multibaseMultikeyHeader - The multibase-multikey + * header to register. + * @param {Function} options.fromMultibase - A function that converts a + * `{publicKeyMultibase}` value into a key pair interface. + */ + use({multibaseMultikeyHeader, fromMultibase} = {}) { + this.didKeyDriver.use({multibaseMultikeyHeader, fromMultibase}); + } + + /** + * Generates a new `did:web` method DID Document from a KeyPair. + * + * @param {object} options - Options hashmap. + * @param {URL} options.url - The HTTPS url of the DID document. + * @param {object} options.verificationKeyPair - A verification KeyPair. + * @param {object} [options.keyAgreementKeyPair] - A keyAgreement KeyPair. + * + * @returns {Promise<{didDocument: object, keyPairs: Map, + * methodFor: Function}>} Resolves with the generated DID Document, along + * with the corresponding key pairs used to generate it (for storage in a + * KMS). + */ + async fromKeyPair({url, verificationKeyPair, keyAgreementKeyPair} = {}) { + (0,_assertions_js__WEBPACK_IMPORTED_MODULE_2__.assertDomain)({allowList: this.allowList, url}); + + const {didDocument, keyPairs} = await this.didKeyDriver.fromKeyPair({ + verificationKeyPair, keyAgreementKeyPair + }); + + // update `didDocument` using url-based DID + const {did} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.httpsUrlToDidUrl)(url); + didDocument.id = did; + + // replace all other `did:key` occurrences + for(const [key, value] of Object.entries(didDocument)) { + if(Array.isArray(value)) { + for(const [i, e] of value.entries()) { + if(typeof e?.id === 'string' && e.id.startsWith('did:key:')) { + e.id = _replaceDidKeyIdWithDidWebId(did, e.id); + if(e?.controller?.startsWith('did:key:')) { + e.controller = did; + } + } else if(typeof e === 'string' && e.startsWith('did:key:')) { + value[i] = _replaceDidKeyIdWithDidWebId(did, e); + } + } + } else if(value?.id === 'string' && value.id.startsWith('did:key:')) { + value.id = _replaceDidKeyIdWithDidWebId(did, value.id); + if(value?.controller?.startsWith('did:key:')) { + value.controller = did; + } + } else if(typeof value === 'string' && value.startsWith('did:key:')) { + didDocument[key] = _replaceDidKeyIdWithDidWebId(did, value); + } + } + + // update each `keyPair` + const newKeyPairs = new Map(); + for(const [key, value] of keyPairs) { + const fragmentIdx = key.indexOf('#'); + value.id = did + key.slice(fragmentIdx); + value.controller = did; + newKeyPairs.set(value.id, value); + } + + // convenience function that returns the public/private key pair instance + // for a given purpose (authentication, assertionMethod, keyAgreement, etc). + const methodFor = ({purpose}) => { + const {id: methodId} = this.publicMethodFor({didDocument, purpose}); + return newKeyPairs.get(methodId); + }; + return {didDocument, keyPairs: newKeyPairs, methodFor}; + } + + /** + * Returns the public key (verification method) object for a given DID + * Document and purpose. Useful in conjunction with a `.get()` call. + * + * @example + * const didDocument = await didWebDriver.get({did}); + * const authKeyData = didDriver.publicMethodFor({ + * didDocument, purpose: 'authentication' + * }); + * // you can then create a suite instance object to verify signatures etc. + * const keyPair = await EcdsaMultikey.from(authKeyData); + * const {verify} = authPublicKey.verifier(); + * + * @param {object} options - Options object. + * @param {object} options.didDocument - DID Document (retrieved via a + * `.get()` or from some other source). + * @param {string} options.purpose - Verification method purpose, such as + * 'authentication', 'assertionMethod', 'keyAgreement' and so on. + * + * @returns {object} Returns the public key object (obtained from the DID + * Document), without a `@context`. + */ + publicMethodFor({didDocument, purpose} = {}) { + if(!didDocument) { + throw new TypeError('The "didDocument" parameter is required.'); + } + if(!purpose) { + throw new TypeError('The "purpose" parameter is required.'); + } + + const method = _digitalcredentials_did_io__WEBPACK_IMPORTED_MODULE_0__.findVerificationMethod({doc: didDocument, purpose}); + if(!method) { + throw new Error(`No verification method found for purpose "${purpose}"`); + } + return method; + } + + /** + * Returns a `did:web` method DID Document for a given DID, or a key document + * for a given DID URL (key id). + * Either a `did` or `url` param is required. + * + * @example + * await resolver.get({did}); // -> did document + * await resolver.get({url: keyId}); // -> public key node + * + * @param {object} options - Options object. + * @param {string} [options.did] - DID URL (which can be a bare DID). + * @param {string} [options.url] - Alias for the `did` url param, supported + * for better readability of invoking code. + * @param {object} [options.fetchOptions = {}] - Options for the request. + * + * @returns {Promise} Resolves to a DID Document or a + * public key node with context. + */ + async get({did, url, fetchOptions = {}} = {}) { + did = did || url; + // checks the DID is a valid did:web url then produces an HTTPS url + const {baseUrl, fragment} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.didUrlToHttpsUrl)(did); + // ensures the domain is allowed + (0,_assertions_js__WEBPACK_IMPORTED_MODULE_2__.assertDomain)({allowList: this.allowList, url: baseUrl}); + // overwrite global options with request specific options + const requestOptions = {...this.fetchOptions, ...fetchOptions}; + const {data} = await _digitalcredentials_http_client__WEBPACK_IMPORTED_MODULE_5__.httpClient.get(baseUrl, requestOptions); + // split on `?` query or `#` fragment + const [didAuth] = did.split(/(?=[\?#])/); + + if(data?.id !== didAuth) { + throw new Error(`DID document for DID "${did}" not found.`); + } + + // FIXME: perform DID document validation + // FIXME: handle URL query param / services + const didDocument = data; + + // if a fragment was found use the fragment to dereference a subnode + // in the did doc + if(fragment) { + const id = `${data.id}${fragment}`; + return (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.getNode)({didDocument: data, id}); + } + // resolve the full DID Document + return didDocument; + } +} + +function _replaceDidKeyIdWithDidWebId(did, value) { + const fragmentIdx = value.indexOf('#'); + return did + (fragmentIdx === -1 ? '' : value.slice(fragmentIdx)); +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-web/lib/assertions.js" +/*!***************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-web/lib/assertions.js ***! + \***************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ assertDidWebUrl: () => (/* binding */ assertDidWebUrl), +/* harmony export */ assertDomain: () => (/* binding */ assertDomain), +/* harmony export */ assertHttps: () => (/* binding */ assertHttps), +/* harmony export */ assertHttpsUrl: () => (/* binding */ assertHttpsUrl), +/* harmony export */ assertUrl: () => (/* binding */ assertUrl) +/* harmony export */ }); +/*! + * Copyright (c) 2023-2024 Digital Bazaar, Inc. All rights reserved. + */ +function assertHttpsUrl(url) { + const _url = assertUrl(url); + assertHttps(_url); +} + +function assertUrl(url) { + if(url instanceof URL) { + return url; + } + if(typeof url === 'string') { + return new URL(url); + } + throw new TypeError('"url" must be a string or a URL'); +} + +function assertHttps(url) { + if(url.protocol === 'https:') { + return true; + } + throw new TypeError( + `"url" protocol must by "https:"; received "${url.protocol}"`); +} + +function assertDidWebUrl(did) { + if(!did) { + throw new TypeError('"did" must be a non-zero length string.'); + } + const didType = typeof did; + if(didType !== 'string') { + throw new TypeError(`Expected DID to be a string; received "${didType}"`); + } + const [scheme, method, domain] = did.split(':', 3); + if(scheme !== 'did') { + const e = new Error(`Scheme must be "did"; received "${scheme}"`); + e.code = 'invalidDid'; + throw e; + } + if(method !== 'web') { + const e = new Error(`Did method must be "web"; received "${method}"`); + e.code = 'methodNotSupported'; + throw e; + } + if(!domain) { + throw new Error( + `Expected domain to be a non-zero length string; received "${domain}"`); + } + if(domain.includes('/')) { + throw new Error( + `Expected domain to not contain a path; received "${domain}"`); + } +} + +function assertDomain({allowList, url}) { + if(!allowList) { + return; + } + if(allowList.length <= 0) { + return; + } + const {host} = new URL(url); + if(allowList.includes(host)) { + return; + } + throw new Error(`Domain "${host}" is not allowed.`); +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-web/lib/constants.js" +/*!**************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-web/lib/constants.js ***! + \**************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ contextsBySuite: () => (/* binding */ contextsBySuite), +/* harmony export */ defaultFetchOptions: () => (/* binding */ defaultFetchOptions), +/* harmony export */ didFile: () => (/* binding */ didFile), +/* harmony export */ didPrefix: () => (/* binding */ didPrefix), +/* harmony export */ fileSuffix: () => (/* binding */ fileSuffix) +/* harmony export */ }); +/*! + * Copyright (c) 2023-2024 Digital Bazaar, Inc. All rights reserved. + */ +// for backwards compat only, not actually importing these suites +const ED25519_KEY_2018_CONTEXT_URL = + 'https://w3id.org/security/suites/ed25519-2018/v1'; +const ED25519_KEY_2020_CONTEXT_URL = + 'https://w3id.org/security/suites/ed25519-2020/v1'; +const X25519_KEY_2019_CONTEXT_URL = + 'https://w3id.org/security/suites/x25519-2019/v1'; +const X25519_KEY_2020_CONTEXT_URL = + 'https://w3id.org/security/suites/x25519-2020/v1'; + +const MULTIKEY_CONTEXT_V1_URL = 'https://w3id.org/security/multikey/v1'; + +const contextsBySuite = new Map([ + ['Ed25519VerificationKey2020', ED25519_KEY_2020_CONTEXT_URL], + ['Ed25519VerificationKey2018', ED25519_KEY_2018_CONTEXT_URL], + ['Multikey', MULTIKEY_CONTEXT_V1_URL], + ['X25519KeyAgreementKey2020', X25519_KEY_2020_CONTEXT_URL], + ['X25519KeyAgreementKey2019', X25519_KEY_2019_CONTEXT_URL] +]); + +const defaultFetchOptions = { + // size in bytes for did documents + size: 8192, + // request time out in ms + timeout: 5000 +}; + +const didPrefix = 'did:web:'; +const didFile = 'did.json'; +const fileSuffix = `.well-known/${didFile}`; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-web/lib/helpers.js" +/*!************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-web/lib/helpers.js ***! + \************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ didUrlToHttpsUrl: () => (/* binding */ didUrlToHttpsUrl), +/* harmony export */ getNode: () => (/* binding */ getNode), +/* harmony export */ httpsUrlToDidUrl: () => (/* binding */ httpsUrlToDidUrl) +/* harmony export */ }); +/* harmony import */ var _assertions_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./assertions.js */ "./node_modules/@digitalcredentials/did-method-web/lib/assertions.js"); +/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants.js */ "./node_modules/@digitalcredentials/did-method-web/lib/constants.js"); +/* harmony import */ var klona__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! klona */ "./node_modules/klona/dist/index.mjs"); +/*! + * Copyright (c) 2023-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + + +/** + * Takes in an HTTPS (well-known) DID web url and returns a `did:web` DID URL. + * + * @param {URL|string} url - A url. + * + * @returns {string} A `did:web` URL. + */ +function httpsUrlToDidUrl(url) { + (0,_assertions_js__WEBPACK_IMPORTED_MODULE_0__.assertHttpsUrl)(url); + const { + host, + hash, + search, + pathname + } = new URL(url); + const base = `${_constants_js__WEBPACK_IMPORTED_MODULE_1__.didPrefix}${encodeURIComponent(host)}`; + // replace all / with : + const paths = _encodePaths(pathname); + // preserve the params and hash aka fragment + const did = base + paths; + const fullUrl = did + search + hash; + return {did, fullUrl}; +} + +function didUrlToHttpsUrl(did) { + (0,_assertions_js__WEBPACK_IMPORTED_MODULE_0__.assertDidWebUrl)(did); + const { + pathname, + hash, + searchParams, + search + } = new URL(did); + const ids = pathname.split(':'); + // remove the first id web + ids.shift(); + const [domain, ...paths] = ids; + const origin = `https://${decodeURIComponent(domain)}`; + const baseUrl = `${origin}/${_decodePaths(paths)}`; + const urlWithoutFragment = `${baseUrl}${search}`; + const fullUrl = `${urlWithoutFragment}${hash}`; + return { + origin, baseUrl, urlWithoutFragment, fullUrl, + searchParams, search, fragment: hash, + domain: decodeURIComponent(domain) + }; +} + +/** + * Returns the subnode of a DID document based on its `id`. + * + * @param {object} options - Options hashmap. + * @param {object} options.didDocument - The DID Document that might contain + * the subnode identified by `id`. + * @param {string} options.id - The identifier for the subnode. + * + * @returns {object} Returns the subnode, with `@context`. + */ +function getNode({didDocument, id}) { + // do verification method search first + let match = didDocument?.verificationMethod?.find(vm => vm?.id === id); + if(!match) { + // check other top-level nodes + for(const [key, value] of Object.entries(didDocument)) { + if(key === '@context' || key === 'verificationMethod') { + continue; + } + if(Array.isArray(value)) { + match = value.find(e => e?.id === id); + } else if(value?.id === id) { + match = value; + } + if(match) { + break; + } + } + } + + if(!match) { + throw new Error(`DID document entity with id "${id}" not found.`); + } + + return { + '@context': (0,klona__WEBPACK_IMPORTED_MODULE_2__.klona)( + _constants_js__WEBPACK_IMPORTED_MODULE_1__.contextsBySuite.get(match.type) ?? didDocument['@context']), + ...(0,klona__WEBPACK_IMPORTED_MODULE_2__.klona)(match) + }; +} + +/** + * Takes in the pathname from URL, splits the paths + * on "/", uri encodes them, & then rejoins them with ":". + * + * @param {string} paths - The paths to encode. + * + * @returns {string} The paths in did format. + */ +function _encodePaths(paths) { + // remove the fileSuffix, then possibly did.json + const basePaths = paths.replace(_constants_js__WEBPACK_IMPORTED_MODULE_1__.fileSuffix, '').replace(_constants_js__WEBPACK_IMPORTED_MODULE_1__.didFile, ''); + if(basePaths === '/') { + return ''; + } + // split on "/" & remove empty strings + const _paths = basePaths.split('/').filter(Boolean); + return ':' + _paths.map(encodeURIComponent).join(':'); +} + +/** + * If no paths just return well-known/did.json else return paths with + * did.json at the end. + * + * @private + * @param {Array} paths - Potential url paths. + * + * @returns {string} The resulting paths for the url. + */ +function _decodePaths(paths) { + if(paths.length === 0) { + return _constants_js__WEBPACK_IMPORTED_MODULE_1__.fileSuffix; + } + return `${paths.map(decodeURIComponent).join('/')}/${_constants_js__WEBPACK_IMPORTED_MODULE_1__.didFile}`; +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/did-method-web/lib/index.js" +/*!**********************************************************************!*\ + !*** ./node_modules/@digitalcredentials/did-method-web/lib/index.js ***! + \**********************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ DidWebDriver: () => (/* reexport safe */ _DidWebDriver_js__WEBPACK_IMPORTED_MODULE_1__.DidWebDriver), +/* harmony export */ createFromMultibase: () => (/* reexport safe */ _digitalcredentials_did_method_key__WEBPACK_IMPORTED_MODULE_2__.createFromMultibase), +/* harmony export */ didUrlToHttpsUrl: () => (/* reexport safe */ _helpers_js__WEBPACK_IMPORTED_MODULE_0__.didUrlToHttpsUrl), +/* harmony export */ driver: () => (/* binding */ driver), +/* harmony export */ httpsUrlToDidUrl: () => (/* reexport safe */ _helpers_js__WEBPACK_IMPORTED_MODULE_0__.httpsUrlToDidUrl) +/* harmony export */ }); +/* harmony import */ var _helpers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./helpers.js */ "./node_modules/@digitalcredentials/did-method-web/lib/helpers.js"); +/* harmony import */ var _DidWebDriver_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DidWebDriver.js */ "./node_modules/@digitalcredentials/did-method-web/lib/DidWebDriver.js"); +/* harmony import */ var _digitalcredentials_did_method_key__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @digitalcredentials/did-method-key */ "./node_modules/@digitalcredentials/did-method-key/lib/index.js"); +/*! + * Copyright (c) 2023-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + +// re-export `createFromMultibase` for `use` API + + +/** + * Helper method to match the `.driver()` API of other `did-io` plugins. + * + * @param {object} options - Options to use. + * @param {Array} [options.allowList] - A list of allowed domains. + * @param {object} options.fetchOptions - Options for the http client. + * + * @returns {DidWebDriver} Returns an instance of a did:web resolver driver. + */ +function driver({allowList, fetchOptions} = {}) { + return new _DidWebDriver_js__WEBPACK_IMPORTED_MODULE_1__.DidWebDriver({allowList, fetchOptions}); +} + + + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/ed25519-multikey/lib/constants.js" +/*!****************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/ed25519-multikey/lib/constants.js ***! + \****************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ ED25519_SIGNATURE_2018_V1_URL: () => (/* binding */ ED25519_SIGNATURE_2018_V1_URL), +/* harmony export */ ED25519_SIGNATURE_2020_V1_URL: () => (/* binding */ ED25519_SIGNATURE_2020_V1_URL), +/* harmony export */ MULTIBASE_BASE58BTC_HEADER: () => (/* binding */ MULTIBASE_BASE58BTC_HEADER), +/* harmony export */ MULTICODEC_PRIV_HEADER: () => (/* binding */ MULTICODEC_PRIV_HEADER), +/* harmony export */ MULTICODEC_PUB_HEADER: () => (/* binding */ MULTICODEC_PUB_HEADER), +/* harmony export */ MULTIKEY_CONTEXT_V1_URL: () => (/* binding */ MULTIKEY_CONTEXT_V1_URL), +/* harmony export */ PUBLIC_KEY_SIZE: () => (/* binding */ PUBLIC_KEY_SIZE), +/* harmony export */ SECRET_KEY_SIZE: () => (/* binding */ SECRET_KEY_SIZE) +/* harmony export */ }); +/*! + * Copyright (c) 2022-2024 Digital Bazaar, Inc. All rights reserved. + */ + +// Ed25519 Signature 2018 Context v1 URL +const ED25519_SIGNATURE_2018_V1_URL = + 'https://w3id.org/security/suites/ed25519-2018/v1'; +// Ed25519 Signature 2020 Context v1 URL +const ED25519_SIGNATURE_2020_V1_URL = + 'https://w3id.org/security/suites/ed25519-2020/v1'; +// multibase base58-btc header +const MULTIBASE_BASE58BTC_HEADER = 'z'; +// multicodec ed25519-pub header as varint +const MULTICODEC_PUB_HEADER = new Uint8Array([0xed, 0x01]); +// multicodec ed25519-priv header as varint +const MULTICODEC_PRIV_HEADER = new Uint8Array([0x80, 0x26]); +// multikey context v1 url +const MULTIKEY_CONTEXT_V1_URL = 'https://w3id.org/security/multikey/v1'; +// Ed25519 public key size in bytes +const PUBLIC_KEY_SIZE = 32; +// Ed25519 secret key size in bytes +const SECRET_KEY_SIZE = 32; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/ed25519-multikey/lib/ed25519-browser.js" +/*!**********************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/ed25519-multikey/lib/ed25519-browser.js ***! + \**********************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair), +/* harmony export */ generateKeyPairFromSeed: () => (/* binding */ generateKeyPairFromSeed), +/* harmony export */ sha256digest: () => (/* binding */ sha256digest), +/* harmony export */ sign: () => (/* binding */ sign), +/* harmony export */ verify: () => (/* binding */ verify) +/* harmony export */ }); +/* harmony import */ var _noble_ed25519__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @noble/ed25519 */ "./node_modules/@noble/ed25519/lib/esm/index.js"); +/* harmony import */ var _validators_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./validators.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/validators.js"); +/*! + * Copyright (c) 2020-2022 Digital Bazaar, Inc. All rights reserved. + */ + + + +// browser MUST provide "crypto.getRandomValues" +const crypto = globalThis.crypto; +if(!crypto.getRandomValues) { + throw new Error('Browser does not provide "crypto.getRandomValues".'); +} + +async function generateKeyPairFromSeed(seed) { + (0,_validators_js__WEBPACK_IMPORTED_MODULE_1__.assertKeyBytes)({ + bytes: seed, + expectedLength: 32, + }); + const publicKey = await _noble_ed25519__WEBPACK_IMPORTED_MODULE_0__.getPublicKey(seed); + const secretKey = new Uint8Array(64); + secretKey.set(seed); + secretKey.set(publicKey, seed.length); + return { + publicKey, + secretKey + }; +} + +async function generateKeyPair() { + const seed = new Uint8Array(32); + crypto.getRandomValues(seed); + const keyPair = await generateKeyPairFromSeed(seed); + seed.fill(0); + return keyPair; +} + +async function sign(secretKey, data) { + return _noble_ed25519__WEBPACK_IMPORTED_MODULE_0__.sign(data, secretKey.slice(0, 32)); +} + +async function verify(publicKey, data, signature) { + return _noble_ed25519__WEBPACK_IMPORTED_MODULE_0__.verify(signature, data, publicKey); +} + +async function sha256digest({data}) { + return crypto.subtle.digest('SHA-256', data); +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/ed25519-multikey/lib/factory.js" +/*!**************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/ed25519-multikey/lib/factory.js ***! + \**************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ createSigner: () => (/* binding */ createSigner), +/* harmony export */ createVerifier: () => (/* binding */ createVerifier) +/* harmony export */ }); +/* harmony import */ var _ed25519_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ed25519.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/ed25519-browser.js"); +/*! + * Copyright (c) 2022 Digital Bazaar, Inc. All rights reserved. + */ + + +const ALGORITHM = 'Ed25519'; + +function createSigner({id, secretKey}) { + if(!secretKey) { + throw new Error('A secret key is not available for signing.'); + } + return { + algorithm: ALGORITHM, + id, + async sign({data}) { + return _ed25519_js__WEBPACK_IMPORTED_MODULE_0__.sign(secretKey, data); + }, + }; +} + +function createVerifier({id, publicKey}) { + if(!publicKey) { + throw new Error('A public key is not available for verifying.'); + } + return { + algorithm: ALGORITHM, + id, + async verify({data, signature}) { + return _ed25519_js__WEBPACK_IMPORTED_MODULE_0__.verify(publicKey, data, signature); + }, + }; +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/ed25519-multikey/lib/helpers.js" +/*!**************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/ed25519-multikey/lib/helpers.js ***! + \**************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ mbDecodeKeyPair: () => (/* binding */ mbDecodeKeyPair), +/* harmony export */ mbEncodeKeyPair: () => (/* binding */ mbEncodeKeyPair) +/* harmony export */ }); +/* harmony import */ var base58_universal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! base58-universal */ "./node_modules/base58-universal/lib/index.js"); +/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/constants.js"); +/*! + * Copyright (c) 2020-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + +function mbEncodeKeyPair({keyPair}) { + const result = {}; + if(keyPair.publicKey) { + result.publicKeyMultibase = _encodeMbKey( + _constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTICODEC_PUB_HEADER, keyPair.publicKey); + } + if(keyPair.secretKey) { + result.secretKeyMultibase = _encodeMbKey( + _constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTICODEC_PRIV_HEADER, keyPair.secretKey); + } + return result; +} + +function mbDecodeKeyPair({publicKeyMultibase, secretKeyMultibase}) { + if(!(publicKeyMultibase && typeof publicKeyMultibase === 'string' && + publicKeyMultibase[0] === 'z')) { + throw new Error( + '"publicKeyMultibase" must be a multibase, base58-encoded string.'); + } + // remove multibase header + const publicKeyMulticodec = base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(publicKeyMultibase.substr(1)); + // remove multicodec header + const publicKey = publicKeyMulticodec.slice(_constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTICODEC_PUB_HEADER.length); + + let secretKey; + if(secretKeyMultibase) { + if(!(typeof secretKeyMultibase === 'string' && + secretKeyMultibase[0] === 'z')) { + throw new Error( + '"secretKeyMultibase" must be a multibase, base58-encoded string.'); + } + // remove multibase header + const secretKeyMulticodec = base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(secretKeyMultibase.substr(1)); + // remove multicodec header + secretKey = secretKeyMulticodec.slice(_constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTICODEC_PRIV_HEADER.length); + } + + return { + publicKey, + secretKey + }; +} + +// encode a multibase base58-btc multicodec key +function _encodeMbKey(header, key) { + const mbKey = new Uint8Array(header.length + key.length); + + mbKey.set(header); + mbKey.set(key, header.length); + + return _constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTIBASE_BASE58BTC_HEADER + base58_universal__WEBPACK_IMPORTED_MODULE_0__.encode(mbKey); +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/ed25519-multikey/lib/index.js" +/*!************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/ed25519-multikey/lib/index.js ***! + \************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ from: () => (/* binding */ from), +/* harmony export */ fromJwk: () => (/* binding */ fromJwk), +/* harmony export */ generate: () => (/* binding */ generate), +/* harmony export */ toJwk: () => (/* binding */ toJwk) +/* harmony export */ }); +/* harmony import */ var base64url_universal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! base64url-universal */ "./node_modules/base64url-universal/lib/browser.js"); +/* harmony import */ var _ed25519_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ed25519.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/ed25519-browser.js"); +/* harmony import */ var _factory_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./factory.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/factory.js"); +/* harmony import */ var _serialize_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./serialize.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/serialize.js"); +/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./constants.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/constants.js"); +/* harmony import */ var _helpers_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./helpers.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/helpers.js"); +/* harmony import */ var _keyPairTranslator_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./keyPairTranslator.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/keyPairTranslator.js"); +/*! + * Copyright (c) 2020-2023 Digital Bazaar, Inc. All rights reserved. + */ + + + + + + + + +async function generate({id, controller, seed} = {}) { + let key; + if(seed) { + key = await _ed25519_js__WEBPACK_IMPORTED_MODULE_1__.generateKeyPairFromSeed(seed); + } else { + key = await _ed25519_js__WEBPACK_IMPORTED_MODULE_1__.generateKeyPair(); + } + + const {publicKeyMultibase, secretKeyMultibase} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_5__.mbEncodeKeyPair)({ + keyPair: key + }); + if(controller && !id) { + id = `${controller}#${publicKeyMultibase}`; + } + const keyPair = { + id, + controller, + publicKeyMultibase, + secretKeyMultibase, + ...key, + }; + return _createKeyPairInterface({keyPair}); +} + +// import key pair from JSON Multikey +async function from(key) { + let multikey = {...key}; + if(multikey.type !== 'Multikey') { + // attempt loading from JWK if `publicKeyJwk` is present + if(multikey.publicKeyJwk) { + let id; + let controller; + if(multikey.type === 'JsonWebKey' || multikey.type === 'JsonWebKey2020') { + ({id, controller} = multikey); + } + return fromJwk({ + jwk: multikey.publicKeyJwk, secretKey: false, id, controller + }); + } + if(multikey.type) { + multikey = await (0,_keyPairTranslator_js__WEBPACK_IMPORTED_MODULE_6__.toMultikey)({keyPair: multikey}); + return _createKeyPairInterface({keyPair: multikey}); + } + } + if(!multikey.type) { + multikey.type = 'Multikey'; + } + if(!multikey['@context']) { + multikey['@context'] = _constants_js__WEBPACK_IMPORTED_MODULE_4__.MULTIKEY_CONTEXT_V1_URL; + } + + _assertMultikey(multikey); + return _createKeyPairInterface({keyPair: multikey}); +} + +// imports key pair from JWK +async function fromJwk({jwk, secretKey = false, id, controller} = {}) { + const multikey = { + '@context': _constants_js__WEBPACK_IMPORTED_MODULE_4__.MULTIKEY_CONTEXT_V1_URL, + type: 'Multikey', + publicKeyMultibase: (0,_serialize_js__WEBPACK_IMPORTED_MODULE_3__.jwkToPublicKeyMultibase)({jwk}) + }; + if(typeof id === 'string') { + multikey.id = id; + } + if(typeof controller === 'string') { + multikey.controller = controller; + } + if(secretKey && jwk.d) { + multikey.secretKeyMultibase = (0,_serialize_js__WEBPACK_IMPORTED_MODULE_3__.jwkToSecretKeyMultibase)({jwk}); + } + return from(multikey); +} + +// converts key pair to JWK +async function toJwk({keyPair, secretKey = false} = {}) { + const jwk = { + kty: 'OKP', + crv: 'Ed25519', + x: base64url_universal__WEBPACK_IMPORTED_MODULE_0__.encode(keyPair.publicKey) + }; + const useSecretKey = secretKey && !!keyPair.secretKey; + if(useSecretKey) { + jwk.d = base64url_universal__WEBPACK_IMPORTED_MODULE_0__.encode(keyPair.secretKey); + } + return jwk; +} + +async function _createKeyPairInterface({keyPair}) { + if(!keyPair.publicKey) { + keyPair = await (0,_serialize_js__WEBPACK_IMPORTED_MODULE_3__.importKeyPair)(keyPair); + } + keyPair = { + ...keyPair, + async export({ + publicKey = true, secretKey = false, includeContext = true, raw = false, + canonicalize = false + } = {}) { + if(raw) { + const {publicKey, secretKey} = keyPair; + const result = {}; + if(publicKey) { + result.publicKey = publicKey.slice(); + } + if(secretKey) { + if(canonicalize && secretKey.length > _constants_js__WEBPACK_IMPORTED_MODULE_4__.SECRET_KEY_SIZE) { + result.secretKey = secretKey.subarray(0, _constants_js__WEBPACK_IMPORTED_MODULE_4__.SECRET_KEY_SIZE).slice(); + } else { + result.secretKey = secretKey; + } + } + return result; + } + return (0,_serialize_js__WEBPACK_IMPORTED_MODULE_3__.exportKeyPair)({ + keyPair, publicKey, secretKey, includeContext, canonicalize + }); + }, + signer() { + const {id, secretKey} = keyPair; + return (0,_factory_js__WEBPACK_IMPORTED_MODULE_2__.createSigner)({id, secretKey}); + }, + verifier() { + const {id, publicKey} = keyPair; + return (0,_factory_js__WEBPACK_IMPORTED_MODULE_2__.createVerifier)({id, publicKey}); + } + }; + + return keyPair; +} + +function _assertMultikey(key) { + if(!(key && typeof key === 'object')) { + throw new TypeError('"key" must be an object.'); + } + if(key.type !== 'Multikey') { + throw new Error('"key" must be a Multikey with type "Multikey".'); + } + if(!(key['@context'] === _constants_js__WEBPACK_IMPORTED_MODULE_4__.MULTIKEY_CONTEXT_V1_URL || + (Array.isArray(key['@context']) && + key['@context'].includes(_constants_js__WEBPACK_IMPORTED_MODULE_4__.MULTIKEY_CONTEXT_V1_URL)))) { + throw new TypeError( + '"key" must be a Multikey with context ' + + `"${_constants_js__WEBPACK_IMPORTED_MODULE_4__.MULTIKEY_CONTEXT_V1_URL}".`); + } +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/ed25519-multikey/lib/keyPairTranslationMap.js" +/*!****************************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/ed25519-multikey/lib/keyPairTranslationMap.js ***! + \****************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ keyPairTranslationMap: () => (/* binding */ keyPairTranslationMap) +/* harmony export */ }); +/* harmony import */ var base58_universal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! base58-universal */ "./node_modules/base58-universal/lib/index.js"); +/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/constants.js"); +/* harmony import */ var _helpers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./helpers.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/helpers.js"); +/*! + * Copyright (c) 2022-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + + +const keyPairTranslationMap = new Map([ + ['Ed25519VerificationKey2020', { + contextUrl: _constants_js__WEBPACK_IMPORTED_MODULE_1__.ED25519_SIGNATURE_2020_V1_URL, + translationFn: _translateEd25519VerificationKey2020 + }], + ['Ed25519VerificationKey2018', { + contextUrl: _constants_js__WEBPACK_IMPORTED_MODULE_1__.ED25519_SIGNATURE_2018_V1_URL, + translationFn: _translateEd25519VerificationKey2018 + }] +]); + +async function _translateEd25519VerificationKey2020({keyPair}) { + return { + ...keyPair, + type: 'Multikey', + '@context': _constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTIKEY_CONTEXT_V1_URL, + secretKeyMultibase: keyPair.privateKeyMultibase + }; +} + +async function _translateEd25519VerificationKey2018({keyPair}) { + const key = { + publicKey: base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(keyPair.publicKeyBase58), + secretKey: undefined + }; + + if(keyPair.privateKeyBase58) { + key.secretKey = base58_universal__WEBPACK_IMPORTED_MODULE_0__.decode(keyPair.privateKeyBase58); + } + + const {publicKeyMultibase, secretKeyMultibase} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_2__.mbEncodeKeyPair)({ + keyPair: key + }); + + return { + '@context': _constants_js__WEBPACK_IMPORTED_MODULE_1__.MULTIKEY_CONTEXT_V1_URL, + id: keyPair.id, + type: 'Multikey', + controller: keyPair.controller, + revoked: keyPair.revoked, + publicKeyMultibase, + secretKeyMultibase, + }; +} + + + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/ed25519-multikey/lib/keyPairTranslator.js" +/*!************************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/ed25519-multikey/lib/keyPairTranslator.js ***! + \************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ toMultikey: () => (/* binding */ toMultikey) +/* harmony export */ }); +/* harmony import */ var _keyPairTranslationMap_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./keyPairTranslationMap.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/keyPairTranslationMap.js"); +/*! + * Copyright (c) 2022 Digital Bazaar, Inc. All rights reserved. + */ + + +async function toMultikey({keyPair}) { + const translationResult = _keyPairTranslationMap_js__WEBPACK_IMPORTED_MODULE_0__.keyPairTranslationMap.get(keyPair.type); + if(!translationResult) { + throw new Error(`Unsupported key type "${keyPair.type}".`); + } + + const {contextUrl, translationFn} = translationResult; + if(!keyPair['@context']) { + keyPair['@context'] = contextUrl; + } + if(!_includesContext({document: keyPair, contextUrl})) { + throw new Error(`Context not supported "${keyPair['@context']}".`); + } + + return translationFn({keyPair}); +} + +function _includesContext({document, contextUrl}) { + const context = document['@context']; + return context === contextUrl || + (Array.isArray(context) && context.includes(contextUrl)); +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/ed25519-multikey/lib/serialize.js" +/*!****************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/ed25519-multikey/lib/serialize.js ***! + \****************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ exportKeyPair: () => (/* binding */ exportKeyPair), +/* harmony export */ importKeyPair: () => (/* binding */ importKeyPair), +/* harmony export */ jwkToPublicKeyBytes: () => (/* binding */ jwkToPublicKeyBytes), +/* harmony export */ jwkToPublicKeyMultibase: () => (/* binding */ jwkToPublicKeyMultibase), +/* harmony export */ jwkToSecretKeyBytes: () => (/* binding */ jwkToSecretKeyBytes), +/* harmony export */ jwkToSecretKeyMultibase: () => (/* binding */ jwkToSecretKeyMultibase), +/* harmony export */ rawToPublicKeyMultibase: () => (/* binding */ rawToPublicKeyMultibase), +/* harmony export */ rawToSecretKeyMultibase: () => (/* binding */ rawToSecretKeyMultibase) +/* harmony export */ }); +/* harmony import */ var base64url_universal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! base64url-universal */ "./node_modules/base64url-universal/lib/browser.js"); +/* harmony import */ var _helpers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./helpers.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/helpers.js"); +/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants.js */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/constants.js"); +/*! + * Copyright (c) 2022-2024 Digital Bazaar, Inc. All rights reserved. + */ + + + + +const LEGACY_SECRET_KEY_SIZE = _constants_js__WEBPACK_IMPORTED_MODULE_2__.SECRET_KEY_SIZE + _constants_js__WEBPACK_IMPORTED_MODULE_2__.PUBLIC_KEY_SIZE; + +async function exportKeyPair({ + keyPair, secretKey, publicKey, includeContext, canonicalize = false +} = {}) { + if(!(publicKey || secretKey)) { + throw new TypeError( + 'Export requires specifying either "publicKey" or "secretKey".'); + } + + const useSecretKey = secretKey && !!keyPair.secretKey; + + // export as Multikey + const exported = {}; + if(includeContext) { + exported['@context'] = _constants_js__WEBPACK_IMPORTED_MODULE_2__.MULTIKEY_CONTEXT_V1_URL; + } + exported.id = keyPair.id; + exported.type = 'Multikey'; + exported.controller = keyPair.controller; + + if(publicKey) { + exported.publicKeyMultibase = rawToPublicKeyMultibase(keyPair); + } + if(useSecretKey) { + exported.secretKeyMultibase = rawToSecretKeyMultibase({ + ...keyPair, canonicalize + }); + } + + if(keyPair.revoked) { + exported.revoked = keyPair.revoked; + } + + return exported; +} + +async function importKeyPair({ + id, controller, secretKeyMultibase, publicKeyMultibase, revoked +}) { + if(!publicKeyMultibase) { + throw new TypeError('The "publicKeyMultibase" property is required.'); + } + + const { + publicKey, secretKey + } = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.mbDecodeKeyPair)({publicKeyMultibase, secretKeyMultibase}); + + if(controller && !id) { + id = `${controller}#${publicKeyMultibase}`; + } + + return { + id, + controller, + publicKey, + secretKey, + publicKeyMultibase, + secretKeyMultibase, + revoked, + }; +} + +function jwkToPublicKeyBytes({jwk} = {}) { + const {kty, crv, x} = jwk; + if(kty !== 'OKP') { + throw new TypeError('"jwk.kty" must be "OKP".'); + } + if(crv !== 'Ed25519') { + throw new TypeError('"jwk.crv" must be "Ed25519".'); + } + if(typeof x !== 'string') { + throw new TypeError('"jwk.x" must be a string.'); + } + const publicKey = base64url_universal__WEBPACK_IMPORTED_MODULE_0__.decode(jwk.x); + if(publicKey.length !== _constants_js__WEBPACK_IMPORTED_MODULE_2__.PUBLIC_KEY_SIZE) { + throw new Error( + `Invalid public key size (${publicKey.length}); ` + + `expected ${_constants_js__WEBPACK_IMPORTED_MODULE_2__.PUBLIC_KEY_SIZE}.`); + } + return publicKey; +} + +function jwkToPublicKeyMultibase({jwk} = {}) { + const publicKey = jwkToPublicKeyBytes({jwk}); + const {publicKeyMultibase} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.mbEncodeKeyPair)({ + keyPair: {publicKey} + }); + return publicKeyMultibase; +} + +function jwkToSecretKeyBytes({jwk} = {}) { + const {kty, crv, d} = jwk; + if(kty !== 'OKP') { + throw new TypeError('"jwk.kty" must be "OKP".'); + } + if(crv !== 'Ed25519') { + throw new TypeError('"jwk.crv" must be "Ed25519".'); + } + if(typeof d !== 'string') { + throw new TypeError('"jwk.d" must be a string.'); + } + const secretKey = Uint8Array.from(base64url_universal__WEBPACK_IMPORTED_MODULE_0__.decode(jwk.d)); + if(secretKey.length !== _constants_js__WEBPACK_IMPORTED_MODULE_2__.SECRET_KEY_SIZE) { + throw new Error( + `Invalid secret key size (${secretKey.length}); ` + + `expected ${_constants_js__WEBPACK_IMPORTED_MODULE_2__.SECRET_KEY_SIZE}.`); + } + return secretKey; +} + +function jwkToSecretKeyMultibase({jwk} = {}) { + const secretKey = jwkToSecretKeyBytes({jwk}); + const {secretKeyMultibase} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.mbEncodeKeyPair)({ + keyPair: {secretKey} + }); + return secretKeyMultibase; +} + +function rawToPublicKeyMultibase({publicKey} = {}) { + if(publicKey.length !== _constants_js__WEBPACK_IMPORTED_MODULE_2__.PUBLIC_KEY_SIZE) { + throw new Error( + `Invalid public key size (${publicKey.length}); ` + + `expected ${_constants_js__WEBPACK_IMPORTED_MODULE_2__.PUBLIC_KEY_SIZE}.`); + } + const {publicKeyMultibase} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.mbEncodeKeyPair)({ + keyPair: {publicKey} + }); + return publicKeyMultibase; +} + +function rawToSecretKeyMultibase({ + secretKey, canonicalize = false +} = {}) { + if(secretKey.length !== _constants_js__WEBPACK_IMPORTED_MODULE_2__.SECRET_KEY_SIZE) { + if(secretKey.length !== LEGACY_SECRET_KEY_SIZE) { + throw new Error( + `Invalid secret key size (${secretKey.length}); ` + + `expected ${_constants_js__WEBPACK_IMPORTED_MODULE_2__.SECRET_KEY_SIZE}.`); + } + // handle legacy concatenated (secret key + public key) + if(canonicalize) { + secretKey = secretKey.subarray(0, _constants_js__WEBPACK_IMPORTED_MODULE_2__.SECRET_KEY_SIZE); + } + } + const {secretKeyMultibase} = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_1__.mbEncodeKeyPair)({ + keyPair: {secretKey} + }); + return secretKeyMultibase; +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/ed25519-multikey/lib/validators.js" +/*!*****************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/ed25519-multikey/lib/validators.js ***! + \*****************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ assertKeyBytes: () => (/* binding */ assertKeyBytes) +/* harmony export */ }); +/*! + * Copyright (c) 2022 Digital Bazaar, Inc. All rights reserved. + */ + +/** + * Asserts that key bytes have a type of Uint8Array and a specific length. + * + * @throws {TypeError|SyntaxError} - Throws a Type or Syntax error. + * + * @param {object} options - Options to use. + * @param {Uint8Array} options.bytes - The bytes being checked. + * @param {number} [options.expectedLength=32] - The expected bytes length. + * @param {string} [options.code] - An optional code for the error. + * + * @returns {undefined} Returns on success throws on error. + */ +function assertKeyBytes({bytes, expectedLength = 32, code}) { + if(!(bytes instanceof Uint8Array)) { + throw new TypeError('"bytes" must be a Uint8Array.'); + } + if(bytes.length !== expectedLength) { + const error = new Error( + `"bytes" must be a ${expectedLength}-byte Uint8Array.`); + // we need DataError for invalid byte length + error.name = 'DataError'; + // add the error code from the did:key spec if provided + if(code) { + error.code = code; + } + throw error; + } +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/http-client/dist/agentCompatibility-browser.js" +/*!*****************************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/http-client/dist/agentCompatibility-browser.js ***! + \*****************************************************************************************/ +(__unused_webpack_module, exports) { + +"use strict"; + + +/*! + * Copyright (c) 2022 Digital Bazaar, Inc. All rights reserved. + */ +// no-op for browsers +function convertAgent(options) { + return options; +} + +exports.convertAgent = convertAgent; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/http-client/dist/deferred.js" +/*!***********************************************************************!*\ + !*** ./node_modules/@digitalcredentials/http-client/dist/deferred.js ***! + \***********************************************************************/ +(__unused_webpack_module, exports) { + +"use strict"; + + +function deferred(f) { + let promise; + + return { + then( + onfulfilled, + onrejected + ) { + // Use logical OR assignment when Node.js 14.x support is dropped + //promise ||= new Promise(resolve => resolve(f())); + promise || (promise = new Promise(resolve => resolve(f()))); + return promise.then( + onfulfilled, + onrejected + ); + }, + }; +} + +exports.deferred = deferred; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/http-client/dist/esm/index.js" +/*!************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/http-client/dist/esm/index.js ***! + \************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ DEFAULT_HEADERS: () => (/* binding */ DEFAULT_HEADERS), +/* harmony export */ httpClient: () => (/* binding */ httpClient), +/* harmony export */ kyPromise: () => (/* binding */ kyPromise) +/* harmony export */ }); +/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index.js */ "./node_modules/@digitalcredentials/http-client/dist/index.js"); + +const DEFAULT_HEADERS = _index_js__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_HEADERS; +const httpClient = _index_js__WEBPACK_IMPORTED_MODULE_0__.httpClient; +const kyPromise = _index_js__WEBPACK_IMPORTED_MODULE_0__.kyPromise; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/http-client/dist/httpClient.js" +/*!*************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/http-client/dist/httpClient.js ***! + \*************************************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +var agentCompatibility = __webpack_require__(/*! ./agentCompatibility.js */ "./node_modules/@digitalcredentials/http-client/dist/agentCompatibility-browser.js"); +var deferred = __webpack_require__(/*! ./deferred.js */ "./node_modules/@digitalcredentials/http-client/dist/deferred.js"); + +/*! + * Copyright (c) 2020-2022 Digital Bazaar, Inc. All rights reserved. + */ + +const kyOriginalPromise = deferred.deferred(() => Promise.resolve(/*! import() */).then(__webpack_require__.bind(__webpack_require__, /*! ky */ "./node_modules/ky/distribution/index.js")) + .then(({default: ky}) => ky)); + +const DEFAULT_HEADERS = { + Accept: 'application/ld+json, application/json' +}; + +// methods to proxy from ky +const PROXY_METHODS = new Set([ + 'get', 'post', 'put', 'push', 'patch', 'head', 'delete' +]); + +/** + * Returns a custom httpClient instance. Used to specify default headers and + * other default overrides. + * + * @param {object} [options={}] - Options hashmap. + * @param {object} [options.parent] - The ky promise to inherit from. + * @param {object} [options.headers={}] - Default header overrides. + * @param {object} [options.params] - Other default overrides. + * + * @returns {Function} Custom httpClient instance. + */ +function createInstance({ + parent = kyOriginalPromise, headers = {}, ...params +} = {}) { + // convert legacy agent options + params = agentCompatibility.convertAgent(params); + + // create new ky instance that will asynchronously resolve + const kyPromise = deferred.deferred(() => parent.then(kyBase => { + let ky; + if(parent === kyOriginalPromise) { + // ensure default headers, allow overrides + ky = kyBase.create({ + headers: {...DEFAULT_HEADERS, ...headers}, + ...params + }); + } else { + // extend parent + ky = kyBase.extend({headers, ...params}); + } + return ky; + })); + + return _createHttpClient(kyPromise); +} + +function _createHttpClient(kyPromise) { + async function httpClient(...args) { + const ky = await kyPromise; + const method = ((args[1] && args[1].method) || 'get').toLowerCase(); + if(PROXY_METHODS.has(method)) { + return httpClient[method].apply(ky[method], args); + } + + // convert legacy agent options + args[1] = agentCompatibility.convertAgent(args[1]); + return ky.apply(ky, args); + } + + for(const method of PROXY_METHODS) { + httpClient[method] = async function(...args) { + const ky = await kyPromise; + return _handleResponse(ky[method], ky, args); + }; + } + + httpClient.create = function({headers = {}, ...params}) { + return createInstance({headers, ...params}); + }; + + httpClient.extend = function({headers = {}, ...params}) { + return createInstance({parent: kyPromise, headers, ...params}); + }; + + // default async `stop` signal getter + Object.defineProperty(httpClient, 'stop', { + async get() { + const ky = await kyPromise; + return ky.stop; + } + }); + + return httpClient; +} + +async function _handleResponse(target, thisArg, args) { + // convert legacy agent options + args[1] = agentCompatibility.convertAgent(args[1]); + + let response; + const [url] = args; + try { + response = await target.apply(thisArg, args); + } catch(error) { + return _handleError({error, url}); + } + const {parseBody = true} = args[1] || {}; + // always set 'data', default to undefined + let data; + if(parseBody) { + // a 204 will not include a content-type header + const contentType = response.headers.get('content-type'); + if(contentType && contentType.includes('json')) { + data = await response.json(); + } + } + Object.defineProperty(response, 'data', {value: data}); + return response; +} + +/** + * @param {object} options - Options hashmap. + * @param {Error} options.error - Error thrown during http operation. + * @param {string} options.url - Target URL of the request. + * + * @returns {Promise} Rejects with a thrown error. + */ +async function _handleError({error, url}) { + error.requestUrl = url; + + // handle network errors and system errors that do not have a response + if(!error.response) { + if(error.message === 'Failed to fetch') { + error.message = `Failed to fetch "${url}". Possible CORS error.`; + } + // ky's TimeoutError class + if(error.name === 'TimeoutError') { + error.message = `Request to "${url}" timed out.`; + } + + throw error; + } + + // always move status up to the root of error + error.status = error.response.status; + + const contentType = error.response.headers.get('content-type'); + if(contentType && contentType.includes('json')) { + const errorBody = await error.response.json(); + // the HTTPError received from ky has a generic message based on status + // use that if the JSON body does not include a message + error.message = errorBody.message || error.message; + error.data = errorBody; + } + throw error; +} + +exports.DEFAULT_HEADERS = DEFAULT_HEADERS; +exports.createInstance = createInstance; +exports.kyOriginalPromise = kyOriginalPromise; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/http-client/dist/index.js" +/*!********************************************************************!*\ + !*** ./node_modules/@digitalcredentials/http-client/dist/index.js ***! + \********************************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +var httpClient$1 = __webpack_require__(/*! ./httpClient.js */ "./node_modules/@digitalcredentials/http-client/dist/httpClient.js"); + +/*! + * Copyright (c) 2020-2022 Digital Bazaar, Inc. All rights reserved. + */ + +const httpClient = httpClient$1.createInstance(); + +exports.DEFAULT_HEADERS = httpClient$1.DEFAULT_HEADERS; +exports.kyPromise = httpClient$1.kyOriginalPromise; +exports.httpClient = httpClient; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/lru-memoize/dist/LruCache.js" +/*!***********************************************************************!*\ + !*** ./node_modules/@digitalcredentials/lru-memoize/dist/LruCache.js ***! + \***********************************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var LRU = __webpack_require__(/*! lru-cache */ "./node_modules/lru-cache/index.js"); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var LRU__default = /*#__PURE__*/_interopDefaultLegacy(LRU); + +/*! + * Copyright (c) 2020-2021 Digital Bazaar, Inc. All rights reserved. + */ + +/** + * LruCache uses the npm module `lru-cache` to memoize promises. + * + * @see https://www.npmjs.com/package/lru-cache + * @see https://en.wikipedia.org/wiki/Memoization + * @param {object} cacheOptions - Options for `lru-cache`. + * See the npm docs for more options. + * @param {number} [cacheOptions.max] - The max size of the cache. + * @param {number} [cacheOptions.maxAge] - The maxAge of an item in ms. + * @param {boolean} [cacheOptions.updateAgeOnGet=false] - When using + * time-expiring entries with maxAge, setting this to true will make + * each entry's effective time update to the current time whenever it is + * retrieved from cache, thereby extending the expiration date of the entry. + * @param {boolean} [cacheOptions.disposeOnSettle=false] - When set to true + * entries will be removed from cache once they've settled. This is to only + * be used when one needs a promise queue. + * + * @returns {LruCache} The class. +*/ +class LruCache { + constructor(cacheOptions) { + this.options = cacheOptions || {}; + this.cache = new LRU__default["default"](cacheOptions); + } + + /** + * Deletes a key from the LRU cache. + * + * @param {string} key - A key for the cache. + * + * @returns {undefined} + */ + delete(key) { + return this.cache.del(key); + } + + /** + * Memoizes a promise via an LRU cache. + * + * @param {object} options - Options to use. + * @param {string} options.key - A key for the cache. + * @param {Function} options.fn - A Function that returns a + * promise to memoize. + * + * @returns {Promise} - The result of the memoized promise. + */ + async memoize({key, fn}) { + let promise = this.cache.get(key); + if(promise) { + return promise; + } + + // cache miss + promise = fn(); + this.cache.set(key, promise); + + let result; + try { + result = await promise; + } catch(e) { + // if the promise rejects, delete it + this.cache.del(key); + throw e; + } + + if(this.options.disposeOnSettle) { + this.cache.del(key); + } + + return result; + } +} + +exports.LruCache = LruCache; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/lru-memoize/dist/index.js" +/*!********************************************************************!*\ + !*** ./node_modules/@digitalcredentials/lru-memoize/dist/index.js ***! + \********************************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var LruCache = __webpack_require__(/*! ./LruCache.js */ "./node_modules/@digitalcredentials/lru-memoize/dist/LruCache.js"); + + + +exports.LruCache = LruCache.LruCache; + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/open-badges-context/dist/context.esm.js" +/*!**********************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/open-badges-context/dist/context.esm.js ***! + \**********************************************************************************/ +(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CONTEXT_URL_V3: () => (/* binding */ context_2), +/* harmony export */ CONTEXT_URL_V3_0_0: () => (/* binding */ context_6), +/* harmony export */ CONTEXT_URL_V3_0_1: () => (/* binding */ context_7), +/* harmony export */ CONTEXT_URL_V3_0_2: () => (/* binding */ context_8), +/* harmony export */ CONTEXT_URL_V3_0_3: () => (/* binding */ context_9), +/* harmony export */ CONTEXT_URL_V3_ALPHA: () => (/* binding */ context_3), +/* harmony export */ CONTEXT_URL_V3_BETA: () => (/* binding */ context_5), +/* harmony export */ CONTEXT_URL_V3_EXTENSIONS: () => (/* binding */ context_10), +/* harmony export */ CONTEXT_URL_V3_JFF_V1: () => (/* binding */ context_4), +/* harmony export */ contexts: () => (/* binding */ context_1), +/* harmony export */ "default": () => (/* binding */ context$1) +/* harmony export */ }); +function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var context = createCommonjsModule(function (module, exports) { +!function(t,e){for(var i in e)t[i]=e[i];}(exports,function(t){var e={};function i(o){if(e[o])return e[o].exports;var s=e[o]={i:o,l:!1,exports:{}};return t[o].call(s.exports,s,s.exports,i),s.l=!0,s.exports}return i.m=t,i.c=e,i.d=function(t,e,o){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:o});},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0});},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var o=Object.create(null);if(i.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var s in t)i.d(o,s,function(e){return t[e]}.bind(null,s));return o},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=0)}([function(t,e,i){/*! + * Copyright (c) 2022 Digital Credentials Consortium. All rights reserved. + */const o=i(1),s=i(2),l=i(3),r=i(4),p=i(5),a=i(6),c="https://imsglobal.github.io/openbadges-specification/ob_v3p0.html",d="https://w3c-ccg.github.io/vc-ed/plugfest-1-2022/jff-vc-edu-plugfest-1-context.json",g="https://purl.imsglobal.org/spec/ob/v3p0/context-3.0.1.json",b="https://purl.imsglobal.org/spec/ob/v3p0/context-3.0.2.json",h="https://purl.imsglobal.org/spec/ob/v3p0/context-3.0.3.json",m=new Map;m.set(c,o),m.set(d,o),m.set("OBv3_beta",o),m.set("https://purl.imsglobal.org/spec/ob/v3p0/context.json",s),m.set(g,l),m.set(b,r),m.set(h,p),m.set("https://purl.imsglobal.org/spec/ob/v3p0/extensions.json",a);const n=h;m.set(n,p),t.exports={contexts:m,CONTEXT_URL_V3_ALPHA:c,CONTEXT_URL_V3_JFF_V1:d,CONTEXT_URL_V3_BETA:"OBv3_beta",CONTEXT_URL_V3_0_0:"https://purl.imsglobal.org/spec/ob/v3p0/context.json",CONTEXT_URL_V3_0_1:g,CONTEXT_URL_V3_0_2:b,CONTEXT_URL_V3_0_3:h,CONTEXT_URL_V3_EXTENSIONS:"https://purl.imsglobal.org/spec/ob/v3p0/extensions.json",CONTEXT_URL_V3:n};},function(t,e,i){/*! + * Copyright (c) 2023 Digital Credentials Consortium. All rights reserved. + */t.exports={"@context":{id:"@id",type:"@type",xsd:"https://www.w3.org/2001/XMLSchema#",OpenBadgeCredential:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#OpenBadgeCredential"},Achievement:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#Achievement","@context":{achievementType:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#achievementType","@type":"xsd:string"},alignment:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#Alignment"},creator:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#Profile"},creditsAvailable:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#creditsAvailable","@type":"xsd:float"},criteria:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#criteria","@type":"@id"},fieldOfStudy:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#fieldOfStudy","@type":"xsd:string"},humanCode:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#humanCode","@type":"xsd:string"},specialization:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#specialization","@type":"xsd:string"},tags:{"@id":"https://schema.org/keywords","@type":"xsd:string","@container":"@set"}}},AchievementCredential:{"@id":"OpenBadgeCredential"},AchievementSubject:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#AchievementSubject","@context":{achievement:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#Achievement"},identifier:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#Identifier"},result:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#Result"}}},Address:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#Address","@context":{addressCountry:{"@id":"https://schema.org/addressCountry","@type":"xsd:string"},addressCountryCode:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#CountryCode","@type":"xsd:string"},addressLocality:{"@id":"https://schema.org/addresLocality","@type":"xsd:string"},addressRegion:{"@id":"https://schema.org/addressRegion","@type":"xsd:string"},geo:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#GeoCoordinates"},postOfficeBoxNumber:{"@id":"https://schema.org/postOfficeBoxNumber","@type":"xsd:string"},postalCode:{"@id":"https://schema.org/postalCode","@type":"xsd:string"},streetAddress:{"@id":"https://schema.org/streetAddress","@type":"xsd:string"}}},Alignment:{"@id":"https://schema.org/Alignment","@context":{targetCode:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#targetCode","@type":"xsd:string"},targetDescription:{"@id":"https://schema.org/targetDescription","@type":"xsd:string"},targetFramework:{"@id":"https://schema.org/targetFramework","@type":"xsd:string"},targetName:{"@id":"https://schema.org/targetName","@type":"xsd:string"},targetType:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#targetType","@type":"xsd:string"},targetUrl:{"@id":"https://schema.org/targetUrl","@type":"xsd:anyURI"}}},Criteria:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#Criteria"},EndorsementCredential:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#EndorsementCredential"},EndorsementSubject:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#EndorsementSubject","@context":{endorsementComment:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#endorsementComment","@type":"xsd:string"}}},Evidence:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#Evidence","@context":{audience:{"@id":"https://schema.org/audience","@type":"xsd:string"},genre:{"@id":"https://schema.org/genre","@type":"xsd:string"}}},GeoCoordinates:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#GeoCoordinates","@context":{latitude:{"@id":"https://schema.org/latitude","@type":"xsd:string"},longitude:{"@id":"https://schema.org/longitude","@type":"xsd:string"}}},IdentityObject:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#IdentityObject","@context":{hashed:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#hashed","@type":"xsd:boolean"},identityHash:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#identityHash","@type":"xsd:string"},salt:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#salt","@type":"xsd:string"}}},Image:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#IdentityImage","@context":{caption:{"@id":"https://schema.org/caption","@type":"xsd:string"}}},Profile:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#Profile","@context":{additionalName:{"@id":"https://schema.org/additionalName","@type":"xsd:string"},address:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#Address"},dateOfBirth:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#dateOfBirth","@type":"xsd:date"},email:{"@id":"https://schema.org/email","@type":"xsd:string"},familyName:{"@id":"https://schema.org/familyName","@type":"xsd:string"},familyNamePrefix:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#familyNamePrefix","@type":"xsd:string"},givenName:{"@id":"https://schema.org/givenName","@type":"xsd:string"},honorificPrefix:{"@id":"https://schema.org/honorificPrefix","@type":"xsd:string"},honorificSuffix:{"@id":"https://schema.org/honorificSuffix","@type":"xsd:string"},parentOrg:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#parentOrg","@type":"xsd:string"},patronymicName:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#patronymicName","@type":"xsd:string"},phone:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#PhoneNumber","@type":"xsd:string"},official:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#official","@type":"xsd:string"},sisSourcedId:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#sisSourcedId","@type":"xsd:string"},sourcedId:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#sourcedId","@type":"xsd:string"}}},Result:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#Result","@context":{achievedLevel:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#achievedLevel","@type":"xsd:anyURI"},resultDescription:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#resultDescription","@type":"xsd:anyURI"},status:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#status","@type":"xsd:string"},value:{"@id":"https://schema.org/value","@type":"xsd:string"}}},ResultDescription:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#ResultDescription","@context":{allowedValue:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#allowedValue","@type":"xsd:string"},requiredLevel:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#requiredLevel","@type":"xsd:anyURI"},requiredValue:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#requiredValue","@type":"xsd:string"},resultType:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#resultType","@type":"xsd:string"},rubricCriterionLevel:"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#RubricCriterionLevel",valueMax:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#valueMax","@type":"xsd:string"},valueMin:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#valueMin","@type":"xsd:string"}}},RubricCriterionLevel:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#RubricCriterionLevel","@context":{level:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#level","@type":"xsd:string"},points:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#points","@type":"xsd:string"}}},alignment:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#Alignment","@type":"@id"},description:{"@id":"https://schema.org/description","@type":"xsd:string"},endorsement:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#endorsement","@type":"@id"},image:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#image","@type":"@id"},name:{"@id":"https://schema.org/name","@type":"xsd:string"},narrative:{"@id":"https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#narrative","@type":"xsd:string"},url:{"@id":"https://schema.org/url","@type":"xsd:anyURI"}}};},function(t,e,i){/*! + * Copyright (c) 2022 Digital Credentials Consortium. All rights reserved. + */t.exports={"@context":{id:"@id",type:"@type",xsd:"https://www.w3.org/2001/XMLSchema#",OpenBadgeCredential:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#OpenBadgeCredential"},Achievement:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Achievement","@context":{achievementType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#achievementType","@type":"xsd:string"},alignment:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#alignment","@type":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Alignment","@container":"@set"},creator:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Profile"},creditsAvailable:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#creditsAvailable","@type":"xsd:float"},criteria:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Criteria","@type":"@id"},fieldOfStudy:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#fieldOfStudy","@type":"xsd:string"},humanCode:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#humanCode","@type":"xsd:string"},otherIdentifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#otherIdentifier","@type":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#IdentifierEntry","@container":"@set"},related:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#related","@type":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Related","@container":"@set"},resultDescription:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#resultDescription","@type":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#ResultDescription","@container":"@set"},specialization:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#specialization","@type":"xsd:string"},tag:{"@id":"https://schema.org/keywords","@type":"xsd:string","@container":"@set"},version:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#version","@type":"xsd:string"}}},AchievementCredential:{"@id":"OpenBadgeCredential"},AchievementSubject:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#AchievementSubject","@context":{achievement:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Achievement"},activityEndDate:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#activityEndDate","@type":"xsd:date"},activityStartDate:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#activityStartDate","@type":"xsd:date"},creditsEarned:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#creditsEarned","@type":"xsd:float"},identifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identifier","@type":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#IdentityObject","@container":"@set"},licenseNumber:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#licenseNumber","@type":"xsd:string"},result:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#result","@type":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Result","@container":"@set"},role:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#role","@type":"xsd:string"},source:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#source","@type":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Profile"},term:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#term","@type":"xsd:string"}}},Address:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Address","@context":{addressCountry:{"@id":"https://schema.org/addressCountry","@type":"xsd:string"},addressCountryCode:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#CountryCode","@type":"xsd:string"},addressLocality:{"@id":"https://schema.org/addressLocality","@type":"xsd:string"},addressRegion:{"@id":"https://schema.org/addressRegion","@type":"xsd:string"},geo:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#GeoCoordinates"},postOfficeBoxNumber:{"@id":"https://schema.org/postOfficeBoxNumber","@type":"xsd:string"},postalCode:{"@id":"https://schema.org/postalCode","@type":"xsd:string"},streetAddress:{"@id":"https://schema.org/streetAddress","@type":"xsd:string"}}},Alignment:{"@id":"https://schema.org/Alignment","@context":{targetCode:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#targetCode","@type":"xsd:string"},targetDescription:{"@id":"https://schema.org/targetDescription","@type":"xsd:string"},targetFramework:{"@id":"https://schema.org/targetFramework","@type":"xsd:string"},targetName:{"@id":"https://schema.org/targetName","@type":"xsd:string"},targetType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#targetType","@type":"xsd:string"},targetUrl:{"@id":"https://schema.org/targetUrl","@type":"xsd:anyURI"}}},Criteria:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Criteria"},EndorsementCredential:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#EndorsementCredential"},EndorsementSubject:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#EndorsementSubject","@context":{endorsementComment:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#endorsementComment","@type":"xsd:string"}}},Evidence:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Evidence","@context":{audience:{"@id":"https://schema.org/audience","@type":"xsd:string"},genre:{"@id":"https://schema.org/genre","@type":"xsd:string"}}},GeoCoordinates:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#GeoCoordinates","@context":{latitude:{"@id":"https://schema.org/latitude","@type":"xsd:string"},longitude:{"@id":"https://schema.org/longitude","@type":"xsd:string"}}},IdentifierEntry:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#IdentifierEntry","@context":{identifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identifier","@type":"xsd:string"},identifierType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identifierType","@type":"xsd:string"}}},IdentityObject:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#IdentityObject","@context":{hashed:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#hashed","@type":"xsd:boolean"},identityHash:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identityHash","@type":"xsd:string"},identityType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identityType","@type":"xsd:string"},salt:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#salt","@type":"xsd:string"}}},Image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Image","@context":{caption:{"@id":"https://schema.org/caption","@type":"xsd:string"}}},Profile:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Profile","@context":{additionalName:{"@id":"https://schema.org/additionalName","@type":"xsd:string"},address:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Address"},dateOfBirth:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#dateOfBirth","@type":"xsd:date"},email:{"@id":"https://schema.org/email","@type":"xsd:string"},familyName:{"@id":"https://schema.org/familyName","@type":"xsd:string"},familyNamePrefix:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#familyNamePrefix","@type":"xsd:string"},givenName:{"@id":"https://schema.org/givenName","@type":"xsd:string"},honorificPrefix:{"@id":"https://schema.org/honorificPrefix","@type":"xsd:string"},honorificSuffix:{"@id":"https://schema.org/honorificSuffix","@type":"xsd:string"},otherIdentifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#otherIdentifier","@type":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#IdentifierEntry","@container":"@set"},parentOrg:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#parentOrg","@type":"xsd:string"},patronymicName:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#patronymicName","@type":"xsd:string"},phone:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#PhoneNumber","@type":"xsd:string"},official:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#official","@type":"xsd:string"}}},Related:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Related","@context":{version:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#version","@type":"xsd:string"}}},Result:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Result","@context":{achievedLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#achievedLevel","@type":"xsd:anyURI"},resultDescription:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#resultDescription","@type":"xsd:anyURI"},status:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#status","@type":"xsd:string"},value:{"@id":"https://schema.org/value","@type":"xsd:string"}}},ResultDescription:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#ResultDescription","@context":{allowedValue:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#allowedValue","@type":"xsd:string","@container":"@set"},requiredLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#requiredLevel","@type":"xsd:anyURI"},requiredValue:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#requiredValue","@type":"xsd:string"},resultType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#resultType","@type":"xsd:string"},rubricCriterionLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#rubricCriterionLevel","@type":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#RubricCriterionLevel","@container":"@set"},valueMax:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#valueMax","@type":"xsd:string"},valueMin:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#valueMin","@type":"xsd:string"}}},RubricCriterionLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#RubricCriterionLevel","@context":{level:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#level","@type":"xsd:string"},points:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#points","@type":"xsd:string"}}},alignment:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#alignment","@type":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Alignment","@container":"@set"},description:{"@id":"https://schema.org/description","@type":"xsd:string"},endorsement:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#endorsement","@type":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#EndorsementCredential","@container":"@set"},image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#image","@type":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Image"},name:{"@id":"https://schema.org/name","@type":"xsd:string"},narrative:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#narrative","@type":"xsd:string"},url:{"@id":"https://schema.org/url","@type":"xsd:anyURI"}}};},function(t,e,i){/*! + * Copyright (c) 2023 Digital Credentials Consortium. All rights reserved. + */t.exports={"@context":{id:"@id",type:"@type",xsd:"https://www.w3.org/2001/XMLSchema#",OpenBadgeCredential:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#OpenBadgeCredential"},Achievement:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Achievement","@context":{achievementType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#achievementType","@type":"xsd:string"},alignment:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#alignment","@container":"@set"},creator:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#creator"},creditsAvailable:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#creditsAvailable","@type":"xsd:float"},criteria:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Criteria","@type":"@id"},fieldOfStudy:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#fieldOfStudy","@type":"xsd:string"},humanCode:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#humanCode","@type":"xsd:string"},image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Image","@type":"@id"},otherIdentifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#otherIdentifier","@container":"@set"},related:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#related","@container":"@set"},resultDescription:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#resultDescription","@container":"@set"},specialization:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#specialization","@type":"xsd:string"},tag:{"@id":"https://schema.org/keywords","@type":"xsd:string","@container":"@set"},version:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#version","@type":"xsd:string"}}},AchievementCredential:{"@id":"OpenBadgeCredential"},AchievementSubject:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#AchievementSubject","@context":{achievement:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#achievement-0"},activityEndDate:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#activityEndDate","@type":"xsd:date"},activityStartDate:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#activityStartDate","@type":"xsd:date"},creditsEarned:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#creditsEarned","@type":"xsd:float"},identifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identifier","@container":"@set"},image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Image","@type":"@id"},licenseNumber:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#licenseNumber","@type":"xsd:string"},result:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#result","@container":"@set"},role:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#role","@type":"xsd:string"},source:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#source","@type":"@id"},term:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#term","@type":"xsd:string"}}},Address:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Address","@context":{addressCountry:{"@id":"https://schema.org/addressCountry","@type":"xsd:string"},addressCountryCode:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#CountryCode","@type":"xsd:string"},addressLocality:{"@id":"https://schema.org/addressLocality","@type":"xsd:string"},addressRegion:{"@id":"https://schema.org/addressRegion","@type":"xsd:string"},geo:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#GeoCoordinates"},postOfficeBoxNumber:{"@id":"https://schema.org/postOfficeBoxNumber","@type":"xsd:string"},postalCode:{"@id":"https://schema.org/postalCode","@type":"xsd:string"},streetAddress:{"@id":"https://schema.org/streetAddress","@type":"xsd:string"}}},Alignment:{"@id":"https://schema.org/AlignmentObject","@context":{targetCode:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#targetCode","@type":"xsd:string"},targetDescription:{"@id":"https://schema.org/targetDescription","@type":"xsd:string"},targetFramework:{"@id":"https://schema.org/targetFramework","@type":"xsd:string"},targetName:{"@id":"https://schema.org/targetName","@type":"xsd:string"},targetType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#targetType","@type":"xsd:string"},targetUrl:{"@id":"https://schema.org/targetUrl","@type":"xsd:anyURI"}}},Criteria:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Criteria"},EndorsementCredential:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#EndorsementCredential"},EndorsementSubject:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#EndorsementSubject","@context":{endorsementComment:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#endorsementComment","@type":"xsd:string"}}},Evidence:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Evidence","@context":{audience:{"@id":"https://schema.org/audience","@type":"xsd:string"},genre:{"@id":"https://schema.org/genre","@type":"xsd:string"}}},GeoCoordinates:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#GeoCoordinates","@context":{latitude:{"@id":"https://schema.org/latitude","@type":"xsd:string"},longitude:{"@id":"https://schema.org/longitude","@type":"xsd:string"}}},IdentifierEntry:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#IdentifierEntry","@context":{identifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identifier","@type":"xsd:string"},identifierType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identifierType","@type":"xsd:string"}}},IdentityObject:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#IdentityObject","@context":{hashed:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#hashed","@type":"xsd:boolean"},identityHash:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identityHash","@type":"xsd:string"},identityType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identityType","@type":"xsd:string"},salt:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#salt","@type":"xsd:string"}}},Image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Image","@context":{caption:{"@id":"https://schema.org/caption","@type":"xsd:string"}}},Profile:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Profile","@context":{additionalName:{"@id":"https://schema.org/additionalName","@type":"xsd:string"},address:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#address","@type":"@id"},dateOfBirth:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#dateOfBirth","@type":"xsd:date"},email:{"@id":"https://schema.org/email","@type":"xsd:string"},familyName:{"@id":"https://schema.org/familyName","@type":"xsd:string"},familyNamePrefix:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#familyNamePrefix","@type":"xsd:string"},givenName:{"@id":"https://schema.org/givenName","@type":"xsd:string"},honorificPrefix:{"@id":"https://schema.org/honorificPrefix","@type":"xsd:string"},honorificSuffix:{"@id":"https://schema.org/honorificSuffix","@type":"xsd:string"},image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Image","@type":"@id"},otherIdentifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#otherIdentifier","@container":"@set"},parentOrg:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#parentOrg","@type":"@id"},patronymicName:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#patronymicName","@type":"xsd:string"},phone:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#phone","@type":"xsd:string"},official:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#official","@type":"xsd:string"}}},Related:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Related","@context":{version:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#version","@type":"xsd:string"}}},Result:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Result","@context":{achievedLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#achievedLevel","@type":"xsd:anyURI"},resultDescription:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#resultDescription","@type":"xsd:anyURI"},status:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#status","@type":"xsd:string"},value:{"@id":"https://schema.org/value","@type":"xsd:string"}}},ResultDescription:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#ResultDescription","@context":{allowedValue:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#allowedValue","@type":"xsd:string","@container":"@set"},requiredLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#requiredLevel","@type":"xsd:anyURI"},requiredValue:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#requiredValue","@type":"xsd:string"},resultType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#resultType","@type":"xsd:string"},rubricCriterionLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#rubricCriterionLevel","@container":"@set"},valueMax:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#valueMax","@type":"xsd:string"},valueMin:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#valueMin","@type":"xsd:string"}}},RubricCriterionLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#RubricCriterionLevel","@context":{level:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#level","@type":"xsd:string"},points:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#points","@type":"xsd:string"}}},alignment:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#alignment","@container":"@set"},awardedDate:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#awardedDate","@type":"xsd:dateTime"},description:{"@id":"https://schema.org/description","@type":"xsd:string"},endorsement:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#endorsement","@container":"@set"},image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#image","@type":"@id"},name:{"@id":"https://schema.org/name","@type":"xsd:string"},narrative:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#narrative","@type":"xsd:string"},url:{"@id":"https://schema.org/url","@type":"xsd:anyURI"}}};},function(t,e,i){/*! + * Copyright (c) 2023 Digital Credentials Consortium. All rights reserved. + */t.exports={"@context":{"@protected":!0,id:"@id",type:"@type",OpenBadgeCredential:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#OpenBadgeCredential"},Achievement:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Achievement","@context":{"@protected":!0,id:"@id",type:"@type",achievementType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#achievementType"},alignment:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#alignment","@container":"@set"},creator:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#creator"},creditsAvailable:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#creditsAvailable","@type":"https://www.w3.org/2001/XMLSchema#float"},criteria:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Criteria","@type":"@id"},fieldOfStudy:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#fieldOfStudy"},humanCode:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#humanCode"},image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Image","@type":"@id"},otherIdentifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#otherIdentifier","@container":"@set"},related:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#related","@container":"@set"},resultDescription:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#resultDescription","@container":"@set"},specialization:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#specialization"},tag:{"@id":"https://schema.org/keywords","@container":"@set"},version:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#version"}}},AchievementCredential:{"@id":"OpenBadgeCredential"},AchievementSubject:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#AchievementSubject","@context":{"@protected":!0,id:"@id",type:"@type",achievement:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#achievement-0"},activityEndDate:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#activityEndDate","@type":"https://www.w3.org/2001/XMLSchema#date"},activityStartDate:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#activityStartDate","@type":"https://www.w3.org/2001/XMLSchema#date"},creditsEarned:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#creditsEarned","@type":"https://www.w3.org/2001/XMLSchema#float"},identifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identifier","@container":"@set"},image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Image","@type":"@id"},licenseNumber:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#licenseNumber"},result:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#result","@container":"@set"},role:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#role"},source:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#source","@type":"@id"},term:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#term"}}},Address:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Address","@context":{"@protected":!0,id:"@id",type:"@type",addressCountry:{"@id":"https://schema.org/addressCountry"},addressCountryCode:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#CountryCode"},addressLocality:{"@id":"https://schema.org/addressLocality"},addressRegion:{"@id":"https://schema.org/addressRegion"},geo:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#GeoCoordinates"},postOfficeBoxNumber:{"@id":"https://schema.org/postOfficeBoxNumber"},postalCode:{"@id":"https://schema.org/postalCode"},streetAddress:{"@id":"https://schema.org/streetAddress"}}},Alignment:{"@id":"https://schema.org/AlignmentObject","@context":{"@protected":!0,id:"@id",type:"@type",targetCode:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#targetCode"},targetDescription:{"@id":"https://schema.org/targetDescription"},targetFramework:{"@id":"https://schema.org/targetFramework"},targetName:{"@id":"https://schema.org/targetName"},targetType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#targetType"},targetUrl:{"@id":"https://schema.org/targetUrl","@type":"https://www.w3.org/2001/XMLSchema#anyURI"}}},Criteria:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Criteria"},EndorsementCredential:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#EndorsementCredential"},EndorsementSubject:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#EndorsementSubject","@context":{"@protected":!0,id:"@id",type:"@type",endorsementComment:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#endorsementComment"}}},Evidence:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Evidence","@context":{"@protected":!0,id:"@id",type:"@type",audience:{"@id":"https://schema.org/audience"},genre:{"@id":"https://schema.org/genre"}}},GeoCoordinates:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#GeoCoordinates","@context":{"@protected":!0,id:"@id",type:"@type",latitude:{"@id":"https://schema.org/latitude"},longitude:{"@id":"https://schema.org/longitude"}}},IdentifierEntry:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#IdentifierEntry","@context":{"@protected":!0,id:"@id",type:"@type",identifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identifier"},identifierType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identifierType"}}},IdentityObject:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#IdentityObject","@context":{"@protected":!0,id:"@id",type:"@type",hashed:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#hashed","@type":"https://www.w3.org/2001/XMLSchema#boolean"},identityHash:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identityHash"},identityType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identityType"},salt:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#salt"}}},Image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Image","@context":{"@protected":!0,id:"@id",type:"@type",caption:{"@id":"https://schema.org/caption"}}},Profile:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Profile","@context":{"@protected":!0,id:"@id",type:"@type",additionalName:{"@id":"https://schema.org/additionalName"},address:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#address","@type":"@id"},dateOfBirth:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#dateOfBirth","@type":"https://www.w3.org/2001/XMLSchema#date"},email:{"@id":"https://schema.org/email"},familyName:{"@id":"https://schema.org/familyName"},familyNamePrefix:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#familyNamePrefix"},givenName:{"@id":"https://schema.org/givenName"},honorificPrefix:{"@id":"https://schema.org/honorificPrefix"},honorificSuffix:{"@id":"https://schema.org/honorificSuffix"},image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Image","@type":"@id"},otherIdentifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#otherIdentifier","@container":"@set"},parentOrg:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#parentOrg","@type":"@id"},patronymicName:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#patronymicName"},phone:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#phone"},official:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#official"}}},Related:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Related","@context":{"@protected":!0,id:"@id",type:"@type",version:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#version"}}},Result:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Result","@context":{"@protected":!0,id:"@id",type:"@type",achievedLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#achievedLevel","@type":"https://www.w3.org/2001/XMLSchema#anyURI"},resultDescription:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#resultDescription","@type":"https://www.w3.org/2001/XMLSchema#anyURI"},status:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#status"},value:{"@id":"https://schema.org/value"}}},ResultDescription:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#ResultDescription","@context":{"@protected":!0,id:"@id",type:"@type",allowedValue:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#allowedValue","@container":"@list"},requiredLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#requiredLevel","@type":"https://www.w3.org/2001/XMLSchema#anyURI"},requiredValue:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#requiredValue"},resultType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#resultType"},rubricCriterionLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#rubricCriterionLevel","@container":"@set"},valueMax:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#valueMax"},valueMin:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#valueMin"}}},RubricCriterionLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#RubricCriterionLevel","@context":{"@protected":!0,id:"@id",type:"@type",level:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#level"},points:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#points"}}},alignment:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#alignment","@container":"@set"},description:{"@id":"https://schema.org/description"},endorsement:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#endorsement","@container":"@set"},image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Image","@type":"@id"},name:{"@id":"https://schema.org/name"},narrative:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#narrative"},url:{"@id":"https://schema.org/url","@type":"https://www.w3.org/2001/XMLSchema#anyURI"}}};},function(t,e,i){/*! + * Copyright (c) 2024 Digital Credentials Consortium. All rights reserved. + */t.exports={"@context":{"@protected":!0,id:"@id",type:"@type",OpenBadgeCredential:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#OpenBadgeCredential"},Achievement:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Achievement","@context":{"@protected":!0,id:"@id",type:"@type",achievementType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#achievementType"},alignment:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#alignment","@container":"@set"},creator:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#creator"},creditsAvailable:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#creditsAvailable","@type":"https://www.w3.org/2001/XMLSchema#float"},criteria:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Criteria","@type":"@id"},fieldOfStudy:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#fieldOfStudy"},humanCode:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#humanCode"},image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#image","@type":"@id"},otherIdentifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#otherIdentifier","@container":"@set"},related:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#related","@container":"@set"},resultDescription:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#resultDescription","@container":"@set"},specialization:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#specialization"},tag:{"@id":"https://schema.org/keywords","@container":"@set"},version:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#version"},inLanguage:{"@id":"https://schema.org/inLanguage"}}},AchievementCredential:{"@id":"OpenBadgeCredential"},AchievementSubject:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#AchievementSubject","@context":{"@protected":!0,id:"@id",type:"@type",achievement:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#achievement"},activityEndDate:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#activityEndDate","@type":"https://www.w3.org/2001/XMLSchema#date"},activityStartDate:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#activityStartDate","@type":"https://www.w3.org/2001/XMLSchema#date"},creditsEarned:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#creditsEarned","@type":"https://www.w3.org/2001/XMLSchema#float"},identifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identifier","@container":"@set"},image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#image","@type":"@id"},licenseNumber:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#licenseNumber"},result:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#result","@container":"@set"},role:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#role"},source:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#source","@type":"@id"},term:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#term"}}},Address:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Address","@context":{"@protected":!0,id:"@id",type:"@type",addressCountry:{"@id":"https://schema.org/addressCountry"},addressCountryCode:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#CountryCode"},addressLocality:{"@id":"https://schema.org/addressLocality"},addressRegion:{"@id":"https://schema.org/addressRegion"},geo:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#GeoCoordinates"},postOfficeBoxNumber:{"@id":"https://schema.org/postOfficeBoxNumber"},postalCode:{"@id":"https://schema.org/postalCode"},streetAddress:{"@id":"https://schema.org/streetAddress"}}},Alignment:{"@id":"https://schema.org/AlignmentObject","@context":{"@protected":!0,id:"@id",type:"@type",targetCode:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#targetCode"},targetDescription:{"@id":"https://schema.org/targetDescription"},targetFramework:{"@id":"https://schema.org/targetFramework"},targetName:{"@id":"https://schema.org/targetName"},targetType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#targetType"},targetUrl:{"@id":"https://schema.org/targetUrl","@type":"https://www.w3.org/2001/XMLSchema#anyURI"}}},Criteria:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Criteria"},EndorsementCredential:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#EndorsementCredential"},EndorsementSubject:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#EndorsementSubject","@context":{"@protected":!0,id:"@id",type:"@type",endorsementComment:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#endorsementComment"}}},Evidence:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Evidence","@context":{"@protected":!0,id:"@id",type:"@type",audience:{"@id":"https://schema.org/audience"},genre:{"@id":"https://schema.org/genre"}}},GeoCoordinates:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#GeoCoordinates","@context":{"@protected":!0,id:"@id",type:"@type",latitude:{"@id":"https://schema.org/latitude"},longitude:{"@id":"https://schema.org/longitude"}}},IdentifierEntry:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#IdentifierEntry","@context":{"@protected":!0,id:"@id",type:"@type",identifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identifier"},identifierType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identifierType"}}},IdentityObject:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#IdentityObject","@context":{"@protected":!0,id:"@id",type:"@type",hashed:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#hashed","@type":"https://www.w3.org/2001/XMLSchema#boolean"},identityHash:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identityHash"},identityType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#identityType"},salt:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#salt"}}},Image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Image","@context":{"@protected":!0,id:"@id",type:"@type",caption:{"@id":"https://schema.org/caption"}}},Profile:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Profile","@context":{"@protected":!0,id:"@id",type:"@type",additionalName:{"@id":"https://schema.org/additionalName"},address:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#address","@type":"@id"},dateOfBirth:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#dateOfBirth","@type":"https://www.w3.org/2001/XMLSchema#date"},email:{"@id":"https://schema.org/email"},familyName:{"@id":"https://schema.org/familyName"},familyNamePrefix:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#familyNamePrefix"},givenName:{"@id":"https://schema.org/givenName"},honorificPrefix:{"@id":"https://schema.org/honorificPrefix"},honorificSuffix:{"@id":"https://schema.org/honorificSuffix"},image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#image","@type":"@id"},otherIdentifier:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#otherIdentifier","@container":"@set"},parentOrg:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#parentOrg","@type":"@id"},patronymicName:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#patronymicName"},phone:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#phone"},official:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#official"}}},Related:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Related","@context":{"@protected":!0,id:"@id",type:"@type",version:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#version"},inLanguage:{"@id":"https://schema.org/inLanguage"}}},Result:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#Result","@context":{"@protected":!0,id:"@id",type:"@type",achievedLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#achievedLevel","@type":"https://www.w3.org/2001/XMLSchema#anyURI"},resultDescription:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#resultDescription","@type":"https://www.w3.org/2001/XMLSchema#anyURI"},status:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#status"},value:{"@id":"https://schema.org/value"}}},ResultDescription:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#ResultDescription","@context":{"@protected":!0,id:"@id",type:"@type",allowedValue:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#allowedValue","@container":"@list"},requiredLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#requiredLevel","@type":"https://www.w3.org/2001/XMLSchema#anyURI"},requiredValue:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#requiredValue"},resultType:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#resultType"},rubricCriterionLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#rubricCriterionLevel","@container":"@set"},valueMax:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#valueMax"},valueMin:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#valueMin"}}},RubricCriterionLevel:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#RubricCriterionLevel","@context":{"@protected":!0,id:"@id",type:"@type",level:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#level"},points:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#points"}}},alignment:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#alignment","@container":"@set"},description:{"@id":"https://schema.org/description"},endorsement:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#endorsement","@container":"@set"},image:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#image","@type":"@id"},inLanguage:{"@id":"https://schema.org/inLanguage"},name:{"@id":"https://schema.org/name"},narrative:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#narrative"},url:{"@id":"https://schema.org/url","@type":"https://www.w3.org/2001/XMLSchema#anyURI"},awardedDate:{"@id":"https://purl.imsglobal.org/spec/vc/ob/vocab.html#awardedDate","@type":"xsd:dateTime"}}};},function(t,e,i){/*! + * Copyright (c) 2024 Digital Credentials Consortium. All rights reserved. + */t.exports={"@context":{id:"@id",type:"@type","1EdTechJsonSchemaValidator2019":"https://purl.imsglobal.org/spec/vccs/v1p0/context.json#1EdTechJsonSchemaValidator2019","1EdTechRevocationList":"https://purl.imsglobal.org/spec/vcrl/v1p0/context.json#1EdTechRevocationList","1EdTechCredentialRefresh":"https://purl.imsglobal.org/spec/vccr/v1p0/context.json#1EdTechCredentialRefresh"}};}])); +}); + +var context$1 = unwrapExports(context); +var context_1 = context.contexts; +var context_2 = context.CONTEXT_URL_V3; +var context_3 = context.CONTEXT_URL_V3_ALPHA; +var context_4 = context.CONTEXT_URL_V3_JFF_V1; +var context_5 = context.CONTEXT_URL_V3_BETA; +var context_6 = context.CONTEXT_URL_V3_0_0; +var context_7 = context.CONTEXT_URL_V3_0_1; +var context_8 = context.CONTEXT_URL_V3_0_2; +var context_9 = context.CONTEXT_URL_V3_0_3; +var context_10 = context.CONTEXT_URL_V3_EXTENSIONS; + + + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/security-document-loader/dist/documentLoader.js" +/*!******************************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/security-document-loader/dist/documentLoader.js ***! + \******************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ httpClientHandler: () => (/* binding */ httpClientHandler), +/* harmony export */ securityLoader: () => (/* binding */ securityLoader) +/* harmony export */ }); +/* harmony import */ var _digitalcredentials_did_method_key__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @digitalcredentials/did-method-key */ "./node_modules/@digitalcredentials/did-method-key/lib/index.js"); +/* harmony import */ var _digitalcredentials_did_method_web__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @digitalcredentials/did-method-web */ "./node_modules/@digitalcredentials/did-method-web/lib/index.js"); +/* harmony import */ var _digitalcredentials_credentials_v2_context__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @digitalcredentials/credentials-v2-context */ "./node_modules/@digitalcredentials/credentials-v2-context/js/index.js"); +/* harmony import */ var _digitalbazaar_vc_bitstring_status_list_context__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @digitalbazaar/vc-bitstring-status-list-context */ "./node_modules/@digitalbazaar/vc-bitstring-status-list-context/js/index.js"); +/* harmony import */ var credentials_context__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! credentials-context */ "./node_modules/credentials-context/dist/context.esm.js"); +/* harmony import */ var _digitalbazaar_vc_status_list_context__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @digitalbazaar/vc-status-list-context */ "./node_modules/@digitalbazaar/vc-status-list-context/dist/context.esm.js"); +/* harmony import */ var _digitalbazaar_data_integrity_context__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @digitalbazaar/data-integrity-context */ "./node_modules/@digitalbazaar/data-integrity-context/dist/context.esm.js"); +/* harmony import */ var _digitalcredentials_ed25519_multikey__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @digitalcredentials/ed25519-multikey */ "./node_modules/@digitalcredentials/ed25519-multikey/lib/index.js"); +/* harmony import */ var _digitalcredentials_did_io__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @digitalcredentials/did-io */ "./node_modules/@digitalcredentials/did-io/dist/esm/index.js"); +/* harmony import */ var _digitalcredentials_dcc_context__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @digitalcredentials/dcc-context */ "./node_modules/@digitalcredentials/dcc-context/js/index.js"); +/* harmony import */ var did_context__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! did-context */ "./node_modules/did-context/dist/context.esm.js"); +/* harmony import */ var ed25519_signature_2020_context__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ed25519-signature-2020-context */ "./node_modules/ed25519-signature-2020-context/dist/context.esm.js"); +/* harmony import */ var x25519_key_agreement_2020_context__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! x25519-key-agreement-2020-context */ "./node_modules/x25519-key-agreement-2020-context/dist/context.esm.js"); +/* harmony import */ var jsonld_document_loader__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! jsonld-document-loader */ "./node_modules/jsonld-document-loader/lib/index.js"); +/* harmony import */ var _digitalcredentials_open_badges_context__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @digitalcredentials/open-badges-context */ "./node_modules/@digitalcredentials/open-badges-context/dist/context.esm.js"); +/* harmony import */ var _digitalcredentials_http_client__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @digitalcredentials/http-client */ "./node_modules/@digitalcredentials/http-client/dist/esm/index.js"); +/* harmony import */ var _parseResponse_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./parseResponse.js */ "./node_modules/@digitalcredentials/security-document-loader/dist/parseResponse.js"); +/*! + * Copyright (c) 2021 Interop Alliance and Dmitri Zagidulin. All rights reserved. + */ + + + + + + + + +// import { Ed25519VerificationKey2020 } +// from '@digitalcredentials/ed25519-verification-key-2020'; +// import { X25519KeyAgreementKey2020 } +// from '@digitalcredentials/x25519-key-agreement-key-2020'; + + + + + + + + + +const resolver = new _digitalcredentials_did_io__WEBPACK_IMPORTED_MODULE_8__.CachedResolver(); +const didKeyDriver = _digitalcredentials_did_method_key__WEBPACK_IMPORTED_MODULE_0__.driver(); +const didWebDriver = _digitalcredentials_did_method_web__WEBPACK_IMPORTED_MODULE_1__.driver(); +resolver.use(didKeyDriver); +resolver.use(didWebDriver); +didWebDriver.use({ + multibaseMultikeyHeader: 'z6Mk', + fromMultibase: _digitalcredentials_ed25519_multikey__WEBPACK_IMPORTED_MODULE_7__.from +}); +didKeyDriver.use({ + multibaseMultikeyHeader: 'z6Mk', + fromMultibase: _digitalcredentials_ed25519_multikey__WEBPACK_IMPORTED_MODULE_7__.from +}); +const httpClientHandler = { + /** + * @param {object} options - Options hashmap. + * @param {string} options.url - Document URL. + * @returns {Promise<{contextUrl: null, document, documentUrl}>} - Resolves + * with documentLoader document. + */ + async get(params) { + if (!params.url.startsWith('http')) { + throw new Error('NotFoundError'); + } + let result; + try { + const headers = { + 'Cache-Control': 'no-cache', + 'Pragma': 'no-cache' + }; + result = await _digitalcredentials_http_client__WEBPACK_IMPORTED_MODULE_15__.httpClient.get(params.url, { headers, parseBody: false }); + } + catch (e) { + throw new Error(`NotFoundError loading "${params.url}": ${e.message}`); + } + return (0,_parseResponse_js__WEBPACK_IMPORTED_MODULE_16__.parseResponseBody)(result); + } +}; +function securityLoader({ fetchRemoteContexts = false, useOBv3BetaContext = false } = {}) { + const loader = new jsonld_document_loader__WEBPACK_IMPORTED_MODULE_13__.JsonLdDocumentLoader(); + // Ed25519 Signature 2020 Context + loader.addStatic(ed25519_signature_2020_context__WEBPACK_IMPORTED_MODULE_11__["default"].constants.CONTEXT_URL, ed25519_signature_2020_context__WEBPACK_IMPORTED_MODULE_11__["default"].contexts.get(ed25519_signature_2020_context__WEBPACK_IMPORTED_MODULE_11__["default"].constants.CONTEXT_URL)); + // X25519 Key Agreement 2020 Context + loader.addStatic(x25519_key_agreement_2020_context__WEBPACK_IMPORTED_MODULE_12__["default"].constants.CONTEXT_URL, x25519_key_agreement_2020_context__WEBPACK_IMPORTED_MODULE_12__["default"].contexts.get(x25519_key_agreement_2020_context__WEBPACK_IMPORTED_MODULE_12__["default"].constants.CONTEXT_URL)); + // DID Context + loader.addStatic(did_context__WEBPACK_IMPORTED_MODULE_10__["default"].constants.DID_CONTEXT_URL, did_context__WEBPACK_IMPORTED_MODULE_10__["default"].contexts.get(did_context__WEBPACK_IMPORTED_MODULE_10__["default"].constants.DID_CONTEXT_URL)); + // Verifiable Credentials Data Model 1.0 Context + loader.addStatic(credentials_context__WEBPACK_IMPORTED_MODULE_4__["default"].CONTEXT_URL, credentials_context__WEBPACK_IMPORTED_MODULE_4__["default"].CONTEXT); + // Verifiable Credentials Data Model 2.0 Context - BETA / non-final + loader.addStatic(_digitalcredentials_credentials_v2_context__WEBPACK_IMPORTED_MODULE_2__.CONTEXT_URL, _digitalcredentials_credentials_v2_context__WEBPACK_IMPORTED_MODULE_2__.CONTEXT); + // Data Integrity Context + for (const [url, context] of _digitalbazaar_data_integrity_context__WEBPACK_IMPORTED_MODULE_6__["default"].contexts) { + loader.addStatic(url, context); + } + // DCC Context + loader.addStatic(_digitalcredentials_dcc_context__WEBPACK_IMPORTED_MODULE_9__.CONTEXT_URL_V1, _digitalcredentials_dcc_context__WEBPACK_IMPORTED_MODULE_9__.CONTEXT_V1); + // Bitstring Status List Context + loader.addStatic(_digitalbazaar_vc_bitstring_status_list_context__WEBPACK_IMPORTED_MODULE_3__.CONTEXT_URL, _digitalbazaar_vc_bitstring_status_list_context__WEBPACK_IMPORTED_MODULE_3__.CONTEXT); + // Status List 2021 Context (DEPRECATED) + loader.addStatic(_digitalbazaar_vc_status_list_context__WEBPACK_IMPORTED_MODULE_5__["default"].CONTEXT_URL_V1, _digitalbazaar_vc_status_list_context__WEBPACK_IMPORTED_MODULE_5__["default"].CONTEXT_V1); + // Open Badges v3 Contexts, includes OBv3 Beta, 3.0, 3.0.1, 3.0.2, etc. + for (const [url, context] of _digitalcredentials_open_badges_context__WEBPACK_IMPORTED_MODULE_14__["default"].contexts) { + loader.addStatic(url, context); + } + if (useOBv3BetaContext) { + // Workaround to validate legacy OBv3 BETA context VCs + loader.addStatic(_digitalcredentials_open_badges_context__WEBPACK_IMPORTED_MODULE_14__["default"].CONTEXT_URL_V3_0_0, _digitalcredentials_open_badges_context__WEBPACK_IMPORTED_MODULE_14__["default"].contexts.get(_digitalcredentials_open_badges_context__WEBPACK_IMPORTED_MODULE_14__["default"].CONTEXT_URL_V3_BETA)); + } + loader.setDidResolver(resolver); + // Enable loading of arbitrary contexts from web + if (fetchRemoteContexts) { + loader.setProtocolHandler({ protocol: 'http', handler: httpClientHandler }); + loader.setProtocolHandler({ protocol: 'https', handler: httpClientHandler }); + } + return loader; +} + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/security-document-loader/dist/index.js" +/*!*********************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/security-document-loader/dist/index.js ***! + \*********************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ httpClientHandler: () => (/* reexport safe */ _documentLoader_js__WEBPACK_IMPORTED_MODULE_0__.httpClientHandler), +/* harmony export */ securityLoader: () => (/* reexport safe */ _documentLoader_js__WEBPACK_IMPORTED_MODULE_0__.securityLoader) +/* harmony export */ }); +/* harmony import */ var _documentLoader_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./documentLoader.js */ "./node_modules/@digitalcredentials/security-document-loader/dist/documentLoader.js"); +/*! + * Copyright (c) 2021 Interop Alliance and Dmitri Zagidulin. All rights reserved. + */ + + + +/***/ }, + +/***/ "./node_modules/@digitalcredentials/security-document-loader/dist/parseResponse.js" +/*!*****************************************************************************************!*\ + !*** ./node_modules/@digitalcredentials/security-document-loader/dist/parseResponse.js ***! + \*****************************************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ parseResponseBody: () => (/* binding */ parseResponseBody) +/* harmony export */ }); +/* harmony import */ var html_entities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! html-entities */ "./node_modules/html-entities/dist/esm/index.js"); + +async function parseResponseBody(response) { + const responseText = await response.text(); + const responseTextDecoded = html_entities__WEBPACK_IMPORTED_MODULE_0__.decode(responseText); + return JSON.parse(responseTextDecoded); +} + + +/***/ }, + +/***/ "./node_modules/@noble/ed25519/lib/esm/index.js" +/*!******************************************************!*\ + !*** ./node_modules/@noble/ed25519/lib/esm/index.js ***! + \******************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +var crypto__WEBPACK_IMPORTED_MODULE_0___namespace_cache; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CURVE: () => (/* binding */ CURVE), +/* harmony export */ ExtendedPoint: () => (/* binding */ ExtendedPoint), +/* harmony export */ Point: () => (/* binding */ Point), +/* harmony export */ RistrettoPoint: () => (/* binding */ RistrettoPoint), +/* harmony export */ Signature: () => (/* binding */ Signature), +/* harmony export */ bytesToHex: () => (/* binding */ bytesToHex), +/* harmony export */ curve25519: () => (/* binding */ curve25519), +/* harmony export */ getPublicKey: () => (/* binding */ getPublicKey), +/* harmony export */ getSharedSecret: () => (/* binding */ getSharedSecret), +/* harmony export */ hexToBytes: () => (/* binding */ hexToBytes), +/* harmony export */ sign: () => (/* binding */ sign), +/* harmony export */ sync: () => (/* binding */ sync), +/* harmony export */ utils: () => (/* binding */ utils), +/* harmony export */ verify: () => (/* binding */ verify) +/* harmony export */ }); +/* harmony import */ var crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! crypto */ "?51ea"); +/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */ + +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const _8n = BigInt(8); +const CU_O = BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'); +const CURVE = Object.freeze({ + a: BigInt(-1), + d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'), + P: BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949'), + l: CU_O, + n: CU_O, + h: BigInt(8), + Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'), + Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'), +}); + +const POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000'); +const SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); +const SQRT_D = BigInt('6853475219497561581579357271197624642482790079785650197046958215289687604742'); +const SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); +const INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); +const ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); +const D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); +class ExtendedPoint { + constructor(x, y, z, t) { + this.x = x; + this.y = y; + this.z = z; + this.t = t; + } + static fromAffine(p) { + if (!(p instanceof Point)) { + throw new TypeError('ExtendedPoint#fromAffine: expected Point'); + } + if (p.equals(Point.ZERO)) + return ExtendedPoint.ZERO; + return new ExtendedPoint(p.x, p.y, _1n, mod(p.x * p.y)); + } + static toAffineBatch(points) { + const toInv = invertBatch(points.map((p) => p.z)); + return points.map((p, i) => p.toAffine(toInv[i])); + } + static normalizeZ(points) { + return this.toAffineBatch(points).map(this.fromAffine); + } + equals(other) { + assertExtPoint(other); + const { x: X1, y: Y1, z: Z1 } = this; + const { x: X2, y: Y2, z: Z2 } = other; + const X1Z2 = mod(X1 * Z2); + const X2Z1 = mod(X2 * Z1); + const Y1Z2 = mod(Y1 * Z2); + const Y2Z1 = mod(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + negate() { + return new ExtendedPoint(mod(-this.x), this.y, this.z, mod(-this.t)); + } + double() { + const { x: X1, y: Y1, z: Z1 } = this; + const { a } = CURVE; + const M = mod; + const A = M(X1 * X1); + const B = M(Y1 * Y1); + const C = M(_2n * M(Z1 * Z1)); + const D = M(a * A); + const x1y1 = X1 + Y1; + const E = M(M(x1y1 * x1y1) - A - B); + const G = D + B; + const F = G - C; + const H = D - B; + const X3 = M(E * F); + const Y3 = M(G * H); + const T3 = M(E * H); + const Z3 = M(F * G); + return new ExtendedPoint(X3, Y3, Z3, T3); + } + add(other) { + const { x: X1, y: Y1, z: Z1, t: T1 } = this; + assertExtPoint(other); + const { x: X2, y: Y2, z: Z2, t: T2 } = other; + const { a, d } = CURVE; + const M = mod; + const A = M(X1 * X2); + const B = M(Y1 * Y2); + const C = M(T1 * d * T2); + const D = M(Z1 * Z2); + const E = M((X1 + Y1) * (X2 + Y2) - A - B); + const F = M(D - C); + const G = M(D + C); + const H = M(B - a * A); + const X3 = M(E * F); + const Y3 = M(G * H); + const T3 = M(E * H); + const Z3 = M(F * G); + return new ExtendedPoint(X3, Y3, Z3, T3); + } + subtract(other) { + return this.add(other.negate()); + } + precomputeWindow(W) { + const windows = 1 + 256 / W; + const points = []; + let p = this; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + for (let i = 1; i < 2 ** (W - 1); i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + } + wNAF(n, affinePoint) { + if (!affinePoint && this.equals(ExtendedPoint.BASE)) + affinePoint = Point.BASE; + const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1; + if (256 % W) { + throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2'); + } + let precomputes = affinePoint && pointPrecomputes.get(affinePoint); + if (!precomputes) { + precomputes = this.precomputeWindow(W); + if (affinePoint && W !== 1) { + precomputes = ExtendedPoint.normalizeZ(precomputes); + pointPrecomputes.set(affinePoint, precomputes); + } + } + let p = ExtendedPoint.ZERO; + let f = ExtendedPoint.BASE; + const windows = 1 + 256 / W; + const windowSize = 2 ** (W - 1); + const mask = BigInt(2 ** W - 1); + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for (let window = 0; window < windows; window++) { + const offset = window * windowSize; + let wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n; + } + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; + const cond1 = window % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } + else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + return ExtendedPoint.normalizeZ([p, f])[0]; + } + multiply(scalar, affinePoint) { + return this.wNAF(normalizeScalar(scalar, CURVE.l), affinePoint); + } + multiplyUnsafe(scalar) { + let n = normalizeScalar(scalar, CURVE.l, false); + const G = ExtendedPoint.BASE; + const P0 = ExtendedPoint.ZERO; + if (n === _0n) + return P0; + if (this.equals(P0) || n === _1n) + return this; + if (this.equals(G)) + return this.wNAF(n); + let p = P0; + let d = this; + while (n > _0n) { + if (n & _1n) + p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + } + isSmallOrder() { + return this.multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO); + } + isTorsionFree() { + let p = this.multiplyUnsafe(CURVE.l / _2n).double(); + if (CURVE.l % _2n) + p = p.add(this); + return p.equals(ExtendedPoint.ZERO); + } + toAffine(invZ) { + const { x, y, z } = this; + const is0 = this.equals(ExtendedPoint.ZERO); + if (invZ == null) + invZ = is0 ? _8n : invert(z); + const ax = mod(x * invZ); + const ay = mod(y * invZ); + const zz = mod(z * invZ); + if (is0) + return Point.ZERO; + if (zz !== _1n) + throw new Error('invZ was invalid'); + return new Point(ax, ay); + } + fromRistrettoBytes() { + legacyRist(); + } + toRistrettoBytes() { + legacyRist(); + } + fromRistrettoHash() { + legacyRist(); + } +} +ExtendedPoint.BASE = new ExtendedPoint(CURVE.Gx, CURVE.Gy, _1n, mod(CURVE.Gx * CURVE.Gy)); +ExtendedPoint.ZERO = new ExtendedPoint(_0n, _1n, _1n, _0n); +function constTimeNegate(condition, item) { + const neg = item.negate(); + return condition ? neg : item; +} +function assertExtPoint(other) { + if (!(other instanceof ExtendedPoint)) + throw new TypeError('ExtendedPoint expected'); +} +function assertRstPoint(other) { + if (!(other instanceof RistrettoPoint)) + throw new TypeError('RistrettoPoint expected'); +} +function legacyRist() { + throw new Error('Legacy method: switch to RistrettoPoint'); +} +class RistrettoPoint { + constructor(ep) { + this.ep = ep; + } + static calcElligatorRistrettoMap(r0) { + const { d } = CURVE; + const r = mod(SQRT_M1 * r0 * r0); + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); + let c = BigInt(-1); + const D = mod((c - d * r) * mod(r + d)); + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); + let s_ = mod(s * r0); + if (!edIsNegative(s_)) + s_ = mod(-s_); + if (!Ns_D_is_sq) + s = s_; + if (!Ns_D_is_sq) + c = r; + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); + const s2 = s * s; + const W0 = mod((s + s) * D); + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); + const W2 = mod(_1n - s2); + const W3 = mod(_1n + s2); + return new ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); + } + static hashToCurve(hex) { + hex = ensureBytes(hex, 64); + const r1 = bytes255ToNumberLE(hex.slice(0, 32)); + const R1 = this.calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(hex.slice(32, 64)); + const R2 = this.calcElligatorRistrettoMap(r2); + return new RistrettoPoint(R1.add(R2)); + } + static fromHex(hex) { + hex = ensureBytes(hex, 32); + const { a, d } = CURVE; + const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint'; + const s = bytes255ToNumberLE(hex); + if (!equalBytes(numberTo32BytesLE(s), hex) || edIsNegative(s)) + throw new Error(emsg); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); + const u2 = mod(_1n - a * s2); + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); + const Dx = mod(I * u2); + const Dy = mod(I * Dx * v); + let x = mod((s + s) * Dx); + if (edIsNegative(x)) + x = mod(-x); + const y = mod(u1 * Dy); + const t = mod(x * y); + if (!isValid || edIsNegative(t) || y === _0n) + throw new Error(emsg); + return new RistrettoPoint(new ExtendedPoint(x, y, _1n, t)); + } + toRawBytes() { + let { x, y, z, t } = this.ep; + const u1 = mod(mod(z + y) * mod(z - y)); + const u2 = mod(x * y); + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); + const D1 = mod(invsqrt * u1); + const D2 = mod(invsqrt * u2); + const zInv = mod(D1 * D2 * t); + let D; + if (edIsNegative(t * zInv)) { + let _x = mod(y * SQRT_M1); + let _y = mod(x * SQRT_M1); + x = _x; + y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } + else { + D = D2; + } + if (edIsNegative(x * zInv)) + y = mod(-y); + let s = mod((z - y) * D); + if (edIsNegative(s)) + s = mod(-s); + return numberTo32BytesLE(s); + } + toHex() { + return bytesToHex(this.toRawBytes()); + } + toString() { + return this.toHex(); + } + equals(other) { + assertRstPoint(other); + const a = this.ep; + const b = other.ep; + const one = mod(a.x * b.y) === mod(a.y * b.x); + const two = mod(a.y * b.y) === mod(a.x * b.x); + return one || two; + } + add(other) { + assertRstPoint(other); + return new RistrettoPoint(this.ep.add(other.ep)); + } + subtract(other) { + assertRstPoint(other); + return new RistrettoPoint(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return new RistrettoPoint(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return new RistrettoPoint(this.ep.multiplyUnsafe(scalar)); + } +} +RistrettoPoint.BASE = new RistrettoPoint(ExtendedPoint.BASE); +RistrettoPoint.ZERO = new RistrettoPoint(ExtendedPoint.ZERO); +const pointPrecomputes = new WeakMap(); +class Point { + constructor(x, y) { + this.x = x; + this.y = y; + } + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + static fromHex(hex, strict = true) { + const { d, P } = CURVE; + hex = ensureBytes(hex, 32); + const normed = hex.slice(); + normed[31] = hex[31] & ~0x80; + const y = bytesToNumberLE(normed); + if (strict && y >= P) + throw new Error('Expected 0 < hex < P'); + if (!strict && y >= POW_2_256) + throw new Error('Expected 0 < hex < 2**256'); + const y2 = mod(y * y); + const u = mod(y2 - _1n); + const v = mod(d * y2 + _1n); + let { isValid, value: x } = uvRatio(u, v); + if (!isValid) + throw new Error('Point.fromHex: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; + const isLastByteOdd = (hex[31] & 0x80) !== 0; + if (isLastByteOdd !== isXOdd) { + x = mod(-x); + } + return new Point(x, y); + } + static async fromPrivateKey(privateKey) { + return (await getExtendedPublicKey(privateKey)).point; + } + toRawBytes() { + const bytes = numberTo32BytesLE(this.y); + bytes[31] |= this.x & _1n ? 0x80 : 0; + return bytes; + } + toHex() { + return bytesToHex(this.toRawBytes()); + } + toX25519() { + const { y } = this; + const u = mod((_1n + y) * invert(_1n - y)); + return numberTo32BytesLE(u); + } + isTorsionFree() { + return ExtendedPoint.fromAffine(this).isTorsionFree(); + } + equals(other) { + return this.x === other.x && this.y === other.y; + } + negate() { + return new Point(mod(-this.x), this.y); + } + add(other) { + return ExtendedPoint.fromAffine(this).add(ExtendedPoint.fromAffine(other)).toAffine(); + } + subtract(other) { + return this.add(other.negate()); + } + multiply(scalar) { + return ExtendedPoint.fromAffine(this).multiply(scalar, this).toAffine(); + } +} +Point.BASE = new Point(CURVE.Gx, CURVE.Gy); +Point.ZERO = new Point(_0n, _1n); +class Signature { + constructor(r, s) { + this.r = r; + this.s = s; + this.assertValidity(); + } + static fromHex(hex) { + const bytes = ensureBytes(hex, 64); + const r = Point.fromHex(bytes.slice(0, 32), false); + const s = bytesToNumberLE(bytes.slice(32, 64)); + return new Signature(r, s); + } + assertValidity() { + const { r, s } = this; + if (!(r instanceof Point)) + throw new Error('Expected Point instance'); + normalizeScalar(s, CURVE.l, false); + return this; + } + toRawBytes() { + const u8 = new Uint8Array(64); + u8.set(this.r.toRawBytes()); + u8.set(numberTo32BytesLE(this.s), 32); + return u8; + } + toHex() { + return bytesToHex(this.toRawBytes()); + } +} + +function isBytes(a) { + return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array'); +} +function abytes(item) { + if (!isBytes(item)) + throw new Error('Uint8Array expected'); +} +function concatBytes(...arrays) { + arrays.every(abytes); + if (arrays.length === 1) + return arrays[0]; + const length = arrays.reduce((a, arr) => a + arr.length, 0); + const result = new Uint8Array(length); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const arr = arrays[i]; + result.set(arr, pad); + pad += arr.length; + } + return result; +} +const hexes = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +function bytesToHex(bytes) { + abytes(bytes); + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; +function asciiToBase16(ch) { + if (ch >= asciis._0 && ch <= asciis._9) + return ch - asciis._0; + if (ch >= asciis.A && ch <= asciis.F) + return ch - (asciis.A - 10); + if (ch >= asciis.a && ch <= asciis.f) + return ch - (asciis.a - 10); + return; +} +function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error('hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; + } + return array; +} +function numberTo32BytesBE(num) { + const length = 32; + const hex = num.toString(16).padStart(length * 2, '0'); + return hexToBytes(hex); +} +function numberTo32BytesLE(num) { + return numberTo32BytesBE(num).reverse(); +} +function edIsNegative(num) { + return (mod(num) & _1n) === _1n; +} +function bytesToNumberLE(uint8a) { + abytes(uint8a); + return BigInt('0x' + bytesToHex(Uint8Array.from(uint8a).reverse())); +} +const MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +function bytes255ToNumberLE(bytes) { + return mod(bytesToNumberLE(bytes) & MAX_255B); +} +function mod(a, b = CURVE.P) { + const res = a % b; + return res >= _0n ? res : b + res; +} +function invert(number, modulo = CURVE.P) { + if (number === _0n || modulo <= _0n) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + let a = mod(number, modulo); + let b = modulo; + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +function invertBatch(nums, p = CURVE.P) { + const tmp = new Array(nums.length); + const lastMultiplied = nums.reduce((acc, num, i) => { + if (num === _0n) + return acc; + tmp[i] = acc; + return mod(acc * num, p); + }, _1n); + const inverted = invert(lastMultiplied, p); + nums.reduceRight((acc, num, i) => { + if (num === _0n) + return acc; + tmp[i] = mod(acc * tmp[i], p); + return mod(acc * num, p); + }, inverted); + return tmp; +} +function pow2(x, power) { + const { P } = CURVE; + let res = x; + while (power-- > _0n) { + res *= res; + res %= P; + } + return res; +} +function pow_2_252_3(x) { + const { P } = CURVE; + const _5n = BigInt(5); + const _10n = BigInt(10); + const _20n = BigInt(20); + const _40n = BigInt(40); + const _80n = BigInt(80); + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; + const b4 = (pow2(b2, _2n) * b2) % P; + const b5 = (pow2(b4, _1n) * x) % P; + const b10 = (pow2(b5, _5n) * b5) % P; + const b20 = (pow2(b10, _10n) * b10) % P; + const b40 = (pow2(b20, _20n) * b20) % P; + const b80 = (pow2(b40, _40n) * b40) % P; + const b160 = (pow2(b80, _80n) * b80) % P; + const b240 = (pow2(b160, _80n) * b80) % P; + const b250 = (pow2(b240, _10n) * b10) % P; + const pow_p_5_8 = (pow2(b250, _2n) * x) % P; + return { pow_p_5_8, b2 }; +} +function uvRatio(u, v) { + const v3 = mod(v * v * v); + const v7 = mod(v3 * v3 * v); + const pow = pow_2_252_3(u * v7).pow_p_5_8; + let x = mod(u * v3 * pow); + const vx2 = mod(v * x * x); + const root1 = x; + const root2 = mod(x * SQRT_M1); + const useRoot1 = vx2 === u; + const useRoot2 = vx2 === mod(-u); + const noRoot = vx2 === mod(-u * SQRT_M1); + if (useRoot1) + x = root1; + if (useRoot2 || noRoot) + x = root2; + if (edIsNegative(x)) + x = mod(-x); + return { isValid: useRoot1 || useRoot2, value: x }; +} +function invertSqrt(number) { + return uvRatio(_1n, number); +} +function modlLE(hash) { + return mod(bytesToNumberLE(hash), CURVE.l); +} +function equalBytes(b1, b2) { + if (b1.length !== b2.length) { + return false; + } + for (let i = 0; i < b1.length; i++) { + if (b1[i] !== b2[i]) { + return false; + } + } + return true; +} +function ensureBytes(hex, expectedLength) { + const bytes = isBytes(hex) ? Uint8Array.from(hex) : hexToBytes(hex); + if (typeof expectedLength === 'number' && bytes.length !== expectedLength) + throw new Error(`Expected ${expectedLength} bytes`); + return bytes; +} +function normalizeScalar(num, max, strict = true) { + if (!max) + throw new TypeError('Specify max value'); + if (typeof num === 'number' && Number.isSafeInteger(num)) + num = BigInt(num); + if (typeof num === 'bigint' && num < max) { + if (strict) { + if (_0n < num) + return num; + } + else { + if (_0n <= num) + return num; + } + } + throw new TypeError('Expected valid scalar: 0 < scalar < max'); +} +function adjustBytes25519(bytes) { + bytes[0] &= 248; + bytes[31] &= 127; + bytes[31] |= 64; + return bytes; +} +function decodeScalar25519(n) { + return bytesToNumberLE(adjustBytes25519(ensureBytes(n, 32))); +} +function checkPrivateKey(key) { + key = + typeof key === 'bigint' || typeof key === 'number' + ? numberTo32BytesBE(normalizeScalar(key, POW_2_256)) + : ensureBytes(key); + if (key.length !== 32) + throw new Error(`Expected 32 bytes`); + return key; +} +function getKeyFromHash(hashed) { + const head = adjustBytes25519(hashed.slice(0, 32)); + const prefix = hashed.slice(32, 64); + const scalar = modlLE(head); + const point = Point.BASE.multiply(scalar); + const pointBytes = point.toRawBytes(); + return { head, prefix, scalar, point, pointBytes }; +} +let _sha512Sync; +function sha512s(...m) { + if (typeof _sha512Sync !== 'function') + throw new Error('utils.sha512Sync must be set to use sync methods'); + return _sha512Sync(...m); +} +async function getExtendedPublicKey(key) { + return getKeyFromHash(await utils.sha512(checkPrivateKey(key))); +} +function getExtendedPublicKeySync(key) { + return getKeyFromHash(sha512s(checkPrivateKey(key))); +} +async function getPublicKey(privateKey) { + return (await getExtendedPublicKey(privateKey)).pointBytes; +} +function getPublicKeySync(privateKey) { + return getExtendedPublicKeySync(privateKey).pointBytes; +} +async function sign(message, privateKey) { + message = ensureBytes(message); + const { prefix, scalar, pointBytes } = await getExtendedPublicKey(privateKey); + const r = modlLE(await utils.sha512(prefix, message)); + const R = Point.BASE.multiply(r); + const k = modlLE(await utils.sha512(R.toRawBytes(), pointBytes, message)); + const s = mod(r + k * scalar, CURVE.l); + return new Signature(R, s).toRawBytes(); +} +function signSync(message, privateKey) { + message = ensureBytes(message); + const { prefix, scalar, pointBytes } = getExtendedPublicKeySync(privateKey); + const r = modlLE(sha512s(prefix, message)); + const R = Point.BASE.multiply(r); + const k = modlLE(sha512s(R.toRawBytes(), pointBytes, message)); + const s = mod(r + k * scalar, CURVE.l); + return new Signature(R, s).toRawBytes(); +} +function prepareVerification(sig, message, publicKey) { + message = ensureBytes(message); + if (!(publicKey instanceof Point)) + publicKey = Point.fromHex(publicKey, false); + const { r, s } = sig instanceof Signature ? sig.assertValidity() : Signature.fromHex(sig); + const SB = ExtendedPoint.BASE.multiplyUnsafe(s); + return { r, s, SB, pub: publicKey, msg: message }; +} +function finishVerification(publicKey, r, SB, hashed) { + const k = modlLE(hashed); + const kA = ExtendedPoint.fromAffine(publicKey).multiplyUnsafe(k); + const RkA = ExtendedPoint.fromAffine(r).add(kA); + return RkA.subtract(SB).multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO); +} +async function verify(sig, message, publicKey) { + const { r, SB, msg, pub } = prepareVerification(sig, message, publicKey); + const hashed = await utils.sha512(r.toRawBytes(), pub.toRawBytes(), msg); + return finishVerification(pub, r, SB, hashed); +} +function verifySync(sig, message, publicKey) { + const { r, SB, msg, pub } = prepareVerification(sig, message, publicKey); + const hashed = sha512s(r.toRawBytes(), pub.toRawBytes(), msg); + return finishVerification(pub, r, SB, hashed); +} +const sync = { + getExtendedPublicKey: getExtendedPublicKeySync, + getPublicKey: getPublicKeySync, + sign: signSync, + verify: verifySync, +}; +async function getSharedSecret(privateKey, publicKey) { + const { head } = await getExtendedPublicKey(privateKey); + const u = Point.fromHex(publicKey).toX25519(); + return curve25519.scalarMult(head, u); +} +Point.BASE._setWindowSize(8); +function cswap(swap, x_2, x_3) { + const dummy = mod(swap * (x_2 - x_3)); + x_2 = mod(x_2 - dummy); + x_3 = mod(x_3 + dummy); + return [x_2, x_3]; +} +function montgomeryLadder(pointU, scalar) { + const { P } = CURVE; + const u = normalizeScalar(pointU, P); + const k = normalizeScalar(scalar, P); + const a24 = BigInt(121665); + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + let sw; + for (let t = BigInt(255 - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + swap = k_t; + const A = x_2 + z_2; + const AA = mod(A * A); + const B = x_2 - z_2; + const BB = mod(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = mod(D * A); + const CB = mod(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = mod(dacb * dacb); + z_3 = mod(x_1 * mod(da_cb * da_cb)); + x_2 = mod(AA * BB); + z_2 = mod(E * (AA + mod(a24 * E))); + } + sw = cswap(swap, x_2, x_3); + x_2 = sw[0]; + x_3 = sw[1]; + sw = cswap(swap, z_2, z_3); + z_2 = sw[0]; + z_3 = sw[1]; + const { pow_p_5_8, b2 } = pow_2_252_3(z_2); + const xp2 = mod(pow2(pow_p_5_8, BigInt(3)) * b2); + return mod(x_2 * xp2); +} +function encodeUCoordinate(u) { + return numberTo32BytesLE(mod(u, CURVE.P)); +} +function decodeUCoordinate(uEnc) { + const u = ensureBytes(uEnc, 32); + u[31] &= 127; + return bytesToNumberLE(u); +} +const curve25519 = { + BASE_POINT_U: '0900000000000000000000000000000000000000000000000000000000000000', + scalarMult(privateKey, publicKey) { + const u = decodeUCoordinate(publicKey); + const p = decodeScalar25519(privateKey); + const pu = montgomeryLadder(u, p); + if (pu === _0n) + throw new Error('Invalid private or public key received'); + return encodeUCoordinate(pu); + }, + scalarMultBase(privateKey) { + return curve25519.scalarMult(privateKey, curve25519.BASE_POINT_U); + }, +}; +const crypto = { + node: /*#__PURE__*/ (crypto__WEBPACK_IMPORTED_MODULE_0___namespace_cache || (crypto__WEBPACK_IMPORTED_MODULE_0___namespace_cache = __webpack_require__.t(crypto__WEBPACK_IMPORTED_MODULE_0__, 2))), + web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined, +}; +const utils = { + bytesToHex, + hexToBytes, + concatBytes, + getExtendedPublicKey, + mod, + invert, + TORSION_SUBGROUP: [ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', + ], + hashToPrivateScalar: (hash) => { + hash = ensureBytes(hash); + if (hash.length < 40 || hash.length > 1024) + throw new Error('Expected 40-1024 bytes of private key as per FIPS 186'); + return mod(bytesToNumberLE(hash), CURVE.l - _1n) + _1n; + }, + randomBytes: (bytesLength = 32) => { + if (crypto.web) { + return crypto.web.getRandomValues(new Uint8Array(bytesLength)); + } + else if (crypto.node) { + const { randomBytes } = crypto.node; + return new Uint8Array(randomBytes(bytesLength).buffer); + } + else { + throw new Error("The environment doesn't have randomBytes function"); + } + }, + randomPrivateKey: () => { + return utils.randomBytes(32); + }, + sha512: async (...messages) => { + const message = concatBytes(...messages); + if (crypto.web) { + const buffer = await crypto.web.subtle.digest('SHA-512', message.buffer); + return new Uint8Array(buffer); + } + else if (crypto.node) { + return Uint8Array.from(crypto.node.createHash('sha512').update(message).digest()); + } + else { + throw new Error("The environment doesn't have sha512 function"); + } + }, + precompute(windowSize = 8, point = Point.BASE) { + const cached = point.equals(Point.BASE) ? point : new Point(point.x, point.y); + cached._setWindowSize(windowSize); + cached.multiply(_2n); + return cached; + }, + sha512Sync: undefined, +}; +Object.defineProperties(utils, { + sha512Sync: { + configurable: false, + get() { + return _sha512Sync; + }, + set(val) { + if (!_sha512Sync) + _sha512Sync = val; + }, + }, +}); + + +/***/ }, + +/***/ "./node_modules/base58-universal/lib/baseN.js" +/*!****************************************************!*\ + !*** ./node_modules/base58-universal/lib/baseN.js ***! + \****************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ decode: () => (/* binding */ decode), +/* harmony export */ encode: () => (/* binding */ encode) +/* harmony export */ }); +/** + * Base-N/Base-X encoding/decoding functions. + * + * Original implementation from base-x: + * https://github.com/cryptocoinjs/base-x + * + * Which is MIT licensed: + * + * The MIT License (MIT) + * + * Copyright base-x contributors (c) 2016 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ +// baseN alphabet indexes +const _reverseAlphabets = {}; + +/** + * BaseN-encodes a Uint8Array using the given alphabet. + * + * @param {Uint8Array} input - The bytes to encode in a Uint8Array. + * @param {string} alphabet - The alphabet to use for encoding. + * @param {number} maxline - The maximum number of encoded characters per line + * to use, defaults to none. + * + * @returns {string} The baseN-encoded output string. + */ +function encode(input, alphabet, maxline) { + if(!(input instanceof Uint8Array)) { + throw new TypeError('"input" must be a Uint8Array.'); + } + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + if(maxline !== undefined && typeof maxline !== 'number') { + throw new TypeError('"maxline" must be a number.'); + } + if(input.length === 0) { + return ''; + } + + let output = ''; + + let i = 0; + const base = alphabet.length; + const first = alphabet.charAt(0); + const digits = [0]; + for(i = 0; i < input.length; ++i) { + let carry = input[i]; + for(let j = 0; j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + + while(carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + + // deal with leading zeros + for(i = 0; input[i] === 0 && i < input.length - 1; ++i) { + output += first; + } + // convert digits to a string + for(i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + + if(maxline) { + const regex = new RegExp('.{1,' + maxline + '}', 'g'); + output = output.match(regex).join('\r\n'); + } + + return output; +} + +/** + * Decodes a baseN-encoded (using the given alphabet) string to a + * Uint8Array. + * + * @param {string} input - The baseN-encoded input string. + * @param {string} alphabet - The alphabet to use for decoding. + * + * @returns {Uint8Array} The decoded bytes in a Uint8Array. + */ +function decode(input, alphabet) { + if(typeof input !== 'string') { + throw new TypeError('"input" must be a string.'); + } + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + if(input.length === 0) { + return new Uint8Array(); + } + + let table = _reverseAlphabets[alphabet]; + if(!table) { + // compute reverse alphabet + table = _reverseAlphabets[alphabet] = []; + for(let i = 0; i < alphabet.length; ++i) { + table[alphabet.charCodeAt(i)] = i; + } + } + + // remove whitespace characters + input = input.replace(/\s/g, ''); + + const base = alphabet.length; + const first = alphabet.charAt(0); + const bytes = [0]; + for(let i = 0; i < input.length; i++) { + const value = table[input.charCodeAt(i)]; + if(value === undefined) { + return; + } + + let carry = value; + for(let j = 0; j < bytes.length; ++j) { + carry += bytes[j] * base; + bytes[j] = carry & 0xff; + carry >>= 8; + } + + while(carry > 0) { + bytes.push(carry & 0xff); + carry >>= 8; + } + } + + // deal with leading zeros + for(let k = 0; input[k] === first && k < input.length - 1; ++k) { + bytes.push(0); + } + + return new Uint8Array(bytes.reverse()); +} + + +/***/ }, + +/***/ "./node_modules/base58-universal/lib/index.js" +/*!****************************************************!*\ + !*** ./node_modules/base58-universal/lib/index.js ***! + \****************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ decode: () => (/* binding */ decode), +/* harmony export */ encode: () => (/* binding */ encode) +/* harmony export */ }); +/* harmony import */ var _baseN_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./baseN.js */ "./node_modules/base58-universal/lib/baseN.js"); +/*! + * Copyright (c) 2019-2022 Digital Bazaar, Inc. All rights reserved. + */ + + +// base58 characters (Bitcoin alphabet) +const alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + +function encode(input, maxline) { + return (0,_baseN_js__WEBPACK_IMPORTED_MODULE_0__.encode)(input, alphabet, maxline); +} + +function decode(input) { + return (0,_baseN_js__WEBPACK_IMPORTED_MODULE_0__.decode)(input, alphabet); +} + + +/***/ }, + +/***/ "./node_modules/base64url-universal/lib/base64url.js" +/*!***********************************************************!*\ + !*** ./node_modules/base64url-universal/lib/base64url.js ***! + \***********************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ decode: () => (/* binding */ decode), +/* harmony export */ encode: () => (/* binding */ encode) +/* harmony export */ }); +/*! + * Copyright (c) 2018-2022 Digital Bazaar, Inc. All rights reserved. + */ +/** + * Encode/Decode input according to the "Base64url Encoding" format as specified + * in JSON Web Signature (JWS) RFC7517. A URL safe character set is used and + * trailing '=', line breaks, whitespace, and other characters are omitted. + * + * @module base64url-universal + */ + +const _alphabet = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; +const _alphabetIdx = [ + 62, -1, -1, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, + -1, -1, -1, 64, -1, -1, -1, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + -1, -1, -1, -1, 63, -1, + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 +]; + +/** + * Encodes input according to the "Base64url Encoding" format as specified + * in JSON Web Signature (JWS) RFC7517. A URL safe character set is used and + * trailing '=', line breaks, whitespace, and other characters are omitted. + * + * @alias module:base64url-universal + * @param {(Uint8Array | string)} input - The data to encode. + * + * @returns {string} The encoded value. + */ +function encode(input) { + if(!((input instanceof Uint8Array) || (typeof input === 'string'))) { + throw new TypeError('"input" be a string or Uint8Array.'); + } + if(typeof input === 'string') { + // convert input to Uint8Array + input = new TextEncoder().encode(input); + } + let output = ''; + let chr1; + let chr2; + let chr3; + let i = 0; + while(i < input.byteLength) { + chr1 = input[i++]; + chr2 = input[i++]; + chr3 = input[i++]; + + // encode 4 character group + output += _alphabet.charAt(chr1 >> 2); + output += _alphabet.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); + if(!isNaN(chr2)) { + output += _alphabet.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); + if(!isNaN(chr3)) { + output += _alphabet.charAt(chr3 & 63); + } + } + } + return output; +} + +/** + * Decodes input according to the "Base64url Encoding" format as specified + * in JSON Web Signature (JWS) RFC7517. A URL safe character set is used and + * trailing '=', line breaks, whitespace, and other characters are omitted. + * + * @alias module:base64url-universal + * @param {string} input - The data to decode. + * + * @returns {Uint8Array} The decoded value. + */ +function decode(input) { + let length = input.length; + const mod4 = length % 4; + if(mod4 === 1) { + throw new Error('Illegal base64 string.'); + } + let diff = 0; + if(mod4 > 0) { + diff = 4 - mod4; + length += diff; + } + + const output = new Uint8Array(length / 4 * 3 - diff); + + let enc1; + let enc2; + let enc3; + let enc4; + let i = 0; + let j = 0; + + while(i < length) { + enc1 = _alphabetIdx[input.charCodeAt(i++) - 45]; + enc2 = _alphabetIdx[input.charCodeAt(i++) - 45]; + + output[j++] = (enc1 << 2) | (enc2 >> 4); + if(i < input.length) { + // can decode at least 2 bytes + enc3 = _alphabetIdx[input.charCodeAt(i++) - 45]; + output[j++] = ((enc2 & 15) << 4) | (enc3 >> 2); + if(i < input.length) { + // can decode 3 bytes + enc4 = _alphabetIdx[input.charCodeAt(i++) - 45]; + output[j++] = ((enc3 & 3) << 6) | enc4; + } + } + } + + return output; +} + + +/***/ }, + +/***/ "./node_modules/base64url-universal/lib/browser.js" +/*!*********************************************************!*\ + !*** ./node_modules/base64url-universal/lib/browser.js ***! + \*********************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ decode: () => (/* reexport safe */ _base64url_js__WEBPACK_IMPORTED_MODULE_0__.decode), +/* harmony export */ encode: () => (/* reexport safe */ _base64url_js__WEBPACK_IMPORTED_MODULE_0__.encode) +/* harmony export */ }); +/* harmony import */ var _base64url_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base64url.js */ "./node_modules/base64url-universal/lib/base64url.js"); +/*! + * Copyright (c) 2018-2022 Digital Bazaar, Inc. All rights reserved. + */ + + + +/***/ }, + +/***/ "./node_modules/canonicalize/lib/canonicalize.js" +/*!*******************************************************!*\ + !*** ./node_modules/canonicalize/lib/canonicalize.js ***! + \*******************************************************/ +(module) { + +"use strict"; +/* jshint esversion: 6 */ +/* jslint node: true */ + + +module.exports = function serialize (object) { + if (object === null || typeof object !== 'object' || object.toJSON != null) { + return JSON.stringify(object); + } + + if (Array.isArray(object)) { + return '[' + object.reduce((t, cv, ci) => { + const comma = ci === 0 ? '' : ','; + const value = cv === undefined || typeof cv === 'symbol' ? null : cv; + return t + comma + serialize(value); + }, '') + ']'; + } + + return '{' + Object.keys(object).sort().reduce((t, cv, ci) => { + if (object[cv] === undefined || + typeof object[cv] === 'symbol') { + return t; + } + const comma = t.length === 0 ? '' : ','; + return t + comma + serialize(cv) + ':' + serialize(object[cv]); + }, '') + '}'; +}; + + +/***/ }, + +/***/ "./node_modules/credentials-context/dist/context.esm.js" +/*!**************************************************************!*\ + !*** ./node_modules/credentials-context/dist/context.esm.js ***! + \**************************************************************/ +(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CONTEXT: () => (/* binding */ context_3), +/* harmony export */ CONTEXT_URL: () => (/* binding */ context_4), +/* harmony export */ CONTEXT_URL_V1: () => (/* binding */ context_5), +/* harmony export */ CREDENTIALS_CONTEXT_V1_URL: () => (/* binding */ context_6), +/* harmony export */ constants: () => (/* binding */ context_2), +/* harmony export */ contexts: () => (/* binding */ context_1), +/* harmony export */ "default": () => (/* binding */ context$1) +/* harmony export */ }); +function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var context = createCommonjsModule(function (module, exports) { +/*! For license information please see context.js.LICENSE.txt */ +(()=>{var e={717:e=>{e.exports={CONTEXT_FILENAME:"credentials-v1.jsonld",CONTEXT_URL:"https://www.w3.org/2018/credentials/v1",CREDENTIALS_CONTEXT_V1_URL:"https://www.w3.org/2018/credentials/v1"};},869:e=>{e.exports={"@context":{"@version":1.1,"@protected":!0,id:"@id",type:"@type",VerifiableCredential:{"@id":"https://www.w3.org/2018/credentials#VerifiableCredential","@context":{"@version":1.1,"@protected":!0,id:"@id",type:"@type",cred:"https://www.w3.org/2018/credentials#",sec:"https://w3id.org/security#",xsd:"http://www.w3.org/2001/XMLSchema#",credentialSchema:{"@id":"cred:credentialSchema","@type":"@id","@context":{"@version":1.1,"@protected":!0,id:"@id",type:"@type",cred:"https://www.w3.org/2018/credentials#",JsonSchemaValidator2018:"cred:JsonSchemaValidator2018"}},credentialStatus:{"@id":"cred:credentialStatus","@type":"@id"},credentialSubject:{"@id":"cred:credentialSubject","@type":"@id"},evidence:{"@id":"cred:evidence","@type":"@id"},expirationDate:{"@id":"cred:expirationDate","@type":"xsd:dateTime"},holder:{"@id":"cred:holder","@type":"@id"},issued:{"@id":"cred:issued","@type":"xsd:dateTime"},issuer:{"@id":"cred:issuer","@type":"@id"},issuanceDate:{"@id":"cred:issuanceDate","@type":"xsd:dateTime"},proof:{"@id":"sec:proof","@type":"@id","@container":"@graph"},refreshService:{"@id":"cred:refreshService","@type":"@id","@context":{"@version":1.1,"@protected":!0,id:"@id",type:"@type",cred:"https://www.w3.org/2018/credentials#",ManualRefreshService2018:"cred:ManualRefreshService2018"}},termsOfUse:{"@id":"cred:termsOfUse","@type":"@id"},validFrom:{"@id":"cred:validFrom","@type":"xsd:dateTime"},validUntil:{"@id":"cred:validUntil","@type":"xsd:dateTime"}}},VerifiablePresentation:{"@id":"https://www.w3.org/2018/credentials#VerifiablePresentation","@context":{"@version":1.1,"@protected":!0,id:"@id",type:"@type",cred:"https://www.w3.org/2018/credentials#",sec:"https://w3id.org/security#",holder:{"@id":"cred:holder","@type":"@id"},proof:{"@id":"sec:proof","@type":"@id","@container":"@graph"},verifiableCredential:{"@id":"cred:verifiableCredential","@type":"@id","@container":"@graph"}}},EcdsaSecp256k1Signature2019:{"@id":"https://w3id.org/security#EcdsaSecp256k1Signature2019","@context":{"@version":1.1,"@protected":!0,id:"@id",type:"@type",sec:"https://w3id.org/security#",xsd:"http://www.w3.org/2001/XMLSchema#",challenge:"sec:challenge",created:{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},domain:"sec:domain",expires:{"@id":"sec:expiration","@type":"xsd:dateTime"},jws:"sec:jws",nonce:"sec:nonce",proofPurpose:{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":!0,id:"@id",type:"@type",sec:"https://w3id.org/security#",assertionMethod:{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},authentication:{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},proofValue:"sec:proofValue",verificationMethod:{"@id":"sec:verificationMethod","@type":"@id"}}},EcdsaSecp256r1Signature2019:{"@id":"https://w3id.org/security#EcdsaSecp256r1Signature2019","@context":{"@version":1.1,"@protected":!0,id:"@id",type:"@type",sec:"https://w3id.org/security#",xsd:"http://www.w3.org/2001/XMLSchema#",challenge:"sec:challenge",created:{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},domain:"sec:domain",expires:{"@id":"sec:expiration","@type":"xsd:dateTime"},jws:"sec:jws",nonce:"sec:nonce",proofPurpose:{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":!0,id:"@id",type:"@type",sec:"https://w3id.org/security#",assertionMethod:{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},authentication:{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},proofValue:"sec:proofValue",verificationMethod:{"@id":"sec:verificationMethod","@type":"@id"}}},Ed25519Signature2018:{"@id":"https://w3id.org/security#Ed25519Signature2018","@context":{"@version":1.1,"@protected":!0,id:"@id",type:"@type",sec:"https://w3id.org/security#",xsd:"http://www.w3.org/2001/XMLSchema#",challenge:"sec:challenge",created:{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},domain:"sec:domain",expires:{"@id":"sec:expiration","@type":"xsd:dateTime"},jws:"sec:jws",nonce:"sec:nonce",proofPurpose:{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":!0,id:"@id",type:"@type",sec:"https://w3id.org/security#",assertionMethod:{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},authentication:{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},proofValue:"sec:proofValue",verificationMethod:{"@id":"sec:verificationMethod","@type":"@id"}}},RsaSignature2018:{"@id":"https://w3id.org/security#RsaSignature2018","@context":{"@version":1.1,"@protected":!0,challenge:"sec:challenge",created:{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},domain:"sec:domain",expires:{"@id":"sec:expiration","@type":"xsd:dateTime"},jws:"sec:jws",nonce:"sec:nonce",proofPurpose:{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":!0,id:"@id",type:"@type",sec:"https://w3id.org/security#",assertionMethod:{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},authentication:{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},proofValue:"sec:proofValue",verificationMethod:{"@id":"sec:verificationMethod","@type":"@id"}}},proof:{"@id":"https://w3id.org/security#proof","@type":"@id","@container":"@graph"}}};},858:(e,t,i)=>{const{CONTEXT_URL:d}=i(717),r=i(869);e.exports={documentLoader(e){if(e!==d)throw new Error(`Loading document "${e}" is not allowed.`);return {contextUrl:null,document:r,documentUrl:e}}};},243:(e,t,i)=>{const d=i(869),r=i(717),{documentLoader:o}=i(858),{CONTEXT_URL:c}=r,s=new Map;s.set(r.CONTEXT_URL,d),e.exports={constants:r,contexts:s,documentLoader:o,CONTEXT_URL:c,CREDENTIALS_CONTEXT_V1_URL:c,CONTEXT_URL_V1:c,CONTEXT:d};}},t={},i=function i(d){var r=t[d];if(void 0!==r)return r.exports;var o=t[d]={exports:{}};return e[d](o,o.exports,i),o.exports}(243),d=exports;for(var r in i)d[r]=i[r];i.__esModule&&Object.defineProperty(d,"__esModule",{value:!0});})(); +}); + +var context$1 = unwrapExports(context); +var context_1 = context.contexts; +var context_2 = context.constants; +var context_3 = context.CONTEXT; +var context_4 = context.CONTEXT_URL; +var context_5 = context.CONTEXT_URL_V1; +var context_6 = context.CREDENTIALS_CONTEXT_V1_URL; + + + + +/***/ }, + +/***/ "./node_modules/crypto-ld/lib/CryptoLD.js" +/*!************************************************!*\ + !*** ./node_modules/crypto-ld/lib/CryptoLD.js ***! + \************************************************/ +(module) { + +"use strict"; +/*! + * Copyright (c) 2020 Digital Bazaar, Inc. All rights reserved. + */ + + +/** + * General purpose key generation driver for Linked Data cryptographic key + * pairs. + * + * @param {Map} [suites] - Optional map of supported suites, by suite id. + */ +class CryptoLD { + constructor({suites} = {}) { + this.suites = suites || new Map(); + } + + /** + * Installs support for a key type (suite). + * + * @param {LDKeyPair} keyPairLib - Conforming key pair library for a suite. + */ + use(keyPairLib) { + this.suites.set(keyPairLib.suite, keyPairLib); + } + + /** + * Generates a public/private LDKeyPair. + * + * @param {object} options - Suite-specific key options. + * @param {string} options.type - Key suite id (for example, + * 'Ed25519VerificationKey2020'). + * @param {string} [options.controller] - Controller DID or URL for the + * generated key pair. If present, used to auto-initialize the key.id. + * + * @returns {Promise} + */ + async generate(options = {}) { + const Suite = this._suiteForType(options); + return Suite.generate(options); + } + + /** + * Imports a public/private key pair from serialized data. + * + * @param {object} serialized - Serialized key object. + * + * @throws {Error} - On missing or invalid serialized key data. + * + * @returns {Promise} + */ + async from(serialized = {}) { + const Suite = this._suiteForType(serialized); + + if(serialized['@context']) { + // presume this may be an untrusted (fetched, etc) key document + return Suite.fromKeyDocument({document: serialized}); + } + + return Suite.from(serialized); + } + + /** + * Imports a key pair instance from a provided externally fetched key + * document (fetched via a secure JSON-LD `documentLoader` or via + * `cryptoLd.fromKeyId()`), optionally checking it for revocation and required + * context. + * + * @param {object} options - Options hashmap. + * @param {string} options.document - Externally fetched key document. + * @param {boolean} [options.checkContext=true] - Whether to check that the + * fetched key document contains the context required by the key's crypto + * suite. + * @param {boolean} [options.checkRevoked=true] - Whether to check the key + * object for the presence of the `revoked` timestamp. + * + * @returns {Promise} Resolves with the resulting key pair + * instance. + */ + async fromKeyDocument({ + document, checkContext = true, checkRevoked = true + } = {}) { + if(!document) { + throw new TypeError('The "document" parameter is required.'); + } + const Suite = this._suiteForType(document); + + return Suite.fromKeyDocument({document, checkContext, checkRevoked}); + } + + /** + * Imports a key pair instance via the provided `documentLoader` function, + * optionally checking it for revocation and required context. + * + * @param {object} options - Options hashmap. + * @param {string} options.id - Key ID or URI. + * @param {Function} options.documentLoader - JSON-LD Document Loader. + * @param {boolean} [options.checkContext=true] - Whether to check that the + * fetched key document contains the context required by the key's crypto + * suite. + * @param {boolean} [options.checkRevoked=true] - Whether to check the key + * object for the presence of the `revoked` timestamp. + * + * @returns {Promise} Resolves with the appropriate key pair + * instance. + */ + async fromKeyId({ + id, documentLoader, checkContext = true, checkRevoked = true + } = {}) { + if(!id) { + throw new TypeError('The "id" parameter is required.'); + } + if(!documentLoader) { + throw new TypeError('The "documentLoader" parameter is required.'); + } + let keyDocument; + try { + ({document: keyDocument} = await documentLoader(id)); + // the supplied documentLoader may not be properly implemented + if(!keyDocument) { + throw new Error( + 'The "documentLoader" function must return a "document" object.'); + } + } catch(e) { + const error = new Error('Error fetching document: ' + e.message); + error.cause = e; + throw error; + } + const fetchedType = keyDocument.type; + if(!fetchedType) { + throw new Error('Key suite type not found in fetched document.'); + } + const keySuite = this.suites.get(fetchedType); + if(!keySuite) { + throw new Error(`Support for suite "${fetchedType}" is not installed.`); + } + + return keySuite.fromKeyDocument({document: keyDocument, checkContext, + checkRevoked}); + } + + /** + * Tests if a given key type is currently installed. + * + * @param {string} [type] - Key suite id ('Ed25519VerificationKey2020'). + * @private + */ + _installed({type}) { + return this.suites.has(type); + } + + /** + * Returns the installed crypto suite class for a given document's type. + * + * @param {object} document - A serialized key document (or options document). + * @param {string} document.type - Key suite id (for example, + * 'Ed25519VerificationKey2020'). + * + * @returns {object} LDKeyPair (crypto suite) class. + */ + _suiteForType(document) { + const type = document && document.type; + + if(!type) { + throw new TypeError('Missing key type.'); + } + if(!this._installed({type})) { + throw new Error(`Support for key type "${type}" is not installed.`); + } + + return this.suites.get(type); + } +} + +module.exports = { + CryptoLD +}; + + +/***/ }, + +/***/ "./node_modules/crypto-ld/lib/LDKeyPair.js" +/*!*************************************************!*\ + !*** ./node_modules/crypto-ld/lib/LDKeyPair.js ***! + \*************************************************/ +(module) { + +"use strict"; +/*! + * Copyright (c) 2018-2021 Digital Bazaar, Inc. All rights reserved. + */ + + +/** + * When adding support for a new suite type for `crypto-ld`, developers should + * do the following: + * + * 1. Create their own npm package / github repo, such as `example-key-pair`. + * 2. Subclass LDKeyPair. + * 3. Override relevant methods (such as `export()` and `fingerprint()`). + * 4. Add to the key type table in the `crypto-ld` README.md (that's this repo). + */ +class LDKeyPair { + /** + * Creates a public/private key pair instance. This is an abstract base class, + * actual key material and suite-specific methods are handled in the subclass. + * + * To generate or import a key pair, use the `cryptoLd` instance. + * @see CryptoLD.js + * + * @param {string} id - The key id, typically composed of controller + * URL and key fingerprint as hash fragment. + * @param {string} controller - DID/URL of the person/entity + * controlling this key. + * @param {string} [revoked] - Timestamp of when the key has been revoked, + * in RFC3339 format. If not present, the key itself is considered not + * revoked. (Note that this mechanism is slightly different than DID + * Document key revocation, where a DID controller can revoke a key from + * that DID by removing it from the DID Document.) + */ + constructor({id, controller, revoked} = {}) { + this.id = id; + this.controller = controller; + this.revoked = revoked; + // this.type is set in subclass constructor + } + + /** + * Generates a new public/private key pair instance. + * Note that this method is not typically called directly by client code, + * but instead is used through a `cryptoLd` instance. + * + * @param {object} options - Suite-specific options for the KeyPair. For + * common options, see the `LDKeyPair.constructor()` docstring. + * + * @returns {Promise} An LDKeyPair instance. + */ + static async generate(/* options */) { + throw new Error('Abstract method, must be implemented in subclass.'); + } + + /** + * Imports a key pair instance from a provided externally fetched key + * document (fetched via a secure JSON-LD `documentLoader` or via + * `cryptoLd.fromKeyId()`), optionally checking it for revocation and required + * context. + * + * @param {object} options - Options hashmap. + * @param {string} options.document - Externally fetched key document. + * @param {boolean} [options.checkContext=true] - Whether to check that the + * fetched key document contains the context required by the key's crypto + * suite. + * @param {boolean} [options.checkRevoked=true] - Whether to check the key + * object for the presence of the `revoked` timestamp. + * + * @returns {Promise} Resolves with the resulting key pair + * instance. + */ + static async fromKeyDocument({ + document, checkContext = true, checkRevoked = true + } = {}) { + if(!document) { + throw new TypeError('The "document" parameter is required.'); + } + + if(checkContext) { + const fetchedDocContexts = [].concat(document['@context']); + if(!fetchedDocContexts.includes(this.SUITE_CONTEXT)) { + throw new Error('Key document does not contain required context "' + + this.SUITE_CONTEXT + '".'); + } + } + if(checkRevoked && document.revoked) { + throw new Error(`Key has been revoked since: "${document.revoked}".`); + } + return this.from(document); + } + + /** + * Generates a KeyPair from some options. + * @param {object} options - Will generate a key pair + * in multiple different formats. + * @example + * > const options = { + * type: 'Ed25519VerificationKey2020' + * }; + * > const edKeyPair = await LDKeyPair.from(options); + * + * @returns {Promise} A LDKeyPair. + * @throws Unsupported Key Type. + */ + static async from(/* options */) { + throw new Error('Abstract method from() must be implemented in subclass.'); + } + + /** + * Exports the serialized representation of the KeyPair + * and other information that json-ld Signatures can use to form a proof. + * + * NOTE: Subclasses MUST override this method (and add the exporting of + * their public and private key material). + * + * @param {object} [options={}] - Options hashmap. + * @param {boolean} [options.publicKey] - Export public key material? + * @param {boolean} [options.privateKey] - Export private key material? + * + * @returns {object} A public key object + * information used in verification methods by signatures. + */ + export({publicKey = false, privateKey = false} = {}) { + if(!publicKey && !privateKey) { + throw new Error( + 'Export requires specifying either "publicKey" or "privateKey".'); + } + const key = { + id: this.id, + type: this.type, + controller: this.controller + }; + if(this.revoked) { + key.revoked = this.revoked; + } + + return key; + } + + /** + * Returns the public key fingerprint, multibase+multicodec encoded. The + * specific fingerprint method is determined by the key suite, and is often + * either a hash of the public key material (such as with RSA), or the + * full encoded public key (for key types with sufficiently short + * representations, such as ed25519). + * This is frequently used in initializing the key id, or generating some + * types of cryptonym DIDs. + * + * @returns {string} + */ + fingerprint() { + throw new Error('Abstract method, must be implemented in subclass.'); + } + + /** + * Verifies that a given key fingerprint matches the public key material + * belonging to this key pair. + * + * @param {string} fingerprint - Public key fingerprint. + * + * @returns {{verified: boolean}} + */ + verifyFingerprint(/* {fingerprint} */) { + throw new Error('Abstract method, must be implemented in subclass.'); + } + + /* eslint-disable max-len */ + /** + * Returns a signer object for use with + * [jsonld-signatures]{@link https://github.com/digitalbazaar/jsonld-signatures}. + * NOTE: Applies only to verifier type keys (like ed25519). + * + * @example + * > const signer = keyPair.signer(); + * > signer + * { sign: [AsyncFunction: sign] } + * > signer.sign({data}); + * + * @returns {{sign: Function}} A signer for json-ld usage. + */ + /* eslint-enable */ + signer() { + return { + async sign({/* data */}) { + throw new Error('Abstract method, must be implemented in subclass.'); + } + }; + } + + /* eslint-disable max-len */ + /** + * Returns a verifier object for use with + * [jsonld-signatures]{@link https://github.com/digitalbazaar/jsonld-signatures}. + * NOTE: Applies only to verifier type keys (like ed25519). + * + * @example + * > const verifier = keyPair.verifier(); + * > verifier + * { verify: [AsyncFunction: verify] } + * > verifier.verify(key); + * + * @returns {{verify: Function}} Used to verify jsonld-signatures. + */ + /* eslint-enable */ + verifier() { + return { + async verify({/* data, signature */}) { + throw new Error('Abstract method, must be implemented in subclass.'); + } + }; + } +} + +// Implementers must override this in subclasses +LDKeyPair.SUITE_CONTEXT = 'INVALID LDKeyPair CONTEXT'; + +module.exports = { + LDKeyPair +}; + + +/***/ }, + +/***/ "./node_modules/crypto-ld/lib/index.js" +/*!*********************************************!*\ + !*** ./node_modules/crypto-ld/lib/index.js ***! + \*********************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2018-2020 Digital Bazaar, Inc. All rights reserved. + */ + + +const {CryptoLD} = __webpack_require__(/*! ./CryptoLD */ "./node_modules/crypto-ld/lib/CryptoLD.js"); +const {LDKeyPair} = __webpack_require__(/*! ./LDKeyPair */ "./node_modules/crypto-ld/lib/LDKeyPair.js"); + +module.exports = { + CryptoLD, + LDKeyPair +}; + + +/***/ }, + +/***/ "./node_modules/did-context/dist/context.esm.js" +/*!******************************************************!*\ + !*** ./node_modules/did-context/dist/context.esm.js ***! + \******************************************************/ +(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CONTEXT: () => (/* binding */ context_3), +/* harmony export */ CONTEXT_URL: () => (/* binding */ context_4), +/* harmony export */ CONTEXT_URL_V1: () => (/* binding */ context_5), +/* harmony export */ DID_CONTEXT_URL: () => (/* binding */ context_6), +/* harmony export */ constants: () => (/* binding */ context_2), +/* harmony export */ contexts: () => (/* binding */ context_1), +/* harmony export */ "default": () => (/* binding */ context$1) +/* harmony export */ }); +function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var context = createCommonjsModule(function (module, exports) { +/*! For license information please see context.js.LICENSE.txt */ +(()=>{var t={717:t=>{const e="https://www.w3.org/ns/did/v1";t.exports={CONTEXT_FILENAME:"did-v1.jsonld",DID_CONTEXT_URL:e,CONTEXT_URL:e,CONTEXT_URL_V1:e};},869:t=>{t.exports={"@context":{"@protected":!0,id:"@id",type:"@type",alsoKnownAs:{"@id":"https://www.w3.org/ns/activitystreams#alsoKnownAs","@type":"@id"},assertionMethod:{"@id":"https://w3id.org/security#assertionMethod","@type":"@id","@container":"@set"},authentication:{"@id":"https://w3id.org/security#authenticationMethod","@type":"@id","@container":"@set"},capabilityDelegation:{"@id":"https://w3id.org/security#capabilityDelegationMethod","@type":"@id","@container":"@set"},capabilityInvocation:{"@id":"https://w3id.org/security#capabilityInvocationMethod","@type":"@id","@container":"@set"},controller:{"@id":"https://w3id.org/security#controller","@type":"@id"},keyAgreement:{"@id":"https://w3id.org/security#keyAgreementMethod","@type":"@id","@container":"@set"},service:{"@id":"https://www.w3.org/ns/did#service","@type":"@id","@context":{"@protected":!0,id:"@id",type:"@type",serviceEndpoint:{"@id":"https://www.w3.org/ns/did#serviceEndpoint","@type":"@id"}}},verificationMethod:{"@id":"https://w3id.org/security#verificationMethod","@type":"@id"}}};},243:(t,e,i)=>{const o=i(869),r=i(717),{CONTEXT_URL:s,DID_CONTEXT_URL:d}=r,n=new Map;n.set(s,o),t.exports={constants:r,contexts:n,DID_CONTEXT_URL:d,CONTEXT_URL:s,CONTEXT_URL_V1:s,CONTEXT:o};}},e={},i=function i(o){var r=e[o];if(void 0!==r)return r.exports;var s=e[o]={exports:{}};return t[o](s,s.exports,i),s.exports}(243),o=exports;for(var r in i)o[r]=i[r];i.__esModule&&Object.defineProperty(o,"__esModule",{value:!0});})(); +}); + +var context$1 = unwrapExports(context); +var context_1 = context.contexts; +var context_2 = context.constants; +var context_3 = context.CONTEXT; +var context_4 = context.CONTEXT_URL; +var context_5 = context.CONTEXT_URL_V1; +var context_6 = context.DID_CONTEXT_URL; + + + + +/***/ }, + +/***/ "./node_modules/ed25519-signature-2020-context/dist/context.esm.js" +/*!*************************************************************************!*\ + !*** ./node_modules/ed25519-signature-2020-context/dist/context.esm.js ***! + \*************************************************************************/ +(__unused_webpack_module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ CONTEXT: () => (/* binding */ context_3), +/* harmony export */ CONTEXT_URL: () => (/* binding */ context_4), +/* harmony export */ appContextMap: () => (/* binding */ context_5), +/* harmony export */ constants: () => (/* binding */ context_2), +/* harmony export */ contexts: () => (/* binding */ context_1), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ documentLoader: () => (/* binding */ context_6) +/* harmony export */ }); +function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var context = createCommonjsModule(function (module, exports) { +!function(t,e){for(var i in e)t[i]=e[i];}(exports,function(t){var e={};function i(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,i),o.l=!0,o.exports}return i.m=t,i.c=e,i.d=function(t,e,r){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r});},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0});},i.t=function(t,e){if(1&e&&(t=i(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(i.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)i.d(r,o,function(e){return t[e]}.bind(null,o));return r},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=2)}([function(t,e,i){/*! + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */t.exports={"@context":{id:"@id",type:"@type","@protected":!0,proof:{"@id":"https://w3id.org/security#proof","@type":"@id","@container":"@graph"},Ed25519VerificationKey2020:{"@id":"https://w3id.org/security#Ed25519VerificationKey2020","@context":{"@protected":!0,id:"@id",type:"@type",controller:{"@id":"https://w3id.org/security#controller","@type":"@id"},revoked:{"@id":"https://w3id.org/security#revoked","@type":"http://www.w3.org/2001/XMLSchema#dateTime"},publicKeyMultibase:{"@id":"https://w3id.org/security#publicKeyMultibase","@type":"https://w3id.org/security#multibase"}}},Ed25519Signature2020:{"@id":"https://w3id.org/security#Ed25519Signature2020","@context":{"@protected":!0,id:"@id",type:"@type",challenge:"https://w3id.org/security#challenge",created:{"@id":"http://purl.org/dc/terms/created","@type":"http://www.w3.org/2001/XMLSchema#dateTime"},domain:"https://w3id.org/security#domain",expires:{"@id":"https://w3id.org/security#expiration","@type":"http://www.w3.org/2001/XMLSchema#dateTime"},nonce:"https://w3id.org/security#nonce",proofPurpose:{"@id":"https://w3id.org/security#proofPurpose","@type":"@vocab","@context":{"@protected":!0,id:"@id",type:"@type",assertionMethod:{"@id":"https://w3id.org/security#assertionMethod","@type":"@id","@container":"@set"},authentication:{"@id":"https://w3id.org/security#authenticationMethod","@type":"@id","@container":"@set"},capabilityInvocation:{"@id":"https://w3id.org/security#capabilityInvocationMethod","@type":"@id","@container":"@set"},capabilityDelegation:{"@id":"https://w3id.org/security#capabilityDelegationMethod","@type":"@id","@container":"@set"},keyAgreement:{"@id":"https://w3id.org/security#keyAgreementMethod","@type":"@id","@container":"@set"}}},proofValue:{"@id":"https://w3id.org/security#proofValue","@type":"https://w3id.org/security#multibase"},verificationMethod:{"@id":"https://w3id.org/security#verificationMethod","@type":"@id"}}}}};},function(t,e,i){/*! + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */t.exports={CONTEXT_FILENAME:"ed25519-signature-2020-v1.jsonld",CONTEXT_URL:"https://w3id.org/security/suites/ed25519-2020/v1",CBORLD_CODEC_VALUE:20};},function(t,e,i){/*! + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */const r=i(0),o=i(1),{documentLoader:n}=i(3),{CONTEXT_URL:d,CBORLD_CODEC_VALUE:c}=o,s=new Map;s.set(o.CONTEXT_URL,r);const p=new Map;p.set(d,c),t.exports={constants:o,contexts:s,appContextMap:p,documentLoader:n,CONTEXT_URL:d,CONTEXT:r};},function(t,e,i){/*! + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */const{CONTEXT_URL:r}=i(1),o=i(0);t.exports={documentLoader(t){if(t!==r)throw new Error(`Loading document "${t}" is not allowed.`);return {contextUrl:null,document:o,documentUrl:t}}};}])); +}); + +var context$1 = unwrapExports(context); +var context_1 = context.contexts; +var context_2 = context.constants; +var context_3 = context.CONTEXT; +var context_4 = context.CONTEXT_URL; +var context_5 = context.appContextMap; +var context_6 = context.documentLoader; + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (context$1); + + + +/***/ }, + +/***/ "./node_modules/ed2curve/ed2curve.js" +/*!*******************************************!*\ + !*** ./node_modules/ed2curve/ed2curve.js ***! + \*******************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +/* + * ed2curve: convert Ed25519 signing key pair into Curve25519 + * key pair suitable for Diffie-Hellman key exchange. + * + * Written by Dmitry Chestnykh in 2014. Public domain. + */ +/* jshint newcap: false */ +(function(root, f) { + 'use strict'; + if ( true && module.exports) module.exports = f(__webpack_require__(/*! tweetnacl */ "./node_modules/tweetnacl/nacl-fast.js")); + else root.ed2curve = f(root.nacl); +}(this, function(nacl) { + 'use strict'; + if (!nacl) throw new Error('tweetnacl not loaded'); + + // -- Operations copied from TweetNaCl.js. -- + + var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; + }; + + var gf0 = gf(), + gf1 = gf([1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + + function car25519(o) { + var c; + var i; + for (i = 0; i < 16; i++) { + o[i] += 65536; + c = Math.floor(o[i] / 65536); + o[(i+1)*(i<15?1:0)] += c - 1 + 37 * (c-1) * (i===15?1:0); + o[i] -= (c * 65536); + } + } + + function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } + } + + function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; + } + + // addition + function A(o, a, b) { + var i; + for (i = 0; i < 16; i++) o[i] = (a[i] + b[i])|0; + } + + // subtraction + function Z(o, a, b) { + var i; + for (i = 0; i < 16; i++) o[i] = (a[i] - b[i])|0; + } + + // multiplication + function M(o, a, b) { + var i, j, t = new Float64Array(31); + for (i = 0; i < 31; i++) t[i] = 0; + for (i = 0; i < 16; i++) { + for (j = 0; j < 16; j++) { + t[i+j] += a[i] * b[j]; + } + } + for (i = 0; i < 15; i++) { + t[i] += 38 * t[i+16]; + } + for (i = 0; i < 16; i++) o[i] = t[i]; + car25519(o); + car25519(o); + } + + // squaring + function S(o, a) { + M(o, a, a); + } + + // inversion + function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; + } + + function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); + } + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i] >> 8; + } + } + + function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; + } + + function vn(x, xi, y, yi, n) { + var i, d = 0; + for (i = 0; i < n; i++) d |= x[xi + i] ^ y[yi + i]; + return (1 & ((d - 1) >>> 8)) - 1; + } + + function crypto_verify_32(x, xi, y, yi) { + return vn(x, xi, y, yi, 32); + } + + function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); + } + + function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if (a !== 1) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; + } + + function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i] | 0; + } + + function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); + + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; + + if (par25519(r[0]) === (p[31] >> 7)) Z(r[0], gf0, r[0]); + + M(r[3], r[0], r[1]); + return 0; + } + + // ---- + + // Converts Ed25519 public key to Curve25519 public key. + // montgomeryX = (edwardsY + 1)*inverse(1 - edwardsY) mod p + function convertPublicKey(pk) { + var z = new Uint8Array(32), + q = [gf(), gf(), gf(), gf()], + a = gf(), b = gf(); + + if (unpackneg(q, pk)) return null; // reject invalid key + + var y = q[1]; + + A(a, gf1, y); + Z(b, gf1, y); + inv25519(b, b); + M(a, a, b); + + pack25519(z, a); + return z; + } + + // Converts Ed25519 secret key to Curve25519 secret key. + function convertSecretKey(sk) { + var d = new Uint8Array(64), o = new Uint8Array(32), i; + nacl.lowlevel.crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + for (i = 0; i < 32; i++) o[i] = d[i]; + for (i = 0; i < 64; i++) d[i] = 0; + return o; + } + + function convertKeyPair(edKeyPair) { + var publicKey = convertPublicKey(edKeyPair.publicKey); + if (!publicKey) return null; + return { + publicKey: publicKey, + secretKey: convertSecretKey(edKeyPair.secretKey) + }; + } + + return { + convertPublicKey: convertPublicKey, + convertSecretKey: convertSecretKey, + convertKeyPair: convertKeyPair, + }; + +})); + + +/***/ }, + +/***/ "./node_modules/html-entities/dist/esm/index.js" +/*!******************************************************!*\ + !*** ./node_modules/html-entities/dist/esm/index.js ***! + \******************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ decode: () => (/* binding */ decode), +/* harmony export */ decodeEntity: () => (/* binding */ decodeEntity), +/* harmony export */ encode: () => (/* binding */ encode) +/* harmony export */ }); +/* harmony import */ var _named_references_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./named-references.js */ "./node_modules/html-entities/dist/esm/named-references.js"); +/* harmony import */ var _numeric_unicode_map_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./numeric-unicode-map.js */ "./node_modules/html-entities/dist/esm/numeric-unicode-map.js"); +/* harmony import */ var _surrogate_pairs_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./surrogate-pairs.js */ "./node_modules/html-entities/dist/esm/surrogate-pairs.js"); +var __assign = (undefined && undefined.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; + + + +var allNamedReferences = __assign(__assign({}, _named_references_js__WEBPACK_IMPORTED_MODULE_0__.namedReferences), { all: _named_references_js__WEBPACK_IMPORTED_MODULE_0__.namedReferences.html5 }); +var encodeRegExps = { + specialChars: /[<>'"&]/g, + nonAscii: /[<>'"&\u0080-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, + nonAsciiPrintable: /[<>'"&\x01-\x08\x11-\x15\x17-\x1F\x7f-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, + nonAsciiPrintableOnly: /[\x01-\x08\x11-\x15\x17-\x1F\x7f-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g, + extensive: /[\x01-\x0c\x0e-\x1f\x21-\x2c\x2e-\x2f\x3a-\x40\x5b-\x60\x7b-\x7d\x7f-\uD7FF\uE000-\uFFFF\uDC00-\uDFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g +}; +var defaultEncodeOptions = { + mode: 'specialChars', + level: 'all', + numeric: 'decimal' +}; +/** Encodes all the necessary (specified by `level`) characters in the text */ +function encode(text, _a) { + var _b = _a === void 0 ? defaultEncodeOptions : _a, _c = _b.mode, mode = _c === void 0 ? 'specialChars' : _c, _d = _b.numeric, numeric = _d === void 0 ? 'decimal' : _d, _e = _b.level, level = _e === void 0 ? 'all' : _e; + if (!text) { + return ''; + } + var encodeRegExp = encodeRegExps[mode]; + var references = allNamedReferences[level].characters; + var isHex = numeric === 'hexadecimal'; + return String.prototype.replace.call(text, encodeRegExp, function (input) { + var result = references[input]; + if (!result) { + var code = input.length > 1 ? (0,_surrogate_pairs_js__WEBPACK_IMPORTED_MODULE_2__.getCodePoint)(input, 0) : input.charCodeAt(0); + result = (isHex ? '&#x' + code.toString(16) : '&#' + code) + ';'; + } + return result; + }); +} +var defaultDecodeOptions = { + scope: 'body', + level: 'all' +}; +var strict = /&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);/g; +var attribute = /&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+)[;=]?/g; +var baseDecodeRegExps = { + xml: { + strict: strict, + attribute: attribute, + body: _named_references_js__WEBPACK_IMPORTED_MODULE_0__.bodyRegExps.xml + }, + html4: { + strict: strict, + attribute: attribute, + body: _named_references_js__WEBPACK_IMPORTED_MODULE_0__.bodyRegExps.html4 + }, + html5: { + strict: strict, + attribute: attribute, + body: _named_references_js__WEBPACK_IMPORTED_MODULE_0__.bodyRegExps.html5 + } +}; +var decodeRegExps = __assign(__assign({}, baseDecodeRegExps), { all: baseDecodeRegExps.html5 }); +var fromCharCode = String.fromCharCode; +var outOfBoundsChar = fromCharCode(65533); +var defaultDecodeEntityOptions = { + level: 'all' +}; +function getDecodedEntity(entity, references, isAttribute, isStrict) { + var decodeResult = entity; + var decodeEntityLastChar = entity[entity.length - 1]; + if (isAttribute && decodeEntityLastChar === '=') { + decodeResult = entity; + } + else if (isStrict && decodeEntityLastChar !== ';') { + decodeResult = entity; + } + else { + var decodeResultByReference = references[entity]; + if (decodeResultByReference) { + decodeResult = decodeResultByReference; + } + else if (entity[0] === '&' && entity[1] === '#') { + var decodeSecondChar = entity[2]; + var decodeCode = decodeSecondChar == 'x' || decodeSecondChar == 'X' + ? parseInt(entity.substr(3), 16) + : parseInt(entity.substr(2)); + decodeResult = + decodeCode >= 0x10ffff + ? outOfBoundsChar + : decodeCode > 65535 + ? (0,_surrogate_pairs_js__WEBPACK_IMPORTED_MODULE_2__.fromCodePoint)(decodeCode) + : fromCharCode(_numeric_unicode_map_js__WEBPACK_IMPORTED_MODULE_1__.numericUnicodeMap[decodeCode] || decodeCode); + } + } + return decodeResult; +} +/** Decodes a single entity */ +function decodeEntity(entity, _a) { + var _b = _a === void 0 ? defaultDecodeEntityOptions : _a, _c = _b.level, level = _c === void 0 ? 'all' : _c; + if (!entity) { + return ''; + } + return getDecodedEntity(entity, allNamedReferences[level].entities, false, false); +} +/** Decodes all entities in the text */ +function decode(text, _a) { + var _b = _a === void 0 ? defaultDecodeOptions : _a, _c = _b.level, level = _c === void 0 ? 'all' : _c, _d = _b.scope, scope = _d === void 0 ? level === 'xml' ? 'strict' : 'body' : _d; + if (!text) { + return ''; + } + var decodeRegExp = decodeRegExps[level][scope]; + var references = allNamedReferences[level].entities; + var isAttribute = scope === 'attribute'; + var isStrict = scope === 'strict'; + return text.replace(decodeRegExp, function (entity) { return getDecodedEntity(entity, references, isAttribute, isStrict); }); +} +//# sourceMappingURL=index.js.map + +/***/ }, + +/***/ "./node_modules/html-entities/dist/esm/named-references.js" +/*!*****************************************************************!*\ + !*** ./node_modules/html-entities/dist/esm/named-references.js ***! + \*****************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ bodyRegExps: () => (/* binding */ bodyRegExps), +/* harmony export */ namedReferences: () => (/* binding */ namedReferences) +/* harmony export */ }); +var __assign = (undefined && undefined.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +// This file is autogenerated by tools/process-named-references.ts +var pairDivider = "~"; +var blockDivider = "~~"; +function generateNamedReferences(input, prev) { + var entities = {}; + var characters = {}; + var blocks = input.split(blockDivider); + var isOptionalBlock = false; + for (var i = 0; blocks.length > i; i++) { + var entries = blocks[i].split(pairDivider); + for (var j = 0; j < entries.length; j += 2) { + var entity = entries[j]; + var character = entries[j + 1]; + var fullEntity = '&' + entity + ';'; + entities[fullEntity] = character; + if (isOptionalBlock) { + entities['&' + entity] = character; + } + characters[character] = fullEntity; + } + isOptionalBlock = true; + } + return prev ? + { entities: __assign(__assign({}, entities), prev.entities), characters: __assign(__assign({}, characters), prev.characters) } : + { entities: entities, characters: characters }; +} +var bodyRegExps = { + xml: /&(?:#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g, + html4: /∉|&(?:nbsp|iexcl|cent|pound|curren|yen|brvbar|sect|uml|copy|ordf|laquo|not|shy|reg|macr|deg|plusmn|sup2|sup3|acute|micro|para|middot|cedil|sup1|ordm|raquo|frac14|frac12|frac34|iquest|Agrave|Aacute|Acirc|Atilde|Auml|Aring|AElig|Ccedil|Egrave|Eacute|Ecirc|Euml|Igrave|Iacute|Icirc|Iuml|ETH|Ntilde|Ograve|Oacute|Ocirc|Otilde|Ouml|times|Oslash|Ugrave|Uacute|Ucirc|Uuml|Yacute|THORN|szlig|agrave|aacute|acirc|atilde|auml|aring|aelig|ccedil|egrave|eacute|ecirc|euml|igrave|iacute|icirc|iuml|eth|ntilde|ograve|oacute|ocirc|otilde|ouml|divide|oslash|ugrave|uacute|ucirc|uuml|yacute|thorn|yuml|quot|amp|lt|gt|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g, + html5: /·|℗|⋇|⪧|⩺|⋗|⦕|⩼|⪆|⥸|⋗|⋛|⪌|≷|≳|⪦|⩹|⋖|⋋|⋉|⥶|⩻|⦖|◃|⊴|◂|∉|⋹̸|⋵̸|∉|⋷|⋶|∌|∌|⋾|⋽|∥|⊠|⨱|⨰|&(?:AElig|AMP|Aacute|Acirc|Agrave|Aring|Atilde|Auml|COPY|Ccedil|ETH|Eacute|Ecirc|Egrave|Euml|GT|Iacute|Icirc|Igrave|Iuml|LT|Ntilde|Oacute|Ocirc|Ograve|Oslash|Otilde|Ouml|QUOT|REG|THORN|Uacute|Ucirc|Ugrave|Uuml|Yacute|aacute|acirc|acute|aelig|agrave|amp|aring|atilde|auml|brvbar|ccedil|cedil|cent|copy|curren|deg|divide|eacute|ecirc|egrave|eth|euml|frac12|frac14|frac34|gt|iacute|icirc|iexcl|igrave|iquest|iuml|laquo|lt|macr|micro|middot|nbsp|not|ntilde|oacute|ocirc|ograve|ordf|ordm|oslash|otilde|ouml|para|plusmn|pound|quot|raquo|reg|sect|shy|sup1|sup2|sup3|szlig|thorn|times|uacute|ucirc|ugrave|uml|uuml|yacute|yen|yuml|#\d+|#[xX][\da-fA-F]+|[0-9a-zA-Z]+);?/g +}; +var namedReferences = {}; +namedReferences['xml'] = generateNamedReferences("lt~<~gt~>~quot~\"~apos~'~amp~&"); +namedReferences['html4'] = generateNamedReferences("apos~'~OElig~Œ~oelig~œ~Scaron~Š~scaron~š~Yuml~Ÿ~circ~ˆ~tilde~˜~ensp~ ~emsp~ ~thinsp~ ~zwnj~‌~zwj~‍~lrm~‎~rlm~‏~ndash~–~mdash~—~lsquo~‘~rsquo~’~sbquo~‚~ldquo~“~rdquo~”~bdquo~„~dagger~†~Dagger~‡~permil~‰~lsaquo~‹~rsaquo~›~euro~€~fnof~ƒ~Alpha~Α~Beta~Β~Gamma~Γ~Delta~Δ~Epsilon~Ε~Zeta~Ζ~Eta~Η~Theta~Θ~Iota~Ι~Kappa~Κ~Lambda~Λ~Mu~Μ~Nu~Ν~Xi~Ξ~Omicron~Ο~Pi~Π~Rho~Ρ~Sigma~Σ~Tau~Τ~Upsilon~Υ~Phi~Φ~Chi~Χ~Psi~Ψ~Omega~Ω~alpha~α~beta~β~gamma~γ~delta~δ~epsilon~ε~zeta~ζ~eta~η~theta~θ~iota~ι~kappa~κ~lambda~λ~mu~μ~nu~ν~xi~ξ~omicron~ο~pi~π~rho~ρ~sigmaf~ς~sigma~σ~tau~τ~upsilon~υ~phi~φ~chi~χ~psi~ψ~omega~ω~thetasym~ϑ~upsih~ϒ~piv~ϖ~bull~•~hellip~…~prime~′~Prime~″~oline~‾~frasl~⁄~weierp~℘~image~ℑ~real~ℜ~trade~™~alefsym~ℵ~larr~←~uarr~↑~rarr~→~darr~↓~harr~↔~crarr~↵~lArr~⇐~uArr~⇑~rArr~⇒~dArr~⇓~hArr~⇔~forall~∀~part~∂~exist~∃~empty~∅~nabla~∇~isin~∈~notin~∉~ni~∋~prod~∏~sum~∑~minus~−~lowast~∗~radic~√~prop~∝~infin~∞~ang~∠~and~∧~or~∨~cap~∩~cup~∪~int~∫~there4~∴~sim~∼~cong~≅~asymp~≈~ne~≠~equiv~≡~le~≤~ge~≥~sub~⊂~sup~⊃~nsub~⊄~sube~⊆~supe~⊇~oplus~⊕~otimes~⊗~perp~⊥~sdot~⋅~lceil~⌈~rceil~⌉~lfloor~⌊~rfloor~⌋~lang~〈~rang~〉~loz~◊~spades~♠~clubs~♣~hearts~♥~diams~♦~~nbsp~ ~iexcl~¡~cent~¢~pound~£~curren~¤~yen~¥~brvbar~¦~sect~§~uml~¨~copy~©~ordf~ª~laquo~«~not~¬~shy~­~reg~®~macr~¯~deg~°~plusmn~±~sup2~²~sup3~³~acute~´~micro~µ~para~¶~middot~·~cedil~¸~sup1~¹~ordm~º~raquo~»~frac14~¼~frac12~½~frac34~¾~iquest~¿~Agrave~À~Aacute~Á~Acirc~Â~Atilde~Ã~Auml~Ä~Aring~Å~AElig~Æ~Ccedil~Ç~Egrave~È~Eacute~É~Ecirc~Ê~Euml~Ë~Igrave~Ì~Iacute~Í~Icirc~Î~Iuml~Ï~ETH~Ð~Ntilde~Ñ~Ograve~Ò~Oacute~Ó~Ocirc~Ô~Otilde~Õ~Ouml~Ö~times~×~Oslash~Ø~Ugrave~Ù~Uacute~Ú~Ucirc~Û~Uuml~Ü~Yacute~Ý~THORN~Þ~szlig~ß~agrave~à~aacute~á~acirc~â~atilde~ã~auml~ä~aring~å~aelig~æ~ccedil~ç~egrave~è~eacute~é~ecirc~ê~euml~ë~igrave~ì~iacute~í~icirc~î~iuml~ï~eth~ð~ntilde~ñ~ograve~ò~oacute~ó~ocirc~ô~otilde~õ~ouml~ö~divide~÷~oslash~ø~ugrave~ù~uacute~ú~ucirc~û~uuml~ü~yacute~ý~thorn~þ~yuml~ÿ~quot~\"~amp~&~lt~<~gt~>"); +namedReferences['html5'] = generateNamedReferences("Abreve~Ă~Acy~А~Afr~𝔄~Amacr~Ā~And~⩓~Aogon~Ą~Aopf~𝔸~ApplyFunction~⁡~Ascr~𝒜~Assign~≔~Backslash~∖~Barv~⫧~Barwed~⌆~Bcy~Б~Because~∵~Bernoullis~ℬ~Bfr~𝔅~Bopf~𝔹~Breve~˘~Bscr~ℬ~Bumpeq~≎~CHcy~Ч~Cacute~Ć~Cap~⋒~CapitalDifferentialD~ⅅ~Cayleys~ℭ~Ccaron~Č~Ccirc~Ĉ~Cconint~∰~Cdot~Ċ~Cedilla~¸~CenterDot~·~Cfr~ℭ~CircleDot~⊙~CircleMinus~⊖~CirclePlus~⊕~CircleTimes~⊗~ClockwiseContourIntegral~∲~CloseCurlyDoubleQuote~”~CloseCurlyQuote~’~Colon~∷~Colone~⩴~Congruent~≡~Conint~∯~ContourIntegral~∮~Copf~ℂ~Coproduct~∐~CounterClockwiseContourIntegral~∳~Cross~⨯~Cscr~𝒞~Cup~⋓~CupCap~≍~DD~ⅅ~DDotrahd~⤑~DJcy~Ђ~DScy~Ѕ~DZcy~Џ~Darr~↡~Dashv~⫤~Dcaron~Ď~Dcy~Д~Del~∇~Dfr~𝔇~DiacriticalAcute~´~DiacriticalDot~˙~DiacriticalDoubleAcute~˝~DiacriticalGrave~`~DiacriticalTilde~˜~Diamond~⋄~DifferentialD~ⅆ~Dopf~𝔻~Dot~¨~DotDot~⃜~DotEqual~≐~DoubleContourIntegral~∯~DoubleDot~¨~DoubleDownArrow~⇓~DoubleLeftArrow~⇐~DoubleLeftRightArrow~⇔~DoubleLeftTee~⫤~DoubleLongLeftArrow~⟸~DoubleLongLeftRightArrow~⟺~DoubleLongRightArrow~⟹~DoubleRightArrow~⇒~DoubleRightTee~⊨~DoubleUpArrow~⇑~DoubleUpDownArrow~⇕~DoubleVerticalBar~∥~DownArrow~↓~DownArrowBar~⤓~DownArrowUpArrow~⇵~DownBreve~̑~DownLeftRightVector~⥐~DownLeftTeeVector~⥞~DownLeftVector~↽~DownLeftVectorBar~⥖~DownRightTeeVector~⥟~DownRightVector~⇁~DownRightVectorBar~⥗~DownTee~⊤~DownTeeArrow~↧~Downarrow~⇓~Dscr~𝒟~Dstrok~Đ~ENG~Ŋ~Ecaron~Ě~Ecy~Э~Edot~Ė~Efr~𝔈~Element~∈~Emacr~Ē~EmptySmallSquare~◻~EmptyVerySmallSquare~▫~Eogon~Ę~Eopf~𝔼~Equal~⩵~EqualTilde~≂~Equilibrium~⇌~Escr~ℰ~Esim~⩳~Exists~∃~ExponentialE~ⅇ~Fcy~Ф~Ffr~𝔉~FilledSmallSquare~◼~FilledVerySmallSquare~▪~Fopf~𝔽~ForAll~∀~Fouriertrf~ℱ~Fscr~ℱ~GJcy~Ѓ~Gammad~Ϝ~Gbreve~Ğ~Gcedil~Ģ~Gcirc~Ĝ~Gcy~Г~Gdot~Ġ~Gfr~𝔊~Gg~⋙~Gopf~𝔾~GreaterEqual~≥~GreaterEqualLess~⋛~GreaterFullEqual~≧~GreaterGreater~⪢~GreaterLess~≷~GreaterSlantEqual~⩾~GreaterTilde~≳~Gscr~𝒢~Gt~≫~HARDcy~Ъ~Hacek~ˇ~Hat~^~Hcirc~Ĥ~Hfr~ℌ~HilbertSpace~ℋ~Hopf~ℍ~HorizontalLine~─~Hscr~ℋ~Hstrok~Ħ~HumpDownHump~≎~HumpEqual~≏~IEcy~Е~IJlig~IJ~IOcy~Ё~Icy~И~Idot~İ~Ifr~ℑ~Im~ℑ~Imacr~Ī~ImaginaryI~ⅈ~Implies~⇒~Int~∬~Integral~∫~Intersection~⋂~InvisibleComma~⁣~InvisibleTimes~⁢~Iogon~Į~Iopf~𝕀~Iscr~ℐ~Itilde~Ĩ~Iukcy~І~Jcirc~Ĵ~Jcy~Й~Jfr~𝔍~Jopf~𝕁~Jscr~𝒥~Jsercy~Ј~Jukcy~Є~KHcy~Х~KJcy~Ќ~Kcedil~Ķ~Kcy~К~Kfr~𝔎~Kopf~𝕂~Kscr~𝒦~LJcy~Љ~Lacute~Ĺ~Lang~⟪~Laplacetrf~ℒ~Larr~↞~Lcaron~Ľ~Lcedil~Ļ~Lcy~Л~LeftAngleBracket~⟨~LeftArrow~←~LeftArrowBar~⇤~LeftArrowRightArrow~⇆~LeftCeiling~⌈~LeftDoubleBracket~⟦~LeftDownTeeVector~⥡~LeftDownVector~⇃~LeftDownVectorBar~⥙~LeftFloor~⌊~LeftRightArrow~↔~LeftRightVector~⥎~LeftTee~⊣~LeftTeeArrow~↤~LeftTeeVector~⥚~LeftTriangle~⊲~LeftTriangleBar~⧏~LeftTriangleEqual~⊴~LeftUpDownVector~⥑~LeftUpTeeVector~⥠~LeftUpVector~↿~LeftUpVectorBar~⥘~LeftVector~↼~LeftVectorBar~⥒~Leftarrow~⇐~Leftrightarrow~⇔~LessEqualGreater~⋚~LessFullEqual~≦~LessGreater~≶~LessLess~⪡~LessSlantEqual~⩽~LessTilde~≲~Lfr~𝔏~Ll~⋘~Lleftarrow~⇚~Lmidot~Ŀ~LongLeftArrow~⟵~LongLeftRightArrow~⟷~LongRightArrow~⟶~Longleftarrow~⟸~Longleftrightarrow~⟺~Longrightarrow~⟹~Lopf~𝕃~LowerLeftArrow~↙~LowerRightArrow~↘~Lscr~ℒ~Lsh~↰~Lstrok~Ł~Lt~≪~Map~⤅~Mcy~М~MediumSpace~ ~Mellintrf~ℳ~Mfr~𝔐~MinusPlus~∓~Mopf~𝕄~Mscr~ℳ~NJcy~Њ~Nacute~Ń~Ncaron~Ň~Ncedil~Ņ~Ncy~Н~NegativeMediumSpace~​~NegativeThickSpace~​~NegativeThinSpace~​~NegativeVeryThinSpace~​~NestedGreaterGreater~≫~NestedLessLess~≪~NewLine~\n~Nfr~𝔑~NoBreak~⁠~NonBreakingSpace~ ~Nopf~ℕ~Not~⫬~NotCongruent~≢~NotCupCap~≭~NotDoubleVerticalBar~∦~NotElement~∉~NotEqual~≠~NotEqualTilde~≂̸~NotExists~∄~NotGreater~≯~NotGreaterEqual~≱~NotGreaterFullEqual~≧̸~NotGreaterGreater~≫̸~NotGreaterLess~≹~NotGreaterSlantEqual~⩾̸~NotGreaterTilde~≵~NotHumpDownHump~≎̸~NotHumpEqual~≏̸~NotLeftTriangle~⋪~NotLeftTriangleBar~⧏̸~NotLeftTriangleEqual~⋬~NotLess~≮~NotLessEqual~≰~NotLessGreater~≸~NotLessLess~≪̸~NotLessSlantEqual~⩽̸~NotLessTilde~≴~NotNestedGreaterGreater~⪢̸~NotNestedLessLess~⪡̸~NotPrecedes~⊀~NotPrecedesEqual~⪯̸~NotPrecedesSlantEqual~⋠~NotReverseElement~∌~NotRightTriangle~⋫~NotRightTriangleBar~⧐̸~NotRightTriangleEqual~⋭~NotSquareSubset~⊏̸~NotSquareSubsetEqual~⋢~NotSquareSuperset~⊐̸~NotSquareSupersetEqual~⋣~NotSubset~⊂⃒~NotSubsetEqual~⊈~NotSucceeds~⊁~NotSucceedsEqual~⪰̸~NotSucceedsSlantEqual~⋡~NotSucceedsTilde~≿̸~NotSuperset~⊃⃒~NotSupersetEqual~⊉~NotTilde~≁~NotTildeEqual~≄~NotTildeFullEqual~≇~NotTildeTilde~≉~NotVerticalBar~∤~Nscr~𝒩~Ocy~О~Odblac~Ő~Ofr~𝔒~Omacr~Ō~Oopf~𝕆~OpenCurlyDoubleQuote~“~OpenCurlyQuote~‘~Or~⩔~Oscr~𝒪~Otimes~⨷~OverBar~‾~OverBrace~⏞~OverBracket~⎴~OverParenthesis~⏜~PartialD~∂~Pcy~П~Pfr~𝔓~PlusMinus~±~Poincareplane~ℌ~Popf~ℙ~Pr~⪻~Precedes~≺~PrecedesEqual~⪯~PrecedesSlantEqual~≼~PrecedesTilde~≾~Product~∏~Proportion~∷~Proportional~∝~Pscr~𝒫~Qfr~𝔔~Qopf~ℚ~Qscr~𝒬~RBarr~⤐~Racute~Ŕ~Rang~⟫~Rarr~↠~Rarrtl~⤖~Rcaron~Ř~Rcedil~Ŗ~Rcy~Р~Re~ℜ~ReverseElement~∋~ReverseEquilibrium~⇋~ReverseUpEquilibrium~⥯~Rfr~ℜ~RightAngleBracket~⟩~RightArrow~→~RightArrowBar~⇥~RightArrowLeftArrow~⇄~RightCeiling~⌉~RightDoubleBracket~⟧~RightDownTeeVector~⥝~RightDownVector~⇂~RightDownVectorBar~⥕~RightFloor~⌋~RightTee~⊢~RightTeeArrow~↦~RightTeeVector~⥛~RightTriangle~⊳~RightTriangleBar~⧐~RightTriangleEqual~⊵~RightUpDownVector~⥏~RightUpTeeVector~⥜~RightUpVector~↾~RightUpVectorBar~⥔~RightVector~⇀~RightVectorBar~⥓~Rightarrow~⇒~Ropf~ℝ~RoundImplies~⥰~Rrightarrow~⇛~Rscr~ℛ~Rsh~↱~RuleDelayed~⧴~SHCHcy~Щ~SHcy~Ш~SOFTcy~Ь~Sacute~Ś~Sc~⪼~Scedil~Ş~Scirc~Ŝ~Scy~С~Sfr~𝔖~ShortDownArrow~↓~ShortLeftArrow~←~ShortRightArrow~→~ShortUpArrow~↑~SmallCircle~∘~Sopf~𝕊~Sqrt~√~Square~□~SquareIntersection~⊓~SquareSubset~⊏~SquareSubsetEqual~⊑~SquareSuperset~⊐~SquareSupersetEqual~⊒~SquareUnion~⊔~Sscr~𝒮~Star~⋆~Sub~⋐~Subset~⋐~SubsetEqual~⊆~Succeeds~≻~SucceedsEqual~⪰~SucceedsSlantEqual~≽~SucceedsTilde~≿~SuchThat~∋~Sum~∑~Sup~⋑~Superset~⊃~SupersetEqual~⊇~Supset~⋑~TRADE~™~TSHcy~Ћ~TScy~Ц~Tab~\t~Tcaron~Ť~Tcedil~Ţ~Tcy~Т~Tfr~𝔗~Therefore~∴~ThickSpace~  ~ThinSpace~ ~Tilde~∼~TildeEqual~≃~TildeFullEqual~≅~TildeTilde~≈~Topf~𝕋~TripleDot~⃛~Tscr~𝒯~Tstrok~Ŧ~Uarr~↟~Uarrocir~⥉~Ubrcy~Ў~Ubreve~Ŭ~Ucy~У~Udblac~Ű~Ufr~𝔘~Umacr~Ū~UnderBar~_~UnderBrace~⏟~UnderBracket~⎵~UnderParenthesis~⏝~Union~⋃~UnionPlus~⊎~Uogon~Ų~Uopf~𝕌~UpArrow~↑~UpArrowBar~⤒~UpArrowDownArrow~⇅~UpDownArrow~↕~UpEquilibrium~⥮~UpTee~⊥~UpTeeArrow~↥~Uparrow~⇑~Updownarrow~⇕~UpperLeftArrow~↖~UpperRightArrow~↗~Upsi~ϒ~Uring~Ů~Uscr~𝒰~Utilde~Ũ~VDash~⊫~Vbar~⫫~Vcy~В~Vdash~⊩~Vdashl~⫦~Vee~⋁~Verbar~‖~Vert~‖~VerticalBar~∣~VerticalLine~|~VerticalSeparator~❘~VerticalTilde~≀~VeryThinSpace~ ~Vfr~𝔙~Vopf~𝕍~Vscr~𝒱~Vvdash~⊪~Wcirc~Ŵ~Wedge~⋀~Wfr~𝔚~Wopf~𝕎~Wscr~𝒲~Xfr~𝔛~Xopf~𝕏~Xscr~𝒳~YAcy~Я~YIcy~Ї~YUcy~Ю~Ycirc~Ŷ~Ycy~Ы~Yfr~𝔜~Yopf~𝕐~Yscr~𝒴~ZHcy~Ж~Zacute~Ź~Zcaron~Ž~Zcy~З~Zdot~Ż~ZeroWidthSpace~​~Zfr~ℨ~Zopf~ℤ~Zscr~𝒵~abreve~ă~ac~∾~acE~∾̳~acd~∿~acy~а~af~⁡~afr~𝔞~aleph~ℵ~amacr~ā~amalg~⨿~andand~⩕~andd~⩜~andslope~⩘~andv~⩚~ange~⦤~angle~∠~angmsd~∡~angmsdaa~⦨~angmsdab~⦩~angmsdac~⦪~angmsdad~⦫~angmsdae~⦬~angmsdaf~⦭~angmsdag~⦮~angmsdah~⦯~angrt~∟~angrtvb~⊾~angrtvbd~⦝~angsph~∢~angst~Å~angzarr~⍼~aogon~ą~aopf~𝕒~ap~≈~apE~⩰~apacir~⩯~ape~≊~apid~≋~approx~≈~approxeq~≊~ascr~𝒶~ast~*~asympeq~≍~awconint~∳~awint~⨑~bNot~⫭~backcong~≌~backepsilon~϶~backprime~‵~backsim~∽~backsimeq~⋍~barvee~⊽~barwed~⌅~barwedge~⌅~bbrk~⎵~bbrktbrk~⎶~bcong~≌~bcy~б~becaus~∵~because~∵~bemptyv~⦰~bepsi~϶~bernou~ℬ~beth~ℶ~between~≬~bfr~𝔟~bigcap~⋂~bigcirc~◯~bigcup~⋃~bigodot~⨀~bigoplus~⨁~bigotimes~⨂~bigsqcup~⨆~bigstar~★~bigtriangledown~▽~bigtriangleup~△~biguplus~⨄~bigvee~⋁~bigwedge~⋀~bkarow~⤍~blacklozenge~⧫~blacksquare~▪~blacktriangle~▴~blacktriangledown~▾~blacktriangleleft~◂~blacktriangleright~▸~blank~␣~blk12~▒~blk14~░~blk34~▓~block~█~bne~=⃥~bnequiv~≡⃥~bnot~⌐~bopf~𝕓~bot~⊥~bottom~⊥~bowtie~⋈~boxDL~╗~boxDR~╔~boxDl~╖~boxDr~╓~boxH~═~boxHD~╦~boxHU~╩~boxHd~╤~boxHu~╧~boxUL~╝~boxUR~╚~boxUl~╜~boxUr~╙~boxV~║~boxVH~╬~boxVL~╣~boxVR~╠~boxVh~╫~boxVl~╢~boxVr~╟~boxbox~⧉~boxdL~╕~boxdR~╒~boxdl~┐~boxdr~┌~boxh~─~boxhD~╥~boxhU~╨~boxhd~┬~boxhu~┴~boxminus~⊟~boxplus~⊞~boxtimes~⊠~boxuL~╛~boxuR~╘~boxul~┘~boxur~└~boxv~│~boxvH~╪~boxvL~╡~boxvR~╞~boxvh~┼~boxvl~┤~boxvr~├~bprime~‵~breve~˘~bscr~𝒷~bsemi~⁏~bsim~∽~bsime~⋍~bsol~\\~bsolb~⧅~bsolhsub~⟈~bullet~•~bump~≎~bumpE~⪮~bumpe~≏~bumpeq~≏~cacute~ć~capand~⩄~capbrcup~⩉~capcap~⩋~capcup~⩇~capdot~⩀~caps~∩︀~caret~⁁~caron~ˇ~ccaps~⩍~ccaron~č~ccirc~ĉ~ccups~⩌~ccupssm~⩐~cdot~ċ~cemptyv~⦲~centerdot~·~cfr~𝔠~chcy~ч~check~✓~checkmark~✓~cir~○~cirE~⧃~circeq~≗~circlearrowleft~↺~circlearrowright~↻~circledR~®~circledS~Ⓢ~circledast~⊛~circledcirc~⊚~circleddash~⊝~cire~≗~cirfnint~⨐~cirmid~⫯~cirscir~⧂~clubsuit~♣~colon~:~colone~≔~coloneq~≔~comma~,~commat~@~comp~∁~compfn~∘~complement~∁~complexes~ℂ~congdot~⩭~conint~∮~copf~𝕔~coprod~∐~copysr~℗~cross~✗~cscr~𝒸~csub~⫏~csube~⫑~csup~⫐~csupe~⫒~ctdot~⋯~cudarrl~⤸~cudarrr~⤵~cuepr~⋞~cuesc~⋟~cularr~↶~cularrp~⤽~cupbrcap~⩈~cupcap~⩆~cupcup~⩊~cupdot~⊍~cupor~⩅~cups~∪︀~curarr~↷~curarrm~⤼~curlyeqprec~⋞~curlyeqsucc~⋟~curlyvee~⋎~curlywedge~⋏~curvearrowleft~↶~curvearrowright~↷~cuvee~⋎~cuwed~⋏~cwconint~∲~cwint~∱~cylcty~⌭~dHar~⥥~daleth~ℸ~dash~‐~dashv~⊣~dbkarow~⤏~dblac~˝~dcaron~ď~dcy~д~dd~ⅆ~ddagger~‡~ddarr~⇊~ddotseq~⩷~demptyv~⦱~dfisht~⥿~dfr~𝔡~dharl~⇃~dharr~⇂~diam~⋄~diamond~⋄~diamondsuit~♦~die~¨~digamma~ϝ~disin~⋲~div~÷~divideontimes~⋇~divonx~⋇~djcy~ђ~dlcorn~⌞~dlcrop~⌍~dollar~$~dopf~𝕕~dot~˙~doteq~≐~doteqdot~≑~dotminus~∸~dotplus~∔~dotsquare~⊡~doublebarwedge~⌆~downarrow~↓~downdownarrows~⇊~downharpoonleft~⇃~downharpoonright~⇂~drbkarow~⤐~drcorn~⌟~drcrop~⌌~dscr~𝒹~dscy~ѕ~dsol~⧶~dstrok~đ~dtdot~⋱~dtri~▿~dtrif~▾~duarr~⇵~duhar~⥯~dwangle~⦦~dzcy~џ~dzigrarr~⟿~eDDot~⩷~eDot~≑~easter~⩮~ecaron~ě~ecir~≖~ecolon~≕~ecy~э~edot~ė~ee~ⅇ~efDot~≒~efr~𝔢~eg~⪚~egs~⪖~egsdot~⪘~el~⪙~elinters~⏧~ell~ℓ~els~⪕~elsdot~⪗~emacr~ē~emptyset~∅~emptyv~∅~emsp13~ ~emsp14~ ~eng~ŋ~eogon~ę~eopf~𝕖~epar~⋕~eparsl~⧣~eplus~⩱~epsi~ε~epsiv~ϵ~eqcirc~≖~eqcolon~≕~eqsim~≂~eqslantgtr~⪖~eqslantless~⪕~equals~=~equest~≟~equivDD~⩸~eqvparsl~⧥~erDot~≓~erarr~⥱~escr~ℯ~esdot~≐~esim~≂~excl~!~expectation~ℰ~exponentiale~ⅇ~fallingdotseq~≒~fcy~ф~female~♀~ffilig~ffi~fflig~ff~ffllig~ffl~ffr~𝔣~filig~fi~fjlig~fj~flat~♭~fllig~fl~fltns~▱~fopf~𝕗~fork~⋔~forkv~⫙~fpartint~⨍~frac13~⅓~frac15~⅕~frac16~⅙~frac18~⅛~frac23~⅔~frac25~⅖~frac35~⅗~frac38~⅜~frac45~⅘~frac56~⅚~frac58~⅝~frac78~⅞~frown~⌢~fscr~𝒻~gE~≧~gEl~⪌~gacute~ǵ~gammad~ϝ~gap~⪆~gbreve~ğ~gcirc~ĝ~gcy~г~gdot~ġ~gel~⋛~geq~≥~geqq~≧~geqslant~⩾~ges~⩾~gescc~⪩~gesdot~⪀~gesdoto~⪂~gesdotol~⪄~gesl~⋛︀~gesles~⪔~gfr~𝔤~gg~≫~ggg~⋙~gimel~ℷ~gjcy~ѓ~gl~≷~glE~⪒~gla~⪥~glj~⪤~gnE~≩~gnap~⪊~gnapprox~⪊~gne~⪈~gneq~⪈~gneqq~≩~gnsim~⋧~gopf~𝕘~grave~`~gscr~ℊ~gsim~≳~gsime~⪎~gsiml~⪐~gtcc~⪧~gtcir~⩺~gtdot~⋗~gtlPar~⦕~gtquest~⩼~gtrapprox~⪆~gtrarr~⥸~gtrdot~⋗~gtreqless~⋛~gtreqqless~⪌~gtrless~≷~gtrsim~≳~gvertneqq~≩︀~gvnE~≩︀~hairsp~ ~half~½~hamilt~ℋ~hardcy~ъ~harrcir~⥈~harrw~↭~hbar~ℏ~hcirc~ĥ~heartsuit~♥~hercon~⊹~hfr~𝔥~hksearow~⤥~hkswarow~⤦~hoarr~⇿~homtht~∻~hookleftarrow~↩~hookrightarrow~↪~hopf~𝕙~horbar~―~hscr~𝒽~hslash~ℏ~hstrok~ħ~hybull~⁃~hyphen~‐~ic~⁣~icy~и~iecy~е~iff~⇔~ifr~𝔦~ii~ⅈ~iiiint~⨌~iiint~∭~iinfin~⧜~iiota~℩~ijlig~ij~imacr~ī~imagline~ℐ~imagpart~ℑ~imath~ı~imof~⊷~imped~Ƶ~in~∈~incare~℅~infintie~⧝~inodot~ı~intcal~⊺~integers~ℤ~intercal~⊺~intlarhk~⨗~intprod~⨼~iocy~ё~iogon~į~iopf~𝕚~iprod~⨼~iscr~𝒾~isinE~⋹~isindot~⋵~isins~⋴~isinsv~⋳~isinv~∈~it~⁢~itilde~ĩ~iukcy~і~jcirc~ĵ~jcy~й~jfr~𝔧~jmath~ȷ~jopf~𝕛~jscr~𝒿~jsercy~ј~jukcy~є~kappav~ϰ~kcedil~ķ~kcy~к~kfr~𝔨~kgreen~ĸ~khcy~х~kjcy~ќ~kopf~𝕜~kscr~𝓀~lAarr~⇚~lAtail~⤛~lBarr~⤎~lE~≦~lEg~⪋~lHar~⥢~lacute~ĺ~laemptyv~⦴~lagran~ℒ~langd~⦑~langle~⟨~lap~⪅~larrb~⇤~larrbfs~⤟~larrfs~⤝~larrhk~↩~larrlp~↫~larrpl~⤹~larrsim~⥳~larrtl~↢~lat~⪫~latail~⤙~late~⪭~lates~⪭︀~lbarr~⤌~lbbrk~❲~lbrace~{~lbrack~[~lbrke~⦋~lbrksld~⦏~lbrkslu~⦍~lcaron~ľ~lcedil~ļ~lcub~{~lcy~л~ldca~⤶~ldquor~„~ldrdhar~⥧~ldrushar~⥋~ldsh~↲~leftarrow~←~leftarrowtail~↢~leftharpoondown~↽~leftharpoonup~↼~leftleftarrows~⇇~leftrightarrow~↔~leftrightarrows~⇆~leftrightharpoons~⇋~leftrightsquigarrow~↭~leftthreetimes~⋋~leg~⋚~leq~≤~leqq~≦~leqslant~⩽~les~⩽~lescc~⪨~lesdot~⩿~lesdoto~⪁~lesdotor~⪃~lesg~⋚︀~lesges~⪓~lessapprox~⪅~lessdot~⋖~lesseqgtr~⋚~lesseqqgtr~⪋~lessgtr~≶~lesssim~≲~lfisht~⥼~lfr~𝔩~lg~≶~lgE~⪑~lhard~↽~lharu~↼~lharul~⥪~lhblk~▄~ljcy~љ~ll~≪~llarr~⇇~llcorner~⌞~llhard~⥫~lltri~◺~lmidot~ŀ~lmoust~⎰~lmoustache~⎰~lnE~≨~lnap~⪉~lnapprox~⪉~lne~⪇~lneq~⪇~lneqq~≨~lnsim~⋦~loang~⟬~loarr~⇽~lobrk~⟦~longleftarrow~⟵~longleftrightarrow~⟷~longmapsto~⟼~longrightarrow~⟶~looparrowleft~↫~looparrowright~↬~lopar~⦅~lopf~𝕝~loplus~⨭~lotimes~⨴~lowbar~_~lozenge~◊~lozf~⧫~lpar~(~lparlt~⦓~lrarr~⇆~lrcorner~⌟~lrhar~⇋~lrhard~⥭~lrtri~⊿~lscr~𝓁~lsh~↰~lsim~≲~lsime~⪍~lsimg~⪏~lsqb~[~lsquor~‚~lstrok~ł~ltcc~⪦~ltcir~⩹~ltdot~⋖~lthree~⋋~ltimes~⋉~ltlarr~⥶~ltquest~⩻~ltrPar~⦖~ltri~◃~ltrie~⊴~ltrif~◂~lurdshar~⥊~luruhar~⥦~lvertneqq~≨︀~lvnE~≨︀~mDDot~∺~male~♂~malt~✠~maltese~✠~map~↦~mapsto~↦~mapstodown~↧~mapstoleft~↤~mapstoup~↥~marker~▮~mcomma~⨩~mcy~м~measuredangle~∡~mfr~𝔪~mho~℧~mid~∣~midast~*~midcir~⫰~minusb~⊟~minusd~∸~minusdu~⨪~mlcp~⫛~mldr~…~mnplus~∓~models~⊧~mopf~𝕞~mp~∓~mscr~𝓂~mstpos~∾~multimap~⊸~mumap~⊸~nGg~⋙̸~nGt~≫⃒~nGtv~≫̸~nLeftarrow~⇍~nLeftrightarrow~⇎~nLl~⋘̸~nLt~≪⃒~nLtv~≪̸~nRightarrow~⇏~nVDash~⊯~nVdash~⊮~nacute~ń~nang~∠⃒~nap~≉~napE~⩰̸~napid~≋̸~napos~ʼn~napprox~≉~natur~♮~natural~♮~naturals~ℕ~nbump~≎̸~nbumpe~≏̸~ncap~⩃~ncaron~ň~ncedil~ņ~ncong~≇~ncongdot~⩭̸~ncup~⩂~ncy~н~neArr~⇗~nearhk~⤤~nearr~↗~nearrow~↗~nedot~≐̸~nequiv~≢~nesear~⤨~nesim~≂̸~nexist~∄~nexists~∄~nfr~𝔫~ngE~≧̸~nge~≱~ngeq~≱~ngeqq~≧̸~ngeqslant~⩾̸~nges~⩾̸~ngsim~≵~ngt~≯~ngtr~≯~nhArr~⇎~nharr~↮~nhpar~⫲~nis~⋼~nisd~⋺~niv~∋~njcy~њ~nlArr~⇍~nlE~≦̸~nlarr~↚~nldr~‥~nle~≰~nleftarrow~↚~nleftrightarrow~↮~nleq~≰~nleqq~≦̸~nleqslant~⩽̸~nles~⩽̸~nless~≮~nlsim~≴~nlt~≮~nltri~⋪~nltrie~⋬~nmid~∤~nopf~𝕟~notinE~⋹̸~notindot~⋵̸~notinva~∉~notinvb~⋷~notinvc~⋶~notni~∌~notniva~∌~notnivb~⋾~notnivc~⋽~npar~∦~nparallel~∦~nparsl~⫽⃥~npart~∂̸~npolint~⨔~npr~⊀~nprcue~⋠~npre~⪯̸~nprec~⊀~npreceq~⪯̸~nrArr~⇏~nrarr~↛~nrarrc~⤳̸~nrarrw~↝̸~nrightarrow~↛~nrtri~⋫~nrtrie~⋭~nsc~⊁~nsccue~⋡~nsce~⪰̸~nscr~𝓃~nshortmid~∤~nshortparallel~∦~nsim~≁~nsime~≄~nsimeq~≄~nsmid~∤~nspar~∦~nsqsube~⋢~nsqsupe~⋣~nsubE~⫅̸~nsube~⊈~nsubset~⊂⃒~nsubseteq~⊈~nsubseteqq~⫅̸~nsucc~⊁~nsucceq~⪰̸~nsup~⊅~nsupE~⫆̸~nsupe~⊉~nsupset~⊃⃒~nsupseteq~⊉~nsupseteqq~⫆̸~ntgl~≹~ntlg~≸~ntriangleleft~⋪~ntrianglelefteq~⋬~ntriangleright~⋫~ntrianglerighteq~⋭~num~#~numero~№~numsp~ ~nvDash~⊭~nvHarr~⤄~nvap~≍⃒~nvdash~⊬~nvge~≥⃒~nvgt~>⃒~nvinfin~⧞~nvlArr~⤂~nvle~≤⃒~nvlt~<⃒~nvltrie~⊴⃒~nvrArr~⤃~nvrtrie~⊵⃒~nvsim~∼⃒~nwArr~⇖~nwarhk~⤣~nwarr~↖~nwarrow~↖~nwnear~⤧~oS~Ⓢ~oast~⊛~ocir~⊚~ocy~о~odash~⊝~odblac~ő~odiv~⨸~odot~⊙~odsold~⦼~ofcir~⦿~ofr~𝔬~ogon~˛~ogt~⧁~ohbar~⦵~ohm~Ω~oint~∮~olarr~↺~olcir~⦾~olcross~⦻~olt~⧀~omacr~ō~omid~⦶~ominus~⊖~oopf~𝕠~opar~⦷~operp~⦹~orarr~↻~ord~⩝~order~ℴ~orderof~ℴ~origof~⊶~oror~⩖~orslope~⩗~orv~⩛~oscr~ℴ~osol~⊘~otimesas~⨶~ovbar~⌽~par~∥~parallel~∥~parsim~⫳~parsl~⫽~pcy~п~percnt~%~period~.~pertenk~‱~pfr~𝔭~phiv~ϕ~phmmat~ℳ~phone~☎~pitchfork~⋔~planck~ℏ~planckh~ℎ~plankv~ℏ~plus~+~plusacir~⨣~plusb~⊞~pluscir~⨢~plusdo~∔~plusdu~⨥~pluse~⩲~plussim~⨦~plustwo~⨧~pm~±~pointint~⨕~popf~𝕡~pr~≺~prE~⪳~prap~⪷~prcue~≼~pre~⪯~prec~≺~precapprox~⪷~preccurlyeq~≼~preceq~⪯~precnapprox~⪹~precneqq~⪵~precnsim~⋨~precsim~≾~primes~ℙ~prnE~⪵~prnap~⪹~prnsim~⋨~profalar~⌮~profline~⌒~profsurf~⌓~propto~∝~prsim~≾~prurel~⊰~pscr~𝓅~puncsp~ ~qfr~𝔮~qint~⨌~qopf~𝕢~qprime~⁗~qscr~𝓆~quaternions~ℍ~quatint~⨖~quest~?~questeq~≟~rAarr~⇛~rAtail~⤜~rBarr~⤏~rHar~⥤~race~∽̱~racute~ŕ~raemptyv~⦳~rangd~⦒~range~⦥~rangle~⟩~rarrap~⥵~rarrb~⇥~rarrbfs~⤠~rarrc~⤳~rarrfs~⤞~rarrhk~↪~rarrlp~↬~rarrpl~⥅~rarrsim~⥴~rarrtl~↣~rarrw~↝~ratail~⤚~ratio~∶~rationals~ℚ~rbarr~⤍~rbbrk~❳~rbrace~}~rbrack~]~rbrke~⦌~rbrksld~⦎~rbrkslu~⦐~rcaron~ř~rcedil~ŗ~rcub~}~rcy~р~rdca~⤷~rdldhar~⥩~rdquor~”~rdsh~↳~realine~ℛ~realpart~ℜ~reals~ℝ~rect~▭~rfisht~⥽~rfr~𝔯~rhard~⇁~rharu~⇀~rharul~⥬~rhov~ϱ~rightarrow~→~rightarrowtail~↣~rightharpoondown~⇁~rightharpoonup~⇀~rightleftarrows~⇄~rightleftharpoons~⇌~rightrightarrows~⇉~rightsquigarrow~↝~rightthreetimes~⋌~ring~˚~risingdotseq~≓~rlarr~⇄~rlhar~⇌~rmoust~⎱~rmoustache~⎱~rnmid~⫮~roang~⟭~roarr~⇾~robrk~⟧~ropar~⦆~ropf~𝕣~roplus~⨮~rotimes~⨵~rpar~)~rpargt~⦔~rppolint~⨒~rrarr~⇉~rscr~𝓇~rsh~↱~rsqb~]~rsquor~’~rthree~⋌~rtimes~⋊~rtri~▹~rtrie~⊵~rtrif~▸~rtriltri~⧎~ruluhar~⥨~rx~℞~sacute~ś~sc~≻~scE~⪴~scap~⪸~sccue~≽~sce~⪰~scedil~ş~scirc~ŝ~scnE~⪶~scnap~⪺~scnsim~⋩~scpolint~⨓~scsim~≿~scy~с~sdotb~⊡~sdote~⩦~seArr~⇘~searhk~⤥~searr~↘~searrow~↘~semi~;~seswar~⤩~setminus~∖~setmn~∖~sext~✶~sfr~𝔰~sfrown~⌢~sharp~♯~shchcy~щ~shcy~ш~shortmid~∣~shortparallel~∥~sigmav~ς~simdot~⩪~sime~≃~simeq~≃~simg~⪞~simgE~⪠~siml~⪝~simlE~⪟~simne~≆~simplus~⨤~simrarr~⥲~slarr~←~smallsetminus~∖~smashp~⨳~smeparsl~⧤~smid~∣~smile~⌣~smt~⪪~smte~⪬~smtes~⪬︀~softcy~ь~sol~/~solb~⧄~solbar~⌿~sopf~𝕤~spadesuit~♠~spar~∥~sqcap~⊓~sqcaps~⊓︀~sqcup~⊔~sqcups~⊔︀~sqsub~⊏~sqsube~⊑~sqsubset~⊏~sqsubseteq~⊑~sqsup~⊐~sqsupe~⊒~sqsupset~⊐~sqsupseteq~⊒~squ~□~square~□~squarf~▪~squf~▪~srarr~→~sscr~𝓈~ssetmn~∖~ssmile~⌣~sstarf~⋆~star~☆~starf~★~straightepsilon~ϵ~straightphi~ϕ~strns~¯~subE~⫅~subdot~⪽~subedot~⫃~submult~⫁~subnE~⫋~subne~⊊~subplus~⪿~subrarr~⥹~subset~⊂~subseteq~⊆~subseteqq~⫅~subsetneq~⊊~subsetneqq~⫋~subsim~⫇~subsub~⫕~subsup~⫓~succ~≻~succapprox~⪸~succcurlyeq~≽~succeq~⪰~succnapprox~⪺~succneqq~⪶~succnsim~⋩~succsim~≿~sung~♪~supE~⫆~supdot~⪾~supdsub~⫘~supedot~⫄~suphsol~⟉~suphsub~⫗~suplarr~⥻~supmult~⫂~supnE~⫌~supne~⊋~supplus~⫀~supset~⊃~supseteq~⊇~supseteqq~⫆~supsetneq~⊋~supsetneqq~⫌~supsim~⫈~supsub~⫔~supsup~⫖~swArr~⇙~swarhk~⤦~swarr~↙~swarrow~↙~swnwar~⤪~target~⌖~tbrk~⎴~tcaron~ť~tcedil~ţ~tcy~т~tdot~⃛~telrec~⌕~tfr~𝔱~therefore~∴~thetav~ϑ~thickapprox~≈~thicksim~∼~thkap~≈~thksim~∼~timesb~⊠~timesbar~⨱~timesd~⨰~tint~∭~toea~⤨~top~⊤~topbot~⌶~topcir~⫱~topf~𝕥~topfork~⫚~tosa~⤩~tprime~‴~triangle~▵~triangledown~▿~triangleleft~◃~trianglelefteq~⊴~triangleq~≜~triangleright~▹~trianglerighteq~⊵~tridot~◬~trie~≜~triminus~⨺~triplus~⨹~trisb~⧍~tritime~⨻~trpezium~⏢~tscr~𝓉~tscy~ц~tshcy~ћ~tstrok~ŧ~twixt~≬~twoheadleftarrow~↞~twoheadrightarrow~↠~uHar~⥣~ubrcy~ў~ubreve~ŭ~ucy~у~udarr~⇅~udblac~ű~udhar~⥮~ufisht~⥾~ufr~𝔲~uharl~↿~uharr~↾~uhblk~▀~ulcorn~⌜~ulcorner~⌜~ulcrop~⌏~ultri~◸~umacr~ū~uogon~ų~uopf~𝕦~uparrow~↑~updownarrow~↕~upharpoonleft~↿~upharpoonright~↾~uplus~⊎~upsi~υ~upuparrows~⇈~urcorn~⌝~urcorner~⌝~urcrop~⌎~uring~ů~urtri~◹~uscr~𝓊~utdot~⋰~utilde~ũ~utri~▵~utrif~▴~uuarr~⇈~uwangle~⦧~vArr~⇕~vBar~⫨~vBarv~⫩~vDash~⊨~vangrt~⦜~varepsilon~ϵ~varkappa~ϰ~varnothing~∅~varphi~ϕ~varpi~ϖ~varpropto~∝~varr~↕~varrho~ϱ~varsigma~ς~varsubsetneq~⊊︀~varsubsetneqq~⫋︀~varsupsetneq~⊋︀~varsupsetneqq~⫌︀~vartheta~ϑ~vartriangleleft~⊲~vartriangleright~⊳~vcy~в~vdash~⊢~vee~∨~veebar~⊻~veeeq~≚~vellip~⋮~verbar~|~vert~|~vfr~𝔳~vltri~⊲~vnsub~⊂⃒~vnsup~⊃⃒~vopf~𝕧~vprop~∝~vrtri~⊳~vscr~𝓋~vsubnE~⫋︀~vsubne~⊊︀~vsupnE~⫌︀~vsupne~⊋︀~vzigzag~⦚~wcirc~ŵ~wedbar~⩟~wedge~∧~wedgeq~≙~wfr~𝔴~wopf~𝕨~wp~℘~wr~≀~wreath~≀~wscr~𝓌~xcap~⋂~xcirc~◯~xcup~⋃~xdtri~▽~xfr~𝔵~xhArr~⟺~xharr~⟷~xlArr~⟸~xlarr~⟵~xmap~⟼~xnis~⋻~xodot~⨀~xopf~𝕩~xoplus~⨁~xotime~⨂~xrArr~⟹~xrarr~⟶~xscr~𝓍~xsqcup~⨆~xuplus~⨄~xutri~△~xvee~⋁~xwedge~⋀~yacy~я~ycirc~ŷ~ycy~ы~yfr~𝔶~yicy~ї~yopf~𝕪~yscr~𝓎~yucy~ю~zacute~ź~zcaron~ž~zcy~з~zdot~ż~zeetrf~ℨ~zfr~𝔷~zhcy~ж~zigrarr~⇝~zopf~𝕫~zscr~𝓏~~AMP~&~COPY~©~GT~>~LT~<~QUOT~\"~REG~®", namedReferences['html4']); +//# sourceMappingURL=named-references.js.map + +/***/ }, + +/***/ "./node_modules/html-entities/dist/esm/numeric-unicode-map.js" +/*!********************************************************************!*\ + !*** ./node_modules/html-entities/dist/esm/numeric-unicode-map.js ***! + \********************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ numericUnicodeMap: () => (/* binding */ numericUnicodeMap) +/* harmony export */ }); +var numericUnicodeMap = { + 0: 65533, + 128: 8364, + 130: 8218, + 131: 402, + 132: 8222, + 133: 8230, + 134: 8224, + 135: 8225, + 136: 710, + 137: 8240, + 138: 352, + 139: 8249, + 140: 338, + 142: 381, + 145: 8216, + 146: 8217, + 147: 8220, + 148: 8221, + 149: 8226, + 150: 8211, + 151: 8212, + 152: 732, + 153: 8482, + 154: 353, + 155: 8250, + 156: 339, + 158: 382, + 159: 376 +}; +//# sourceMappingURL=numeric-unicode-map.js.map + +/***/ }, + +/***/ "./node_modules/html-entities/dist/esm/surrogate-pairs.js" +/*!****************************************************************!*\ + !*** ./node_modules/html-entities/dist/esm/surrogate-pairs.js ***! + \****************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ fromCodePoint: () => (/* binding */ fromCodePoint), +/* harmony export */ getCodePoint: () => (/* binding */ getCodePoint), +/* harmony export */ highSurrogateFrom: () => (/* binding */ highSurrogateFrom), +/* harmony export */ highSurrogateTo: () => (/* binding */ highSurrogateTo) +/* harmony export */ }); +var fromCodePoint = String.fromCodePoint || + function (astralCodePoint) { + return String.fromCharCode(Math.floor((astralCodePoint - 0x10000) / 0x400) + 0xd800, ((astralCodePoint - 0x10000) % 0x400) + 0xdc00); + }; +// @ts-expect-error - String.prototype.codePointAt might not exist in older node versions +var getCodePoint = String.prototype.codePointAt + ? function (input, position) { + return input.codePointAt(position); + } + : function (input, position) { + return (input.charCodeAt(position) - 0xd800) * 0x400 + input.charCodeAt(position + 1) - 0xdc00 + 0x10000; + }; +var highSurrogateFrom = 0xd800; +var highSurrogateTo = 0xdbff; +//# sourceMappingURL=surrogate-pairs.js.map + +/***/ }, + +/***/ "./node_modules/jsonld-document-loader/lib/JsonLdDocumentLoader.js" +/*!*************************************************************************!*\ + !*** ./node_modules/jsonld-document-loader/lib/JsonLdDocumentLoader.js ***! + \*************************************************************************/ +(module) { + +"use strict"; +/*! + * Copyright (c) 2019-2022 Digital Bazaar, Inc. All rights reserved. + */ + + +class JsonLdDocumentLoader { + constructor() { + this.documents = new Map(); + this.protocolHandlers = new Map(); + } + + addStatic(url, document) { + if(!_isString(url)) { + throw new TypeError('The first parameter (url) must be a string.'); + } + if(!_isObject(document)) { + throw new TypeError('The second parameter (document) must be an object.'); + } + this.documents.set(url, document); + } + + /** + * Adds a custom protocol handler to the loader. + * + * @example + * // Using did-io's CachedResolver instance as a did: protocol handler + * jld.addProtocolHandler({protocol: 'did', handler: cachedResolver}); + * + * @param {string} protocol - Protocol id, such as 'did', 'https', etc. + * @param {{get: Function}} handler - Protocol handler object, exposes an + * async `get({url})` method. + */ + setProtocolHandler({protocol, handler} = {}) { + this.protocolHandlers.set(protocol, handler); + } + + /** + * Sets a DID resolver (either a method-specific resolver to support just a + * single DID method, or a general driver harness to support multiple DID + * methods) as the 'did' protocol handler. + * + * @param {object} didResolver - A did-io style did method driver, such + * as did-method-key and did-veres-one. (Exposes a `.method` property, + * and a `.get()` function.) + */ + setDidResolver(didResolver) { + this.setProtocolHandler({protocol: 'did', handler: didResolver}); + } + + async documentLoader(url) { + if(!_isString(url)) { + throw new TypeError('The "url" parameter must be a string.'); + } + let document; + + // First, check in the static document list + document = this.documents.get(url); + + // if static document was found, use `static` tag + let tag; + if(document) { + tag = 'static'; + } + + if(!document) { + const [protocol] = url.split(':'); + // Check if this protocol has a custom handler installed + if(this.protocolHandlers.has(protocol)) { + document = await this.protocolHandlers.get(protocol).get({url}); + } + } + + if(document) { + const result = { + contextUrl: null, + document, + documentUrl: url + }; + // include `tag` if set + if(tag) { + result.tag = tag; + } + return result; + } + throw new Error(`Document not found in document loader: ${url}`); + } + + /** + * Returns the self-contained `documentLoader` function for passing to various + * json-ld libraries. + * + * @example + * import {JsonLdDocumentLoader} from 'jsonld-document-loader'; + * const jdl = new JsonLdDocumentLoader(); + * jdl.addSatic(MY_URL, MY_CONTEXT); + * const doucmentLoader = jdl.build(); + * + * @returns {Function} + */ + build() { + return this.documentLoader.bind(this); + } +} + +function _isString(arg) { + return typeof (arg) === 'string'; +} +function _isObject(arg) { + return typeof (arg) === 'object' && arg !== null; +} + +module.exports = JsonLdDocumentLoader; + + +/***/ }, + +/***/ "./node_modules/jsonld-document-loader/lib/index.js" +/*!**********************************************************!*\ + !*** ./node_modules/jsonld-document-loader/lib/index.js ***! + \**********************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2019-2021 Digital Bazaar, Inc. All rights reserved. + */ + + +exports.JsonLdDocumentLoader = __webpack_require__(/*! ./JsonLdDocumentLoader */ "./node_modules/jsonld-document-loader/lib/JsonLdDocumentLoader.js"); + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/ProofSet.js" +/*!********************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/ProofSet.js ***! + \********************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2018-2022 Digital Bazaar, Inc. All rights reserved. + */ + + +const constants = __webpack_require__(/*! ./constants */ "./node_modules/jsonld-signatures/lib/constants.js"); +const jsonld = __webpack_require__(/*! jsonld */ "./node_modules/jsonld/lib/jsonld.js"); +const {extendContextLoader, strictDocumentLoader} = __webpack_require__(/*! ./documentLoader */ "./node_modules/jsonld-signatures/lib/documentLoader.js"); +const {serializeError} = __webpack_require__(/*! serialize-error */ "./node_modules/serialize-error/index.js"); + +module.exports = class ProofSet { + /** + * Adds a Linked Data proof to a document. If the document contains other + * proofs, the new proof will be appended to the existing set of proofs. + * + * Important note: This method assumes that the term `proof` in the given + * document has the same definition as the `https://w3id.org/security/v2` + * JSON-LD @context. + * + * @param document {object} - JSON-LD Document to be signed. + * @param options {object} Options hashmap. + * + * A `suite` option is required: + * + * @param options.suite {LinkedDataSignature} a signature suite instance + * that will create the proof. + * + * A `purpose` option is required: + * + * @param options.purpose {ProofPurpose} a proof purpose instance that will + * augment the proof with information describing its intended purpose. + * + * Advanced optional parameters and overrides: + * + * @param [documentLoader] {function} a custom document loader, + * `Promise documentLoader(url)`. + * + * @return {Promise} resolves with the signed document, with + * the signature in the top-level `proof` property. + */ + async add(document, {suite, purpose, documentLoader} = {}) { + if(!suite) { + throw new TypeError('"options.suite" is required.'); + } + if(!purpose) { + throw new TypeError('"options.purpose" is required.'); + } + + if(documentLoader) { + documentLoader = extendContextLoader(documentLoader); + } else { + documentLoader = strictDocumentLoader; + } + + // shallow copy document to allow removal of existing proofs + const input = {...document}; + delete input.proof; + + // get existing proof set, if any + const proofSet = _getProofs({document}); + + // create the new proof + const proof = await suite.createProof({ + document: input, purpose, proofSet, documentLoader + }); + + jsonld.addValue(document, 'proof', proof); + + return document; + } + + /** + * Derives a new Linked Data document with a new `proof` from an existing + * document with an existing proof set. + * + * Important note: This method assumes that the term `proof` in the given + * document has the same definition as the `https://w3id.org/security/v2` + * JSON-LD @context. + * + * @param document {object} - JSON-LD Document from which to derive a proof. + * @param options {object} Options hashmap. + * + * A `suite` option is required: + * + * @param options.suite {LinkedDataSignature} a signature suite instance + * that will derive the new document and new `proof`. + * + * A `purpose` option is required: + * + * @param options.purpose {ProofPurpose} a proof purpose instance that will + * augment the proof with information describing its intended purpose. + * + * Advanced optional parameters and overrides: + * + * @param [documentLoader] {function} a custom document loader, + * `Promise documentLoader(url)`. + * + * @return {Promise} resolves with the new document, with a new + * top-level `proof` property. + */ + async derive(document, {suite, purpose, documentLoader} = {}) { + if(!suite) { + throw new TypeError('"options.suite" is required.'); + } + if(!purpose) { + throw new TypeError('"options.purpose" is required.'); + } + + if(documentLoader) { + documentLoader = extendContextLoader(documentLoader); + } else { + documentLoader = strictDocumentLoader; + } + + // shallow copy document to allow removal of existing proofs + const input = {...document}; + delete input.proof; + + // get existing proof set, if any + const proofSet = _getProofs({document}); + + // create the new document and proof + const newDocument = await suite.derive({ + document: input, purpose, proofSet, documentLoader + }); + + return newDocument; + } + + /** + * Verifies Linked Data proof(s) on a document. The proofs to be verified + * must match the given proof purpose. + * + * Important note: This method assumes that the term `proof` in the given + * document has the same definition as the `https://w3id.org/security/v2` + * JSON-LD @context. + * + * @param {object} document - The JSON-LD document with one or more proofs to + * be verified. + * + * @param {LinkedDataSignature|LinkedDataSignature[]} suite - + * Acceptable signature suite instances for verifying the proof(s). + * + * @param {ProofPurpose} purpose - A proof purpose instance that will + * match proofs to be verified and ensure they were created according to + * the appropriate purpose. + * + * Advanced optional parameters and overrides: + * + * @param {function} [documentLoader] a custom document loader, + * `Promise documentLoader(url)`. + * + * @return {Promise<{verified: boolean, results: Array, error: *}>} resolves + * with an object with a `verified`boolean property that is `true` if at + * least one proof matching the given purpose and suite verifies and `false` + * otherwise; a `results` property with an array of detailed results; + * if `false` an `error` property will be present. + */ + async verify(document, {suite, purpose, documentLoader} = {}) { + if(!suite) { + throw new TypeError('"options.suite" is required.'); + } + if(!purpose) { + throw new TypeError('"options.purpose" is required.'); + } + const suites = Array.isArray(suite) ? suite : [suite]; + if(suites.length === 0) { + throw new TypeError('At least one suite is required.'); + } + + if(documentLoader) { + documentLoader = extendContextLoader(documentLoader); + } else { + documentLoader = strictDocumentLoader; + } + + try { + // shallow copy to allow for removal of proof set prior to canonize + document = {...document}; + + // get proofs from document + const proofSet = _getProofs({document}); + if(proofSet.length === 0) { + // no possible matches + throw new Error('No matching proofs found in the given document.'); + } + // clear proofs from shallow copy + delete document.proof; + + // verify proofs + const results = await _verify( + {document, suites, proofSet, purpose, documentLoader}); + if(results.length === 0) { + const error = new Error( + 'Did not verify any proofs; insufficient proofs matched the ' + + 'acceptable suite(s) and required purpose(s).'); + error.name = 'NotFoundError'; + throw error; + } + + // combine results + const verified = results.some(r => r.verified); + if(!verified) { + const errors = [].concat( + ...results.filter(r => r.error).map(r => r.error)); + const result = {verified, results}; + if(errors.length > 0) { + result.error = errors; + } + return result; + } + return {verified, results}; + } catch(error) { + _makeSerializable(error); + return {verified: false, error}; + } + } +}; + +function _getProofs({document}) { + // handle document preprocessing to find proofs + let proofSet; + proofSet = jsonld.getValues(document, 'proof'); + + // shallow copy proofs and add document context or SECURITY_CONTEXT_URL + const context = document['@context'] || constants.SECURITY_CONTEXT_URL; + proofSet = proofSet.map(proof => { + const {cryptosuite} = proof; + // JCS Data Integrity Suites require unmodified proofs + if(cryptosuite?.includes?.('-jcs-')) { + return proof; + } + return {'@context': context, ...proof}; + }); + + return proofSet; +} + +async function _verify({ + document, suites, proofSet, purpose, documentLoader +}) { + // map each purpose to at least one proof to verify + const purposes = Array.isArray(purpose) ? purpose : [purpose]; + const purposeToProofs = new Map(); + const proofToSuite = new Map(); + const suiteMatchQueue = new Map(); + await Promise.all(purposes.map(purpose => _matchProofSet({ + purposeToProofs, proofToSuite, purpose, proofSet, suites, + suiteMatchQueue, document, documentLoader + }))); + + // every purpose must have at least one matching proof or verify will fail + if(purposeToProofs.size < purposes.length) { + // insufficient proofs to verify, so don't bother verifying any + return []; + } + + // verify every proof in `proofToSuite`; these proofs matched a purpose + const verifyResults = new Map(); + await Promise.all([...proofToSuite.entries()].map(async ([proof, suite]) => { + let result; + try { + // create backwards-compatible deferred proof purpose to capture + // verification method from old-style suites + let vm; + const purpose = { + async validate(proof, {verificationMethod}) { + vm = verificationMethod; + return {valid: true}; + } + }; + const {verified, verificationMethod, error} = await suite.verifyProof( + {proof, document, purpose, proofSet, documentLoader}); + if(!vm) { + vm = verificationMethod; + } + result = {proof, verified, verificationMethod: vm, error}; + } catch(error) { + result = {proof, verified: false, error}; + } + + if(result.error) { + // ensure error is serializable + _makeSerializable(result.error); + } + + verifyResults.set(proof, result); + })); + + // validate proof against each purpose that matched it + await Promise.all([...purposeToProofs.entries()].map( + async ([purpose, proofs]) => { + for(const proof of proofs) { + const result = verifyResults.get(proof); + if(!result.verified) { + // if proof was not verified, so not bother validating purpose + continue; + } + + // validate purpose + const {verificationMethod} = result; + const suite = proofToSuite.get(proof); + let purposeResult; + try { + purposeResult = await purpose.validate(proof, { + document, suite, verificationMethod, documentLoader + }); + } catch(error) { + purposeResult = {valid: false, error}; + } + + // add `purposeResult` to verification result regardless of validity + // to ensure that all purposes are represented + if(result.purposeResult) { + if(Array.isArray(result.purposeResult)) { + result.purposeResult.push(purposeResult); + } else { + result.purposeResult = [result.purposeResult, purposeResult]; + } + } else { + result.purposeResult = purposeResult; + } + + if(!purposeResult.valid) { + // ensure error is serializable + _makeSerializable(purposeResult.error); + + // if no top level error set yet, set it + if(!result.error) { + result.verified = false; + result.error = purposeResult.error; + } + } + } + })); + + return [...verifyResults.values()]; +} + +// add a `toJSON` method to an error which allows for errors in validation +// reports to be serialized properly by `JSON.stringify`. +function _makeSerializable(error) { + Object.defineProperty(error, 'toJSON', { + value: function() { + return serializeError(this); + }, + configurable: true, + writable: true + }); +} + +async function _matchProofSet({ + purposeToProofs, proofToSuite, purpose, proofSet, suites, + suiteMatchQueue, document, documentLoader +}) { + for(const proof of proofSet) { + // first check if the proof matches the purpose; if it doesn't continue + if(!await purpose.match(proof, {document, documentLoader})) { + continue; + } + + // next, find the suite that can verify the proof; if found, `matched` + // will be set to `true` and the proof will be added to `purposeToProofs` + // and `proofToSuite` to be processed -- otherwise it will not be; if + // no proofs are added for a given purpose, an exception will be thrown + let matched = false; + for(const s of suites) { + // `matchingProofs` is a map of promises that resolve to whether a + // proof matches a suite; multiple purposes and suites may be checked + // in parallel so a promise queue is used to prevent duplicate work + let matchingProofs = suiteMatchQueue.get(s); + if(!matchingProofs) { + suiteMatchQueue.set(s, matchingProofs = new Map()); + } + let promise = matchingProofs.get(proof); + if(!promise) { + promise = s.matchProof({proof, document, documentLoader}); + matchingProofs.set(proof, promise); + } + if(await promise) { + // found the matching suite for the proof; there should only be one + // suite that can verify a particular proof; add the proof to the + // map of proofs to be verified along with the matching suite + matched = true; + proofToSuite.set(proof, s); + break; + } + } + + if(matched) { + // note proof was a match for the purpose and an acceptable suite; it + // will need to be verified by the suite and then validated against the + // purpose + const matches = purposeToProofs.get(purpose); + if(matches) { + matches.push(proof); + } else { + purposeToProofs.set(purpose, [proof]); + } + } + } +} + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/VerificationError.js" +/*!*****************************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/VerificationError.js ***! + \*****************************************************************/ +(module) { + +"use strict"; +/*! + * Copyright (c) 2020 Digital Bazaar, Inc. All rights reserved. + */ + + +/** + * Used as an umbrella wrapper around multiple verification errors. + */ +class VerificationError extends Error { + /** + * @param {Error|Error[]} errors + */ + constructor(errors) { + super('Verification error(s).'); + + this.name = 'VerificationError'; + this.errors = [].concat(errors); + } +} +module.exports = VerificationError; + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/constants.js" +/*!*********************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/constants.js ***! + \*********************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2017-2023 Digital Bazaar, Inc. All rights reserved. + */ + + +const { + constants: securityConstants +} = __webpack_require__(/*! @digitalbazaar/security-context */ "./node_modules/@digitalbazaar/security-context/dist/context.esm.js"); + +module.exports = { + SECURITY_CONTEXT_URL: securityConstants.SECURITY_CONTEXT_V2_URL, + SECURITY_CONTEXT_V1_URL: securityConstants.SECURITY_CONTEXT_V1_URL, + SECURITY_CONTEXT_V2_URL: securityConstants.SECURITY_CONTEXT_V2_URL, + SECURITY_PROOF_URL: 'https://w3id.org/security#proof', + SECURITY_SIGNATURE_URL: 'https://w3id.org/security#signature' +}; + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/contexts.js" +/*!********************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/contexts.js ***! + \********************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2017-2023 Digital Bazaar, Inc. All rights reserved. + */ + + +const constants = __webpack_require__(/*! ./constants */ "./node_modules/jsonld-signatures/lib/constants.js"); +const {contexts: securityContexts} = __webpack_require__(/*! @digitalbazaar/security-context */ "./node_modules/@digitalbazaar/security-context/dist/context.esm.js"); + +module.exports = new Map([ + [constants.SECURITY_CONTEXT_V1_URL, + securityContexts.get(constants.SECURITY_CONTEXT_V1_URL)], + [constants.SECURITY_CONTEXT_V2_URL, + securityContexts.get(constants.SECURITY_CONTEXT_V2_URL)] +]); + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/documentLoader.js" +/*!**************************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/documentLoader.js ***! + \**************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2018-2021 Digital Bazaar, Inc. All rights reserved. + */ + + +/*eslint max-len: ["error", { "ignoreComments": true }]*/ + +// load locally embedded contexts +const contexts = __webpack_require__(/*! ./contexts */ "./node_modules/jsonld-signatures/lib/contexts.js"); + +/** + * This is a utility module that provides a set of functions for using or + * extending jsonld-signature's built-in JSON-LD document loader. + * @see https://www.w3.org/TR/json-ld11-api/#loaddocumentcallback + */ +const api = {}; +module.exports = api; + +api.extendContextLoader = documentLoader => { + /** + * extendContextLoader extends another JSON-LD document loader. + * Given a document loader to extend, this method will return a + * new document loader that will first check for a URL in + * jsonld-signature's built-in context map and, if not found, + * it will fall back to using the passed document loader. + * This utility method can be used to ensure that any local, + * in-memory, immutable context documents provided by + * jsonld-signatures will be used prior to using another + * document loader to load other documents. + * + * @param {Function} documentLoader - A function that fetches a document. + * @see [node documentLoader example]{@link https://github.com/digitalbazaar/jsonld.js/blob/master/lib/documentLoaders/node.js} + * @see [xhr documentLoader example]{@link https://github.com/digitalbazaar/jsonld.js/blob/master/lib/documentLoaders/xhr.js} + * + * @returns {Function} A function that accepts a + * url then fetches a jsonld document. + */ + return async url => { + const context = contexts.get(url); + if(context !== undefined) { + return { + contextUrl: null, + documentUrl: url, + document: context, + tag: 'static' + }; + } + return documentLoader(url); + }; +}; + +api.strictDocumentLoader = api.extendContextLoader(url => { + /** + * strictDocumentLoader extends extendContextLoader. + * ensuring no network calls are made so the only documents + * available are the built-in contexts. + * @see documentLoader.extendContextLoader + * + * @param {string} url - A valid url to a jsonld context. + * + * @throws {Error} Always throws an error if the + * url is not in the context map + * (i.e., not a URL for a locally available context document). + * @return {Object} A JSON-LD RemoteDocument + * that is a copy of a locally available context. + */ + throw new Error(`${url} not found.`); +}); + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/jsonld-signatures.js" +/*!*****************************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/jsonld-signatures.js ***! + \*****************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2010-2023 Digital Bazaar, Inc. All rights reserved. + */ + + +/* Core API */ +const api = {}; +module.exports = api; + +/* API Constants */ +const constants = __webpack_require__(/*! ./constants */ "./node_modules/jsonld-signatures/lib/constants.js"); +Object.assign(api, constants); + +// TODO: support `ProofChain` +const ProofSet = __webpack_require__(/*! ./ProofSet */ "./node_modules/jsonld-signatures/lib/ProofSet.js"); +const VerificationError = __webpack_require__(/*! ./VerificationError */ "./node_modules/jsonld-signatures/lib/VerificationError.js"); + +/** + * Derives a proof from the provided document, resulting in a new document + * with a new `proof` on it as generated by the given cryptographic suite. + * + * @param {object} document - The JSON-LD document from which to derive a + * new proof. + * + * @param {object} options - Options hashmap. + * @param {LinkedDataSignature} options.suite - The linked data signature + * cryptographic suite, containing private key material, with which to sign + * the document. + * + * @param {ProofPurpose} purpose - A proof purpose instance that will + * match proofs to be verified and ensure they were created according to + * the appropriate purpose. + * + * @param {function} documentLoader - A secure document loader (it is + * recommended to use one that provides static known documents, instead of + * fetching from the web) for returning contexts, controller documents, keys, + * and other relevant URLs needed for the proof. + * + * Advanced optional parameters and overrides: + * + * @param {function} [options.expansionMap] - NOT SUPPORTED; do not use. + * @param {boolean} [options.addSuiteContext=true] - Toggles the default + * behavior of each signature suite enforcing the presence of its own + * `@context` (if it is not present, it's added to the context list). + * + * @returns {Promise} Resolves with signed document. + */ +api.derive = async function derive(document, { + suite, purpose, documentLoader, addSuiteContext = true +} = {}) { + if(typeof document !== 'object') { + throw new TypeError('The "document" parameter must be an object.'); + } + // Ensure document contains the signature suite specific context URL + // or throw an error (in case an advanced user overrides the + // `addSuiteContext` flag to false). + suite.ensureSuiteContext({document, addSuiteContext}); + + try { + return await new ProofSet().derive( + document, {suite, purpose, documentLoader}); + } catch(e) { + if(!documentLoader && e.name === 'jsonld.InvalidUrl') { + const {details: {url}} = e; + const err = new Error( + `A URL "${url}" could not be fetched; you need to pass ` + + '"documentLoader" or resolve the URL before calling "derive".'); + err.cause = e; + throw err; + } + throw e; + } +}; + +/** + * Cryptographically signs the provided document by adding a `proof` section, + * based on the provided suite and proof purpose. + * + * @param {object} document - The JSON-LD document to be signed. + * + * @param {object} options - Options hashmap. + * @param {LinkedDataSignature} options.suite - The linked data signature + * cryptographic suite with which to sign the document. + * + * @param {ProofPurpose} purpose - A proof purpose instance that will + * match proofs to be verified and ensure they were created according to + * the appropriate purpose. + * + * @param {function} documentLoader - A secure document loader (it is + * recommended to use one that provides static known documents, instead of + * fetching from the web) for returning contexts, controller documents, keys, + * and other relevant URLs needed for the proof. + * + * Advanced optional parameters and overrides: + * + * @param {function} [options.expansionMap] - NOT SUPPORTED; do not use. + * @param {boolean} [options.addSuiteContext=true] - Toggles the default + * behavior of each signature suite enforcing the presence of its own + * `@context` (if it is not present, it's added to the context list). + * + * @returns {Promise} Resolves with signed document. + */ +api.sign = async function sign(document, { + suite, purpose, documentLoader, expansionMap, addSuiteContext = true +} = {}) { + if(expansionMap) { + throw new Error('"expansionMap" not supported.'); + } + if(typeof document !== 'object') { + throw new TypeError('The "document" parameter must be an object.'); + } + // Ensure document contains the signature suite specific context URL + // or throw an error (in case an advanced user overrides the `addSuiteContext` + // flag to false). + suite.ensureSuiteContext({document, addSuiteContext}); + + try { + return await new ProofSet().add(document, {suite, purpose, documentLoader}); + } catch(e) { + if(!documentLoader && e.name === 'jsonld.InvalidUrl') { + const {details: {url}} = e; + const err = new Error( + `A URL "${url}" could not be fetched; you need to pass ` + + '"documentLoader" or resolve the URL before calling "sign".'); + err.cause = e; + throw err; + } + throw e; + } +}; + +/** + * Verifies the linked data signature on the provided document. + * + * @param {object} document - The JSON-LD document with one or more proofs to be + * verified. + * + * @param {object} options - The options to use. + * @param {LinkedDataSignature|LinkedDataSignature[]} options.suite - + * Acceptable signature suite instances for verifying the proof(s). + * + * @param {ProofPurpose} purpose - A proof purpose instance that will + * match proofs to be verified and ensure they were created according to + * the appropriate purpose. + * + * Advanced optional parameters and overrides: + * + * @param {function} [options.documentLoader] - A custom document loader, + * `Promise documentLoader(url)`. + * @param {function} [options.expansionMap] - NOT SUPPORTED; do not use. + * + * @return {Promise<{verified: boolean, results: Array, + * error: VerificationError}>} + * resolves with an object with a `verified` boolean property that is `true` + * if at least one proof matching the given purpose and suite verifies and + * `false` otherwise; a `results` property with an array of detailed results; + * if `false` an `error` property will be present, with `error.errors` + * containing all of the errors that occurred during the verification process. + */ +api.verify = async function verify(document, { + suite, purpose, documentLoader, expansionMap +} = {}) { + if(expansionMap) { + throw new Error('"expansionMap" not supported.'); + } + if(typeof document !== 'object') { + throw new TypeError('The "document" parameter must be an object.'); + } + const result = await new ProofSet().verify( + document, {suite, purpose, documentLoader}); + const {error} = result; + if(error) { + if(!documentLoader && error.name === 'jsonld.InvalidUrl') { + const {details: {url}} = error; + const urlError = new Error( + `A URL "${url}" could not be fetched; you need to pass ` + + '"documentLoader" or resolve the URL before calling "verify".'); + result.error = new VerificationError(urlError); + } else { + result.error = new VerificationError(error); + } + } + return result; +}; + +// expose suite classes +api.suites = (__webpack_require__(/*! ./suites */ "./node_modules/jsonld-signatures/lib/suites.js").suites); + +// expose ProofPurpose classes to enable extensions +api.purposes = (__webpack_require__(/*! ./purposes */ "./node_modules/jsonld-signatures/lib/purposes.js").purposes); + +// expose document loader helpers +Object.assign(api, __webpack_require__(/*! ./documentLoader */ "./node_modules/jsonld-signatures/lib/documentLoader.js")); + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/purposes.js" +/*!********************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/purposes.js ***! + \********************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2018 Digital Bazaar, Inc. All rights reserved. + */ + + +const api = {}; +module.exports = api; + +// TODO: only require dynamically as needed or according to build +api.purposes = { + AssertionProofPurpose: __webpack_require__(/*! ./purposes/AssertionProofPurpose */ "./node_modules/jsonld-signatures/lib/purposes/AssertionProofPurpose.js"), + AuthenticationProofPurpose: __webpack_require__(/*! ./purposes/AuthenticationProofPurpose */ "./node_modules/jsonld-signatures/lib/purposes/AuthenticationProofPurpose.js"), + ControllerProofPurpose: __webpack_require__(/*! ./purposes/ControllerProofPurpose */ "./node_modules/jsonld-signatures/lib/purposes/ControllerProofPurpose.js"), + ProofPurpose: __webpack_require__(/*! ./purposes/ProofPurpose */ "./node_modules/jsonld-signatures/lib/purposes/ProofPurpose.js") +}; + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/purposes/AssertionProofPurpose.js" +/*!******************************************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/purposes/AssertionProofPurpose.js ***! + \******************************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2018 Digital Bazaar, Inc. All rights reserved. + */ + + +const ControllerProofPurpose = __webpack_require__(/*! ./ControllerProofPurpose */ "./node_modules/jsonld-signatures/lib/purposes/ControllerProofPurpose.js"); + +module.exports = class AssertionProofPurpose extends ControllerProofPurpose { + constructor({ + term = 'assertionMethod', controller, + date, maxTimestampDelta = Infinity} = {}) { + super({term, controller, date, maxTimestampDelta}); + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/purposes/AuthenticationProofPurpose.js" +/*!***********************************************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/purposes/AuthenticationProofPurpose.js ***! + \***********************************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2018 Digital Bazaar, Inc. All rights reserved. + */ + + +const ControllerProofPurpose = __webpack_require__(/*! ./ControllerProofPurpose */ "./node_modules/jsonld-signatures/lib/purposes/ControllerProofPurpose.js"); + +module.exports = class AuthenticationProofPurpose extends + ControllerProofPurpose { + constructor({ + term = 'authentication', controller, + challenge, date, domain, maxTimestampDelta = Infinity} = {}) { + super({term, controller, date, maxTimestampDelta}); + if(typeof challenge !== 'string') { + throw new TypeError('"challenge" must be a string.'); + } + if(domain !== undefined && typeof domain !== 'string') { + throw new TypeError('"domain" must be a string.'); + } + this.challenge = challenge; + this.domain = domain; + } + + async validate(proof, {verificationMethod, documentLoader, expansionMap}) { + try { + // check challenge + if(proof.challenge !== this.challenge) { + throw new Error( + 'The challenge is not as expected; ' + + `challenge="${proof.challenge}", expected="${this.challenge}"`); + } + + // check domain + if(this.domain !== undefined) { + // `proof.domain` must equal `this.domain` OR if `proof.domain` is + // an array, the array must include `this.domain` as an element + const {domain} = proof; + if(!(domain === this.domain || + (Array.isArray(domain) && domain.includes(this.domain)))) { + throw new Error( + 'The domain is not as expected; ' + + `domain=${JSON.stringify(domain)}, ` + + `expected=${JSON.stringify(this.domain)}`); + } + } + + return super.validate( + proof, {verificationMethod, documentLoader, expansionMap}); + } catch(error) { + return {valid: false, error}; + } + } + + async update(proof, {document, suite, documentLoader, expansionMap}) { + proof = await super.update( + proof, {document, suite, documentLoader, expansionMap}); + proof.challenge = this.challenge; + if(this.domain !== undefined) { + proof.domain = this.domain; + } + return proof; + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/purposes/ControllerProofPurpose.js" +/*!*******************************************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/purposes/ControllerProofPurpose.js ***! + \*******************************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2018-2022 Digital Bazaar, Inc. All rights reserved. + */ + + +const constants = __webpack_require__(/*! ../constants */ "./node_modules/jsonld-signatures/lib/constants.js"); +const jsonld = __webpack_require__(/*! jsonld */ "./node_modules/jsonld/lib/jsonld.js"); +const ProofPurpose = __webpack_require__(/*! ./ProofPurpose */ "./node_modules/jsonld-signatures/lib/purposes/ProofPurpose.js"); + +// DID documents can be specially optimized +const DID_CONTEXT_V1 = 'https://www.w3.org/ns/did/v1'; +// verification relationship terms that are known to appear in DID documents +const DID_VR_TERMS = [ + 'assertionMethod', + 'authentication', + 'capabilityInvocation', + 'capabilityDelegation', + 'keyAgreement', + 'verificationMethod' +]; + +module.exports = class ControllerProofPurpose extends ProofPurpose { + /** + * Creates a proof purpose that will validate whether or not the verification + * method in a proof was authorized by its declared controller for the + * proof's purpose. + * + * @param term {string} the `proofPurpose` term, as defined in the + * SECURITY_CONTEXT_URL `@context` or a URI if not defined in such. + * @param [controller] {object} the description of the controller, if it + * is not to be dereferenced via a `documentLoader`. + * @param [date] {string or Date or integer} the expected date for + * the creation of the proof. + * @param [maxTimestampDelta] {integer} a maximum number of seconds that + * the date on the signature can deviate from, defaults to `Infinity`. + */ + constructor({term, controller, date, maxTimestampDelta = Infinity} = {}) { + super({term, date, maxTimestampDelta}); + if(controller !== undefined) { + if(typeof controller !== 'object') { + throw new TypeError('"controller" must be an object.'); + } + this.controller = controller; + } + this._termDefinedByDIDContext = DID_VR_TERMS.includes(term); + } + + /** + * Validates the purpose of a proof. This method is called during + * proof verification, after the proof value has been checked against the + * given verification method (e.g. in the case of a digital signature, the + * signature has been cryptographically verified against the public key). + * + * @param proof + * @param verificationMethod + * @param documentLoader + * @param expansionMap + * + * @throws {Error} If verification method not authorized by controller + * @throws {Error} If proof's created timestamp is out of range + * + * @returns {Promise<{valid: boolean, error: Error}>} + */ + async validate(proof, {verificationMethod, documentLoader, expansionMap}) { + try { + const result = await super.validate( + proof, {verificationMethod, documentLoader, expansionMap}); + if(!result.valid) { + throw result.error; + } + + const {id: verificationId} = verificationMethod; + if(typeof verificationId !== 'string') { + throw new Error( + `Verification method ID "${verificationMethod.id}" ` + + 'must be a string.'); + } + const {term, _termDefinedByDIDContext} = this; + + // if no `controller` specified, use verification method's + if(this.controller) { + result.controller = this.controller; + } else { + const {controller} = verificationMethod; + let controllerId; + if(controller) { + if(typeof controller === 'object') { + controllerId = controller.id; + } else if(typeof controller !== 'string') { + throw new TypeError( + '"controller" must be a string representing a URL.'); + } else { + controllerId = controller; + } + } + + // apply optimization to controller documents that are DID documents; + // if `term` is one of those defined by the DID context + let {document} = await documentLoader(controllerId); + const mustFrame = !(_termDefinedByDIDContext && + document['@context'] === DID_CONTEXT_V1 || + (Array.isArray(document['@context']) && + document['@context'][0] === DID_CONTEXT_V1)); + if(mustFrame) { + // Note: `expansionMap` is intentionally not passed; we can safely + // drop properties here and must allow for it + document = await jsonld.frame(document, { + '@context': constants.SECURITY_CONTEXT_URL, + id: controllerId, + // this term must be in the JSON-LD controller document or + // verification will fail + [term]: { + '@embed': '@never', + id: verificationId + } + }, {documentLoader, compactToRelative: false, safe: true}); + } + result.controller = document; + } + + const verificationMethods = jsonld.getValues(result.controller, term); + result.valid = verificationMethods.some(vm => + vm === verificationId || + (typeof vm === 'object' && vm.id === verificationId)); + if(!result.valid) { + throw new Error( + `Verification method "${verificationMethod.id}" not authorized ` + + `by controller for proof purpose "${this.term}".`); + } + return result; + } catch(error) { + return {valid: false, error}; + } + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/purposes/ProofPurpose.js" +/*!*********************************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/purposes/ProofPurpose.js ***! + \*********************************************************************/ +(module) { + +"use strict"; +/*! + * Copyright (c) 2018 Digital Bazaar, Inc. All rights reserved. + */ + + +module.exports = class ProofPurpose { + /** + * @param term {string} the `proofPurpose` term, as defined in the + * SECURITY_CONTEXT_URL `@context` or a URI if not defined in such. + * @param [date] {string or Date or integer} the expected date for + * the creation of the proof. + * @param [maxTimestampDelta] {integer} a maximum number of seconds that + * the date on the signature can deviate from, defaults to `Infinity`. + */ + constructor({term, date, maxTimestampDelta = Infinity} = {}) { + if(term === undefined) { + throw new Error('"term" is required.'); + } + if(maxTimestampDelta !== undefined && + typeof maxTimestampDelta !== 'number') { + throw new TypeError('"maxTimestampDelta" must be a number.'); + } + this.term = term; + if(date !== undefined) { + this.date = new Date(date); + if(isNaN(this.date)) { + throw TypeError(`"date" "${date}" is not a valid date.`); + } + } + this.maxTimestampDelta = maxTimestampDelta; + } + + /** + * Called to validate the purpose of a proof. This method is called during + * proof verification, after the proof value has been checked against the + * given verification method (e.g. in the case of a digital signature, the + * signature has been cryptographically verified against the public key). + * + * @param proof {object} the proof, in the `constants.SECURITY_CONTEXT_URL`, + * with the matching purpose to validate. + * + * @return {Promise} resolves to an object with `valid` and `error`. + */ + async validate( + proof, {/*document, suite, verificationMethod, + documentLoader,*/ expansionMap}) { + if(expansionMap) { + throw new Error('"expansionMap" not supported.'); + } + + try { + // check expiration + if(this.maxTimestampDelta !== Infinity) { + const expected = (this.date || new Date()).getTime(); + const delta = this.maxTimestampDelta * 1000; + const created = new Date(proof.created).getTime(); + // comparing this way handles NaN case where `created` is invalid + if(!(created >= (expected - delta) && created <= (expected + delta))) { + throw new Error('The proof\'s created timestamp is out of range.'); + } + } + return {valid: true}; + } catch(error) { + return {valid: false, error}; + } + } + + /** + * Called to update a proof when it is being created, adding any properties + * specific to this purpose. This method is called prior to the proof + * value being generated such that any properties added may be, for example, + * included in a digital signature value. + * + * @param proof {object} the proof, in the `constants.SECURITY_CONTEXT_URL` + * to update. + * + * @return {Promise} resolves to the proof instance (in the + * `constants.SECURITY_CONTEXT_URL`. + */ + async update(proof, {/*document, suite, documentLoader,*/ expansionMap}) { + if(expansionMap) { + throw new Error('"expansionMap" not supported.'); + } + proof.proofPurpose = this.term; + return proof; + } + + /** + * Determines if the given proof has a purpose that matches this instance, + * i.e. this ProofPurpose instance should be used to validate the given + * proof. + * + * @param proof {object} the proof to check. + * + * @return {Promise} `true` if there's a match, `false` if not. + */ + async match(proof, {/* document, documentLoader,*/ expansionMap}) { + if(expansionMap) { + throw new Error('"expansionMap" not supported.'); + } + return proof.proofPurpose === this.term; + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/sha256digest-browser.js" +/*!********************************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/sha256digest-browser.js ***! + \********************************************************************/ +(module) { + +"use strict"; +/* + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */ +/* eslint-env browser */ + +const crypto = self && (self.crypto || self.msCrypto); + +module.exports = { + /** + * Hashes a string of data using SHA-256. + * + * @param {string} string - the string to hash. + * + * @return {Uint8Array} the hash digest. + */ + async sha256digest({string}) { + const bytes = new TextEncoder().encode(string); + return new Uint8Array( + await crypto.subtle.digest('SHA-256', bytes) + ); + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/suites.js" +/*!******************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/suites.js ***! + \******************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2018 Digital Bazaar, Inc. All rights reserved. + */ + + +const api = {}; +module.exports = api; + +// TODO: only require dynamically as needed or according to build +api.suites = { + LinkedDataProof: __webpack_require__(/*! ./suites/LinkedDataProof */ "./node_modules/jsonld-signatures/lib/suites/LinkedDataProof.js"), + LinkedDataSignature: __webpack_require__(/*! ./suites/LinkedDataSignature */ "./node_modules/jsonld-signatures/lib/suites/LinkedDataSignature.js") +}; + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/suites/LinkedDataProof.js" +/*!**********************************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/suites/LinkedDataProof.js ***! + \**********************************************************************/ +(module) { + +"use strict"; +/*! + * Copyright (c) 2018-2023 Digital Bazaar, Inc. All rights reserved. + */ + + +module.exports = class LinkedDataProof { + constructor({type} = {}) { + if(typeof type !== 'string') { + throw new TypeError('A LinkedDataProof must have a "type".'); + } + this.type = type; + } + + /** + * @param {object} options - The options to use. + * @param {object} options.document - The document to be signed. + * @param {ProofPurpose} options.purpose - The proof purpose instance. + * @param {Array} options.proofSet - Any existing proof set. + * @param {function} options.documentLoader - The document loader to use. + * @param {function} options.expansionMap - NOT SUPPORTED; do not use. + * + * @returns {Promise} Resolves with the created proof object. + */ + async createProof({ + /* document, purpose, proofSet, documentLoader, expansionMap */ + }) { + throw new Error('"createProof" must be implemented in a derived class.'); + } + + /** + * @param {object} options - The options to use. + * @param {object} options.document - The document from which to derive + * a new document and proof. + * @param {ProofPurpose} options.purpose - The proof purpose instance. + * @param {Array} options.proofSet - Any existing proof set. + * @param {function} options.documentLoader - The document loader to use. + * + * @returns {Promise} Resolves with the new document with a new + * `proof` field. + */ + async derive({ + /* document, purpose, proofSet, documentLoader */ + }) { + throw new Error('"deriveProof" must be implemented in a derived class.'); + } + + /** + * @param {object} options - The options to use. + * @param {object} options.proof - The proof to be verified. + * @param {object} options.document - The document the proof applies to. + * @param {ProofPurpose} options.purpose - The proof purpose instance. + * @param {Array} options.proofSet - Any existing proof set. + * @param {function} options.documentLoader - The document loader to use. + * @param {function} options.expansionMap - NOT SUPPORTED; do not use. + * + * @returns {Promise<{object}>} Resolves with the verification result. + */ + async verifyProof({ + /* proof, document, purpose, proofSet, documentLoader, expansionMap */ + }) { + throw new Error('"verifyProof" must be implemented in a derived class.'); + } + + /** + * Checks whether a given proof exists in the document. + * + * @param {object} options - The options to use. + * @param {object} options.proof - The proof to match. + * + * @returns {Promise} Whether a match for the proof was found. + */ + async matchProof({ + proof /*, document, purpose, documentLoader, expansionMap */ + }) { + return proof.type === this.type; + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/suites/LinkedDataSignature.js" +/*!**************************************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/suites/LinkedDataSignature.js ***! + \**************************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2017-2024 Digital Bazaar, Inc. All rights reserved. + */ + + +const constants = __webpack_require__(/*! ../constants */ "./node_modules/jsonld-signatures/lib/constants.js"); +const jsonld = __webpack_require__(/*! jsonld */ "./node_modules/jsonld/lib/jsonld.js"); +const rdfCanonize = __webpack_require__(/*! rdf-canonize */ "./node_modules/rdf-canonize/index.js"); +const util = __webpack_require__(/*! ../util */ "./node_modules/jsonld-signatures/lib/util.js"); +const {sha256digest} = __webpack_require__(/*! ../sha256digest */ "./node_modules/jsonld-signatures/lib/sha256digest-browser.js"); +const LinkedDataProof = __webpack_require__(/*! ./LinkedDataProof */ "./node_modules/jsonld-signatures/lib/suites/LinkedDataProof.js"); + +module.exports = class LinkedDataSignature extends LinkedDataProof { + /** + * Parent class from which the various LinkDataSignature suites (such as + * `Ed25519Signature2020`) inherit. + * NOTE: Developers are never expected to use this class directly, but to + * only work with individual suites. + * + * @param {object} options - Options hashmap. + * @param {string} options.type - Suite name, provided by subclass. + * @typedef LDKeyPair + * @param {LDKeyPair} LDKeyClass - The crypto-ld key class that this suite + * will use to sign/verify signatures. Provided by subclass. Used + * during the `verifySignature` operation, to create an instance (containing + * a `verifier()` property) of a public key fetched via a `documentLoader`. + * + * @param {string} contextUrl - JSON-LD context URL that corresponds to this + * signature suite. Provided by subclass. Used for enforcing suite context + * during the `sign()` operation. + * + * For `sign()` operations, either a `key` OR a `signer` is required. + * For `verify()` operations, you can pass in a verifier (from KMS), or + * the public key will be fetched via documentLoader. + * + * @param {object} [options.key] - An optional key object (containing an + * `id` property, and either `signer` or `verifier`, depending on the + * intended operation. Useful for when the application is managing keys + * itself (when using a KMS, you never have access to the private key, + * and so should use the `signer` param instead). + * + * @param {{sign: Function, id: string}} [options.signer] - Signer object + * that has two properties: an async `sign()` method, and an `id`. This is + * useful when interfacing with a KMS (since you don't get access to the + * private key and its `signer`, the KMS client gives you only the signer + * object to use). + * + * @param {{verify: Function, id: string}} [options.verifier] - Verifier + * object that has two properties: an async `verify()` method, and an `id`. + * Useful when working with a KMS-provided verifier. + * + * Advanced optional parameters and overrides: + * + * @param {object} [options.proof] - A JSON-LD document with options to use + * for the `proof` node (e.g. any other custom fields can be provided here + * using a context different from security-v2). If not provided, this is + * constructed during signing. + * @param {string|Date} [options.date] - Signing date to use (otherwise + * defaults to `now()`). + * @param {boolean} [options.useNativeCanonize] - Whether to use a native + * canonize algorithm. + * @param {object} [options.canonizeOptions] - Options to pass to + * canonize algorithm. + */ + constructor({ + type, proof, LDKeyClass, date, key, signer, verifier, useNativeCanonize, + canonizeOptions, contextUrl + } = {}) { + super({type}); + this.LDKeyClass = LDKeyClass; + this.contextUrl = contextUrl; + this.proof = proof; + const vm = _processSignatureParams({key, signer, verifier}); + this.verificationMethod = vm.verificationMethod; + this.key = vm.key; + this.signer = vm.signer; + this.verifier = vm.verifier; + this.canonizeOptions = canonizeOptions; + if(date) { + this.date = new Date(date); + if(isNaN(this.date)) { + throw TypeError(`"date" "${date}" is not a valid date.`); + } + } + this.useNativeCanonize = useNativeCanonize; + this._hashCache = null; + } + + /** + * @param {object} options - The options to use. + * @param {object} options.document - The document to be signed. + * @param {ProofPurpose} options.purpose - The proof purpose instance. + * @param {Array} options.proofSet - Any existing proof set. + * @param {function} options.documentLoader - The document loader to use. + * @param {function} options.expansionMap - NOT SUPPORTED; do not use. + * + * @returns {Promise} Resolves with the created proof object. + */ + async createProof({ + document, purpose, proofSet, documentLoader, expansionMap + }) { + if(expansionMap) { + throw new Error('"expansionMap" not supported.'); + } + + // build proof (currently known as `signature options` in spec) + let proof; + if(this.proof) { + // shallow copy + proof = {...this.proof}; + } else { + // create proof JSON-LD document + proof = {}; + } + + // ensure proof type is set + proof.type = this.type; + + // set default `now` date if not given in `proof` or `options` + let date = this.date; + if(proof.created === undefined && date === undefined) { + date = new Date(); + } + + // ensure date is in string format + if(date && typeof date !== 'string') { + date = util.w3cDate(date); + } + + // add API overrides + if(date) { + proof.created = date; + } + + proof.verificationMethod = this.verificationMethod; + + // add any extensions to proof (mostly for legacy support) + proof = await this.updateProof( + {document, proof, proofSet, purpose, documentLoader}); + + // allow purpose to update the proof; the `proof` is in the + // SECURITY_CONTEXT_URL `@context` -- therefore the `purpose` must + // ensure any added fields are also represented in that same `@context` + proof = await purpose.update( + proof, {document, suite: this, documentLoader}); + + // create data to sign + const verifyData = await this.createVerifyData( + {document, proof, proofSet, documentLoader}); + + // sign data + proof = await this.sign({verifyData, document, proof, documentLoader}); + + return proof; + } + + /** + * @param {object} options - The options to use. + * @param {object} options.proof - The proof to be updated. + * @param {Array} options.proofSet - Any existing proof set. + * @param {function} options.expansionMap - NOT SUPPORTED; do not use. + * + * @returns {Promise} Resolves with the created proof object. + */ + async updateProof({proof, expansionMap}) { + if(expansionMap) { + throw new Error('"expansionMap" not supported.'); + } + // extending classes may do more + return proof; + } + + /** + * @param {object} options - The options to use. + * @param {object} options.proof - The proof to be verified. + * @param {object} options.document - The document the proof applies to. + * @param {ProofPurpose} options.purpose - The proof purpose instance. + * @param {Array} options.proofSet - Any existing proof set. + * @param {function} options.documentLoader - The document loader to use. + * @param {function} options.expansionMap - NOT SUPPORTED; do not use. + * + * @returns {Promise<{object}>} Resolves with the verification result. + */ + async verifyProof({proof, document, proofSet, documentLoader, expansionMap}) { + if(expansionMap) { + throw new Error('"expansionMap" not supported.'); + } + + try { + // create data to verify + const verifyData = await this.createVerifyData( + {document, proof, proofSet, documentLoader, expansionMap}); + + // fetch verification method + const verificationMethod = await this.getVerificationMethod( + {proof, document, documentLoader, expansionMap}); + + // verify signature on data + const verified = await this.verifySignature({ + verifyData, verificationMethod, document, proof, + documentLoader, expansionMap}); + if(!verified) { + throw new Error('Invalid signature.'); + } + + return {verified: true, verificationMethod}; + } catch(error) { + return {verified: false, error}; + } + } + + async canonize(input, {documentLoader, expansionMap, skipExpansion}) { + if(expansionMap) { + throw new Error('"expansionMap" not supported.'); + } + return _canonize(input, { + algorithm: 'RDFC-1.0', + // do not resolve any relative URLs or terms, throw errors instead + base: null, + format: 'application/n-quads', + documentLoader, + // throw errors if any values would be dropped due to missing + // definitions or relative URLs + safe: true, + skipExpansion, + useNative: this.useNativeCanonize, + ...this.canonizeOptions + }); + } + + async canonizeProof(proof, {document, documentLoader, expansionMap}) { + if(expansionMap) { + throw new Error('"expansionMap" not supported.'); + } + // `jws`,`signatureValue`,`proofValue` must not be included in the proof + // options + proof = { + '@context': document['@context'] || constants.SECURITY_CONTEXT_URL, + ...proof + }; + delete proof.jws; + delete proof.signatureValue; + delete proof.proofValue; + return this.canonize(proof, { + documentLoader, + expansionMap, + skipExpansion: false, + ...this.canonizeOptions + }); + } + + /** + * @param {object} options - The options to use. + * @param {object} options.document - The document to be signed/verified. + * @param {object} options.proof - The proof to be verified. + * @param {Array} options.proofSet - Any existing proof set. + * @param {function} options.documentLoader - The document loader to use. + * @param {function} options.expansionMap - NOT SUPPORTED; do not use. + * + * @returns {Promise<{Uint8Array}>}. + */ + async createVerifyData({document, proof, documentLoader, expansionMap}) { + if(expansionMap) { + throw new Error('"expansionMap" not supported.'); + } + // get cached document hash + let cachedDocHash; + const {_hashCache} = this; + if(_hashCache && _hashCache.document === document) { + cachedDocHash = _hashCache.hash; + } else { + this._hashCache = { + document, + // canonize and hash document + hash: cachedDocHash = + this.canonize(document, {documentLoader, expansionMap}) + .then(c14nDocument => sha256digest({string: c14nDocument})) + }; + } + + // await both c14n proof hash and c14n document hash + const [proofHash, docHash] = await Promise.all([ + // canonize and hash proof + this.canonizeProof( + proof, {document, documentLoader, expansionMap}) + .then(c14nProofOptions => sha256digest({string: c14nProofOptions})), + cachedDocHash + ]); + + // concatenate hash of c14n proof options and hash of c14n document + return util.concat(proofHash, docHash); + } + + /** + * @param verifyData {Uint8Array}. + * @param document {object} document from which to derive a new document + * and proof. + * @param proof {object} + * @param proofSet {Array} + * @param documentLoader {function} + * + * @returns {Promise<{object}>} The new document with `proof`. + */ + async derive() { + throw new Error('Must be implemented by a derived class.'); + } + + /** + * @param document {object} to be signed. + * @param proof {object} + * @param documentLoader {function} + */ + async getVerificationMethod({proof, documentLoader}) { + let {verificationMethod} = proof; + + if(typeof verificationMethod === 'object') { + verificationMethod = verificationMethod.id; + } + + if(!verificationMethod) { + throw new Error('No "verificationMethod" found in proof.'); + } + + // Note: `expansionMap` is intentionally not passed; we can safely drop + // properties here and must allow for it + const framed = await jsonld.frame(verificationMethod, { + '@context': constants.SECURITY_CONTEXT_URL, + '@embed': '@always', + id: verificationMethod + }, {documentLoader, compactToRelative: false, safe: true}); + if(!framed) { + throw new Error(`Verification method ${verificationMethod} not found.`); + } + + // ensure verification method has not been revoked + if(framed.revoked !== undefined) { + throw new Error('The verification method has been revoked.'); + } + + return framed; + } + + /** + * @param verifyData {Uint8Array}. + * @param document {object} to be signed. + * @param proof {object} + * @param documentLoader {function} + * @param expansionMap {function} + * + * @returns {Promise<{object}>} the proof containing the signature value. + */ + async sign() { + throw new Error('Must be implemented by a derived class.'); + } + + /** + * @param verifyData {Uint8Array}. + * @param verificationMethod {object}. + * @param document {object} to be signed. + * @param proof {object} + * @param documentLoader {function} + * @param expansionMap {function} + * + * @returns {Promise} + */ + async verifySignature() { + throw new Error('Must be implemented by a derived class.'); + } + + /** + * Ensures the document to be signed contains the required signature suite + * specific `@context`, by either adding it (if `addSuiteContext` is true), + * or throwing an error if it's missing. + * + * @param {object} options - Options hashmap. + * @param {object} options.document - JSON-LD document to be signed. + * @param {boolean} options.addSuiteContext - Add suite context? + */ + ensureSuiteContext({document, addSuiteContext}) { + const {contextUrl} = this; + + if(_includesContext({document, contextUrl})) { + // document already includes the required context + return; + } + + if(!addSuiteContext) { + throw new TypeError( + `The document to be signed must contain this suite's @context, ` + + `"${contextUrl}".`); + } + + // enforce the suite's context by adding it to the document + const existingContext = document['@context'] || []; + + document['@context'] = Array.isArray(existingContext) ? + [...existingContext, contextUrl] : [existingContext, contextUrl]; + } +}; + +/** + * Tests whether a provided JSON-LD document includes a context URL in its + * `@context` property. + * + * @param {object} options - Options hashmap. + * @param {object} options.document - A JSON-LD document. + * @param {string} options.contextUrl - A context URL. + * + * @returns {boolean} Returns true if document includes context. + */ +function _includesContext({document, contextUrl}) { + const context = document['@context']; + return context === contextUrl || + (Array.isArray(context) && context.includes(contextUrl)); +} + +/** + * See constructor docstring for param details. + * + * @returns {{verificationMethod: string, key: LDKeyPair, + * signer: {sign: Function, id: string}, + * verifier: {verify: Function, id: string}}} - Validated and initialized + * key-related parameters. + */ +function _processSignatureParams({key, signer, verifier}) { + // We are explicitly not requiring a key or signer/verifier param to be + // present, to support the verify() use case where the verificationMethod + // is being fetched by the documentLoader + + const vm = {}; + if(key) { + vm.key = key; + vm.verificationMethod = key.id; + if(typeof key.signer === 'function') { + vm.signer = key.signer(); + } + if(typeof key.verifier === 'function') { + vm.verifier = key.verifier(); + } + if(!(vm.signer || vm.verifier)) { + throw new TypeError( + 'The "key" parameter must contain a "signer" or "verifier" method.'); + } + } else { + vm.verificationMethod = (signer && signer.id) || + (verifier && verifier.id); + vm.signer = signer; + vm.verifier = verifier; + } + + if(vm.signer) { + if(typeof vm.signer.sign !== 'function') { + throw new TypeError('A signer API has not been specified.'); + } + } + if(vm.verifier) { + if(typeof vm.verifier.verify !== 'function') { + throw new TypeError('A verifier API has not been specified.'); + } + } + + return vm; +} + +async function _canonize(input, options) { + // convert to RDF dataset and do canonicalization + const opts = { + rdfDirection: 'i18n-datatype', ...options, produceGeneralizedRdf: false, + }; + delete opts.format; + const dataset = await jsonld.toRDF(input, opts); + return rdfCanonize.canonize(dataset, options); +} + + +/***/ }, + +/***/ "./node_modules/jsonld-signatures/lib/util.js" +/*!****************************************************!*\ + !*** ./node_modules/jsonld-signatures/lib/util.js ***! + \****************************************************/ +(module) { + +"use strict"; +/* + * Copyright (c) 2017-2021 Digital Bazaar, Inc. All rights reserved. + */ + + +const api = {}; +module.exports = api; + +/** + * Converts the given date into W3C datetime format (eg: 2011-03-09T21:55:41Z). + * + * @param date the date to convert. + * + * @return the date in W3C datetime format. + */ +api.w3cDate = date => { + if(date === undefined || date === null) { + date = new Date(); + } else if(typeof date === 'number' || typeof date === 'string') { + date = new Date(date); + } + const str = date.toISOString(); + return str.substr(0, str.length - 5) + 'Z'; +}; + +/** + * Concatenates two Uint8Arrays. + * + * @param b1 {Uint8Array}. + * @param b2 {Uint8Array}. + * + * @return {Uint8Array} the result. + */ +api.concat = (b1, b2) => { + const rval = new Uint8Array(b1.length + b2.length); + rval.set(b1, 0); + rval.set(b2, b1.length); + return rval; +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/ContextResolver.js" +/*!****************************************************!*\ + !*** ./node_modules/jsonld/lib/ContextResolver.js ***! + \****************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2019 Digital Bazaar, Inc. All rights reserved. + */ + + +const { + isArray: _isArray, + isObject: _isObject, + isString: _isString, +} = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); +const { + asArray: _asArray +} = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); +const {prependBase} = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); +const ResolvedContext = __webpack_require__(/*! ./ResolvedContext */ "./node_modules/jsonld/lib/ResolvedContext.js"); + +const MAX_CONTEXT_URLS = 10; + +module.exports = class ContextResolver { + /** + * Creates a ContextResolver. + * + * @param sharedCache a shared LRU cache with `get` and `set` APIs. + */ + constructor({sharedCache}) { + this.perOpCache = new Map(); + this.sharedCache = sharedCache; + } + + async resolve({ + activeCtx, context, documentLoader, base, cycles = new Set() + }) { + // process `@context` + if(context && _isObject(context) && context['@context']) { + context = context['@context']; + } + + // context is one or more contexts + context = _asArray(context); + + // resolve each context in the array + const allResolved = []; + for(const ctx of context) { + if(_isString(ctx)) { + // see if `ctx` has been resolved before... + let resolved = this._get(ctx); + if(!resolved) { + // not resolved yet, resolve + resolved = await this._resolveRemoteContext( + {activeCtx, url: ctx, documentLoader, base, cycles}); + } + + // add to output and continue + if(_isArray(resolved)) { + allResolved.push(...resolved); + } else { + allResolved.push(resolved); + } + continue; + } + if(ctx === null) { + // handle `null` context, nothing to cache + allResolved.push(new ResolvedContext({document: null})); + continue; + } + if(!_isObject(ctx)) { + _throwInvalidLocalContext(context); + } + // context is an object, get/create `ResolvedContext` for it + const key = JSON.stringify(ctx); + let resolved = this._get(key); + if(!resolved) { + // create a new static `ResolvedContext` and cache it + resolved = new ResolvedContext({document: ctx}); + this._cacheResolvedContext({key, resolved, tag: 'static'}); + } + allResolved.push(resolved); + } + + return allResolved; + } + + _get(key) { + // get key from per operation cache; no `tag` is used with this cache so + // any retrieved context will always be the same during a single operation + let resolved = this.perOpCache.get(key); + if(!resolved) { + // see if the shared cache has a `static` entry for this URL + const tagMap = this.sharedCache.get(key); + if(tagMap) { + resolved = tagMap.get('static'); + if(resolved) { + this.perOpCache.set(key, resolved); + } + } + } + return resolved; + } + + _cacheResolvedContext({key, resolved, tag}) { + this.perOpCache.set(key, resolved); + if(tag !== undefined) { + let tagMap = this.sharedCache.get(key); + if(!tagMap) { + tagMap = new Map(); + this.sharedCache.set(key, tagMap); + } + tagMap.set(tag, resolved); + } + return resolved; + } + + async _resolveRemoteContext({activeCtx, url, documentLoader, base, cycles}) { + // resolve relative URL and fetch context + url = prependBase(base, url); + const {context, remoteDoc} = await this._fetchContext( + {activeCtx, url, documentLoader, cycles}); + + // update base according to remote document and resolve any relative URLs + base = remoteDoc.documentUrl || url; + _resolveContextUrls({context, base}); + + // resolve, cache, and return context + const resolved = await this.resolve( + {activeCtx, context, documentLoader, base, cycles}); + this._cacheResolvedContext({key: url, resolved, tag: remoteDoc.tag}); + return resolved; + } + + async _fetchContext({activeCtx, url, documentLoader, cycles}) { + // check for max context URLs fetched during a resolve operation + if(cycles.size > MAX_CONTEXT_URLS) { + throw new JsonLdError( + 'Maximum number of @context URLs exceeded.', + 'jsonld.ContextUrlError', + { + code: activeCtx.processingMode === 'json-ld-1.0' ? + 'loading remote context failed' : + 'context overflow', + max: MAX_CONTEXT_URLS + }); + } + + // check for context URL cycle + // shortcut to avoid extra work that would eventually hit the max above + if(cycles.has(url)) { + throw new JsonLdError( + 'Cyclical @context URLs detected.', + 'jsonld.ContextUrlError', + { + code: activeCtx.processingMode === 'json-ld-1.0' ? + 'recursive context inclusion' : + 'context overflow', + url + }); + } + + // track cycles + cycles.add(url); + + let context; + let remoteDoc; + + try { + remoteDoc = await documentLoader(url); + context = remoteDoc.document || null; + // parse string context as JSON + if(_isString(context)) { + context = JSON.parse(context); + } + } catch(e) { + throw new JsonLdError( + 'Dereferencing a URL did not result in a valid JSON-LD object. ' + + 'Possible causes are an inaccessible URL perhaps due to ' + + 'a same-origin policy (ensure the server uses CORS if you are ' + + 'using client-side JavaScript), too many redirects, a ' + + 'non-JSON response, or more than one HTTP Link Header was ' + + 'provided for a remote context. ' + + `URL: "${url}".`, + 'jsonld.InvalidUrl', + {code: 'loading remote context failed', url, cause: e}); + } + + // ensure ctx is an object + if(!_isObject(context)) { + throw new JsonLdError( + 'Dereferencing a URL did not result in a JSON object. The ' + + 'response was valid JSON, but it was not a JSON object. ' + + `URL: "${url}".`, + 'jsonld.InvalidUrl', {code: 'invalid remote context', url}); + } + + // use empty context if no @context key is present + if(!('@context' in context)) { + context = {'@context': {}}; + } else { + context = {'@context': context['@context']}; + } + + // append @context URL to context if given + if(remoteDoc.contextUrl) { + if(!_isArray(context['@context'])) { + context['@context'] = [context['@context']]; + } + context['@context'].push(remoteDoc.contextUrl); + } + + return {context, remoteDoc}; + } +}; + +function _throwInvalidLocalContext(ctx) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context must be an object.', + 'jsonld.SyntaxError', { + code: 'invalid local context', context: ctx + }); +} + +/** + * Resolve all relative `@context` URLs in the given context by inline + * replacing them with absolute URLs. + * + * @param context the context. + * @param base the base IRI to use to resolve relative IRIs. + */ +function _resolveContextUrls({context, base}) { + if(!context) { + return; + } + + const ctx = context['@context']; + + if(_isString(ctx)) { + context['@context'] = prependBase(base, ctx); + return; + } + + if(_isArray(ctx)) { + for(let i = 0; i < ctx.length; ++i) { + const element = ctx[i]; + if(_isString(element)) { + ctx[i] = prependBase(base, element); + continue; + } + if(_isObject(element)) { + _resolveContextUrls({context: {'@context': element}, base}); + } + } + return; + } + + if(!_isObject(ctx)) { + // no @context URLs can be found in non-object + return; + } + + // ctx is an object, resolve any context URLs in terms + for(const term in ctx) { + _resolveContextUrls({context: ctx[term], base}); + } +} + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/JsonLdError.js" +/*!************************************************!*\ + !*** ./node_modules/jsonld/lib/JsonLdError.js ***! + \************************************************/ +(module) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +module.exports = class JsonLdError extends Error { + /** + * Creates a JSON-LD Error. + * + * @param msg the error message. + * @param type the error type. + * @param details the error details. + */ + constructor( + message = 'An unspecified JSON-LD error occurred.', + name = 'jsonld.Error', + details = {}) { + super(message); + this.name = name; + this.message = message; + this.details = details; + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/JsonLdProcessor.js" +/*!****************************************************!*\ + !*** ./node_modules/jsonld/lib/JsonLdProcessor.js ***! + \****************************************************/ +(module) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +module.exports = jsonld => { + class JsonLdProcessor { + toString() { + return '[object JsonLdProcessor]'; + } + } + Object.defineProperty(JsonLdProcessor, 'prototype', { + writable: false, + enumerable: false + }); + Object.defineProperty(JsonLdProcessor.prototype, 'constructor', { + writable: true, + enumerable: false, + configurable: true, + value: JsonLdProcessor + }); + + // The Web IDL test harness will check the number of parameters defined in + // the functions below. The number of parameters must exactly match the + // required (non-optional) parameters of the JsonLdProcessor interface as + // defined here: + // https://www.w3.org/TR/json-ld-api/#the-jsonldprocessor-interface + + JsonLdProcessor.compact = function(input, ctx) { + if(arguments.length < 2) { + return Promise.reject( + new TypeError('Could not compact, too few arguments.')); + } + return jsonld.compact(input, ctx); + }; + JsonLdProcessor.expand = function(input) { + if(arguments.length < 1) { + return Promise.reject( + new TypeError('Could not expand, too few arguments.')); + } + return jsonld.expand(input); + }; + JsonLdProcessor.flatten = function(input) { + if(arguments.length < 1) { + return Promise.reject( + new TypeError('Could not flatten, too few arguments.')); + } + return jsonld.flatten(input); + }; + + return JsonLdProcessor; +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/NQuads.js" +/*!*******************************************!*\ + !*** ./node_modules/jsonld/lib/NQuads.js ***! + \*******************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +// TODO: move `NQuads` to its own package +module.exports = __webpack_require__(/*! rdf-canonize */ "./node_modules/jsonld/node_modules/rdf-canonize/index.js").NQuads; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/RequestQueue.js" +/*!*************************************************!*\ + !*** ./node_modules/jsonld/lib/RequestQueue.js ***! + \*************************************************/ +(module) { + +"use strict"; +/* + * Copyright (c) 2017-2019 Digital Bazaar, Inc. All rights reserved. + */ + + +module.exports = class RequestQueue { + /** + * Creates a simple queue for requesting documents. + */ + constructor() { + this._requests = {}; + } + + wrapLoader(loader) { + const self = this; + self._loader = loader; + return function(/* url */) { + return self.add.apply(self, arguments); + }; + } + + async add(url) { + let promise = this._requests[url]; + if(promise) { + // URL already queued, wait for it to load + return Promise.resolve(promise); + } + + // queue URL and load it + promise = this._requests[url] = this._loader(url); + + try { + return await promise; + } finally { + delete this._requests[url]; + } + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/ResolvedContext.js" +/*!****************************************************!*\ + !*** ./node_modules/jsonld/lib/ResolvedContext.js ***! + \****************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2019 Digital Bazaar, Inc. All rights reserved. + */ + + +const LRU = __webpack_require__(/*! lru-cache */ "./node_modules/lru-cache/index.js"); + +const MAX_ACTIVE_CONTEXTS = 10; + +module.exports = class ResolvedContext { + /** + * Creates a ResolvedContext. + * + * @param document the context document. + */ + constructor({document}) { + this.document = document; + // TODO: enable customization of processed context cache + // TODO: limit based on size of processed contexts vs. number of them + this.cache = new LRU({max: MAX_ACTIVE_CONTEXTS}); + } + + getProcessed(activeCtx) { + return this.cache.get(activeCtx); + } + + setProcessed(activeCtx, processedCtx) { + this.cache.set(activeCtx, processedCtx); + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/compact.js" +/*!********************************************!*\ + !*** ./node_modules/jsonld/lib/compact.js ***! + \********************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); + +const { + isArray: _isArray, + isObject: _isObject, + isString: _isString, + isUndefined: _isUndefined +} = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const { + isList: _isList, + isValue: _isValue, + isGraph: _isGraph, + isSimpleGraph: _isSimpleGraph, + isSubjectReference: _isSubjectReference +} = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); + +const { + expandIri: _expandIri, + getContextValue: _getContextValue, + isKeyword: _isKeyword, + process: _processContext, + processingMode: _processingMode +} = __webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js"); + +const { + removeBase: _removeBase, + prependBase: _prependBase +} = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); + +const { + REGEX_KEYWORD, + addValue: _addValue, + asArray: _asArray, + compareShortestLeast: _compareShortestLeast +} = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); + +const api = {}; +module.exports = api; + +/** + * Recursively compacts an element using the given active context. All values + * must be in expanded form before this method is called. + * + * @param activeCtx the active context to use. + * @param activeProperty the compacted property associated with the element + * to compact, null for none. + * @param element the element to compact. + * @param options the compaction options. + * + * @return a promise that resolves to the compacted value. + */ +api.compact = async ({ + activeCtx, + activeProperty = null, + element, + options = {} +}) => { + // recursively compact array + if(_isArray(element)) { + let rval = []; + for(let i = 0; i < element.length; ++i) { + const compacted = await api.compact({ + activeCtx, + activeProperty, + element: element[i], + options + }); + if(compacted === null) { + // FIXME: need event? + continue; + } + rval.push(compacted); + } + if(options.compactArrays && rval.length === 1) { + // use single element if no container is specified + const container = _getContextValue( + activeCtx, activeProperty, '@container') || []; + if(container.length === 0) { + rval = rval[0]; + } + } + return rval; + } + + // use any scoped context on activeProperty + const ctx = _getContextValue(activeCtx, activeProperty, '@context'); + if(!_isUndefined(ctx)) { + activeCtx = await _processContext({ + activeCtx, + localCtx: ctx, + propagate: true, + overrideProtected: true, + options + }); + } + + // recursively compact object + if(_isObject(element)) { + if(options.link && '@id' in element && + options.link.hasOwnProperty(element['@id'])) { + // check for a linked element to reuse + const linked = options.link[element['@id']]; + for(let i = 0; i < linked.length; ++i) { + if(linked[i].expanded === element) { + return linked[i].compacted; + } + } + } + + // do value compaction on @values and subject references + if(_isValue(element) || _isSubjectReference(element)) { + const rval = + api.compactValue({activeCtx, activeProperty, value: element, options}); + if(options.link && _isSubjectReference(element)) { + // store linked element + if(!(options.link.hasOwnProperty(element['@id']))) { + options.link[element['@id']] = []; + } + options.link[element['@id']].push({expanded: element, compacted: rval}); + } + return rval; + } + + // if expanded property is @list and we're contained within a list + // container, recursively compact this item to an array + if(_isList(element)) { + const container = _getContextValue( + activeCtx, activeProperty, '@container') || []; + if(container.includes('@list')) { + return api.compact({ + activeCtx, + activeProperty, + element: element['@list'], + options + }); + } + } + + // FIXME: avoid misuse of active property as an expanded property? + const insideReverse = (activeProperty === '@reverse'); + + const rval = {}; + + // original context before applying property-scoped and local contexts + const inputCtx = activeCtx; + + // revert to previous context, if there is one, + // and element is not a value object or a node reference + if(!_isValue(element) && !_isSubjectReference(element)) { + activeCtx = activeCtx.revertToPreviousContext(); + } + + // apply property-scoped context after reverting term-scoped context + const propertyScopedCtx = + _getContextValue(inputCtx, activeProperty, '@context'); + if(!_isUndefined(propertyScopedCtx)) { + activeCtx = await _processContext({ + activeCtx, + localCtx: propertyScopedCtx, + propagate: true, + overrideProtected: true, + options + }); + } + + if(options.link && '@id' in element) { + // store linked element + if(!options.link.hasOwnProperty(element['@id'])) { + options.link[element['@id']] = []; + } + options.link[element['@id']].push({expanded: element, compacted: rval}); + } + + // apply any context defined on an alias of @type + // if key is @type and any compacted value is a term having a local + // context, overlay that context + let types = element['@type'] || []; + if(types.length > 1) { + types = Array.from(types).sort(); + } + // find all type-scoped contexts based on current context, prior to + // updating it + const typeContext = activeCtx; + for(const type of types) { + const compactedType = api.compactIri( + {activeCtx: typeContext, iri: type, relativeTo: {vocab: true}}); + + // Use any type-scoped context defined on this value + const ctx = _getContextValue(inputCtx, compactedType, '@context'); + if(!_isUndefined(ctx)) { + activeCtx = await _processContext({ + activeCtx, + localCtx: ctx, + options, + propagate: false + }); + } + } + + // process element keys in order + const keys = Object.keys(element).sort(); + for(const expandedProperty of keys) { + const expandedValue = element[expandedProperty]; + + // compact @id + if(expandedProperty === '@id') { + let compactedValue = _asArray(expandedValue).map( + expandedIri => api.compactIri({ + activeCtx, + iri: expandedIri, + relativeTo: {vocab: false}, + base: options.base + })); + if(compactedValue.length === 1) { + compactedValue = compactedValue[0]; + } + + // use keyword alias and add value + const alias = api.compactIri( + {activeCtx, iri: '@id', relativeTo: {vocab: true}}); + + rval[alias] = compactedValue; + continue; + } + + // compact @type(s) + if(expandedProperty === '@type') { + // resolve type values against previous context + let compactedValue = _asArray(expandedValue).map( + expandedIri => api.compactIri({ + activeCtx: inputCtx, + iri: expandedIri, + relativeTo: {vocab: true} + })); + if(compactedValue.length === 1) { + compactedValue = compactedValue[0]; + } + + // use keyword alias and add value + const alias = api.compactIri( + {activeCtx, iri: '@type', relativeTo: {vocab: true}}); + const container = _getContextValue( + activeCtx, alias, '@container') || []; + + // treat as array for @type if @container includes @set + const typeAsSet = + container.includes('@set') && + _processingMode(activeCtx, 1.1); + const isArray = + typeAsSet || (_isArray(compactedValue) && expandedValue.length === 0); + _addValue(rval, alias, compactedValue, {propertyIsArray: isArray}); + continue; + } + + // handle @reverse + if(expandedProperty === '@reverse') { + // recursively compact expanded value + const compactedValue = await api.compact({ + activeCtx, + activeProperty: '@reverse', + element: expandedValue, + options + }); + + // handle double-reversed properties + for(const compactedProperty in compactedValue) { + if(activeCtx.mappings.has(compactedProperty) && + activeCtx.mappings.get(compactedProperty).reverse) { + const value = compactedValue[compactedProperty]; + const container = _getContextValue( + activeCtx, compactedProperty, '@container') || []; + const useArray = ( + container.includes('@set') || !options.compactArrays); + _addValue( + rval, compactedProperty, value, {propertyIsArray: useArray}); + delete compactedValue[compactedProperty]; + } + } + + if(Object.keys(compactedValue).length > 0) { + // use keyword alias and add value + const alias = api.compactIri({ + activeCtx, + iri: expandedProperty, + relativeTo: {vocab: true} + }); + _addValue(rval, alias, compactedValue); + } + + continue; + } + + if(expandedProperty === '@preserve') { + // compact using activeProperty + const compactedValue = await api.compact({ + activeCtx, + activeProperty, + element: expandedValue, + options + }); + + if(!(_isArray(compactedValue) && compactedValue.length === 0)) { + _addValue(rval, expandedProperty, compactedValue); + } + continue; + } + + // handle @index property + if(expandedProperty === '@index') { + // drop @index if inside an @index container + const container = _getContextValue( + activeCtx, activeProperty, '@container') || []; + if(container.includes('@index')) { + continue; + } + + // use keyword alias and add value + const alias = api.compactIri({ + activeCtx, + iri: expandedProperty, + relativeTo: {vocab: true} + }); + _addValue(rval, alias, expandedValue); + continue; + } + + // skip array processing for keywords that aren't + // @graph, @list, or @included + if(expandedProperty !== '@graph' && expandedProperty !== '@list' && + expandedProperty !== '@included' && + _isKeyword(expandedProperty)) { + // use keyword alias and add value as is + const alias = api.compactIri({ + activeCtx, + iri: expandedProperty, + relativeTo: {vocab: true} + }); + _addValue(rval, alias, expandedValue); + continue; + } + + // Note: expanded value must be an array due to expansion algorithm. + if(!_isArray(expandedValue)) { + throw new JsonLdError( + 'JSON-LD expansion error; expanded value must be an array.', + 'jsonld.SyntaxError'); + } + + // preserve empty arrays + if(expandedValue.length === 0) { + const itemActiveProperty = api.compactIri({ + activeCtx, + iri: expandedProperty, + value: expandedValue, + relativeTo: {vocab: true}, + reverse: insideReverse + }); + const nestProperty = activeCtx.mappings.has(itemActiveProperty) ? + activeCtx.mappings.get(itemActiveProperty)['@nest'] : null; + let nestResult = rval; + if(nestProperty) { + _checkNestProperty(activeCtx, nestProperty, options); + if(!_isObject(rval[nestProperty])) { + rval[nestProperty] = {}; + } + nestResult = rval[nestProperty]; + } + _addValue( + nestResult, itemActiveProperty, expandedValue, { + propertyIsArray: true + }); + } + + // recusively process array values + for(const expandedItem of expandedValue) { + // compact property and get container type + const itemActiveProperty = api.compactIri({ + activeCtx, + iri: expandedProperty, + value: expandedItem, + relativeTo: {vocab: true}, + reverse: insideReverse + }); + + // if itemActiveProperty is a @nest property, add values to nestResult, + // otherwise rval + const nestProperty = activeCtx.mappings.has(itemActiveProperty) ? + activeCtx.mappings.get(itemActiveProperty)['@nest'] : null; + let nestResult = rval; + if(nestProperty) { + _checkNestProperty(activeCtx, nestProperty, options); + if(!_isObject(rval[nestProperty])) { + rval[nestProperty] = {}; + } + nestResult = rval[nestProperty]; + } + + const container = _getContextValue( + activeCtx, itemActiveProperty, '@container') || []; + + // get simple @graph or @list value if appropriate + const isGraph = _isGraph(expandedItem); + const isList = _isList(expandedItem); + let inner; + if(isList) { + inner = expandedItem['@list']; + } else if(isGraph) { + inner = expandedItem['@graph']; + } + + // recursively compact expanded item + let compactedItem = await api.compact({ + activeCtx, + activeProperty: itemActiveProperty, + element: (isList || isGraph) ? inner : expandedItem, + options + }); + + // handle @list + if(isList) { + // ensure @list value is an array + if(!_isArray(compactedItem)) { + compactedItem = [compactedItem]; + } + + if(!container.includes('@list')) { + // wrap using @list alias + compactedItem = { + [api.compactIri({ + activeCtx, + iri: '@list', + relativeTo: {vocab: true} + })]: compactedItem + }; + + // include @index from expanded @list, if any + if('@index' in expandedItem) { + compactedItem[api.compactIri({ + activeCtx, + iri: '@index', + relativeTo: {vocab: true} + })] = expandedItem['@index']; + } + } else { + _addValue(nestResult, itemActiveProperty, compactedItem, { + valueIsArray: true, + allowDuplicate: true + }); + continue; + } + } + + // Graph object compaction cases + if(isGraph) { + if(container.includes('@graph') && (container.includes('@id') || + container.includes('@index') && _isSimpleGraph(expandedItem))) { + // get or create the map object + let mapObject; + if(nestResult.hasOwnProperty(itemActiveProperty)) { + mapObject = nestResult[itemActiveProperty]; + } else { + nestResult[itemActiveProperty] = mapObject = {}; + } + + // index on @id or @index or alias of @none + const key = (container.includes('@id') ? + expandedItem['@id'] : expandedItem['@index']) || + api.compactIri({activeCtx, iri: '@none', + relativeTo: {vocab: true}}); + // add compactedItem to map, using value of `@id` or a new blank + // node identifier + + _addValue( + mapObject, key, compactedItem, { + propertyIsArray: + (!options.compactArrays || container.includes('@set')) + }); + } else if(container.includes('@graph') && + _isSimpleGraph(expandedItem)) { + // container includes @graph but not @id or @index and value is a + // simple graph object add compact value + // if compactedItem contains multiple values, it is wrapped in + // `@included` + if(_isArray(compactedItem) && compactedItem.length > 1) { + compactedItem = {'@included': compactedItem}; + } + _addValue( + nestResult, itemActiveProperty, compactedItem, { + propertyIsArray: + (!options.compactArrays || container.includes('@set')) + }); + } else { + // wrap using @graph alias, remove array if only one item and + // compactArrays not set + if(_isArray(compactedItem) && compactedItem.length === 1 && + options.compactArrays) { + compactedItem = compactedItem[0]; + } + compactedItem = { + [api.compactIri({ + activeCtx, + iri: '@graph', + relativeTo: {vocab: true} + })]: compactedItem + }; + + // include @id from expanded graph, if any + if('@id' in expandedItem) { + compactedItem[api.compactIri({ + activeCtx, + iri: '@id', + relativeTo: {vocab: true} + })] = expandedItem['@id']; + } + + // include @index from expanded graph, if any + if('@index' in expandedItem) { + compactedItem[api.compactIri({ + activeCtx, + iri: '@index', + relativeTo: {vocab: true} + })] = expandedItem['@index']; + } + _addValue( + nestResult, itemActiveProperty, compactedItem, { + propertyIsArray: + (!options.compactArrays || container.includes('@set')) + }); + } + } else if(container.includes('@language') || + container.includes('@index') || container.includes('@id') || + container.includes('@type')) { + // handle language and index maps + // get or create the map object + let mapObject; + if(nestResult.hasOwnProperty(itemActiveProperty)) { + mapObject = nestResult[itemActiveProperty]; + } else { + nestResult[itemActiveProperty] = mapObject = {}; + } + + let key; + if(container.includes('@language')) { + // if container is a language map, simplify compacted value to + // a simple string + if(_isValue(compactedItem)) { + compactedItem = compactedItem['@value']; + } + key = expandedItem['@language']; + } else if(container.includes('@index')) { + const indexKey = _getContextValue( + activeCtx, itemActiveProperty, '@index') || '@index'; + const containerKey = api.compactIri( + {activeCtx, iri: indexKey, relativeTo: {vocab: true}}); + if(indexKey === '@index') { + key = expandedItem['@index']; + delete compactedItem[containerKey]; + } else { + let others; + [key, ...others] = _asArray(compactedItem[indexKey] || []); + if(!_isString(key)) { + // Will use @none if it isn't a string. + key = null; + } else { + switch(others.length) { + case 0: + delete compactedItem[indexKey]; + break; + case 1: + compactedItem[indexKey] = others[0]; + break; + default: + compactedItem[indexKey] = others; + break; + } + } + } + } else if(container.includes('@id')) { + const idKey = api.compactIri({activeCtx, iri: '@id', + relativeTo: {vocab: true}}); + key = compactedItem[idKey]; + delete compactedItem[idKey]; + } else if(container.includes('@type')) { + const typeKey = api.compactIri({ + activeCtx, + iri: '@type', + relativeTo: {vocab: true} + }); + let types; + [key, ...types] = _asArray(compactedItem[typeKey] || []); + switch(types.length) { + case 0: + delete compactedItem[typeKey]; + break; + case 1: + compactedItem[typeKey] = types[0]; + break; + default: + compactedItem[typeKey] = types; + break; + } + + // If compactedItem contains a single entry + // whose key maps to @id, recompact without @type + if(Object.keys(compactedItem).length === 1 && + '@id' in expandedItem) { + compactedItem = await api.compact({ + activeCtx, + activeProperty: itemActiveProperty, + element: {'@id': expandedItem['@id']}, + options + }); + } + } + + // if compacting this value which has no key, index on @none + if(!key) { + key = api.compactIri({activeCtx, iri: '@none', + relativeTo: {vocab: true}}); + } + // add compact value to map object using key from expanded value + // based on the container type + _addValue( + mapObject, key, compactedItem, { + propertyIsArray: container.includes('@set') + }); + } else { + // use an array if: compactArrays flag is false, + // @container is @set or @list , value is an empty + // array, or key is @graph + const isArray = (!options.compactArrays || + container.includes('@set') || container.includes('@list') || + (_isArray(compactedItem) && compactedItem.length === 0) || + expandedProperty === '@list' || expandedProperty === '@graph'); + + // add compact value + _addValue( + nestResult, itemActiveProperty, compactedItem, + {propertyIsArray: isArray}); + } + } + } + + return rval; + } + + // only primitives remain which are already compact + return element; +}; + +/** + * Compacts an IRI or keyword into a term or prefix if it can be. If the + * IRI has an associated value it may be passed. + * + * @param activeCtx the active context to use. + * @param iri the IRI to compact. + * @param value the value to check or null. + * @param relativeTo options for how to compact IRIs: + * vocab: true to split after @vocab, false not to. + * @param reverse true if a reverse property is being compacted, false if not. + * @param base the absolute URL to use for compacting document-relative IRIs. + * + * @return the compacted term, prefix, keyword alias, or the original IRI. + */ +api.compactIri = ({ + activeCtx, + iri, + value = null, + relativeTo = {vocab: false}, + reverse = false, + base = null +}) => { + // can't compact null + if(iri === null) { + return iri; + } + + // if context is from a property term scoped context composed with a + // type-scoped context, then use the previous context instead + if(activeCtx.isPropertyTermScoped && activeCtx.previousContext) { + activeCtx = activeCtx.previousContext; + } + + const inverseCtx = activeCtx.getInverse(); + + // if term is a keyword, it may be compacted to a simple alias + if(_isKeyword(iri) && + iri in inverseCtx && + '@none' in inverseCtx[iri] && + '@type' in inverseCtx[iri]['@none'] && + '@none' in inverseCtx[iri]['@none']['@type']) { + return inverseCtx[iri]['@none']['@type']['@none']; + } + + // use inverse context to pick a term if iri is relative to vocab + if(relativeTo.vocab && iri in inverseCtx) { + const defaultLanguage = activeCtx['@language'] || '@none'; + + // prefer @index if available in value + const containers = []; + if(_isObject(value) && '@index' in value && !('@graph' in value)) { + containers.push('@index', '@index@set'); + } + + // if value is a preserve object, use its value + if(_isObject(value) && '@preserve' in value) { + value = value['@preserve'][0]; + } + + // prefer most specific container including @graph, prefering @set + // variations + if(_isGraph(value)) { + // favor indexmap if the graph is indexed + if('@index' in value) { + containers.push( + '@graph@index', '@graph@index@set', '@index', '@index@set'); + } + // favor idmap if the graph is has an @id + if('@id' in value) { + containers.push( + '@graph@id', '@graph@id@set'); + } + containers.push('@graph', '@graph@set', '@set'); + // allow indexmap if the graph is not indexed + if(!('@index' in value)) { + containers.push( + '@graph@index', '@graph@index@set', '@index', '@index@set'); + } + // allow idmap if the graph does not have an @id + if(!('@id' in value)) { + containers.push('@graph@id', '@graph@id@set'); + } + } else if(_isObject(value) && !_isValue(value)) { + containers.push('@id', '@id@set', '@type', '@set@type'); + } + + // defaults for term selection based on type/language + let typeOrLanguage = '@language'; + let typeOrLanguageValue = '@null'; + + if(reverse) { + typeOrLanguage = '@type'; + typeOrLanguageValue = '@reverse'; + containers.push('@set'); + } else if(_isList(value)) { + // choose the most specific term that works for all elements in @list + // only select @list containers if @index is NOT in value + if(!('@index' in value)) { + containers.push('@list'); + } + const list = value['@list']; + if(list.length === 0) { + // any empty list can be matched against any term that uses the + // @list container regardless of @type or @language + typeOrLanguage = '@any'; + typeOrLanguageValue = '@none'; + } else { + let commonLanguage = (list.length === 0) ? defaultLanguage : null; + let commonType = null; + for(let i = 0; i < list.length; ++i) { + const item = list[i]; + let itemLanguage = '@none'; + let itemType = '@none'; + if(_isValue(item)) { + if('@direction' in item) { + const lang = (item['@language'] || '').toLowerCase(); + const dir = item['@direction']; + itemLanguage = `${lang}_${dir}`; + } else if('@language' in item) { + itemLanguage = item['@language'].toLowerCase(); + } else if('@type' in item) { + itemType = item['@type']; + } else { + // plain literal + itemLanguage = '@null'; + } + } else { + itemType = '@id'; + } + if(commonLanguage === null) { + commonLanguage = itemLanguage; + } else if(itemLanguage !== commonLanguage && _isValue(item)) { + commonLanguage = '@none'; + } + if(commonType === null) { + commonType = itemType; + } else if(itemType !== commonType) { + commonType = '@none'; + } + // there are different languages and types in the list, so choose + // the most generic term, no need to keep iterating the list + if(commonLanguage === '@none' && commonType === '@none') { + break; + } + } + commonLanguage = commonLanguage || '@none'; + commonType = commonType || '@none'; + if(commonType !== '@none') { + typeOrLanguage = '@type'; + typeOrLanguageValue = commonType; + } else { + typeOrLanguageValue = commonLanguage; + } + } + } else { + if(_isValue(value)) { + if('@language' in value && !('@index' in value)) { + containers.push('@language', '@language@set'); + typeOrLanguageValue = value['@language']; + const dir = value['@direction']; + if(dir) { + typeOrLanguageValue = `${typeOrLanguageValue}_${dir}`; + } + } else if('@direction' in value && !('@index' in value)) { + typeOrLanguageValue = `_${value['@direction']}`; + } else if('@type' in value) { + typeOrLanguage = '@type'; + typeOrLanguageValue = value['@type']; + } + } else { + typeOrLanguage = '@type'; + typeOrLanguageValue = '@id'; + } + containers.push('@set'); + } + + // do term selection + containers.push('@none'); + + // an index map can be used to index values using @none, so add as a low + // priority + if(_isObject(value) && !('@index' in value)) { + // allow indexing even if no @index present + containers.push('@index', '@index@set'); + } + + // values without type or language can use @language map + if(_isValue(value) && Object.keys(value).length === 1) { + // allow indexing even if no @index present + containers.push('@language', '@language@set'); + } + + const term = _selectTerm( + activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue); + if(term !== null) { + return term; + } + } + + // no term match, use @vocab if available + if(relativeTo.vocab) { + if('@vocab' in activeCtx) { + // determine if vocab is a prefix of the iri + const vocab = activeCtx['@vocab']; + if(iri.indexOf(vocab) === 0 && iri !== vocab) { + // use suffix as relative iri if it is not a term in the active context + const suffix = iri.substr(vocab.length); + if(!activeCtx.mappings.has(suffix)) { + return suffix; + } + } + } + } + + // no term or @vocab match, check for possible CURIEs + let choice = null; + // TODO: make FastCurieMap a class with a method to do this lookup + const partialMatches = []; + let iriMap = activeCtx.fastCurieMap; + // check for partial matches of against `iri`, which means look until + // iri.length - 1, not full length + const maxPartialLength = iri.length - 1; + for(let i = 0; i < maxPartialLength && iri[i] in iriMap; ++i) { + iriMap = iriMap[iri[i]]; + if('' in iriMap) { + partialMatches.push(iriMap[''][0]); + } + } + // check partial matches in reverse order to prefer longest ones first + for(let i = partialMatches.length - 1; i >= 0; --i) { + const entry = partialMatches[i]; + const terms = entry.terms; + for(const term of terms) { + // a CURIE is usable if: + // 1. it has no mapping, OR + // 2. value is null, which means we're not compacting an @value, AND + // the mapping matches the IRI + const curie = term + ':' + iri.substr(entry.iri.length); + const isUsableCurie = (activeCtx.mappings.get(term)._prefix && + (!activeCtx.mappings.has(curie) || + (value === null && activeCtx.mappings.get(curie)['@id'] === iri))); + + // select curie if it is shorter or the same length but lexicographically + // less than the current choice + if(isUsableCurie && (choice === null || + _compareShortestLeast(curie, choice) < 0)) { + choice = curie; + } + } + } + + // return chosen curie + if(choice !== null) { + return choice; + } + + // If iri could be confused with a compact IRI using a term in this context, + // signal an error + for(const [term, td] of activeCtx.mappings) { + if(td && td._prefix && iri.startsWith(term + ':')) { + throw new JsonLdError( + `Absolute IRI "${iri}" confused with prefix "${term}".`, + 'jsonld.SyntaxError', + {code: 'IRI confused with prefix', context: activeCtx}); + } + } + + // compact IRI relative to base + if(!relativeTo.vocab) { + if('@base' in activeCtx) { + if(!activeCtx['@base']) { + // The None case preserves rval as potentially relative + return iri; + } else { + const _iri = _removeBase(_prependBase(base, activeCtx['@base']), iri); + return REGEX_KEYWORD.test(_iri) ? `./${_iri}` : _iri; + } + } else { + return _removeBase(base, iri); + } + } + + // return IRI as is + return iri; +}; + +/** + * Performs value compaction on an object with '@value' or '@id' as the only + * property. + * + * @param activeCtx the active context. + * @param activeProperty the active property that points to the value. + * @param value the value to compact. + * @param {Object} [options] - processing options. + * + * @return the compaction result. + */ +api.compactValue = ({activeCtx, activeProperty, value, options}) => { + // value is a @value + if(_isValue(value)) { + // get context rules + const type = _getContextValue(activeCtx, activeProperty, '@type'); + const language = _getContextValue(activeCtx, activeProperty, '@language'); + const direction = _getContextValue(activeCtx, activeProperty, '@direction'); + const container = + _getContextValue(activeCtx, activeProperty, '@container') || []; + + // whether or not the value has an @index that must be preserved + const preserveIndex = '@index' in value && !container.includes('@index'); + + // if there's no @index to preserve ... + if(!preserveIndex && type !== '@none') { + // matching @type or @language specified in context, compact value + if(value['@type'] === type) { + return value['@value']; + } + if('@language' in value && value['@language'] === language && + '@direction' in value && value['@direction'] === direction) { + return value['@value']; + } + if('@language' in value && value['@language'] === language) { + return value['@value']; + } + if('@direction' in value && value['@direction'] === direction) { + return value['@value']; + } + } + + // return just the value of @value if all are true: + // 1. @value is the only key or @index isn't being preserved + // 2. there is no default language or @value is not a string or + // the key has a mapping with a null @language + const keyCount = Object.keys(value).length; + const isValueOnlyKey = (keyCount === 1 || + (keyCount === 2 && '@index' in value && !preserveIndex)); + const hasDefaultLanguage = ('@language' in activeCtx); + const isValueString = _isString(value['@value']); + const hasNullMapping = (activeCtx.mappings.has(activeProperty) && + activeCtx.mappings.get(activeProperty)['@language'] === null); + if(isValueOnlyKey && + type !== '@none' && + (!hasDefaultLanguage || !isValueString || hasNullMapping)) { + return value['@value']; + } + + const rval = {}; + + // preserve @index + if(preserveIndex) { + rval[api.compactIri({ + activeCtx, + iri: '@index', + relativeTo: {vocab: true} + })] = value['@index']; + } + + if('@type' in value) { + // compact @type IRI + rval[api.compactIri({ + activeCtx, + iri: '@type', + relativeTo: {vocab: true} + })] = api.compactIri( + {activeCtx, iri: value['@type'], relativeTo: {vocab: true}}); + } else if('@language' in value) { + // alias @language + rval[api.compactIri({ + activeCtx, + iri: '@language', + relativeTo: {vocab: true} + })] = value['@language']; + } + + if('@direction' in value) { + // alias @direction + rval[api.compactIri({ + activeCtx, + iri: '@direction', + relativeTo: {vocab: true} + })] = value['@direction']; + } + + // alias @value + rval[api.compactIri({ + activeCtx, + iri: '@value', + relativeTo: {vocab: true} + })] = value['@value']; + + return rval; + } + + // value is a subject reference + const expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true}, + options); + const type = _getContextValue(activeCtx, activeProperty, '@type'); + const compacted = api.compactIri({ + activeCtx, + iri: value['@id'], + relativeTo: {vocab: type === '@vocab'}, + base: options.base}); + + // compact to scalar + if(type === '@id' || type === '@vocab' || expandedProperty === '@graph') { + return compacted; + } + + return { + [api.compactIri({ + activeCtx, + iri: '@id', + relativeTo: {vocab: true} + })]: compacted + }; +}; + +/** + * Picks the preferred compaction term from the given inverse context entry. + * + * @param activeCtx the active context. + * @param iri the IRI to pick the term for. + * @param value the value to pick the term for. + * @param containers the preferred containers. + * @param typeOrLanguage either '@type' or '@language'. + * @param typeOrLanguageValue the preferred value for '@type' or '@language'. + * + * @return the preferred term. + */ +function _selectTerm( + activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue) { + if(typeOrLanguageValue === null) { + typeOrLanguageValue = '@null'; + } + + // preferences for the value of @type or @language + const prefs = []; + + // determine prefs for @id based on whether or not value compacts to a term + if((typeOrLanguageValue === '@id' || typeOrLanguageValue === '@reverse') && + _isObject(value) && '@id' in value) { + // prefer @reverse first + if(typeOrLanguageValue === '@reverse') { + prefs.push('@reverse'); + } + // try to compact value to a term + const term = api.compactIri( + {activeCtx, iri: value['@id'], relativeTo: {vocab: true}}); + if(activeCtx.mappings.has(term) && + activeCtx.mappings.get(term) && + activeCtx.mappings.get(term)['@id'] === value['@id']) { + // prefer @vocab + prefs.push.apply(prefs, ['@vocab', '@id']); + } else { + // prefer @id + prefs.push.apply(prefs, ['@id', '@vocab']); + } + } else { + prefs.push(typeOrLanguageValue); + + // consider direction only + const langDir = prefs.find(el => el.includes('_')); + if(langDir) { + // consider _dir portion + prefs.push(langDir.replace(/^[^_]+_/, '_')); + } + } + prefs.push('@none'); + + const containerMap = activeCtx.inverse[iri]; + for(const container of containers) { + // if container not available in the map, continue + if(!(container in containerMap)) { + continue; + } + + const typeOrLanguageValueMap = containerMap[container][typeOrLanguage]; + for(const pref of prefs) { + // if type/language option not available in the map, continue + if(!(pref in typeOrLanguageValueMap)) { + continue; + } + + // select term + return typeOrLanguageValueMap[pref]; + } + } + + return null; +} + +/** + * The value of `@nest` in the term definition must either be `@nest`, or a term + * which resolves to `@nest`. + * + * @param activeCtx the active context. + * @param nestProperty a term in the active context or `@nest`. + * @param {Object} [options] - processing options. + */ +function _checkNestProperty(activeCtx, nestProperty, options) { + if(_expandIri(activeCtx, nestProperty, {vocab: true}, options) !== '@nest') { + throw new JsonLdError( + 'JSON-LD compact error; nested property must have an @nest value ' + + 'resolving to @nest.', + 'jsonld.SyntaxError', {code: 'invalid @nest value'}); + } +} + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/constants.js" +/*!**********************************************!*\ + !*** ./node_modules/jsonld/lib/constants.js ***! + \**********************************************/ +(module) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; +const XSD = 'http://www.w3.org/2001/XMLSchema#'; + +module.exports = { + // TODO: Deprecated and will be removed later. Use LINK_HEADER_CONTEXT. + LINK_HEADER_REL: 'http://www.w3.org/ns/json-ld#context', + + LINK_HEADER_CONTEXT: 'http://www.w3.org/ns/json-ld#context', + + RDF, + RDF_LIST: RDF + 'List', + RDF_FIRST: RDF + 'first', + RDF_REST: RDF + 'rest', + RDF_NIL: RDF + 'nil', + RDF_TYPE: RDF + 'type', + RDF_PLAIN_LITERAL: RDF + 'PlainLiteral', + RDF_XML_LITERAL: RDF + 'XMLLiteral', + RDF_JSON_LITERAL: RDF + 'JSON', + RDF_OBJECT: RDF + 'object', + RDF_LANGSTRING: RDF + 'langString', + + XSD, + XSD_BOOLEAN: XSD + 'boolean', + XSD_DOUBLE: XSD + 'double', + XSD_INTEGER: XSD + 'integer', + XSD_STRING: XSD + 'string', +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/context.js" +/*!********************************************!*\ + !*** ./node_modules/jsonld/lib/context.js ***! + \********************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017-2019 Digital Bazaar, Inc. All rights reserved. + */ + + +const util = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); + +const { + isArray: _isArray, + isObject: _isObject, + isString: _isString, + isUndefined: _isUndefined +} = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const { + isAbsolute: _isAbsoluteIri, + isRelative: _isRelativeIri, + prependBase +} = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); + +const { + handleEvent: _handleEvent +} = __webpack_require__(/*! ./events */ "./node_modules/jsonld/lib/events.js"); + +const { + REGEX_BCP47, + REGEX_KEYWORD, + asArray: _asArray, + compareShortestLeast: _compareShortestLeast +} = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); + +const INITIAL_CONTEXT_CACHE = new Map(); +const INITIAL_CONTEXT_CACHE_MAX_SIZE = 10000; + +const api = {}; +module.exports = api; + +/** + * Processes a local context and returns a new active context. + * + * @param activeCtx the current active context. + * @param localCtx the local context to process. + * @param options the context processing options. + * @param propagate `true` if `false`, retains any previously defined term, + * which can be rolled back when the descending into a new node object. + * @param overrideProtected `false` allows protected terms to be modified. + * + * @return a Promise that resolves to the new active context. + */ +api.process = async ({ + activeCtx, localCtx, options, + propagate = true, + overrideProtected = false, + cycles = new Set() +}) => { + // normalize local context to an array of @context objects + if(_isObject(localCtx) && '@context' in localCtx && + _isArray(localCtx['@context'])) { + localCtx = localCtx['@context']; + } + const ctxs = _asArray(localCtx); + + // no contexts in array, return current active context w/o changes + if(ctxs.length === 0) { + return activeCtx; + } + + // event handler for capturing events to replay when using a cached context + const events = []; + const eventCaptureHandler = [ + ({event, next}) => { + events.push(event); + next(); + } + ]; + // chain to original handler + if(options.eventHandler) { + eventCaptureHandler.push(options.eventHandler); + } + // store original options to use when replaying events + const originalOptions = options; + // shallow clone options with event capture handler + options = {...options, eventHandler: eventCaptureHandler}; + + // resolve contexts + const resolved = await options.contextResolver.resolve({ + activeCtx, + context: localCtx, + documentLoader: options.documentLoader, + base: options.base + }); + + // override propagate if first resolved context has `@propagate` + if(_isObject(resolved[0].document) && + typeof resolved[0].document['@propagate'] === 'boolean') { + // retrieve early, error checking done later + propagate = resolved[0].document['@propagate']; + } + + // process each context in order, update active context + // on each iteration to ensure proper caching + let rval = activeCtx; + + // track the previous context + // if not propagating, make sure rval has a previous context + if(!propagate && !rval.previousContext) { + // clone `rval` context before updating + rval = rval.clone(); + rval.previousContext = activeCtx; + } + + for(const resolvedContext of resolved) { + let {document: ctx} = resolvedContext; + + // update active context to one computed from last iteration + activeCtx = rval; + + // reset to initial context + if(ctx === null) { + // We can't nullify if there are protected terms and we're + // not allowing overrides (e.g. processing a property term scoped context) + if(!overrideProtected && Object.keys(activeCtx.protected).length !== 0) { + throw new JsonLdError( + 'Tried to nullify a context with protected terms outside of ' + + 'a term definition.', + 'jsonld.SyntaxError', + {code: 'invalid context nullification'}); + } + rval = activeCtx = api.getInitialContext(options).clone(); + continue; + } + + // get processed context from cache if available + const processed = resolvedContext.getProcessed(activeCtx); + if(processed) { + if(originalOptions.eventHandler) { + // replay events with original non-capturing options + for(const event of processed.events) { + _handleEvent({event, options: originalOptions}); + } + } + + rval = activeCtx = processed.context; + continue; + } + + // dereference @context key if present + if(_isObject(ctx) && '@context' in ctx) { + ctx = ctx['@context']; + } + + // context must be an object by now, all URLs retrieved before this call + if(!_isObject(ctx)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context must be an object.', + 'jsonld.SyntaxError', {code: 'invalid local context', context: ctx}); + } + + // TODO: there is likely a `previousContext` cloning optimization that + // could be applied here (no need to copy it under certain conditions) + + // clone context before updating it + rval = rval.clone(); + + // define context mappings for keys in local context + const defined = new Map(); + + // handle @version + if('@version' in ctx) { + if(ctx['@version'] !== 1.1) { + throw new JsonLdError( + 'Unsupported JSON-LD version: ' + ctx['@version'], + 'jsonld.UnsupportedVersion', + {code: 'invalid @version value', context: ctx}); + } + if(activeCtx.processingMode && + activeCtx.processingMode === 'json-ld-1.0') { + throw new JsonLdError( + '@version: ' + ctx['@version'] + ' not compatible with ' + + activeCtx.processingMode, + 'jsonld.ProcessingModeConflict', + {code: 'processing mode conflict', context: ctx}); + } + rval.processingMode = 'json-ld-1.1'; + rval['@version'] = ctx['@version']; + defined.set('@version', true); + } + + // if not set explicitly, set processingMode to "json-ld-1.1" + rval.processingMode = + rval.processingMode || activeCtx.processingMode; + + // handle @base + if('@base' in ctx) { + let base = ctx['@base']; + + if(base === null || _isAbsoluteIri(base)) { + // no action + } else if(_isRelativeIri(base)) { + base = prependBase(rval['@base'], base); + } else { + throw new JsonLdError( + 'Invalid JSON-LD syntax; the value of "@base" in a ' + + '@context must be an absolute IRI, a relative IRI, or null.', + 'jsonld.SyntaxError', {code: 'invalid base IRI', context: ctx}); + } + + rval['@base'] = base; + defined.set('@base', true); + } + + // handle @vocab + if('@vocab' in ctx) { + const value = ctx['@vocab']; + if(value === null) { + delete rval['@vocab']; + } else if(!_isString(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; the value of "@vocab" in a ' + + '@context must be a string or null.', + 'jsonld.SyntaxError', {code: 'invalid vocab mapping', context: ctx}); + } else if(!_isAbsoluteIri(value) && api.processingMode(rval, 1.0)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; the value of "@vocab" in a ' + + '@context must be an absolute IRI.', + 'jsonld.SyntaxError', {code: 'invalid vocab mapping', context: ctx}); + } else { + const vocab = _expandIri(rval, value, {vocab: true, base: true}, + undefined, undefined, options); + if(!_isAbsoluteIri(vocab)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'relative @vocab reference', + level: 'warning', + message: 'Relative @vocab reference found.', + details: { + vocab + } + }, + options + }); + } + } + rval['@vocab'] = vocab; + } + defined.set('@vocab', true); + } + + // handle @language + if('@language' in ctx) { + const value = ctx['@language']; + if(value === null) { + delete rval['@language']; + } else if(!_isString(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; the value of "@language" in a ' + + '@context must be a string or null.', + 'jsonld.SyntaxError', + {code: 'invalid default language', context: ctx}); + } else { + if(!value.match(REGEX_BCP47)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'invalid @language value', + level: 'warning', + message: '@language value must be valid BCP47.', + details: { + language: value + } + }, + options + }); + } + } + rval['@language'] = value.toLowerCase(); + } + defined.set('@language', true); + } + + // handle @direction + if('@direction' in ctx) { + const value = ctx['@direction']; + if(activeCtx.processingMode === 'json-ld-1.0') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @direction not compatible with ' + + activeCtx.processingMode, + 'jsonld.SyntaxError', + {code: 'invalid context member', context: ctx}); + } + if(value === null) { + delete rval['@direction']; + } else if(value !== 'ltr' && value !== 'rtl') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; the value of "@direction" in a ' + + '@context must be null, "ltr", or "rtl".', + 'jsonld.SyntaxError', + {code: 'invalid base direction', context: ctx}); + } else { + rval['@direction'] = value; + } + defined.set('@direction', true); + } + + // handle @propagate + // note: we've already extracted it, here we just do error checking + if('@propagate' in ctx) { + const value = ctx['@propagate']; + if(activeCtx.processingMode === 'json-ld-1.0') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @propagate not compatible with ' + + activeCtx.processingMode, + 'jsonld.SyntaxError', + {code: 'invalid context entry', context: ctx}); + } + if(typeof value !== 'boolean') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @propagate value must be a boolean.', + 'jsonld.SyntaxError', + {code: 'invalid @propagate value', context: localCtx}); + } + defined.set('@propagate', true); + } + + // handle @import + if('@import' in ctx) { + const value = ctx['@import']; + if(activeCtx.processingMode === 'json-ld-1.0') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @import not compatible with ' + + activeCtx.processingMode, + 'jsonld.SyntaxError', + {code: 'invalid context entry', context: ctx}); + } + if(!_isString(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @import must be a string.', + 'jsonld.SyntaxError', + {code: 'invalid @import value', context: localCtx}); + } + + // resolve contexts + const resolvedImport = await options.contextResolver.resolve({ + activeCtx, + context: value, + documentLoader: options.documentLoader, + base: options.base + }); + if(resolvedImport.length !== 1) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @import must reference a single context.', + 'jsonld.SyntaxError', + {code: 'invalid remote context', context: localCtx}); + } + const processedImport = resolvedImport[0].getProcessed(activeCtx); + if(processedImport) { + // Note: if the same context were used in this active context + // as a reference context, then processed_input might not + // be a dict. + ctx = processedImport; + } else { + const importCtx = resolvedImport[0].document; + if('@import' in importCtx) { + throw new JsonLdError( + 'Invalid JSON-LD syntax: ' + + 'imported context must not include @import.', + 'jsonld.SyntaxError', + {code: 'invalid context entry', context: localCtx}); + } + + // merge ctx into importCtx and replace rval with the result + for(const key in importCtx) { + if(!ctx.hasOwnProperty(key)) { + ctx[key] = importCtx[key]; + } + } + + // Note: this could potenially conflict if the import + // were used in the same active context as a referenced + // context and an import. In this case, we + // could override the cached result, but seems unlikely. + resolvedImport[0].setProcessed(activeCtx, ctx); + } + + defined.set('@import', true); + } + + // handle @protected; determine whether this sub-context is declaring + // all its terms to be "protected" (exceptions can be made on a + // per-definition basis) + defined.set('@protected', ctx['@protected'] || false); + + // process all other keys + for(const key in ctx) { + api.createTermDefinition({ + activeCtx: rval, + localCtx: ctx, + term: key, + defined, + options, + overrideProtected + }); + + if(_isObject(ctx[key]) && '@context' in ctx[key]) { + const keyCtx = ctx[key]['@context']; + let process = true; + if(_isString(keyCtx)) { + const url = prependBase(options.base, keyCtx); + // track processed contexts to avoid scoped context recursion + if(cycles.has(url)) { + process = false; + } else { + cycles.add(url); + } + } + // parse context to validate + if(process) { + try { + await api.process({ + activeCtx: rval.clone(), + localCtx: ctx[key]['@context'], + overrideProtected: true, + options, + cycles + }); + } catch(e) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; invalid scoped context.', + 'jsonld.SyntaxError', + { + code: 'invalid scoped context', + context: ctx[key]['@context'], + term: key + }); + } + } + } + } + + // cache processed result + resolvedContext.setProcessed(activeCtx, { + context: rval, + events + }); + } + + return rval; +}; + +/** + * Creates a term definition during context processing. + * + * @param activeCtx the current active context. + * @param localCtx the local context being processed. + * @param term the term in the local context to define the mapping for. + * @param defined a map of defining/defined keys to detect cycles and prevent + * double definitions. + * @param {Object} [options] - creation options. + * @param overrideProtected `false` allows protected terms to be modified. + */ +api.createTermDefinition = ({ + activeCtx, + localCtx, + term, + defined, + options, + overrideProtected = false, +}) => { + if(defined.has(term)) { + // term already defined + if(defined.get(term)) { + return; + } + // cycle detected + throw new JsonLdError( + 'Cyclical context definition detected.', + 'jsonld.CyclicalContext', + {code: 'cyclic IRI mapping', context: localCtx, term}); + } + + // now defining term + defined.set(term, false); + + // get context term value + let value; + if(localCtx.hasOwnProperty(term)) { + value = localCtx[term]; + } + + if(term === '@type' && + _isObject(value) && + (value['@container'] || '@set') === '@set' && + api.processingMode(activeCtx, 1.1)) { + + const validKeys = ['@container', '@id', '@protected']; + const keys = Object.keys(value); + if(keys.length === 0 || keys.some(k => !validKeys.includes(k))) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; keywords cannot be overridden.', + 'jsonld.SyntaxError', + {code: 'keyword redefinition', context: localCtx, term}); + } + } else if(api.isKeyword(term)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; keywords cannot be overridden.', + 'jsonld.SyntaxError', + {code: 'keyword redefinition', context: localCtx, term}); + } else if(term.match(REGEX_KEYWORD)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'reserved term', + level: 'warning', + message: + 'Terms beginning with "@" are ' + + 'reserved for future use and dropped.', + details: { + term + } + }, + options + }); + } + return; + } else if(term === '') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a term cannot be an empty string.', + 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + + // keep reference to previous mapping for potential `@protected` check + const previousMapping = activeCtx.mappings.get(term); + + // remove old mapping + if(activeCtx.mappings.has(term)) { + activeCtx.mappings.delete(term); + } + + // convert short-hand value to object w/@id + let simpleTerm = false; + if(_isString(value) || value === null) { + simpleTerm = true; + value = {'@id': value}; + } + + if(!_isObject(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context term values must be ' + + 'strings or objects.', + 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + + // create new mapping + const mapping = {}; + activeCtx.mappings.set(term, mapping); + mapping.reverse = false; + + // make sure term definition only has expected keywords + const validKeys = ['@container', '@id', '@language', '@reverse', '@type']; + + // JSON-LD 1.1 support + if(api.processingMode(activeCtx, 1.1)) { + validKeys.push( + '@context', '@direction', '@index', '@nest', '@prefix', '@protected'); + } + + for(const kw in value) { + if(!validKeys.includes(kw)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a term definition must not contain ' + kw, + 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + } + + // always compute whether term has a colon as an optimization for + // _compactIri + const colon = term.indexOf(':'); + mapping._termHasColon = (colon > 0); + + if('@reverse' in value) { + if('@id' in value) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a @reverse term definition must not ' + + 'contain @id.', 'jsonld.SyntaxError', + {code: 'invalid reverse property', context: localCtx}); + } + if('@nest' in value) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a @reverse term definition must not ' + + 'contain @nest.', 'jsonld.SyntaxError', + {code: 'invalid reverse property', context: localCtx}); + } + const reverse = value['@reverse']; + if(!_isString(reverse)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a @context @reverse value must be a string.', + 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx}); + } + + if(reverse.match(REGEX_KEYWORD)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'reserved @reverse value', + level: 'warning', + message: + '@reverse values beginning with "@" are ' + + 'reserved for future use and dropped.', + details: { + reverse + } + }, + options + }); + } + if(previousMapping) { + activeCtx.mappings.set(term, previousMapping); + } else { + activeCtx.mappings.delete(term); + } + return; + } + + // expand and add @id mapping + const id = _expandIri( + activeCtx, reverse, {vocab: true, base: false}, localCtx, defined, + options); + if(!_isAbsoluteIri(id)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a @context @reverse value must be an ' + + 'absolute IRI or a blank node identifier.', + 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx}); + } + + mapping['@id'] = id; + mapping.reverse = true; + } else if('@id' in value) { + let id = value['@id']; + if(id && !_isString(id)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a @context @id value must be an array ' + + 'of strings or a string.', + 'jsonld.SyntaxError', {code: 'invalid IRI mapping', context: localCtx}); + } + if(id === null) { + // reserve a null term, which may be protected + mapping['@id'] = null; + } else if(!api.isKeyword(id) && id.match(REGEX_KEYWORD)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'reserved @id value', + level: 'warning', + message: + '@id values beginning with "@" are ' + + 'reserved for future use and dropped.', + details: { + id + } + }, + options + }); + } + if(previousMapping) { + activeCtx.mappings.set(term, previousMapping); + } else { + activeCtx.mappings.delete(term); + } + return; + } else if(id !== term) { + // expand and add @id mapping + id = _expandIri( + activeCtx, id, {vocab: true, base: false}, localCtx, defined, options); + if(!_isAbsoluteIri(id) && !api.isKeyword(id)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a @context @id value must be an ' + + 'absolute IRI, a blank node identifier, or a keyword.', + 'jsonld.SyntaxError', + {code: 'invalid IRI mapping', context: localCtx}); + } + + // if term has the form of an IRI it must map the same + if(term.match(/(?::[^:])|\//)) { + const termDefined = new Map(defined).set(term, true); + const termIri = _expandIri( + activeCtx, term, {vocab: true, base: false}, + localCtx, termDefined, options); + if(termIri !== id) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; term in form of IRI must ' + + 'expand to definition.', + 'jsonld.SyntaxError', + {code: 'invalid IRI mapping', context: localCtx}); + } + } + + mapping['@id'] = id; + // indicate if this term may be used as a compact IRI prefix + mapping._prefix = (simpleTerm && + !mapping._termHasColon && + id.match(/[:\/\?#\[\]@]$/) !== null); + } + } + + if(!('@id' in mapping)) { + // see if the term has a prefix + if(mapping._termHasColon) { + const prefix = term.substr(0, colon); + if(localCtx.hasOwnProperty(prefix)) { + // define parent prefix + api.createTermDefinition({ + activeCtx, localCtx, term: prefix, defined, options + }); + } + + if(activeCtx.mappings.has(prefix)) { + // set @id based on prefix parent + const suffix = term.substr(colon + 1); + mapping['@id'] = activeCtx.mappings.get(prefix)['@id'] + suffix; + } else { + // term is an absolute IRI + mapping['@id'] = term; + } + } else if(term === '@type') { + // Special case, were we've previously determined that container is @set + mapping['@id'] = term; + } else { + // non-IRIs *must* define @ids if @vocab is not available + if(!('@vocab' in activeCtx)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context terms must define an @id.', + 'jsonld.SyntaxError', + {code: 'invalid IRI mapping', context: localCtx, term}); + } + // prepend vocab to term + mapping['@id'] = activeCtx['@vocab'] + term; + } + } + + // Handle term protection + if(value['@protected'] === true || + (defined.get('@protected') === true && value['@protected'] !== false)) { + activeCtx.protected[term] = true; + mapping.protected = true; + } + + // IRI mapping now defined + defined.set(term, true); + + if('@type' in value) { + let type = value['@type']; + if(!_isString(type)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an @context @type value must be a string.', + 'jsonld.SyntaxError', + {code: 'invalid type mapping', context: localCtx}); + } + + if((type === '@json' || type === '@none')) { + if(api.processingMode(activeCtx, 1.0)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an @context @type value must not be ' + + `"${type}" in JSON-LD 1.0 mode.`, + 'jsonld.SyntaxError', + {code: 'invalid type mapping', context: localCtx}); + } + } else if(type !== '@id' && type !== '@vocab') { + // expand @type to full IRI + type = _expandIri( + activeCtx, type, {vocab: true, base: false}, localCtx, defined, + options); + if(!_isAbsoluteIri(type)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an @context @type value must be an ' + + 'absolute IRI.', + 'jsonld.SyntaxError', + {code: 'invalid type mapping', context: localCtx}); + } + if(type.indexOf('_:') === 0) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an @context @type value must be an IRI, ' + + 'not a blank node identifier.', + 'jsonld.SyntaxError', + {code: 'invalid type mapping', context: localCtx}); + } + } + + // add @type to mapping + mapping['@type'] = type; + } + + if('@container' in value) { + // normalize container to an array form + const container = _isString(value['@container']) ? + [value['@container']] : (value['@container'] || []); + const validContainers = ['@list', '@set', '@index', '@language']; + let isValid = true; + const hasSet = container.includes('@set'); + + // JSON-LD 1.1 support + if(api.processingMode(activeCtx, 1.1)) { + validContainers.push('@graph', '@id', '@type'); + + // check container length + if(container.includes('@list')) { + if(container.length !== 1) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @container with @list must ' + + 'have no other values', + 'jsonld.SyntaxError', + {code: 'invalid container mapping', context: localCtx}); + } + } else if(container.includes('@graph')) { + if(container.some(key => + key !== '@graph' && key !== '@id' && key !== '@index' && + key !== '@set')) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @container with @graph must ' + + 'have no other values other than @id, @index, and @set', + 'jsonld.SyntaxError', + {code: 'invalid container mapping', context: localCtx}); + } + } else { + // otherwise, container may also include @set + isValid &= container.length <= (hasSet ? 2 : 1); + } + + if(container.includes('@type')) { + // If mapping does not have an @type, + // set it to @id + mapping['@type'] = mapping['@type'] || '@id'; + + // type mapping must be either @id or @vocab + if(!['@id', '@vocab'].includes(mapping['@type'])) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; container: @type requires @type to be ' + + '@id or @vocab.', + 'jsonld.SyntaxError', + {code: 'invalid type mapping', context: localCtx}); + } + } + } else { + // in JSON-LD 1.0, container must not be an array (it must be a string, + // which is one of the validContainers) + isValid &= !_isArray(value['@container']); + + // check container length + isValid &= container.length <= 1; + } + + // check against valid containers + isValid &= container.every(c => validContainers.includes(c)); + + // @set not allowed with @list + isValid &= !(hasSet && container.includes('@list')); + + if(!isValid) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @container value must be ' + + 'one of the following: ' + validContainers.join(', '), + 'jsonld.SyntaxError', + {code: 'invalid container mapping', context: localCtx}); + } + + if(mapping.reverse && + !container.every(c => ['@index', '@set'].includes(c))) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @container value for a @reverse ' + + 'type definition must be @index or @set.', 'jsonld.SyntaxError', + {code: 'invalid reverse property', context: localCtx}); + } + + // add @container to mapping + mapping['@container'] = container; + } + + // property indexing + if('@index' in value) { + if(!('@container' in value) || !mapping['@container'].includes('@index')) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @index without @index in @container: ' + + `"${value['@index']}" on term "${term}".`, 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + if(!_isString(value['@index']) || value['@index'].indexOf('@') === 0) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @index must expand to an IRI: ' + + `"${value['@index']}" on term "${term}".`, 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + mapping['@index'] = value['@index']; + } + + // scoped contexts + if('@context' in value) { + mapping['@context'] = value['@context']; + } + + if('@language' in value && !('@type' in value)) { + let language = value['@language']; + if(language !== null && !_isString(language)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @language value must be ' + + 'a string or null.', 'jsonld.SyntaxError', + {code: 'invalid language mapping', context: localCtx}); + } + + // add @language to mapping + if(language !== null) { + language = language.toLowerCase(); + } + mapping['@language'] = language; + } + + // term may be used as a prefix + if('@prefix' in value) { + if(term.match(/:|\//)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @prefix used on a compact IRI term', + 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + if(api.isKeyword(mapping['@id'])) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; keywords may not be used as prefixes', + 'jsonld.SyntaxError', + {code: 'invalid term definition', context: localCtx}); + } + if(typeof value['@prefix'] === 'boolean') { + mapping._prefix = value['@prefix'] === true; + } else { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context value for @prefix must be boolean', + 'jsonld.SyntaxError', + {code: 'invalid @prefix value', context: localCtx}); + } + } + + if('@direction' in value) { + const direction = value['@direction']; + if(direction !== null && direction !== 'ltr' && direction !== 'rtl') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @direction value must be ' + + 'null, "ltr", or "rtl".', + 'jsonld.SyntaxError', + {code: 'invalid base direction', context: localCtx}); + } + mapping['@direction'] = direction; + } + + if('@nest' in value) { + const nest = value['@nest']; + if(!_isString(nest) || (nest !== '@nest' && nest.indexOf('@') === 0)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context @nest value must be ' + + 'a string which is not a keyword other than @nest.', + 'jsonld.SyntaxError', + {code: 'invalid @nest value', context: localCtx}); + } + mapping['@nest'] = nest; + } + + // disallow aliasing @context and @preserve + const id = mapping['@id']; + if(id === '@context' || id === '@preserve') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; @context and @preserve cannot be aliased.', + 'jsonld.SyntaxError', {code: 'invalid keyword alias', context: localCtx}); + } + + // Check for overriding protected terms + if(previousMapping && previousMapping.protected && !overrideProtected) { + // force new term to continue to be protected and see if the mappings would + // be equal + activeCtx.protected[term] = true; + mapping.protected = true; + if(!_deepCompare(previousMapping, mapping)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; tried to redefine a protected term.', + 'jsonld.SyntaxError', + {code: 'protected term redefinition', context: localCtx, term}); + } + } +}; + +/** + * Expands a string to a full IRI. The string may be a term, a prefix, a + * relative IRI, or an absolute IRI. The associated absolute IRI will be + * returned. + * + * @param activeCtx the current active context. + * @param value the string to expand. + * @param relativeTo options for how to resolve relative IRIs: + * base: true to resolve against the base IRI, false not to. + * vocab: true to concatenate after @vocab, false not to. + * @param {Object} [options] - processing options. + * + * @return the expanded value. + */ +api.expandIri = (activeCtx, value, relativeTo, options) => { + return _expandIri(activeCtx, value, relativeTo, undefined, undefined, + options); +}; + +/** + * Expands a string to a full IRI. The string may be a term, a prefix, a + * relative IRI, or an absolute IRI. The associated absolute IRI will be + * returned. + * + * @param activeCtx the current active context. + * @param value the string to expand. + * @param relativeTo options for how to resolve relative IRIs: + * base: true to resolve against the base IRI, false not to. + * vocab: true to concatenate after @vocab, false not to. + * @param localCtx the local context being processed (only given if called + * during context processing). + * @param defined a map for tracking cycles in context definitions (only given + * if called during context processing). + * @param {Object} [options] - processing options. + * + * @return the expanded value. + */ +function _expandIri(activeCtx, value, relativeTo, localCtx, defined, options) { + // already expanded + if(value === null || !_isString(value) || api.isKeyword(value)) { + return value; + } + + // ignore non-keyword things that look like a keyword + if(value.match(REGEX_KEYWORD)) { + return null; + } + + // define term dependency if not defined + if(localCtx && localCtx.hasOwnProperty(value) && + defined.get(value) !== true) { + api.createTermDefinition({ + activeCtx, localCtx, term: value, defined, options + }); + } + + relativeTo = relativeTo || {}; + if(relativeTo.vocab) { + const mapping = activeCtx.mappings.get(value); + + // value is explicitly ignored with a null mapping + if(mapping === null) { + return null; + } + + if(_isObject(mapping) && '@id' in mapping) { + // value is a term + return mapping['@id']; + } + } + + // split value into prefix:suffix + const colon = value.indexOf(':'); + if(colon > 0) { + const prefix = value.substr(0, colon); + const suffix = value.substr(colon + 1); + + // do not expand blank nodes (prefix of '_') or already-absolute + // IRIs (suffix of '//') + if(prefix === '_' || suffix.indexOf('//') === 0) { + return value; + } + + // prefix dependency not defined, define it + if(localCtx && localCtx.hasOwnProperty(prefix)) { + api.createTermDefinition({ + activeCtx, localCtx, term: prefix, defined, options + }); + } + + // use mapping if prefix is defined + const mapping = activeCtx.mappings.get(prefix); + if(mapping && mapping._prefix) { + return mapping['@id'] + suffix; + } + + // already absolute IRI + if(_isAbsoluteIri(value)) { + return value; + } + } + + // A flag that captures whether the iri being expanded is + // the value for an @type + //let typeExpansion = false; + + //if(options !== undefined && options.typeExpansion !== undefined) { + // typeExpansion = options.typeExpansion; + //} + + if(relativeTo.vocab && '@vocab' in activeCtx) { + // prepend vocab + const prependedResult = activeCtx['@vocab'] + value; + // FIXME: needed? may be better as debug event. + /* + if(options && options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'prepending @vocab during expansion', + level: 'info', + message: 'Prepending @vocab during expansion.', + details: { + type: '@vocab', + vocab: activeCtx['@vocab'], + value, + result: prependedResult, + typeExpansion + } + }, + options + }); + } + */ + // the null case preserves value as potentially relative + value = prependedResult; + } else if(relativeTo.base) { + // prepend base + let prependedResult; + let base; + if('@base' in activeCtx) { + if(activeCtx['@base']) { + base = prependBase(options.base, activeCtx['@base']); + prependedResult = prependBase(base, value); + } else { + base = activeCtx['@base']; + prependedResult = value; + } + } else { + base = options.base; + prependedResult = prependBase(options.base, value); + } + // FIXME: needed? may be better as debug event. + /* + if(options && options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'prepending @base during expansion', + level: 'info', + message: 'Prepending @base during expansion.', + details: { + type: '@base', + base, + value, + result: prependedResult, + typeExpansion + } + }, + options + }); + } + */ + // the null case preserves value as potentially relative + value = prependedResult; + } + + // FIXME: duplicate? needed? maybe just enable in a verbose debug mode + /* + if(!_isAbsoluteIri(value) && options && options.eventHandler) { + // emit event indicating a relative IRI was found, which can result in it + // being dropped when converting to other RDF representations + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'relative IRI after expansion', + // FIXME: what level? + level: 'warning', + message: 'Relative IRI after expansion.', + details: { + relativeIri: value, + typeExpansion + } + }, + options + }); + // NOTE: relative reference events emitted at calling sites as needed + } + */ + + return value; +} + +/** + * Gets the initial context. + * + * @param options the options to use: + * [base] the document base IRI. + * + * @return the initial context. + */ +api.getInitialContext = options => { + const key = JSON.stringify({processingMode: options.processingMode}); + const cached = INITIAL_CONTEXT_CACHE.get(key); + if(cached) { + return cached; + } + + const initialContext = { + processingMode: options.processingMode, + mappings: new Map(), + inverse: null, + getInverse: _createInverseContext, + clone: _cloneActiveContext, + revertToPreviousContext: _revertToPreviousContext, + protected: {} + }; + // TODO: consider using LRU cache instead + if(INITIAL_CONTEXT_CACHE.size === INITIAL_CONTEXT_CACHE_MAX_SIZE) { + // clear whole cache -- assumes scenario where the cache fills means + // the cache isn't being used very efficiently anyway + INITIAL_CONTEXT_CACHE.clear(); + } + INITIAL_CONTEXT_CACHE.set(key, initialContext); + return initialContext; + + /** + * Generates an inverse context for use in the compaction algorithm, if + * not already generated for the given active context. + * + * @return the inverse context. + */ + function _createInverseContext() { + const activeCtx = this; + + // lazily create inverse + if(activeCtx.inverse) { + return activeCtx.inverse; + } + const inverse = activeCtx.inverse = {}; + + // variables for building fast CURIE map + const fastCurieMap = activeCtx.fastCurieMap = {}; + const irisToTerms = {}; + + // handle default language + const defaultLanguage = (activeCtx['@language'] || '@none').toLowerCase(); + + // handle default direction + const defaultDirection = activeCtx['@direction']; + + // create term selections for each mapping in the context, ordered by + // shortest and then lexicographically least + const mappings = activeCtx.mappings; + const terms = [...mappings.keys()].sort(_compareShortestLeast); + for(const term of terms) { + const mapping = mappings.get(term); + if(mapping === null) { + continue; + } + + let container = mapping['@container'] || '@none'; + container = [].concat(container).sort().join(''); + + if(mapping['@id'] === null) { + continue; + } + // iterate over every IRI in the mapping + const ids = _asArray(mapping['@id']); + for(const iri of ids) { + let entry = inverse[iri]; + const isKeyword = api.isKeyword(iri); + + if(!entry) { + // initialize entry + inverse[iri] = entry = {}; + + if(!isKeyword && !mapping._termHasColon) { + // init IRI to term map and fast CURIE prefixes + irisToTerms[iri] = [term]; + const fastCurieEntry = {iri, terms: irisToTerms[iri]}; + if(iri[0] in fastCurieMap) { + fastCurieMap[iri[0]].push(fastCurieEntry); + } else { + fastCurieMap[iri[0]] = [fastCurieEntry]; + } + } + } else if(!isKeyword && !mapping._termHasColon) { + // add IRI to term match + irisToTerms[iri].push(term); + } + + // add new entry + if(!entry[container]) { + entry[container] = { + '@language': {}, + '@type': {}, + '@any': {} + }; + } + entry = entry[container]; + _addPreferredTerm(term, entry['@any'], '@none'); + + if(mapping.reverse) { + // term is preferred for values using @reverse + _addPreferredTerm(term, entry['@type'], '@reverse'); + } else if(mapping['@type'] === '@none') { + _addPreferredTerm(term, entry['@any'], '@none'); + _addPreferredTerm(term, entry['@language'], '@none'); + _addPreferredTerm(term, entry['@type'], '@none'); + } else if('@type' in mapping) { + // term is preferred for values using specific type + _addPreferredTerm(term, entry['@type'], mapping['@type']); + } else if('@language' in mapping && '@direction' in mapping) { + // term is preferred for values using specific language and direction + const language = mapping['@language']; + const direction = mapping['@direction']; + if(language && direction) { + _addPreferredTerm(term, entry['@language'], + `${language}_${direction}`.toLowerCase()); + } else if(language) { + _addPreferredTerm(term, entry['@language'], language.toLowerCase()); + } else if(direction) { + _addPreferredTerm(term, entry['@language'], `_${direction}`); + } else { + _addPreferredTerm(term, entry['@language'], '@null'); + } + } else if('@language' in mapping) { + _addPreferredTerm(term, entry['@language'], + (mapping['@language'] || '@null').toLowerCase()); + } else if('@direction' in mapping) { + if(mapping['@direction']) { + _addPreferredTerm(term, entry['@language'], + `_${mapping['@direction']}`); + } else { + _addPreferredTerm(term, entry['@language'], '@none'); + } + } else if(defaultDirection) { + _addPreferredTerm(term, entry['@language'], `_${defaultDirection}`); + _addPreferredTerm(term, entry['@language'], '@none'); + _addPreferredTerm(term, entry['@type'], '@none'); + } else { + // add entries for no type and no language + _addPreferredTerm(term, entry['@language'], defaultLanguage); + _addPreferredTerm(term, entry['@language'], '@none'); + _addPreferredTerm(term, entry['@type'], '@none'); + } + } + } + + // build fast CURIE map + for(const key in fastCurieMap) { + _buildIriMap(fastCurieMap, key, 1); + } + + return inverse; + } + + /** + * Runs a recursive algorithm to build a lookup map for quickly finding + * potential CURIEs. + * + * @param iriMap the map to build. + * @param key the current key in the map to work on. + * @param idx the index into the IRI to compare. + */ + function _buildIriMap(iriMap, key, idx) { + const entries = iriMap[key]; + const next = iriMap[key] = {}; + + let iri; + let letter; + for(const entry of entries) { + iri = entry.iri; + if(idx >= iri.length) { + letter = ''; + } else { + letter = iri[idx]; + } + if(letter in next) { + next[letter].push(entry); + } else { + next[letter] = [entry]; + } + } + + for(const key in next) { + if(key === '') { + continue; + } + _buildIriMap(next, key, idx + 1); + } + } + + /** + * Adds the term for the given entry if not already added. + * + * @param term the term to add. + * @param entry the inverse context typeOrLanguage entry to add to. + * @param typeOrLanguageValue the key in the entry to add to. + */ + function _addPreferredTerm(term, entry, typeOrLanguageValue) { + if(!entry.hasOwnProperty(typeOrLanguageValue)) { + entry[typeOrLanguageValue] = term; + } + } + + /** + * Clones an active context, creating a child active context. + * + * @return a clone (child) of the active context. + */ + function _cloneActiveContext() { + const child = {}; + child.mappings = util.clone(this.mappings); + child.clone = this.clone; + child.inverse = null; + child.getInverse = this.getInverse; + child.protected = util.clone(this.protected); + if(this.previousContext) { + child.previousContext = this.previousContext.clone(); + } + child.revertToPreviousContext = this.revertToPreviousContext; + if('@base' in this) { + child['@base'] = this['@base']; + } + if('@language' in this) { + child['@language'] = this['@language']; + } + if('@vocab' in this) { + child['@vocab'] = this['@vocab']; + } + return child; + } + + /** + * Reverts any type-scoped context in this active context to the previous + * context. + */ + function _revertToPreviousContext() { + if(!this.previousContext) { + return this; + } + return this.previousContext.clone(); + } +}; + +/** + * Gets the value for the given active context key and type, null if none is + * set or undefined if none is set and type is '@context'. + * + * @param ctx the active context. + * @param key the context key. + * @param [type] the type of value to get (eg: '@id', '@type'), if not + * specified gets the entire entry for a key, null if not found. + * + * @return the value, null, or undefined. + */ +api.getContextValue = (ctx, key, type) => { + // invalid key + if(key === null) { + if(type === '@context') { + return undefined; + } + return null; + } + + // get specific entry information + if(ctx.mappings.has(key)) { + const entry = ctx.mappings.get(key); + + if(_isUndefined(type)) { + // return whole entry + return entry; + } + if(entry.hasOwnProperty(type)) { + // return entry value for type + return entry[type]; + } + } + + // get default language + if(type === '@language' && type in ctx) { + return ctx[type]; + } + + // get default direction + if(type === '@direction' && type in ctx) { + return ctx[type]; + } + + if(type === '@context') { + return undefined; + } + return null; +}; + +/** + * Processing Mode check. + * + * @param activeCtx the current active context. + * @param version the string or numeric version to check. + * + * @return boolean. + */ +api.processingMode = (activeCtx, version) => { + if(version.toString() >= '1.1') { + return !activeCtx.processingMode || + activeCtx.processingMode >= 'json-ld-' + version.toString(); + } else { + return activeCtx.processingMode === 'json-ld-1.0'; + } +}; + +/** + * Returns whether or not the given value is a keyword. + * + * @param v the value to check. + * + * @return true if the value is a keyword, false if not. + */ +api.isKeyword = v => { + if(!_isString(v) || v[0] !== '@') { + return false; + } + switch(v) { + case '@base': + case '@container': + case '@context': + case '@default': + case '@direction': + case '@embed': + case '@explicit': + case '@graph': + case '@id': + case '@included': + case '@index': + case '@json': + case '@language': + case '@list': + case '@nest': + case '@none': + case '@omitDefault': + case '@prefix': + case '@preserve': + case '@protected': + case '@requireAll': + case '@reverse': + case '@set': + case '@type': + case '@value': + case '@version': + case '@vocab': + return true; + } + return false; +}; + +function _deepCompare(x1, x2) { + // compare `null` or primitive types directly + if((!(x1 && typeof x1 === 'object')) || + (!(x2 && typeof x2 === 'object'))) { + return x1 === x2; + } + // x1 and x2 are objects (also potentially arrays) + const x1Array = Array.isArray(x1); + if(x1Array !== Array.isArray(x2)) { + return false; + } + if(x1Array) { + if(x1.length !== x2.length) { + return false; + } + for(let i = 0; i < x1.length; ++i) { + if(!_deepCompare(x1[i], x2[i])) { + return false; + } + } + return true; + } + // x1 and x2 are non-array objects + const k1s = Object.keys(x1); + const k2s = Object.keys(x2); + if(k1s.length !== k2s.length) { + return false; + } + for(const k1 in x1) { + let v1 = x1[k1]; + let v2 = x2[k1]; + // special case: `@container` can be in any order + if(k1 === '@container') { + if(Array.isArray(v1) && Array.isArray(v2)) { + v1 = v1.slice().sort(); + v2 = v2.slice().sort(); + } + } + if(!_deepCompare(v1, v2)) { + return false; + } + } + return true; +} + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/documentLoaders/xhr.js" +/*!********************************************************!*\ + !*** ./node_modules/jsonld/lib/documentLoaders/xhr.js ***! + \********************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const {parseLinkHeader, buildHeaders} = __webpack_require__(/*! ../util */ "./node_modules/jsonld/lib/util.js"); +const {LINK_HEADER_CONTEXT} = __webpack_require__(/*! ../constants */ "./node_modules/jsonld/lib/constants.js"); +const JsonLdError = __webpack_require__(/*! ../JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); +const RequestQueue = __webpack_require__(/*! ../RequestQueue */ "./node_modules/jsonld/lib/RequestQueue.js"); +const {prependBase} = __webpack_require__(/*! ../url */ "./node_modules/jsonld/lib/url.js"); + +const REGEX_LINK_HEADER = /(^|(\r\n))link:/i; + +/** + * Creates a built-in XMLHttpRequest document loader. + * + * @param options the options to use: + * secure: require all URLs to use HTTPS. + * headers: an object (map) of headers which will be passed as request + * headers for the requested document. Accept is not allowed. + * [xhr]: the XMLHttpRequest API to use. + * + * @return the XMLHttpRequest document loader. + */ +module.exports = ({ + secure, + headers = {}, + xhr +} = {headers: {}}) => { + headers = buildHeaders(headers); + const queue = new RequestQueue(); + return queue.wrapLoader(loader); + + async function loader(url) { + if(url.indexOf('http:') !== 0 && url.indexOf('https:') !== 0) { + throw new JsonLdError( + 'URL could not be dereferenced; only "http" and "https" URLs are ' + + 'supported.', + 'jsonld.InvalidUrl', {code: 'loading document failed', url}); + } + if(secure && url.indexOf('https') !== 0) { + throw new JsonLdError( + 'URL could not be dereferenced; secure mode is enabled and ' + + 'the URL\'s scheme is not "https".', + 'jsonld.InvalidUrl', {code: 'loading document failed', url}); + } + + let req; + try { + req = await _get(xhr, url, headers); + } catch(e) { + throw new JsonLdError( + 'URL could not be dereferenced, an error occurred.', + 'jsonld.LoadDocumentError', + {code: 'loading document failed', url, cause: e}); + } + + if(req.status >= 400) { + throw new JsonLdError( + 'URL could not be dereferenced: ' + req.statusText, + 'jsonld.LoadDocumentError', { + code: 'loading document failed', + url, + httpStatusCode: req.status + }); + } + + let doc = {contextUrl: null, documentUrl: url, document: req.response}; + let alternate = null; + + // handle Link Header (avoid unsafe header warning by existence testing) + const contentType = req.getResponseHeader('Content-Type'); + let linkHeader; + if(REGEX_LINK_HEADER.test(req.getAllResponseHeaders())) { + linkHeader = req.getResponseHeader('Link'); + } + if(linkHeader && contentType !== 'application/ld+json') { + // only 1 related link header permitted + const linkHeaders = parseLinkHeader(linkHeader); + const linkedContext = linkHeaders[LINK_HEADER_CONTEXT]; + if(Array.isArray(linkedContext)) { + throw new JsonLdError( + 'URL could not be dereferenced, it has more than one ' + + 'associated HTTP Link Header.', + 'jsonld.InvalidUrl', + {code: 'multiple context link headers', url}); + } + if(linkedContext) { + doc.contextUrl = linkedContext.target; + } + + // "alternate" link header is a redirect + alternate = linkHeaders.alternate; + if(alternate && + alternate.type == 'application/ld+json' && + !(contentType || '').match(/^application\/(\w*\+)?json$/)) { + doc = await loader(prependBase(url, alternate.target)); + } + } + + return doc; + } +}; + +function _get(xhr, url, headers) { + xhr = xhr || XMLHttpRequest; + const req = new xhr(); + return new Promise((resolve, reject) => { + req.onload = () => resolve(req); + req.onerror = err => reject(err); + req.open('GET', url, true); + for(const k in headers) { + req.setRequestHeader(k, headers[k]); + } + req.send(); + }); +} + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/events.js" +/*!*******************************************!*\ + !*** ./node_modules/jsonld/lib/events.js ***! + \*******************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2020 Digital Bazaar, Inc. All rights reserved. + */ + + +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); + +const { + isArray: _isArray +} = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const { + asArray: _asArray +} = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); + +const api = {}; +module.exports = api; + +// default handler, store as null or an array +// exposed to allow fast external pre-handleEvent() checks +api.defaultEventHandler = null; + +/** + * Setup event handler. + * + * Return an array event handler constructed from an optional safe mode + * handler, an optional options event handler, and an optional default handler. + * + * @param {object} options - processing options + * {function|object|array} [eventHandler] - an event handler. + * + * @return an array event handler. + */ +api.setupEventHandler = ({options = {}}) => { + // build in priority order + const eventHandler = [].concat( + options.safe ? api.safeEventHandler : [], + options.eventHandler ? _asArray(options.eventHandler) : [], + api.defaultEventHandler ? api.defaultEventHandler : [] + ); + // null if no handlers + return eventHandler.length === 0 ? null : eventHandler; +}; + +/** + * Handle an event. + * + * Top level APIs have a common 'eventHandler' option. This option can be a + * function, array of functions, object mapping event.code to functions (with a + * default to call next()), or any combination of such handlers. Handlers will + * be called with an object with an 'event' entry and a 'next' function. Custom + * handlers should process the event as appropriate. The 'next()' function + * should be called to let the next handler process the event. + * + * NOTE: Only call this function if options.eventHandler is set and is an + * array of hanlers. This is an optimization. Callers are expected to check + * for an event handler before constructing events and calling this function. + * + * @param {object} event - event structure: + * {string} code - event code + * {string} level - severity level, one of: ['warning'] + * {string} message - human readable message + * {object} details - event specific details + * @param {object} options - processing options + * {array} eventHandler - an event handler array. + */ +api.handleEvent = ({ + event, + options +}) => { + _handle({event, handlers: options.eventHandler}); +}; + +function _handle({event, handlers}) { + let doNext = true; + for(let i = 0; doNext && i < handlers.length; ++i) { + doNext = false; + const handler = handlers[i]; + if(_isArray(handler)) { + doNext = _handle({event, handlers: handler}); + } else if(typeof handler === 'function') { + handler({event, next: () => { + doNext = true; + }}); + } else if(typeof handler === 'object') { + if(event.code in handler) { + handler[event.code]({event, next: () => { + doNext = true; + }}); + } else { + doNext = true; + } + } else { + throw new JsonLdError( + 'Invalid event handler.', + 'jsonld.InvalidEventHandler', + {event}); + } + } + return doNext; +} + +const _notSafeEventCodes = new Set([ + 'empty object', + 'free-floating scalar', + 'invalid @language value', + 'invalid property', + // NOTE: spec edge case + 'null @id value', + 'null @value value', + 'object with only @id', + 'object with only @language', + 'object with only @list', + 'object with only @value', + 'relative @id reference', + 'relative @type reference', + 'relative @vocab reference', + 'reserved @id value', + 'reserved @reverse value', + 'reserved term', + // toRDF + 'blank node predicate', + 'relative graph reference', + 'relative object reference', + 'relative predicate reference', + 'relative subject reference', + // toRDF / fromRDF + 'rdfDirection not set' +]); + +// safe handler that rejects unsafe warning conditions +api.safeEventHandler = function safeEventHandler({event, next}) { + // fail on all unsafe warnings + if(event.level === 'warning' && _notSafeEventCodes.has(event.code)) { + throw new JsonLdError( + 'Safe mode validation error.', + 'jsonld.ValidationError', + {event} + ); + } + next(); +}; + +// logs all events and continues +api.logEventHandler = function logEventHandler({event, next}) { + console.log(`EVENT: ${event.message}`, {event}); + next(); +}; + +// log 'warning' level events +api.logWarningEventHandler = function logWarningEventHandler({event, next}) { + if(event.level === 'warning') { + console.warn(`WARNING: ${event.message}`, {event}); + } + next(); +}; + +// fallback to throw errors for any unhandled events +api.unhandledEventHandler = function unhandledEventHandler({event}) { + throw new JsonLdError( + 'No handler for event.', + 'jsonld.UnhandledEvent', + {event} + ); +}; + +/** + * Set default event handler. + * + * By default, all event are unhandled. It is recommended to pass in an + * eventHandler into each call. However, this call allows using a default + * eventHandler when one is not otherwise provided. + * + * @param {object} options - default handler options: + * {function|object|array} eventHandler - a default event handler. + * falsey to unset. + */ +api.setDefaultEventHandler = function({eventHandler} = {}) { + api.defaultEventHandler = eventHandler ? _asArray(eventHandler) : null; +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/expand.js" +/*!*******************************************!*\ + !*** ./node_modules/jsonld/lib/expand.js ***! + \*******************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); + +const { + isArray: _isArray, + isObject: _isObject, + isEmptyObject: _isEmptyObject, + isString: _isString, + isUndefined: _isUndefined +} = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const { + isList: _isList, + isValue: _isValue, + isGraph: _isGraph, + isSubject: _isSubject +} = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); + +const { + expandIri: _expandIri, + getContextValue: _getContextValue, + isKeyword: _isKeyword, + process: _processContext, + processingMode: _processingMode +} = __webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js"); + +const { + isAbsolute: _isAbsoluteIri +} = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); + +const { + REGEX_BCP47, + REGEX_KEYWORD, + addValue: _addValue, + asArray: _asArray, + getValues: _getValues, + validateTypeValue: _validateTypeValue +} = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); + +const { + handleEvent: _handleEvent +} = __webpack_require__(/*! ./events */ "./node_modules/jsonld/lib/events.js"); + +const api = {}; +module.exports = api; + +/** + * Recursively expands an element using the given context. Any context in + * the element will be removed. All context URLs must have been retrieved + * before calling this method. + * + * @param activeCtx the context to use. + * @param activeProperty the property for the element, null for none. + * @param element the element to expand. + * @param options the expansion options. + * @param insideList true if the element is a list, false if not. + * @param insideIndex true if the element is inside an index container, + * false if not. + * @param typeScopedContext an optional type-scoped active context for + * expanding values of nodes that were expressed according to + * a type-scoped context. + * + * @return a Promise that resolves to the expanded value. + */ +api.expand = async ({ + activeCtx, + activeProperty = null, + element, + options = {}, + insideList = false, + insideIndex = false, + typeScopedContext = null +}) => { + // nothing to expand + if(element === null || element === undefined) { + return null; + } + + // disable framing if activeProperty is @default + if(activeProperty === '@default') { + options = Object.assign({}, options, {isFrame: false}); + } + + if(!_isArray(element) && !_isObject(element)) { + // drop free-floating scalars that are not in lists + if(!insideList && (activeProperty === null || + _expandIri(activeCtx, activeProperty, {vocab: true}, + options) === '@graph')) { + // FIXME + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'free-floating scalar', + level: 'warning', + message: 'Dropping free-floating scalar not in a list.', + details: { + value: element + //activeProperty + //insideList + } + }, + options + }); + } + return null; + } + + // expand element according to value expansion rules + return _expandValue({activeCtx, activeProperty, value: element, options}); + } + + // recursively expand array + if(_isArray(element)) { + let rval = []; + const container = _getContextValue( + activeCtx, activeProperty, '@container') || []; + insideList = insideList || container.includes('@list'); + for(let i = 0; i < element.length; ++i) { + // expand element + let e = await api.expand({ + activeCtx, + activeProperty, + element: element[i], + options, + insideIndex, + typeScopedContext + }); + if(insideList && _isArray(e)) { + e = {'@list': e}; + } + + if(e === null) { + // FIXME: add debug event? + //unmappedValue: element[i], + //activeProperty, + //parent: element, + //index: i, + //expandedParent: rval, + //insideList + + // NOTE: no-value events emitted at calling sites as needed + continue; + } + + if(_isArray(e)) { + rval = rval.concat(e); + } else { + rval.push(e); + } + } + return rval; + } + + // recursively expand object: + + // first, expand the active property + const expandedActiveProperty = _expandIri( + activeCtx, activeProperty, {vocab: true}, options); + + // Get any property-scoped context for activeProperty + const propertyScopedCtx = + _getContextValue(activeCtx, activeProperty, '@context'); + + // second, determine if any type-scoped context should be reverted; it + // should only be reverted when the following are all true: + // 1. `element` is not a value or subject reference + // 2. `insideIndex` is false + typeScopedContext = typeScopedContext || + (activeCtx.previousContext ? activeCtx : null); + let keys = Object.keys(element).sort(); + let mustRevert = !insideIndex; + if(mustRevert && typeScopedContext && keys.length <= 2 && + !keys.includes('@context')) { + for(const key of keys) { + const expandedProperty = _expandIri( + typeScopedContext, key, {vocab: true}, options); + if(expandedProperty === '@value') { + // value found, ensure type-scoped context is used to expand it + mustRevert = false; + activeCtx = typeScopedContext; + break; + } + if(expandedProperty === '@id' && keys.length === 1) { + // subject reference found, do not revert + mustRevert = false; + break; + } + } + } + + if(mustRevert) { + // revert type scoped context + activeCtx = activeCtx.revertToPreviousContext(); + } + + // apply property-scoped context after reverting term-scoped context + if(!_isUndefined(propertyScopedCtx)) { + activeCtx = await _processContext({ + activeCtx, + localCtx: propertyScopedCtx, + propagate: true, + overrideProtected: true, + options + }); + } + + // if element has a context, process it + if('@context' in element) { + activeCtx = await _processContext( + {activeCtx, localCtx: element['@context'], options}); + } + + // set the type-scoped context to the context on input, for use later + typeScopedContext = activeCtx; + + // Remember the first key found expanding to @type + let typeKey = null; + + // look for scoped contexts on `@type` + for(const key of keys) { + const expandedProperty = _expandIri(activeCtx, key, {vocab: true}, options); + if(expandedProperty === '@type') { + // set scoped contexts from @type + // avoid sorting if possible + typeKey = typeKey || key; + const value = element[key]; + const types = + Array.isArray(value) ? + (value.length > 1 ? value.slice().sort() : value) : [value]; + for(const type of types) { + const ctx = _getContextValue(typeScopedContext, type, '@context'); + if(!_isUndefined(ctx)) { + activeCtx = await _processContext({ + activeCtx, + localCtx: ctx, + options, + propagate: false + }); + } + } + } + } + + // process each key and value in element, ignoring @nest content + let rval = {}; + await _expandObject({ + activeCtx, + activeProperty, + expandedActiveProperty, + element, + expandedParent: rval, + options, + insideList, + typeKey, + typeScopedContext + }); + + // get property count on expanded output + keys = Object.keys(rval); + let count = keys.length; + + if('@value' in rval) { + // @value must only have @language or @type + if('@type' in rval && ('@language' in rval || '@direction' in rval)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an element containing "@value" may not ' + + 'contain both "@type" and either "@language" or "@direction".', + 'jsonld.SyntaxError', {code: 'invalid value object', element: rval}); + } + let validCount = count - 1; + if('@type' in rval) { + validCount -= 1; + } + if('@index' in rval) { + validCount -= 1; + } + if('@language' in rval) { + validCount -= 1; + } + if('@direction' in rval) { + validCount -= 1; + } + if(validCount !== 0) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an element containing "@value" may only ' + + 'have an "@index" property and either "@type" ' + + 'or either or both "@language" or "@direction".', + 'jsonld.SyntaxError', {code: 'invalid value object', element: rval}); + } + const values = rval['@value'] === null ? [] : _asArray(rval['@value']); + const types = _getValues(rval, '@type'); + + // drop null @values + if(_processingMode(activeCtx, 1.1) && types.includes('@json') && + types.length === 1) { + // Any value of @value is okay if @type: @json + } else if(values.length === 0) { + // FIXME + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'null @value value', + level: 'warning', + message: 'Dropping null @value value.', + details: { + value: rval + } + }, + options + }); + } + rval = null; + } else if(!values.every(v => (_isString(v) || _isEmptyObject(v))) && + '@language' in rval) { + // if @language is present, @value must be a string + throw new JsonLdError( + 'Invalid JSON-LD syntax; only strings may be language-tagged.', + 'jsonld.SyntaxError', + {code: 'invalid language-tagged value', element: rval}); + } else if(!types.every(t => + (_isAbsoluteIri(t) && !(_isString(t) && t.indexOf('_:') === 0) || + _isEmptyObject(t)))) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; an element containing "@value" and "@type" ' + + 'must have an absolute IRI for the value of "@type".', + 'jsonld.SyntaxError', {code: 'invalid typed value', element: rval}); + } + } else if('@type' in rval && !_isArray(rval['@type'])) { + // convert @type to an array + rval['@type'] = [rval['@type']]; + } else if('@set' in rval || '@list' in rval) { + // handle @set and @list + if(count > 1 && !(count === 2 && '@index' in rval)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; if an element has the property "@set" ' + + 'or "@list", then it can have at most one other property that is ' + + '"@index".', 'jsonld.SyntaxError', + {code: 'invalid set or list object', element: rval}); + } + // optimize away @set + if('@set' in rval) { + rval = rval['@set']; + keys = Object.keys(rval); + count = keys.length; + } + } else if(count === 1 && '@language' in rval) { + // drop objects with only @language + // FIXME + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'object with only @language', + level: 'warning', + message: 'Dropping object with only @language.', + details: { + value: rval + } + }, + options + }); + } + rval = null; + } + + // drop certain top-level objects that do not occur in lists + if(_isObject(rval) && + !options.keepFreeFloatingNodes && !insideList && + (activeProperty === null || + expandedActiveProperty === '@graph' || + (_getContextValue(activeCtx, activeProperty, '@container') || []) + .includes('@graph') + )) { + // drop empty object, top-level @value/@list, or object with only @id + rval = _dropUnsafeObject({value: rval, count, options}); + } + + return rval; +}; + +/** + * Drop empty object, top-level @value/@list, or object with only @id + * + * @param value Value to check. + * @param count Number of properties in object. + * @param options The expansion options. + * + * @return null if dropped, value otherwise. + */ +function _dropUnsafeObject({ + value, + count, + options +}) { + if(count === 0 || '@value' in value || '@list' in value || + (count === 1 && '@id' in value)) { + // FIXME + if(options.eventHandler) { + // FIXME: one event or diff event for empty, @v/@l, {@id}? + let code; + let message; + if(count === 0) { + code = 'empty object'; + message = 'Dropping empty object.'; + } else if('@value' in value) { + code = 'object with only @value'; + message = 'Dropping object with only @value.'; + } else if('@list' in value) { + code = 'object with only @list'; + message = 'Dropping object with only @list.'; + } else if(count === 1 && '@id' in value) { + code = 'object with only @id'; + message = 'Dropping object with only @id.'; + } + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code, + level: 'warning', + message, + details: { + value + } + }, + options + }); + } + return null; + } + return value; +} + +/** + * Expand each key and value of element adding to result + * + * @param activeCtx the context to use. + * @param activeProperty the property for the element. + * @param expandedActiveProperty the expansion of activeProperty + * @param element the element to expand. + * @param expandedParent the expanded result into which to add values. + * @param options the expansion options. + * @param insideList true if the element is a list, false if not. + * @param typeKey first key found expanding to @type. + * @param typeScopedContext the context before reverting. + */ +async function _expandObject({ + activeCtx, + activeProperty, + expandedActiveProperty, + element, + expandedParent, + options = {}, + insideList, + typeKey, + typeScopedContext +}) { + const keys = Object.keys(element).sort(); + const nests = []; + let unexpandedValue; + + // Figure out if this is the type for a JSON literal + const isJsonType = element[typeKey] && + _expandIri(activeCtx, + (_isArray(element[typeKey]) ? element[typeKey][0] : element[typeKey]), + {vocab: true}, { + ...options, + typeExpansion: true + }) === '@json'; + + for(const key of keys) { + let value = element[key]; + let expandedValue; + + // skip @context + if(key === '@context') { + continue; + } + + // expand property + const expandedProperty = _expandIri(activeCtx, key, {vocab: true}, options); + + // drop non-absolute IRI keys that aren't keywords + if(expandedProperty === null || + !(_isAbsoluteIri(expandedProperty) || _isKeyword(expandedProperty))) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'invalid property', + level: 'warning', + message: 'Dropping property that did not expand into an ' + + 'absolute IRI or keyword.', + details: { + property: key, + expandedProperty + } + }, + options + }); + } + continue; + } + + if(_isKeyword(expandedProperty)) { + if(expandedActiveProperty === '@reverse') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a keyword cannot be used as a @reverse ' + + 'property.', 'jsonld.SyntaxError', + {code: 'invalid reverse property map', value}); + } + if(expandedProperty in expandedParent && + expandedProperty !== '@included' && + expandedProperty !== '@type') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; colliding keywords detected.', + 'jsonld.SyntaxError', + {code: 'colliding keywords', keyword: expandedProperty}); + } + } + + // syntax error if @id is not a string + if(expandedProperty === '@id') { + if(!_isString(value)) { + if(!options.isFrame) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@id" value must a string.', + 'jsonld.SyntaxError', {code: 'invalid @id value', value}); + } + if(_isObject(value)) { + // empty object is a wildcard + if(!_isEmptyObject(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@id" value an empty object or array ' + + 'of strings, if framing', + 'jsonld.SyntaxError', {code: 'invalid @id value', value}); + } + } else if(_isArray(value)) { + if(!value.every(v => _isString(v))) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@id" value an empty object or array ' + + 'of strings, if framing', + 'jsonld.SyntaxError', {code: 'invalid @id value', value}); + } + } else { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@id" value an empty object or array ' + + 'of strings, if framing', + 'jsonld.SyntaxError', {code: 'invalid @id value', value}); + } + } + + _addValue( + expandedParent, '@id', + _asArray(value).map(v => { + if(_isString(v)) { + const ve = _expandIri(activeCtx, v, {base: true}, options); + if(options.eventHandler) { + if(ve === null) { + // NOTE: spec edge case + // See https://github.com/w3c/json-ld-api/issues/480 + if(v === null) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'null @id value', + level: 'warning', + message: 'Null @id found.', + details: { + id: v + } + }, + options + }); + } else { + // matched KEYWORD regex + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'reserved @id value', + level: 'warning', + message: 'Reserved @id found.', + details: { + id: v + } + }, + options + }); + } + } else if(!_isAbsoluteIri(ve)) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'relative @id reference', + level: 'warning', + message: 'Relative @id reference found.', + details: { + id: v, + expandedId: ve + } + }, + options + }); + } + } + return ve; + } + return v; + }), + {propertyIsArray: options.isFrame}); + continue; + } + + if(expandedProperty === '@type') { + // if framing, can be a default object, but need to expand + // key to determine that + if(_isObject(value)) { + value = Object.fromEntries(Object.entries(value).map(([k, v]) => [ + _expandIri(typeScopedContext, k, {vocab: true}), + _asArray(v).map(vv => + _expandIri(typeScopedContext, vv, {base: true, vocab: true}, + {...options, typeExpansion: true}) + ) + ])); + } + _validateTypeValue(value, options.isFrame); + _addValue( + expandedParent, '@type', + _asArray(value).map(v => { + if(_isString(v)) { + const ve = _expandIri(typeScopedContext, v, + {base: true, vocab: true}, + {...options, typeExpansion: true}); + if(ve !== '@json' && !_isAbsoluteIri(ve)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'relative @type reference', + level: 'warning', + message: 'Relative @type reference found.', + details: { + type: v + } + }, + options + }); + } + } + return ve; + } + return v; + }), + {propertyIsArray: !!options.isFrame}); + continue; + } + + // Included blocks are treated as an array of separate object nodes sharing + // the same referencing active_property. + // For 1.0, it is skipped as are other unknown keywords + if(expandedProperty === '@included' && _processingMode(activeCtx, 1.1)) { + const includedResult = _asArray(await api.expand({ + activeCtx, + activeProperty, + element: value, + options + })); + + // Expanded values must be node objects + if(!includedResult.every(v => _isSubject(v))) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; ' + + 'values of @included must expand to node objects.', + 'jsonld.SyntaxError', {code: 'invalid @included value', value}); + } + + _addValue( + expandedParent, '@included', includedResult, {propertyIsArray: true}); + continue; + } + + // @graph must be an array or an object + if(expandedProperty === '@graph' && + !(_isObject(value) || _isArray(value))) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@graph" value must not be an ' + + 'object or an array.', + 'jsonld.SyntaxError', {code: 'invalid @graph value', value}); + } + + if(expandedProperty === '@value') { + // capture value for later + // "colliding keywords" check prevents this from being set twice + unexpandedValue = value; + if(isJsonType && _processingMode(activeCtx, 1.1)) { + // no coercion to array, and retain all values + expandedParent['@value'] = value; + } else { + _addValue( + expandedParent, '@value', value, {propertyIsArray: options.isFrame}); + } + continue; + } + + // @language must be a string + // it should match BCP47 + if(expandedProperty === '@language') { + if(value === null) { + // drop null @language values, they expand as if they didn't exist + continue; + } + if(!_isString(value) && !options.isFrame) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@language" value must be a string.', + 'jsonld.SyntaxError', + {code: 'invalid language-tagged string', value}); + } + // ensure language value is lowercase + value = _asArray(value).map(v => _isString(v) ? v.toLowerCase() : v); + + // ensure language tag matches BCP47 + for(const language of value) { + if(_isString(language) && !language.match(REGEX_BCP47)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'invalid @language value', + level: 'warning', + message: '@language value must be valid BCP47.', + details: { + language + } + }, + options + }); + } + } + } + + _addValue( + expandedParent, '@language', value, {propertyIsArray: options.isFrame}); + continue; + } + + // @direction must be "ltr" or "rtl" + if(expandedProperty === '@direction') { + if(!_isString(value) && !options.isFrame) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@direction" value must be a string.', + 'jsonld.SyntaxError', + {code: 'invalid base direction', value}); + } + + value = _asArray(value); + + // ensure direction is "ltr" or "rtl" + for(const dir of value) { + if(_isString(dir) && dir !== 'ltr' && dir !== 'rtl') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@direction" must be "ltr" or "rtl".', + 'jsonld.SyntaxError', + {code: 'invalid base direction', value}); + } + } + + _addValue( + expandedParent, '@direction', value, + {propertyIsArray: options.isFrame}); + continue; + } + + // @index must be a string + if(expandedProperty === '@index') { + if(!_isString(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@index" value must be a string.', + 'jsonld.SyntaxError', + {code: 'invalid @index value', value}); + } + _addValue(expandedParent, '@index', value); + continue; + } + + // @reverse must be an object + if(expandedProperty === '@reverse') { + if(!_isObject(value)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@reverse" value must be an object.', + 'jsonld.SyntaxError', {code: 'invalid @reverse value', value}); + } + + expandedValue = await api.expand({ + activeCtx, + activeProperty: '@reverse', + element: value, + options + }); + // properties double-reversed + if('@reverse' in expandedValue) { + for(const property in expandedValue['@reverse']) { + _addValue( + expandedParent, property, expandedValue['@reverse'][property], + {propertyIsArray: true}); + } + } + + // FIXME: can this be merged with code below to simplify? + // merge in all reversed properties + let reverseMap = expandedParent['@reverse'] || null; + for(const property in expandedValue) { + if(property === '@reverse') { + continue; + } + if(reverseMap === null) { + reverseMap = expandedParent['@reverse'] = {}; + } + _addValue(reverseMap, property, [], {propertyIsArray: true}); + const items = expandedValue[property]; + for(let ii = 0; ii < items.length; ++ii) { + const item = items[ii]; + if(_isValue(item) || _isList(item)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@reverse" value must not be a ' + + '@value or an @list.', 'jsonld.SyntaxError', + {code: 'invalid reverse property value', value: expandedValue}); + } + _addValue(reverseMap, property, item, {propertyIsArray: true}); + } + } + + continue; + } + + // nested keys + if(expandedProperty === '@nest') { + nests.push(key); + continue; + } + + // use potential scoped context for key + let termCtx = activeCtx; + const ctx = _getContextValue(activeCtx, key, '@context'); + if(!_isUndefined(ctx)) { + termCtx = await _processContext({ + activeCtx, + localCtx: ctx, + propagate: true, + overrideProtected: true, + options + }); + } + + const container = _getContextValue(activeCtx, key, '@container') || []; + + if(container.includes('@language') && _isObject(value)) { + const direction = _getContextValue(termCtx, key, '@direction'); + // handle language map container (skip if value is not an object) + expandedValue = _expandLanguageMap(termCtx, value, direction, options); + } else if(container.includes('@index') && _isObject(value)) { + // handle index container (skip if value is not an object) + const asGraph = container.includes('@graph'); + const indexKey = _getContextValue(termCtx, key, '@index') || '@index'; + const propertyIndex = indexKey !== '@index' && + _expandIri(activeCtx, indexKey, {vocab: true}, options); + + expandedValue = await _expandIndexMap({ + activeCtx: termCtx, + options, + activeProperty: key, + value, + asGraph, + indexKey, + propertyIndex + }); + } else if(container.includes('@id') && _isObject(value)) { + // handle id container (skip if value is not an object) + const asGraph = container.includes('@graph'); + expandedValue = await _expandIndexMap({ + activeCtx: termCtx, + options, + activeProperty: key, + value, + asGraph, + indexKey: '@id' + }); + } else if(container.includes('@type') && _isObject(value)) { + // handle type container (skip if value is not an object) + expandedValue = await _expandIndexMap({ + // since container is `@type`, revert type scoped context when expanding + activeCtx: termCtx.revertToPreviousContext(), + options, + activeProperty: key, + value, + asGraph: false, + indexKey: '@type' + }); + } else { + // recurse into @list or @set + const isList = expandedProperty === '@list'; + if(isList || expandedProperty === '@set') { + let nextActiveProperty = activeProperty; + if(isList && expandedActiveProperty === '@graph') { + nextActiveProperty = null; + } + expandedValue = await api.expand({ + activeCtx: termCtx, + activeProperty: nextActiveProperty, + element: value, + options, + insideList: isList + }); + } else if( + _getContextValue(activeCtx, key, '@type') === '@json') { + expandedValue = { + '@type': '@json', + '@value': value + }; + } else { + // recursively expand value with key as new active property + expandedValue = await api.expand({ + activeCtx: termCtx, + activeProperty: key, + element: value, + options, + insideList: false + }); + } + } + + // drop null values if property is not @value + if(expandedValue === null && expandedProperty !== '@value') { + // FIXME: event? + //unmappedValue: value, + //expandedProperty, + //key, + continue; + } + + // convert expanded value to @list if container specifies it + if(expandedProperty !== '@list' && !_isList(expandedValue) && + container.includes('@list')) { + // ensure expanded value in @list is an array + expandedValue = {'@list': _asArray(expandedValue)}; + } + + // convert expanded value to @graph if container specifies it + // and value is not, itself, a graph + // index cases handled above + if(container.includes('@graph') && + !container.some(key => key === '@id' || key === '@index')) { + // ensure expanded values are in an array + expandedValue = _asArray(expandedValue); + if(!options.isFrame) { + // drop items if needed + expandedValue = expandedValue.filter(v => { + const count = Object.keys(v).length; + return _dropUnsafeObject({value: v, count, options}) !== null; + }); + } + if(expandedValue.length === 0) { + // all items dropped, skip adding and continue + continue; + } + // convert to graph + expandedValue = expandedValue.map(v => ({'@graph': _asArray(v)})); + } + + // FIXME: can this be merged with code above to simplify? + // merge in reverse properties + if(termCtx.mappings.has(key) && termCtx.mappings.get(key).reverse) { + const reverseMap = + expandedParent['@reverse'] = expandedParent['@reverse'] || {}; + expandedValue = _asArray(expandedValue); + for(let ii = 0; ii < expandedValue.length; ++ii) { + const item = expandedValue[ii]; + if(_isValue(item) || _isList(item)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@reverse" value must not be a ' + + '@value or an @list.', 'jsonld.SyntaxError', + {code: 'invalid reverse property value', value: expandedValue}); + } + _addValue(reverseMap, expandedProperty, item, {propertyIsArray: true}); + } + continue; + } + + // add value for property + // special keywords handled above + _addValue(expandedParent, expandedProperty, expandedValue, { + propertyIsArray: true + }); + } + + // @value must not be an object or an array (unless framing) or if @type is + // @json + if('@value' in expandedParent) { + if(expandedParent['@type'] === '@json' && _processingMode(activeCtx, 1.1)) { + // allow any value, to be verified when the object is fully expanded and + // the @type is @json. + } else if((_isObject(unexpandedValue) || _isArray(unexpandedValue)) && + !options.isFrame) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@value" value must not be an ' + + 'object or an array.', + 'jsonld.SyntaxError', + {code: 'invalid value object value', value: unexpandedValue}); + } + } + + // expand each nested key + for(const key of nests) { + const nestedValues = _isArray(element[key]) ? element[key] : [element[key]]; + for(const nv of nestedValues) { + if(!_isObject(nv) || Object.keys(nv).some(k => + _expandIri(activeCtx, k, {vocab: true}, options) === '@value')) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; nested value must be a node object.', + 'jsonld.SyntaxError', + {code: 'invalid @nest value', value: nv}); + } + await _expandObject({ + activeCtx, + activeProperty, + expandedActiveProperty, + element: nv, + expandedParent, + options, + insideList, + typeScopedContext, + typeKey + }); + } + } +} + +/** + * Expands the given value by using the coercion and keyword rules in the + * given context. + * + * @param activeCtx the active context to use. + * @param activeProperty the active property the value is associated with. + * @param value the value to expand. + * @param {Object} [options] - processing options. + * + * @return the expanded value. + */ +function _expandValue({activeCtx, activeProperty, value, options}) { + // nothing to expand + if(value === null || value === undefined) { + return null; + } + + // special-case expand @id and @type (skips '@id' expansion) + const expandedProperty = _expandIri( + activeCtx, activeProperty, {vocab: true}, options); + if(expandedProperty === '@id') { + return _expandIri(activeCtx, value, {base: true}, options); + } else if(expandedProperty === '@type') { + return _expandIri(activeCtx, value, {vocab: true, base: true}, + {...options, typeExpansion: true}); + } + + // get type definition from context + const type = _getContextValue(activeCtx, activeProperty, '@type'); + + // do @id expansion (automatic for @graph) + if((type === '@id' || expandedProperty === '@graph') && _isString(value)) { + const expandedValue = _expandIri(activeCtx, value, {base: true}, options); + // NOTE: handle spec edge case and avoid invalid {"@id": null} + if(expandedValue === null && value.match(REGEX_KEYWORD)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'reserved @id value', + level: 'warning', + message: 'Reserved @id found.', + details: { + id: activeProperty + } + }, + options + }); + } + } + return {'@id': expandedValue}; + } + // do @id expansion w/vocab + if(type === '@vocab' && _isString(value)) { + return { + '@id': _expandIri(activeCtx, value, {vocab: true, base: true}, options) + }; + } + + // do not expand keyword values + if(_isKeyword(expandedProperty)) { + return value; + } + + const rval = {}; + + if(type && !['@id', '@vocab', '@none'].includes(type)) { + // other type + rval['@type'] = type; + } else if(_isString(value)) { + // check for language tagging for strings + const language = _getContextValue(activeCtx, activeProperty, '@language'); + if(language !== null) { + rval['@language'] = language; + } + const direction = _getContextValue(activeCtx, activeProperty, '@direction'); + if(direction !== null) { + rval['@direction'] = direction; + } + } + // do conversion of values that aren't basic JSON types to strings + if(!['boolean', 'number', 'string'].includes(typeof value)) { + value = value.toString(); + } + rval['@value'] = value; + + return rval; +} + +/** + * Expands a language map. + * + * @param activeCtx the active context to use. + * @param languageMap the language map to expand. + * @param direction the direction to apply to values. + * @param {Object} [options] - processing options. + * + * @return the expanded language map. + */ +function _expandLanguageMap(activeCtx, languageMap, direction, options) { + const rval = []; + const keys = Object.keys(languageMap).sort(); + for(const key of keys) { + const expandedKey = _expandIri(activeCtx, key, {vocab: true}, options); + let val = languageMap[key]; + if(!_isArray(val)) { + val = [val]; + } + for(const item of val) { + if(item === null) { + // null values are allowed (8.5) but ignored (3.1) + continue; + } + if(!_isString(item)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; language map values must be strings.', + 'jsonld.SyntaxError', + {code: 'invalid language map value', languageMap}); + } + const val = {'@value': item}; + if(expandedKey !== '@none') { + if(!key.match(REGEX_BCP47)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'invalid @language value', + level: 'warning', + message: '@language value must be valid BCP47.', + details: { + language: key + } + }, + options + }); + } + } + val['@language'] = key.toLowerCase(); + } + if(direction) { + val['@direction'] = direction; + } + rval.push(val); + } + } + return rval; +} + +async function _expandIndexMap({ + activeCtx, options, activeProperty, value, asGraph, indexKey, propertyIndex +}) { + const rval = []; + const keys = Object.keys(value).sort(); + const isTypeIndex = indexKey === '@type'; + for(let key of keys) { + // if indexKey is @type, there may be a context defined for it + if(isTypeIndex) { + const ctx = _getContextValue(activeCtx, key, '@context'); + if(!_isUndefined(ctx)) { + activeCtx = await _processContext({ + activeCtx, + localCtx: ctx, + propagate: false, + options + }); + } + } + + let val = value[key]; + if(!_isArray(val)) { + val = [val]; + } + + val = await api.expand({ + activeCtx, + activeProperty, + element: val, + options, + insideList: false, + insideIndex: true + }); + + // expand for @type, but also for @none + let expandedKey; + if(propertyIndex) { + if(key === '@none') { + expandedKey = '@none'; + } else { + expandedKey = _expandValue( + {activeCtx, activeProperty: indexKey, value: key, options}); + } + } else { + expandedKey = _expandIri(activeCtx, key, {vocab: true}, options); + } + + if(indexKey === '@id') { + // expand document relative + key = _expandIri(activeCtx, key, {base: true}, options); + } else if(isTypeIndex) { + key = expandedKey; + } + + for(let item of val) { + // If this is also a @graph container, turn items into graphs + if(asGraph && !_isGraph(item)) { + item = {'@graph': [item]}; + } + if(indexKey === '@type') { + if(expandedKey === '@none') { + // ignore @none + } else if(item['@type']) { + item['@type'] = [key].concat(item['@type']); + } else { + item['@type'] = [key]; + } + } else if(_isValue(item) && + !['@language', '@type', '@index'].includes(indexKey)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; Attempt to add illegal key to value ' + + `object: "${indexKey}".`, + 'jsonld.SyntaxError', + {code: 'invalid value object', value: item}); + } else if(propertyIndex) { + // index is a property to be expanded, and values interpreted for that + // property + if(expandedKey !== '@none') { + // expand key as a value + _addValue(item, propertyIndex, expandedKey, { + propertyIsArray: true, + prependValue: true + }); + } + } else if(expandedKey !== '@none' && !(indexKey in item)) { + item[indexKey] = key; + } + rval.push(item); + } + } + return rval; +} + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/flatten.js" +/*!********************************************!*\ + !*** ./node_modules/jsonld/lib/flatten.js ***! + \********************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const { + isSubjectReference: _isSubjectReference +} = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); + +const { + createMergedNodeMap: _createMergedNodeMap +} = __webpack_require__(/*! ./nodeMap */ "./node_modules/jsonld/lib/nodeMap.js"); + +const api = {}; +module.exports = api; + +/** + * Performs JSON-LD flattening. + * + * @param input the expanded JSON-LD to flatten. + * + * @return the flattened output. + */ +api.flatten = input => { + const defaultGraph = _createMergedNodeMap(input); + + // produce flattened output + const flattened = []; + const keys = Object.keys(defaultGraph).sort(); + for(let ki = 0; ki < keys.length; ++ki) { + const node = defaultGraph[keys[ki]]; + // only add full subjects to top-level + if(!_isSubjectReference(node)) { + flattened.push(node); + } + } + return flattened; +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/frame.js" +/*!******************************************!*\ + !*** ./node_modules/jsonld/lib/frame.js ***! + \******************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const {isKeyword} = __webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js"); +const graphTypes = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); +const util = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); +const url = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); +const { + createNodeMap: _createNodeMap, + mergeNodeMapGraphs: _mergeNodeMapGraphs +} = __webpack_require__(/*! ./nodeMap */ "./node_modules/jsonld/lib/nodeMap.js"); + +const api = {}; +module.exports = api; + +/** + * Performs JSON-LD `merged` framing. + * + * @param input the expanded JSON-LD to frame. + * @param frame the expanded JSON-LD frame to use. + * @param options the framing options. + * + * @return the framed output. + */ +api.frameMergedOrDefault = (input, frame, options) => { + // create framing state + const state = { + options, + embedded: false, + graph: '@default', + graphMap: {'@default': {}}, + subjectStack: [], + link: {}, + bnodeMap: {} + }; + + // produce a map of all graphs and name each bnode + // FIXME: currently uses subjects from @merged graph only + const issuer = new util.IdentifierIssuer('_:b'); + _createNodeMap(input, state.graphMap, '@default', issuer); + if(options.merged) { + state.graphMap['@merged'] = _mergeNodeMapGraphs(state.graphMap); + state.graph = '@merged'; + } + state.subjects = state.graphMap[state.graph]; + + // frame the subjects + const framed = []; + api.frame(state, Object.keys(state.subjects).sort(), frame, framed); + + // If pruning blank nodes, find those to prune + if(options.pruneBlankNodeIdentifiers) { + // remove all blank nodes appearing only once, done in compaction + options.bnodesToClear = + Object.keys(state.bnodeMap).filter(id => state.bnodeMap[id].length === 1); + } + + // remove @preserve from results + options.link = {}; + return _cleanupPreserve(framed, options); +}; + +/** + * Frames subjects according to the given frame. + * + * @param state the current framing state. + * @param subjects the subjects to filter. + * @param frame the frame. + * @param parent the parent subject or top-level array. + * @param property the parent property, initialized to null. + */ +api.frame = (state, subjects, frame, parent, property = null) => { + // validate the frame + _validateFrame(frame); + frame = frame[0]; + + // get flags for current frame + const options = state.options; + const flags = { + embed: _getFrameFlag(frame, options, 'embed'), + explicit: _getFrameFlag(frame, options, 'explicit'), + requireAll: _getFrameFlag(frame, options, 'requireAll') + }; + + // get link for current graph + if(!state.link.hasOwnProperty(state.graph)) { + state.link[state.graph] = {}; + } + const link = state.link[state.graph]; + + // filter out subjects that match the frame + const matches = _filterSubjects(state, subjects, frame, flags); + + // add matches to output + const ids = Object.keys(matches).sort(); + for(const id of ids) { + const subject = matches[id]; + + /* Note: In order to treat each top-level match as a compartmentalized + result, clear the unique embedded subjects map when the property is null, + which only occurs at the top-level. */ + if(property === null) { + state.uniqueEmbeds = {[state.graph]: {}}; + } else { + state.uniqueEmbeds[state.graph] = state.uniqueEmbeds[state.graph] || {}; + } + + if(flags.embed === '@link' && id in link) { + // TODO: may want to also match an existing linked subject against + // the current frame ... so different frames could produce different + // subjects that are only shared in-memory when the frames are the same + + // add existing linked subject + _addFrameOutput(parent, property, link[id]); + continue; + } + + // start output for subject + const output = {'@id': id}; + if(id.indexOf('_:') === 0) { + util.addValue(state.bnodeMap, id, output, {propertyIsArray: true}); + } + link[id] = output; + + // validate @embed + if((flags.embed === '@first' || flags.embed === '@last') && state.is11) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; invalid value of @embed.', + 'jsonld.SyntaxError', {code: 'invalid @embed value', frame}); + } + + if(!state.embedded && state.uniqueEmbeds[state.graph].hasOwnProperty(id)) { + // skip adding this node object to the top level, as it was + // already included in another node object + continue; + } + + // if embed is @never or if a circular reference would be created by an + // embed, the subject cannot be embedded, just add the reference; + // note that a circular reference won't occur when the embed flag is + // `@link` as the above check will short-circuit before reaching this point + if(state.embedded && + (flags.embed === '@never' || + _createsCircularReference(subject, state.graph, state.subjectStack))) { + _addFrameOutput(parent, property, output); + continue; + } + + // if only the first (or once) should be embedded + if(state.embedded && + (flags.embed == '@first' || flags.embed == '@once') && + state.uniqueEmbeds[state.graph].hasOwnProperty(id)) { + _addFrameOutput(parent, property, output); + continue; + } + + // if only the last match should be embedded + if(flags.embed === '@last') { + // remove any existing embed + if(id in state.uniqueEmbeds[state.graph]) { + _removeEmbed(state, id); + } + } + + state.uniqueEmbeds[state.graph][id] = {parent, property}; + + // push matching subject onto stack to enable circular embed checks + state.subjectStack.push({subject, graph: state.graph}); + + // subject is also the name of a graph + if(id in state.graphMap) { + let recurse = false; + let subframe = null; + if(!('@graph' in frame)) { + recurse = state.graph !== '@merged'; + subframe = {}; + } else { + subframe = frame['@graph'][0]; + recurse = !(id === '@merged' || id === '@default'); + if(!types.isObject(subframe)) { + subframe = {}; + } + } + + if(recurse) { + // recurse into graph + api.frame( + {...state, graph: id, embedded: false}, + Object.keys(state.graphMap[id]).sort(), [subframe], output, '@graph'); + } + } + + // if frame has @included, recurse over its sub-frame + if('@included' in frame) { + api.frame( + {...state, embedded: false}, + subjects, frame['@included'], output, '@included'); + } + + // iterate over subject properties + for(const prop of Object.keys(subject).sort()) { + // copy keywords to output + if(isKeyword(prop)) { + output[prop] = util.clone(subject[prop]); + + if(prop === '@type') { + // count bnode values of @type + for(const type of subject['@type']) { + if(type.indexOf('_:') === 0) { + util.addValue( + state.bnodeMap, type, output, {propertyIsArray: true}); + } + } + } + continue; + } + + // explicit is on and property isn't in the frame, skip processing + if(flags.explicit && !(prop in frame)) { + continue; + } + + // add objects + for(const o of subject[prop]) { + const subframe = (prop in frame ? + frame[prop] : _createImplicitFrame(flags)); + + // recurse into list + if(graphTypes.isList(o)) { + const subframe = + (frame[prop] && frame[prop][0] && frame[prop][0]['@list']) ? + frame[prop][0]['@list'] : + _createImplicitFrame(flags); + + // add empty list + const list = {'@list': []}; + _addFrameOutput(output, prop, list); + + // add list objects + const src = o['@list']; + for(const oo of src) { + if(graphTypes.isSubjectReference(oo)) { + // recurse into subject reference + api.frame( + {...state, embedded: true}, + [oo['@id']], subframe, list, '@list'); + } else { + // include other values automatically + _addFrameOutput(list, '@list', util.clone(oo)); + } + } + } else if(graphTypes.isSubjectReference(o)) { + // recurse into subject reference + api.frame( + {...state, embedded: true}, + [o['@id']], subframe, output, prop); + } else if(_valueMatch(subframe[0], o)) { + // include other values, if they match + _addFrameOutput(output, prop, util.clone(o)); + } + } + } + + // handle defaults + for(const prop of Object.keys(frame).sort()) { + // skip keywords + if(prop === '@type') { + if(!types.isObject(frame[prop][0]) || + !('@default' in frame[prop][0])) { + continue; + } + // allow through default types + } else if(isKeyword(prop)) { + continue; + } + + // if omit default is off, then include default values for properties + // that appear in the next frame but are not in the matching subject + const next = frame[prop][0] || {}; + const omitDefaultOn = _getFrameFlag(next, options, 'omitDefault'); + if(!omitDefaultOn && !(prop in output)) { + let preserve = '@null'; + if('@default' in next) { + preserve = util.clone(next['@default']); + } + if(!types.isArray(preserve)) { + preserve = [preserve]; + } + output[prop] = [{'@preserve': preserve}]; + } + } + + // if embed reverse values by finding nodes having this subject as a value + // of the associated property + for(const reverseProp of Object.keys(frame['@reverse'] || {}).sort()) { + const subframe = frame['@reverse'][reverseProp]; + for(const subject of Object.keys(state.subjects)) { + const nodeValues = + util.getValues(state.subjects[subject], reverseProp); + if(nodeValues.some(v => v['@id'] === id)) { + // node has property referencing this subject, recurse + output['@reverse'] = output['@reverse'] || {}; + util.addValue( + output['@reverse'], reverseProp, [], {propertyIsArray: true}); + api.frame( + {...state, embedded: true}, + [subject], subframe, output['@reverse'][reverseProp], + property); + } + } + } + + // add output to parent + _addFrameOutput(parent, property, output); + + // pop matching subject from circular ref-checking stack + state.subjectStack.pop(); + } +}; + +/** + * Replace `@null` with `null`, removing it from arrays. + * + * @param input the framed, compacted output. + * @param options the framing options used. + * + * @return the resulting output. + */ +api.cleanupNull = (input, options) => { + // recurse through arrays + if(types.isArray(input)) { + const noNulls = input.map(v => api.cleanupNull(v, options)); + return noNulls.filter(v => v); // removes nulls from array + } + + if(input === '@null') { + return null; + } + + if(types.isObject(input)) { + // handle in-memory linked nodes + if('@id' in input) { + const id = input['@id']; + if(options.link.hasOwnProperty(id)) { + const idx = options.link[id].indexOf(input); + if(idx !== -1) { + // already visited + return options.link[id][idx]; + } + // prevent circular visitation + options.link[id].push(input); + } else { + // prevent circular visitation + options.link[id] = [input]; + } + } + + for(const key in input) { + input[key] = api.cleanupNull(input[key], options); + } + } + return input; +}; + +/** + * Creates an implicit frame when recursing through subject matches. If + * a frame doesn't have an explicit frame for a particular property, then + * a wildcard child frame will be created that uses the same flags that the + * parent frame used. + * + * @param flags the current framing flags. + * + * @return the implicit frame. + */ +function _createImplicitFrame(flags) { + const frame = {}; + for(const key in flags) { + if(flags[key] !== undefined) { + frame['@' + key] = [flags[key]]; + } + } + return [frame]; +} + +/** + * Checks the current subject stack to see if embedding the given subject + * would cause a circular reference. + * + * @param subjectToEmbed the subject to embed. + * @param graph the graph the subject to embed is in. + * @param subjectStack the current stack of subjects. + * + * @return true if a circular reference would be created, false if not. + */ +function _createsCircularReference(subjectToEmbed, graph, subjectStack) { + for(let i = subjectStack.length - 1; i >= 0; --i) { + const subject = subjectStack[i]; + if(subject.graph === graph && + subject.subject['@id'] === subjectToEmbed['@id']) { + return true; + } + } + return false; +} + +/** + * Gets the frame flag value for the given flag name. + * + * @param frame the frame. + * @param options the framing options. + * @param name the flag name. + * + * @return the flag value. + */ +function _getFrameFlag(frame, options, name) { + const flag = '@' + name; + let rval = (flag in frame ? frame[flag][0] : options[name]); + if(name === 'embed') { + // default is "@last" + // backwards-compatibility support for "embed" maps: + // true => "@last" + // false => "@never" + if(rval === true) { + rval = '@once'; + } else if(rval === false) { + rval = '@never'; + } else if(rval !== '@always' && rval !== '@never' && rval !== '@link' && + rval !== '@first' && rval !== '@last' && rval !== '@once') { + throw new JsonLdError( + 'Invalid JSON-LD syntax; invalid value of @embed.', + 'jsonld.SyntaxError', {code: 'invalid @embed value', frame}); + } + } + return rval; +} + +/** + * Validates a JSON-LD frame, throwing an exception if the frame is invalid. + * + * @param frame the frame to validate. + */ +function _validateFrame(frame) { + if(!types.isArray(frame) || frame.length !== 1 || !types.isObject(frame[0])) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; a JSON-LD frame must be a single object.', + 'jsonld.SyntaxError', {frame}); + } + + if('@id' in frame[0]) { + for(const id of util.asArray(frame[0]['@id'])) { + // @id must be wildcard or an IRI + if(!(types.isObject(id) || url.isAbsolute(id)) || + (types.isString(id) && id.indexOf('_:') === 0)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; invalid @id in frame.', + 'jsonld.SyntaxError', {code: 'invalid frame', frame}); + } + } + } + + if('@type' in frame[0]) { + for(const type of util.asArray(frame[0]['@type'])) { + // @type must be wildcard, IRI, or @json + if(!(types.isObject(type) || url.isAbsolute(type) || + (type === '@json')) || + (types.isString(type) && type.indexOf('_:') === 0)) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; invalid @type in frame.', + 'jsonld.SyntaxError', {code: 'invalid frame', frame}); + } + } + } +} + +/** + * Returns a map of all of the subjects that match a parsed frame. + * + * @param state the current framing state. + * @param subjects the set of subjects to filter. + * @param frame the parsed frame. + * @param flags the frame flags. + * + * @return all of the matched subjects. + */ +function _filterSubjects(state, subjects, frame, flags) { + // filter subjects in @id order + const rval = {}; + for(const id of subjects) { + const subject = state.graphMap[state.graph][id]; + if(_filterSubject(state, subject, frame, flags)) { + rval[id] = subject; + } + } + return rval; +} + +/** + * Returns true if the given subject matches the given frame. + * + * Matches either based on explicit type inclusion where the node has any + * type listed in the frame. If the frame has empty types defined matches + * nodes not having a @type. If the frame has a type of {} defined matches + * nodes having any type defined. + * + * Otherwise, does duck typing, where the node must have all of the + * properties defined in the frame. + * + * @param state the current framing state. + * @param subject the subject to check. + * @param frame the frame to check. + * @param flags the frame flags. + * + * @return true if the subject matches, false if not. + */ +function _filterSubject(state, subject, frame, flags) { + // check ducktype + let wildcard = true; + let matchesSome = false; + + for(const key in frame) { + let matchThis = false; + const nodeValues = util.getValues(subject, key); + const isEmpty = util.getValues(frame, key).length === 0; + + if(key === '@id') { + // match on no @id or any matching @id, including wildcard + if(types.isEmptyObject(frame['@id'][0] || {})) { + matchThis = true; + } else if(frame['@id'].length >= 0) { + matchThis = frame['@id'].includes(nodeValues[0]); + } + if(!flags.requireAll) { + return matchThis; + } + } else if(key === '@type') { + // check @type (object value means 'any' type, + // fall through to ducktyping) + wildcard = false; + if(isEmpty) { + if(nodeValues.length > 0) { + // don't match on no @type + return false; + } + matchThis = true; + } else if(frame['@type'].length === 1 && + types.isEmptyObject(frame['@type'][0])) { + // match on wildcard @type if there is a type + matchThis = nodeValues.length > 0; + } else { + // match on a specific @type + for(const type of frame['@type']) { + if(types.isObject(type) && '@default' in type) { + // match on default object + matchThis = true; + } else { + matchThis = matchThis || nodeValues.some(tt => tt === type); + } + } + } + if(!flags.requireAll) { + return matchThis; + } + } else if(isKeyword(key)) { + continue; + } else { + // Force a copy of this frame entry so it can be manipulated + const thisFrame = util.getValues(frame, key)[0]; + let hasDefault = false; + if(thisFrame) { + _validateFrame([thisFrame]); + hasDefault = '@default' in thisFrame; + } + + // no longer a wildcard pattern if frame has any non-keyword properties + wildcard = false; + + // skip, but allow match if node has no value for property, and frame has + // a default value + if(nodeValues.length === 0 && hasDefault) { + continue; + } + + // if frame value is empty, don't match if subject has any value + if(nodeValues.length > 0 && isEmpty) { + return false; + } + + if(thisFrame === undefined) { + // node does not match if values is not empty and the value of property + // in frame is match none. + if(nodeValues.length > 0) { + return false; + } + matchThis = true; + } else { + if(graphTypes.isList(thisFrame)) { + const listValue = thisFrame['@list'][0]; + if(graphTypes.isList(nodeValues[0])) { + const nodeListValues = nodeValues[0]['@list']; + + if(graphTypes.isValue(listValue)) { + // match on any matching value + matchThis = nodeListValues.some(lv => _valueMatch(listValue, lv)); + } else if(graphTypes.isSubject(listValue) || + graphTypes.isSubjectReference(listValue)) { + matchThis = nodeListValues.some(lv => _nodeMatch( + state, listValue, lv, flags)); + } + } + } else if(graphTypes.isValue(thisFrame)) { + matchThis = nodeValues.some(nv => _valueMatch(thisFrame, nv)); + } else if(graphTypes.isSubjectReference(thisFrame)) { + matchThis = + nodeValues.some(nv => _nodeMatch(state, thisFrame, nv, flags)); + } else if(types.isObject(thisFrame)) { + matchThis = nodeValues.length > 0; + } else { + matchThis = false; + } + } + } + + // all non-defaulted values must match if requireAll is set + if(!matchThis && flags.requireAll) { + return false; + } + + matchesSome = matchesSome || matchThis; + } + + // return true if wildcard or subject matches some properties + return wildcard || matchesSome; +} + +/** + * Removes an existing embed. + * + * @param state the current framing state. + * @param id the @id of the embed to remove. + */ +function _removeEmbed(state, id) { + // get existing embed + const embeds = state.uniqueEmbeds[state.graph]; + const embed = embeds[id]; + const parent = embed.parent; + const property = embed.property; + + // create reference to replace embed + const subject = {'@id': id}; + + // remove existing embed + if(types.isArray(parent)) { + // replace subject with reference + for(let i = 0; i < parent.length; ++i) { + if(util.compareValues(parent[i], subject)) { + parent[i] = subject; + break; + } + } + } else { + // replace subject with reference + const useArray = types.isArray(parent[property]); + util.removeValue(parent, property, subject, {propertyIsArray: useArray}); + util.addValue(parent, property, subject, {propertyIsArray: useArray}); + } + + // recursively remove dependent dangling embeds + const removeDependents = id => { + // get embed keys as a separate array to enable deleting keys in map + const ids = Object.keys(embeds); + for(const next of ids) { + if(next in embeds && types.isObject(embeds[next].parent) && + embeds[next].parent['@id'] === id) { + delete embeds[next]; + removeDependents(next); + } + } + }; + removeDependents(id); +} + +/** + * Removes the @preserve keywords from expanded result of framing. + * + * @param input the framed, framed output. + * @param options the framing options used. + * + * @return the resulting output. + */ +function _cleanupPreserve(input, options) { + // recurse through arrays + if(types.isArray(input)) { + return input.map(value => _cleanupPreserve(value, options)); + } + + if(types.isObject(input)) { + // remove @preserve + if('@preserve' in input) { + return input['@preserve'][0]; + } + + // skip @values + if(graphTypes.isValue(input)) { + return input; + } + + // recurse through @lists + if(graphTypes.isList(input)) { + input['@list'] = _cleanupPreserve(input['@list'], options); + return input; + } + + // handle in-memory linked nodes + if('@id' in input) { + const id = input['@id']; + if(options.link.hasOwnProperty(id)) { + const idx = options.link[id].indexOf(input); + if(idx !== -1) { + // already visited + return options.link[id][idx]; + } + // prevent circular visitation + options.link[id].push(input); + } else { + // prevent circular visitation + options.link[id] = [input]; + } + } + + // recurse through properties + for(const prop in input) { + // potentially remove the id, if it is an unreference bnode + if(prop === '@id' && options.bnodesToClear.includes(input[prop])) { + delete input['@id']; + continue; + } + + input[prop] = _cleanupPreserve(input[prop], options); + } + } + return input; +} + +/** + * Adds framing output to the given parent. + * + * @param parent the parent to add to. + * @param property the parent property. + * @param output the output to add. + */ +function _addFrameOutput(parent, property, output) { + if(types.isObject(parent)) { + util.addValue(parent, property, output, {propertyIsArray: true}); + } else { + parent.push(output); + } +} + +/** + * Node matches if it is a node, and matches the pattern as a frame. + * + * @param state the current framing state. + * @param pattern used to match value + * @param value to check + * @param flags the frame flags. + */ +function _nodeMatch(state, pattern, value, flags) { + if(!('@id' in value)) { + return false; + } + const nodeObject = state.subjects[value['@id']]; + return nodeObject && _filterSubject(state, nodeObject, pattern, flags); +} + +/** + * Value matches if it is a value and matches the value pattern + * + * * `pattern` is empty + * * @values are the same, or `pattern[@value]` is a wildcard, and + * * @types are the same or `value[@type]` is not null + * and `pattern[@type]` is `{}`, or `value[@type]` is null + * and `pattern[@type]` is null or `[]`, and + * * @languages are the same or `value[@language]` is not null + * and `pattern[@language]` is `{}`, or `value[@language]` is null + * and `pattern[@language]` is null or `[]`. + * + * @param pattern used to match value + * @param value to check + */ +function _valueMatch(pattern, value) { + const v1 = value['@value']; + const t1 = value['@type']; + const l1 = value['@language']; + const v2 = pattern['@value'] ? + (types.isArray(pattern['@value']) ? + pattern['@value'] : [pattern['@value']]) : + []; + const t2 = pattern['@type'] ? + (types.isArray(pattern['@type']) ? + pattern['@type'] : [pattern['@type']]) : + []; + const l2 = pattern['@language'] ? + (types.isArray(pattern['@language']) ? + pattern['@language'] : [pattern['@language']]) : + []; + + if(v2.length === 0 && t2.length === 0 && l2.length === 0) { + return true; + } + if(!(v2.includes(v1) || types.isEmptyObject(v2[0]))) { + return false; + } + if(!(!t1 && t2.length === 0 || t2.includes(t1) || t1 && + types.isEmptyObject(t2[0]))) { + return false; + } + if(!(!l1 && l2.length === 0 || l2.includes(l1) || l1 && + types.isEmptyObject(l2[0]))) { + return false; + } + return true; +} + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/fromRdf.js" +/*!********************************************!*\ + !*** ./node_modules/jsonld/lib/fromRdf.js ***! + \********************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017-2023 Digital Bazaar, Inc. All rights reserved. + */ + + +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); +const graphTypes = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const { + REGEX_BCP47, + addValue: _addValue +} = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); + +const { + handleEvent: _handleEvent +} = __webpack_require__(/*! ./events */ "./node_modules/jsonld/lib/events.js"); + +// constants +const { + // RDF, + RDF_LIST, + RDF_FIRST, + RDF_REST, + RDF_NIL, + RDF_TYPE, + // RDF_PLAIN_LITERAL, + // RDF_XML_LITERAL, + RDF_JSON_LITERAL, + // RDF_OBJECT, + // RDF_LANGSTRING, + + // XSD, + XSD_BOOLEAN, + XSD_DOUBLE, + XSD_INTEGER, + XSD_STRING, +} = __webpack_require__(/*! ./constants */ "./node_modules/jsonld/lib/constants.js"); + +const api = {}; +module.exports = api; + +/** + * Converts an RDF dataset to JSON-LD. + * + * @param dataset the RDF dataset. + * @param options the RDF serialization options. + * + * @return a Promise that resolves to the JSON-LD output. + */ +api.fromRDF = async ( + dataset, + options +) => { + const { + useRdfType = false, + useNativeTypes = false, + rdfDirection = null + } = options; + // FIXME: use Maps? + const defaultGraph = {}; + const graphMap = {'@default': defaultGraph}; + const referencedOnce = {}; + if(rdfDirection) { + if(rdfDirection === 'compound-literal') { + throw new JsonLdError( + 'Unsupported rdfDirection value.', + 'jsonld.InvalidRdfDirection', + {value: rdfDirection}); + } else if(rdfDirection !== 'i18n-datatype') { + throw new JsonLdError( + 'Unknown rdfDirection value.', + 'jsonld.InvalidRdfDirection', + {value: rdfDirection}); + } + } + + for(const quad of dataset) { + // TODO: change 'name' to 'graph' + const name = (quad.graph.termType === 'DefaultGraph') ? + '@default' : quad.graph.value; + if(!(name in graphMap)) { + graphMap[name] = {}; + } + if(name !== '@default' && !(name in defaultGraph)) { + defaultGraph[name] = {'@id': name}; + } + + const nodeMap = graphMap[name]; + + // get subject, predicate, object + const s = quad.subject.value; + const p = quad.predicate.value; + const o = quad.object; + + if(!(s in nodeMap)) { + nodeMap[s] = {'@id': s}; + } + const node = nodeMap[s]; + + const objectIsNode = o.termType.endsWith('Node'); + if(objectIsNode && !(o.value in nodeMap)) { + nodeMap[o.value] = {'@id': o.value}; + } + + if(p === RDF_TYPE && !useRdfType && objectIsNode) { + _addValue(node, '@type', o.value, {propertyIsArray: true}); + continue; + } + + const value = _RDFToObject(o, useNativeTypes, rdfDirection, options); + _addValue(node, p, value, {propertyIsArray: true}); + + // object may be an RDF list/partial list node but we can't know easily + // until all triples are read + if(objectIsNode) { + if(o.value === RDF_NIL) { + // track rdf:nil uniquely per graph + const object = nodeMap[o.value]; + if(!('usages' in object)) { + object.usages = []; + } + object.usages.push({ + node, + property: p, + value + }); + } else if(o.value in referencedOnce) { + // object referenced more than once + referencedOnce[o.value] = false; + } else { + // keep track of single reference + referencedOnce[o.value] = { + node, + property: p, + value + }; + } + } + } + + /* + for(let name in dataset) { + const graph = dataset[name]; + if(!(name in graphMap)) { + graphMap[name] = {}; + } + if(name !== '@default' && !(name in defaultGraph)) { + defaultGraph[name] = {'@id': name}; + } + const nodeMap = graphMap[name]; + for(let ti = 0; ti < graph.length; ++ti) { + const triple = graph[ti]; + + // get subject, predicate, object + const s = triple.subject.value; + const p = triple.predicate.value; + const o = triple.object; + + if(!(s in nodeMap)) { + nodeMap[s] = {'@id': s}; + } + const node = nodeMap[s]; + + const objectIsId = (o.type === 'IRI' || o.type === 'blank node'); + if(objectIsId && !(o.value in nodeMap)) { + nodeMap[o.value] = {'@id': o.value}; + } + + if(p === RDF_TYPE && !useRdfType && objectIsId) { + _addValue(node, '@type', o.value, {propertyIsArray: true}); + continue; + } + + const value = _RDFToObject(o, useNativeTypes); + _addValue(node, p, value, {propertyIsArray: true}); + + // object may be an RDF list/partial list node but we can't know easily + // until all triples are read + if(objectIsId) { + if(o.value === RDF_NIL) { + // track rdf:nil uniquely per graph + const object = nodeMap[o.value]; + if(!('usages' in object)) { + object.usages = []; + } + object.usages.push({ + node: node, + property: p, + value: value + }); + } else if(o.value in referencedOnce) { + // object referenced more than once + referencedOnce[o.value] = false; + } else { + // keep track of single reference + referencedOnce[o.value] = { + node: node, + property: p, + value: value + }; + } + } + } + }*/ + + // convert linked lists to @list arrays + for(const name in graphMap) { + const graphObject = graphMap[name]; + + // no @lists to be converted, continue + if(!(RDF_NIL in graphObject)) { + continue; + } + + // iterate backwards through each RDF list + const nil = graphObject[RDF_NIL]; + if(!nil.usages) { + continue; + } + for(let usage of nil.usages) { + let node = usage.node; + let property = usage.property; + let head = usage.value; + const list = []; + const listNodes = []; + + // ensure node is a well-formed list node; it must: + // 1. Be referenced only once. + // 2. Have an array for rdf:first that has 1 item. + // 3. Have an array for rdf:rest that has 1 item. + // 4. Have no keys other than: @id, rdf:first, rdf:rest, and, + // optionally, @type where the value is rdf:List. + let nodeKeyCount = Object.keys(node).length; + while(property === RDF_REST && + types.isObject(referencedOnce[node['@id']]) && + types.isArray(node[RDF_FIRST]) && node[RDF_FIRST].length === 1 && + types.isArray(node[RDF_REST]) && node[RDF_REST].length === 1 && + (nodeKeyCount === 3 || + (nodeKeyCount === 4 && types.isArray(node['@type']) && + node['@type'].length === 1 && node['@type'][0] === RDF_LIST))) { + list.push(node[RDF_FIRST][0]); + listNodes.push(node['@id']); + + // get next node, moving backwards through list + usage = referencedOnce[node['@id']]; + node = usage.node; + property = usage.property; + head = usage.value; + nodeKeyCount = Object.keys(node).length; + + // if node is not a blank node, then list head found + if(!graphTypes.isBlankNode(node)) { + break; + } + } + + // transform list into @list object + delete head['@id']; + head['@list'] = list.reverse(); + for(const listNode of listNodes) { + delete graphObject[listNode]; + } + } + + delete nil.usages; + } + + const result = []; + const subjects = Object.keys(defaultGraph).sort(); + for(const subject of subjects) { + const node = defaultGraph[subject]; + if(subject in graphMap) { + const graph = node['@graph'] = []; + const graphObject = graphMap[subject]; + const graphSubjects = Object.keys(graphObject).sort(); + for(const graphSubject of graphSubjects) { + const node = graphObject[graphSubject]; + // only add full subjects to top-level + if(!graphTypes.isSubjectReference(node)) { + graph.push(node); + } + } + } + // only add full subjects to top-level + if(!graphTypes.isSubjectReference(node)) { + result.push(node); + } + } + + return result; +}; + +/** + * Converts an RDF triple object to a JSON-LD object. + * + * @param o the RDF triple object to convert. + * @param useNativeTypes true to output native types, false not to. + * @param rdfDirection text direction mode [null, i18n-datatype] + * @param options top level API options + * + * @return the JSON-LD object. + */ +function _RDFToObject(o, useNativeTypes, rdfDirection, options) { + // convert NamedNode/BlankNode object to JSON-LD + if(o.termType.endsWith('Node')) { + return {'@id': o.value}; + } + + // convert literal to JSON-LD + const rval = {'@value': o.value}; + + // add language + if(o.language) { + if(!o.language.match(REGEX_BCP47)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'invalid @language value', + level: 'warning', + message: '@language value must be valid BCP47.', + details: { + language: o.language + } + }, + options + }); + } + } + rval['@language'] = o.language; + } else { + let type = o.datatype.value; + if(!type) { + type = XSD_STRING; + } + if(type === RDF_JSON_LITERAL) { + type = '@json'; + try { + rval['@value'] = JSON.parse(rval['@value']); + } catch(e) { + throw new JsonLdError( + 'JSON literal could not be parsed.', + 'jsonld.InvalidJsonLiteral', + {code: 'invalid JSON literal', value: rval['@value'], cause: e}); + } + } + // use native types for certain xsd types + if(useNativeTypes) { + if(type === XSD_BOOLEAN) { + if(rval['@value'] === 'true') { + rval['@value'] = true; + } else if(rval['@value'] === 'false') { + rval['@value'] = false; + } + } else if(types.isNumeric(rval['@value'])) { + if(type === XSD_INTEGER) { + const i = parseInt(rval['@value'], 10); + if(i.toFixed(0) === rval['@value']) { + rval['@value'] = i; + } + } else if(type === XSD_DOUBLE) { + rval['@value'] = parseFloat(rval['@value']); + } + } + // do not add native type + if(![XSD_BOOLEAN, XSD_INTEGER, XSD_DOUBLE, XSD_STRING].includes(type)) { + rval['@type'] = type; + } + } else if(rdfDirection === 'i18n-datatype' && + type.startsWith('https://www.w3.org/ns/i18n#')) { + const [, language, direction] = type.split(/[#_]/); + if(language.length > 0) { + rval['@language'] = language; + if(!language.match(REGEX_BCP47)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'invalid @language value', + level: 'warning', + message: '@language value must be valid BCP47.', + details: { + language + } + }, + options + }); + } + } + } + rval['@direction'] = direction; + } else if(type !== XSD_STRING) { + rval['@type'] = type; + } + } + + return rval; +} + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/graphTypes.js" +/*!***********************************************!*\ + !*** ./node_modules/jsonld/lib/graphTypes.js ***! + \***********************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const api = {}; +module.exports = api; + +/** + * Returns true if the given value is a subject with properties. + * + * @param v the value to check. + * + * @return true if the value is a subject with properties, false if not. + */ +api.isSubject = v => { + // Note: A value is a subject if all of these hold true: + // 1. It is an Object. + // 2. It is not a @value, @set, or @list. + // 3. It has more than 1 key OR any existing key is not @id. + if(types.isObject(v) && + !(('@value' in v) || ('@set' in v) || ('@list' in v))) { + const keyCount = Object.keys(v).length; + return (keyCount > 1 || !('@id' in v)); + } + return false; +}; + +/** + * Returns true if the given value is a subject reference. + * + * @param v the value to check. + * + * @return true if the value is a subject reference, false if not. + */ +api.isSubjectReference = v => + // Note: A value is a subject reference if all of these hold true: + // 1. It is an Object. + // 2. It has a single key: @id. + (types.isObject(v) && Object.keys(v).length === 1 && ('@id' in v)); + +/** + * Returns true if the given value is a @value. + * + * @param v the value to check. + * + * @return true if the value is a @value, false if not. + */ +api.isValue = v => + // Note: A value is a @value if all of these hold true: + // 1. It is an Object. + // 2. It has the @value property. + types.isObject(v) && ('@value' in v); + +/** + * Returns true if the given value is a @list. + * + * @param v the value to check. + * + * @return true if the value is a @list, false if not. + */ +api.isList = v => + // Note: A value is a @list if all of these hold true: + // 1. It is an Object. + // 2. It has the @list property. + types.isObject(v) && ('@list' in v); + +/** + * Returns true if the given value is a @graph. + * + * @return true if the value is a @graph, false if not. + */ +api.isGraph = v => { + // Note: A value is a graph if all of these hold true: + // 1. It is an object. + // 2. It has an `@graph` key. + // 3. It may have '@id' or '@index' + return types.isObject(v) && + '@graph' in v && + Object.keys(v) + .filter(key => key !== '@id' && key !== '@index').length === 1; +}; + +/** + * Returns true if the given value is a simple @graph. + * + * @return true if the value is a simple @graph, false if not. + */ +api.isSimpleGraph = v => { + // Note: A value is a simple graph if all of these hold true: + // 1. It is an object. + // 2. It has an `@graph` key. + // 3. It has only 1 key or 2 keys where one of them is `@index`. + return api.isGraph(v) && !('@id' in v); +}; + +/** + * Returns true if the given value is a blank node. + * + * @param v the value to check. + * + * @return true if the value is a blank node, false if not. + */ +api.isBlankNode = v => { + // Note: A value is a blank node if all of these hold true: + // 1. It is an Object. + // 2. If it has an @id key that is not a string OR begins with '_:'. + // 3. It has no keys OR is not a @value, @set, or @list. + if(types.isObject(v)) { + if('@id' in v) { + const id = v['@id']; + return !types.isString(id) || id.indexOf('_:') === 0; + } + return (Object.keys(v).length === 0 || + !(('@value' in v) || ('@set' in v) || ('@list' in v))); + } + return false; +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/jsonld.js" +/*!*******************************************!*\ + !*** ./node_modules/jsonld/lib/jsonld.js ***! + \*******************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +/** + * A JavaScript implementation of the JSON-LD API. + * + * @author Dave Longley + * + * @license BSD 3-Clause License + * Copyright (c) 2011-2022 Digital Bazaar, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of the Digital Bazaar, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +const canonize = __webpack_require__(/*! rdf-canonize */ "./node_modules/jsonld/node_modules/rdf-canonize/index.js"); +const platform = __webpack_require__(/*! ./platform */ "./node_modules/jsonld/lib/platform-browser.js"); +const util = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); +const ContextResolver = __webpack_require__(/*! ./ContextResolver */ "./node_modules/jsonld/lib/ContextResolver.js"); +const IdentifierIssuer = util.IdentifierIssuer; +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); +const LRU = __webpack_require__(/*! lru-cache */ "./node_modules/lru-cache/index.js"); +const NQuads = __webpack_require__(/*! ./NQuads */ "./node_modules/jsonld/lib/NQuads.js"); + +const {expand: _expand} = __webpack_require__(/*! ./expand */ "./node_modules/jsonld/lib/expand.js"); +const {flatten: _flatten} = __webpack_require__(/*! ./flatten */ "./node_modules/jsonld/lib/flatten.js"); +const {fromRDF: _fromRDF} = __webpack_require__(/*! ./fromRdf */ "./node_modules/jsonld/lib/fromRdf.js"); +const {toRDF: _toRDF} = __webpack_require__(/*! ./toRdf */ "./node_modules/jsonld/lib/toRdf.js"); + +const { + frameMergedOrDefault: _frameMergedOrDefault, + cleanupNull: _cleanupNull +} = __webpack_require__(/*! ./frame */ "./node_modules/jsonld/lib/frame.js"); + +const { + isArray: _isArray, + isObject: _isObject, + isString: _isString +} = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const { + isSubjectReference: _isSubjectReference, +} = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); + +const { + expandIri: _expandIri, + getInitialContext: _getInitialContext, + process: _processContext, + processingMode: _processingMode +} = __webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js"); + +const { + compact: _compact, + compactIri: _compactIri +} = __webpack_require__(/*! ./compact */ "./node_modules/jsonld/lib/compact.js"); + +const { + createNodeMap: _createNodeMap, + createMergedNodeMap: _createMergedNodeMap, + mergeNodeMaps: _mergeNodeMaps +} = __webpack_require__(/*! ./nodeMap */ "./node_modules/jsonld/lib/nodeMap.js"); + +const { + logEventHandler: _logEventHandler, + logWarningEventHandler: _logWarningEventHandler, + safeEventHandler: _safeEventHandler, + setDefaultEventHandler: _setDefaultEventHandler, + setupEventHandler: _setupEventHandler, + strictEventHandler: _strictEventHandler, + unhandledEventHandler: _unhandledEventHandler +} = __webpack_require__(/*! ./events */ "./node_modules/jsonld/lib/events.js"); + +/* eslint-disable indent */ +// attaches jsonld API to the given object +const wrapper = function(jsonld) { + +/** Registered RDF dataset parsers hashed by content-type. */ +const _rdfParsers = {}; + +// resolved context cache +// TODO: consider basing max on context size rather than number +const RESOLVED_CONTEXT_CACHE_MAX_SIZE = 100; +const _resolvedContextCache = new LRU({max: RESOLVED_CONTEXT_CACHE_MAX_SIZE}); + +/* Core API */ + +/** + * Performs JSON-LD compaction. + * + * @param input the JSON-LD input to compact. + * @param ctx the context to compact with. + * @param [options] options to use: + * [base] the base IRI to use. + * [compactArrays] true to compact arrays to single values when + * appropriate, false not to (default: true). + * [compactToRelative] true to compact IRIs to be relative to document + * base, false to keep absolute (default: true) + * [graph] true to always output a top-level graph (default: false). + * [expandContext] a context to expand with. + * [skipExpansion] true to assume the input is expanded and skip + * expansion, false not to, defaults to false. Some well-formed + * and safe-mode checks may be omitted. + * [documentLoader(url, options)] the document loader. + * [framing] true if compaction is occuring during a framing operation. + * [safe] true to use safe mode. (default: false) + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the compacted output. + */ +jsonld.compact = async function(input, ctx, options) { + if(arguments.length < 2) { + throw new TypeError('Could not compact, too few arguments.'); + } + + if(ctx === null) { + throw new JsonLdError( + 'The compaction context must not be null.', + 'jsonld.CompactError', {code: 'invalid local context'}); + } + + // nothing to compact + if(input === null) { + return null; + } + + // set default options + options = _setDefaults(options, { + base: _isString(input) ? input : '', + compactArrays: true, + compactToRelative: true, + graph: false, + skipExpansion: false, + link: false, + issuer: new IdentifierIssuer('_:b'), + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + if(options.link) { + // force skip expansion when linking, "link" is not part of the public + // API, it should only be called from framing + options.skipExpansion = true; + } + if(!options.compactToRelative) { + delete options.base; + } + + // expand input + let expanded; + if(options.skipExpansion) { + expanded = input; + } else { + expanded = await jsonld.expand(input, options); + } + + // process context + const activeCtx = await jsonld.processContext( + _getInitialContext(options), ctx, options); + + // do compaction + let compacted = await _compact({ + activeCtx, + element: expanded, + options + }); + + // perform clean up + if(options.compactArrays && !options.graph && _isArray(compacted)) { + if(compacted.length === 1) { + // simplify to a single item + compacted = compacted[0]; + } else if(compacted.length === 0) { + // simplify to an empty object + compacted = {}; + } + } else if(options.graph && _isObject(compacted)) { + // always use array if graph option is on + compacted = [compacted]; + } + + // follow @context key + if(_isObject(ctx) && '@context' in ctx) { + ctx = ctx['@context']; + } + + // build output context + ctx = util.clone(ctx); + if(!_isArray(ctx)) { + ctx = [ctx]; + } + // remove empty contexts + const tmp = ctx; + ctx = []; + for(let i = 0; i < tmp.length; ++i) { + if(!_isObject(tmp[i]) || Object.keys(tmp[i]).length > 0) { + ctx.push(tmp[i]); + } + } + + // remove array if only one context + const hasContext = (ctx.length > 0); + if(ctx.length === 1) { + ctx = ctx[0]; + } + + // add context and/or @graph + if(_isArray(compacted)) { + // use '@graph' keyword + const graphAlias = _compactIri({ + activeCtx, iri: '@graph', relativeTo: {vocab: true} + }); + const graph = compacted; + compacted = {}; + if(hasContext) { + compacted['@context'] = ctx; + } + compacted[graphAlias] = graph; + } else if(_isObject(compacted) && hasContext) { + // reorder keys so @context is first + const graph = compacted; + compacted = {'@context': ctx}; + for(const key in graph) { + compacted[key] = graph[key]; + } + } + + return compacted; +}; + +/** + * Performs JSON-LD expansion. + * + * @param input the JSON-LD input to expand. + * @param [options] the options to use: + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [keepFreeFloatingNodes] true to keep free-floating nodes, + * false not to, defaults to false. + * [documentLoader(url, options)] the document loader. + * [safe] true to use safe mode. (default: false) + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the expanded output. + */ +jsonld.expand = async function(input, options) { + if(arguments.length < 1) { + throw new TypeError('Could not expand, too few arguments.'); + } + + // set default options + options = _setDefaults(options, { + keepFreeFloatingNodes: false, + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + + // build set of objects that may have @contexts to resolve + const toResolve = {}; + + // build set of contexts to process prior to expansion + const contextsToProcess = []; + + // if an `expandContext` has been given ensure it gets resolved + if('expandContext' in options) { + const expandContext = util.clone(options.expandContext); + if(_isObject(expandContext) && '@context' in expandContext) { + toResolve.expandContext = expandContext; + } else { + toResolve.expandContext = {'@context': expandContext}; + } + contextsToProcess.push(toResolve.expandContext); + } + + // if input is a string, attempt to dereference remote document + let defaultBase; + if(!_isString(input)) { + // input is not a URL, do not need to retrieve it first + toResolve.input = util.clone(input); + } else { + // load remote doc + const remoteDoc = await jsonld.get(input, options); + defaultBase = remoteDoc.documentUrl; + toResolve.input = remoteDoc.document; + if(remoteDoc.contextUrl) { + // context included in HTTP link header and must be resolved + toResolve.remoteContext = {'@context': remoteDoc.contextUrl}; + contextsToProcess.push(toResolve.remoteContext); + } + } + + // set default base + if(!('base' in options)) { + options.base = defaultBase || ''; + } + + // process any additional contexts + let activeCtx = _getInitialContext(options); + for(const localCtx of contextsToProcess) { + activeCtx = await _processContext({activeCtx, localCtx, options}); + } + + // expand resolved input + let expanded = await _expand({ + activeCtx, + element: toResolve.input, + options + }); + + // optimize away @graph with no other properties + if(_isObject(expanded) && ('@graph' in expanded) && + Object.keys(expanded).length === 1) { + expanded = expanded['@graph']; + } else if(expanded === null) { + expanded = []; + } + + // normalize to an array + if(!_isArray(expanded)) { + expanded = [expanded]; + } + + return expanded; +}; + +/** + * Performs JSON-LD flattening. + * + * @param input the JSON-LD to flatten. + * @param ctx the context to use to compact the flattened output, or null. + * @param [options] the options to use: + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [documentLoader(url, options)] the document loader. + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the flattened output. + */ +jsonld.flatten = async function(input, ctx, options) { + if(arguments.length < 1) { + return new TypeError('Could not flatten, too few arguments.'); + } + + if(typeof ctx === 'function') { + ctx = null; + } else { + ctx = ctx || null; + } + + // set default options + options = _setDefaults(options, { + base: _isString(input) ? input : '', + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + + // expand input + const expanded = await jsonld.expand(input, options); + + // do flattening + const flattened = _flatten(expanded); + + if(ctx === null) { + // no compaction required + return flattened; + } + + // compact result (force @graph option to true, skip expansion) + options.graph = true; + options.skipExpansion = true; + const compacted = await jsonld.compact(flattened, ctx, options); + + return compacted; +}; + +/** + * Performs JSON-LD framing. + * + * @param input the JSON-LD input to frame. + * @param frame the JSON-LD frame to use. + * @param [options] the framing options. + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [embed] default @embed flag: '@last', '@always', '@never', '@link' + * (default: '@last'). + * [explicit] default @explicit flag (default: false). + * [requireAll] default @requireAll flag (default: true). + * [omitDefault] default @omitDefault flag (default: false). + * [documentLoader(url, options)] the document loader. + * [safe] true to use safe mode. (default: false) + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the framed output. + */ +jsonld.frame = async function(input, frame, options) { + if(arguments.length < 2) { + throw new TypeError('Could not frame, too few arguments.'); + } + + // set default options + options = _setDefaults(options, { + base: _isString(input) ? input : '', + embed: '@once', + explicit: false, + requireAll: false, + omitDefault: false, + bnodesToClear: [], + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + + // if frame is a string, attempt to dereference remote document + if(_isString(frame)) { + // load remote doc + const remoteDoc = await jsonld.get(frame, options); + frame = remoteDoc.document; + + if(remoteDoc.contextUrl) { + // inject link header @context into frame + let ctx = frame['@context']; + if(!ctx) { + ctx = remoteDoc.contextUrl; + } else if(_isArray(ctx)) { + ctx.push(remoteDoc.contextUrl); + } else { + ctx = [ctx, remoteDoc.contextUrl]; + } + frame['@context'] = ctx; + } + } + + const frameContext = frame ? frame['@context'] || {} : {}; + + // process context + const activeCtx = await jsonld.processContext( + _getInitialContext(options), frameContext, options); + + // mode specific defaults + if(!options.hasOwnProperty('omitGraph')) { + options.omitGraph = _processingMode(activeCtx, 1.1); + } + if(!options.hasOwnProperty('pruneBlankNodeIdentifiers')) { + options.pruneBlankNodeIdentifiers = _processingMode(activeCtx, 1.1); + } + + // expand input + const expanded = await jsonld.expand(input, options); + + // expand frame + const opts = {...options}; + opts.isFrame = true; + opts.keepFreeFloatingNodes = true; + const expandedFrame = await jsonld.expand(frame, opts); + + // if the unexpanded frame includes a key expanding to @graph, frame the + // default graph, otherwise, the merged graph + const frameKeys = Object.keys(frame) + .map(key => _expandIri(activeCtx, key, {vocab: true})); + opts.merged = !frameKeys.includes('@graph'); + opts.is11 = _processingMode(activeCtx, 1.1); + + // do framing + const framed = _frameMergedOrDefault(expanded, expandedFrame, opts); + + opts.graph = !options.omitGraph; + opts.skipExpansion = true; + opts.link = {}; + opts.framing = true; + let compacted = await jsonld.compact(framed, frameContext, opts); + + // replace @null with null, compacting arrays + opts.link = {}; + compacted = _cleanupNull(compacted, opts); + + return compacted; +}; + +/** + * **Experimental** + * + * Links a JSON-LD document's nodes in memory. + * + * @param input the JSON-LD document to link. + * @param [ctx] the JSON-LD context to apply. + * @param [options] the options to use: + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [documentLoader(url, options)] the document loader. + * [safe] true to use safe mode. (default: false) + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the linked output. + */ +jsonld.link = async function(input, ctx, options) { + // API matches running frame with a wildcard frame and embed: '@link' + // get arguments + const frame = {}; + if(ctx) { + frame['@context'] = ctx; + } + frame['@embed'] = '@link'; + return jsonld.frame(input, frame, options); +}; + +/** + * Performs RDF dataset normalization on the given input. The input is JSON-LD + * unless the 'inputFormat' option is used. The output is an RDF dataset + * unless the 'format' option is used. + * + * Note: Canonicalization sets `safe` to `true` and `base` to `null` by + * default in order to produce safe outputs and "fail closed" by default. This + * is different from the other API transformations in this version which + * allow unsafe defaults (for cryptographic usage) in order to comply with the + * JSON-LD 1.1 specification. + * + * @param input the input to normalize as JSON-LD or as a format specified by + * the 'inputFormat' option. + * @param [options] the options to use: + * [algorithm] the normalization algorithm to use, `URDNA2015` or + * `URGNA2012` (default: `URDNA2015`). + * [base] the base IRI to use (default: `null`). + * [expandContext] a context to expand with. + * [skipExpansion] true to assume the input is expanded and skip + * expansion, false not to, defaults to false. Some well-formed + * and safe-mode checks may be omitted. + * [inputFormat] the format if input is not JSON-LD: + * 'application/n-quads' for N-Quads. + * [format] the format if output is a string: + * 'application/n-quads' for N-Quads. + * [documentLoader(url, options)] the document loader. + * [useNative] true to use a native canonize algorithm + * [rdfDirection] null or 'i18n-datatype' to support RDF + * transformation of @direction (default: null). + * [safe] true to use safe mode. (default: true). + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the normalized output. + */ +jsonld.normalize = jsonld.canonize = async function(input, options) { + if(arguments.length < 1) { + throw new TypeError('Could not canonize, too few arguments.'); + } + + // set default options + options = _setDefaults(options, { + base: _isString(input) ? input : null, + algorithm: 'URDNA2015', + skipExpansion: false, + safe: true, + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + if('inputFormat' in options) { + if(options.inputFormat !== 'application/n-quads' && + options.inputFormat !== 'application/nquads') { + throw new JsonLdError( + 'Unknown canonicalization input format.', + 'jsonld.CanonizeError'); + } + // TODO: `await` for async parsers + const parsedInput = NQuads.parse(input); + + // do canonicalization + return canonize.canonize(parsedInput, options); + } + + // convert to RDF dataset then do normalization + const opts = {...options}; + delete opts.format; + opts.produceGeneralizedRdf = false; + const dataset = await jsonld.toRDF(input, opts); + + // do canonicalization + return canonize.canonize(dataset, options); +}; + +/** + * Converts an RDF dataset to JSON-LD. + * + * @param dataset a serialized string of RDF in a format specified by the + * format option or an RDF dataset to convert. + * @param [options] the options to use: + * [format] the format if dataset param must first be parsed: + * 'application/n-quads' for N-Quads (default). + * [rdfParser] a custom RDF-parser to use to parse the dataset. + * [useRdfType] true to use rdf:type, false to use @type + * (default: false). + * [useNativeTypes] true to convert XSD types into native types + * (boolean, integer, double), false not to (default: false). + * [rdfDirection] null or 'i18n-datatype' to support RDF + * transformation of @direction (default: null). + * [safe] true to use safe mode. (default: false) + * + * @return a Promise that resolves to the JSON-LD document. + */ +jsonld.fromRDF = async function(dataset, options) { + if(arguments.length < 1) { + throw new TypeError('Could not convert from RDF, too few arguments.'); + } + + // set default options + options = _setDefaults(options, { + format: _isString(dataset) ? 'application/n-quads' : undefined + }); + + const {format} = options; + let {rdfParser} = options; + + // handle special format + if(format) { + // check supported formats + rdfParser = rdfParser || _rdfParsers[format]; + if(!rdfParser) { + throw new JsonLdError( + 'Unknown input format.', + 'jsonld.UnknownFormat', {format}); + } + } else { + // no-op parser, assume dataset already parsed + rdfParser = () => dataset; + } + + // rdfParser must be synchronous or return a promise, no callback support + const parsedDataset = await rdfParser(dataset); + return _fromRDF(parsedDataset, options); +}; + +/** + * Outputs the RDF dataset found in the given JSON-LD object. + * + * @param input the JSON-LD input. + * @param [options] the options to use: + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [skipExpansion] true to assume the input is expanded and skip + * expansion, false not to, defaults to false. Some well-formed + * and safe-mode checks may be omitted. + * [format] the format to use to output a string: + * 'application/n-quads' for N-Quads. + * [produceGeneralizedRdf] true to output generalized RDF, false + * to produce only standard RDF (default: false). + * [documentLoader(url, options)] the document loader. + * [safe] true to use safe mode. (default: false) + * [rdfDirection] null or 'i18n-datatype' to support RDF + * transformation of @direction (default: null). + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the RDF dataset. + */ +jsonld.toRDF = async function(input, options) { + if(arguments.length < 1) { + throw new TypeError('Could not convert to RDF, too few arguments.'); + } + + // set default options + options = _setDefaults(options, { + base: _isString(input) ? input : '', + skipExpansion: false, + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + + // TODO: support toRDF custom map? + let expanded; + if(options.skipExpansion) { + expanded = input; + } else { + // expand input + expanded = await jsonld.expand(input, options); + } + + // output RDF dataset + const dataset = _toRDF(expanded, options); + if(options.format) { + if(options.format === 'application/n-quads' || + options.format === 'application/nquads') { + return NQuads.serialize(dataset); + } + throw new JsonLdError( + 'Unknown output format.', + 'jsonld.UnknownFormat', {format: options.format}); + } + + return dataset; +}; + +/** + * **Experimental** + * + * Recursively flattens the nodes in the given JSON-LD input into a merged + * map of node ID => node. All graphs will be merged into the default graph. + * + * @param input the JSON-LD input. + * @param [options] the options to use: + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes. + * [documentLoader(url, options)] the document loader. + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the merged node map. + */ +jsonld.createNodeMap = async function(input, options) { + if(arguments.length < 1) { + throw new TypeError('Could not create node map, too few arguments.'); + } + + // set default options + options = _setDefaults(options, { + base: _isString(input) ? input : '', + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + + // expand input + const expanded = await jsonld.expand(input, options); + + return _createMergedNodeMap(expanded, options); +}; + +/** + * **Experimental** + * + * Merges two or more JSON-LD documents into a single flattened document. + * + * @param docs the JSON-LD documents to merge together. + * @param ctx the context to use to compact the merged result, or null. + * @param [options] the options to use: + * [base] the base IRI to use. + * [expandContext] a context to expand with. + * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes. + * [mergeNodes] true to merge properties for nodes with the same ID, + * false to ignore new properties for nodes with the same ID once + * the ID has been defined; note that this may not prevent merging + * new properties where a node is in the `object` position + * (default: true). + * [documentLoader(url, options)] the document loader. + * [safe] true to use safe mode. (default: false) + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the merged output. + */ +jsonld.merge = async function(docs, ctx, options) { + if(arguments.length < 1) { + throw new TypeError('Could not merge, too few arguments.'); + } + if(!_isArray(docs)) { + throw new TypeError('Could not merge, "docs" must be an array.'); + } + + if(typeof ctx === 'function') { + ctx = null; + } else { + ctx = ctx || null; + } + + // set default options + options = _setDefaults(options, { + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + + // expand all documents + const expanded = await Promise.all(docs.map(doc => { + const opts = {...options}; + return jsonld.expand(doc, opts); + })); + + let mergeNodes = true; + if('mergeNodes' in options) { + mergeNodes = options.mergeNodes; + } + + const issuer = options.issuer || new IdentifierIssuer('_:b'); + const graphs = {'@default': {}}; + + for(let i = 0; i < expanded.length; ++i) { + // uniquely relabel blank nodes + const doc = util.relabelBlankNodes(expanded[i], { + issuer: new IdentifierIssuer('_:b' + i + '-') + }); + + // add nodes to the shared node map graphs if merging nodes, to a + // separate graph set if not + const _graphs = (mergeNodes || i === 0) ? graphs : {'@default': {}}; + _createNodeMap(doc, _graphs, '@default', issuer); + + if(_graphs !== graphs) { + // merge document graphs but don't merge existing nodes + for(const graphName in _graphs) { + const _nodeMap = _graphs[graphName]; + if(!(graphName in graphs)) { + graphs[graphName] = _nodeMap; + continue; + } + const nodeMap = graphs[graphName]; + for(const key in _nodeMap) { + if(!(key in nodeMap)) { + nodeMap[key] = _nodeMap[key]; + } + } + } + } + } + + // add all non-default graphs to default graph + const defaultGraph = _mergeNodeMaps(graphs); + + // produce flattened output + const flattened = []; + const keys = Object.keys(defaultGraph).sort(); + for(let ki = 0; ki < keys.length; ++ki) { + const node = defaultGraph[keys[ki]]; + // only add full subjects to top-level + if(!_isSubjectReference(node)) { + flattened.push(node); + } + } + + if(ctx === null) { + return flattened; + } + + // compact result (force @graph option to true, skip expansion) + options.graph = true; + options.skipExpansion = true; + const compacted = await jsonld.compact(flattened, ctx, options); + + return compacted; +}; + +/** + * The default document loader for external documents. + * + * @param url the URL to load. + * + * @return a promise that resolves to the remote document. + */ +Object.defineProperty(jsonld, 'documentLoader', { + get: () => jsonld._documentLoader, + set: v => jsonld._documentLoader = v +}); +// default document loader not implemented +jsonld.documentLoader = async url => { + throw new JsonLdError( + 'Could not retrieve a JSON-LD document from the URL. URL ' + + 'dereferencing not implemented.', 'jsonld.LoadDocumentError', + {code: 'loading document failed', url}); +}; + +/** + * Gets a remote JSON-LD document using the default document loader or + * one given in the passed options. + * + * @param url the URL to fetch. + * @param [options] the options to use: + * [documentLoader] the document loader to use. + * + * @return a Promise that resolves to the retrieved remote document. + */ +jsonld.get = async function(url, options) { + let load; + if(typeof options.documentLoader === 'function') { + load = options.documentLoader; + } else { + load = jsonld.documentLoader; + } + + const remoteDoc = await load(url); + + try { + if(!remoteDoc.document) { + throw new JsonLdError( + 'No remote document found at the given URL.', + 'jsonld.NullRemoteDocument'); + } + if(_isString(remoteDoc.document)) { + remoteDoc.document = JSON.parse(remoteDoc.document); + } + } catch(e) { + throw new JsonLdError( + 'Could not retrieve a JSON-LD document from the URL.', + 'jsonld.LoadDocumentError', { + code: 'loading document failed', + cause: e, + remoteDoc + }); + } + + return remoteDoc; +}; + +/** + * Processes a local context, resolving any URLs as necessary, and returns a + * new active context. + * + * @param activeCtx the current active context. + * @param localCtx the local context to process. + * @param [options] the options to use: + * [documentLoader(url, options)] the document loader. + * [safe] true to use safe mode. (default: false) + * [contextResolver] internal use only. + * + * @return a Promise that resolves to the new active context. + */ +jsonld.processContext = async function( + activeCtx, localCtx, options) { + // set default options + options = _setDefaults(options, { + base: '', + contextResolver: new ContextResolver( + {sharedCache: _resolvedContextCache}) + }); + + // return initial context early for null context + if(localCtx === null) { + return _getInitialContext(options); + } + + // get URLs in localCtx + localCtx = util.clone(localCtx); + if(!(_isObject(localCtx) && '@context' in localCtx)) { + localCtx = {'@context': localCtx}; + } + + return _processContext({activeCtx, localCtx, options}); +}; + +// backwards compatibility +jsonld.getContextValue = (__webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js").getContextValue); + +/** + * Document loaders. + */ +jsonld.documentLoaders = {}; + +/** + * Assigns the default document loader for external document URLs to a built-in + * default. Supported types currently include: 'xhr' and 'node'. + * + * @param type the type to set. + * @param [params] the parameters required to use the document loader. + */ +jsonld.useDocumentLoader = function(type) { + if(!(type in jsonld.documentLoaders)) { + throw new JsonLdError( + 'Unknown document loader type: "' + type + '"', + 'jsonld.UnknownDocumentLoader', + {type}); + } + + // set document loader + jsonld.documentLoader = jsonld.documentLoaders[type].apply( + jsonld, Array.prototype.slice.call(arguments, 1)); +}; + +/** + * Registers an RDF dataset parser by content-type, for use with + * jsonld.fromRDF. An RDF dataset parser will always be given one parameter, + * a string of input. An RDF dataset parser can be synchronous or + * asynchronous (by returning a promise). + * + * @param contentType the content-type for the parser. + * @param parser(input) the parser function (takes a string as a parameter + * and either returns an RDF dataset or a Promise that resolves to one. + */ +jsonld.registerRDFParser = function(contentType, parser) { + _rdfParsers[contentType] = parser; +}; + +/** + * Unregisters an RDF dataset parser by content-type. + * + * @param contentType the content-type for the parser. + */ +jsonld.unregisterRDFParser = function(contentType) { + delete _rdfParsers[contentType]; +}; + +// register the N-Quads RDF parser +jsonld.registerRDFParser('application/n-quads', NQuads.parse); +jsonld.registerRDFParser('application/nquads', NQuads.parse); + +/* URL API */ +jsonld.url = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); + +/* Events API and handlers */ +jsonld.logEventHandler = _logEventHandler; +jsonld.logWarningEventHandler = _logWarningEventHandler; +jsonld.safeEventHandler = _safeEventHandler; +jsonld.setDefaultEventHandler = _setDefaultEventHandler; +jsonld.strictEventHandler = _strictEventHandler; +jsonld.unhandledEventHandler = _unhandledEventHandler; + +/* Utility API */ +jsonld.util = util; +// backwards compatibility +Object.assign(jsonld, util); + +// reexpose API as jsonld.promises for backwards compatability +jsonld.promises = jsonld; + +// backwards compatibility +jsonld.RequestQueue = __webpack_require__(/*! ./RequestQueue */ "./node_modules/jsonld/lib/RequestQueue.js"); + +/* WebIDL API */ +jsonld.JsonLdProcessor = __webpack_require__(/*! ./JsonLdProcessor */ "./node_modules/jsonld/lib/JsonLdProcessor.js")(jsonld); + +platform.setupGlobals(jsonld); +platform.setupDocumentLoaders(jsonld); + +function _setDefaults(options, { + documentLoader = jsonld.documentLoader, + ...defaults +}) { + // fail if obsolete options present + if(options && 'compactionMap' in options) { + throw new JsonLdError( + '"compactionMap" not supported.', + 'jsonld.OptionsError'); + } + if(options && 'expansionMap' in options) { + throw new JsonLdError( + '"expansionMap" not supported.', + 'jsonld.OptionsError'); + } + return Object.assign( + {}, + {documentLoader}, + defaults, + options, + {eventHandler: _setupEventHandler({options})} + ); +} + +// end of jsonld API `wrapper` factory +return jsonld; +}; + +// external APIs: + +// used to generate a new jsonld API instance +const factory = function() { + return wrapper(function() { + return factory(); + }); +}; + +// wrap the main jsonld API instance +wrapper(factory); +// export API +module.exports = factory; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/nodeMap.js" +/*!********************************************!*\ + !*** ./node_modules/jsonld/lib/nodeMap.js ***! + \********************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const {isKeyword} = __webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js"); +const graphTypes = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); +const util = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); + +const api = {}; +module.exports = api; + +/** + * Creates a merged JSON-LD node map (node ID => node). + * + * @param input the expanded JSON-LD to create a node map of. + * @param [options] the options to use: + * [issuer] a jsonld.IdentifierIssuer to use to label blank nodes. + * + * @return the node map. + */ +api.createMergedNodeMap = (input, options) => { + options = options || {}; + + // produce a map of all subjects and name each bnode + const issuer = options.issuer || new util.IdentifierIssuer('_:b'); + const graphs = {'@default': {}}; + api.createNodeMap(input, graphs, '@default', issuer); + + // add all non-default graphs to default graph + return api.mergeNodeMaps(graphs); +}; + +/** + * Recursively flattens the subjects in the given JSON-LD expanded input + * into a node map. + * + * @param input the JSON-LD expanded input. + * @param graphs a map of graph name to subject map. + * @param graph the name of the current graph. + * @param issuer the blank node identifier issuer. + * @param name the name assigned to the current input if it is a bnode. + * @param list the list to append to, null for none. + */ +api.createNodeMap = (input, graphs, graph, issuer, name, list) => { + // recurse through array + if(types.isArray(input)) { + for(const node of input) { + api.createNodeMap(node, graphs, graph, issuer, undefined, list); + } + return; + } + + // add non-object to list + if(!types.isObject(input)) { + if(list) { + list.push(input); + } + return; + } + + // add values to list + if(graphTypes.isValue(input)) { + if('@type' in input) { + let type = input['@type']; + // rename @type blank node + if(type.indexOf('_:') === 0) { + input['@type'] = type = issuer.getId(type); + } + } + if(list) { + list.push(input); + } + return; + } else if(list && graphTypes.isList(input)) { + const _list = []; + api.createNodeMap(input['@list'], graphs, graph, issuer, name, _list); + list.push({'@list': _list}); + return; + } + + // Note: At this point, input must be a subject. + + // spec requires @type to be named first, so assign names early + if('@type' in input) { + const types = input['@type']; + for(const type of types) { + if(type.indexOf('_:') === 0) { + issuer.getId(type); + } + } + } + + // get name for subject + if(types.isUndefined(name)) { + name = graphTypes.isBlankNode(input) ? + issuer.getId(input['@id']) : input['@id']; + } + + // add subject reference to list + if(list) { + list.push({'@id': name}); + } + + // create new subject or merge into existing one + const subjects = graphs[graph]; + const subject = subjects[name] = subjects[name] || {}; + subject['@id'] = name; + const properties = Object.keys(input).sort(); + for(let property of properties) { + // skip @id + if(property === '@id') { + continue; + } + + // handle reverse properties + if(property === '@reverse') { + const referencedNode = {'@id': name}; + const reverseMap = input['@reverse']; + for(const reverseProperty in reverseMap) { + const items = reverseMap[reverseProperty]; + for(const item of items) { + let itemName = item['@id']; + if(graphTypes.isBlankNode(item)) { + itemName = issuer.getId(itemName); + } + api.createNodeMap(item, graphs, graph, issuer, itemName); + util.addValue( + subjects[itemName], reverseProperty, referencedNode, + {propertyIsArray: true, allowDuplicate: false}); + } + } + continue; + } + + // recurse into graph + if(property === '@graph') { + // add graph subjects map entry + if(!(name in graphs)) { + graphs[name] = {}; + } + api.createNodeMap(input[property], graphs, name, issuer); + continue; + } + + // recurse into included + if(property === '@included') { + api.createNodeMap(input[property], graphs, graph, issuer); + continue; + } + + // copy non-@type keywords + if(property !== '@type' && isKeyword(property)) { + if(property === '@index' && property in subject && + (input[property] !== subject[property] || + input[property]['@id'] !== subject[property]['@id'])) { + throw new JsonLdError( + 'Invalid JSON-LD syntax; conflicting @index property detected.', + 'jsonld.SyntaxError', + {code: 'conflicting indexes', subject}); + } + subject[property] = input[property]; + continue; + } + + // iterate over objects + const objects = input[property]; + + // if property is a bnode, assign it a new id + if(property.indexOf('_:') === 0) { + property = issuer.getId(property); + } + + // ensure property is added for empty arrays + if(objects.length === 0) { + util.addValue(subject, property, [], {propertyIsArray: true}); + continue; + } + for(let o of objects) { + if(property === '@type') { + // rename @type blank nodes + o = (o.indexOf('_:') === 0) ? issuer.getId(o) : o; + } + + // handle embedded subject or subject reference + if(graphTypes.isSubject(o) || graphTypes.isSubjectReference(o)) { + // skip null @id + if('@id' in o && !o['@id']) { + continue; + } + + // relabel blank node @id + const id = graphTypes.isBlankNode(o) ? + issuer.getId(o['@id']) : o['@id']; + + // add reference and recurse + util.addValue( + subject, property, {'@id': id}, + {propertyIsArray: true, allowDuplicate: false}); + api.createNodeMap(o, graphs, graph, issuer, id); + } else if(graphTypes.isValue(o)) { + util.addValue( + subject, property, o, + {propertyIsArray: true, allowDuplicate: false}); + } else if(graphTypes.isList(o)) { + // handle @list + const _list = []; + api.createNodeMap(o['@list'], graphs, graph, issuer, name, _list); + o = {'@list': _list}; + util.addValue( + subject, property, o, + {propertyIsArray: true, allowDuplicate: false}); + } else { + // handle @value + api.createNodeMap(o, graphs, graph, issuer, name); + util.addValue( + subject, property, o, {propertyIsArray: true, allowDuplicate: false}); + } + } + } +}; + +/** + * Merge separate named graphs into a single merged graph including + * all nodes from the default graph and named graphs. + * + * @param graphs a map of graph name to subject map. + * + * @return the merged graph map. + */ +api.mergeNodeMapGraphs = graphs => { + const merged = {}; + for(const name of Object.keys(graphs).sort()) { + for(const id of Object.keys(graphs[name]).sort()) { + const node = graphs[name][id]; + if(!(id in merged)) { + merged[id] = {'@id': id}; + } + const mergedNode = merged[id]; + + for(const property of Object.keys(node).sort()) { + if(isKeyword(property) && property !== '@type') { + // copy keywords + mergedNode[property] = util.clone(node[property]); + } else { + // merge objects + for(const value of node[property]) { + util.addValue( + mergedNode, property, util.clone(value), + {propertyIsArray: true, allowDuplicate: false}); + } + } + } + } + } + + return merged; +}; + +api.mergeNodeMaps = graphs => { + // add all non-default graphs to default graph + const defaultGraph = graphs['@default']; + const graphNames = Object.keys(graphs).sort(); + for(const graphName of graphNames) { + if(graphName === '@default') { + continue; + } + const nodeMap = graphs[graphName]; + let subject = defaultGraph[graphName]; + if(!subject) { + defaultGraph[graphName] = subject = { + '@id': graphName, + '@graph': [] + }; + } else if(!('@graph' in subject)) { + subject['@graph'] = []; + } + const graph = subject['@graph']; + for(const id of Object.keys(nodeMap).sort()) { + const node = nodeMap[id]; + // only add full subjects + if(!graphTypes.isSubjectReference(node)) { + graph.push(node); + } + } + } + return defaultGraph; +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/platform-browser.js" +/*!*****************************************************!*\ + !*** ./node_modules/jsonld/lib/platform-browser.js ***! + \*****************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2021 Digital Bazaar, Inc. All rights reserved. + */ + + +const xhrLoader = __webpack_require__(/*! ./documentLoaders/xhr */ "./node_modules/jsonld/lib/documentLoaders/xhr.js"); + +const api = {}; +module.exports = api; + +/** + * Setup browser document loaders. + * + * @param jsonld the jsonld api. + */ +api.setupDocumentLoaders = function(jsonld) { + if(typeof XMLHttpRequest !== 'undefined') { + jsonld.documentLoaders.xhr = xhrLoader; + // use xhr document loader by default + jsonld.useDocumentLoader('xhr'); + } +}; + +/** + * Setup browser globals. + * + * @param jsonld the jsonld api. + */ +api.setupGlobals = function(jsonld) { + // setup browser global JsonLdProcessor + if(typeof globalThis.JsonLdProcessor === 'undefined') { + Object.defineProperty(globalThis, 'JsonLdProcessor', { + writable: true, + enumerable: false, + configurable: true, + value: jsonld.JsonLdProcessor + }); + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/toRdf.js" +/*!******************************************!*\ + !*** ./node_modules/jsonld/lib/toRdf.js ***! + \******************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017-2023 Digital Bazaar, Inc. All rights reserved. + */ + + +const {createNodeMap} = __webpack_require__(/*! ./nodeMap */ "./node_modules/jsonld/lib/nodeMap.js"); +const {isKeyword} = __webpack_require__(/*! ./context */ "./node_modules/jsonld/lib/context.js"); +const graphTypes = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); +const jsonCanonicalize = __webpack_require__(/*! canonicalize */ "./node_modules/canonicalize/lib/canonicalize.js"); +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); +const util = __webpack_require__(/*! ./util */ "./node_modules/jsonld/lib/util.js"); + +const { + handleEvent: _handleEvent +} = __webpack_require__(/*! ./events */ "./node_modules/jsonld/lib/events.js"); + +const { + // RDF, + // RDF_LIST, + RDF_FIRST, + RDF_REST, + RDF_NIL, + RDF_TYPE, + // RDF_PLAIN_LITERAL, + // RDF_XML_LITERAL, + RDF_JSON_LITERAL, + // RDF_OBJECT, + RDF_LANGSTRING, + + // XSD, + XSD_BOOLEAN, + XSD_DOUBLE, + XSD_INTEGER, + XSD_STRING, +} = __webpack_require__(/*! ./constants */ "./node_modules/jsonld/lib/constants.js"); + +const { + isAbsolute: _isAbsoluteIri +} = __webpack_require__(/*! ./url */ "./node_modules/jsonld/lib/url.js"); + +const api = {}; +module.exports = api; + +/** + * Outputs an RDF dataset for the expanded JSON-LD input. + * + * @param input the expanded JSON-LD input. + * @param options the RDF serialization options. + * + * @return the RDF dataset. + */ +api.toRDF = (input, options) => { + // create node map for default graph (and any named graphs) + const issuer = new util.IdentifierIssuer('_:b'); + const nodeMap = {'@default': {}}; + createNodeMap(input, nodeMap, '@default', issuer); + + const dataset = []; + const graphNames = Object.keys(nodeMap).sort(); + for(const graphName of graphNames) { + let graphTerm; + if(graphName === '@default') { + graphTerm = {termType: 'DefaultGraph', value: ''}; + } else if(_isAbsoluteIri(graphName)) { + if(graphName.startsWith('_:')) { + graphTerm = {termType: 'BlankNode'}; + } else { + graphTerm = {termType: 'NamedNode'}; + } + graphTerm.value = graphName; + } else { + // skip relative IRIs (not valid RDF) + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'relative graph reference', + level: 'warning', + message: 'Relative graph reference found.', + details: { + graph: graphName + } + }, + options + }); + } + continue; + } + _graphToRDF(dataset, nodeMap[graphName], graphTerm, issuer, options); + } + + return dataset; +}; + +/** + * Adds RDF quads for a particular graph to the given dataset. + * + * @param dataset the dataset to append RDF quads to. + * @param graph the graph to create RDF quads for. + * @param graphTerm the graph term for each quad. + * @param issuer a IdentifierIssuer for assigning blank node names. + * @param options the RDF serialization options. + * + * @return the array of RDF triples for the given graph. + */ +function _graphToRDF(dataset, graph, graphTerm, issuer, options) { + const ids = Object.keys(graph).sort(); + for(const id of ids) { + const node = graph[id]; + const properties = Object.keys(node).sort(); + for(let property of properties) { + const items = node[property]; + if(property === '@type') { + property = RDF_TYPE; + } else if(isKeyword(property)) { + continue; + } + + for(const item of items) { + // RDF subject + const subject = { + termType: id.startsWith('_:') ? 'BlankNode' : 'NamedNode', + value: id + }; + + // skip relative IRI subjects (not valid RDF) + if(!_isAbsoluteIri(id)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'relative subject reference', + level: 'warning', + message: 'Relative subject reference found.', + details: { + subject: id + } + }, + options + }); + } + continue; + } + + // RDF predicate + const predicate = { + termType: property.startsWith('_:') ? 'BlankNode' : 'NamedNode', + value: property + }; + + // skip relative IRI predicates (not valid RDF) + if(!_isAbsoluteIri(property)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'relative predicate reference', + level: 'warning', + message: 'Relative predicate reference found.', + details: { + predicate: property + } + }, + options + }); + } + continue; + } + + // skip blank node predicates unless producing generalized RDF + if(predicate.termType === 'BlankNode' && + !options.produceGeneralizedRdf) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'blank node predicate', + level: 'warning', + message: 'Dropping blank node predicate.', + details: { + // FIXME: add better issuer API to get reverse mapping + property: issuer.getOldIds() + .find(key => issuer.getId(key) === property) + } + }, + options + }); + } + continue; + } + + // convert list, value or node object to triple + const object = _objectToRDF( + item, issuer, dataset, graphTerm, options.rdfDirection, options); + // skip null objects (they are relative IRIs) + if(object) { + dataset.push({ + subject, + predicate, + object, + graph: graphTerm + }); + } + } + } + } +} + +/** + * Converts a @list value into linked list of blank node RDF quads + * (an RDF collection). + * + * @param list the @list value. + * @param issuer a IdentifierIssuer for assigning blank node names. + * @param dataset the array of quads to append to. + * @param graphTerm the graph term for each quad. + * @param options the RDF serialization options. + * + * @return the head of the list. + */ +function _listToRDF(list, issuer, dataset, graphTerm, rdfDirection, options) { + const first = {termType: 'NamedNode', value: RDF_FIRST}; + const rest = {termType: 'NamedNode', value: RDF_REST}; + const nil = {termType: 'NamedNode', value: RDF_NIL}; + + const last = list.pop(); + // Result is the head of the list + const result = last ? {termType: 'BlankNode', value: issuer.getId()} : nil; + let subject = result; + + for(const item of list) { + const object = _objectToRDF( + item, issuer, dataset, graphTerm, rdfDirection, options); + const next = {termType: 'BlankNode', value: issuer.getId()}; + dataset.push({ + subject, + predicate: first, + object, + graph: graphTerm + }); + dataset.push({ + subject, + predicate: rest, + object: next, + graph: graphTerm + }); + subject = next; + } + + // Tail of list + if(last) { + const object = _objectToRDF( + last, issuer, dataset, graphTerm, rdfDirection, options); + dataset.push({ + subject, + predicate: first, + object, + graph: graphTerm + }); + dataset.push({ + subject, + predicate: rest, + object: nil, + graph: graphTerm + }); + } + + return result; +} + +/** + * Converts a JSON-LD value object to an RDF literal or a JSON-LD string, + * node object to an RDF resource, or adds a list. + * + * @param item the JSON-LD value or node object. + * @param issuer a IdentifierIssuer for assigning blank node names. + * @param dataset the dataset to append RDF quads to. + * @param graphTerm the graph term for each quad. + * @param options the RDF serialization options. + * + * @return the RDF literal or RDF resource. + */ +function _objectToRDF( + item, issuer, dataset, graphTerm, rdfDirection, options +) { + const object = {}; + + // convert value object to RDF + if(graphTypes.isValue(item)) { + object.termType = 'Literal'; + object.value = undefined; + object.datatype = { + termType: 'NamedNode' + }; + let value = item['@value']; + const datatype = item['@type'] || null; + + // convert to XSD/JSON datatypes as appropriate + if(datatype === '@json') { + object.value = jsonCanonicalize(value); + object.datatype.value = RDF_JSON_LITERAL; + } else if(types.isBoolean(value)) { + object.value = value.toString(); + object.datatype.value = datatype || XSD_BOOLEAN; + } else if(types.isDouble(value) || datatype === XSD_DOUBLE) { + if(!types.isDouble(value)) { + value = parseFloat(value); + } + // canonical double representation + object.value = value.toExponential(15).replace(/(\d)0*e\+?/, '$1E'); + object.datatype.value = datatype || XSD_DOUBLE; + } else if(types.isNumber(value)) { + object.value = value.toFixed(0); + object.datatype.value = datatype || XSD_INTEGER; + } else if('@direction' in item && rdfDirection === 'i18n-datatype') { + const language = (item['@language'] || '').toLowerCase(); + const direction = item['@direction']; + const datatype = `https://www.w3.org/ns/i18n#${language}_${direction}`; + object.datatype.value = datatype; + object.value = value; + } else if('@direction' in item && rdfDirection === 'compound-literal') { + throw new JsonLdError( + 'Unsupported rdfDirection value.', + 'jsonld.InvalidRdfDirection', + {value: rdfDirection}); + } else if('@direction' in item && rdfDirection) { + throw new JsonLdError( + 'Unknown rdfDirection value.', + 'jsonld.InvalidRdfDirection', + {value: rdfDirection}); + } else if('@language' in item) { + if('@direction' in item && !rdfDirection) { + if(options.eventHandler) { + // FIXME: only emit once? + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'rdfDirection not set', + level: 'warning', + message: 'rdfDirection not set for @direction.', + details: { + object: object.value + } + }, + options + }); + } + } + object.value = value; + object.datatype.value = datatype || RDF_LANGSTRING; + object.language = item['@language']; + } else { + if('@direction' in item && !rdfDirection) { + if(options.eventHandler) { + // FIXME: only emit once? + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'rdfDirection not set', + level: 'warning', + message: 'rdfDirection not set for @direction.', + details: { + object: object.value + } + }, + options + }); + } + } + object.value = value; + object.datatype.value = datatype || XSD_STRING; + } + } else if(graphTypes.isList(item)) { + const _list = _listToRDF( + item['@list'], issuer, dataset, graphTerm, rdfDirection, options); + object.termType = _list.termType; + object.value = _list.value; + } else { + // convert string/node object to RDF + const id = types.isObject(item) ? item['@id'] : item; + object.termType = id.startsWith('_:') ? 'BlankNode' : 'NamedNode'; + object.value = id; + } + + // skip relative IRIs, not valid RDF + if(object.termType === 'NamedNode' && !_isAbsoluteIri(object.value)) { + if(options.eventHandler) { + _handleEvent({ + event: { + type: ['JsonLdEvent'], + code: 'relative object reference', + level: 'warning', + message: 'Relative object reference found.', + details: { + object: object.value + } + }, + options + }); + } + return null; + } + + return object; +} + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/types.js" +/*!******************************************!*\ + !*** ./node_modules/jsonld/lib/types.js ***! + \******************************************/ +(module) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const api = {}; +module.exports = api; + +/** + * Returns true if the given value is an Array. + * + * @param v the value to check. + * + * @return true if the value is an Array, false if not. + */ +api.isArray = Array.isArray; + +/** + * Returns true if the given value is a Boolean. + * + * @param v the value to check. + * + * @return true if the value is a Boolean, false if not. + */ +api.isBoolean = v => (typeof v === 'boolean' || + Object.prototype.toString.call(v) === '[object Boolean]'); + +/** + * Returns true if the given value is a double. + * + * @param v the value to check. + * + * @return true if the value is a double, false if not. + */ +api.isDouble = v => api.isNumber(v) && + (String(v).indexOf('.') !== -1 || Math.abs(v) >= 1e21); + +/** + * Returns true if the given value is an empty Object. + * + * @param v the value to check. + * + * @return true if the value is an empty Object, false if not. + */ +api.isEmptyObject = v => api.isObject(v) && Object.keys(v).length === 0; + +/** + * Returns true if the given value is a Number. + * + * @param v the value to check. + * + * @return true if the value is a Number, false if not. + */ +api.isNumber = v => (typeof v === 'number' || + Object.prototype.toString.call(v) === '[object Number]'); + +/** + * Returns true if the given value is numeric. + * + * @param v the value to check. + * + * @return true if the value is numeric, false if not. + */ +api.isNumeric = v => !isNaN(parseFloat(v)) && isFinite(v); + +/** + * Returns true if the given value is an Object. + * + * @param v the value to check. + * + * @return true if the value is an Object, false if not. + */ +api.isObject = v => Object.prototype.toString.call(v) === '[object Object]'; + +/** + * Returns true if the given value is a String. + * + * @param v the value to check. + * + * @return true if the value is a String, false if not. + */ +api.isString = v => (typeof v === 'string' || + Object.prototype.toString.call(v) === '[object String]'); + +/** + * Returns true if the given value is undefined. + * + * @param v the value to check. + * + * @return true if the value is undefined, false if not. + */ +api.isUndefined = v => typeof v === 'undefined'; + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/url.js" +/*!****************************************!*\ + !*** ./node_modules/jsonld/lib/url.js ***! + \****************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017 Digital Bazaar, Inc. All rights reserved. + */ + + +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); + +const api = {}; +module.exports = api; + +// define URL parser +// parseUri 1.2.2 +// (c) Steven Levithan +// MIT License +// with local jsonld.js modifications +api.parsers = { + simple: { + // RFC 3986 basic parts + keys: [ + 'href', 'scheme', 'authority', 'path', 'query', 'fragment' + ], + /* eslint-disable-next-line max-len */ + regex: /^(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/ + }, + full: { + keys: [ + 'href', 'protocol', 'scheme', 'authority', 'auth', 'user', 'password', + 'hostname', 'port', 'path', 'directory', 'file', 'query', 'fragment' + ], + /* eslint-disable-next-line max-len */ + regex: /^(([a-zA-Z][a-zA-Z0-9+-.]*):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?(?:(((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/ + } +}; +api.parse = (str, parser) => { + const parsed = {}; + const o = api.parsers[parser || 'full']; + const m = o.regex.exec(str); + let i = o.keys.length; + while(i--) { + parsed[o.keys[i]] = (m[i] === undefined) ? null : m[i]; + } + + // remove default ports in found in URLs + if((parsed.scheme === 'https' && parsed.port === '443') || + (parsed.scheme === 'http' && parsed.port === '80')) { + parsed.href = parsed.href.replace(':' + parsed.port, ''); + parsed.authority = parsed.authority.replace(':' + parsed.port, ''); + parsed.port = null; + } + + parsed.normalizedPath = api.removeDotSegments(parsed.path); + return parsed; +}; + +/** + * Prepends a base IRI to the given relative IRI. + * + * @param base the base IRI. + * @param iri the relative IRI. + * + * @return the absolute IRI. + */ +api.prependBase = (base, iri) => { + // skip IRI processing + if(base === null) { + return iri; + } + // already an absolute IRI + if(api.isAbsolute(iri)) { + return iri; + } + + // parse base if it is a string + if(!base || types.isString(base)) { + base = api.parse(base || ''); + } + + // parse given IRI + const rel = api.parse(iri); + + // per RFC3986 5.2.2 + const transform = { + protocol: base.protocol || '' + }; + + if(rel.authority !== null) { + transform.authority = rel.authority; + transform.path = rel.path; + transform.query = rel.query; + } else { + transform.authority = base.authority; + + if(rel.path === '') { + transform.path = base.path; + if(rel.query !== null) { + transform.query = rel.query; + } else { + transform.query = base.query; + } + } else { + if(rel.path.indexOf('/') === 0) { + // IRI represents an absolute path + transform.path = rel.path; + } else { + // merge paths + let path = base.path; + + // append relative path to the end of the last directory from base + path = path.substr(0, path.lastIndexOf('/') + 1); + if((path.length > 0 || base.authority) && path.substr(-1) !== '/') { + path += '/'; + } + path += rel.path; + + transform.path = path; + } + transform.query = rel.query; + } + } + + if(rel.path !== '') { + // remove slashes and dots in path + transform.path = api.removeDotSegments(transform.path); + } + + // construct URL + let rval = transform.protocol; + if(transform.authority !== null) { + rval += '//' + transform.authority; + } + rval += transform.path; + if(transform.query !== null) { + rval += '?' + transform.query; + } + if(rel.fragment !== null) { + rval += '#' + rel.fragment; + } + + // handle empty base + if(rval === '') { + rval = './'; + } + + return rval; +}; + +/** + * Removes a base IRI from the given absolute IRI. + * + * @param base the base IRI. + * @param iri the absolute IRI. + * + * @return the relative IRI if relative to base, otherwise the absolute IRI. + */ +api.removeBase = (base, iri) => { + // skip IRI processing + if(base === null) { + return iri; + } + + if(!base || types.isString(base)) { + base = api.parse(base || ''); + } + + // establish base root + let root = ''; + if(base.href !== '') { + root += (base.protocol || '') + '//' + (base.authority || ''); + } else if(iri.indexOf('//')) { + // support network-path reference with empty base + root += '//'; + } + + // IRI not relative to base + if(iri.indexOf(root) !== 0) { + return iri; + } + + // remove root from IRI and parse remainder + const rel = api.parse(iri.substr(root.length)); + + // remove path segments that match (do not remove last segment unless there + // is a hash or query) + const baseSegments = base.normalizedPath.split('/'); + const iriSegments = rel.normalizedPath.split('/'); + const last = (rel.fragment || rel.query) ? 0 : 1; + while(baseSegments.length > 0 && iriSegments.length > last) { + if(baseSegments[0] !== iriSegments[0]) { + break; + } + baseSegments.shift(); + iriSegments.shift(); + } + + // use '../' for each non-matching base segment + let rval = ''; + if(baseSegments.length > 0) { + // don't count the last segment (if it ends with '/' last path doesn't + // count and if it doesn't end with '/' it isn't a path) + baseSegments.pop(); + for(let i = 0; i < baseSegments.length; ++i) { + rval += '../'; + } + } + + // prepend remaining segments + rval += iriSegments.join('/'); + + // add query and hash + if(rel.query !== null) { + rval += '?' + rel.query; + } + if(rel.fragment !== null) { + rval += '#' + rel.fragment; + } + + // handle empty base + if(rval === '') { + rval = './'; + } + + return rval; +}; + +/** + * Removes dot segments from a URL path. + * + * @param path the path to remove dot segments from. + */ +api.removeDotSegments = path => { + // RFC 3986 5.2.4 (reworked) + + // empty path shortcut + if(path.length === 0) { + return ''; + } + + const input = path.split('/'); + const output = []; + + while(input.length > 0) { + const next = input.shift(); + const done = input.length === 0; + + if(next === '.') { + if(done) { + // ensure output has trailing / + output.push(''); + } + continue; + } + + if(next === '..') { + output.pop(); + if(done) { + // ensure output has trailing / + output.push(''); + } + continue; + } + + output.push(next); + } + + // if path was absolute, ensure output has leading / + if(path[0] === '/' && output.length > 0 && output[0] !== '') { + output.unshift(''); + } + if(output.length === 1 && output[0] === '') { + return '/'; + } + + return output.join('/'); +}; + +// TODO: time better isAbsolute/isRelative checks using full regexes: +// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + +// regex to check for absolute IRI (starting scheme and ':') or blank node IRI +const isAbsoluteRegex = /^([A-Za-z][A-Za-z0-9+-.]*|_):[^\s]*$/; + +/** + * Returns true if the given value is an absolute IRI or blank node IRI, false + * if not. + * Note: This weak check only checks for a correct starting scheme. + * + * @param v the value to check. + * + * @return true if the value is an absolute IRI, false if not. + */ +api.isAbsolute = v => types.isString(v) && isAbsoluteRegex.test(v); + +/** + * Returns true if the given value is a relative IRI, false if not. + * Note: this is a weak check. + * + * @param v the value to check. + * + * @return true if the value is a relative IRI, false if not. + */ +api.isRelative = v => types.isString(v); + + +/***/ }, + +/***/ "./node_modules/jsonld/lib/util.js" +/*!*****************************************!*\ + !*** ./node_modules/jsonld/lib/util.js ***! + \*****************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + * Copyright (c) 2017-2019 Digital Bazaar, Inc. All rights reserved. + */ + + +const graphTypes = __webpack_require__(/*! ./graphTypes */ "./node_modules/jsonld/lib/graphTypes.js"); +const types = __webpack_require__(/*! ./types */ "./node_modules/jsonld/lib/types.js"); +// TODO: move `IdentifierIssuer` to its own package +const IdentifierIssuer = (__webpack_require__(/*! rdf-canonize */ "./node_modules/jsonld/node_modules/rdf-canonize/index.js").IdentifierIssuer); +const JsonLdError = __webpack_require__(/*! ./JsonLdError */ "./node_modules/jsonld/lib/JsonLdError.js"); + +// constants +const REGEX_BCP47 = /^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/; +const REGEX_LINK_HEADERS = /(?:<[^>]*?>|"[^"]*?"|[^,])+/g; +const REGEX_LINK_HEADER = /\s*<([^>]*?)>\s*(?:;\s*(.*))?/; +const REGEX_LINK_HEADER_PARAMS = + /(.*?)=(?:(?:"([^"]*?)")|([^"]*?))\s*(?:(?:;\s*)|$)/g; +const REGEX_KEYWORD = /^@[a-zA-Z]+$/; + +const DEFAULTS = { + headers: { + accept: 'application/ld+json, application/json' + } +}; + +const api = {}; +module.exports = api; +api.IdentifierIssuer = IdentifierIssuer; +api.REGEX_BCP47 = REGEX_BCP47; +api.REGEX_KEYWORD = REGEX_KEYWORD; + +/** + * Clones an object, array, Map, Set, or string/number. If a typed JavaScript + * object is given, such as a Date, it will be converted to a string. + * + * @param value the value to clone. + * + * @return the cloned value. + */ +api.clone = function(value) { + if(value && typeof value === 'object') { + let rval; + if(types.isArray(value)) { + rval = []; + for(let i = 0; i < value.length; ++i) { + rval[i] = api.clone(value[i]); + } + } else if(value instanceof Map) { + rval = new Map(); + for(const [k, v] of value) { + rval.set(k, api.clone(v)); + } + } else if(value instanceof Set) { + rval = new Set(); + for(const v of value) { + rval.add(api.clone(v)); + } + } else if(types.isObject(value)) { + rval = {}; + for(const key in value) { + rval[key] = api.clone(value[key]); + } + } else { + rval = value.toString(); + } + return rval; + } + return value; +}; + +/** + * Ensure a value is an array. If the value is an array, it is returned. + * Otherwise, it is wrapped in an array. + * + * @param value the value to return as an array. + * + * @return the value as an array. + */ +api.asArray = function(value) { + return Array.isArray(value) ? value : [value]; +}; + +/** + * Builds an HTTP headers object for making a JSON-LD request from custom + * headers and asserts the `accept` header isn't overridden. + * + * @param headers an object of headers with keys as header names and values + * as header values. + * + * @return an object of headers with a valid `accept` header. + */ +api.buildHeaders = (headers = {}) => { + const hasAccept = Object.keys(headers).some( + h => h.toLowerCase() === 'accept'); + + if(hasAccept) { + throw new RangeError( + 'Accept header may not be specified; only "' + + DEFAULTS.headers.accept + '" is supported.'); + } + + return Object.assign({Accept: DEFAULTS.headers.accept}, headers); +}; + +/** + * Parses a link header. The results will be key'd by the value of "rel". + * + * Link: ; + * rel="http://www.w3.org/ns/json-ld#context"; type="application/ld+json" + * + * Parses as: { + * 'http://www.w3.org/ns/json-ld#context': { + * target: http://json-ld.org/contexts/person.jsonld, + * type: 'application/ld+json' + * } + * } + * + * If there is more than one "rel" with the same IRI, then entries in the + * resulting map for that "rel" will be arrays. + * + * @param header the link header to parse. + */ +api.parseLinkHeader = header => { + const rval = {}; + // split on unbracketed/unquoted commas + const entries = header.match(REGEX_LINK_HEADERS); + for(let i = 0; i < entries.length; ++i) { + let match = entries[i].match(REGEX_LINK_HEADER); + if(!match) { + continue; + } + const result = {target: match[1]}; + const params = match[2]; + while((match = REGEX_LINK_HEADER_PARAMS.exec(params))) { + result[match[1]] = (match[2] === undefined) ? match[3] : match[2]; + } + const rel = result.rel || ''; + if(Array.isArray(rval[rel])) { + rval[rel].push(result); + } else if(rval.hasOwnProperty(rel)) { + rval[rel] = [rval[rel], result]; + } else { + rval[rel] = result; + } + } + return rval; +}; + +/** + * Throws an exception if the given value is not a valid @type value. + * + * @param v the value to check. + */ +api.validateTypeValue = (v, isFrame) => { + if(types.isString(v)) { + return; + } + + if(types.isArray(v) && v.every(vv => types.isString(vv))) { + return; + } + if(isFrame && types.isObject(v)) { + switch(Object.keys(v).length) { + case 0: + // empty object is wildcard + return; + case 1: + // default entry is all strings + if('@default' in v && + api.asArray(v['@default']).every(vv => types.isString(vv))) { + return; + } + } + } + + throw new JsonLdError( + 'Invalid JSON-LD syntax; "@type" value must a string, an array of ' + + 'strings, an empty object, ' + + 'or a default object.', 'jsonld.SyntaxError', + {code: 'invalid type value', value: v}); +}; + +/** + * Returns true if the given subject has the given property. + * + * @param subject the subject to check. + * @param property the property to look for. + * + * @return true if the subject has the given property, false if not. + */ +api.hasProperty = (subject, property) => { + if(subject.hasOwnProperty(property)) { + const value = subject[property]; + return (!types.isArray(value) || value.length > 0); + } + return false; +}; + +/** + * Determines if the given value is a property of the given subject. + * + * @param subject the subject to check. + * @param property the property to check. + * @param value the value to check. + * + * @return true if the value exists, false if not. + */ +api.hasValue = (subject, property, value) => { + if(api.hasProperty(subject, property)) { + let val = subject[property]; + const isList = graphTypes.isList(val); + if(types.isArray(val) || isList) { + if(isList) { + val = val['@list']; + } + for(let i = 0; i < val.length; ++i) { + if(api.compareValues(value, val[i])) { + return true; + } + } + } else if(!types.isArray(value)) { + // avoid matching the set of values with an array value parameter + return api.compareValues(value, val); + } + } + return false; +}; + +/** + * Adds a value to a subject. If the value is an array, all values in the + * array will be added. + * + * @param subject the subject to add the value to. + * @param property the property that relates the value to the subject. + * @param value the value to add. + * @param [options] the options to use: + * [propertyIsArray] true if the property is always an array, false + * if not (default: false). + * [valueIsArray] true if the value to be added should be preserved as + * an array (lists) (default: false). + * [allowDuplicate] true to allow duplicates, false not to (uses a + * simple shallow comparison of subject ID or value) (default: true). + * [prependValue] false to prepend value to any existing values. + * (default: false) + */ +api.addValue = (subject, property, value, options) => { + options = options || {}; + if(!('propertyIsArray' in options)) { + options.propertyIsArray = false; + } + if(!('valueIsArray' in options)) { + options.valueIsArray = false; + } + if(!('allowDuplicate' in options)) { + options.allowDuplicate = true; + } + if(!('prependValue' in options)) { + options.prependValue = false; + } + + if(options.valueIsArray) { + subject[property] = value; + } else if(types.isArray(value)) { + if(value.length === 0 && options.propertyIsArray && + !subject.hasOwnProperty(property)) { + subject[property] = []; + } + if(options.prependValue) { + value = value.concat(subject[property]); + subject[property] = []; + } + for(let i = 0; i < value.length; ++i) { + api.addValue(subject, property, value[i], options); + } + } else if(subject.hasOwnProperty(property)) { + // check if subject already has value if duplicates not allowed + const hasValue = (!options.allowDuplicate && + api.hasValue(subject, property, value)); + + // make property an array if value not present or always an array + if(!types.isArray(subject[property]) && + (!hasValue || options.propertyIsArray)) { + subject[property] = [subject[property]]; + } + + // add new value + if(!hasValue) { + if(options.prependValue) { + subject[property].unshift(value); + } else { + subject[property].push(value); + } + } + } else { + // add new value as set or single value + subject[property] = options.propertyIsArray ? [value] : value; + } +}; + +/** + * Gets all of the values for a subject's property as an array. + * + * @param subject the subject. + * @param property the property. + * + * @return all of the values for a subject's property as an array. + */ +api.getValues = (subject, property) => [].concat(subject[property] || []); + +/** + * Removes a property from a subject. + * + * @param subject the subject. + * @param property the property. + */ +api.removeProperty = (subject, property) => { + delete subject[property]; +}; + +/** + * Removes a value from a subject. + * + * @param subject the subject. + * @param property the property that relates the value to the subject. + * @param value the value to remove. + * @param [options] the options to use: + * [propertyIsArray] true if the property is always an array, false + * if not (default: false). + */ +api.removeValue = (subject, property, value, options) => { + options = options || {}; + if(!('propertyIsArray' in options)) { + options.propertyIsArray = false; + } + + // filter out value + const values = api.getValues(subject, property).filter( + e => !api.compareValues(e, value)); + + if(values.length === 0) { + api.removeProperty(subject, property); + } else if(values.length === 1 && !options.propertyIsArray) { + subject[property] = values[0]; + } else { + subject[property] = values; + } +}; + +/** + * Relabels all blank nodes in the given JSON-LD input. + * + * @param input the JSON-LD input. + * @param [options] the options to use: + * [issuer] an IdentifierIssuer to use to label blank nodes. + */ +api.relabelBlankNodes = (input, options) => { + options = options || {}; + const issuer = options.issuer || new IdentifierIssuer('_:b'); + return _labelBlankNodes(issuer, input); +}; + +/** + * Compares two JSON-LD values for equality. Two JSON-LD values will be + * considered equal if: + * + * 1. They are both primitives of the same type and value. + * 2. They are both @values with the same @value, @type, @language, + * and @index, OR + * 3. They both have @ids they are the same. + * + * @param v1 the first value. + * @param v2 the second value. + * + * @return true if v1 and v2 are considered equal, false if not. + */ +api.compareValues = (v1, v2) => { + // 1. equal primitives + if(v1 === v2) { + return true; + } + + // 2. equal @values + if(graphTypes.isValue(v1) && graphTypes.isValue(v2) && + v1['@value'] === v2['@value'] && + v1['@type'] === v2['@type'] && + v1['@language'] === v2['@language'] && + v1['@index'] === v2['@index']) { + return true; + } + + // 3. equal @ids + if(types.isObject(v1) && + ('@id' in v1) && + types.isObject(v2) && + ('@id' in v2)) { + return v1['@id'] === v2['@id']; + } + + return false; +}; + +/** + * Compares two strings first based on length and then lexicographically. + * + * @param a the first string. + * @param b the second string. + * + * @return -1 if a < b, 1 if a > b, 0 if a === b. + */ +api.compareShortestLeast = (a, b) => { + if(a.length < b.length) { + return -1; + } + if(b.length < a.length) { + return 1; + } + if(a === b) { + return 0; + } + return (a < b) ? -1 : 1; +}; + +/** + * Labels the blank nodes in the given value using the given IdentifierIssuer. + * + * @param issuer the IdentifierIssuer to use. + * @param element the element with blank nodes to rename. + * + * @return the element. + */ +function _labelBlankNodes(issuer, element) { + if(types.isArray(element)) { + for(let i = 0; i < element.length; ++i) { + element[i] = _labelBlankNodes(issuer, element[i]); + } + } else if(graphTypes.isList(element)) { + element['@list'] = _labelBlankNodes(issuer, element['@list']); + } else if(types.isObject(element)) { + // relabel blank node + if(graphTypes.isBlankNode(element)) { + element['@id'] = issuer.getId(element['@id']); + } + + // recursively apply to all keys + const keys = Object.keys(element).sort(); + for(let ki = 0; ki < keys.length; ++ki) { + const key = keys[ki]; + if(key !== '@id') { + element[key] = _labelBlankNodes(issuer, element[key]); + } + } + } + + return element; +} + + +/***/ }, + +/***/ "./node_modules/jsonld/node_modules/rdf-canonize/index.js" +/*!****************************************************************!*\ + !*** ./node_modules/jsonld/node_modules/rdf-canonize/index.js ***! + \****************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +/** + * An implementation of the RDF Dataset Normalization specification. + * + * @author Dave Longley + * + * Copyright 2010-2021 Digital Bazaar, Inc. + */ +module.exports = __webpack_require__(/*! ./lib */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/index.js"); + + +/***/ }, + +/***/ "./node_modules/jsonld/node_modules/rdf-canonize/lib/IdentifierIssuer.js" +/*!*******************************************************************************!*\ + !*** ./node_modules/jsonld/node_modules/rdf-canonize/lib/IdentifierIssuer.js ***! + \*******************************************************************************/ +(module) { + +"use strict"; +/* + * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved. + */ + + +module.exports = class IdentifierIssuer { + /** + * Creates a new IdentifierIssuer. A IdentifierIssuer issues unique + * identifiers, keeping track of any previously issued identifiers. + * + * @param prefix the prefix to use (''). + * @param existing an existing Map to use. + * @param counter the counter to use. + */ + constructor(prefix, existing = new Map(), counter = 0) { + this.prefix = prefix; + this._existing = existing; + this.counter = counter; + } + + /** + * Copies this IdentifierIssuer. + * + * @return a copy of this IdentifierIssuer. + */ + clone() { + const {prefix, _existing, counter} = this; + return new IdentifierIssuer(prefix, new Map(_existing), counter); + } + + /** + * Gets the new identifier for the given old identifier, where if no old + * identifier is given a new identifier will be generated. + * + * @param [old] the old identifier to get the new identifier for. + * + * @return the new identifier. + */ + getId(old) { + // return existing old identifier + const existing = old && this._existing.get(old); + if(existing) { + return existing; + } + + // get next identifier + const identifier = this.prefix + this.counter; + this.counter++; + + // save mapping + if(old) { + this._existing.set(old, identifier); + } + + return identifier; + } + + /** + * Returns true if the given old identifer has already been assigned a new + * identifier. + * + * @param old the old identifier to check. + * + * @return true if the old identifier has been assigned a new identifier, + * false if not. + */ + hasId(old) { + return this._existing.has(old); + } + + /** + * Returns all of the IDs that have been issued new IDs in the order in + * which they were issued new IDs. + * + * @return the list of old IDs that has been issued new IDs in order. + */ + getOldIds() { + return [...this._existing.keys()]; + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/node_modules/rdf-canonize/lib/MessageDigest-browser.js" +/*!************************************************************************************!*\ + !*** ./node_modules/jsonld/node_modules/rdf-canonize/lib/MessageDigest-browser.js ***! + \************************************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. + */ + + +__webpack_require__(/*! setimmediate */ "./node_modules/setimmediate/setImmediate.js"); + +const crypto = self.crypto || self.msCrypto; + +module.exports = class MessageDigest { + /** + * Creates a new MessageDigest. + * + * @param algorithm the algorithm to use. + */ + constructor(algorithm) { + // check if crypto.subtle is available + // check is here rather than top-level to only fail if class is used + if(!(crypto && crypto.subtle)) { + throw new Error('crypto.subtle not found.'); + } + if(algorithm === 'sha256') { + this.algorithm = {name: 'SHA-256'}; + } else if(algorithm === 'sha1') { + this.algorithm = {name: 'SHA-1'}; + } else { + throw new Error(`Unsupported algorithm "${algorithm}".`); + } + this._content = ''; + } + + update(msg) { + this._content += msg; + } + + async digest() { + const data = new TextEncoder().encode(this._content); + const buffer = new Uint8Array( + await crypto.subtle.digest(this.algorithm, data)); + // return digest in hex + let hex = ''; + for(let i = 0; i < buffer.length; ++i) { + hex += buffer[i].toString(16).padStart(2, '0'); + } + return hex; + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/node_modules/rdf-canonize/lib/NQuads.js" +/*!*********************************************************************!*\ + !*** ./node_modules/jsonld/node_modules/rdf-canonize/lib/NQuads.js ***! + \*********************************************************************/ +(module) { + +"use strict"; +/*! + * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. + */ + + +// eslint-disable-next-line no-unused-vars +const TERMS = ['subject', 'predicate', 'object', 'graph']; +const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; +const RDF_LANGSTRING = RDF + 'langString'; +const XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string'; + +const TYPE_NAMED_NODE = 'NamedNode'; +const TYPE_BLANK_NODE = 'BlankNode'; +const TYPE_LITERAL = 'Literal'; +const TYPE_DEFAULT_GRAPH = 'DefaultGraph'; + +// build regexes +const REGEX = {}; +(() => { + const iri = '(?:<([^:]+:[^>]*)>)'; + // https://www.w3.org/TR/turtle/#grammar-production-BLANK_NODE_LABEL + const PN_CHARS_BASE = + 'A-Z' + 'a-z' + + '\u00C0-\u00D6' + + '\u00D8-\u00F6' + + '\u00F8-\u02FF' + + '\u0370-\u037D' + + '\u037F-\u1FFF' + + '\u200C-\u200D' + + '\u2070-\u218F' + + '\u2C00-\u2FEF' + + '\u3001-\uD7FF' + + '\uF900-\uFDCF' + + '\uFDF0-\uFFFD'; + // TODO: + //'\u10000-\uEFFFF'; + const PN_CHARS_U = + PN_CHARS_BASE + + '_'; + const PN_CHARS = + PN_CHARS_U + + '0-9' + + '-' + + '\u00B7' + + '\u0300-\u036F' + + '\u203F-\u2040'; + const BLANK_NODE_LABEL = + '(_:' + + '(?:[' + PN_CHARS_U + '0-9])' + + '(?:(?:[' + PN_CHARS + '.])*(?:[' + PN_CHARS + ']))?' + + ')'; + const bnode = BLANK_NODE_LABEL; + const plain = '"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"'; + const datatype = '(?:\\^\\^' + iri + ')'; + const language = '(?:@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*))'; + const literal = '(?:' + plain + '(?:' + datatype + '|' + language + ')?)'; + const ws = '[ \\t]+'; + const wso = '[ \\t]*'; + + // define quad part regexes + const subject = '(?:' + iri + '|' + bnode + ')' + ws; + const property = iri + ws; + const object = '(?:' + iri + '|' + bnode + '|' + literal + ')' + wso; + const graphName = '(?:\\.|(?:(?:' + iri + '|' + bnode + ')' + wso + '\\.))'; + + // end of line and empty regexes + REGEX.eoln = /(?:\r\n)|(?:\n)|(?:\r)/g; + REGEX.empty = new RegExp('^' + wso + '$'); + + // full quad regex + REGEX.quad = new RegExp( + '^' + wso + subject + property + object + graphName + wso + '$'); +})(); + +module.exports = class NQuads { + /** + * Parses RDF in the form of N-Quads. + * + * @param input the N-Quads input to parse. + * + * @return an RDF dataset (an array of quads per http://rdf.js.org/). + */ + static parse(input) { + // build RDF dataset + const dataset = []; + + const graphs = {}; + + // split N-Quad input into lines + const lines = input.split(REGEX.eoln); + let lineNumber = 0; + for(const line of lines) { + lineNumber++; + + // skip empty lines + if(REGEX.empty.test(line)) { + continue; + } + + // parse quad + const match = line.match(REGEX.quad); + if(match === null) { + throw new Error('N-Quads parse error on line ' + lineNumber + '.'); + } + + // create RDF quad + const quad = {subject: null, predicate: null, object: null, graph: null}; + + // get subject + if(match[1] !== undefined) { + quad.subject = {termType: TYPE_NAMED_NODE, value: match[1]}; + } else { + quad.subject = {termType: TYPE_BLANK_NODE, value: match[2]}; + } + + // get predicate + quad.predicate = {termType: TYPE_NAMED_NODE, value: match[3]}; + + // get object + if(match[4] !== undefined) { + quad.object = {termType: TYPE_NAMED_NODE, value: match[4]}; + } else if(match[5] !== undefined) { + quad.object = {termType: TYPE_BLANK_NODE, value: match[5]}; + } else { + quad.object = { + termType: TYPE_LITERAL, + value: undefined, + datatype: { + termType: TYPE_NAMED_NODE + } + }; + if(match[7] !== undefined) { + quad.object.datatype.value = match[7]; + } else if(match[8] !== undefined) { + quad.object.datatype.value = RDF_LANGSTRING; + quad.object.language = match[8]; + } else { + quad.object.datatype.value = XSD_STRING; + } + quad.object.value = _unescape(match[6]); + } + + // get graph + if(match[9] !== undefined) { + quad.graph = { + termType: TYPE_NAMED_NODE, + value: match[9] + }; + } else if(match[10] !== undefined) { + quad.graph = { + termType: TYPE_BLANK_NODE, + value: match[10] + }; + } else { + quad.graph = { + termType: TYPE_DEFAULT_GRAPH, + value: '' + }; + } + + // only add quad if it is unique in its graph + if(!(quad.graph.value in graphs)) { + graphs[quad.graph.value] = [quad]; + dataset.push(quad); + } else { + let unique = true; + const quads = graphs[quad.graph.value]; + for(const q of quads) { + if(_compareTriples(q, quad)) { + unique = false; + break; + } + } + if(unique) { + quads.push(quad); + dataset.push(quad); + } + } + } + + return dataset; + } + + /** + * Converts an RDF dataset to N-Quads. + * + * @param dataset (array of quads) the RDF dataset to convert. + * + * @return the N-Quads string. + */ + static serialize(dataset) { + if(!Array.isArray(dataset)) { + dataset = NQuads.legacyDatasetToQuads(dataset); + } + const quads = []; + for(const quad of dataset) { + quads.push(NQuads.serializeQuad(quad)); + } + return quads.sort().join(''); + } + + /** + * Converts RDF quad components to an N-Quad string (a single quad). + * + * @param {Object} s - N-Quad subject component. + * @param {Object} p - N-Quad predicate component. + * @param {Object} o - N-Quad object component. + * @param {Object} g - N-Quad graph component. + * + * @return {string} the N-Quad. + */ + static serializeQuadComponents(s, p, o, g) { + let nquad = ''; + + // subject can only be NamedNode or BlankNode + if(s.termType === TYPE_NAMED_NODE) { + nquad += `<${s.value}>`; + } else { + nquad += `${s.value}`; + } + + // predicate can only be NamedNode + nquad += ` <${p.value}> `; + + // object is NamedNode, BlankNode, or Literal + if(o.termType === TYPE_NAMED_NODE) { + nquad += `<${o.value}>`; + } else if(o.termType === TYPE_BLANK_NODE) { + nquad += o.value; + } else { + nquad += `"${_escape(o.value)}"`; + if(o.datatype.value === RDF_LANGSTRING) { + if(o.language) { + nquad += `@${o.language}`; + } + } else if(o.datatype.value !== XSD_STRING) { + nquad += `^^<${o.datatype.value}>`; + } + } + + // graph can only be NamedNode or BlankNode (or DefaultGraph, but that + // does not add to `nquad`) + if(g.termType === TYPE_NAMED_NODE) { + nquad += ` <${g.value}>`; + } else if(g.termType === TYPE_BLANK_NODE) { + nquad += ` ${g.value}`; + } + + nquad += ' .\n'; + return nquad; + } + + /** + * Converts an RDF quad to an N-Quad string (a single quad). + * + * @param quad the RDF quad convert. + * + * @return the N-Quad string. + */ + static serializeQuad(quad) { + return NQuads.serializeQuadComponents( + quad.subject, quad.predicate, quad.object, quad.graph); + } + + /** + * Converts a legacy-formatted dataset to an array of quads dataset per + * http://rdf.js.org/. + * + * @param dataset the legacy dataset to convert. + * + * @return the array of quads dataset. + */ + static legacyDatasetToQuads(dataset) { + const quads = []; + + const termTypeMap = { + 'blank node': TYPE_BLANK_NODE, + IRI: TYPE_NAMED_NODE, + literal: TYPE_LITERAL + }; + + for(const graphName in dataset) { + const triples = dataset[graphName]; + triples.forEach(triple => { + const quad = {}; + for(const componentName in triple) { + const oldComponent = triple[componentName]; + const newComponent = { + termType: termTypeMap[oldComponent.type], + value: oldComponent.value + }; + if(newComponent.termType === TYPE_LITERAL) { + newComponent.datatype = { + termType: TYPE_NAMED_NODE + }; + if('datatype' in oldComponent) { + newComponent.datatype.value = oldComponent.datatype; + } + if('language' in oldComponent) { + if(!('datatype' in oldComponent)) { + newComponent.datatype.value = RDF_LANGSTRING; + } + newComponent.language = oldComponent.language; + } else if(!('datatype' in oldComponent)) { + newComponent.datatype.value = XSD_STRING; + } + } + quad[componentName] = newComponent; + } + if(graphName === '@default') { + quad.graph = { + termType: TYPE_DEFAULT_GRAPH, + value: '' + }; + } else { + quad.graph = { + termType: graphName.startsWith('_:') ? + TYPE_BLANK_NODE : TYPE_NAMED_NODE, + value: graphName + }; + } + quads.push(quad); + }); + } + + return quads; + } +}; + +/** + * Compares two RDF triples for equality. + * + * @param t1 the first triple. + * @param t2 the second triple. + * + * @return true if the triples are the same, false if not. + */ +function _compareTriples(t1, t2) { + // compare subject and object types first as it is the quickest check + if(!(t1.subject.termType === t2.subject.termType && + t1.object.termType === t2.object.termType)) { + return false; + } + // compare values + if(!(t1.subject.value === t2.subject.value && + t1.predicate.value === t2.predicate.value && + t1.object.value === t2.object.value)) { + return false; + } + if(t1.object.termType !== TYPE_LITERAL) { + // no `datatype` or `language` to check + return true; + } + return ( + (t1.object.datatype.termType === t2.object.datatype.termType) && + (t1.object.language === t2.object.language) && + (t1.object.datatype.value === t2.object.datatype.value) + ); +} + +const _escapeRegex = /["\\\n\r]/g; +/** + * Escape string to N-Quads literal + */ +function _escape(s) { + return s.replace(_escapeRegex, function(match) { + switch(match) { + case '"': return '\\"'; + case '\\': return '\\\\'; + case '\n': return '\\n'; + case '\r': return '\\r'; + } + }); +} + +const _unescapeRegex = + /(?:\\([tbnrf"'\\]))|(?:\\u([0-9A-Fa-f]{4}))|(?:\\U([0-9A-Fa-f]{8}))/g; +/** + * Unescape N-Quads literal to string + */ +function _unescape(s) { + return s.replace(_unescapeRegex, function(match, code, u, U) { + if(code) { + switch(code) { + case 't': return '\t'; + case 'b': return '\b'; + case 'n': return '\n'; + case 'r': return '\r'; + case 'f': return '\f'; + case '"': return '"'; + case '\'': return '\''; + case '\\': return '\\'; + } + } + if(u) { + return String.fromCharCode(parseInt(u, 16)); + } + if(U) { + // FIXME: support larger values + throw new Error('Unsupported U escape'); + } + }); +} + + +/***/ }, + +/***/ "./node_modules/jsonld/node_modules/rdf-canonize/lib/Permuter.js" +/*!***********************************************************************!*\ + !*** ./node_modules/jsonld/node_modules/rdf-canonize/lib/Permuter.js ***! + \***********************************************************************/ +(module) { + +"use strict"; +/*! + * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. + */ + + +module.exports = class Permuter { + /** + * A Permuter iterates over all possible permutations of the given array + * of elements. + * + * @param list the array of elements to iterate over. + */ + constructor(list) { + // original array + this.current = list.sort(); + // indicates whether there are more permutations + this.done = false; + // directional info for permutation algorithm + this.dir = new Map(); + for(let i = 0; i < list.length; ++i) { + this.dir.set(list[i], true); + } + } + + /** + * Returns true if there is another permutation. + * + * @return true if there is another permutation, false if not. + */ + hasNext() { + return !this.done; + } + + /** + * Gets the next permutation. Call hasNext() to ensure there is another one + * first. + * + * @return the next permutation. + */ + next() { + // copy current permutation to return it + const {current, dir} = this; + const rval = current.slice(); + + /* Calculate the next permutation using the Steinhaus-Johnson-Trotter + permutation algorithm. */ + + // get largest mobile element k + // (mobile: element is greater than the one it is looking at) + let k = null; + let pos = 0; + const length = current.length; + for(let i = 0; i < length; ++i) { + const element = current[i]; + const left = dir.get(element); + if((k === null || element > k) && + ((left && i > 0 && element > current[i - 1]) || + (!left && i < (length - 1) && element > current[i + 1]))) { + k = element; + pos = i; + } + } + + // no more permutations + if(k === null) { + this.done = true; + } else { + // swap k and the element it is looking at + const swap = dir.get(k) ? pos - 1 : pos + 1; + current[pos] = current[swap]; + current[swap] = k; + + // reverse the direction of all elements larger than k + for(const element of current) { + if(element > k) { + dir.set(element, !dir.get(element)); + } + } + } + + return rval; + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/node_modules/rdf-canonize/lib/URDNA2015.js" +/*!************************************************************************!*\ + !*** ./node_modules/jsonld/node_modules/rdf-canonize/lib/URDNA2015.js ***! + \************************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. + */ + + +const IdentifierIssuer = __webpack_require__(/*! ./IdentifierIssuer */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/IdentifierIssuer.js"); +const MessageDigest = __webpack_require__(/*! ./MessageDigest */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/MessageDigest-browser.js"); +const Permuter = __webpack_require__(/*! ./Permuter */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/Permuter.js"); +const NQuads = __webpack_require__(/*! ./NQuads */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/NQuads.js"); + +module.exports = class URDNA2015 { + constructor({ + createMessageDigest = () => new MessageDigest('sha256'), + canonicalIdMap = new Map(), + maxDeepIterations = Infinity + } = {}) { + this.name = 'URDNA2015'; + this.blankNodeInfo = new Map(); + this.canonicalIssuer = new IdentifierIssuer('_:c14n', canonicalIdMap); + this.createMessageDigest = createMessageDigest; + this.maxDeepIterations = maxDeepIterations; + this.quads = null; + this.deepIterations = null; + } + + // 4.4) Normalization Algorithm + async main(dataset) { + this.deepIterations = new Map(); + this.quads = dataset; + + // 1) Create the normalization state. + // 2) For every quad in input dataset: + for(const quad of dataset) { + // 2.1) For each blank node that occurs in the quad, add a reference + // to the quad using the blank node identifier in the blank node to + // quads map, creating a new entry if necessary. + this._addBlankNodeQuadInfo({quad, component: quad.subject}); + this._addBlankNodeQuadInfo({quad, component: quad.object}); + this._addBlankNodeQuadInfo({quad, component: quad.graph}); + } + + // 3) Create a list of non-normalized blank node identifiers + // non-normalized identifiers and populate it using the keys from the + // blank node to quads map. + // Note: We use a map here and it was generated during step 2. + + // 4) `simple` flag is skipped -- loop is optimized away. This optimization + // is permitted because there was a typo in the hash first degree quads + // algorithm in the URDNA2015 spec that was implemented widely making it + // such that it could not be fixed; the result was that the loop only + // needs to be run once and the first degree quad hashes will never change. + // 5.1-5.2 are skipped; first degree quad hashes are generated just once + // for all non-normalized blank nodes. + + // 5.3) For each blank node identifier identifier in non-normalized + // identifiers: + const hashToBlankNodes = new Map(); + const nonNormalized = [...this.blankNodeInfo.keys()]; + let i = 0; + for(const id of nonNormalized) { + // Note: batch hashing first degree quads 100 at a time + if(++i % 100 === 0) { + await this._yield(); + } + // steps 5.3.1 and 5.3.2: + await this._hashAndTrackBlankNode({id, hashToBlankNodes}); + } + + // 5.4) For each hash to identifier list mapping in hash to blank + // nodes map, lexicographically-sorted by hash: + const hashes = [...hashToBlankNodes.keys()].sort(); + // optimize away second sort, gather non-unique hashes in order as we go + const nonUnique = []; + for(const hash of hashes) { + // 5.4.1) If the length of identifier list is greater than 1, + // continue to the next mapping. + const idList = hashToBlankNodes.get(hash); + if(idList.length > 1) { + nonUnique.push(idList); + continue; + } + + // 5.4.2) Use the Issue Identifier algorithm, passing canonical + // issuer and the single blank node identifier in identifier + // list, identifier, to issue a canonical replacement identifier + // for identifier. + const id = idList[0]; + this.canonicalIssuer.getId(id); + + // Note: These steps are skipped, optimized away since the loop + // only needs to be run once. + // 5.4.3) Remove identifier from non-normalized identifiers. + // 5.4.4) Remove hash from the hash to blank nodes map. + // 5.4.5) Set simple to true. + } + + // 6) For each hash to identifier list mapping in hash to blank nodes map, + // lexicographically-sorted by hash: + // Note: sort optimized away, use `nonUnique`. + for(const idList of nonUnique) { + // 6.1) Create hash path list where each item will be a result of + // running the Hash N-Degree Quads algorithm. + const hashPathList = []; + + // 6.2) For each blank node identifier identifier in identifier list: + for(const id of idList) { + // 6.2.1) If a canonical identifier has already been issued for + // identifier, continue to the next identifier. + if(this.canonicalIssuer.hasId(id)) { + continue; + } + + // 6.2.2) Create temporary issuer, an identifier issuer + // initialized with the prefix _:b. + const issuer = new IdentifierIssuer('_:b'); + + // 6.2.3) Use the Issue Identifier algorithm, passing temporary + // issuer and identifier, to issue a new temporary blank node + // identifier for identifier. + issuer.getId(id); + + // 6.2.4) Run the Hash N-Degree Quads algorithm, passing + // temporary issuer, and append the result to the hash path list. + const result = await this.hashNDegreeQuads(id, issuer); + hashPathList.push(result); + } + + // 6.3) For each result in the hash path list, + // lexicographically-sorted by the hash in result: + hashPathList.sort(_stringHashCompare); + for(const result of hashPathList) { + // 6.3.1) For each blank node identifier, existing identifier, + // that was issued a temporary identifier by identifier issuer + // in result, issue a canonical identifier, in the same order, + // using the Issue Identifier algorithm, passing canonical + // issuer and existing identifier. + const oldIds = result.issuer.getOldIds(); + for(const id of oldIds) { + this.canonicalIssuer.getId(id); + } + } + } + + /* Note: At this point all blank nodes in the set of RDF quads have been + assigned canonical identifiers, which have been stored in the canonical + issuer. Here each quad is updated by assigning each of its blank nodes + its new identifier. */ + + // 7) For each quad, quad, in input dataset: + const normalized = []; + for(const quad of this.quads) { + // 7.1) Create a copy, quad copy, of quad and replace any existing + // blank node identifiers using the canonical identifiers + // previously issued by canonical issuer. + // Note: We optimize away the copy here. + const nQuad = NQuads.serializeQuadComponents( + this._componentWithCanonicalId(quad.subject), + quad.predicate, + this._componentWithCanonicalId(quad.object), + this._componentWithCanonicalId(quad.graph) + ); + // 7.2) Add quad copy to the normalized dataset. + normalized.push(nQuad); + } + + // sort normalized output + normalized.sort(); + + // 8) Return the normalized dataset. + return normalized.join(''); + } + + // 4.6) Hash First Degree Quads + async hashFirstDegreeQuads(id) { + // 1) Initialize nquads to an empty list. It will be used to store quads in + // N-Quads format. + const nquads = []; + + // 2) Get the list of quads `quads` associated with the reference blank node + // identifier in the blank node to quads map. + const info = this.blankNodeInfo.get(id); + const quads = info.quads; + + // 3) For each quad `quad` in `quads`: + for(const quad of quads) { + // 3.1) Serialize the quad in N-Quads format with the following special + // rule: + + // 3.1.1) If any component in quad is an blank node, then serialize it + // using a special identifier as follows: + const copy = { + subject: null, predicate: quad.predicate, object: null, graph: null + }; + // 3.1.2) If the blank node's existing blank node identifier matches + // the reference blank node identifier then use the blank node + // identifier _:a, otherwise, use the blank node identifier _:z. + copy.subject = this.modifyFirstDegreeComponent( + id, quad.subject, 'subject'); + copy.object = this.modifyFirstDegreeComponent( + id, quad.object, 'object'); + copy.graph = this.modifyFirstDegreeComponent( + id, quad.graph, 'graph'); + nquads.push(NQuads.serializeQuad(copy)); + } + + // 4) Sort nquads in lexicographical order. + nquads.sort(); + + // 5) Return the hash that results from passing the sorted, joined nquads + // through the hash algorithm. + const md = this.createMessageDigest(); + for(const nquad of nquads) { + md.update(nquad); + } + info.hash = await md.digest(); + return info.hash; + } + + // 4.7) Hash Related Blank Node + async hashRelatedBlankNode(related, quad, issuer, position) { + // 1) Set the identifier to use for related, preferring first the canonical + // identifier for related if issued, second the identifier issued by issuer + // if issued, and last, if necessary, the result of the Hash First Degree + // Quads algorithm, passing related. + let id; + if(this.canonicalIssuer.hasId(related)) { + id = this.canonicalIssuer.getId(related); + } else if(issuer.hasId(related)) { + id = issuer.getId(related); + } else { + id = this.blankNodeInfo.get(related).hash; + } + + // 2) Initialize a string input to the value of position. + // Note: We use a hash object instead. + const md = this.createMessageDigest(); + md.update(position); + + // 3) If position is not g, append <, the value of the predicate in quad, + // and > to input. + if(position !== 'g') { + md.update(this.getRelatedPredicate(quad)); + } + + // 4) Append identifier to input. + md.update(id); + + // 5) Return the hash that results from passing input through the hash + // algorithm. + return md.digest(); + } + + // 4.8) Hash N-Degree Quads + async hashNDegreeQuads(id, issuer) { + const deepIterations = this.deepIterations.get(id) || 0; + if(deepIterations > this.maxDeepIterations) { + throw new Error( + `Maximum deep iterations (${this.maxDeepIterations}) exceeded.`); + } + this.deepIterations.set(id, deepIterations + 1); + + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + // Note: 2) and 3) handled within `createHashToRelated` + const md = this.createMessageDigest(); + const hashToRelated = await this.createHashToRelated(id, issuer); + + // 4) Create an empty string, data to hash. + // Note: We created a hash object `md` above instead. + + // 5) For each related hash to blank node list mapping in hash to related + // blank nodes map, sorted lexicographically by related hash: + const hashes = [...hashToRelated.keys()].sort(); + for(const hash of hashes) { + // 5.1) Append the related hash to the data to hash. + md.update(hash); + + // 5.2) Create a string chosen path. + let chosenPath = ''; + + // 5.3) Create an unset chosen issuer variable. + let chosenIssuer; + + // 5.4) For each permutation of blank node list: + const permuter = new Permuter(hashToRelated.get(hash)); + let i = 0; + while(permuter.hasNext()) { + const permutation = permuter.next(); + // Note: batch permutations 3 at a time + if(++i % 3 === 0) { + await this._yield(); + } + + // 5.4.1) Create a copy of issuer, issuer copy. + let issuerCopy = issuer.clone(); + + // 5.4.2) Create a string path. + let path = ''; + + // 5.4.3) Create a recursion list, to store blank node identifiers + // that must be recursively processed by this algorithm. + const recursionList = []; + + // 5.4.4) For each related in permutation: + let nextPermutation = false; + for(const related of permutation) { + // 5.4.4.1) If a canonical identifier has been issued for + // related, append it to path. + if(this.canonicalIssuer.hasId(related)) { + path += this.canonicalIssuer.getId(related); + } else { + // 5.4.4.2) Otherwise: + // 5.4.4.2.1) If issuer copy has not issued an identifier for + // related, append related to recursion list. + if(!issuerCopy.hasId(related)) { + recursionList.push(related); + } + // 5.4.4.2.2) Use the Issue Identifier algorithm, passing + // issuer copy and related and append the result to path. + path += issuerCopy.getId(related); + } + + // 5.4.4.3) If chosen path is not empty and the length of path + // is greater than or equal to the length of chosen path and + // path is lexicographically greater than chosen path, then + // skip to the next permutation. + // Note: Comparing path length to chosen path length can be optimized + // away; only compare lexicographically. + if(chosenPath.length !== 0 && path > chosenPath) { + nextPermutation = true; + break; + } + } + + if(nextPermutation) { + continue; + } + + // 5.4.5) For each related in recursion list: + for(const related of recursionList) { + // 5.4.5.1) Set result to the result of recursively executing + // the Hash N-Degree Quads algorithm, passing related for + // identifier and issuer copy for path identifier issuer. + const result = await this.hashNDegreeQuads(related, issuerCopy); + + // 5.4.5.2) Use the Issue Identifier algorithm, passing issuer + // copy and related and append the result to path. + path += issuerCopy.getId(related); + + // 5.4.5.3) Append <, the hash in result, and > to path. + path += `<${result.hash}>`; + + // 5.4.5.4) Set issuer copy to the identifier issuer in + // result. + issuerCopy = result.issuer; + + // 5.4.5.5) If chosen path is not empty and the length of path + // is greater than or equal to the length of chosen path and + // path is lexicographically greater than chosen path, then + // skip to the next permutation. + // Note: Comparing path length to chosen path length can be optimized + // away; only compare lexicographically. + if(chosenPath.length !== 0 && path > chosenPath) { + nextPermutation = true; + break; + } + } + + if(nextPermutation) { + continue; + } + + // 5.4.6) If chosen path is empty or path is lexicographically + // less than chosen path, set chosen path to path and chosen + // issuer to issuer copy. + if(chosenPath.length === 0 || path < chosenPath) { + chosenPath = path; + chosenIssuer = issuerCopy; + } + } + + // 5.5) Append chosen path to data to hash. + md.update(chosenPath); + + // 5.6) Replace issuer, by reference, with chosen issuer. + issuer = chosenIssuer; + } + + // 6) Return issuer and the hash that results from passing data to hash + // through the hash algorithm. + return {hash: await md.digest(), issuer}; + } + + // helper for modifying component during Hash First Degree Quads + modifyFirstDegreeComponent(id, component) { + if(component.termType !== 'BlankNode') { + return component; + } + /* Note: A mistake in the URDNA2015 spec that made its way into + implementations (and therefore must stay to avoid interop breakage) + resulted in an assigned canonical ID, if available for + `component.value`, not being used in place of `_:a`/`_:z`, so + we don't use it here. */ + return { + termType: 'BlankNode', + value: component.value === id ? '_:a' : '_:z' + }; + } + + // helper for getting a related predicate + getRelatedPredicate(quad) { + return `<${quad.predicate.value}>`; + } + + // helper for creating hash to related blank nodes map + async createHashToRelated(id, issuer) { + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + const hashToRelated = new Map(); + + // 2) Get a reference, quads, to the list of quads in the blank node to + // quads map for the key identifier. + const quads = this.blankNodeInfo.get(id).quads; + + // 3) For each quad in quads: + let i = 0; + for(const quad of quads) { + // Note: batch hashing related blank node quads 100 at a time + if(++i % 100 === 0) { + await this._yield(); + } + // 3.1) For each component in quad, if component is the subject, object, + // and graph name and it is a blank node that is not identified by + // identifier: + // steps 3.1.1 and 3.1.2 occur in helpers: + await Promise.all([ + this._addRelatedBlankNodeHash({ + quad, component: quad.subject, position: 's', + id, issuer, hashToRelated + }), + this._addRelatedBlankNodeHash({ + quad, component: quad.object, position: 'o', + id, issuer, hashToRelated + }), + this._addRelatedBlankNodeHash({ + quad, component: quad.graph, position: 'g', + id, issuer, hashToRelated + }) + ]); + } + + return hashToRelated; + } + + async _hashAndTrackBlankNode({id, hashToBlankNodes}) { + // 5.3.1) Create a hash, hash, according to the Hash First Degree + // Quads algorithm. + const hash = await this.hashFirstDegreeQuads(id); + + // 5.3.2) Add hash and identifier to hash to blank nodes map, + // creating a new entry if necessary. + const idList = hashToBlankNodes.get(hash); + if(!idList) { + hashToBlankNodes.set(hash, [id]); + } else { + idList.push(id); + } + } + + _addBlankNodeQuadInfo({quad, component}) { + if(component.termType !== 'BlankNode') { + return; + } + const id = component.value; + const info = this.blankNodeInfo.get(id); + if(info) { + info.quads.add(quad); + } else { + this.blankNodeInfo.set(id, {quads: new Set([quad]), hash: null}); + } + } + + async _addRelatedBlankNodeHash( + {quad, component, position, id, issuer, hashToRelated}) { + if(!(component.termType === 'BlankNode' && component.value !== id)) { + return; + } + // 3.1.1) Set hash to the result of the Hash Related Blank Node + // algorithm, passing the blank node identifier for component as + // related, quad, path identifier issuer as issuer, and position as + // either s, o, or g based on whether component is a subject, object, + // graph name, respectively. + const related = component.value; + const hash = await this.hashRelatedBlankNode( + related, quad, issuer, position); + + // 3.1.2) Add a mapping of hash to the blank node identifier for + // component to hash to related blank nodes map, adding an entry as + // necessary. + const entries = hashToRelated.get(hash); + if(entries) { + entries.push(related); + } else { + hashToRelated.set(hash, [related]); + } + } + + // canonical ids for 7.1 + _componentWithCanonicalId(component) { + if(component.termType === 'BlankNode' && + !component.value.startsWith(this.canonicalIssuer.prefix)) { + // create new BlankNode + return { + termType: 'BlankNode', + value: this.canonicalIssuer.getId(component.value) + }; + } + return component; + } + + async _yield() { + return new Promise(resolve => setImmediate(resolve)); + } +}; + +function _stringHashCompare(a, b) { + return a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0; +} + + +/***/ }, + +/***/ "./node_modules/jsonld/node_modules/rdf-canonize/lib/URDNA2015Sync.js" +/*!****************************************************************************!*\ + !*** ./node_modules/jsonld/node_modules/rdf-canonize/lib/URDNA2015Sync.js ***! + \****************************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. + */ + + +const IdentifierIssuer = __webpack_require__(/*! ./IdentifierIssuer */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/IdentifierIssuer.js"); +// FIXME: do not import; convert to requiring a +// hash factory +const MessageDigest = __webpack_require__(/*! ./MessageDigest */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/MessageDigest-browser.js"); +const Permuter = __webpack_require__(/*! ./Permuter */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/Permuter.js"); +const NQuads = __webpack_require__(/*! ./NQuads */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/NQuads.js"); + +module.exports = class URDNA2015Sync { + constructor({ + createMessageDigest = () => new MessageDigest('sha256'), + canonicalIdMap = new Map(), + maxDeepIterations = Infinity + } = {}) { + this.name = 'URDNA2015'; + this.blankNodeInfo = new Map(); + this.canonicalIssuer = new IdentifierIssuer('_:c14n', canonicalIdMap); + this.createMessageDigest = createMessageDigest; + this.maxDeepIterations = maxDeepIterations; + this.quads = null; + this.deepIterations = null; + } + + // 4.4) Normalization Algorithm + main(dataset) { + this.deepIterations = new Map(); + this.quads = dataset; + + // 1) Create the normalization state. + // 2) For every quad in input dataset: + for(const quad of dataset) { + // 2.1) For each blank node that occurs in the quad, add a reference + // to the quad using the blank node identifier in the blank node to + // quads map, creating a new entry if necessary. + this._addBlankNodeQuadInfo({quad, component: quad.subject}); + this._addBlankNodeQuadInfo({quad, component: quad.object}); + this._addBlankNodeQuadInfo({quad, component: quad.graph}); + } + + // 3) Create a list of non-normalized blank node identifiers + // non-normalized identifiers and populate it using the keys from the + // blank node to quads map. + // Note: We use a map here and it was generated during step 2. + + // 4) `simple` flag is skipped -- loop is optimized away. This optimization + // is permitted because there was a typo in the hash first degree quads + // algorithm in the URDNA2015 spec that was implemented widely making it + // such that it could not be fixed; the result was that the loop only + // needs to be run once and the first degree quad hashes will never change. + // 5.1-5.2 are skipped; first degree quad hashes are generated just once + // for all non-normalized blank nodes. + + // 5.3) For each blank node identifier identifier in non-normalized + // identifiers: + const hashToBlankNodes = new Map(); + const nonNormalized = [...this.blankNodeInfo.keys()]; + for(const id of nonNormalized) { + // steps 5.3.1 and 5.3.2: + this._hashAndTrackBlankNode({id, hashToBlankNodes}); + } + + // 5.4) For each hash to identifier list mapping in hash to blank + // nodes map, lexicographically-sorted by hash: + const hashes = [...hashToBlankNodes.keys()].sort(); + // optimize away second sort, gather non-unique hashes in order as we go + const nonUnique = []; + for(const hash of hashes) { + // 5.4.1) If the length of identifier list is greater than 1, + // continue to the next mapping. + const idList = hashToBlankNodes.get(hash); + if(idList.length > 1) { + nonUnique.push(idList); + continue; + } + + // 5.4.2) Use the Issue Identifier algorithm, passing canonical + // issuer and the single blank node identifier in identifier + // list, identifier, to issue a canonical replacement identifier + // for identifier. + const id = idList[0]; + this.canonicalIssuer.getId(id); + + // Note: These steps are skipped, optimized away since the loop + // only needs to be run once. + // 5.4.3) Remove identifier from non-normalized identifiers. + // 5.4.4) Remove hash from the hash to blank nodes map. + // 5.4.5) Set simple to true. + } + + // 6) For each hash to identifier list mapping in hash to blank nodes map, + // lexicographically-sorted by hash: + // Note: sort optimized away, use `nonUnique`. + for(const idList of nonUnique) { + // 6.1) Create hash path list where each item will be a result of + // running the Hash N-Degree Quads algorithm. + const hashPathList = []; + + // 6.2) For each blank node identifier identifier in identifier list: + for(const id of idList) { + // 6.2.1) If a canonical identifier has already been issued for + // identifier, continue to the next identifier. + if(this.canonicalIssuer.hasId(id)) { + continue; + } + + // 6.2.2) Create temporary issuer, an identifier issuer + // initialized with the prefix _:b. + const issuer = new IdentifierIssuer('_:b'); + + // 6.2.3) Use the Issue Identifier algorithm, passing temporary + // issuer and identifier, to issue a new temporary blank node + // identifier for identifier. + issuer.getId(id); + + // 6.2.4) Run the Hash N-Degree Quads algorithm, passing + // temporary issuer, and append the result to the hash path list. + const result = this.hashNDegreeQuads(id, issuer); + hashPathList.push(result); + } + + // 6.3) For each result in the hash path list, + // lexicographically-sorted by the hash in result: + hashPathList.sort(_stringHashCompare); + for(const result of hashPathList) { + // 6.3.1) For each blank node identifier, existing identifier, + // that was issued a temporary identifier by identifier issuer + // in result, issue a canonical identifier, in the same order, + // using the Issue Identifier algorithm, passing canonical + // issuer and existing identifier. + const oldIds = result.issuer.getOldIds(); + for(const id of oldIds) { + this.canonicalIssuer.getId(id); + } + } + } + + /* Note: At this point all blank nodes in the set of RDF quads have been + assigned canonical identifiers, which have been stored in the canonical + issuer. Here each quad is updated by assigning each of its blank nodes + its new identifier. */ + + // 7) For each quad, quad, in input dataset: + const normalized = []; + for(const quad of this.quads) { + // 7.1) Create a copy, quad copy, of quad and replace any existing + // blank node identifiers using the canonical identifiers + // previously issued by canonical issuer. + // Note: We optimize away the copy here. + const nQuad = NQuads.serializeQuadComponents( + this._componentWithCanonicalId({component: quad.subject}), + quad.predicate, + this._componentWithCanonicalId({component: quad.object}), + this._componentWithCanonicalId({component: quad.graph}) + ); + // 7.2) Add quad copy to the normalized dataset. + normalized.push(nQuad); + } + + // sort normalized output + normalized.sort(); + + // 8) Return the normalized dataset. + return normalized.join(''); + } + + // 4.6) Hash First Degree Quads + hashFirstDegreeQuads(id) { + // 1) Initialize nquads to an empty list. It will be used to store quads in + // N-Quads format. + const nquads = []; + + // 2) Get the list of quads `quads` associated with the reference blank node + // identifier in the blank node to quads map. + const info = this.blankNodeInfo.get(id); + const quads = info.quads; + + // 3) For each quad `quad` in `quads`: + for(const quad of quads) { + // 3.1) Serialize the quad in N-Quads format with the following special + // rule: + + // 3.1.1) If any component in quad is an blank node, then serialize it + // using a special identifier as follows: + const copy = { + subject: null, predicate: quad.predicate, object: null, graph: null + }; + // 3.1.2) If the blank node's existing blank node identifier matches + // the reference blank node identifier then use the blank node + // identifier _:a, otherwise, use the blank node identifier _:z. + copy.subject = this.modifyFirstDegreeComponent( + id, quad.subject, 'subject'); + copy.object = this.modifyFirstDegreeComponent( + id, quad.object, 'object'); + copy.graph = this.modifyFirstDegreeComponent( + id, quad.graph, 'graph'); + nquads.push(NQuads.serializeQuad(copy)); + } + + // 4) Sort nquads in lexicographical order. + nquads.sort(); + + // 5) Return the hash that results from passing the sorted, joined nquads + // through the hash algorithm. + const md = this.createMessageDigest(); + for(const nquad of nquads) { + md.update(nquad); + } + info.hash = md.digest(); + return info.hash; + } + + // 4.7) Hash Related Blank Node + hashRelatedBlankNode(related, quad, issuer, position) { + // 1) Set the identifier to use for related, preferring first the canonical + // identifier for related if issued, second the identifier issued by issuer + // if issued, and last, if necessary, the result of the Hash First Degree + // Quads algorithm, passing related. + let id; + if(this.canonicalIssuer.hasId(related)) { + id = this.canonicalIssuer.getId(related); + } else if(issuer.hasId(related)) { + id = issuer.getId(related); + } else { + id = this.blankNodeInfo.get(related).hash; + } + + // 2) Initialize a string input to the value of position. + // Note: We use a hash object instead. + const md = this.createMessageDigest(); + md.update(position); + + // 3) If position is not g, append <, the value of the predicate in quad, + // and > to input. + if(position !== 'g') { + md.update(this.getRelatedPredicate(quad)); + } + + // 4) Append identifier to input. + md.update(id); + + // 5) Return the hash that results from passing input through the hash + // algorithm. + return md.digest(); + } + + // 4.8) Hash N-Degree Quads + hashNDegreeQuads(id, issuer) { + const deepIterations = this.deepIterations.get(id) || 0; + if(deepIterations > this.maxDeepIterations) { + throw new Error( + `Maximum deep iterations (${this.maxDeepIterations}) exceeded.`); + } + this.deepIterations.set(id, deepIterations + 1); + + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + // Note: 2) and 3) handled within `createHashToRelated` + const md = this.createMessageDigest(); + const hashToRelated = this.createHashToRelated(id, issuer); + + // 4) Create an empty string, data to hash. + // Note: We created a hash object `md` above instead. + + // 5) For each related hash to blank node list mapping in hash to related + // blank nodes map, sorted lexicographically by related hash: + const hashes = [...hashToRelated.keys()].sort(); + for(const hash of hashes) { + // 5.1) Append the related hash to the data to hash. + md.update(hash); + + // 5.2) Create a string chosen path. + let chosenPath = ''; + + // 5.3) Create an unset chosen issuer variable. + let chosenIssuer; + + // 5.4) For each permutation of blank node list: + const permuter = new Permuter(hashToRelated.get(hash)); + while(permuter.hasNext()) { + const permutation = permuter.next(); + + // 5.4.1) Create a copy of issuer, issuer copy. + let issuerCopy = issuer.clone(); + + // 5.4.2) Create a string path. + let path = ''; + + // 5.4.3) Create a recursion list, to store blank node identifiers + // that must be recursively processed by this algorithm. + const recursionList = []; + + // 5.4.4) For each related in permutation: + let nextPermutation = false; + for(const related of permutation) { + // 5.4.4.1) If a canonical identifier has been issued for + // related, append it to path. + if(this.canonicalIssuer.hasId(related)) { + path += this.canonicalIssuer.getId(related); + } else { + // 5.4.4.2) Otherwise: + // 5.4.4.2.1) If issuer copy has not issued an identifier for + // related, append related to recursion list. + if(!issuerCopy.hasId(related)) { + recursionList.push(related); + } + // 5.4.4.2.2) Use the Issue Identifier algorithm, passing + // issuer copy and related and append the result to path. + path += issuerCopy.getId(related); + } + + // 5.4.4.3) If chosen path is not empty and the length of path + // is greater than or equal to the length of chosen path and + // path is lexicographically greater than chosen path, then + // skip to the next permutation. + // Note: Comparing path length to chosen path length can be optimized + // away; only compare lexicographically. + if(chosenPath.length !== 0 && path > chosenPath) { + nextPermutation = true; + break; + } + } + + if(nextPermutation) { + continue; + } + + // 5.4.5) For each related in recursion list: + for(const related of recursionList) { + // 5.4.5.1) Set result to the result of recursively executing + // the Hash N-Degree Quads algorithm, passing related for + // identifier and issuer copy for path identifier issuer. + const result = this.hashNDegreeQuads(related, issuerCopy); + + // 5.4.5.2) Use the Issue Identifier algorithm, passing issuer + // copy and related and append the result to path. + path += issuerCopy.getId(related); + + // 5.4.5.3) Append <, the hash in result, and > to path. + path += `<${result.hash}>`; + + // 5.4.5.4) Set issuer copy to the identifier issuer in + // result. + issuerCopy = result.issuer; + + // 5.4.5.5) If chosen path is not empty and the length of path + // is greater than or equal to the length of chosen path and + // path is lexicographically greater than chosen path, then + // skip to the next permutation. + // Note: Comparing path length to chosen path length can be optimized + // away; only compare lexicographically. + if(chosenPath.length !== 0 && path > chosenPath) { + nextPermutation = true; + break; + } + } + + if(nextPermutation) { + continue; + } + + // 5.4.6) If chosen path is empty or path is lexicographically + // less than chosen path, set chosen path to path and chosen + // issuer to issuer copy. + if(chosenPath.length === 0 || path < chosenPath) { + chosenPath = path; + chosenIssuer = issuerCopy; + } + } + + // 5.5) Append chosen path to data to hash. + md.update(chosenPath); + + // 5.6) Replace issuer, by reference, with chosen issuer. + issuer = chosenIssuer; + } + + // 6) Return issuer and the hash that results from passing data to hash + // through the hash algorithm. + return {hash: md.digest(), issuer}; + } + + // helper for modifying component during Hash First Degree Quads + modifyFirstDegreeComponent(id, component) { + if(component.termType !== 'BlankNode') { + return component; + } + /* Note: A mistake in the URDNA2015 spec that made its way into + implementations (and therefore must stay to avoid interop breakage) + resulted in an assigned canonical ID, if available for + `component.value`, not being used in place of `_:a`/`_:z`, so + we don't use it here. */ + return { + termType: 'BlankNode', + value: component.value === id ? '_:a' : '_:z' + }; + } + + // helper for getting a related predicate + getRelatedPredicate(quad) { + return `<${quad.predicate.value}>`; + } + + // helper for creating hash to related blank nodes map + createHashToRelated(id, issuer) { + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + const hashToRelated = new Map(); + + // 2) Get a reference, quads, to the list of quads in the blank node to + // quads map for the key identifier. + const quads = this.blankNodeInfo.get(id).quads; + + // 3) For each quad in quads: + for(const quad of quads) { + // 3.1) For each component in quad, if component is the subject, object, + // or graph name and it is a blank node that is not identified by + // identifier: + // steps 3.1.1 and 3.1.2 occur in helpers: + this._addRelatedBlankNodeHash({ + quad, component: quad.subject, position: 's', + id, issuer, hashToRelated + }); + this._addRelatedBlankNodeHash({ + quad, component: quad.object, position: 'o', + id, issuer, hashToRelated + }); + this._addRelatedBlankNodeHash({ + quad, component: quad.graph, position: 'g', + id, issuer, hashToRelated + }); + } + + return hashToRelated; + } + + _hashAndTrackBlankNode({id, hashToBlankNodes}) { + // 5.3.1) Create a hash, hash, according to the Hash First Degree + // Quads algorithm. + const hash = this.hashFirstDegreeQuads(id); + + // 5.3.2) Add hash and identifier to hash to blank nodes map, + // creating a new entry if necessary. + const idList = hashToBlankNodes.get(hash); + if(!idList) { + hashToBlankNodes.set(hash, [id]); + } else { + idList.push(id); + } + } + + _addBlankNodeQuadInfo({quad, component}) { + if(component.termType !== 'BlankNode') { + return; + } + const id = component.value; + const info = this.blankNodeInfo.get(id); + if(info) { + info.quads.add(quad); + } else { + this.blankNodeInfo.set(id, {quads: new Set([quad]), hash: null}); + } + } + + _addRelatedBlankNodeHash( + {quad, component, position, id, issuer, hashToRelated}) { + if(!(component.termType === 'BlankNode' && component.value !== id)) { + return; + } + // 3.1.1) Set hash to the result of the Hash Related Blank Node + // algorithm, passing the blank node identifier for component as + // related, quad, path identifier issuer as issuer, and position as + // either s, o, or g based on whether component is a subject, object, + // graph name, respectively. + const related = component.value; + const hash = this.hashRelatedBlankNode(related, quad, issuer, position); + + // 3.1.2) Add a mapping of hash to the blank node identifier for + // component to hash to related blank nodes map, adding an entry as + // necessary. + const entries = hashToRelated.get(hash); + if(entries) { + entries.push(related); + } else { + hashToRelated.set(hash, [related]); + } + } + + // canonical ids for 7.1 + _componentWithCanonicalId({component}) { + if(component.termType === 'BlankNode' && + !component.value.startsWith(this.canonicalIssuer.prefix)) { + // create new BlankNode + return { + termType: 'BlankNode', + value: this.canonicalIssuer.getId(component.value) + }; + } + return component; + } +}; + +function _stringHashCompare(a, b) { + return a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0; +} + + +/***/ }, + +/***/ "./node_modules/jsonld/node_modules/rdf-canonize/lib/URGNA2012.js" +/*!************************************************************************!*\ + !*** ./node_modules/jsonld/node_modules/rdf-canonize/lib/URGNA2012.js ***! + \************************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. + */ + + +const MessageDigest = __webpack_require__(/*! ./MessageDigest */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/MessageDigest-browser.js"); +const URDNA2015 = __webpack_require__(/*! ./URDNA2015 */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/URDNA2015.js"); + +module.exports = class URDNA2012 extends URDNA2015 { + constructor() { + super(); + this.name = 'URGNA2012'; + this.createMessageDigest = () => new MessageDigest('sha1'); + } + + // helper for modifying component during Hash First Degree Quads + modifyFirstDegreeComponent(id, component, key) { + if(component.termType !== 'BlankNode') { + return component; + } + if(key === 'graph') { + return { + termType: 'BlankNode', + value: '_:g' + }; + } + return { + termType: 'BlankNode', + value: (component.value === id ? '_:a' : '_:z') + }; + } + + // helper for getting a related predicate + getRelatedPredicate(quad) { + return quad.predicate.value; + } + + // helper for creating hash to related blank nodes map + async createHashToRelated(id, issuer) { + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + const hashToRelated = new Map(); + + // 2) Get a reference, quads, to the list of quads in the blank node to + // quads map for the key identifier. + const quads = this.blankNodeInfo.get(id).quads; + + // 3) For each quad in quads: + let i = 0; + for(const quad of quads) { + // 3.1) If the quad's subject is a blank node that does not match + // identifier, set hash to the result of the Hash Related Blank Node + // algorithm, passing the blank node identifier for subject as related, + // quad, path identifier issuer as issuer, and p as position. + let position; + let related; + if(quad.subject.termType === 'BlankNode' && quad.subject.value !== id) { + related = quad.subject.value; + position = 'p'; + } else if( + quad.object.termType === 'BlankNode' && quad.object.value !== id) { + // 3.2) Otherwise, if quad's object is a blank node that does not match + // identifier, to the result of the Hash Related Blank Node algorithm, + // passing the blank node identifier for object as related, quad, path + // identifier issuer as issuer, and r as position. + related = quad.object.value; + position = 'r'; + } else { + // 3.3) Otherwise, continue to the next quad. + continue; + } + // Note: batch hashing related blank nodes 100 at a time + if(++i % 100 === 0) { + await this._yield(); + } + // 3.4) Add a mapping of hash to the blank node identifier for the + // component that matched (subject or object) to hash to related blank + // nodes map, adding an entry as necessary. + const hash = await this.hashRelatedBlankNode( + related, quad, issuer, position); + const entries = hashToRelated.get(hash); + if(entries) { + entries.push(related); + } else { + hashToRelated.set(hash, [related]); + } + } + + return hashToRelated; + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/node_modules/rdf-canonize/lib/URGNA2012Sync.js" +/*!****************************************************************************!*\ + !*** ./node_modules/jsonld/node_modules/rdf-canonize/lib/URGNA2012Sync.js ***! + \****************************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved. + */ + + +const MessageDigest = __webpack_require__(/*! ./MessageDigest */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/MessageDigest-browser.js"); +const URDNA2015Sync = __webpack_require__(/*! ./URDNA2015Sync */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/URDNA2015Sync.js"); + +module.exports = class URDNA2012Sync extends URDNA2015Sync { + constructor() { + super(); + this.name = 'URGNA2012'; + this.createMessageDigest = () => new MessageDigest('sha1'); + } + + // helper for modifying component during Hash First Degree Quads + modifyFirstDegreeComponent(id, component, key) { + if(component.termType !== 'BlankNode') { + return component; + } + if(key === 'graph') { + return { + termType: 'BlankNode', + value: '_:g' + }; + } + return { + termType: 'BlankNode', + value: (component.value === id ? '_:a' : '_:z') + }; + } + + // helper for getting a related predicate + getRelatedPredicate(quad) { + return quad.predicate.value; + } + + // helper for creating hash to related blank nodes map + createHashToRelated(id, issuer) { + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + const hashToRelated = new Map(); + + // 2) Get a reference, quads, to the list of quads in the blank node to + // quads map for the key identifier. + const quads = this.blankNodeInfo.get(id).quads; + + // 3) For each quad in quads: + for(const quad of quads) { + // 3.1) If the quad's subject is a blank node that does not match + // identifier, set hash to the result of the Hash Related Blank Node + // algorithm, passing the blank node identifier for subject as related, + // quad, path identifier issuer as issuer, and p as position. + let position; + let related; + if(quad.subject.termType === 'BlankNode' && quad.subject.value !== id) { + related = quad.subject.value; + position = 'p'; + } else if( + quad.object.termType === 'BlankNode' && quad.object.value !== id) { + // 3.2) Otherwise, if quad's object is a blank node that does not match + // identifier, to the result of the Hash Related Blank Node algorithm, + // passing the blank node identifier for object as related, quad, path + // identifier issuer as issuer, and r as position. + related = quad.object.value; + position = 'r'; + } else { + // 3.3) Otherwise, continue to the next quad. + continue; + } + // 3.4) Add a mapping of hash to the blank node identifier for the + // component that matched (subject or object) to hash to related blank + // nodes map, adding an entry as necessary. + const hash = this.hashRelatedBlankNode(related, quad, issuer, position); + const entries = hashToRelated.get(hash); + if(entries) { + entries.push(related); + } else { + hashToRelated.set(hash, [related]); + } + } + + return hashToRelated; + } +}; + + +/***/ }, + +/***/ "./node_modules/jsonld/node_modules/rdf-canonize/lib/index.js" +/*!********************************************************************!*\ + !*** ./node_modules/jsonld/node_modules/rdf-canonize/lib/index.js ***! + \********************************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/** + * An implementation of the RDF Dataset Normalization specification. + * This library works in the browser and node.js. + * + * BSD 3-Clause License + * Copyright (c) 2016-2023 Digital Bazaar, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of the Digital Bazaar, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +const URDNA2015 = __webpack_require__(/*! ./URDNA2015 */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/URDNA2015.js"); +const URGNA2012 = __webpack_require__(/*! ./URGNA2012 */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/URGNA2012.js"); +const URDNA2015Sync = __webpack_require__(/*! ./URDNA2015Sync */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/URDNA2015Sync.js"); +const URGNA2012Sync = __webpack_require__(/*! ./URGNA2012Sync */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/URGNA2012Sync.js"); + +// optional native support +let rdfCanonizeNative; +try { + rdfCanonizeNative = __webpack_require__(/*! rdf-canonize-native */ "?f4a3"); +} catch(e) {} + +// return a dataset from input dataset or legacy dataset +function _inputToDataset(input/*, options*/) { + // back-compat with legacy dataset + if(!Array.isArray(input)) { + return exports.NQuads.legacyDatasetToQuads(input); + } + return input; +} + +// expose helpers +exports.NQuads = __webpack_require__(/*! ./NQuads */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/NQuads.js"); +exports.IdentifierIssuer = __webpack_require__(/*! ./IdentifierIssuer */ "./node_modules/jsonld/node_modules/rdf-canonize/lib/IdentifierIssuer.js"); + +/** + * Get or set native API. + * + * @param api the native API. + * + * @return the currently set native API. + */ +exports._rdfCanonizeNative = function(api) { + if(api) { + rdfCanonizeNative = api; + } + return rdfCanonizeNative; +}; + +/** + * Asynchronously canonizes an RDF dataset. + * + * @param {Array|object|string} input - The input to canonize given as a + * dataset or legacy dataset. + * @param {object} options - The options to use: + * {string} algorithm - The canonicalization algorithm to use, `URDNA2015` or + * `URGNA2012`. + * {Function} [createMessageDigest] - A factory function for creating a + * `MessageDigest` interface that overrides the built-in message digest + * implementation used by the canonize algorithm; note that using a hash + * algorithm (or HMAC algorithm) that differs from the one specified by + * the canonize algorithm will result in different output. + * {Map} [canonicalIdMap] - An optional Map to be populated by the canonical + * identifier issuer with the bnode identifier mapping generated by the + * canonicalization algorithm. + * {boolean} [useNative=false] - Use native implementation. + * {number} [maxDeepIterations=Infinity] - The maximum number of times to run + * deep comparison algorithms (such as the N-Degree Hash Quads algorithm + * used in URDNA2015) before bailing out and throwing an error; this is a + * useful setting for preventing wasted CPU cycles or DoS when canonizing + * meaningless or potentially malicious datasets, a recommended value is + * `1`. + * + * @return a Promise that resolves to the canonicalized RDF Dataset. + */ +exports.canonize = async function(input, options) { + const dataset = _inputToDataset(input, options); + + if(options.useNative) { + if(!rdfCanonizeNative) { + throw new Error('rdf-canonize-native not available'); + } + if(options.createMessageDigest) { + throw new Error( + '"createMessageDigest" cannot be used with "useNative".'); + } + return new Promise((resolve, reject) => + rdfCanonizeNative.canonize(dataset, options, (err, canonical) => + err ? reject(err) : resolve(canonical))); + } + + if(options.algorithm === 'URDNA2015') { + return new URDNA2015(options).main(dataset); + } + if(options.algorithm === 'URGNA2012') { + if(options.createMessageDigest) { + throw new Error( + '"createMessageDigest" cannot be used with "URGNA2012".'); + } + return new URGNA2012(options).main(dataset); + } + if(!('algorithm' in options)) { + throw new Error('No RDF Dataset Canonicalization algorithm specified.'); + } + throw new Error( + 'Invalid RDF Dataset Canonicalization algorithm: ' + options.algorithm); +}; + +/** + * This method is no longer available in the public API, it is for testing + * only. It synchronously canonizes an RDF dataset and does not work in the + * browser. + * + * @param {Array|object|string} input - The input to canonize given as a + * dataset or legacy dataset. + * @param {object} options - The options to use: + * {string} algorithm - The canonicalization algorithm to use, `URDNA2015` or + * `URGNA2012`. + * {Function} [createMessageDigest] - A factory function for creating a + * `MessageDigest` interface that overrides the built-in message digest + * implementation used by the canonize algorithm; note that using a hash + * algorithm (or HMAC algorithm) that differs from the one specified by + * the canonize algorithm will result in different output. + * {boolean} [useNative=false] - Use native implementation. + * {number} [maxDeepIterations=Infinity] - The maximum number of times to run + * deep comparison algorithms (such as the N-Degree Hash Quads algorithm + * used in URDNA2015) before bailing out and throwing an error; this is a + * useful setting for preventing wasted CPU cycles or DoS when canonizing + * meaningless or potentially malicious datasets, a recommended value is + * `1`. + * + * @return the RDF dataset in canonical form. + */ +exports._canonizeSync = function(input, options) { + const dataset = _inputToDataset(input, options); + + if(options.useNative) { + if(!rdfCanonizeNative) { + throw new Error('rdf-canonize-native not available'); + } + if(options.createMessageDigest) { + throw new Error( + '"createMessageDigest" cannot be used with "useNative".'); + } + return rdfCanonizeNative.canonizeSync(dataset, options); + } + if(options.algorithm === 'URDNA2015') { + return new URDNA2015Sync(options).main(dataset); + } + if(options.algorithm === 'URGNA2012') { + if(options.createMessageDigest) { + throw new Error( + '"createMessageDigest" cannot be used with "URGNA2012".'); + } + return new URGNA2012Sync(options).main(dataset); + } + if(!('algorithm' in options)) { + throw new Error('No RDF Dataset Canonicalization algorithm specified.'); + } + throw new Error( + 'Invalid RDF Dataset Canonicalization algorithm: ' + options.algorithm); +}; + + +/***/ }, + +/***/ "./node_modules/klona/dist/index.mjs" +/*!*******************************************!*\ + !*** ./node_modules/klona/dist/index.mjs ***! + \*******************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ klona: () => (/* binding */ klona) +/* harmony export */ }); +function klona(x) { + if (typeof x !== 'object') return x; + + var k, tmp, str=Object.prototype.toString.call(x); + + if (str === '[object Object]') { + if (x.constructor !== Object && typeof x.constructor === 'function') { + tmp = new x.constructor(); + for (k in x) { + if (x.hasOwnProperty(k) && tmp[k] !== x[k]) { + tmp[k] = klona(x[k]); + } + } + } else { + tmp = {}; // null + for (k in x) { + if (k === '__proto__') { + Object.defineProperty(tmp, k, { + value: klona(x[k]), + configurable: true, + enumerable: true, + writable: true, + }); + } else { + tmp[k] = klona(x[k]); + } + } + } + return tmp; + } + + if (str === '[object Array]') { + k = x.length; + for (tmp=Array(k); k--;) { + tmp[k] = klona(x[k]); + } + return tmp; + } + + if (str === '[object Set]') { + tmp = new Set; + x.forEach(function (val) { + tmp.add(klona(val)); + }); + return tmp; + } + + if (str === '[object Map]') { + tmp = new Map; + x.forEach(function (val, key) { + tmp.set(klona(key), klona(val)); + }); + return tmp; + } + + if (str === '[object Date]') { + return new Date(+x); + } + + if (str === '[object RegExp]') { + tmp = new RegExp(x.source, x.flags); + tmp.lastIndex = x.lastIndex; + return tmp; + } + + if (str === '[object DataView]') { + return new x.constructor( klona(x.buffer) ); + } + + if (str === '[object ArrayBuffer]') { + return x.slice(0); + } + + // ArrayBuffer.isView(x) + // ~> `new` bcuz `Buffer.slice` => ref + if (str.slice(-6) === 'Array]') { + return new x.constructor(x); + } + + return x; +} + + +/***/ }, + +/***/ "./node_modules/ky/distribution/core/Ky.js" +/*!*************************************************!*\ + !*** ./node_modules/ky/distribution/core/Ky.js ***! + \*************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Ky: () => (/* binding */ Ky) +/* harmony export */ }); +/* harmony import */ var _errors_HTTPError_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors/HTTPError.js */ "./node_modules/ky/distribution/errors/HTTPError.js"); +/* harmony import */ var _errors_NonError_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors/NonError.js */ "./node_modules/ky/distribution/errors/NonError.js"); +/* harmony import */ var _errors_ForceRetryError_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors/ForceRetryError.js */ "./node_modules/ky/distribution/errors/ForceRetryError.js"); +/* harmony import */ var _utils_body_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/body.js */ "./node_modules/ky/distribution/utils/body.js"); +/* harmony import */ var _utils_merge_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/merge.js */ "./node_modules/ky/distribution/utils/merge.js"); +/* harmony import */ var _utils_normalize_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/normalize.js */ "./node_modules/ky/distribution/utils/normalize.js"); +/* harmony import */ var _utils_timeout_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/timeout.js */ "./node_modules/ky/distribution/utils/timeout.js"); +/* harmony import */ var _utils_delay_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/delay.js */ "./node_modules/ky/distribution/utils/delay.js"); +/* harmony import */ var _utils_options_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/options.js */ "./node_modules/ky/distribution/utils/options.js"); +/* harmony import */ var _utils_type_guards_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/type-guards.js */ "./node_modules/ky/distribution/utils/type-guards.js"); +/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./constants.js */ "./node_modules/ky/distribution/core/constants.js"); + + + + + + + + + + + +class Ky { + static create(input, options) { + const ky = new Ky(input, options); + const function_ = async () => { + if (typeof ky.#options.timeout === 'number' && ky.#options.timeout > _constants_js__WEBPACK_IMPORTED_MODULE_10__.maxSafeTimeout) { + throw new RangeError(`The \`timeout\` option cannot be greater than ${_constants_js__WEBPACK_IMPORTED_MODULE_10__.maxSafeTimeout}`); + } + // Delay the fetch so that body method shortcuts can set the Accept header + await Promise.resolve(); + // Before using ky.request, _fetch clones it and saves the clone for future retries to use. + // If retry is not needed, close the cloned request's ReadableStream for memory safety. + let response = await ky.#fetch(); + for (const hook of ky.#options.hooks.afterResponse) { + // Clone the response before passing to hook so we can cancel it if needed + const clonedResponse = ky.#decorateResponse(response.clone()); + // eslint-disable-next-line no-await-in-loop + const modifiedResponse = await hook(ky.request, ky.#getNormalizedOptions(), clonedResponse, { retryCount: ky.#retryCount }); + if (modifiedResponse instanceof globalThis.Response) { + response = modifiedResponse; + } + if (modifiedResponse instanceof _constants_js__WEBPACK_IMPORTED_MODULE_10__.RetryMarker) { + // Cancel both the cloned response passed to the hook and the current response + // to prevent resource leaks (especially important in Deno/Bun) + // eslint-disable-next-line no-await-in-loop + await Promise.all([ + clonedResponse.body?.cancel(), + response.body?.cancel(), + ]); + throw new _errors_ForceRetryError_js__WEBPACK_IMPORTED_MODULE_2__.ForceRetryError(modifiedResponse.options); + } + } + ky.#decorateResponse(response); + if (!response.ok && (typeof ky.#options.throwHttpErrors === 'function' + ? ky.#options.throwHttpErrors(response.status) + : ky.#options.throwHttpErrors)) { + let error = new _errors_HTTPError_js__WEBPACK_IMPORTED_MODULE_0__.HTTPError(response, ky.request, ky.#getNormalizedOptions()); + for (const hook of ky.#options.hooks.beforeError) { + // eslint-disable-next-line no-await-in-loop + error = await hook(error, { retryCount: ky.#retryCount }); + } + throw error; + } + // If `onDownloadProgress` is passed, it uses the stream API internally + if (ky.#options.onDownloadProgress) { + if (typeof ky.#options.onDownloadProgress !== 'function') { + throw new TypeError('The `onDownloadProgress` option must be a function'); + } + if (!_constants_js__WEBPACK_IMPORTED_MODULE_10__.supportsResponseStreams) { + throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.'); + } + return (0,_utils_body_js__WEBPACK_IMPORTED_MODULE_3__.streamResponse)(response.clone(), ky.#options.onDownloadProgress); + } + return response; + }; + // Always wrap in #retry to catch forced retries from afterResponse hooks + // Method retriability is checked in #calculateRetryDelay for non-forced retries + const result = ky.#retry(function_) + .finally(async () => { + const originalRequest = ky.#originalRequest; + const cleanupPromises = []; + if (originalRequest && !originalRequest.bodyUsed) { + cleanupPromises.push(originalRequest.body?.cancel()); + } + if (!ky.request.bodyUsed) { + cleanupPromises.push(ky.request.body?.cancel()); + } + await Promise.all(cleanupPromises); + }); + for (const [type, mimeType] of Object.entries(_constants_js__WEBPACK_IMPORTED_MODULE_10__.responseTypes)) { + // Only expose `.bytes()` when the environment implements it. + if (type === 'bytes' + && typeof globalThis.Response?.prototype?.bytes !== 'function') { + continue; + } + result[type] = async () => { + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType); + const response = await result; + if (type === 'json') { + if (response.status === 204) { + return ''; + } + const text = await response.text(); + if (text === '') { + return ''; + } + if (options.parseJson) { + return options.parseJson(text); + } + return JSON.parse(text); + } + return response[type](); + }; + } + return result; + } + // eslint-disable-next-line unicorn/prevent-abbreviations + static #normalizeSearchParams(searchParams) { + // Filter out undefined values from plain objects + if (searchParams && typeof searchParams === 'object' && !Array.isArray(searchParams) && !(searchParams instanceof URLSearchParams)) { + return Object.fromEntries(Object.entries(searchParams).filter(([, value]) => value !== undefined)); + } + return searchParams; + } + request; + #abortController; + #retryCount = 0; + // eslint-disable-next-line @typescript-eslint/prefer-readonly -- False positive: #input is reassigned on line 202 + #input; + #options; + #originalRequest; + #userProvidedAbortSignal; + #cachedNormalizedOptions; + // eslint-disable-next-line complexity + constructor(input, options = {}) { + this.#input = input; + this.#options = { + ...options, + headers: (0,_utils_merge_js__WEBPACK_IMPORTED_MODULE_4__.mergeHeaders)(this.#input.headers, options.headers), + hooks: (0,_utils_merge_js__WEBPACK_IMPORTED_MODULE_4__.mergeHooks)({ + beforeRequest: [], + beforeRetry: [], + beforeError: [], + afterResponse: [], + }, options.hooks), + method: (0,_utils_normalize_js__WEBPACK_IMPORTED_MODULE_5__.normalizeRequestMethod)(options.method ?? this.#input.method ?? 'GET'), + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + prefixUrl: String(options.prefixUrl || ''), + retry: (0,_utils_normalize_js__WEBPACK_IMPORTED_MODULE_5__.normalizeRetryOptions)(options.retry), + throwHttpErrors: options.throwHttpErrors ?? true, + timeout: options.timeout ?? 10_000, + fetch: options.fetch ?? globalThis.fetch.bind(globalThis), + context: options.context ?? {}, + }; + if (typeof this.#input !== 'string' && !(this.#input instanceof URL || this.#input instanceof globalThis.Request)) { + throw new TypeError('`input` must be a string, URL, or Request'); + } + if (this.#options.prefixUrl && typeof this.#input === 'string') { + if (this.#input.startsWith('/')) { + throw new Error('`input` must not begin with a slash when using `prefixUrl`'); + } + if (!this.#options.prefixUrl.endsWith('/')) { + this.#options.prefixUrl += '/'; + } + this.#input = this.#options.prefixUrl + this.#input; + } + if (_constants_js__WEBPACK_IMPORTED_MODULE_10__.supportsAbortController && _constants_js__WEBPACK_IMPORTED_MODULE_10__.supportsAbortSignal) { + this.#userProvidedAbortSignal = this.#options.signal ?? this.#input.signal; + this.#abortController = new globalThis.AbortController(); + this.#options.signal = this.#userProvidedAbortSignal ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController.signal]) : this.#abortController.signal; + } + if (_constants_js__WEBPACK_IMPORTED_MODULE_10__.supportsRequestStreams) { + // @ts-expect-error - Types are outdated. + this.#options.duplex = 'half'; + } + if (this.#options.json !== undefined) { + this.#options.body = this.#options.stringifyJson?.(this.#options.json) ?? JSON.stringify(this.#options.json); + this.#options.headers.set('content-type', this.#options.headers.get('content-type') ?? 'application/json'); + } + // To provide correct form boundary, Content-Type header should be deleted when creating Request from another Request with FormData/URLSearchParams body + // Only delete if user didn't explicitly provide a custom content-type + const userProvidedContentType = options.headers && new globalThis.Headers(options.headers).has('content-type'); + if (this.#input instanceof globalThis.Request + && ((_constants_js__WEBPACK_IMPORTED_MODULE_10__.supportsFormData && this.#options.body instanceof globalThis.FormData) || this.#options.body instanceof URLSearchParams) + && !userProvidedContentType) { + this.#options.headers.delete('content-type'); + } + this.request = new globalThis.Request(this.#input, this.#options); + if ((0,_utils_options_js__WEBPACK_IMPORTED_MODULE_8__.hasSearchParameters)(this.#options.searchParams)) { + // eslint-disable-next-line unicorn/prevent-abbreviations + const textSearchParams = typeof this.#options.searchParams === 'string' + ? this.#options.searchParams.replace(/^\?/, '') + : new URLSearchParams(Ky.#normalizeSearchParams(this.#options.searchParams)).toString(); + // eslint-disable-next-line unicorn/prevent-abbreviations + const searchParams = '?' + textSearchParams; + const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams); + // Recreate request with the updated URL. We already have all options in this.#options, including duplex. + this.request = new globalThis.Request(url, this.#options); + } + // If `onUploadProgress` is passed, it uses the stream API internally + if (this.#options.onUploadProgress) { + if (typeof this.#options.onUploadProgress !== 'function') { + throw new TypeError('The `onUploadProgress` option must be a function'); + } + if (!_constants_js__WEBPACK_IMPORTED_MODULE_10__.supportsRequestStreams) { + throw new Error('Request streams are not supported in your environment. The `duplex` option for `Request` is not available.'); + } + this.request = this.#wrapRequestWithUploadProgress(this.request, this.#options.body ?? undefined); + } + } + #calculateDelay() { + const retryDelay = this.#options.retry.delay(this.#retryCount); + let jitteredDelay = retryDelay; + if (this.#options.retry.jitter === true) { + jitteredDelay = Math.random() * retryDelay; + } + else if (typeof this.#options.retry.jitter === 'function') { + jitteredDelay = this.#options.retry.jitter(retryDelay); + if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) { + jitteredDelay = retryDelay; + } + } + // Handle undefined backoffLimit by treating it as no limit (Infinity) + const backoffLimit = this.#options.retry.backoffLimit ?? Number.POSITIVE_INFINITY; + return Math.min(backoffLimit, jitteredDelay); + } + async #calculateRetryDelay(error) { + this.#retryCount++; + if (this.#retryCount > this.#options.retry.limit) { + throw error; + } + // Wrap non-Error throws to ensure consistent error handling + const errorObject = error instanceof Error ? error : new _errors_NonError_js__WEBPACK_IMPORTED_MODULE_1__.NonError(error); + // Handle forced retry from afterResponse hook - skip method check and shouldRetry + if (errorObject instanceof _errors_ForceRetryError_js__WEBPACK_IMPORTED_MODULE_2__.ForceRetryError) { + return errorObject.customDelay ?? this.#calculateDelay(); + } + // Check if method is retriable for non-forced retries + if (!this.#options.retry.methods.includes(this.request.method.toLowerCase())) { + throw error; + } + // User-provided shouldRetry function takes precedence over all other checks + if (this.#options.retry.shouldRetry !== undefined) { + const result = await this.#options.retry.shouldRetry({ error: errorObject, retryCount: this.#retryCount }); + // Strict boolean checking - only exact true/false are handled specially + if (result === false) { + throw error; + } + if (result === true) { + // Force retry - skip all other validation and return delay + return this.#calculateDelay(); + } + // If undefined or any other value, fall through to default behavior + } + // Default timeout behavior + if ((0,_utils_type_guards_js__WEBPACK_IMPORTED_MODULE_9__.isTimeoutError)(error) && !this.#options.retry.retryOnTimeout) { + throw error; + } + if ((0,_utils_type_guards_js__WEBPACK_IMPORTED_MODULE_9__.isHTTPError)(error)) { + if (!this.#options.retry.statusCodes.includes(error.response.status)) { + throw error; + } + const retryAfter = error.response.headers.get('Retry-After') + ?? error.response.headers.get('RateLimit-Reset') + ?? error.response.headers.get('X-RateLimit-Retry-After') // Symfony-based services + ?? error.response.headers.get('X-RateLimit-Reset') // GitHub + ?? error.response.headers.get('X-Rate-Limit-Reset'); // Twitter + if (retryAfter && this.#options.retry.afterStatusCodes.includes(error.response.status)) { + let after = Number(retryAfter) * 1000; + if (Number.isNaN(after)) { + after = Date.parse(retryAfter) - Date.now(); + } + else if (after >= Date.parse('2024-01-01')) { + // A large number is treated as a timestamp (fixed threshold protects against clock skew) + after -= Date.now(); + } + const max = this.#options.retry.maxRetryAfter ?? after; + // Don't apply jitter when server provides explicit retry timing + return after < max ? after : max; + } + if (error.response.status === 413) { + throw error; + } + } + return this.#calculateDelay(); + } + #decorateResponse(response) { + if (this.#options.parseJson) { + response.json = async () => this.#options.parseJson(await response.text()); + } + return response; + } + async #retry(function_) { + try { + return await function_(); + } + catch (error) { + const ms = Math.min(await this.#calculateRetryDelay(error), _constants_js__WEBPACK_IMPORTED_MODULE_10__.maxSafeTimeout); + if (this.#retryCount < 1) { + throw error; + } + // Only use user-provided signal for delay, not our internal abortController + await (0,_utils_delay_js__WEBPACK_IMPORTED_MODULE_7__["default"])(ms, this.#userProvidedAbortSignal ? { signal: this.#userProvidedAbortSignal } : {}); + // Apply custom request from forced retry before beforeRetry hooks + // Ensure the custom request has the correct managed signal for timeouts and user aborts + if (error instanceof _errors_ForceRetryError_js__WEBPACK_IMPORTED_MODULE_2__.ForceRetryError && error.customRequest) { + const managedRequest = this.#options.signal + ? new globalThis.Request(error.customRequest, { signal: this.#options.signal }) + : new globalThis.Request(error.customRequest); + this.#assignRequest(managedRequest); + } + for (const hook of this.#options.hooks.beforeRetry) { + // eslint-disable-next-line no-await-in-loop + const hookResult = await hook({ + request: this.request, + options: this.#getNormalizedOptions(), + error: error, + retryCount: this.#retryCount, + }); + if (hookResult instanceof globalThis.Request) { + this.#assignRequest(hookResult); + break; + } + // If a Response is returned, use it and skip the retry + if (hookResult instanceof globalThis.Response) { + return hookResult; + } + // If `stop` is returned from the hook, the retry process is stopped + if (hookResult === _constants_js__WEBPACK_IMPORTED_MODULE_10__.stop) { + return; + } + } + return this.#retry(function_); + } + } + async #fetch() { + // Reset abortController if it was aborted (happens on timeout retry) + if (this.#abortController?.signal.aborted) { + this.#abortController = new globalThis.AbortController(); + this.#options.signal = this.#userProvidedAbortSignal ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController.signal]) : this.#abortController.signal; + // Recreate request with new signal + this.request = new globalThis.Request(this.request, { signal: this.#options.signal }); + } + for (const hook of this.#options.hooks.beforeRequest) { + // eslint-disable-next-line no-await-in-loop + const result = await hook(this.request, this.#getNormalizedOptions(), { retryCount: this.#retryCount }); + if (result instanceof Response) { + return result; + } + if (result instanceof globalThis.Request) { + this.#assignRequest(result); + break; + } + } + const nonRequestOptions = (0,_utils_options_js__WEBPACK_IMPORTED_MODULE_8__.findUnknownOptions)(this.request, this.#options); + // Cloning is done here to prepare in advance for retries + this.#originalRequest = this.request; + this.request = this.#originalRequest.clone(); + if (this.#options.timeout === false) { + return this.#options.fetch(this.#originalRequest, nonRequestOptions); + } + return (0,_utils_timeout_js__WEBPACK_IMPORTED_MODULE_6__["default"])(this.#originalRequest, nonRequestOptions, this.#abortController, this.#options); + } + #getNormalizedOptions() { + if (!this.#cachedNormalizedOptions) { + const { hooks, ...normalizedOptions } = this.#options; + this.#cachedNormalizedOptions = Object.freeze(normalizedOptions); + } + return this.#cachedNormalizedOptions; + } + #assignRequest(request) { + this.#cachedNormalizedOptions = undefined; + this.request = this.#wrapRequestWithUploadProgress(request); + } + #wrapRequestWithUploadProgress(request, originalBody) { + if (!this.#options.onUploadProgress || !request.body) { + return request; + } + return (0,_utils_body_js__WEBPACK_IMPORTED_MODULE_3__.streamRequest)(request, this.#options.onUploadProgress, originalBody ?? this.#options.body ?? undefined); + } +} +//# sourceMappingURL=Ky.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/core/constants.js" +/*!********************************************************!*\ + !*** ./node_modules/ky/distribution/core/constants.js ***! + \********************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ RetryMarker: () => (/* binding */ RetryMarker), +/* harmony export */ kyOptionKeys: () => (/* binding */ kyOptionKeys), +/* harmony export */ maxSafeTimeout: () => (/* binding */ maxSafeTimeout), +/* harmony export */ requestMethods: () => (/* binding */ requestMethods), +/* harmony export */ requestOptionsRegistry: () => (/* binding */ requestOptionsRegistry), +/* harmony export */ responseTypes: () => (/* binding */ responseTypes), +/* harmony export */ retry: () => (/* binding */ retry), +/* harmony export */ stop: () => (/* binding */ stop), +/* harmony export */ supportsAbortController: () => (/* binding */ supportsAbortController), +/* harmony export */ supportsAbortSignal: () => (/* binding */ supportsAbortSignal), +/* harmony export */ supportsFormData: () => (/* binding */ supportsFormData), +/* harmony export */ supportsRequestStreams: () => (/* binding */ supportsRequestStreams), +/* harmony export */ supportsResponseStreams: () => (/* binding */ supportsResponseStreams), +/* harmony export */ usualFormBoundarySize: () => (/* binding */ usualFormBoundarySize), +/* harmony export */ vendorSpecificOptions: () => (/* binding */ vendorSpecificOptions) +/* harmony export */ }); +const supportsRequestStreams = (() => { + let duplexAccessed = false; + let hasContentType = false; + const supportsReadableStream = typeof globalThis.ReadableStream === 'function'; + const supportsRequest = typeof globalThis.Request === 'function'; + if (supportsReadableStream && supportsRequest) { + try { + hasContentType = new globalThis.Request('https://empty.invalid', { + body: new globalThis.ReadableStream(), + method: 'POST', + // @ts-expect-error - Types are outdated. + get duplex() { + duplexAccessed = true; + return 'half'; + }, + }).headers.has('Content-Type'); + } + catch (error) { + // QQBrowser on iOS throws "unsupported BodyInit type" error (see issue #581) + if (error instanceof Error && error.message === 'unsupported BodyInit type') { + return false; + } + throw error; + } + } + return duplexAccessed && !hasContentType; +})(); +const supportsAbortController = typeof globalThis.AbortController === 'function'; +const supportsAbortSignal = typeof globalThis.AbortSignal === 'function' && typeof globalThis.AbortSignal.any === 'function'; +const supportsResponseStreams = typeof globalThis.ReadableStream === 'function'; +const supportsFormData = typeof globalThis.FormData === 'function'; +const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete']; +const validate = () => undefined; +validate(); +const responseTypes = { + json: 'application/json', + text: 'text/*', + formData: 'multipart/form-data', + arrayBuffer: '*/*', + blob: '*/*', + // Supported in modern Fetch implementations (for example, browsers and recent Node.js/undici). + // We still feature-check at runtime before exposing the shortcut. + bytes: '*/*', +}; +// The maximum value of a 32bit int (see issue #117) +const maxSafeTimeout = 2_147_483_647; +// Size in bytes of a typical form boundary, used to help estimate upload size +const usualFormBoundarySize = new TextEncoder().encode('------WebKitFormBoundaryaxpyiPgbbPti10Rw').length; +const stop = Symbol('stop'); +/** +Marker returned by ky.retry() to signal a forced retry from afterResponse hooks. +*/ +class RetryMarker { + options; + constructor(options) { + this.options = options; + } +} +/** +Force a retry from an `afterResponse` hook. + +This allows you to retry a request based on the response content, even if the response has a successful status code. The retry will respect the `retry.limit` option and skip the `shouldRetry` check. The forced retry is observable in `beforeRetry` hooks, where the error will be a `ForceRetryError`. + +@param options - Optional configuration for the retry. + +@example +``` +import ky, {isForceRetryError} from 'ky'; + +const api = ky.extend({ + hooks: { + afterResponse: [ + async (request, options, response) => { + // Retry based on response body content + if (response.status === 200) { + const data = await response.clone().json(); + + // Simple retry with default delay + if (data.error?.code === 'TEMPORARY_ERROR') { + return ky.retry(); + } + + // Retry with custom delay from API response + if (data.error?.code === 'RATE_LIMIT') { + return ky.retry({ + delay: data.error.retryAfter * 1000, + code: 'RATE_LIMIT' + }); + } + + // Retry with a modified request (e.g., fallback endpoint) + if (data.error?.code === 'FALLBACK_TO_BACKUP') { + return ky.retry({ + request: new Request('https://backup-api.com/endpoint', { + method: request.method, + headers: request.headers, + }), + code: 'BACKUP_ENDPOINT' + }); + } + + // Retry with refreshed authentication + if (data.error?.code === 'TOKEN_REFRESH' && data.newToken) { + return ky.retry({ + request: new Request(request, { + headers: { + ...Object.fromEntries(request.headers), + 'Authorization': `Bearer ${data.newToken}` + } + }), + code: 'TOKEN_REFRESHED' + }); + } + + // Retry with cause to preserve error chain + try { + validateResponse(data); + } catch (error) { + return ky.retry({ + code: 'VALIDATION_FAILED', + cause: error + }); + } + } + } + ], + beforeRetry: [ + ({error, retryCount}) => { + // Observable in beforeRetry hooks + if (isForceRetryError(error)) { + console.log(`Forced retry #${retryCount}: ${error.message}`); + // Example output: "Forced retry #1: Forced retry: RATE_LIMIT" + } + } + ] + } +}); + +const response = await api.get('https://example.com/api'); +``` +*/ +const retry = (options) => new RetryMarker(options); +const kyOptionKeys = { + json: true, + parseJson: true, + stringifyJson: true, + searchParams: true, + prefixUrl: true, + retry: true, + timeout: true, + hooks: true, + throwHttpErrors: true, + onDownloadProgress: true, + onUploadProgress: true, + fetch: true, + context: true, +}; +// Vendor-specific fetch options that should always be passed to fetch() +// even if they appear on the Request object due to vendor patching. +// See: https://github.com/sindresorhus/ky/issues/541 +const vendorSpecificOptions = { + next: true, // Next.js cache revalidation (revalidate, tags) +}; +// Standard RequestInit options that should NOT be passed separately to fetch() +// because they're already applied to the Request object. +// Note: `dispatcher` and `priority` are NOT included here - they're fetch-only +// options that the Request constructor doesn't accept, so they need to be passed +// separately to fetch(). +const requestOptionsRegistry = { + method: true, + headers: true, + body: true, + mode: true, + credentials: true, + cache: true, + redirect: true, + referrer: true, + referrerPolicy: true, + integrity: true, + keepalive: true, + signal: true, + window: true, + duplex: true, +}; +//# sourceMappingURL=constants.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/errors/ForceRetryError.js" +/*!****************************************************************!*\ + !*** ./node_modules/ky/distribution/errors/ForceRetryError.js ***! + \****************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ ForceRetryError: () => (/* binding */ ForceRetryError) +/* harmony export */ }); +/* harmony import */ var _NonError_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./NonError.js */ "./node_modules/ky/distribution/errors/NonError.js"); + +/** +Internal error used to signal a forced retry from afterResponse hooks. +This is thrown when a user returns ky.retry() from an afterResponse hook. +*/ +class ForceRetryError extends Error { + name = 'ForceRetryError'; + customDelay; + code; + customRequest; + constructor(options) { + // Runtime protection: wrap non-Error causes in NonError + // TypeScript type is Error for guidance, but JS users can pass anything + const cause = options?.cause + ? (options.cause instanceof Error ? options.cause : new _NonError_js__WEBPACK_IMPORTED_MODULE_0__.NonError(options.cause)) + : undefined; + super(options?.code ? `Forced retry: ${options.code}` : 'Forced retry', cause ? { cause } : undefined); + this.customDelay = options?.delay; + this.code = options?.code; + this.customRequest = options?.request; + } +} +//# sourceMappingURL=ForceRetryError.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/errors/HTTPError.js" +/*!**********************************************************!*\ + !*** ./node_modules/ky/distribution/errors/HTTPError.js ***! + \**********************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ HTTPError: () => (/* binding */ HTTPError) +/* harmony export */ }); +class HTTPError extends Error { + response; + request; + options; + constructor(response, request, options) { + const code = (response.status || response.status === 0) ? response.status : ''; + const title = response.statusText ?? ''; + const status = `${code} ${title}`.trim(); + const reason = status ? `status code ${status}` : 'an unknown error'; + super(`Request failed with ${reason}: ${request.method} ${request.url}`); + this.name = 'HTTPError'; + this.response = response; + this.request = request; + this.options = options; + } +} +//# sourceMappingURL=HTTPError.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/errors/NonError.js" +/*!*********************************************************!*\ + !*** ./node_modules/ky/distribution/errors/NonError.js ***! + \*********************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ NonError: () => (/* binding */ NonError) +/* harmony export */ }); +/** +Wrapper for non-Error values that were thrown. + +In JavaScript, any value can be thrown (not just Error instances). This class wraps such values to ensure consistent error handling. +*/ +class NonError extends Error { + name = 'NonError'; + value; + constructor(value) { + let message = 'Non-error value was thrown'; + // Intentionally minimal as this error is just an edge-case. + try { + if (typeof value === 'string') { + message = value; + } + else if (value && typeof value === 'object' && 'message' in value && typeof value.message === 'string') { + message = value.message; + } + } + catch { + // Use default message if accessing properties throws + } + super(message); + this.value = value; + } +} +//# sourceMappingURL=NonError.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/errors/TimeoutError.js" +/*!*************************************************************!*\ + !*** ./node_modules/ky/distribution/errors/TimeoutError.js ***! + \*************************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ TimeoutError: () => (/* binding */ TimeoutError) +/* harmony export */ }); +class TimeoutError extends Error { + request; + constructor(request) { + super(`Request timed out: ${request.method} ${request.url}`); + this.name = 'TimeoutError'; + this.request = request; + } +} +//# sourceMappingURL=TimeoutError.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/index.js" +/*!***********************************************!*\ + !*** ./node_modules/ky/distribution/index.js ***! + \***********************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ ForceRetryError: () => (/* reexport safe */ _errors_ForceRetryError_js__WEBPACK_IMPORTED_MODULE_5__.ForceRetryError), +/* harmony export */ HTTPError: () => (/* reexport safe */ _errors_HTTPError_js__WEBPACK_IMPORTED_MODULE_3__.HTTPError), +/* harmony export */ TimeoutError: () => (/* reexport safe */ _errors_TimeoutError_js__WEBPACK_IMPORTED_MODULE_4__.TimeoutError), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ isForceRetryError: () => (/* reexport safe */ _utils_type_guards_js__WEBPACK_IMPORTED_MODULE_6__.isForceRetryError), +/* harmony export */ isHTTPError: () => (/* reexport safe */ _utils_type_guards_js__WEBPACK_IMPORTED_MODULE_6__.isHTTPError), +/* harmony export */ isKyError: () => (/* reexport safe */ _utils_type_guards_js__WEBPACK_IMPORTED_MODULE_6__.isKyError), +/* harmony export */ isTimeoutError: () => (/* reexport safe */ _utils_type_guards_js__WEBPACK_IMPORTED_MODULE_6__.isTimeoutError) +/* harmony export */ }); +/* harmony import */ var _core_Ky_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./core/Ky.js */ "./node_modules/ky/distribution/core/Ky.js"); +/* harmony import */ var _core_constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./core/constants.js */ "./node_modules/ky/distribution/core/constants.js"); +/* harmony import */ var _utils_merge_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/merge.js */ "./node_modules/ky/distribution/utils/merge.js"); +/* harmony import */ var _errors_HTTPError_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./errors/HTTPError.js */ "./node_modules/ky/distribution/errors/HTTPError.js"); +/* harmony import */ var _errors_TimeoutError_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./errors/TimeoutError.js */ "./node_modules/ky/distribution/errors/TimeoutError.js"); +/* harmony import */ var _errors_ForceRetryError_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./errors/ForceRetryError.js */ "./node_modules/ky/distribution/errors/ForceRetryError.js"); +/* harmony import */ var _utils_type_guards_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/type-guards.js */ "./node_modules/ky/distribution/utils/type-guards.js"); +/*! MIT License © Sindre Sorhus */ + + + +const createInstance = (defaults) => { + // eslint-disable-next-line @typescript-eslint/promise-function-async + const ky = (input, options) => _core_Ky_js__WEBPACK_IMPORTED_MODULE_0__.Ky.create(input, (0,_utils_merge_js__WEBPACK_IMPORTED_MODULE_2__.validateAndMerge)(defaults, options)); + for (const method of _core_constants_js__WEBPACK_IMPORTED_MODULE_1__.requestMethods) { + // eslint-disable-next-line @typescript-eslint/promise-function-async + ky[method] = (input, options) => _core_Ky_js__WEBPACK_IMPORTED_MODULE_0__.Ky.create(input, (0,_utils_merge_js__WEBPACK_IMPORTED_MODULE_2__.validateAndMerge)(defaults, options, { method })); + } + ky.create = (newDefaults) => createInstance((0,_utils_merge_js__WEBPACK_IMPORTED_MODULE_2__.validateAndMerge)(newDefaults)); + ky.extend = (newDefaults) => { + if (typeof newDefaults === 'function') { + newDefaults = newDefaults(defaults ?? {}); + } + return createInstance((0,_utils_merge_js__WEBPACK_IMPORTED_MODULE_2__.validateAndMerge)(defaults, newDefaults)); + }; + ky.stop = _core_constants_js__WEBPACK_IMPORTED_MODULE_1__.stop; + ky.retry = _core_constants_js__WEBPACK_IMPORTED_MODULE_1__.retry; + return ky; +}; +const ky = createInstance(); +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ky); + + + + +// Intentionally not exporting this for now as it's just an implementation detail and we don't want to commit to a certain API yet at least. +// export {NonError} from './errors/NonError.js'; +//# sourceMappingURL=index.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/utils/body.js" +/*!****************************************************!*\ + !*** ./node_modules/ky/distribution/utils/body.js ***! + \****************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ getBodySize: () => (/* binding */ getBodySize), +/* harmony export */ streamRequest: () => (/* binding */ streamRequest), +/* harmony export */ streamResponse: () => (/* binding */ streamResponse) +/* harmony export */ }); +/* harmony import */ var _core_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core/constants.js */ "./node_modules/ky/distribution/core/constants.js"); + +// eslint-disable-next-line @typescript-eslint/ban-types +const getBodySize = (body) => { + if (!body) { + return 0; + } + if (body instanceof FormData) { + // This is an approximation, as FormData size calculation is not straightforward + let size = 0; + for (const [key, value] of body) { + size += _core_constants_js__WEBPACK_IMPORTED_MODULE_0__.usualFormBoundarySize; + size += new TextEncoder().encode(`Content-Disposition: form-data; name="${key}"`).length; + size += typeof value === 'string' + ? new TextEncoder().encode(value).length + : value.size; + } + return size; + } + if (body instanceof Blob) { + return body.size; + } + if (body instanceof ArrayBuffer) { + return body.byteLength; + } + if (typeof body === 'string') { + return new TextEncoder().encode(body).length; + } + if (body instanceof URLSearchParams) { + return new TextEncoder().encode(body.toString()).length; + } + if ('byteLength' in body) { + return (body).byteLength; + } + if (typeof body === 'object' && body !== null) { + try { + const jsonString = JSON.stringify(body); + return new TextEncoder().encode(jsonString).length; + } + catch { + return 0; + } + } + return 0; // Default case, unable to determine size +}; +const withProgress = (stream, totalBytes, onProgress) => { + let previousChunk; + let transferredBytes = 0; + return stream.pipeThrough(new TransformStream({ + transform(currentChunk, controller) { + controller.enqueue(currentChunk); + if (previousChunk) { + transferredBytes += previousChunk.byteLength; + let percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes; + // Avoid reporting 100% progress before the stream is actually finished (in case totalBytes is inaccurate) + if (percent >= 1) { + // Epsilon is used here to get as close as possible to 100% without reaching it. + // If we were to use 0.99 here, percent could potentially go backwards. + percent = 1 - Number.EPSILON; + } + onProgress?.({ percent, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes }, previousChunk); + } + previousChunk = currentChunk; + }, + flush() { + if (previousChunk) { + transferredBytes += previousChunk.byteLength; + onProgress?.({ percent: 1, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes }, previousChunk); + } + }, + })); +}; +const streamResponse = (response, onDownloadProgress) => { + if (!response.body) { + return response; + } + if (response.status === 204) { + return new Response(null, { + status: response.status, + statusText: response.statusText, + headers: response.headers, + }); + } + const totalBytes = Math.max(0, Number(response.headers.get('content-length')) || 0); + return new Response(withProgress(response.body, totalBytes, onDownloadProgress), { + status: response.status, + statusText: response.statusText, + headers: response.headers, + }); +}; +// eslint-disable-next-line @typescript-eslint/ban-types +const streamRequest = (request, onUploadProgress, originalBody) => { + if (!request.body) { + return request; + } + // Use original body for size calculation since request.body is already a stream + const totalBytes = getBodySize(originalBody ?? request.body); + return new Request(request, { + // @ts-expect-error - Types are outdated. + duplex: 'half', + body: withProgress(request.body, totalBytes, onUploadProgress), + }); +}; +//# sourceMappingURL=body.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/utils/delay.js" +/*!*****************************************************!*\ + !*** ./node_modules/ky/distribution/utils/delay.js ***! + \*****************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ delay) +/* harmony export */ }); +// https://github.com/sindresorhus/delay/tree/ab98ae8dfcb38e1593286c94d934e70d14a4e111 +async function delay(ms, { signal }) { + return new Promise((resolve, reject) => { + if (signal) { + signal.throwIfAborted(); + signal.addEventListener('abort', abortHandler, { once: true }); + } + function abortHandler() { + clearTimeout(timeoutId); + reject(signal.reason); + } + const timeoutId = setTimeout(() => { + signal?.removeEventListener('abort', abortHandler); + resolve(); + }, ms); + }); +} +//# sourceMappingURL=delay.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/utils/is.js" +/*!**************************************************!*\ + !*** ./node_modules/ky/distribution/utils/is.js ***! + \**************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ isObject: () => (/* binding */ isObject) +/* harmony export */ }); +// eslint-disable-next-line @typescript-eslint/ban-types +const isObject = (value) => value !== null && typeof value === 'object'; +//# sourceMappingURL=is.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/utils/merge.js" +/*!*****************************************************!*\ + !*** ./node_modules/ky/distribution/utils/merge.js ***! + \*****************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ deepMerge: () => (/* binding */ deepMerge), +/* harmony export */ mergeHeaders: () => (/* binding */ mergeHeaders), +/* harmony export */ mergeHooks: () => (/* binding */ mergeHooks), +/* harmony export */ validateAndMerge: () => (/* binding */ validateAndMerge) +/* harmony export */ }); +/* harmony import */ var _core_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core/constants.js */ "./node_modules/ky/distribution/core/constants.js"); +/* harmony import */ var _is_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./is.js */ "./node_modules/ky/distribution/utils/is.js"); + + +const validateAndMerge = (...sources) => { + for (const source of sources) { + if ((!(0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isObject)(source) || Array.isArray(source)) && source !== undefined) { + throw new TypeError('The `options` argument must be an object'); + } + } + return deepMerge({}, ...sources); +}; +const mergeHeaders = (source1 = {}, source2 = {}) => { + const result = new globalThis.Headers(source1); + const isHeadersInstance = source2 instanceof globalThis.Headers; + const source = new globalThis.Headers(source2); + for (const [key, value] of source.entries()) { + if ((isHeadersInstance && value === 'undefined') || value === undefined) { + result.delete(key); + } + else { + result.set(key, value); + } + } + return result; +}; +function newHookValue(original, incoming, property) { + return (Object.hasOwn(incoming, property) && incoming[property] === undefined) + ? [] + : deepMerge(original[property] ?? [], incoming[property] ?? []); +} +const mergeHooks = (original = {}, incoming = {}) => ({ + beforeRequest: newHookValue(original, incoming, 'beforeRequest'), + beforeRetry: newHookValue(original, incoming, 'beforeRetry'), + afterResponse: newHookValue(original, incoming, 'afterResponse'), + beforeError: newHookValue(original, incoming, 'beforeError'), +}); +const appendSearchParameters = (target, source) => { + const result = new URLSearchParams(); + for (const input of [target, source]) { + if (input === undefined) { + continue; + } + if (input instanceof URLSearchParams) { + for (const [key, value] of input.entries()) { + result.append(key, value); + } + } + else if (Array.isArray(input)) { + for (const pair of input) { + if (!Array.isArray(pair) || pair.length !== 2) { + throw new TypeError('Array search parameters must be provided in [[key, value], ...] format'); + } + result.append(String(pair[0]), String(pair[1])); + } + } + else if ((0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isObject)(input)) { + for (const [key, value] of Object.entries(input)) { + if (value !== undefined) { + result.append(key, String(value)); + } + } + } + else { + // String + const parameters = new URLSearchParams(input); + for (const [key, value] of parameters.entries()) { + result.append(key, value); + } + } + } + return result; +}; +// TODO: Make this strongly-typed (no `any`). +const deepMerge = (...sources) => { + let returnValue = {}; + let headers = {}; + let hooks = {}; + let searchParameters; + const signals = []; + for (const source of sources) { + if (Array.isArray(source)) { + if (!Array.isArray(returnValue)) { + returnValue = []; + } + returnValue = [...returnValue, ...source]; + } + else if ((0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isObject)(source)) { + for (let [key, value] of Object.entries(source)) { + // Special handling for AbortSignal instances + if (key === 'signal' && value instanceof globalThis.AbortSignal) { + signals.push(value); + continue; + } + // Special handling for context - shallow merge only + if (key === 'context') { + if (value !== undefined && value !== null && (!(0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isObject)(value) || Array.isArray(value))) { + throw new TypeError('The `context` option must be an object'); + } + // Shallow merge: always create a new object to prevent mutation bugs + returnValue = { + ...returnValue, + context: (value === undefined || value === null) + ? {} + : { ...returnValue.context, ...value }, + }; + continue; + } + // Special handling for searchParams + if (key === 'searchParams') { + if (value === undefined || value === null) { + // Explicit undefined or null removes searchParams + searchParameters = undefined; + } + else { + // First source: keep as-is to preserve type (string/object/URLSearchParams) + // Subsequent sources: merge and convert to URLSearchParams + searchParameters = searchParameters === undefined ? value : appendSearchParameters(searchParameters, value); + } + continue; + } + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isObject)(value) && key in returnValue) { + value = deepMerge(returnValue[key], value); + } + returnValue = { ...returnValue, [key]: value }; + } + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isObject)(source.hooks)) { + hooks = mergeHooks(hooks, source.hooks); + returnValue.hooks = hooks; + } + if ((0,_is_js__WEBPACK_IMPORTED_MODULE_1__.isObject)(source.headers)) { + headers = mergeHeaders(headers, source.headers); + returnValue.headers = headers; + } + } + } + if (searchParameters !== undefined) { + returnValue.searchParams = searchParameters; + } + if (signals.length > 0) { + if (signals.length === 1) { + returnValue.signal = signals[0]; + } + else if (_core_constants_js__WEBPACK_IMPORTED_MODULE_0__.supportsAbortSignal) { + returnValue.signal = AbortSignal.any(signals); + } + else { + // When AbortSignal.any is not available, use the last signal + // This maintains the previous behavior before signal merging was added + // This can be remove when the `supportsAbortSignal` check is removed.` + returnValue.signal = signals.at(-1); + } + } + if (returnValue.context === undefined) { + returnValue.context = {}; + } + return returnValue; +}; +//# sourceMappingURL=merge.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/utils/normalize.js" +/*!*********************************************************!*\ + !*** ./node_modules/ky/distribution/utils/normalize.js ***! + \*********************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ normalizeRequestMethod: () => (/* binding */ normalizeRequestMethod), +/* harmony export */ normalizeRetryOptions: () => (/* binding */ normalizeRetryOptions) +/* harmony export */ }); +/* harmony import */ var _core_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core/constants.js */ "./node_modules/ky/distribution/core/constants.js"); + +const normalizeRequestMethod = (input) => _core_constants_js__WEBPACK_IMPORTED_MODULE_0__.requestMethods.includes(input) ? input.toUpperCase() : input; +const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace']; +const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504]; +const retryAfterStatusCodes = [413, 429, 503]; +const defaultRetryOptions = { + limit: 2, + methods: retryMethods, + statusCodes: retryStatusCodes, + afterStatusCodes: retryAfterStatusCodes, + maxRetryAfter: Number.POSITIVE_INFINITY, + backoffLimit: Number.POSITIVE_INFINITY, + delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000, + jitter: undefined, + retryOnTimeout: false, +}; +const normalizeRetryOptions = (retry = {}) => { + if (typeof retry === 'number') { + return { + ...defaultRetryOptions, + limit: retry, + }; + } + if (retry.methods && !Array.isArray(retry.methods)) { + throw new Error('retry.methods must be an array'); + } + if (retry.statusCodes && !Array.isArray(retry.statusCodes)) { + throw new Error('retry.statusCodes must be an array'); + } + const normalizedRetry = Object.fromEntries(Object.entries(retry).filter(([, value]) => value !== undefined)); + return { + ...defaultRetryOptions, + ...normalizedRetry, + }; +}; +//# sourceMappingURL=normalize.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/utils/options.js" +/*!*******************************************************!*\ + !*** ./node_modules/ky/distribution/utils/options.js ***! + \*******************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ findUnknownOptions: () => (/* binding */ findUnknownOptions), +/* harmony export */ hasSearchParameters: () => (/* binding */ hasSearchParameters) +/* harmony export */ }); +/* harmony import */ var _core_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../core/constants.js */ "./node_modules/ky/distribution/core/constants.js"); + +const findUnknownOptions = (request, options) => { + const unknownOptions = {}; + for (const key in options) { + // Skip inherited properties + if (!Object.hasOwn(options, key)) { + continue; + } + // An option is passed to fetch() if: + // 1. It's not a standard RequestInit option (not in requestOptionsRegistry) + // 2. It's not a ky-specific option (not in kyOptionKeys) + // 3. Either: + // a. It's not on the Request object, OR + // b. It's a vendor-specific option that should always be passed (in vendorSpecificOptions) + if (!(key in _core_constants_js__WEBPACK_IMPORTED_MODULE_0__.requestOptionsRegistry) && !(key in _core_constants_js__WEBPACK_IMPORTED_MODULE_0__.kyOptionKeys) && (!(key in request) || key in _core_constants_js__WEBPACK_IMPORTED_MODULE_0__.vendorSpecificOptions)) { + unknownOptions[key] = options[key]; + } + } + return unknownOptions; +}; +const hasSearchParameters = (search) => { + if (search === undefined) { + return false; + } + // The `typeof array` still gives "object", so we need different checking for array. + if (Array.isArray(search)) { + return search.length > 0; + } + if (search instanceof URLSearchParams) { + return search.size > 0; + } + // Record + if (typeof search === 'object') { + return Object.keys(search).length > 0; + } + if (typeof search === 'string') { + return search.trim().length > 0; + } + return Boolean(search); +}; +//# sourceMappingURL=options.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/utils/timeout.js" +/*!*******************************************************!*\ + !*** ./node_modules/ky/distribution/utils/timeout.js ***! + \*******************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ timeout) +/* harmony export */ }); +/* harmony import */ var _errors_TimeoutError_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors/TimeoutError.js */ "./node_modules/ky/distribution/errors/TimeoutError.js"); + +// `Promise.race()` workaround (#91) +async function timeout(request, init, abortController, options) { + return new Promise((resolve, reject) => { + const timeoutId = setTimeout(() => { + if (abortController) { + abortController.abort(); + } + reject(new _errors_TimeoutError_js__WEBPACK_IMPORTED_MODULE_0__.TimeoutError(request)); + }, options.timeout); + void options + .fetch(request, init) + .then(resolve) + .catch(reject) + .then(() => { + clearTimeout(timeoutId); + }); + }); +} +//# sourceMappingURL=timeout.js.map + +/***/ }, + +/***/ "./node_modules/ky/distribution/utils/type-guards.js" +/*!***********************************************************!*\ + !*** ./node_modules/ky/distribution/utils/type-guards.js ***! + \***********************************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ isForceRetryError: () => (/* binding */ isForceRetryError), +/* harmony export */ isHTTPError: () => (/* binding */ isHTTPError), +/* harmony export */ isKyError: () => (/* binding */ isKyError), +/* harmony export */ isTimeoutError: () => (/* binding */ isTimeoutError) +/* harmony export */ }); +/* harmony import */ var _errors_HTTPError_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors/HTTPError.js */ "./node_modules/ky/distribution/errors/HTTPError.js"); +/* harmony import */ var _errors_TimeoutError_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors/TimeoutError.js */ "./node_modules/ky/distribution/errors/TimeoutError.js"); +/* harmony import */ var _errors_ForceRetryError_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors/ForceRetryError.js */ "./node_modules/ky/distribution/errors/ForceRetryError.js"); + + + +/** +Type guard to check if an error is a Ky error (HTTPError or TimeoutError). + +@param error - The error to check +@returns `true` if the error is a Ky error, `false` otherwise + +@example +``` +import ky, {isKyError} from 'ky'; +try { + const response = await ky.get('/api/data'); +} catch (error) { + if (isKyError(error)) { + // Handle Ky-specific errors + console.log('Ky error occurred:', error.message); + } else { + // Handle other errors + console.log('Unknown error:', error); + } +} +``` +*/ +function isKyError(error) { + return isHTTPError(error) || isTimeoutError(error); +} +/** +Type guard to check if an error is an HTTPError. + +@param error - The error to check +@returns `true` if the error is an HTTPError, `false` otherwise + +@example +``` +import ky, {isHTTPError} from 'ky'; +try { + const response = await ky.get('/api/data'); +} catch (error) { + if (isHTTPError(error)) { + console.log('HTTP error status:', error.response.status); + } +} +``` +*/ +function isHTTPError(error) { + return error instanceof _errors_HTTPError_js__WEBPACK_IMPORTED_MODULE_0__.HTTPError || (error?.name === _errors_HTTPError_js__WEBPACK_IMPORTED_MODULE_0__.HTTPError.name); +} +/** +Type guard to check if an error is a TimeoutError. + +@param error - The error to check +@returns `true` if the error is a TimeoutError, `false` otherwise + +@example +``` +import ky, {isTimeoutError} from 'ky'; +try { + const response = await ky.get('/api/data', { timeout: 1000 }); +} catch (error) { + if (isTimeoutError(error)) { + console.log('Request timed out:', error.request.url); + } +} +``` +*/ +function isTimeoutError(error) { + return error instanceof _errors_TimeoutError_js__WEBPACK_IMPORTED_MODULE_1__.TimeoutError || (error?.name === _errors_TimeoutError_js__WEBPACK_IMPORTED_MODULE_1__.TimeoutError.name); +} +/** +Type guard to check if an error is a ForceRetryError. + +@param error - The error to check +@returns `true` if the error is a ForceRetryError, `false` otherwise + +@example +``` +import ky, {isForceRetryError} from 'ky'; + +const api = ky.extend({ + hooks: { + beforeRetry: [ + ({error, retryCount}) => { + if (isForceRetryError(error)) { + console.log(`Forced retry #${retryCount}: ${error.code}`); + } + } + ] + } +}); +``` +*/ +function isForceRetryError(error) { + return error instanceof _errors_ForceRetryError_js__WEBPACK_IMPORTED_MODULE_2__.ForceRetryError || (error?.name === _errors_ForceRetryError_js__WEBPACK_IMPORTED_MODULE_2__.ForceRetryError.name); +} +//# sourceMappingURL=type-guards.js.map + +/***/ }, + +/***/ "./node_modules/lru-cache/index.js" +/*!*****************************************!*\ + !*** ./node_modules/lru-cache/index.js ***! + \*****************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; + + +// A linked list to keep track of recently-used-ness +const Yallist = __webpack_require__(/*! yallist */ "./node_modules/yallist/yallist.js") + +const MAX = Symbol('max') +const LENGTH = Symbol('length') +const LENGTH_CALCULATOR = Symbol('lengthCalculator') +const ALLOW_STALE = Symbol('allowStale') +const MAX_AGE = Symbol('maxAge') +const DISPOSE = Symbol('dispose') +const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') +const LRU_LIST = Symbol('lruList') +const CACHE = Symbol('cache') +const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') + +const naiveLength = () => 1 + +// lruList is a yallist where the head is the youngest +// item, and the tail is the oldest. the list contains the Hit +// objects as the entries. +// Each Hit object has a reference to its Yallist.Node. This +// never changes. +// +// cache is a Map (or PseudoMap) that matches the keys to +// the Yallist.Node object. +class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options } + + if (!options) + options = {} + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + const max = this[MAX] = options.max || Infinity + + const lc = options.length || naiveLength + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc + this[ALLOW_STALE] = options.stale || false + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0 + this[DISPOSE] = options.dispose + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false + this.reset() + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity + trim(this) + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA + trim(this) + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC + this[LENGTH] = 0 + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) + this[LENGTH] += hit.length + }) + } + trim(this) + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev + forEachStep(this, fn, walker, thisp) + walker = prev + } + } + + forEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next + forEachStep(this, fn, walker, thisp) + walker = next + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) + } + + this[CACHE] = new Map() // hash of items by key + this[LRU_LIST] = new Yallist() // list of items in order of use recency + this[LENGTH] = 0 // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE] + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0 + const len = this[LENGTH_CALCULATOR](value, key) + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)) + return false + } + + const node = this[CACHE].get(key) + const item = node.value + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value) + } + + item.now = now + item.maxAge = maxAge + item.value = value + this[LENGTH] += len - item.length + item.length = len + this.get(key) + trim(this) + return true + } + + const hit = new Entry(key, value, len, now, maxAge) + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value) + + return false + } + + this[LENGTH] += hit.length + this[LRU_LIST].unshift(hit) + this[CACHE].set(key, this[LRU_LIST].head) + trim(this) + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value + return !isStale(this, hit) + } + + get (key) { + return get(this, key, true) + } + + peek (key) { + return get(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail + if (!node) + return null + + del(this, node) + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)) + } + + load (arr) { + // reset the cache + this.reset() + + const now = Date.now() + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l] + const expiresAt = hit.e || 0 + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v) + else { + const maxAge = expiresAt - now + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge) + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)) + } +} + +const get = (self, key, doUse) => { + const node = self[CACHE].get(key) + if (node) { + const hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now() + self[LRU_LIST].unshiftNode(node) + } + } + return hit.value + } +} + +const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) +} + +const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev + del(self, walker) + walker = prev + } + } +} + +const del = (self, node) => { + if (node) { + const hit = node.value + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value) + + self[LENGTH] -= hit.length + self[CACHE].delete(hit.key) + self[LRU_LIST].removeNode(node) + } +} + +class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key + this.value = value + this.length = length + this.now = now + this.maxAge = maxAge || 0 + } +} + +const forEachStep = (self, fn, node, thisp) => { + let hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + hit = undefined + } + if (hit) + fn.call(thisp, hit.value, hit.key, self) +} + +module.exports = LRUCache + + +/***/ }, + +/***/ "./node_modules/marked/lib/marked.esm.js" +/*!***********************************************!*\ + !*** ./node_modules/marked/lib/marked.esm.js ***! + \***********************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Hooks: () => (/* binding */ S), +/* harmony export */ Lexer: () => (/* binding */ x), +/* harmony export */ Marked: () => (/* binding */ B), +/* harmony export */ Parser: () => (/* binding */ b), +/* harmony export */ Renderer: () => (/* binding */ P), +/* harmony export */ TextRenderer: () => (/* binding */ $), +/* harmony export */ Tokenizer: () => (/* binding */ y), +/* harmony export */ defaults: () => (/* binding */ T), +/* harmony export */ getDefaults: () => (/* binding */ L), +/* harmony export */ lexer: () => (/* binding */ jt), +/* harmony export */ marked: () => (/* binding */ d), +/* harmony export */ options: () => (/* binding */ Dt), +/* harmony export */ parse: () => (/* binding */ Qt), +/* harmony export */ parseInline: () => (/* binding */ Nt), +/* harmony export */ parser: () => (/* binding */ Ft), +/* harmony export */ setOptions: () => (/* binding */ Ht), +/* harmony export */ use: () => (/* binding */ Zt), +/* harmony export */ walkTokens: () => (/* binding */ Gt) +/* harmony export */ }); +/** + * marked v17.0.1 - a markdown parser + * Copyright (c) 2018-2025, MarkedJS. (MIT License) + * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License) + * https://github.com/markedjs/marked + */ + +/** + * DO NOT EDIT THIS FILE + * The code in this file is generated from files in ./src/ + */ + +function L(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=L();function Z(u){T=u}var C={exec:()=>null};function k(u,e=""){let t=typeof u=="string"?u:u.source,n={replace:(r,i)=>{let s=typeof i=="string"?i:i.source;return s=s.replace(m.caret,"$1"),t=t.replace(r,s),n},getRegex:()=>new RegExp(t,e)};return n}var me=(()=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:u=>new RegExp(`^( {0,3}${u})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:u=>new RegExp(`^ {0,${Math.min(3,u-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:u=>new RegExp(`^ {0,${Math.min(3,u-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:u=>new RegExp(`^ {0,${Math.min(3,u-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:u=>new RegExp(`^ {0,${Math.min(3,u-1)}}#`),htmlBeginRegex:u=>new RegExp(`^ {0,${Math.min(3,u-1)}}<(?:[a-z].*>|!--)`,"i")},xe=/^(?:[ \t]*(?:\n|$))+/,be=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Re=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,I=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Te=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,N=/(?:[*+-]|\d{1,9}[.)])/,re=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,se=k(re).replace(/bull/g,N).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Oe=k(re).replace(/bull/g,N).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Q=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,we=/^[^\n]+/,F=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ye=k(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",F).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Pe=k(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,N).getRegex(),v="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",j=/|$))/,Se=k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",j).replace("tag",v).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ie=k(Q).replace("hr",I).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),$e=k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",ie).getRegex(),U={blockquote:$e,code:be,def:ye,fences:Re,heading:Te,hr:I,html:Se,lheading:se,list:Pe,newline:xe,paragraph:ie,table:C,text:we},te=k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",I).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),_e={...U,lheading:Oe,table:te,paragraph:k(Q).replace("hr",I).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",te).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex()},Le={...U,html:k(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",j).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:C,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:k(Q).replace("hr",I).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",se).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Me=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ze=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,oe=/^( {2,}|\\)\n(?!\s*$)/,Ae=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",me?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ue=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,qe=k(ue,"u").replace(/punct/g,D).getRegex(),ve=k(ue,"u").replace(/punct/g,le).getRegex(),pe="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",De=k(pe,"gu").replace(/notPunctSpace/g,ae).replace(/punctSpace/g,K).replace(/punct/g,D).getRegex(),He=k(pe,"gu").replace(/notPunctSpace/g,Ee).replace(/punctSpace/g,Ie).replace(/punct/g,le).getRegex(),Ze=k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ae).replace(/punctSpace/g,K).replace(/punct/g,D).getRegex(),Ge=k(/\\(punct)/,"gu").replace(/punct/g,D).getRegex(),Ne=k(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Qe=k(j).replace("(?:-->|$)","-->").getRegex(),Fe=k("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",Qe).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),q=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,je=k(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",q).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ce=k(/^!?\[(label)\]\[(ref)\]/).replace("label",q).replace("ref",F).getRegex(),he=k(/^!?\[(ref)\](?:\[\])?/).replace("ref",F).getRegex(),Ue=k("reflink|nolink(?!\\()","g").replace("reflink",ce).replace("nolink",he).getRegex(),ne=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,W={_backpedal:C,anyPunctuation:Ge,autolink:Ne,blockSkip:Be,br:oe,code:ze,del:C,emStrongLDelim:qe,emStrongRDelimAst:De,emStrongRDelimUnd:Ze,escape:Me,link:je,nolink:he,punctuation:Ce,reflink:ce,reflinkSearch:Ue,tag:Fe,text:Ae,url:C},Ke={...W,link:k(/^!?\[(label)\]\((.*?)\)/).replace("label",q).getRegex(),reflink:k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",q).getRegex()},G={...W,emStrongRDelimAst:He,emStrongLDelim:ve,url:k(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ne).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:k(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},ke=u=>Xe[u];function w(u,e){if(e){if(m.escapeTest.test(u))return u.replace(m.escapeReplace,ke)}else if(m.escapeTestNoEncode.test(u))return u.replace(m.escapeReplaceNoEncode,ke);return u}function X(u){try{u=encodeURI(u).replace(m.percentDecode,"%")}catch{return null}return u}function J(u,e){let t=u.replace(m.findPipe,(i,s,a)=>{let o=!1,l=s;for(;--l>=0&&a[l]==="\\";)o=!o;return o?"|":" |"}),n=t.split(m.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length0?-2:-1}function ge(u,e,t,n,r){let i=e.href,s=e.title||null,a=u[1].replace(r.other.outputLinkReplace,"$1");n.state.inLink=!0;let o={type:u[0].charAt(0)==="!"?"image":"link",raw:t,href:i,title:s,text:a,tokens:n.inlineTokens(a)};return n.state.inLink=!1,o}function Je(u,e,t){let n=u.match(t.other.indentCodeCompensation);if(n===null)return e;let r=n[1];return e.split(` +`).map(i=>{let s=i.match(t.other.beginningSpace);if(s===null)return i;let[a]=s;return a.length>=r.length?i.slice(r.length):i}).join(` +`)}var y=class{options;rules;lexer;constructor(e){this.options=e||T}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:z(n,` +`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=Je(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=z(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:z(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=z(t[0],` +`).split(` +`),r="",i="",s=[];for(;n.length>0;){let a=!1,o=[],l;for(l=0;l1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let s=this.rules.other.listItemRegex(n),a=!1;for(;e;){let l=!1,p="",c="";if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let g=t[2].split(` +`,1)[0].replace(this.rules.other.listReplaceTabs,O=>" ".repeat(3*O.length)),h=e.split(` +`,1)[0],R=!g.trim(),f=0;if(this.options.pedantic?(f=2,c=g.trimStart()):R?f=t[1].length+1:(f=t[2].search(this.rules.other.nonSpaceChar),f=f>4?1:f,c=g.slice(f),f+=t[1].length),R&&this.rules.other.blankLine.test(h)&&(p+=h+` +`,e=e.substring(h.length+1),l=!0),!l){let O=this.rules.other.nextBulletRegex(f),V=this.rules.other.hrRegex(f),Y=this.rules.other.fencesBeginRegex(f),ee=this.rules.other.headingBeginRegex(f),fe=this.rules.other.htmlBeginRegex(f);for(;e;){let H=e.split(` +`,1)[0],A;if(h=H,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting," "),A=h):A=h.replace(this.rules.other.tabCharGlobal," "),Y.test(h)||ee.test(h)||fe.test(h)||O.test(h)||V.test(h))break;if(A.search(this.rules.other.nonSpaceChar)>=f||!h.trim())c+=` +`+A.slice(f);else{if(R||g.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Y.test(g)||ee.test(g)||V.test(g))break;c+=` +`+h}!R&&!h.trim()&&(R=!0),p+=H+` +`,e=e.substring(H.length+1),g=A.slice(f)}}i.loose||(a?i.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(a=!0)),i.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(c),loose:!1,text:c,tokens:[]}),i.raw+=p}let o=i.items.at(-1);if(o)o.raw=o.raw.trimEnd(),o.text=o.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let l of i.items){if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),l.task){if(l.text=l.text.replace(this.rules.other.listReplaceTask,""),l.tokens[0]?.type==="text"||l.tokens[0]?.type==="paragraph"){l.tokens[0].raw=l.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),l.tokens[0].text=l.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let c=this.lexer.inlineQueue.length-1;c>=0;c--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[c].src)){this.lexer.inlineQueue[c].src=this.lexer.inlineQueue[c].src.replace(this.rules.other.listReplaceTask,"");break}}let p=this.rules.other.listTaskCheckbox.exec(l.raw);if(p){let c={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};l.checked=c.checked,i.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=c.raw+l.tokens[0].raw,l.tokens[0].text=c.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(c)):l.tokens.unshift({type:"paragraph",raw:c.raw,text:c.raw,tokens:[c]}):l.tokens.unshift(c)}}if(!i.loose){let p=l.tokens.filter(g=>g.type==="space"),c=p.length>0&&p.some(g=>this.rules.other.anyLine.test(g.raw));i.loose=c}}if(i.loose)for(let l of i.items){l.loose=!0;for(let p of l.tokens)p.type==="text"&&(p.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:r,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=J(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(` +`):[],s={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===r.length){for(let a of r)this.rules.other.tableAlignRight.test(a)?s.align.push("right"):this.rules.other.tableAlignCenter.test(a)?s.align.push("center"):this.rules.other.tableAlignLeft.test(a)?s.align.push("left"):s.align.push(null);for(let a=0;a({text:o,tokens:this.lexer.inline(o),header:!1,align:s.align[l]})));return s}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` +`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=z(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=de(t[2],"()");if(s===-2)return;if(s>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let r=t[2],i="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],i=s[3])}else i=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),ge(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[r.toLowerCase()];if(!i){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return ge(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!r||r[3]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(r[1]||r[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let s=[...r[0]].length-1,a,o,l=s,p=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+s);(r=c.exec(t))!=null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(o=[...a].length,r[3]||r[4]){l+=o;continue}else if((r[5]||r[6])&&s%3&&!((s+o)%3)){p+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l+p);let g=[...r[0]][0].length,h=e.slice(0,s+r.index+g+o);if(Math.min(s,o)%2){let f=h.slice(1,-1);return{type:"em",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}let R=h.slice(2,-2);return{type:"strong",raw:h,text:R,tokens:this.lexer.inlineTokens(R)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,r;return t[2]==="@"?(n=t[1],r="mailto:"+n):(n=t[1],r=n),{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,r;if(t[2]==="@")n=t[0],r="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?r="http://"+t[0]:r=t[0]}return{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}};var x=class u{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||T,this.options.tokenizer=this.options.tokenizer||new y,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:m,block:E.normal,inline:M.normal};this.options.pedantic?(t.block=E.pedantic,t.inline=M.pedantic):this.options.gfm&&(t.block=E.gfm,this.options.breaks?t.inline=M.breaks:t.inline=M.gfm),this.tokenizer.rules=t}static get rules(){return{block:E,inline:M}}static lex(e,t){return new u(t).lex(e)}static lexInline(e,t){return new u(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,` +`),this.blockTokens(e,this.tokens);for(let t=0;t(r=s.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let s=t.at(-1);r.raw.length===1&&s!==void 0?s.raw+=` +`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+r.raw,s.text+=` +`+r.text,this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+r.raw,s.text+=` +`+r.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startBlock){let s=1/0,a=e.slice(1),o;this.options.extensions.startBlock.forEach(l=>{o=l.call({lexer:this},a),typeof o=="number"&&o>=0&&(s=Math.min(s,o))}),s<1/0&&s>=0&&(i=e.substring(0,s+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){let s=t.at(-1);n&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+r.raw,s.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+r.raw,s.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(e){let s="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(s);break}else throw new Error(s)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,r=null;if(this.tokens.links){let o=Object.keys(this.tokens.links);if(o.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)o.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,r.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+"["+"a".repeat(r[0].length-i-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let s=!1,a="";for(;e;){s||(a=""),s=!1;let o;if(this.options.extensions?.inline?.some(p=>(o=p.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let p=t.at(-1);o.type==="text"&&p?.type==="text"?(p.raw+=o.raw,p.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,n,a)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let l=e;if(this.options.extensions?.startInline){let p=1/0,c=e.slice(1),g;this.options.extensions.startInline.forEach(h=>{g=h.call({lexer:this},c),typeof g=="number"&&g>=0&&(p=Math.min(p,g))}),p<1/0&&p>=0&&(l=e.substring(0,p+1))}if(o=this.tokenizer.inlineText(l)){e=e.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(a=o.raw.slice(-1)),s=!0;let p=t.at(-1);p?.type==="text"?(p.raw+=o.raw,p.text+=o.text):t.push(o);continue}if(e){let p="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(p);break}else throw new Error(p)}}return t}};var P=class{options;parser;constructor(e){this.options=e||T}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(m.notSpaceStart)?.[0],i=e.replace(m.endingNewline,"")+` +`;return r?'
'+(n?i:w(i,!0))+`
+`:"
"+(n?i:w(i,!0))+`
+`}blockquote({tokens:e}){return`
+${this.parser.parse(e)}
+`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} +`}hr(e){return`
+`}list(e){let t=e.ordered,n=e.start,r="";for(let a=0;a +`+r+" +`}listitem(e){return`
  • ${this.parser.parse(e.tokens)}
  • +`}checkbox({checked:e}){return" '}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    +`}table(e){let t="",n="";for(let i=0;i${r}`),` + +`+t+` +`+r+`
    +`}tablerow({text:e}){return` +${e} +`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` +`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${w(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=X(e);if(i===null)return r;e=i;let s='
    ",s}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=X(e);if(i===null)return w(n);e=i;let s=`${n}{let a=i[s].flat(1/0);n=n.concat(this.walkTokens(a,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let s=t.renderers[i.name];s?t.renderers[i.name]=function(...a){let o=i.renderer.apply(this,a);return o===!1&&(o=s.apply(this,a)),o}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[i.level];s?s.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),r.extensions=t),n.renderer){let i=this.defaults.renderer||new P(this.defaults);for(let s in n.renderer){if(!(s in i))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let a=s,o=n.renderer[a],l=i[a];i[a]=(...p)=>{let c=o.apply(i,p);return c===!1&&(c=l.apply(i,p)),c||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new y(this.defaults);for(let s in n.tokenizer){if(!(s in i))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let a=s,o=n.tokenizer[a],l=i[a];i[a]=(...p)=>{let c=o.apply(i,p);return c===!1&&(c=l.apply(i,p)),c}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new S;for(let s in n.hooks){if(!(s in i))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let a=s,o=n.hooks[a],l=i[a];S.passThroughHooks.has(s)?i[a]=p=>{if(this.defaults.async&&S.passThroughHooksRespectAsync.has(s))return(async()=>{let g=await o.call(i,p);return l.call(i,g)})();let c=o.call(i,p);return l.call(i,c)}:i[a]=(...p)=>{if(this.defaults.async)return(async()=>{let g=await o.apply(i,p);return g===!1&&(g=await l.apply(i,p)),g})();let c=o.apply(i,p);return c===!1&&(c=l.apply(i,p)),c}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(a){let o=[];return o.push(s.call(this,a)),i&&(o=o.concat(i.call(this,a))),o}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,r)=>{let i={...r},s={...this.defaults,...i},a=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let o=s.hooks?await s.hooks.preprocess(n):n,p=await(s.hooks?await s.hooks.provideLexer():e?x.lex:x.lexInline)(o,s),c=s.hooks?await s.hooks.processAllTokens(p):p;s.walkTokens&&await Promise.all(this.walkTokens(c,s.walkTokens));let h=await(s.hooks?await s.hooks.provideParser():e?b.parse:b.parseInline)(c,s);return s.hooks?await s.hooks.postprocess(h):h})().catch(a);try{s.hooks&&(n=s.hooks.preprocess(n));let l=(s.hooks?s.hooks.provideLexer():e?x.lex:x.lexInline)(n,s);s.hooks&&(l=s.hooks.processAllTokens(l)),s.walkTokens&&this.walkTokens(l,s.walkTokens);let c=(s.hooks?s.hooks.provideParser():e?b.parse:b.parseInline)(l,s);return s.hooks&&(c=s.hooks.postprocess(c)),c}catch(o){return a(o)}}}onError(e,t){return n=>{if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let r="

    An error occurred:

    "+w(n.message+"",!0)+"
    ";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}};var _=new B;function d(u,e){return _.parse(u,e)}d.options=d.setOptions=function(u){return _.setOptions(u),d.defaults=_.defaults,Z(d.defaults),d};d.getDefaults=L;d.defaults=T;d.use=function(...u){return _.use(...u),d.defaults=_.defaults,Z(d.defaults),d};d.walkTokens=function(u,e){return _.walkTokens(u,e)};d.parseInline=_.parseInline;d.Parser=b;d.parser=b.parse;d.Renderer=P;d.TextRenderer=$;d.Lexer=x;d.lexer=x.lex;d.Tokenizer=y;d.Hooks=S;d.parse=d;var Dt=d.options,Ht=d.setOptions,Zt=d.use,Gt=d.walkTokens,Nt=d.parseInline,Qt=d,Ft=b.parse,jt=x.lex; +//# sourceMappingURL=marked.esm.js.map + + +/***/ }, + +/***/ "./node_modules/pako/dist/pako.esm.mjs" +/*!*********************************************!*\ + !*** ./node_modules/pako/dist/pako.esm.mjs ***! + \*********************************************/ +(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ Deflate: () => (/* binding */ Deflate_1), +/* harmony export */ Inflate: () => (/* binding */ Inflate_1), +/* harmony export */ constants: () => (/* binding */ constants_1), +/* harmony export */ "default": () => (/* binding */ pako), +/* harmony export */ deflate: () => (/* binding */ deflate_1), +/* harmony export */ deflateRaw: () => (/* binding */ deflateRaw_1), +/* harmony export */ gzip: () => (/* binding */ gzip_1), +/* harmony export */ inflate: () => (/* binding */ inflate_1), +/* harmony export */ inflateRaw: () => (/* binding */ inflateRaw_1), +/* harmony export */ ungzip: () => (/* binding */ ungzip_1) +/* harmony export */ }); + +/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */ +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +/* eslint-disable space-unary-ops */ + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//const Z_FILTERED = 1; +//const Z_HUFFMAN_ONLY = 2; +//const Z_RLE = 3; +const Z_FIXED$1 = 4; +//const Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +const Z_BINARY = 0; +const Z_TEXT = 1; +//const Z_ASCII = 1; // = Z_TEXT +const Z_UNKNOWN$1 = 2; + +/*============================================================================*/ + + +function zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +const STORED_BLOCK = 0; +const STATIC_TREES = 1; +const DYN_TREES = 2; +/* The three kinds of block type */ + +const MIN_MATCH$1 = 3; +const MAX_MATCH$1 = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +const LENGTH_CODES$1 = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +const LITERALS$1 = 256; +/* number of literal bytes 0..255 */ + +const L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1; +/* number of Literal or Length codes, including the END_BLOCK code */ + +const D_CODES$1 = 30; +/* number of distance codes */ + +const BL_CODES$1 = 19; +/* number of codes used to transfer the bit lengths */ + +const HEAP_SIZE$1 = 2 * L_CODES$1 + 1; +/* maximum heap size */ + +const MAX_BITS$1 = 15; +/* All codes must not exceed MAX_BITS bits */ + +const Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +const MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +const END_BLOCK = 256; +/* end of block literal code */ + +const REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +const REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +const REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +const extra_lbits = /* extra bits for each length code */ + new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]); + +const extra_dbits = /* extra bits for each distance code */ + new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]); + +const extra_blbits = /* extra bits for each bit length code */ + new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]); + +const bl_order = + new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]); +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +const DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +const static_ltree = new Array((L_CODES$1 + 2) * 2); +zero$1(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +const static_dtree = new Array(D_CODES$1 * 2); +zero$1(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +const _dist_code = new Array(DIST_CODE_LEN); +zero$1(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +const _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1); +zero$1(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +const base_length = new Array(LENGTH_CODES$1); +zero$1(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +const base_dist = new Array(D_CODES$1); +zero$1(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +let static_l_desc; +let static_d_desc; +let static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +const d_code = (dist) => { + + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +}; + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +const put_short = (s, w) => { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +}; + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +const send_bits = (s, value, length) => { + + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +}; + + +const send_code = (s, c, tree) => { + + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +}; + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +const bi_reverse = (code, len) => { + + let res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +}; + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +const bi_flush = (s) => { + + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +}; + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +const gen_bitlen = (s, desc) => { +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ + + const tree = desc.dyn_tree; + const max_code = desc.max_code; + const stree = desc.stat_desc.static_tree; + const has_stree = desc.stat_desc.has_stree; + const extra = desc.stat_desc.extra_bits; + const base = desc.stat_desc.extra_base; + const max_length = desc.stat_desc.max_length; + let h; /* heap index */ + let n, m; /* iterate over the tree elements */ + let bits; /* bit length */ + let xbits; /* extra bits */ + let f; /* frequency */ + let overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS$1; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Tracev((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +}; + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +const gen_codes = (tree, max_code, bl_count) => { +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ + + const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */ + let code = 0; /* running code value */ + let bits; /* bit index */ + let n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS$1; bits++) { + code = (code + bl_count[bits - 1]) << 1; + next_code[bits] = code; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< { + + let n; /* iterates over tree elements */ + let bits; /* bit counter */ + let length; /* length value */ + let code; /* code value */ + let dist; /* distance index */ + const bl_count = new Array(MAX_BITS$1 + 1); + /* number of codes at each bit length for an optimal tree */ + + // do check in _tr_init() + //if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ +/*#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; +#endif*/ + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES$1 - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES$1; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS$1; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES$1 + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES$1; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS); + + //static_init_done = true; +}; + + +/* =========================================================================== + * Initialize a new block. + */ +const init_block = (s) => { + + let n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES$1; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES$1; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.sym_next = s.matches = 0; +}; + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +const bi_windup = (s) => +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +}; + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +const smaller = (tree, n, m, depth) => { + + const _n2 = n * 2; + const _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +}; + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +const pqdownheap = (s, tree, k) => { +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ + + const v = s.heap[k]; + let j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +}; + + +// inlined manually +// const SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +const compress_block = (s, ltree, dtree) => { +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ + + let dist; /* distance of matched string */ + let lc; /* match length or unmatched char (if dist == 0) */ + let sx = 0; /* running index in sym_buf */ + let code; /* the code to send */ + let extra; /* number of extra bits to send */ + + if (s.sym_next !== 0) { + do { + dist = s.pending_buf[s.sym_buf + sx++] & 0xff; + dist += (s.pending_buf[s.sym_buf + sx++] & 0xff) << 8; + lc = s.pending_buf[s.sym_buf + sx++]; + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and sym_buf is ok: */ + //Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow"); + + } while (sx < s.sym_next); + } + + send_code(s, END_BLOCK, ltree); +}; + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +const build_tree = (s, desc) => { +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ + + const tree = desc.dyn_tree; + const stree = desc.stat_desc.static_tree; + const has_stree = desc.stat_desc.has_stree; + const elems = desc.stat_desc.elems; + let n, m; /* iterate over heap elements */ + let max_code = -1; /* largest code with non zero frequency */ + let node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE$1; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +}; + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +const scan_tree = (s, tree, max_code) => { +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ + + let n; /* iterates over all tree elements */ + let prevlen = -1; /* last emitted length */ + let curlen; /* length of current code */ + + let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + let count = 0; /* repeat count of the current code */ + let max_count = 7; /* max repeat count */ + let min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +}; + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +const send_tree = (s, tree, max_code) => { +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ + + let n; /* iterates over all tree elements */ + let prevlen = -1; /* last emitted length */ + let curlen; /* length of current code */ + + let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + let count = 0; /* repeat count of the current code */ + let max_count = 7; /* max repeat count */ + let min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +}; + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +const build_bl_tree = (s) => { + + let max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +}; + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +const send_all_trees = (s, lcodes, dcodes, blcodes) => { +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ + + let rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +}; + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "block list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +const detect_data_type = (s) => { + /* block_mask is the bit mask of block-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + let block_mask = 0xf3ffc07f; + let n; + + /* Check for non-textual ("block-listed") bytes. */ + for (n = 0; n <= 31; n++, block_mask >>>= 1) { + if ((block_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("allow-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS$1; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "block-listed" or "allow-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +}; + + +let static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +const _tr_init$1 = (s) => +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +}; + + +/* =========================================================================== + * Send a stored block + */ +const _tr_stored_block$1 = (s, buf, stored_len, last) => { +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ + + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + bi_windup(s); /* align on byte boundary */ + put_short(s, stored_len); + put_short(s, ~stored_len); + if (stored_len) { + s.pending_buf.set(s.window.subarray(buf, buf + stored_len), s.pending); + } + s.pending += stored_len; +}; + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +const _tr_align$1 = (s) => { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +}; + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and write out the encoded block. + */ +const _tr_flush_block$1 = (s, buf, stored_len, last) => { +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ + + let opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + let max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN$1) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->sym_next / 3)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block$1(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +}; + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +const _tr_tally$1 = (s, dist, lc) => { +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ + + s.pending_buf[s.sym_buf + s.sym_next++] = dist; + s.pending_buf[s.sym_buf + s.sym_next++] = dist >> 8; + s.pending_buf[s.sym_buf + s.sym_next++] = lc; + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + + return (s.sym_next === s.sym_end); +}; + +var _tr_init_1 = _tr_init$1; +var _tr_stored_block_1 = _tr_stored_block$1; +var _tr_flush_block_1 = _tr_flush_block$1; +var _tr_tally_1 = _tr_tally$1; +var _tr_align_1 = _tr_align$1; + +var trees = { + _tr_init: _tr_init_1, + _tr_stored_block: _tr_stored_block_1, + _tr_flush_block: _tr_flush_block_1, + _tr_tally: _tr_tally_1, + _tr_align: _tr_align_1 +}; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +const adler32 = (adler, buf, len, pos) => { + let s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +}; + + +var adler32_1 = adler32; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +const makeTable = () => { + let c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +}; + +// Create table on load. Just 255 signed longs. Not a problem. +const crcTable = new Uint32Array(makeTable()); + + +const crc32 = (crc, buf, len, pos) => { + const t = crcTable; + const end = pos + len; + + crc ^= -1; + + for (let i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +}; + + +var crc32_1 = crc32; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var messages = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var constants$2 = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +const { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees; + + + + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +const { + Z_NO_FLUSH: Z_NO_FLUSH$2, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$3, Z_BLOCK: Z_BLOCK$1, + Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_BUF_ERROR: Z_BUF_ERROR$1, + Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1, + Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1, + Z_UNKNOWN, + Z_DEFLATED: Z_DEFLATED$2 +} = constants$2; + +/*============================================================================*/ + + +const MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +const MAX_WBITS$1 = 15; +/* 32K LZ77 window */ +const DEF_MEM_LEVEL = 8; + + +const LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +const LITERALS = 256; +/* number of literal bytes 0..255 */ +const L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +const D_CODES = 30; +/* number of distance codes */ +const BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +const HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +const MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +const MIN_MATCH = 3; +const MAX_MATCH = 258; +const MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +const PRESET_DICT = 0x20; + +const INIT_STATE = 42; /* zlib header -> BUSY_STATE */ +//#ifdef GZIP +const GZIP_STATE = 57; /* gzip header -> BUSY_STATE | EXTRA_STATE */ +//#endif +const EXTRA_STATE = 69; /* gzip extra block -> NAME_STATE */ +const NAME_STATE = 73; /* gzip file name -> COMMENT_STATE */ +const COMMENT_STATE = 91; /* gzip comment -> HCRC_STATE */ +const HCRC_STATE = 103; /* gzip header CRC -> BUSY_STATE */ +const BUSY_STATE = 113; /* deflate -> FINISH_STATE */ +const FINISH_STATE = 666; /* stream complete */ + +const BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +const BS_BLOCK_DONE = 2; /* block flush performed */ +const BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +const BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +const OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +const err = (strm, errorCode) => { + strm.msg = messages[errorCode]; + return errorCode; +}; + +const rank = (f) => { + return ((f) * 2) - ((f) > 4 ? 9 : 0); +}; + +const zero = (buf) => { + let len = buf.length; while (--len >= 0) { buf[len] = 0; } +}; + +/* =========================================================================== + * Slide the hash table when sliding the window down (could be avoided with 32 + * bit values at the expense of memory usage). We slide even when level == 0 to + * keep the hash table consistent if we switch back to level > 0 later. + */ +const slide_hash = (s) => { + let n, m; + let p; + let wsize = s.w_size; + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= wsize ? m - wsize : 0); + } while (--n); + n = wsize; +//#ifndef FASTEST + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= wsize ? m - wsize : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); +//#endif +}; + +/* eslint-disable new-cap */ +let HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask; +// This hash causes less collisions, https://github.com/nodeca/pako/issues/135 +// But breaks binary compatibility +//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask; +let HASH = HASH_ZLIB; + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output, except for + * some deflate_stored() output, goes through this function so some + * applications may wish to modify it to avoid allocating a large + * strm->next_out buffer and copying into it. (See also read_buf()). + */ +const flush_pending = (strm) => { + const s = strm.state; + + //_tr_flush_bits(s); + let len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +}; + + +const flush_block_only = (s, last) => { + _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +}; + + +const put_byte = (s, b) => { + s.pending_buf[s.pending++] = b; +}; + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +const putShortMSB = (s, b) => { + + // put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +}; + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +const read_buf = (strm, buf, start, size) => { + + let len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start); + if (strm.state.wrap === 1) { + strm.adler = adler32_1(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32_1(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +}; + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +const longest_match = (s, cur_match) => { + + let chain_length = s.max_chain_length; /* max hash chain length */ + let scan = s.strstart; /* current string */ + let match; /* matched string */ + let len; /* length of current match */ + let best_len = s.prev_length; /* best match length so far */ + let nice_match = s.nice_match; /* stop if match long enough */ + const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + const _win = s.window; // shortcut + + const wmask = s.w_mask; + const prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + const strend = s.strstart + MAX_MATCH; + let scan_end1 = _win[scan + best_len - 1]; + let scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +}; + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +const fill_window = (s) => { + + const _w_size = s.w_size; + let n, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + s.window.set(s.window.subarray(_w_size, _w_size + _w_size - more), 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + if (s.insert > s.strstart) { + s.insert = s.strstart; + } + slide_hash(s); + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = HASH(s, s.ins_h, s.window[str + 1]); +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]); + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// const curr = s.strstart + s.lookahead; +// let init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +}; + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * + * In case deflateParams() is used to later switch to a non-zero compression + * level, s->matches (otherwise unused when storing) keeps track of the number + * of hash table slides to perform. If s->matches is 1, then one hash table + * slide will be done when switching. If s->matches is 2, the maximum value + * allowed here, then the hash table will be cleared, since two or more slides + * is the same as a clear. + * + * deflate_stored() is written to minimize the number of times an input byte is + * copied. It is most efficient with large input and output buffers, which + * maximizes the opportunites to have a single copy from next_in to next_out. + */ +const deflate_stored = (s, flush) => { + + /* Smallest worthy block size when not flushing or finishing. By default + * this is 32K. This can be as small as 507 bytes for memLevel == 1. For + * large input and output buffers, the stored block size will be larger. + */ + let min_block = s.pending_buf_size - 5 > s.w_size ? s.w_size : s.pending_buf_size - 5; + + /* Copy as many min_block or larger stored blocks directly to next_out as + * possible. If flushing, copy the remaining available input to next_out as + * stored blocks, if there is enough space. + */ + let len, left, have, last = 0; + let used = s.strm.avail_in; + do { + /* Set len to the maximum size block that we can copy directly with the + * available input data and output space. Set left to how much of that + * would be copied from what's left in the window. + */ + len = 65535/* MAX_STORED */; /* maximum deflate stored block length */ + have = (s.bi_valid + 42) >> 3; /* number of header bytes */ + if (s.strm.avail_out < have) { /* need room for header */ + break; + } + /* maximum stored block length that will fit in avail_out: */ + have = s.strm.avail_out - have; + left = s.strstart - s.block_start; /* bytes left in window */ + if (len > left + s.strm.avail_in) { + len = left + s.strm.avail_in; /* limit len to the input */ + } + if (len > have) { + len = have; /* limit len to the output */ + } + + /* If the stored block would be less than min_block in length, or if + * unable to copy all of the available input when flushing, then try + * copying to the window and the pending buffer instead. Also don't + * write an empty block when flushing -- deflate() does that. + */ + if (len < min_block && ((len === 0 && flush !== Z_FINISH$3) || + flush === Z_NO_FLUSH$2 || + len !== left + s.strm.avail_in)) { + break; + } + + /* Make a dummy stored block in pending to get the header bytes, + * including any pending bits. This also updates the debugging counts. + */ + last = flush === Z_FINISH$3 && len === left + s.strm.avail_in ? 1 : 0; + _tr_stored_block(s, 0, 0, last); + + /* Replace the lengths in the dummy stored block with len. */ + s.pending_buf[s.pending - 4] = len; + s.pending_buf[s.pending - 3] = len >> 8; + s.pending_buf[s.pending - 2] = ~len; + s.pending_buf[s.pending - 1] = ~len >> 8; + + /* Write the stored block header bytes. */ + flush_pending(s.strm); + +//#ifdef ZLIB_DEBUG +// /* Update debugging counts for the data about to be copied. */ +// s->compressed_len += len << 3; +// s->bits_sent += len << 3; +//#endif + + /* Copy uncompressed bytes from the window to next_out. */ + if (left) { + if (left > len) { + left = len; + } + //zmemcpy(s->strm->next_out, s->window + s->block_start, left); + s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out); + s.strm.next_out += left; + s.strm.avail_out -= left; + s.strm.total_out += left; + s.block_start += left; + len -= left; + } + + /* Copy uncompressed bytes directly from next_in to next_out, updating + * the check value. + */ + if (len) { + read_buf(s.strm, s.strm.output, s.strm.next_out, len); + s.strm.next_out += len; + s.strm.avail_out -= len; + s.strm.total_out += len; + } + } while (last === 0); + + /* Update the sliding window with the last s->w_size bytes of the copied + * data, or append all of the copied data to the existing window if less + * than s->w_size bytes were copied. Also update the number of bytes to + * insert in the hash tables, in the event that deflateParams() switches to + * a non-zero compression level. + */ + used -= s.strm.avail_in; /* number of input bytes directly copied */ + if (used) { + /* If any input was used, then no unused input remains in the window, + * therefore s->block_start == s->strstart. + */ + if (used >= s.w_size) { /* supplant the previous history */ + s.matches = 2; /* clear hash */ + //zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size); + s.window.set(s.strm.input.subarray(s.strm.next_in - s.w_size, s.strm.next_in), 0); + s.strstart = s.w_size; + s.insert = s.strstart; + } + else { + if (s.window_size - s.strstart <= used) { + /* Slide the window down. */ + s.strstart -= s.w_size; + //zmemcpy(s->window, s->window + s->w_size, s->strstart); + s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0); + if (s.matches < 2) { + s.matches++; /* add a pending slide_hash() */ + } + if (s.insert > s.strstart) { + s.insert = s.strstart; + } + } + //zmemcpy(s->window + s->strstart, s->strm->next_in - used, used); + s.window.set(s.strm.input.subarray(s.strm.next_in - used, s.strm.next_in), s.strstart); + s.strstart += used; + s.insert += used > s.w_size - s.insert ? s.w_size - s.insert : used; + } + s.block_start = s.strstart; + } + if (s.high_water < s.strstart) { + s.high_water = s.strstart; + } + + /* If the last block was written to next_out, then done. */ + if (last) { + return BS_FINISH_DONE; + } + + /* If flushing and all input has been consumed, then done. */ + if (flush !== Z_NO_FLUSH$2 && flush !== Z_FINISH$3 && + s.strm.avail_in === 0 && s.strstart === s.block_start) { + return BS_BLOCK_DONE; + } + + /* Fill the window with any remaining input. */ + have = s.window_size - s.strstart; + if (s.strm.avail_in > have && s.block_start >= s.w_size) { + /* Slide the window down. */ + s.block_start -= s.w_size; + s.strstart -= s.w_size; + //zmemcpy(s->window, s->window + s->w_size, s->strstart); + s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0); + if (s.matches < 2) { + s.matches++; /* add a pending slide_hash() */ + } + have += s.w_size; /* more space now */ + if (s.insert > s.strstart) { + s.insert = s.strstart; + } + } + if (have > s.strm.avail_in) { + have = s.strm.avail_in; + } + if (have) { + read_buf(s.strm, s.window, s.strstart, have); + s.strstart += have; + s.insert += have > s.w_size - s.insert ? s.w_size - s.insert : have; + } + if (s.high_water < s.strstart) { + s.high_water = s.strstart; + } + + /* There was not enough avail_out to write a complete worthy or flushed + * stored block to next_out. Write a stored block to pending instead, if we + * have enough input for a worthy block, or if flushing and there is enough + * room for the remaining input as a stored block in the pending buffer. + */ + have = (s.bi_valid + 42) >> 3; /* number of header bytes */ + /* maximum stored block length that will fit in pending: */ + have = s.pending_buf_size - have > 65535/* MAX_STORED */ ? 65535/* MAX_STORED */ : s.pending_buf_size - have; + min_block = have > s.w_size ? s.w_size : have; + left = s.strstart - s.block_start; + if (left >= min_block || + ((left || flush === Z_FINISH$3) && flush !== Z_NO_FLUSH$2 && + s.strm.avail_in === 0 && left <= have)) { + len = left > have ? have : left; + last = flush === Z_FINISH$3 && s.strm.avail_in === 0 && + len === left ? 1 : 0; + _tr_stored_block(s, s.block_start, len, last); + s.block_start += len; + flush_pending(s.strm); + } + + /* We've done all we can with the available input and output. */ + return last ? BS_FINISH_STARTED : BS_NEED_MORE; +}; + + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +const deflate_fast = (s, flush) => { + + let hash_head; /* head of the hash chain */ + let bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]); + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]); + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]); + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH$3) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.sym_next) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +}; + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +const deflate_slow = (s, flush) => { + + let hash_head; /* head of hash chain */ + let bflush; /* set if current block must be flushed */ + + let max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]); + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]); + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH$3) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.sym_next) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +}; + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +const deflate_rle = (s, flush) => { + + let bflush; /* set if current block must be flushed */ + let prev; /* byte at distance one to match */ + let scan, strend; /* scan goes up to strend for length of run */ + + const _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$2) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH$3) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.sym_next) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +}; + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +const deflate_huff = (s, flush) => { + + let bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH$2) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH$3) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.sym_next) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +}; + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +const configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +const lm_init = (s) => { + + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +}; + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED$2; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new Uint16Array(HEAP_SIZE * 2); + this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2); + this.bl_tree = new Uint16Array((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new Uint16Array(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new Uint16Array(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.sym_buf = 0; /* buffer for distances and literals/lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.sym_next = 0; /* running index in sym_buf */ + this.sym_end = 0; /* symbol table full when sym_next reaches this */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +/* ========================================================================= + * Check for a valid deflate stream state. Return 0 if ok, 1 if not. + */ +const deflateStateCheck = (strm) => { + + if (!strm) { + return 1; + } + const s = strm.state; + if (!s || s.strm !== strm || (s.status !== INIT_STATE && +//#ifdef GZIP + s.status !== GZIP_STATE && +//#endif + s.status !== EXTRA_STATE && + s.status !== NAME_STATE && + s.status !== COMMENT_STATE && + s.status !== HCRC_STATE && + s.status !== BUSY_STATE && + s.status !== FINISH_STATE)) { + return 1; + } + return 0; +}; + + +const deflateResetKeep = (strm) => { + + if (deflateStateCheck(strm)) { + return err(strm, Z_STREAM_ERROR$2); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + const s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = +//#ifdef GZIP + s.wrap === 2 ? GZIP_STATE : +//#endif + s.wrap ? INIT_STATE : BUSY_STATE; + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = -2; + _tr_init(s); + return Z_OK$3; +}; + + +const deflateReset = (strm) => { + + const ret = deflateResetKeep(strm); + if (ret === Z_OK$3) { + lm_init(strm.state); + } + return ret; +}; + + +const deflateSetHeader = (strm, head) => { + + if (deflateStateCheck(strm) || strm.state.wrap !== 2) { + return Z_STREAM_ERROR$2; + } + strm.state.gzhead = head; + return Z_OK$3; +}; + + +const deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => { + + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR$2; + } + let wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION$1) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED || (windowBits === 8 && wrap !== 1)) { + return err(strm, Z_STREAM_ERROR$2); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + const s = new DeflateState(); + + strm.state = s; + s.strm = strm; + s.status = INIT_STATE; /* to pass state test in deflateReset() */ + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new Uint8Array(s.w_size * 2); + s.head = new Uint16Array(s.hash_size); + s.prev = new Uint16Array(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + /* We overlay pending_buf and sym_buf. This works since the average size + * for length/distance pairs over any compressed block is assured to be 31 + * bits or less. + * + * Analysis: The longest fixed codes are a length code of 8 bits plus 5 + * extra bits, for lengths 131 to 257. The longest fixed distance codes are + * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest + * possible fixed-codes length/distance pair is then 31 bits total. + * + * sym_buf starts one-fourth of the way into pending_buf. So there are + * three bytes in sym_buf for every four bytes in pending_buf. Each symbol + * in sym_buf is three bytes -- two for the distance and one for the + * literal/length. As each symbol is consumed, the pointer to the next + * sym_buf value to read moves forward three bytes. From that symbol, up to + * 31 bits are written to pending_buf. The closest the written pending_buf + * bits gets to the next sym_buf symbol to read is just before the last + * code is written. At that time, 31*(n-2) bits have been written, just + * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at + * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1 + * symbols are written.) The closest the writing gets to what is unread is + * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and + * can range from 128 to 32768. + * + * Therefore, at a minimum, there are 142 bits of space between what is + * written and what is read in the overlain buffers, so the symbols cannot + * be overwritten by the compressed data. That space is actually 139 bits, + * due to the three-bit fixed-code block header. + * + * That covers the case where either Z_FIXED is specified, forcing fixed + * codes, or when the use of fixed codes is chosen, because that choice + * results in a smaller compressed block than dynamic codes. That latter + * condition then assures that the above analysis also covers all dynamic + * blocks. A dynamic-code block will only be chosen to be emitted if it has + * fewer bits than a fixed-code block would for the same set of symbols. + * Therefore its average symbol length is assured to be less than 31. So + * the compressed data for a dynamic block also cannot overwrite the + * symbols from which it is being constructed. + */ + + s.pending_buf_size = s.lit_bufsize * 4; + s.pending_buf = new Uint8Array(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->sym_buf = s->pending_buf + s->lit_bufsize; + s.sym_buf = s.lit_bufsize; + + //s->sym_end = (s->lit_bufsize - 1) * 3; + s.sym_end = (s.lit_bufsize - 1) * 3; + /* We avoid equality with lit_bufsize*3 because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +}; + +const deflateInit = (strm, level) => { + + return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1); +}; + + +/* ========================================================================= */ +const deflate$2 = (strm, flush) => { + + if (deflateStateCheck(strm) || flush > Z_BLOCK$1 || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2; + } + + const s = strm.state; + + if (!strm.output || + (strm.avail_in !== 0 && !strm.input) || + (s.status === FINISH_STATE && flush !== Z_FINISH$3)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$2); + } + + const old_flush = s.last_flush; + s.last_flush = flush; + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK$3; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH$3) { + return err(strm, Z_BUF_ERROR$1); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR$1); + } + + /* Write the header */ + if (s.status === INIT_STATE && s.wrap === 0) { + s.status = BUSY_STATE; + } + if (s.status === INIT_STATE) { + /* zlib header */ + let header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8; + let level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s.pending !== 0) { + s.last_flush = -1; + return Z_OK$3; + } + } +//#ifdef GZIP + if (s.status === GZIP_STATE) { + /* gzip header */ + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s.pending !== 0) { + s.last_flush = -1; + return Z_OK$3; + } + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + let beg = s.pending; /* start of bytes to update crc */ + let left = (s.gzhead.extra.length & 0xffff) - s.gzindex; + while (s.pending + left > s.pending_buf_size) { + let copy = s.pending_buf_size - s.pending; + // zmemcpy(s.pending_buf + s.pending, + // s.gzhead.extra + s.gzindex, copy); + s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex, s.gzindex + copy), s.pending); + s.pending = s.pending_buf_size; + //--- HCRC_UPDATE(beg) ---// + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + //---// + s.gzindex += copy; + flush_pending(strm); + if (s.pending !== 0) { + s.last_flush = -1; + return Z_OK$3; + } + beg = 0; + left -= copy; + } + // JS specific: s.gzhead.extra may be TypedArray or Array for backward compatibility + // TypedArray.slice and TypedArray.from don't exist in IE10-IE11 + let gzhead_extra = new Uint8Array(s.gzhead.extra); + // zmemcpy(s->pending_buf + s->pending, + // s->gzhead->extra + s->gzindex, left); + s.pending_buf.set(gzhead_extra.subarray(s.gzindex, s.gzindex + left), s.pending); + s.pending += left; + //--- HCRC_UPDATE(beg) ---// + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + //---// + s.gzindex = 0; + } + s.status = NAME_STATE; + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + let beg = s.pending; /* start of bytes to update crc */ + let val; + do { + if (s.pending === s.pending_buf_size) { + //--- HCRC_UPDATE(beg) ---// + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + //---// + flush_pending(strm); + if (s.pending !== 0) { + s.last_flush = -1; + return Z_OK$3; + } + beg = 0; + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + //--- HCRC_UPDATE(beg) ---// + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + //---// + s.gzindex = 0; + } + s.status = COMMENT_STATE; + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + let beg = s.pending; /* start of bytes to update crc */ + let val; + do { + if (s.pending === s.pending_buf_size) { + //--- HCRC_UPDATE(beg) ---// + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + //---// + flush_pending(strm); + if (s.pending !== 0) { + s.last_flush = -1; + return Z_OK$3; + } + beg = 0; + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + //--- HCRC_UPDATE(beg) ---// + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg); + } + //---// + } + s.status = HCRC_STATE; + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + if (s.pending !== 0) { + s.last_flush = -1; + return Z_OK$3; + } + } + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + } + s.status = BUSY_STATE; + + /* Compression must start with an empty pending buffer */ + flush_pending(strm); + if (s.pending !== 0) { + s.last_flush = -1; + return Z_OK$3; + } + } +//#endif + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE)) { + let bstate = s.level === 0 ? deflate_stored(s, flush) : + s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : + s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK$3; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + _tr_align(s); + } + else if (flush !== Z_BLOCK$1) { /* FULL_FLUSH or SYNC_FLUSH */ + + _tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH$1) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK$3; + } + } + } + + if (flush !== Z_FINISH$3) { return Z_OK$3; } + if (s.wrap <= 0) { return Z_STREAM_END$3; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK$3 : Z_STREAM_END$3; +}; + + +const deflateEnd = (strm) => { + + if (deflateStateCheck(strm)) { + return Z_STREAM_ERROR$2; + } + + const status = strm.state.status; + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$3; +}; + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +const deflateSetDictionary = (strm, dictionary) => { + + let dictLength = dictionary.length; + + if (deflateStateCheck(strm)) { + return Z_STREAM_ERROR$2; + } + + const s = strm.state; + const wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR$2; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + let tmpDict = new Uint8Array(s.w_size); + tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + const avail = strm.avail_in; + const next = strm.next_in; + const input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + let str = s.strstart; + let n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]); + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK$3; +}; + + +var deflateInit_1 = deflateInit; +var deflateInit2_1 = deflateInit2; +var deflateReset_1 = deflateReset; +var deflateResetKeep_1 = deflateResetKeep; +var deflateSetHeader_1 = deflateSetHeader; +var deflate_2$1 = deflate$2; +var deflateEnd_1 = deflateEnd; +var deflateSetDictionary_1 = deflateSetDictionary; +var deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +module.exports.deflateBound = deflateBound; +module.exports.deflateCopy = deflateCopy; +module.exports.deflateGetDictionary = deflateGetDictionary; +module.exports.deflateParams = deflateParams; +module.exports.deflatePending = deflatePending; +module.exports.deflatePrime = deflatePrime; +module.exports.deflateTune = deflateTune; +*/ + +var deflate_1$2 = { + deflateInit: deflateInit_1, + deflateInit2: deflateInit2_1, + deflateReset: deflateReset_1, + deflateResetKeep: deflateResetKeep_1, + deflateSetHeader: deflateSetHeader_1, + deflate: deflate_2$1, + deflateEnd: deflateEnd_1, + deflateSetDictionary: deflateSetDictionary_1, + deflateInfo: deflateInfo +}; + +const _has = (obj, key) => { + return Object.prototype.hasOwnProperty.call(obj, key); +}; + +var assign = function (obj /*from1, from2, from3, ...*/) { + const sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + const source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (const p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// Join array of chunks to single array. +var flattenChunks = (chunks) => { + // calculate data length + let len = 0; + + for (let i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + const result = new Uint8Array(len); + + for (let i = 0, pos = 0, l = chunks.length; i < l; i++) { + let chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; +}; + +var common = { + assign: assign, + flattenChunks: flattenChunks +}; + +// String encode/decode helpers + + +// Quick check if we can use fast array to bin string conversion +// +// - apply(Array) can fail on Android 2.2 +// - apply(Uint8Array) can fail on iOS 5.1 Safari +// +let STR_APPLY_UIA_OK = true; + +try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } + + +// Table with utf8 lengths (calculated by first byte of sequence) +// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, +// because max possible codepoint is 0x10ffff +const _utf8len = new Uint8Array(256); +for (let q = 0; q < 256; q++) { + _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); +} +_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start + + +// convert string to array (typed, when possible) +var string2buf = (str) => { + if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) { + return new TextEncoder().encode(str); + } + + let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + + // count binary size + for (m_pos = 0; m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; + } + + // allocate buffer + buf = new Uint8Array(buf_len); + + // convert + for (i = 0, m_pos = 0; i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 0xfc00) === 0xdc00) { + c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); + m_pos++; + } + } + if (c < 0x80) { + /* one byte */ + buf[i++] = c; + } else if (c < 0x800) { + /* two bytes */ + buf[i++] = 0xC0 | (c >>> 6); + buf[i++] = 0x80 | (c & 0x3f); + } else if (c < 0x10000) { + /* three bytes */ + buf[i++] = 0xE0 | (c >>> 12); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } else { + /* four bytes */ + buf[i++] = 0xf0 | (c >>> 18); + buf[i++] = 0x80 | (c >>> 12 & 0x3f); + buf[i++] = 0x80 | (c >>> 6 & 0x3f); + buf[i++] = 0x80 | (c & 0x3f); + } + } + + return buf; +}; + +// Helper +const buf2binstring = (buf, len) => { + // On Chrome, the arguments in a function call that are allowed is `65534`. + // If the length of the buffer is smaller than that, we can use this optimization, + // otherwise we will take a slower path. + if (len < 65534) { + if (buf.subarray && STR_APPLY_UIA_OK) { + return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len)); + } + } + + let result = ''; + for (let i = 0; i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; +}; + + +// convert array to string +var buf2string = (buf, max) => { + const len = max || buf.length; + + if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) { + return new TextDecoder().decode(buf.subarray(0, max)); + } + + let i, out; + + // Reserve max possible length (2 words per char) + // NB: by unknown reasons, Array is significantly faster for + // String.fromCharCode.apply than Uint16Array. + const utf16buf = new Array(len * 2); + + for (out = 0, i = 0; i < len;) { + let c = buf[i++]; + // quick process ascii + if (c < 0x80) { utf16buf[out++] = c; continue; } + + let c_len = _utf8len[c]; + // skip 5 & 6 byte codes + if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } + + // apply mask on first byte + c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; + // join the rest + while (c_len > 1 && i < len) { + c = (c << 6) | (buf[i++] & 0x3f); + c_len--; + } + + // terminated by end of string? + if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } + + if (c < 0x10000) { + utf16buf[out++] = c; + } else { + c -= 0x10000; + utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); + utf16buf[out++] = 0xdc00 | (c & 0x3ff); + } + } + + return buf2binstring(utf16buf, out); +}; + + +// Calculate max possible position in utf8 buffer, +// that will not break sequence. If that's not possible +// - (very small limits) return max size as is. +// +// buf[] - utf8 bytes array +// max - length limit (mandatory); +var utf8border = (buf, max) => { + + max = max || buf.length; + if (max > buf.length) { max = buf.length; } + + // go back from last position, until start of sequence found + let pos = max - 1; + while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } + + // Very small and broken sequence, + // return max, because we should return something anyway. + if (pos < 0) { return max; } + + // If we came to start of buffer - that means buffer is too small, + // return max too. + if (pos === 0) { return max; } + + return (pos + _utf8len[buf[pos]] > max) ? pos : max; +}; + +var strings = { + string2buf: string2buf, + buf2string: buf2string, + utf8border: utf8border +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +var zstream = ZStream; + +const toString$1 = Object.prototype.toString; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +const { + Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH: Z_FINISH$2, + Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2, + Z_DEFAULT_COMPRESSION, + Z_DEFAULT_STRATEGY, + Z_DEFLATED: Z_DEFLATED$1 +} = constants$2; + +/* ===========================================================================*/ + + +/** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ + +/* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ + +/** + * Deflate.result -> Uint8Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * const pako = require('pako') + * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * const deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +function Deflate$1(options) { + this.options = common.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED$1, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY + }, options || {}); + + let opt = this.options; + + if (opt.raw && (opt.windowBits > 0)) { + opt.windowBits = -opt.windowBits; + } + + else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { + opt.windowBits += 16; + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream(); + this.strm.avail_out = 0; + + let status = deflate_1$2.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK$2) { + throw new Error(messages[status]); + } + + if (opt.header) { + deflate_1$2.deflateSetHeader(this.strm, opt.header); + } + + if (opt.dictionary) { + let dict; + // Convert data if needed + if (typeof opt.dictionary === 'string') { + // If we need to compress text, change encoding to utf8. + dict = strings.string2buf(opt.dictionary); + } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + + status = deflate_1$2.deflateSetDictionary(this.strm, dict); + + if (status !== Z_OK$2) { + throw new Error(messages[status]); + } + + this._dict_set = true; + } +} + +/** + * Deflate#push(data[, flush_mode]) -> Boolean + * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must + * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending + * buffers and call [[Deflate#onEnd]]. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Deflate$1.prototype.push = function (data, flush_mode) { + const strm = this.strm; + const chunkSize = this.options.chunkSize; + let status, _flush_mode; + + if (this.ended) { return false; } + + if (flush_mode === ~~flush_mode) _flush_mode = flush_mode; + else _flush_mode = flush_mode === true ? Z_FINISH$2 : Z_NO_FLUSH$1; + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings.string2buf(data); + } else if (toString$1.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + for (;;) { + if (strm.avail_out === 0) { + strm.output = new Uint8Array(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + // Make sure avail_out > 6 to avoid repeating markers + if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) { + this.onData(strm.output.subarray(0, strm.next_out)); + strm.avail_out = 0; + continue; + } + + status = deflate_1$2.deflate(strm, _flush_mode); + + // Ended => flush and finish + if (status === Z_STREAM_END$2) { + if (strm.next_out > 0) { + this.onData(strm.output.subarray(0, strm.next_out)); + } + status = deflate_1$2.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK$2; + } + + // Flush if out buffer full + if (strm.avail_out === 0) { + this.onData(strm.output); + continue; + } + + // Flush if requested and has data + if (_flush_mode > 0 && strm.next_out > 0) { + this.onData(strm.output.subarray(0, strm.next_out)); + strm.avail_out = 0; + continue; + } + + if (strm.avail_in === 0) break; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array): output data. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate$1.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH). By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate$1.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK$2) { + this.result = common.flattenChunks(this.chunks); + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array + * - data (Uint8Array|ArrayBuffer|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * + * ##### Example: + * + * ```javascript + * const pako = require('pako') + * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate$1(input, options) { + const deflator = new Deflate$1(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg || messages[deflator.err]; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array + * - data (Uint8Array|ArrayBuffer|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw$1(input, options) { + options = options || {}; + options.raw = true; + return deflate$1(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array + * - data (Uint8Array|ArrayBuffer|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip$1(input, options) { + options = options || {}; + options.gzip = true; + return deflate$1(input, options); +} + + +var Deflate_1$1 = Deflate$1; +var deflate_2 = deflate$1; +var deflateRaw_1$1 = deflateRaw$1; +var gzip_1$1 = gzip$1; +var constants$1 = constants$2; + +var deflate_1$1 = { + Deflate: Deflate_1$1, + deflate: deflate_2, + deflateRaw: deflateRaw_1$1, + gzip: gzip_1$1, + constants: constants$1 +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +const BAD$1 = 16209; /* got a data error -- remain here until reset */ +const TYPE$1 = 16191; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +var inffast = function inflate_fast(strm, start) { + let _in; /* local strm.input */ + let last; /* have enough input while in < last */ + let _out; /* local strm.output */ + let beg; /* inflate()'s initial strm.output */ + let end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + let dmax; /* maximum distance from zlib header */ +//#endif + let wsize; /* window size or zero if not using window */ + let whave; /* valid bytes in the window */ + let wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + let s_window; /* allocated sliding window, if wsize != 0 */ + let hold; /* local strm.hold */ + let bits; /* local strm.bits */ + let lcode; /* local strm.lencode */ + let dcode; /* local strm.distcode */ + let lmask; /* mask for first level of length codes */ + let dmask; /* mask for first level of distance codes */ + let here; /* retrieved table entry */ + let op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + let len; /* match length, unused bytes */ + let dist; /* match distance */ + let from; /* where to copy match from */ + let from_source; + + + let input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + const state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$1; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$1; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD$1; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE$1; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD$1; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +const MAXBITS = 15; +const ENOUGH_LENS$1 = 852; +const ENOUGH_DISTS$1 = 592; +//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +const CODES$1 = 0; +const LENS$1 = 1; +const DISTS$1 = 2; + +const lbase = new Uint16Array([ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]); + +const lext = new Uint8Array([ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]); + +const dbase = new Uint16Array([ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]); + +const dext = new Uint8Array([ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]); + +const inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) => +{ + const bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + let len = 0; /* a code's length in bits */ + let sym = 0; /* index of code symbols */ + let min = 0, max = 0; /* minimum and maximum code lengths */ + let root = 0; /* number of index bits for root table */ + let curr = 0; /* number of index bits for current table */ + let drop = 0; /* code bits to drop for sub-table */ + let left = 0; /* number of prefix codes available */ + let used = 0; /* code entries in table used */ + let huff = 0; /* Huffman code */ + let incr; /* for incrementing code, index */ + let fill; /* index for replicating entries */ + let low; /* low bits for current root entry */ + let mask; /* mask for low root bits */ + let next; /* next available space in table */ + let base = null; /* base value table to use */ +// let shoextra; /* extra bits table to use */ + let match; /* use base and extra for symbol >= match */ + const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + let extra = null; + + let here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES$1 || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES$1) { + base = extra = work; /* dummy value--not used */ + match = 20; + + } else if (type === LENS$1) { + base = lbase; + extra = lext; + match = 257; + + } else { /* DISTS */ + base = dbase; + extra = dext; + match = 0; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS$1 && used > ENOUGH_LENS$1) || + (type === DISTS$1 && used > ENOUGH_DISTS$1)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] + 1 < match) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] >= match) { + here_op = extra[work[sym] - match]; + here_val = base[work[sym] - match]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS$1 && used > ENOUGH_LENS$1) || + (type === DISTS$1 && used > ENOUGH_DISTS$1)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + + +var inftrees = inflate_table; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + + + + + + +const CODES = 0; +const LENS = 1; +const DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +const { + Z_FINISH: Z_FINISH$1, Z_BLOCK, Z_TREES, + Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR: Z_MEM_ERROR$1, Z_BUF_ERROR, + Z_DEFLATED +} = constants$2; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +const HEAD = 16180; /* i: waiting for magic header */ +const FLAGS = 16181; /* i: waiting for method and flags (gzip) */ +const TIME = 16182; /* i: waiting for modification time (gzip) */ +const OS = 16183; /* i: waiting for extra flags and operating system (gzip) */ +const EXLEN = 16184; /* i: waiting for extra length (gzip) */ +const EXTRA = 16185; /* i: waiting for extra bytes (gzip) */ +const NAME = 16186; /* i: waiting for end of file name (gzip) */ +const COMMENT = 16187; /* i: waiting for end of comment (gzip) */ +const HCRC = 16188; /* i: waiting for header crc (gzip) */ +const DICTID = 16189; /* i: waiting for dictionary check value */ +const DICT = 16190; /* waiting for inflateSetDictionary() call */ +const TYPE = 16191; /* i: waiting for type bits, including last-flag bit */ +const TYPEDO = 16192; /* i: same, but skip check to exit inflate on new block */ +const STORED = 16193; /* i: waiting for stored size (length and complement) */ +const COPY_ = 16194; /* i/o: same as COPY below, but only first time in */ +const COPY = 16195; /* i/o: waiting for input or output to copy stored block */ +const TABLE = 16196; /* i: waiting for dynamic block table lengths */ +const LENLENS = 16197; /* i: waiting for code length code lengths */ +const CODELENS = 16198; /* i: waiting for length/lit and distance code lengths */ +const LEN_ = 16199; /* i: same as LEN below, but only first time in */ +const LEN = 16200; /* i: waiting for length/lit/eob code */ +const LENEXT = 16201; /* i: waiting for length extra bits */ +const DIST = 16202; /* i: waiting for distance code */ +const DISTEXT = 16203; /* i: waiting for distance extra bits */ +const MATCH = 16204; /* o: waiting for output space to copy string */ +const LIT = 16205; /* o: waiting for output space to write literal */ +const CHECK = 16206; /* i: waiting for 32-bit check value */ +const LENGTH = 16207; /* i: waiting for 32-bit length (gzip) */ +const DONE = 16208; /* finished check, done -- remain here until reset */ +const BAD = 16209; /* got a data error -- remain here until reset */ +const MEM = 16210; /* got an inflate() memory error -- remain here until reset */ +const SYNC = 16211; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +const ENOUGH_LENS = 852; +const ENOUGH_DISTS = 592; +//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +const MAX_WBITS = 15; +/* 32K LZ77 window */ +const DEF_WBITS = MAX_WBITS; + + +const zswap32 = (q) => { + + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +}; + + +function InflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip, + bit 2 true to validate check value */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib), or + -1 if raw or no header yet */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new Uint16Array(320); /* temporary storage for code lengths */ + this.work = new Uint16Array(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new Int32Array(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + + +const inflateStateCheck = (strm) => { + + if (!strm) { + return 1; + } + const state = strm.state; + if (!state || state.strm !== strm || + state.mode < HEAD || state.mode > SYNC) { + return 1; + } + return 0; +}; + + +const inflateResetKeep = (strm) => { + + if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; } + const state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.flags = -1; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS); + state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK$1; +}; + + +const inflateReset = (strm) => { + + if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; } + const state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +}; + + +const inflateReset2 = (strm, windowBits) => { + let wrap; + + /* get the state */ + if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; } + const state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 5; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR$1; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +}; + + +const inflateInit2 = (strm, windowBits) => { + + if (!strm) { return Z_STREAM_ERROR$1; } + //strm.msg = Z_NULL; /* in case we return an error */ + + const state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.strm = strm; + state.window = null/*Z_NULL*/; + state.mode = HEAD; /* to pass state test in inflateReset2() */ + const ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK$1) { + strm.state = null/*Z_NULL*/; + } + return ret; +}; + + +const inflateInit = (strm) => { + + return inflateInit2(strm, DEF_WBITS); +}; + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +let virgin = true; + +let lenfix, distfix; // We have no pointers in JS, so keep tables separate + + +const fixedtables = (state) => { + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + lenfix = new Int32Array(512); + distfix = new Int32Array(32); + + /* literal/length table */ + let sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inftrees(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inftrees(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +}; + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +const updatewindow = (strm, src, end, copy) => { + + let dist; + const state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new Uint8Array(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + state.window.set(src.subarray(end - state.wsize, end), 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + state.window.set(src.subarray(end - copy, end), 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +}; + + +const inflate$2 = (strm, flush) => { + + let state; + let input, output; // input/output buffers + let next; /* next input INDEX */ + let put; /* next output INDEX */ + let have, left; /* available input and output */ + let hold; /* bit buffer */ + let bits; /* bits in bit buffer */ + let _in, _out; /* save starting available input and output */ + let copy; /* number of stored or match bytes to copy */ + let from; /* where to copy match bytes from */ + let from_source; + let here = 0; /* current decoding table entry */ + let here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //let last; /* parent table entry */ + let last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + let len; /* length to copy for repeats, bits to drop */ + let ret; /* return code */ + const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */ + let opts; + + let n; // temporary variable for NEED_BITS + + const order = /* permutation of code lengths */ + new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]); + + + if (inflateStateCheck(strm) || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR$1; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK$1; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + if (state.wbits === 0) { + state.wbits = 15; + } + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + if (len > 15 || len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + + // !!! pako patch. Force use `options.windowBits` if passed. + // Required to always use max window size by default. + state.dmax = 1 << state.wbits; + //state.dmax = 1 << len; + + state.flags = 0; /* indicate zlib header */ + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if ((state.flags & 0x0200) && (state.wrap & 4)) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if ((state.flags & 0x0200) && (state.wrap & 4)) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32_1(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if ((state.flags & 0x0200) && (state.wrap & 4)) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if ((state.flags & 0x0200) && (state.wrap & 4)) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32_1(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Uint8Array(state.head.extra_len); + } + state.head.extra.set( + input.subarray( + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + next + copy + ), + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if ((state.flags & 0x0200) && (state.wrap & 4)) { + state.check = crc32_1(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if ((state.flags & 0x0200) && (state.wrap & 4)) { + state.check = crc32_1(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if ((state.flags & 0x0200) && (state.wrap & 4)) { + state.check = crc32_1(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 4) && hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT$1; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + output.set(input.subarray(next, next + copy), put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inffast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if ((state.wrap & 4) && _out) { + strm.adler = state.check = + /*UPDATE_CHECK(state.check, put - _out, _out);*/ + (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.wrap & 4) && (state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 4) && hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END$1; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR$1; + break inf_leave; + case MEM: + return Z_MEM_ERROR$1; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR$1; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH$1))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if ((state.wrap & 4) && _out) { + strm.adler = state.check = /*UPDATE_CHECK(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) { + ret = Z_BUF_ERROR; + } + return ret; +}; + + +const inflateEnd = (strm) => { + + if (inflateStateCheck(strm)) { + return Z_STREAM_ERROR$1; + } + + let state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK$1; +}; + + +const inflateGetHeader = (strm, head) => { + + /* check state */ + if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; } + const state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK$1; +}; + + +const inflateSetDictionary = (strm, dictionary) => { + const dictLength = dictionary.length; + + let state; + let dictid; + let ret; + + /* check state */ + if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR$1; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32_1(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR$1; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR$1; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK$1; +}; + + +var inflateReset_1 = inflateReset; +var inflateReset2_1 = inflateReset2; +var inflateResetKeep_1 = inflateResetKeep; +var inflateInit_1 = inflateInit; +var inflateInit2_1 = inflateInit2; +var inflate_2$1 = inflate$2; +var inflateEnd_1 = inflateEnd; +var inflateGetHeader_1 = inflateGetHeader; +var inflateSetDictionary_1 = inflateSetDictionary; +var inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +module.exports.inflateCodesUsed = inflateCodesUsed; +module.exports.inflateCopy = inflateCopy; +module.exports.inflateGetDictionary = inflateGetDictionary; +module.exports.inflateMark = inflateMark; +module.exports.inflatePrime = inflatePrime; +module.exports.inflateSync = inflateSync; +module.exports.inflateSyncPoint = inflateSyncPoint; +module.exports.inflateUndermine = inflateUndermine; +module.exports.inflateValidate = inflateValidate; +*/ + +var inflate_1$2 = { + inflateReset: inflateReset_1, + inflateReset2: inflateReset2_1, + inflateResetKeep: inflateResetKeep_1, + inflateInit: inflateInit_1, + inflateInit2: inflateInit2_1, + inflate: inflate_2$1, + inflateEnd: inflateEnd_1, + inflateGetHeader: inflateGetHeader_1, + inflateSetDictionary: inflateSetDictionary_1, + inflateInfo: inflateInfo +}; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +var gzheader = GZheader; + +const toString = Object.prototype.toString; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +const { + Z_NO_FLUSH, Z_FINISH, + Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR +} = constants$2; + +/* ===========================================================================*/ + + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overridden. + **/ + +/** + * Inflate.result -> Uint8Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * const pako = require('pako') + * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9]) + * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * const inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +function Inflate$1(options) { + this.options = common.assign({ + chunkSize: 1024 * 64, + windowBits: 15, + to: '' + }, options || {}); + + const opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new zstream(); + this.strm.avail_out = 0; + + let status = inflate_1$2.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== Z_OK) { + throw new Error(messages[status]); + } + + this.header = new gzheader(); + + inflate_1$2.inflateGetHeader(this.strm, this.header); + + // Setup dictionary + if (opt.dictionary) { + // Convert data if needed + if (typeof opt.dictionary === 'string') { + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { //In raw mode we need to set the dictionary early + status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== Z_OK) { + throw new Error(messages[status]); + } + } + } +} + +/** + * Inflate#push(data[, flush_mode]) -> Boolean + * - data (Uint8Array|ArrayBuffer): input data + * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE + * flush modes. See constants. Skipped or `false` means Z_NO_FLUSH, + * `true` means Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. If end of stream detected, + * [[Inflate#onEnd]] will be called. + * + * `flush_mode` is not needed for normal operation, because end of stream + * detected automatically. You may try to use it for advanced things, but + * this functionality was not tested. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Inflate$1.prototype.push = function (data, flush_mode) { + const strm = this.strm; + const chunkSize = this.options.chunkSize; + const dictionary = this.options.dictionary; + let status, _flush_mode, last_avail_out; + + if (this.ended) return false; + + if (flush_mode === ~~flush_mode) _flush_mode = flush_mode; + else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH; + + // Convert data if needed + if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + for (;;) { + if (strm.avail_out === 0) { + strm.output = new Uint8Array(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = inflate_1$2.inflate(strm, _flush_mode); + + if (status === Z_NEED_DICT && dictionary) { + status = inflate_1$2.inflateSetDictionary(strm, dictionary); + + if (status === Z_OK) { + status = inflate_1$2.inflate(strm, _flush_mode); + } else if (status === Z_DATA_ERROR) { + // Replace code with more verbose + status = Z_NEED_DICT; + } + } + + // Skip snyc markers if more data follows and not raw mode + while (strm.avail_in > 0 && + status === Z_STREAM_END && + strm.state.wrap > 0 && + data[strm.next_in] !== 0) + { + inflate_1$2.inflateReset(strm); + status = inflate_1$2.inflate(strm, _flush_mode); + } + + switch (status) { + case Z_STREAM_ERROR: + case Z_DATA_ERROR: + case Z_NEED_DICT: + case Z_MEM_ERROR: + this.onEnd(status); + this.ended = true; + return false; + } + + // Remember real `avail_out` value, because we may patch out buffer content + // to align utf8 strings boundaries. + last_avail_out = strm.avail_out; + + if (strm.next_out) { + if (strm.avail_out === 0 || status === Z_STREAM_END) { + + if (this.options.to === 'string') { + + let next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + + let tail = strm.next_out - next_out_utf8; + let utf8str = strings.buf2string(strm.output, next_out_utf8); + + // move tail & realign counters + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0); + + this.onData(utf8str); + + } else { + this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out)); + } + } + } + + // Must repeat iteration if out buffer is full + if (status === Z_OK && last_avail_out === 0) continue; + + // Finalize if end of stream reached. + if (status === Z_STREAM_END) { + status = inflate_1$2.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return true; + } + + if (strm.avail_in === 0) break; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|String): output data. When string output requested, + * each chunk will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate$1.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH). By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate$1.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = common.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|String + * - data (Uint8Array|ArrayBuffer): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * const pako = require('pako'); + * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9])); + * let output; + * + * try { + * output = pako.inflate(input); + * } catch (err) { + * console.log(err); + * } + * ``` + **/ +function inflate$1(input, options) { + const inflator = new Inflate$1(options); + + inflator.push(input); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) throw inflator.msg || messages[inflator.err]; + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|String + * - data (Uint8Array|ArrayBuffer): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw$1(input, options) { + options = options || {}; + options.raw = true; + return inflate$1(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|String + * - data (Uint8Array|ArrayBuffer): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +var Inflate_1$1 = Inflate$1; +var inflate_2 = inflate$1; +var inflateRaw_1$1 = inflateRaw$1; +var ungzip$1 = inflate$1; +var constants = constants$2; + +var inflate_1$1 = { + Inflate: Inflate_1$1, + inflate: inflate_2, + inflateRaw: inflateRaw_1$1, + ungzip: ungzip$1, + constants: constants +}; + +const { Deflate, deflate, deflateRaw, gzip } = deflate_1$1; + +const { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1; + + + +var Deflate_1 = Deflate; +var deflate_1 = deflate; +var deflateRaw_1 = deflateRaw; +var gzip_1 = gzip; +var Inflate_1 = Inflate; +var inflate_1 = inflate; +var inflateRaw_1 = inflateRaw; +var ungzip_1 = ungzip; +var constants_1 = constants$2; + +var pako = { + Deflate: Deflate_1, + deflate: deflate_1, + deflateRaw: deflateRaw_1, + gzip: gzip_1, + Inflate: Inflate_1, + inflate: inflate_1, + inflateRaw: inflateRaw_1, + ungzip: ungzip_1, + constants: constants_1 +}; + + + + +/***/ }, + +/***/ "./node_modules/rdf-canonize/index.js" +/*!********************************************!*\ + !*** ./node_modules/rdf-canonize/index.js ***! + \********************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +/** + * An implementation of the RDF Dataset Normalization specification. + * + * @author Dave Longley + * + * Copyright 2010-2021 Digital Bazaar, Inc. + */ +module.exports = __webpack_require__(/*! ./lib */ "./node_modules/rdf-canonize/lib/index.js"); + + +/***/ }, + +/***/ "./node_modules/rdf-canonize/lib/IdentifierIssuer.js" +/*!***********************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/IdentifierIssuer.js ***! + \***********************************************************/ +(module) { + +"use strict"; +/* + * Copyright (c) 2016-2021 Digital Bazaar, Inc. All rights reserved. + */ + + +module.exports = class IdentifierIssuer { + /** + * Creates a new IdentifierIssuer. A IdentifierIssuer issues unique + * identifiers, keeping track of any previously issued identifiers. + * + * @param {string} prefix - The prefix to use (''). + * @param {Map} [existing] - An existing Map to use. + * @param {number} [counter] - The counter to use. + */ + constructor(prefix, existing = new Map(), counter = 0) { + this.prefix = prefix; + this._existing = existing; + this.counter = counter; + } + + /** + * Copies this IdentifierIssuer. + * + * @returns {object} - A copy of this IdentifierIssuer. + */ + clone() { + const {prefix, _existing, counter} = this; + return new IdentifierIssuer(prefix, new Map(_existing), counter); + } + + /** + * Gets the new identifier for the given old identifier, where if no old + * identifier is given a new identifier will be generated. + * + * @param {string} [old] - The old identifier to get the new identifier for. + * + * @returns {string} - The new identifier. + */ + getId(old) { + // return existing old identifier + const existing = old && this._existing.get(old); + if(existing) { + return existing; + } + + // get next identifier + const identifier = this.prefix + this.counter; + this.counter++; + + // save mapping + if(old) { + this._existing.set(old, identifier); + } + + return identifier; + } + + /** + * Returns true if the given old identifer has already been assigned a new + * identifier. + * + * @param {string} old - The old identifier to check. + * + * @returns {boolean} - True if the old identifier has been assigned a new + * identifier, false if not. + */ + hasId(old) { + return this._existing.has(old); + } + + /** + * Returns all of the IDs that have been issued new IDs in the order in + * which they were issued new IDs. + * + * @returns {Array} - The list of old IDs that has been issued new IDs in + * order. + */ + getOldIds() { + return [...this._existing.keys()]; + } +}; + + +/***/ }, + +/***/ "./node_modules/rdf-canonize/lib/MessageDigest-webcrypto.js" +/*!******************************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/MessageDigest-webcrypto.js ***! + \******************************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2016-2023 Digital Bazaar, Inc. All rights reserved. + */ + + +const {bufferToHex, crypto} = __webpack_require__(/*! ./platform */ "./node_modules/rdf-canonize/lib/platform-browser.js"); + +const algorithmMap = new Map([ + ['sha256', 'SHA-256'], + ['SHA256', 'SHA-256'], + ['SHA-256', 'SHA-256'], + ['sha384', 'SHA-384'], + ['SHA384', 'SHA-384'], + ['SHA-384', 'SHA-384'], + ['sha512', 'SHA-512'], + ['SHA512', 'SHA-512'], + ['SHA-512', 'SHA-512'], +]); + +module.exports = class MessageDigest { + /** + * Creates a new WebCrypto API MessageDigest. + * + * @param {string} algorithm - The algorithm to use. + */ + constructor(algorithm) { + // check if crypto.subtle is available + // check is here rather than top-level to only fail if class is used + if(!(crypto && crypto.subtle)) { + throw new Error('crypto.subtle not found.'); + } + if(!algorithmMap.has(algorithm)) { + throw new Error(`Unsupported algorithm "${algorithm}".`); + } + this.algorithm = algorithmMap.get(algorithm); + this._content = ''; + } + + update(msg) { + this._content += msg; + } + + async digest() { + const data = new TextEncoder().encode(this._content); + const buffer = await crypto.subtle.digest(this.algorithm, data); + return bufferToHex(buffer); + } +}; + + +/***/ }, + +/***/ "./node_modules/rdf-canonize/lib/NQuads.js" +/*!*************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/NQuads.js ***! + \*************************************************/ +(module) { + +"use strict"; +/*! + * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. + */ + + +// eslint-disable-next-line no-unused-vars +const TERMS = ['subject', 'predicate', 'object', 'graph']; +const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; +const RDF_LANGSTRING = RDF + 'langString'; +const XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string'; + +const TYPE_NAMED_NODE = 'NamedNode'; +const TYPE_BLANK_NODE = 'BlankNode'; +const TYPE_LITERAL = 'Literal'; +const TYPE_DEFAULT_GRAPH = 'DefaultGraph'; + +// build regexes +const REGEX = {}; +(() => { + // https://www.w3.org/TR/n-quads/#sec-grammar + // https://www.w3.org/TR/turtle/#grammar-production-BLANK_NODE_LABEL + const PN_CHARS_BASE = + 'A-Z' + 'a-z' + + '\u00C0-\u00D6' + + '\u00D8-\u00F6' + + '\u00F8-\u02FF' + + '\u0370-\u037D' + + '\u037F-\u1FFF' + + '\u200C-\u200D' + + '\u2070-\u218F' + + '\u2C00-\u2FEF' + + '\u3001-\uD7FF' + + '\uF900-\uFDCF' + + '\uFDF0-\uFFFD'; + // TODO: + //'\u10000-\uEFFFF'; + const PN_CHARS_U = + PN_CHARS_BASE + + '_'; + const PN_CHARS = + PN_CHARS_U + + '0-9' + + '-' + + '\u00B7' + + '\u0300-\u036F' + + '\u203F-\u2040'; + const BLANK_NODE_LABEL = + '_:(' + + '(?:[' + PN_CHARS_U + '0-9])' + + '(?:(?:[' + PN_CHARS + '.])*(?:[' + PN_CHARS + ']))?' + + ')'; + // Older simple regex: const IRI = '(?:<([^:]+:[^>]*)>)'; + const UCHAR4 = '\\\\u[0-9A-Fa-f]{4}'; + const UCHAR8 = '\\\\U[0-9A-Fa-f]{8}'; + const IRI = '(?:<((?:' + + '[^\u0000-\u0020<>"{}|^`\\\\]' + '|' + + UCHAR4 + '|' + + UCHAR8 + + ')*)>)'; + const bnode = BLANK_NODE_LABEL; + const plain = '"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"'; + const datatype = '(?:\\^\\^' + IRI + ')'; + const language = '(?:@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*))'; + const literal = '(?:' + plain + '(?:' + datatype + '|' + language + ')?)'; + const ws = '[ \\t]+'; + const wso = '[ \\t]*'; + + // define quad part regexes + const subject = '(?:' + IRI + '|' + bnode + ')' + ws; + const property = IRI + ws; + const object = '(?:' + IRI + '|' + bnode + '|' + literal + ')' + wso; + const graphName = '(?:\\.|(?:(?:' + IRI + '|' + bnode + ')' + wso + '\\.))'; + + // end of line and empty regexes + REGEX.eoln = /(?:\r\n)|(?:\n)|(?:\r)/g; + REGEX.empty = new RegExp('^' + wso + '$'); + + // full quad regex + REGEX.quad = new RegExp( + '^' + wso + subject + property + object + graphName + wso + '$'); +})(); + +module.exports = class NQuads { + /** + * Parses RDF in the form of N-Quads. + * + * @param {string} input - The N-Quads input to parse. + * + * @returns {Array} - An RDF dataset (an array of quads per + * https://rdf.js.org/). + */ + static parse(input) { + // build RDF dataset + const dataset = []; + + const graphs = {}; + + // split N-Quad input into lines + const lines = input.split(REGEX.eoln); + let lineNumber = 0; + for(const line of lines) { + lineNumber++; + + // skip empty lines + if(REGEX.empty.test(line)) { + continue; + } + + // parse quad + const match = line.match(REGEX.quad); + if(match === null) { + throw new Error('N-Quads parse error on line ' + lineNumber + '.'); + } + + // create RDF quad + const quad = {subject: null, predicate: null, object: null, graph: null}; + + // get subject + if(match[1] !== undefined) { + quad.subject = { + termType: TYPE_NAMED_NODE, + value: _iriUnescape(match[1]) + }; + } else { + quad.subject = { + termType: TYPE_BLANK_NODE, + value: match[2] + }; + } + + // get predicate + quad.predicate = { + termType: TYPE_NAMED_NODE, + value: _iriUnescape(match[3]) + }; + + // get object + if(match[4] !== undefined) { + quad.object = { + termType: TYPE_NAMED_NODE, + value: _iriUnescape(match[4]) + }; + } else if(match[5] !== undefined) { + quad.object = { + termType: TYPE_BLANK_NODE, + value: match[5] + }; + } else { + quad.object = { + termType: TYPE_LITERAL, + value: undefined, + datatype: { + termType: TYPE_NAMED_NODE + } + }; + if(match[7] !== undefined) { + quad.object.datatype.value = _iriUnescape(match[7]); + } else if(match[8] !== undefined) { + quad.object.datatype.value = RDF_LANGSTRING; + quad.object.language = match[8]; + } else { + quad.object.datatype.value = XSD_STRING; + } + quad.object.value = _stringLiteralUnescape(match[6]); + } + + // get graph + if(match[9] !== undefined) { + quad.graph = { + termType: TYPE_NAMED_NODE, + value: _iriUnescape(match[9]) + }; + } else if(match[10] !== undefined) { + quad.graph = { + termType: TYPE_BLANK_NODE, + value: match[10] + }; + } else { + quad.graph = { + termType: TYPE_DEFAULT_GRAPH, + value: '' + }; + } + + // only add quad if it is unique in its graph + if(!(quad.graph.value in graphs)) { + graphs[quad.graph.value] = [quad]; + dataset.push(quad); + } else { + let unique = true; + const quads = graphs[quad.graph.value]; + for(const q of quads) { + if(_compareTriples(q, quad)) { + unique = false; + break; + } + } + if(unique) { + quads.push(quad); + dataset.push(quad); + } + } + } + + return dataset; + } + + /** + * Converts an RDF dataset to N-Quads. + * + * @param {Array} dataset - The Array of quads RDF dataset to convert. + * + * @returns {string} - The N-Quads string. + */ + static serialize(dataset) { + const quads = []; + for(const quad of dataset) { + quads.push(NQuads.serializeQuad(quad)); + } + return quads.sort().join(''); + } + + /** + * Converts RDF quad components to an N-Quad string (a single quad). + * + * @param {object} s - N-Quad subject component. + * @param {object} p - N-Quad predicate component. + * @param {object} o - N-Quad object component. + * @param {object} g - N-Quad graph component. + * + * @returns {string} - The N-Quad. + */ + static serializeQuadComponents(s, p, o, g) { + let nquad = ''; + + // subject can only be NamedNode or BlankNode + if(s.termType === TYPE_NAMED_NODE) { + nquad += `<${_iriEscape(s.value)}>`; + } else { + nquad += `_:${s.value}`; + } + + // predicate normally a NamedNode, can be a BlankNode in generalized RDF + if(p.termType === TYPE_NAMED_NODE) { + nquad += ` <${_iriEscape(p.value)}> `; + } else { + nquad += ` _:${p.value} `; + } + + // object is NamedNode, BlankNode, or Literal + if(o.termType === TYPE_NAMED_NODE) { + nquad += `<${_iriEscape(o.value)}>`; + } else if(o.termType === TYPE_BLANK_NODE) { + nquad += `_:${o.value}`; + } else { + nquad += `"${_stringLiteralEscape(o.value)}"`; + if(o.datatype.value === RDF_LANGSTRING) { + if(o.language) { + nquad += `@${o.language}`; + } + } else if(o.datatype.value !== XSD_STRING) { + nquad += `^^<${_iriEscape(o.datatype.value)}>`; + } + } + + // graph can only be NamedNode or BlankNode (or DefaultGraph, but that + // does not add to `nquad`) + if(g.termType === TYPE_NAMED_NODE) { + nquad += ` <${_iriEscape(g.value)}>`; + } else if(g.termType === TYPE_BLANK_NODE) { + nquad += ` _:${g.value}`; + } + + nquad += ' .\n'; + return nquad; + } + + /** + * Converts an RDF quad to an N-Quad string (a single quad). + * + * @param {object} quad - The RDF quad convert. + * + * @returns {string} - The N-Quad string. + */ + static serializeQuad(quad) { + return NQuads.serializeQuadComponents( + quad.subject, quad.predicate, quad.object, quad.graph); + } +}; + +/** + * Compares two RDF triples for equality. + * + * @param {object} t1 - The first triple. + * @param {object} t2 - The second triple. + * + * @returns {boolean} - True if the triples are the same, false if not. + */ +function _compareTriples(t1, t2) { + // compare subject and object types first as it is the quickest check + if(!(t1.subject.termType === t2.subject.termType && + t1.object.termType === t2.object.termType)) { + return false; + } + // compare values + if(!(t1.subject.value === t2.subject.value && + t1.predicate.value === t2.predicate.value && + t1.object.value === t2.object.value)) { + return false; + } + if(t1.object.termType !== TYPE_LITERAL) { + // no `datatype` or `language` to check + return true; + } + return ( + (t1.object.datatype.termType === t2.object.datatype.termType) && + (t1.object.language === t2.object.language) && + (t1.object.datatype.value === t2.object.datatype.value) + ); +} + +const _stringLiteralEscapeRegex = /[\u0000-\u001F\u007F"\\]/g; +const _stringLiteralEscapeMap = []; +for(let n = 0; n <= 0x7f; ++n) { + if(_stringLiteralEscapeRegex.test(String.fromCharCode(n))) { + // default UCHAR mapping + _stringLiteralEscapeMap[n] = + '\\u' + n.toString(16).toUpperCase().padStart(4, '0'); + // reset regex + _stringLiteralEscapeRegex.lastIndex = 0; + } +} +// special ECHAR mappings +_stringLiteralEscapeMap['\b'.codePointAt(0)] = '\\b'; +_stringLiteralEscapeMap['\t'.codePointAt(0)] = '\\t'; +_stringLiteralEscapeMap['\n'.codePointAt(0)] = '\\n'; +_stringLiteralEscapeMap['\f'.codePointAt(0)] = '\\f'; +_stringLiteralEscapeMap['\r'.codePointAt(0)] = '\\r'; +_stringLiteralEscapeMap['"' .codePointAt(0)] = '\\"'; +_stringLiteralEscapeMap['\\'.codePointAt(0)] = '\\\\'; + +/** + * Escape string to N-Quads literal. + * + * @param {string} s - String to escape. + * + * @returns {string} - Escaped N-Quads literal. + */ +function _stringLiteralEscape(s) { + if(!_stringLiteralEscapeRegex.test(s)) { + return s; + } + return s.replace(_stringLiteralEscapeRegex, function(match) { + return _stringLiteralEscapeMap[match.codePointAt(0)]; + }); +} + +const _stringLiteralUnescapeRegex = + /(?:\\([btnfr"'\\]))|(?:\\u([0-9A-Fa-f]{4}))|(?:\\U([0-9A-Fa-f]{8}))/g; + +/** + * Unescape N-Quads literal to string. + * + * @param {string} s - String to unescape. + * + * @returns {string} - Unescaped N-Quads literal. + */ +function _stringLiteralUnescape(s) { + if(!_stringLiteralUnescapeRegex.test(s)) { + return s; + } + return s.replace(_stringLiteralUnescapeRegex, function(match, code, u, U) { + if(code) { + switch(code) { + case 'b': return '\b'; + case 't': return '\t'; + case 'n': return '\n'; + case 'f': return '\f'; + case 'r': return '\r'; + case '"': return '"'; + case '\'': return '\''; + case '\\': return '\\'; + } + } + if(u) { + return String.fromCharCode(parseInt(u, 16)); + } + if(U) { + return String.fromCodePoint(parseInt(U, 16)); + } + }); +} + +const _iriEscapeRegex = /[\u0000-\u0020<>"{}|^`\\]/g; +const _iriEscapeRegexMap = []; +for(let n = 0; n <= 0x7f; ++n) { + if(_iriEscapeRegex.test(String.fromCharCode(n))) { + // UCHAR mapping + _iriEscapeRegexMap[n] = + '\\u' + n.toString(16).toUpperCase().padStart(4, '0'); + // reset regex + _iriEscapeRegex.lastIndex = 0; + } +} + +/** + * Escape IRI to N-Quads IRI. + * + * @param {string} s - IRI to escape. + * + * @returns {string} - Escaped N-Quads IRI. + */ +function _iriEscape(s) { + if(!_iriEscapeRegex.test(s)) { + return s; + } + return s.replace(_iriEscapeRegex, function(match) { + return _iriEscapeRegexMap[match.codePointAt(0)]; + }); +} + +const _iriUnescapeRegex = + /(?:\\u([0-9A-Fa-f]{4}))|(?:\\U([0-9A-Fa-f]{8}))/g; + +/** + * Unescape N-Quads IRI to IRI. + * + * @param {string} s - IRI to unescape. + * + * @returns {string} - Unescaped N-Quads IRI. + */ +function _iriUnescape(s) { + if(!_iriUnescapeRegex.test(s)) { + return s; + } + return s.replace(_iriUnescapeRegex, function(match, u, U) { + if(u) { + return String.fromCharCode(parseInt(u, 16)); + } + if(U) { + return String.fromCodePoint(parseInt(U, 16)); + } + }); +} + + +/***/ }, + +/***/ "./node_modules/rdf-canonize/lib/Permuter.js" +/*!***************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/Permuter.js ***! + \***************************************************/ +(module) { + +"use strict"; +/*! + * Copyright (c) 2016-2022 Digital Bazaar, Inc. All rights reserved. + */ + + +module.exports = class Permuter { + /** + * A Permuter iterates over all possible permutations of the given array + * of elements. + * + * @param {Array} list - The array of elements to iterate over. + */ + constructor(list) { + // original array + this.current = list.sort(); + // indicates whether there are more permutations + this.done = false; + // directional info for permutation algorithm + this.dir = new Map(); + for(let i = 0; i < list.length; ++i) { + this.dir.set(list[i], true); + } + } + + /** + * Returns true if there is another permutation. + * + * @returns {boolean} - True if there is another permutation, false if not. + */ + hasNext() { + return !this.done; + } + + /** + * Gets the next permutation. Call hasNext() to ensure there is another one + * first. + * + * @returns {any} - The next permutation. + */ + next() { + // copy current permutation to return it + const {current, dir} = this; + const rval = current.slice(); + + /* Calculate the next permutation using the Steinhaus-Johnson-Trotter + permutation algorithm. */ + + // get largest mobile element k + // (mobile: element is greater than the one it is looking at) + let k = null; + let pos = 0; + const length = current.length; + for(let i = 0; i < length; ++i) { + const element = current[i]; + const left = dir.get(element); + if((k === null || element > k) && + ((left && i > 0 && element > current[i - 1]) || + (!left && i < (length - 1) && element > current[i + 1]))) { + k = element; + pos = i; + } + } + + // no more permutations + if(k === null) { + this.done = true; + } else { + // swap k and the element it is looking at + const swap = dir.get(k) ? pos - 1 : pos + 1; + current[pos] = current[swap]; + current[swap] = k; + + // reverse the direction of all elements larger than k + for(const element of current) { + if(element > k) { + dir.set(element, !dir.get(element)); + } + } + } + + return rval; + } +}; + + +/***/ }, + +/***/ "./node_modules/rdf-canonize/lib/RDFC10.js" +/*!*************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/RDFC10.js ***! + \*************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2016-2023 Digital Bazaar, Inc. All rights reserved. + */ + + +const IdentifierIssuer = __webpack_require__(/*! ./IdentifierIssuer */ "./node_modules/rdf-canonize/lib/IdentifierIssuer.js"); +const MessageDigest = __webpack_require__(/*! ./MessageDigest */ "./node_modules/rdf-canonize/lib/MessageDigest-webcrypto.js"); +const Permuter = __webpack_require__(/*! ./Permuter */ "./node_modules/rdf-canonize/lib/Permuter.js"); +const NQuads = __webpack_require__(/*! ./NQuads */ "./node_modules/rdf-canonize/lib/NQuads.js"); +const {setImmediate} = __webpack_require__(/*! ./platform */ "./node_modules/rdf-canonize/lib/platform-browser.js"); + +module.exports = class RDFC10 { + constructor({ + createMessageDigest = null, + messageDigestAlgorithm = 'sha256', + canonicalIdMap = new Map(), + maxWorkFactor = 1, + maxDeepIterations = -1, + signal = null + } = {}) { + this.name = 'RDFC-1.0'; + this.blankNodeInfo = new Map(); + this.canonicalIssuer = new IdentifierIssuer('c14n', canonicalIdMap); + this.createMessageDigest = createMessageDigest || + (() => new MessageDigest(messageDigestAlgorithm)); + this.maxWorkFactor = maxWorkFactor; + this.maxDeepIterations = maxDeepIterations; + this.remainingDeepIterations = 0; + this.signal = signal; + this.quads = null; + } + + // 4.4) Normalization Algorithm + async main(dataset) { + this.quads = dataset; + + // 1) Create the normalization state. + // 2) For every quad in input dataset: + for(const quad of dataset) { + // 2.1) For each blank node that occurs in the quad, add a reference + // to the quad using the blank node identifier in the blank node to + // quads map, creating a new entry if necessary. + this._addBlankNodeQuadInfo({quad, component: quad.subject}); + this._addBlankNodeQuadInfo({quad, component: quad.object}); + this._addBlankNodeQuadInfo({quad, component: quad.graph}); + } + + // 3) Create a list of non-normalized blank node identifiers + // non-normalized identifiers and populate it using the keys from the + // blank node to quads map. + // Note: We use a map here and it was generated during step 2. + + // 4) `simple` flag is skipped -- loop is optimized away. This optimization + // is permitted because there was a typo in the hash first degree quads + // algorithm in the RDFC-1.0 spec that was implemented widely making it + // such that it could not be fixed; the result was that the loop only + // needs to be run once and the first degree quad hashes will never change. + // 5.1-5.2 are skipped; first degree quad hashes are generated just once + // for all non-normalized blank nodes. + + // 5.3) For each blank node identifier identifier in non-normalized + // identifiers: + const hashToBlankNodes = new Map(); + const nonNormalized = [...this.blankNodeInfo.keys()]; + let i = 0; + for(const id of nonNormalized) { + // Note: batch hashing first degree quads 100 at a time + if(++i % 100 === 0) { + await this._yield(); + } + // steps 5.3.1 and 5.3.2: + await this._hashAndTrackBlankNode({id, hashToBlankNodes}); + } + + // 5.4) For each hash to identifier list mapping in hash to blank + // nodes map, lexicographically-sorted by hash: + const hashes = [...hashToBlankNodes.keys()].sort(); + // optimize away second sort, gather non-unique hashes in order as we go + const nonUnique = []; + for(const hash of hashes) { + // 5.4.1) If the length of identifier list is greater than 1, + // continue to the next mapping. + const idList = hashToBlankNodes.get(hash); + if(idList.length > 1) { + nonUnique.push(idList); + continue; + } + + // 5.4.2) Use the Issue Identifier algorithm, passing canonical + // issuer and the single blank node identifier in identifier + // list, identifier, to issue a canonical replacement identifier + // for identifier. + const id = idList[0]; + this.canonicalIssuer.getId(id); + + // Note: These steps are skipped, optimized away since the loop + // only needs to be run once. + // 5.4.3) Remove identifier from non-normalized identifiers. + // 5.4.4) Remove hash from the hash to blank nodes map. + // 5.4.5) Set simple to true. + } + + if(this.maxDeepIterations < 0) { + // calculate maxDeepIterations if not explicit + if(this.maxWorkFactor === 0) { + this.maxDeepIterations = 0; + } else if(this.maxWorkFactor === Infinity) { + this.maxDeepIterations = Infinity; + } else { + const nonUniqueCount = + nonUnique.reduce((count, v) => count + v.length, 0); + this.maxDeepIterations = nonUniqueCount ** this.maxWorkFactor; + } + } + // handle any large inputs as Infinity + if(this.maxDeepIterations > Number.MAX_SAFE_INTEGER) { + this.maxDeepIterations = Infinity; + } + this.remainingDeepIterations = this.maxDeepIterations; + + // 6) For each hash to identifier list mapping in hash to blank nodes map, + // lexicographically-sorted by hash: + // Note: sort optimized away, use `nonUnique`. + for(const idList of nonUnique) { + // 6.1) Create hash path list where each item will be a result of + // running the Hash N-Degree Quads algorithm. + const hashPathList = []; + + // 6.2) For each blank node identifier identifier in identifier list: + for(const id of idList) { + // 6.2.1) If a canonical identifier has already been issued for + // identifier, continue to the next identifier. + if(this.canonicalIssuer.hasId(id)) { + continue; + } + + // 6.2.2) Create temporary issuer, an identifier issuer + // initialized with the prefix _:b. + const issuer = new IdentifierIssuer('b'); + + // 6.2.3) Use the Issue Identifier algorithm, passing temporary + // issuer and identifier, to issue a new temporary blank node + // identifier for identifier. + issuer.getId(id); + + // 6.2.4) Run the Hash N-Degree Quads algorithm, passing + // temporary issuer, and append the result to the hash path list. + const result = await this.hashNDegreeQuads(id, issuer); + hashPathList.push(result); + } + + // 6.3) For each result in the hash path list, + // lexicographically-sorted by the hash in result: + hashPathList.sort(_stringHashCompare); + for(const result of hashPathList) { + // 6.3.1) For each blank node identifier, existing identifier, + // that was issued a temporary identifier by identifier issuer + // in result, issue a canonical identifier, in the same order, + // using the Issue Identifier algorithm, passing canonical + // issuer and existing identifier. + const oldIds = result.issuer.getOldIds(); + for(const id of oldIds) { + this.canonicalIssuer.getId(id); + } + } + } + + /* Note: At this point all blank nodes in the set of RDF quads have been + assigned canonical identifiers, which have been stored in the canonical + issuer. Here each quad is updated by assigning each of its blank nodes + its new identifier. */ + + // 7) For each quad, quad, in input dataset: + const normalized = []; + for(const quad of this.quads) { + // 7.1) Create a copy, quad copy, of quad and replace any existing + // blank node identifiers using the canonical identifiers + // previously issued by canonical issuer. + // Note: We optimize away the copy here. + const nQuad = NQuads.serializeQuadComponents( + this._componentWithCanonicalId(quad.subject), + quad.predicate, + this._componentWithCanonicalId(quad.object), + this._componentWithCanonicalId(quad.graph) + ); + // 7.2) Add quad copy to the normalized dataset. + normalized.push(nQuad); + } + + // sort normalized output + normalized.sort(); + + // 8) Return the normalized dataset. + return normalized.join(''); + } + + // 4.6) Hash First Degree Quads + async hashFirstDegreeQuads(id) { + // 1) Initialize nquads to an empty list. It will be used to store quads in + // N-Quads format. + const nquads = []; + + // 2) Get the list of quads `quads` associated with the reference blank node + // identifier in the blank node to quads map. + const info = this.blankNodeInfo.get(id); + const quads = info.quads; + + // 3) For each quad `quad` in `quads`: + for(const quad of quads) { + // 3.1) Serialize the quad in N-Quads format with the following special + // rule: + + // 3.1.1) If any component in quad is an blank node, then serialize it + // using a special identifier as follows: + // 3.1.2) If the blank node's existing blank node identifier matches + // the reference blank node identifier then use the blank node + // identifier _:a, otherwise, use the blank node identifier _:z. + nquads.push(NQuads.serializeQuadComponents( + this.modifyFirstDegreeComponent(id, quad.subject, 'subject'), + quad.predicate, + this.modifyFirstDegreeComponent(id, quad.object, 'object'), + this.modifyFirstDegreeComponent(id, quad.graph, 'graph') + )); + } + + // 4) Sort nquads in lexicographical order. + nquads.sort(); + + // 5) Return the hash that results from passing the sorted, joined nquads + // through the hash algorithm. + const md = this.createMessageDigest(); + for(const nquad of nquads) { + md.update(nquad); + } + info.hash = await md.digest(); + return info.hash; + } + + // 4.7) Hash Related Blank Node + async hashRelatedBlankNode(related, quad, issuer, position) { + // 1) Initialize a string input to the value of position. + // Note: We use a hash object instead. + const md = this.createMessageDigest(); + md.update(position); + + // 2) If position is not g, append <, the value of the predicate in quad, + // and > to input. + if(position !== 'g') { + md.update(this.getRelatedPredicate(quad)); + } + + // 3) Set the identifier to use for related, preferring first the canonical + // identifier for related if issued, second the identifier issued by issuer + // if issued, and last, if necessary, the result of the Hash First Degree + // Quads algorithm, passing related. + let id; + if(this.canonicalIssuer.hasId(related)) { + id = '_:' + this.canonicalIssuer.getId(related); + } else if(issuer.hasId(related)) { + id = '_:' + issuer.getId(related); + } else { + id = this.blankNodeInfo.get(related).hash; + } + + // 4) Append identifier to input. + md.update(id); + + // 5) Return the hash that results from passing input through the hash + // algorithm. + return md.digest(); + } + + // 4.8) Hash N-Degree Quads + async hashNDegreeQuads(id, issuer) { + if(this.remainingDeepIterations === 0) { + throw new Error( + `Maximum deep iterations exceeded (${this.maxDeepIterations}).`); + } + this.remainingDeepIterations--; + + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + // Note: 2) and 3) handled within `createHashToRelated` + const md = this.createMessageDigest(); + const hashToRelated = await this.createHashToRelated(id, issuer); + + // 4) Create an empty string, data to hash. + // Note: We created a hash object `md` above instead. + + // 5) For each related hash to blank node list mapping in hash to related + // blank nodes map, sorted lexicographically by related hash: + const hashes = [...hashToRelated.keys()].sort(); + for(const hash of hashes) { + // 5.1) Append the related hash to the data to hash. + md.update(hash); + + // 5.2) Create a string chosen path. + let chosenPath = ''; + + // 5.3) Create an unset chosen issuer variable. + let chosenIssuer; + + // 5.4) For each permutation of blank node list: + const permuter = new Permuter(hashToRelated.get(hash)); + let i = 0; + while(permuter.hasNext()) { + const permutation = permuter.next(); + // Note: batch permutations 3 at a time + if(++i % 3 === 0) { + if(this.signal && this.signal.aborted) { + throw new Error(`Abort signal received: "${this.signal.reason}".`); + } + await this._yield(); + } + + // 5.4.1) Create a copy of issuer, issuer copy. + let issuerCopy = issuer.clone(); + + // 5.4.2) Create a string path. + let path = ''; + + // 5.4.3) Create a recursion list, to store blank node identifiers + // that must be recursively processed by this algorithm. + const recursionList = []; + + // 5.4.4) For each related in permutation: + let nextPermutation = false; + for(const related of permutation) { + // 5.4.4.1) If a canonical identifier has been issued for + // related, append it to path. + if(this.canonicalIssuer.hasId(related)) { + path += '_:' + this.canonicalIssuer.getId(related); + } else { + // 5.4.4.2) Otherwise: + // 5.4.4.2.1) If issuer copy has not issued an identifier for + // related, append related to recursion list. + if(!issuerCopy.hasId(related)) { + recursionList.push(related); + } + // 5.4.4.2.2) Use the Issue Identifier algorithm, passing + // issuer copy and related and append the result to path. + path += '_:' + issuerCopy.getId(related); + } + + // 5.4.4.3) If chosen path is not empty and the length of path + // is greater than or equal to the length of chosen path and + // path is lexicographically greater than chosen path, then + // skip to the next permutation. + // Note: Comparing path length to chosen path length can be optimized + // away; only compare lexicographically. + if(chosenPath.length !== 0 && path > chosenPath) { + nextPermutation = true; + break; + } + } + + if(nextPermutation) { + continue; + } + + // 5.4.5) For each related in recursion list: + for(const related of recursionList) { + // 5.4.5.1) Set result to the result of recursively executing + // the Hash N-Degree Quads algorithm, passing related for + // identifier and issuer copy for path identifier issuer. + const result = await this.hashNDegreeQuads(related, issuerCopy); + + // 5.4.5.2) Use the Issue Identifier algorithm, passing issuer + // copy and related and append the result to path. + path += '_:' + issuerCopy.getId(related); + + // 5.4.5.3) Append <, the hash in result, and > to path. + path += `<${result.hash}>`; + + // 5.4.5.4) Set issuer copy to the identifier issuer in + // result. + issuerCopy = result.issuer; + + // 5.4.5.5) If chosen path is not empty and the length of path + // is greater than or equal to the length of chosen path and + // path is lexicographically greater than chosen path, then + // skip to the next permutation. + // Note: Comparing path length to chosen path length can be optimized + // away; only compare lexicographically. + if(chosenPath.length !== 0 && path > chosenPath) { + nextPermutation = true; + break; + } + } + + if(nextPermutation) { + continue; + } + + // 5.4.6) If chosen path is empty or path is lexicographically + // less than chosen path, set chosen path to path and chosen + // issuer to issuer copy. + if(chosenPath.length === 0 || path < chosenPath) { + chosenPath = path; + chosenIssuer = issuerCopy; + } + } + + // 5.5) Append chosen path to data to hash. + md.update(chosenPath); + + // 5.6) Replace issuer, by reference, with chosen issuer. + issuer = chosenIssuer; + } + + // 6) Return issuer and the hash that results from passing data to hash + // through the hash algorithm. + return {hash: await md.digest(), issuer}; + } + + // helper for modifying component during Hash First Degree Quads + modifyFirstDegreeComponent(id, component) { + if(component.termType !== 'BlankNode') { + return component; + } + /* Note: A mistake in the RDFC-1.0 spec that made its way into + implementations (and therefore must stay to avoid interop breakage) + resulted in an assigned canonical ID, if available for + `component.value`, not being used in place of `_:a`/`_:z`, so + we don't use it here. */ + return { + termType: 'BlankNode', + value: component.value === id ? 'a' : 'z' + }; + } + + // helper for getting a related predicate + getRelatedPredicate(quad) { + return `<${quad.predicate.value}>`; + } + + // helper for creating hash to related blank nodes map + async createHashToRelated(id, issuer) { + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + const hashToRelated = new Map(); + + // 2) Get a reference, quads, to the list of quads in the blank node to + // quads map for the key identifier. + const quads = this.blankNodeInfo.get(id).quads; + + // 3) For each quad in quads: + let i = 0; + for(const quad of quads) { + // Note: batch hashing related blank node quads 100 at a time + if(++i % 100 === 0) { + await this._yield(); + } + // 3.1) For each component in quad, if component is the subject, object, + // or graph name and it is a blank node that is not identified by + // identifier: + // steps 3.1.1 and 3.1.2 occur in helpers: + await Promise.all([ + this._addRelatedBlankNodeHash({ + quad, component: quad.subject, position: 's', + id, issuer, hashToRelated + }), + this._addRelatedBlankNodeHash({ + quad, component: quad.object, position: 'o', + id, issuer, hashToRelated + }), + this._addRelatedBlankNodeHash({ + quad, component: quad.graph, position: 'g', + id, issuer, hashToRelated + }) + ]); + } + + return hashToRelated; + } + + async _hashAndTrackBlankNode({id, hashToBlankNodes}) { + // 5.3.1) Create a hash, hash, according to the Hash First Degree + // Quads algorithm. + const hash = await this.hashFirstDegreeQuads(id); + + // 5.3.2) Add hash and identifier to hash to blank nodes map, + // creating a new entry if necessary. + const idList = hashToBlankNodes.get(hash); + if(!idList) { + hashToBlankNodes.set(hash, [id]); + } else { + idList.push(id); + } + } + + _addBlankNodeQuadInfo({quad, component}) { + if(component.termType !== 'BlankNode') { + return; + } + const id = component.value; + const info = this.blankNodeInfo.get(id); + if(info) { + info.quads.add(quad); + } else { + this.blankNodeInfo.set(id, {quads: new Set([quad]), hash: null}); + } + } + + async _addRelatedBlankNodeHash( + {quad, component, position, id, issuer, hashToRelated}) { + if(!(component.termType === 'BlankNode' && component.value !== id)) { + return; + } + // 3.1.1) Set hash to the result of the Hash Related Blank Node + // algorithm, passing the blank node identifier for component as + // related, quad, path identifier issuer as issuer, and position as + // either s, o, or g based on whether component is a subject, object, + // graph name, respectively. + const related = component.value; + const hash = await this.hashRelatedBlankNode( + related, quad, issuer, position); + + // 3.1.2) Add a mapping of hash to the blank node identifier for + // component to hash to related blank nodes map, adding an entry as + // necessary. + const entries = hashToRelated.get(hash); + if(entries) { + entries.push(related); + } else { + hashToRelated.set(hash, [related]); + } + } + + // canonical ids for 7.1 + _componentWithCanonicalId(component) { + if(component.termType === 'BlankNode' && + !component.value.startsWith(this.canonicalIssuer.prefix)) { + // create new BlankNode + return { + termType: 'BlankNode', + value: this.canonicalIssuer.getId(component.value) + }; + } + return component; + } + + async _yield() { + return new Promise(resolve => setImmediate(resolve)); + } +}; + +function _stringHashCompare(a, b) { + return a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0; +} + + +/***/ }, + +/***/ "./node_modules/rdf-canonize/lib/RDFC10Sync.js" +/*!*****************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/RDFC10Sync.js ***! + \*****************************************************/ +(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2016-2023 Digital Bazaar, Inc. All rights reserved. + */ + + +const IdentifierIssuer = __webpack_require__(/*! ./IdentifierIssuer */ "./node_modules/rdf-canonize/lib/IdentifierIssuer.js"); +// FIXME: do not import; convert to requiring a +// hash factory +const MessageDigest = __webpack_require__(/*! ./MessageDigest */ "./node_modules/rdf-canonize/lib/MessageDigest-webcrypto.js"); +const Permuter = __webpack_require__(/*! ./Permuter */ "./node_modules/rdf-canonize/lib/Permuter.js"); +const NQuads = __webpack_require__(/*! ./NQuads */ "./node_modules/rdf-canonize/lib/NQuads.js"); + +module.exports = class RDFC10Sync { + constructor({ + createMessageDigest = null, + messageDigestAlgorithm = 'sha256', + canonicalIdMap = new Map(), + maxWorkFactor = 1, + maxDeepIterations = -1, + timeout = 0 + } = {}) { + this.name = 'RDFC-1.0'; + this.blankNodeInfo = new Map(); + this.canonicalIssuer = new IdentifierIssuer('c14n', canonicalIdMap); + this.createMessageDigest = createMessageDigest || + (() => new MessageDigest(messageDigestAlgorithm)); + this.maxWorkFactor = maxWorkFactor; + this.maxDeepIterations = maxDeepIterations; + this.remainingDeepIterations = 0; + this.timeout = timeout; + if(timeout > 0) { + this.startTime = Date.now(); + } + this.quads = null; + } + + // 4.4) Normalization Algorithm + main(dataset) { + this.quads = dataset; + + // 1) Create the normalization state. + // 2) For every quad in input dataset: + for(const quad of dataset) { + // 2.1) For each blank node that occurs in the quad, add a reference + // to the quad using the blank node identifier in the blank node to + // quads map, creating a new entry if necessary. + this._addBlankNodeQuadInfo({quad, component: quad.subject}); + this._addBlankNodeQuadInfo({quad, component: quad.object}); + this._addBlankNodeQuadInfo({quad, component: quad.graph}); + } + + // 3) Create a list of non-normalized blank node identifiers + // non-normalized identifiers and populate it using the keys from the + // blank node to quads map. + // Note: We use a map here and it was generated during step 2. + + // 4) `simple` flag is skipped -- loop is optimized away. This optimization + // is permitted because there was a typo in the hash first degree quads + // algorithm in the RDFC-1.0 spec that was implemented widely making it + // such that it could not be fixed; the result was that the loop only + // needs to be run once and the first degree quad hashes will never change. + // 5.1-5.2 are skipped; first degree quad hashes are generated just once + // for all non-normalized blank nodes. + + // 5.3) For each blank node identifier identifier in non-normalized + // identifiers: + const hashToBlankNodes = new Map(); + const nonNormalized = [...this.blankNodeInfo.keys()]; + for(const id of nonNormalized) { + // steps 5.3.1 and 5.3.2: + this._hashAndTrackBlankNode({id, hashToBlankNodes}); + } + + // 5.4) For each hash to identifier list mapping in hash to blank + // nodes map, lexicographically-sorted by hash: + const hashes = [...hashToBlankNodes.keys()].sort(); + // optimize away second sort, gather non-unique hashes in order as we go + const nonUnique = []; + for(const hash of hashes) { + // 5.4.1) If the length of identifier list is greater than 1, + // continue to the next mapping. + const idList = hashToBlankNodes.get(hash); + if(idList.length > 1) { + nonUnique.push(idList); + continue; + } + + // 5.4.2) Use the Issue Identifier algorithm, passing canonical + // issuer and the single blank node identifier in identifier + // list, identifier, to issue a canonical replacement identifier + // for identifier. + const id = idList[0]; + this.canonicalIssuer.getId(id); + + // Note: These steps are skipped, optimized away since the loop + // only needs to be run once. + // 5.4.3) Remove identifier from non-normalized identifiers. + // 5.4.4) Remove hash from the hash to blank nodes map. + // 5.4.5) Set simple to true. + } + + if(this.maxDeepIterations < 0) { + // calculate maxDeepIterations if not explicit + if(this.maxWorkFactor === 0) { + this.maxDeepIterations = 0; + } else if(this.maxWorkFactor === Infinity) { + this.maxDeepIterations = Infinity; + } else { + const nonUniqueCount = + nonUnique.reduce((count, v) => count + v.length, 0); + this.maxDeepIterations = nonUniqueCount ** this.maxWorkFactor; + } + } + // handle any large inputs as Infinity + if(this.maxDeepIterations > Number.MAX_SAFE_INTEGER) { + this.maxDeepIterations = Infinity; + } + this.remainingDeepIterations = this.maxDeepIterations; + + // 6) For each hash to identifier list mapping in hash to blank nodes map, + // lexicographically-sorted by hash: + // Note: sort optimized away, use `nonUnique`. + for(const idList of nonUnique) { + // 6.1) Create hash path list where each item will be a result of + // running the Hash N-Degree Quads algorithm. + const hashPathList = []; + + // 6.2) For each blank node identifier identifier in identifier list: + for(const id of idList) { + // 6.2.1) If a canonical identifier has already been issued for + // identifier, continue to the next identifier. + if(this.canonicalIssuer.hasId(id)) { + continue; + } + + // 6.2.2) Create temporary issuer, an identifier issuer + // initialized with the prefix _:b. + const issuer = new IdentifierIssuer('b'); + + // 6.2.3) Use the Issue Identifier algorithm, passing temporary + // issuer and identifier, to issue a new temporary blank node + // identifier for identifier. + issuer.getId(id); + + // 6.2.4) Run the Hash N-Degree Quads algorithm, passing + // temporary issuer, and append the result to the hash path list. + const result = this.hashNDegreeQuads(id, issuer); + hashPathList.push(result); + } + + // 6.3) For each result in the hash path list, + // lexicographically-sorted by the hash in result: + hashPathList.sort(_stringHashCompare); + for(const result of hashPathList) { + // 6.3.1) For each blank node identifier, existing identifier, + // that was issued a temporary identifier by identifier issuer + // in result, issue a canonical identifier, in the same order, + // using the Issue Identifier algorithm, passing canonical + // issuer and existing identifier. + const oldIds = result.issuer.getOldIds(); + for(const id of oldIds) { + this.canonicalIssuer.getId(id); + } + } + } + + /* Note: At this point all blank nodes in the set of RDF quads have been + assigned canonical identifiers, which have been stored in the canonical + issuer. Here each quad is updated by assigning each of its blank nodes + its new identifier. */ + + // 7) For each quad, quad, in input dataset: + const normalized = []; + for(const quad of this.quads) { + // 7.1) Create a copy, quad copy, of quad and replace any existing + // blank node identifiers using the canonical identifiers + // previously issued by canonical issuer. + // Note: We optimize away the copy here. + const nQuad = NQuads.serializeQuadComponents( + this._componentWithCanonicalId(quad.subject), + quad.predicate, + this._componentWithCanonicalId(quad.object), + this._componentWithCanonicalId(quad.graph) + ); + // 7.2) Add quad copy to the normalized dataset. + normalized.push(nQuad); + } + + // sort normalized output + normalized.sort(); + + // 8) Return the normalized dataset. + return normalized.join(''); + } + + // 4.6) Hash First Degree Quads + hashFirstDegreeQuads(id) { + // 1) Initialize nquads to an empty list. It will be used to store quads in + // N-Quads format. + const nquads = []; + + // 2) Get the list of quads `quads` associated with the reference blank node + // identifier in the blank node to quads map. + const info = this.blankNodeInfo.get(id); + const quads = info.quads; + + // 3) For each quad `quad` in `quads`: + for(const quad of quads) { + // 3.1) Serialize the quad in N-Quads format with the following special + // rule: + + // 3.1.1) If any component in quad is an blank node, then serialize it + // using a special identifier as follows: + // 3.1.2) If the blank node's existing blank node identifier matches + // the reference blank node identifier then use the blank node + // identifier _:a, otherwise, use the blank node identifier _:z. + nquads.push(NQuads.serializeQuadComponents( + this.modifyFirstDegreeComponent(id, quad.subject, 'subject'), + quad.predicate, + this.modifyFirstDegreeComponent(id, quad.object, 'object'), + this.modifyFirstDegreeComponent(id, quad.graph, 'graph') + )); + } + + // 4) Sort nquads in lexicographical order. + nquads.sort(); + + // 5) Return the hash that results from passing the sorted, joined nquads + // through the hash algorithm. + const md = this.createMessageDigest(); + for(const nquad of nquads) { + md.update(nquad); + } + info.hash = md.digest(); + return info.hash; + } + + // 4.7) Hash Related Blank Node + hashRelatedBlankNode(related, quad, issuer, position) { + // 1) Initialize a string input to the value of position. + // Note: We use a hash object instead. + const md = this.createMessageDigest(); + md.update(position); + + // 2) If position is not g, append <, the value of the predicate in quad, + // and > to input. + if(position !== 'g') { + md.update(this.getRelatedPredicate(quad)); + } + + // 3) Set the identifier to use for related, preferring first the canonical + // identifier for related if issued, second the identifier issued by issuer + // if issued, and last, if necessary, the result of the Hash First Degree + // Quads algorithm, passing related. + let id; + if(this.canonicalIssuer.hasId(related)) { + id = '_:' + this.canonicalIssuer.getId(related); + } else if(issuer.hasId(related)) { + id = '_:' + issuer.getId(related); + } else { + id = this.blankNodeInfo.get(related).hash; + } + + // 4) Append identifier to input. + md.update(id); + + // 5) Return the hash that results from passing input through the hash + // algorithm. + return md.digest(); + } + + // 4.8) Hash N-Degree Quads + hashNDegreeQuads(id, issuer) { + if(this.remainingDeepIterations === 0) { + throw new Error( + `Maximum deep iterations exceeded (${this.maxDeepIterations}).`); + } + this.remainingDeepIterations--; + + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + // Note: 2) and 3) handled within `createHashToRelated` + const md = this.createMessageDigest(); + const hashToRelated = this.createHashToRelated(id, issuer); + + // 4) Create an empty string, data to hash. + // Note: We created a hash object `md` above instead. + + // 5) For each related hash to blank node list mapping in hash to related + // blank nodes map, sorted lexicographically by related hash: + const hashes = [...hashToRelated.keys()].sort(); + for(const hash of hashes) { + // 5.1) Append the related hash to the data to hash. + md.update(hash); + + // 5.2) Create a string chosen path. + let chosenPath = ''; + + // 5.3) Create an unset chosen issuer variable. + let chosenIssuer; + + // 5.4) For each permutation of blank node list: + const permuter = new Permuter(hashToRelated.get(hash)); + let i = 0; + while(permuter.hasNext()) { + const permutation = permuter.next(); + // Note: batch permutations 3 at a time + if(++i % 3 === 0) { + if(this.timeout > 0 && Date.now() - this.startTime > this.timeout) { + throw new Error('Canonize timeout.'); + } + } + + // 5.4.1) Create a copy of issuer, issuer copy. + let issuerCopy = issuer.clone(); + + // 5.4.2) Create a string path. + let path = ''; + + // 5.4.3) Create a recursion list, to store blank node identifiers + // that must be recursively processed by this algorithm. + const recursionList = []; + + // 5.4.4) For each related in permutation: + let nextPermutation = false; + for(const related of permutation) { + // 5.4.4.1) If a canonical identifier has been issued for + // related, append it to path. + if(this.canonicalIssuer.hasId(related)) { + path += '_:' + this.canonicalIssuer.getId(related); + } else { + // 5.4.4.2) Otherwise: + // 5.4.4.2.1) If issuer copy has not issued an identifier for + // related, append related to recursion list. + if(!issuerCopy.hasId(related)) { + recursionList.push(related); + } + // 5.4.4.2.2) Use the Issue Identifier algorithm, passing + // issuer copy and related and append the result to path. + path += '_:' + issuerCopy.getId(related); + } + + // 5.4.4.3) If chosen path is not empty and the length of path + // is greater than or equal to the length of chosen path and + // path is lexicographically greater than chosen path, then + // skip to the next permutation. + // Note: Comparing path length to chosen path length can be optimized + // away; only compare lexicographically. + if(chosenPath.length !== 0 && path > chosenPath) { + nextPermutation = true; + break; + } + } + + if(nextPermutation) { + continue; + } + + // 5.4.5) For each related in recursion list: + for(const related of recursionList) { + // 5.4.5.1) Set result to the result of recursively executing + // the Hash N-Degree Quads algorithm, passing related for + // identifier and issuer copy for path identifier issuer. + const result = this.hashNDegreeQuads(related, issuerCopy); + + // 5.4.5.2) Use the Issue Identifier algorithm, passing issuer + // copy and related and append the result to path. + path += '_:' + issuerCopy.getId(related); + + // 5.4.5.3) Append <, the hash in result, and > to path. + path += `<${result.hash}>`; + + // 5.4.5.4) Set issuer copy to the identifier issuer in + // result. + issuerCopy = result.issuer; + + // 5.4.5.5) If chosen path is not empty and the length of path + // is greater than or equal to the length of chosen path and + // path is lexicographically greater than chosen path, then + // skip to the next permutation. + // Note: Comparing path length to chosen path length can be optimized + // away; only compare lexicographically. + if(chosenPath.length !== 0 && path > chosenPath) { + nextPermutation = true; + break; + } + } + + if(nextPermutation) { + continue; + } + + // 5.4.6) If chosen path is empty or path is lexicographically + // less than chosen path, set chosen path to path and chosen + // issuer to issuer copy. + if(chosenPath.length === 0 || path < chosenPath) { + chosenPath = path; + chosenIssuer = issuerCopy; + } + } + + // 5.5) Append chosen path to data to hash. + md.update(chosenPath); + + // 5.6) Replace issuer, by reference, with chosen issuer. + issuer = chosenIssuer; + } + + // 6) Return issuer and the hash that results from passing data to hash + // through the hash algorithm. + return {hash: md.digest(), issuer}; + } + + // helper for modifying component during Hash First Degree Quads + modifyFirstDegreeComponent(id, component) { + if(component.termType !== 'BlankNode') { + return component; + } + /* Note: A mistake in the RDFC-1.0 spec that made its way into + implementations (and therefore must stay to avoid interop breakage) + resulted in an assigned canonical ID, if available for + `component.value`, not being used in place of `_:a`/`_:z`, so + we don't use it here. */ + return { + termType: 'BlankNode', + value: component.value === id ? 'a' : 'z' + }; + } + + // helper for getting a related predicate + getRelatedPredicate(quad) { + return `<${quad.predicate.value}>`; + } + + // helper for creating hash to related blank nodes map + createHashToRelated(id, issuer) { + // 1) Create a hash to related blank nodes map for storing hashes that + // identify related blank nodes. + const hashToRelated = new Map(); + + // 2) Get a reference, quads, to the list of quads in the blank node to + // quads map for the key identifier. + const quads = this.blankNodeInfo.get(id).quads; + + // 3) For each quad in quads: + for(const quad of quads) { + // 3.1) For each component in quad, if component is the subject, object, + // or graph name and it is a blank node that is not identified by + // identifier: + // steps 3.1.1 and 3.1.2 occur in helpers: + this._addRelatedBlankNodeHash({ + quad, component: quad.subject, position: 's', + id, issuer, hashToRelated + }); + this._addRelatedBlankNodeHash({ + quad, component: quad.object, position: 'o', + id, issuer, hashToRelated + }); + this._addRelatedBlankNodeHash({ + quad, component: quad.graph, position: 'g', + id, issuer, hashToRelated + }); + } + + return hashToRelated; + } + + _hashAndTrackBlankNode({id, hashToBlankNodes}) { + // 5.3.1) Create a hash, hash, according to the Hash First Degree + // Quads algorithm. + const hash = this.hashFirstDegreeQuads(id); + + // 5.3.2) Add hash and identifier to hash to blank nodes map, + // creating a new entry if necessary. + const idList = hashToBlankNodes.get(hash); + if(!idList) { + hashToBlankNodes.set(hash, [id]); + } else { + idList.push(id); + } + } + + _addBlankNodeQuadInfo({quad, component}) { + if(component.termType !== 'BlankNode') { + return; + } + const id = component.value; + const info = this.blankNodeInfo.get(id); + if(info) { + info.quads.add(quad); + } else { + this.blankNodeInfo.set(id, {quads: new Set([quad]), hash: null}); + } + } + + _addRelatedBlankNodeHash( + {quad, component, position, id, issuer, hashToRelated}) { + if(!(component.termType === 'BlankNode' && component.value !== id)) { + return; + } + // 3.1.1) Set hash to the result of the Hash Related Blank Node + // algorithm, passing the blank node identifier for component as + // related, quad, path identifier issuer as issuer, and position as + // either s, o, or g based on whether component is a subject, object, + // graph name, respectively. + const related = component.value; + const hash = this.hashRelatedBlankNode( + related, quad, issuer, position); + + // 3.1.2) Add a mapping of hash to the blank node identifier for + // component to hash to related blank nodes map, adding an entry as + // necessary. + const entries = hashToRelated.get(hash); + if(entries) { + entries.push(related); + } else { + hashToRelated.set(hash, [related]); + } + } + + // canonical ids for 7.1 + _componentWithCanonicalId(component) { + if(component.termType === 'BlankNode' && + !component.value.startsWith(this.canonicalIssuer.prefix)) { + // create new BlankNode + return { + termType: 'BlankNode', + value: this.canonicalIssuer.getId(component.value) + }; + } + return component; + } +}; + +function _stringHashCompare(a, b) { + return a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0; +} + + +/***/ }, + +/***/ "./node_modules/rdf-canonize/lib/index.js" +/*!************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/index.js ***! + \************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/** + * An implementation of the RDF Dataset Normalization specification. + * This library works in the browser and node.js. + * + * BSD 3-Clause License + * Copyright (c) 2016-2023 Digital Bazaar, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of the Digital Bazaar, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + +const RDFC10 = __webpack_require__(/*! ./RDFC10 */ "./node_modules/rdf-canonize/lib/RDFC10.js"); +const RDFC10Sync = __webpack_require__(/*! ./RDFC10Sync */ "./node_modules/rdf-canonize/lib/RDFC10Sync.js"); + +// optional native support +let rdfCanonizeNative; +try { + rdfCanonizeNative = __webpack_require__(/*! rdf-canonize-native */ "?2b19"); +} catch(e) {} + +// return a dataset from input dataset or n-quads +function _inputToDataset(input, options) { + if(options.inputFormat) { + if(options.inputFormat === 'application/n-quads') { + if(typeof input !== 'string') { + throw new Error('N-Quads input must be a string.'); + } + return exports.NQuads.parse(input); + } + throw new Error( + `Unknown canonicalization input format: "${options.inputFormat}".`); + } + return input; +} + +// check for valid output format +function _checkOutputFormat(options) { + // only N-Quads supported + if(options.format) { + if(options.format !== 'application/n-quads') { + throw new Error( + `Unknown canonicalization output format: "${options.format}".`); + } + } +} + +// helper to trace URDNA2015 usage +function _traceURDNA2015() { + if(!!globalThis.RDF_CANONIZE_TRACE_URDNA2015) { + console.trace('[rdf-canonize] URDNA2015 is deprecated, use RDFC-1.0'); + } +} + +// expose helpers +exports.NQuads = __webpack_require__(/*! ./NQuads */ "./node_modules/rdf-canonize/lib/NQuads.js"); +exports.IdentifierIssuer = __webpack_require__(/*! ./IdentifierIssuer */ "./node_modules/rdf-canonize/lib/IdentifierIssuer.js"); + +/** + * Get or set native API. + * + * @param {object} [api] - The native API. + * + * @returns {object} - The currently set native API. + */ +exports._rdfCanonizeNative = function(api) { + if(api) { + rdfCanonizeNative = api; + } + return rdfCanonizeNative; +}; + +/** + * Asynchronously canonizes an RDF dataset. + * + * @param {Array|object|string} input - The input to canonize given as a + * dataset or format specified by 'inputFormat' option. + * @param {object} options - The options to use: + * {string} algorithm - The canonicalization algorithm to use, `RDFC-1.0`. + * {Function} [createMessageDigest] - A factory function for creating a + * `MessageDigest` interface that overrides the built-in message digest + * implementation used by the canonize algorithm; note that using a hash + * algorithm (or HMAC algorithm) that differs from the one specified by + * the canonize algorithm will result in different output. + * {string} [messageDigestAlgorithm=sha256] - Message digest algorithm used + * by the default implementation of `createMessageDigest`. Supported + * algorithms are: 'sha256', 'sha384', 'sha512', and the 'SHA###' and + * 'SHA-###' variations. + * {Map} [canonicalIdMap] - An optional Map to be populated by the canonical + * identifier issuer with the bnode identifier mapping generated by the + * canonicalization algorithm. + * {string} [inputFormat] - The format of the input. Use + * 'application/n-quads' for a N-Quads string that will be parsed. Omit or + * falsy for a JSON dataset. + * {string} [format] - The format of the output. Omit or use + * 'application/n-quads' for a N-Quads string. + * {boolean} [useNative=false] - Use native implementation. + * {number} [maxWorkFactor=1] - Control of the maximum number of times to run + * deep comparison algorithms (such as the N-Degree Hash Quads algorithm + * used in RDFC-1.0) before bailing out and throwing an error; this is a + * useful setting for preventing wasted CPU cycles or DoS when canonizing + * meaningless or potentially malicious datasets. This parameter sets the + * maximum number of iterations based on the number of non-unique blank + * nodes. `0` to disable iterations, `1` for a O(n) limit, `2` for a O(n^2) + * limit, `3` and higher may handle "poison" graphs but may take + * significant computational resources, `Infinity` for no limitation. + * Defaults to `1` which can handle many common inputs. + * {number} [maxDeepIterations=-1] - The maximum number of times to run + * deep comparison algorithms (such as the N-Degree Hash Quads algorithm + * used in RDFC-1.0) before bailing out and throwing an error; this is a + * useful setting for preventing wasted CPU cycles or DoS when canonizing + * meaningless or potentially malicious datasets. If set to a value other + * than `-1` it will explicitly set the number of iterations and override + * `maxWorkFactor`. It is recommended to use `maxWorkFactor`. + * {AbortSignal} [signal] - An AbortSignal used to abort the operation. The + * aborted status is only periodically checked for performance reasons. + * {boolean} [rejectURDNA2015=false] - Reject the "URDNA2015" algorithm name + * instead of treating it as an alias for "RDFC-1.0". + * + * @returns {Promise} - A Promise that resolves to the canonicalized + * RDF Dataset. + */ +exports.canonize = async function(input, options = {}) { + const dataset = _inputToDataset(input, options); + _checkOutputFormat(options); + + if(options.useNative) { + if(!rdfCanonizeNative) { + throw new Error('rdf-canonize-native not available'); + } + if(options.createMessageDigest) { + throw new Error( + '"createMessageDigest" cannot be used with "useNative".'); + } + return new Promise((resolve, reject) => + rdfCanonizeNative.canonize(dataset, options, (err, canonical) => + err ? reject(err) : resolve(canonical))); + } + + if(!('algorithm' in options)) { + throw new Error('No RDF Dataset Canonicalization algorithm specified.'); + } + if(options.algorithm === 'RDFC-1.0') { + return new RDFC10(options).main(dataset); + } + // URDNA2015 deprecated, handled as alias for RDFC-1.0 if allowed + if(options.algorithm === 'URDNA2015' && !options.rejectURDNA2015) { + _traceURDNA2015(); + return new RDFC10(options).main(dataset); + } + throw new Error( + 'Invalid RDF Dataset Canonicalization algorithm: ' + options.algorithm); +}; + +/** + * This method is no longer available in the public API, it is for testing + * only. It synchronously canonizes an RDF dataset and does not work in the + * browser. + * + * @param {Array|object|string} input - The input to canonize given as a + * dataset or format specified by 'inputFormat' option. + * @param {object} options - The options to use: + * {string} algorithm - The canonicalization algorithm to use, `RDFC-1.0`. + * {Function} [createMessageDigest] - A factory function for creating a + * `MessageDigest` interface that overrides the built-in message digest + * implementation used by the canonize algorithm; note that using a hash + * algorithm (or HMAC algorithm) that differs from the one specified by + * the canonize algorithm will result in different output. + * {string} [messageDigestAlgorithm=sha256] - Message digest algorithm used + * by the default implementation of `createMessageDigest`. Supported + * algorithms are: 'sha256', 'sha384', 'sha512', and the 'SHA###' and + * 'SHA-###' variations. + * {Map} [canonicalIdMap] - An optional Map to be populated by the canonical + * identifier issuer with the bnode identifier mapping generated by the + * canonicalization algorithm. + * {string} [inputFormat] - The format of the input. Use + * 'application/n-quads' for a N-Quads string that will be parsed. Omit or + * falsy for a JSON dataset. + * {string} [format] - The format of the output. Omit or use + * 'application/n-quads' for a N-Quads string. + * {boolean} [useNative=false] - Use native implementation. + * {number} [maxWorkFactor=1] - Control of the maximum number of times to run + * deep comparison algorithms (such as the N-Degree Hash Quads algorithm + * used in RDFC-1.0) before bailing out and throwing an error; this is a + * useful setting for preventing wasted CPU cycles or DoS when canonizing + * meaningless or potentially malicious datasets. This parameter sets the + * maximum number of iterations based on the number of non-unique blank + * nodes. `0` to disable iterations, `1` for a O(n) limit, `2` for a O(n^2) + * limit, `3` and higher may handle "poison" graphs but may take + * significant computational resources, `Infinity` for no limitation. + * Defaults to `1` which can handle many common inputs. + * {number} [maxDeepIterations=-1] - The maximum number of times to run + * deep comparison algorithms (such as the N-Degree Hash Quads algorithm + * used in RDFC-1.0) before bailing out and throwing an error; this is a + * useful setting for preventing wasted CPU cycles or DoS when canonizing + * meaningless or potentially malicious datasets. If set to a value other + * than `-1` it will explicitly set the number of iterations and override + * `maxWorkFactor`. It is recommended to use `maxWorkFactor`. + * {number} [timeout=1000] - The maximum number of milliseconds before the + * operation will timeout. This is only periodically checked for + * performance reasons. Use 0 to disable. Note: This is a replacement for + * the async canonize `signal` option common timeout use case. If complex + * abort logic is required, use the async function and the `signal` + * parameter. + * {boolean} [rejectURDNA2015=false] - Reject the "URDNA2015" algorithm name + * instead of treating it as an alias for "RDFC-1.0". + * + * @returns {Promise} - A Promise that resolves to the canonicalized + * RDF Dataset. + */ +exports._canonizeSync = function(input, options = {}) { + const dataset = _inputToDataset(input, options); + _checkOutputFormat(options); + + if(options.useNative) { + if(!rdfCanonizeNative) { + throw new Error('rdf-canonize-native not available'); + } + if(options.createMessageDigest) { + throw new Error( + '"createMessageDigest" cannot be used with "useNative".'); + } + return rdfCanonizeNative.canonizeSync(dataset, options); + } + if(!('algorithm' in options)) { + throw new Error('No RDF Dataset Canonicalization algorithm specified.'); + } + if(options.algorithm === 'RDFC-1.0') { + return new RDFC10Sync(options).main(dataset); + } + // URDNA2015 deprecated, handled as alias for RDFC-1.0 if allowed + if(options.algorithm === 'URDNA2015' && !options.rejectURDNA2015) { + _traceURDNA2015(); + return new RDFC10Sync(options).main(dataset); + } + throw new Error( + 'Invalid RDF Dataset Canonicalization algorithm: ' + options.algorithm); +}; + + +/***/ }, + +/***/ "./node_modules/rdf-canonize/lib/platform-browser.js" +/*!***********************************************************!*\ + !*** ./node_modules/rdf-canonize/lib/platform-browser.js ***! + \***********************************************************/ +(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2023 Digital Bazaar, Inc. All rights reserved. + */ + + +__webpack_require__(/*! setimmediate */ "./node_modules/setimmediate/setImmediate.js"); + +exports.setImmediate = setImmediate; + +// WebCrypto +exports.crypto = globalThis.crypto; + +// precompute byte to hex table +const byteToHex = []; +for(let n = 0; n <= 0xff; ++n) { + byteToHex.push(n.toString(16).padStart(2, '0')); +} + +exports.bufferToHex = function bufferToHex(buffer) { + let hex = ''; + const bytes = new Uint8Array(buffer); + for(let i = 0; i < bytes.length; ++i) { + hex += byteToHex[bytes[i]]; + } + return hex; +}; + + +/***/ }, + +/***/ "./node_modules/serialize-error/index.js" +/*!***********************************************!*\ + !*** ./node_modules/serialize-error/index.js ***! + \***********************************************/ +(module) { + +"use strict"; + + +class NonError extends Error { + constructor(message) { + super(NonError._prepareSuperMessage(message)); + Object.defineProperty(this, 'name', { + value: 'NonError', + configurable: true, + writable: true + }); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, NonError); + } + } + + static _prepareSuperMessage(message) { + try { + return JSON.stringify(message); + } catch { + return String(message); + } + } +} + +const commonProperties = [ + {property: 'name', enumerable: false}, + {property: 'message', enumerable: false}, + {property: 'stack', enumerable: false}, + {property: 'code', enumerable: true} +]; + +const isCalled = Symbol('.toJSON called'); + +const toJSON = from => { + from[isCalled] = true; + const json = from.toJSON(); + delete from[isCalled]; + return json; +}; + +const destroyCircular = ({ + from, + seen, + to_, + forceEnumerable, + maxDepth, + depth +}) => { + const to = to_ || (Array.isArray(from) ? [] : {}); + + seen.push(from); + + if (depth >= maxDepth) { + return to; + } + + if (typeof from.toJSON === 'function' && from[isCalled] !== true) { + return toJSON(from); + } + + for (const [key, value] of Object.entries(from)) { + if (typeof Buffer === 'function' && Buffer.isBuffer(value)) { + to[key] = '[object Buffer]'; + continue; + } + + if (typeof value === 'function') { + continue; + } + + if (!value || typeof value !== 'object') { + to[key] = value; + continue; + } + + if (!seen.includes(from[key])) { + depth++; + + to[key] = destroyCircular({ + from: from[key], + seen: seen.slice(), + forceEnumerable, + maxDepth, + depth + }); + continue; + } + + to[key] = '[Circular]'; + } + + for (const {property, enumerable} of commonProperties) { + if (typeof from[property] === 'string') { + Object.defineProperty(to, property, { + value: from[property], + enumerable: forceEnumerable ? true : enumerable, + configurable: true, + writable: true + }); + } + } + + return to; +}; + +const serializeError = (value, options = {}) => { + const {maxDepth = Number.POSITIVE_INFINITY} = options; + + if (typeof value === 'object' && value !== null) { + return destroyCircular({ + from: value, + seen: [], + forceEnumerable: true, + maxDepth, + depth: 0 + }); + } + + // People sometimes throw things besides Error objects… + if (typeof value === 'function') { + // `JSON.stringify()` discards functions. We do too, unless a function is thrown directly. + return `[Function: ${(value.name || 'anonymous')}]`; + } + + return value; +}; + +const deserializeError = (value, options = {}) => { + const {maxDepth = Number.POSITIVE_INFINITY} = options; + + if (value instanceof Error) { + return value; + } + + if (typeof value === 'object' && value !== null && !Array.isArray(value)) { + const newError = new Error(); // eslint-disable-line unicorn/error-message + destroyCircular({ + from: value, + seen: [], + to_: newError, + maxDepth, + depth: 0 + }); + return newError; + } + + return new NonError(value); +}; + +module.exports = { + serializeError, + deserializeError +}; + + +/***/ }, + +/***/ "./node_modules/setimmediate/setImmediate.js" +/*!***************************************************!*\ + !*** ./node_modules/setimmediate/setImmediate.js ***! + \***************************************************/ +(__unused_webpack_module, __unused_webpack_exports, __webpack_require__) { + +(function (global, undefined) { + "use strict"; + + if (global.setImmediate) { + return; + } + + var nextHandle = 1; // Spec says greater than zero + var tasksByHandle = {}; + var currentlyRunningATask = false; + var doc = global.document; + var registerImmediate; + + function setImmediate(callback) { + // Callback can either be a function or a string + if (typeof callback !== "function") { + callback = new Function("" + callback); + } + // Copy function arguments + var args = new Array(arguments.length - 1); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i + 1]; + } + // Store and register the task + var task = { callback: callback, args: args }; + tasksByHandle[nextHandle] = task; + registerImmediate(nextHandle); + return nextHandle++; + } + + function clearImmediate(handle) { + delete tasksByHandle[handle]; + } + + function run(task) { + var callback = task.callback; + var args = task.args; + switch (args.length) { + case 0: + callback(); + break; + case 1: + callback(args[0]); + break; + case 2: + callback(args[0], args[1]); + break; + case 3: + callback(args[0], args[1], args[2]); + break; + default: + callback.apply(undefined, args); + break; + } + } + + function runIfPresent(handle) { + // From the spec: "Wait until any invocations of this algorithm started before this one have completed." + // So if we're currently running a task, we'll need to delay this invocation. + if (currentlyRunningATask) { + // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a + // "too much recursion" error. + setTimeout(runIfPresent, 0, handle); + } else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunningATask = true; + try { + run(task); + } finally { + clearImmediate(handle); + currentlyRunningATask = false; + } + } + } + } + + function installNextTickImplementation() { + registerImmediate = function(handle) { + process.nextTick(function () { runIfPresent(handle); }); + }; + } + + function canUsePostMessage() { + // The test against `importScripts` prevents this implementation from being installed inside a web worker, + // where `global.postMessage` means something completely different and can't be used for this purpose. + if (global.postMessage && !global.importScripts) { + var postMessageIsAsynchronous = true; + var oldOnMessage = global.onmessage; + global.onmessage = function() { + postMessageIsAsynchronous = false; + }; + global.postMessage("", "*"); + global.onmessage = oldOnMessage; + return postMessageIsAsynchronous; + } + } + + function installPostMessageImplementation() { + // Installs an event handler on `global` for the `message` event: see + // * https://developer.mozilla.org/en/DOM/window.postMessage + // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages + + var messagePrefix = "setImmediate$" + Math.random() + "$"; + var onGlobalMessage = function(event) { + if (event.source === global && + typeof event.data === "string" && + event.data.indexOf(messagePrefix) === 0) { + runIfPresent(+event.data.slice(messagePrefix.length)); + } + }; + + if (global.addEventListener) { + global.addEventListener("message", onGlobalMessage, false); + } else { + global.attachEvent("onmessage", onGlobalMessage); + } + + registerImmediate = function(handle) { + global.postMessage(messagePrefix + handle, "*"); + }; + } + + function installMessageChannelImplementation() { + var channel = new MessageChannel(); + channel.port1.onmessage = function(event) { + var handle = event.data; + runIfPresent(handle); + }; + + registerImmediate = function(handle) { + channel.port2.postMessage(handle); + }; + } + + function installReadyStateChangeImplementation() { + var html = doc.documentElement; + registerImmediate = function(handle) { + // Create a + + + \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..862182f --- /dev/null +++ b/index.html @@ -0,0 +1,52 @@ + + + + + veri-good! + + +
    +
    + +
    +
    University of Wonderful
    +
    Course Credential Verification
    +
    + +
    +
    + + + + \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..8649295 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,5674 @@ +{ + "name": "veri-good", + "version": "0.0.0-beta.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "veri-good", + "version": "0.0.0-beta.1", + "license": "MIT", + "dependencies": { + "@digitalbazaar/data-integrity": "^2.5.0", + "@digitalbazaar/ed25519-signature-2020": "^5.4.0", + "@digitalbazaar/eddsa-rdfc-2022-cryptosuite": "^1.2.0", + "@digitalbazaar/vc": "^7.2.0", + "@digitalbazaar/vc-bitstring-status-list": "^2.0.1", + "@digitalcredentials/security-document-loader": "^8.0.0", + "jsonld-signatures": "^11.5.0", + "marked": "^17.0.1" + }, + "devDependencies": { + "@playwright/test": "^1.57.0", + "html-webpack-plugin": "^5.6.5", + "http-server": "^14.1.1", + "webpack": "^5.104.1", + "webpack-cli": "^6.0.1", + "webpack-dev-server": "^5.2.2" + } + }, + "node_modules/@digitalbazaar/bitstring": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@digitalbazaar/bitstring/-/bitstring-3.1.0.tgz", + "integrity": "sha512-Cii+Sl++qaexOvv3vchhgZFfSmtHPNIPzGegaq4ffPnflVXFu+V2qrJ17aL2+gfLxrlC/zazZFuAltyKTPq7eg==", + "license": "BSD-3-Clause", + "dependencies": { + "base64url-universal": "^2.0.0", + "pako": "^2.0.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/@digitalbazaar/credentials-context": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@digitalbazaar/credentials-context/-/credentials-context-3.2.0.tgz", + "integrity": "sha512-WruXZAF182pCYq/z2JPJ4N4mVDu6pd/hr7widdCqbKekA53BXHoX7XhL9tmRmQ8kfmkaStBfla67QHhkchWYBQ==", + "license": "SEE LICENSE IN LICENSE.md" + }, + "node_modules/@digitalbazaar/data-integrity": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@digitalbazaar/data-integrity/-/data-integrity-2.5.0.tgz", + "integrity": "sha512-ohIieLfgtPQU9BYfj0eKNiz55/ZDOk5YSE9FN/Hn0eXzI8WQzLkzRvC8pvBnzuzXDgCsjPdSqYvzok5PoClMBQ==", + "license": "BSD-3-Clause", + "dependencies": { + "base58-universal": "^2.0.0", + "base64url-universal": "^2.0.0", + "jsonld-signatures": "^11.3.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@digitalbazaar/data-integrity-context": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@digitalbazaar/data-integrity-context/-/data-integrity-context-2.0.1.tgz", + "integrity": "sha512-XpXUzId6ZIEaNq9R+Fv3LrArj1bRj0QX3yfYgxi2bGZGIMs8EkdwsQdzTq38cmHXBQz4DASVun7mBtwrEqjf3g==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=18" + } + }, + "node_modules/@digitalbazaar/ed25519-multikey": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@digitalbazaar/ed25519-multikey/-/ed25519-multikey-1.3.1.tgz", + "integrity": "sha512-55qIbOaAyswVCFfZ70ap7SN2bDSwYmcVbUtGCrpVF/CjuJ8IPqf6z8fDPJzB+CE7Q896SaZlcDukz4LOwIRCPA==", + "license": "BSD-3-Clause", + "dependencies": { + "@noble/ed25519": "^1.6.0", + "base58-universal": "^2.0.0", + "base64url-universal": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/@digitalbazaar/ed25519-signature-2020": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/@digitalbazaar/ed25519-signature-2020/-/ed25519-signature-2020-5.4.0.tgz", + "integrity": "sha512-dHjOv41wiKLoPaE1S9g4NCMKNnelYtBa5fCJKwrqo+cPlLuKcEhtD7w/uuc5non7bf/GX5sa5YfDI/sRUOS6iw==", + "license": "BSD-3-Clause", + "dependencies": { + "@digitalbazaar/ed25519-multikey": "^1.1.0", + "@digitalbazaar/ed25519-verification-key-2020": "^4.1.0", + "base58-universal": "^2.0.0", + "ed25519-signature-2020-context": "^1.1.0", + "jsonld-signatures": "^11.3.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@digitalbazaar/ed25519-verification-key-2020": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@digitalbazaar/ed25519-verification-key-2020/-/ed25519-verification-key-2020-4.2.0.tgz", + "integrity": "sha512-urEVTYkt+uYD8GjdoS6gkm2sKBich1hqx42b6vvUOmNgF0agZ95JlUjiJXEx+VOwu7WSjJSnEBph2Qatkrk1CA==", + "license": "BSD-3-Clause", + "dependencies": { + "@noble/ed25519": "^1.6.0", + "base58-universal": "^2.0.0", + "base64url-universal": "^2.0.0", + "crypto-ld": "^7.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@digitalbazaar/ed25519-verification-key-2020/node_modules/crypto-ld": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/crypto-ld/-/crypto-ld-7.0.0.tgz", + "integrity": "sha512-RrXy6aB0TOhSiqsgavTQt1G8mKomKIaNLb2JZxj7A/Vi0EwmXguuBQoeiAvePfK6bDR3uQbqYnaLLs4irTWwgw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=14" + } + }, + "node_modules/@digitalbazaar/eddsa-rdfc-2022-cryptosuite": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@digitalbazaar/eddsa-rdfc-2022-cryptosuite/-/eddsa-rdfc-2022-cryptosuite-1.2.0.tgz", + "integrity": "sha512-a3PyICe1SI55SgHXgtPRYpzmZ2FMtloQDkVcbhUZ9dpoLcZg5TqsS4U7ap2ggCD4MUXz7uz6ErikJf76Iwyd0g==", + "license": "BSD-3-Clause", + "dependencies": { + "@digitalbazaar/ed25519-multikey": "^1.0.0", + "jsonld": "^8.1.0", + "rdf-canonize": "^4.0.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@digitalbazaar/http-client": { + "version": "3.4.1", + "resolved": "https://registry.npmjs.org/@digitalbazaar/http-client/-/http-client-3.4.1.tgz", + "integrity": "sha512-Ahk1N+s7urkgj7WvvUND5f8GiWEPfUw0D41hdElaqLgu8wZScI8gdI0q+qWw5N1d35x7GCRH2uk9mi+Uzo9M3g==", + "license": "BSD-3-Clause", + "dependencies": { + "ky": "^0.33.3", + "ky-universal": "^0.11.0", + "undici": "^5.21.2" + }, + "engines": { + "node": ">=14.0" + } + }, + "node_modules/@digitalbazaar/http-client/node_modules/ky": { + "version": "0.33.3", + "resolved": "https://registry.npmjs.org/ky/-/ky-0.33.3.tgz", + "integrity": "sha512-CasD9OCEQSFIam2U8efFK81Yeg8vNMTBUqtMOHlrcWQHqUX3HeCl9Dr31u4toV7emlH8Mymk5+9p0lL6mKb/Xw==", + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sindresorhus/ky?sponsor=1" + } + }, + "node_modules/@digitalbazaar/http-client/node_modules/undici": { + "version": "5.29.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.29.0.tgz", + "integrity": "sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg==", + "license": "MIT", + "dependencies": { + "@fastify/busboy": "^2.0.0" + }, + "engines": { + "node": ">=14.0" + } + }, + "node_modules/@digitalbazaar/security-context": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@digitalbazaar/security-context/-/security-context-1.0.1.tgz", + "integrity": "sha512-0WZa6tPiTZZF8leBtQgYAfXQePFQp2z5ivpCEN/iZguYYZ0TB9qRmWtan5XH6mNFuusHtMcyIzAcReyE6rZPhA==", + "license": "BSD-3-Clause" + }, + "node_modules/@digitalbazaar/vc": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@digitalbazaar/vc/-/vc-7.2.0.tgz", + "integrity": "sha512-Fpa7MG+/pxwV0vJbstKJc1DLrVzFYz7mlqZfRMkFOodR0YvVp3GGdiybCKtj7oxv/cuskzuqB/MFmDhq8tEd9g==", + "license": "BSD-3-Clause", + "dependencies": { + "@digitalbazaar/credentials-context": "^3.2.0", + "ed25519-signature-2018-context": "^1.1.0", + "jsonld": "^8.3.3", + "jsonld-signatures": "^11.5.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@digitalbazaar/vc-bitstring-status-list": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@digitalbazaar/vc-bitstring-status-list/-/vc-bitstring-status-list-2.0.1.tgz", + "integrity": "sha512-q4DJN9Pc+sid8Ju3perwiWcD1YOvBYhwYVUEYMROLN4i4m6n24HlckKmsrLIYaB4ko9MduZ8eeRTxxADNLjkvA==", + "license": "BSD-3-Clause", + "dependencies": { + "@digitalbazaar/bitstring": "^3.1.0", + "@digitalbazaar/credentials-context": "^3.2.0", + "@digitalbazaar/vc": "^7.1.1", + "@digitalbazaar/vc-bitstring-status-list-context": "^1.1.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@digitalbazaar/vc-bitstring-status-list-context": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@digitalbazaar/vc-bitstring-status-list-context/-/vc-bitstring-status-list-context-1.1.0.tgz", + "integrity": "sha512-IULBb2BJ/FQwTwdmvtltBb9JspWXY4tS2ZimRtFfWBJW6T35r6x8TzRK6eDVHpLLEzeJs1jCvqqTXWH0RJgQRA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=18" + } + }, + "node_modules/@digitalbazaar/vc-status-list-context": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@digitalbazaar/vc-status-list-context/-/vc-status-list-context-3.1.1.tgz", + "integrity": "sha512-cMVtd+EV+4KN2kUG4/vsV74JVsGE6dcpod6zRoFB/AJA2W/sZbJqR44KL3G6P262+GcAECNhtnSsKsTnQ6y8+w==", + "license": "BSD-3-Clause" + }, + "node_modules/@digitalcredentials/base58-universal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@digitalcredentials/base58-universal/-/base58-universal-1.0.1.tgz", + "integrity": "sha512-1xKdJnfITMvrF/sCgwBx2C4p7qcNAARyIvrAOZGqIHmBaT/hAenpC8bf44qVY+UIMuCYP23kqpIfJQebQDThDQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/@digitalcredentials/credentials-v2-context": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@digitalcredentials/credentials-v2-context/-/credentials-v2-context-1.0.0.tgz", + "integrity": "sha512-n+zBS+fYlKfvDmt8jdpB6n6p2JRLo6v6A2BGLVmbqzHFvfdQZXS+t489TWipFmi5g3FV12/bDCILUpCrqswDvg==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=18" + } + }, + "node_modules/@digitalcredentials/crypto-ld": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/@digitalcredentials/crypto-ld/-/crypto-ld-7.0.6.tgz", + "integrity": "sha512-wxgjiU08rIMUaPhaOOVUjcdWZoL1FVfzGuX9ADHiyx0O34lJ4wdXnGk5QMYgwpl7B4gy1vDDp5VVHpO8l+aVFQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=16" + } + }, + "node_modules/@digitalcredentials/dcc-context": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@digitalcredentials/dcc-context/-/dcc-context-1.0.0.tgz", + "integrity": "sha512-iun3HTqOqcAoG0lz5GWx/fJYxpbKjzqq866dBo0osxs+pj/CwZDNHKXVC6sdd662tXg9EF0r4YdZ/AW6DOnS6A==", + "license": "MIT" + }, + "node_modules/@digitalcredentials/did-io": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@digitalcredentials/did-io/-/did-io-1.0.2.tgz", + "integrity": "sha512-z6lLRe4drHYwtfxbySQJZZl2YbCPvG5UDkh/H3kAK2NSZY9GaIm9iz9A6E/J5Lu6rct/BOj1XQhtEJnzRdB8wQ==", + "license": "BSD-3-Clause", + "dependencies": { + "@digitalcredentials/lru-memoize": "^2.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@digitalcredentials/did-method-key": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@digitalcredentials/did-method-key/-/did-method-key-3.0.0.tgz", + "integrity": "sha512-Cq75fbUkDed1O3TPFY89xlqq+oCKvBCMjDJz8KIVx75eZCnxhcE9h/a4t9yW0FRnp0LBrV9HDoSPNyN9P6dr1A==", + "license": "BSD-3-Clause", + "dependencies": { + "@digitalcredentials/did-io": "^1.0.2", + "@digitalcredentials/x25519-key-agreement-key-2020": "^2.0.2" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/@digitalcredentials/did-method-key/node_modules/@digitalcredentials/x25519-key-agreement-key-2020": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@digitalcredentials/x25519-key-agreement-key-2020/-/x25519-key-agreement-key-2020-2.0.2.tgz", + "integrity": "sha512-7Ay5AkGfIEWBRJiHl6PhrpFrjAqCZ/+G4rV6sqTUGK8fBnkxqlJ/XiD7NouUF6uTalVm7mJWJXHuCN5FAuXGsg==", + "license": "BSD-3-Clause", + "dependencies": { + "@digitalcredentials/base58-universal": "^1.0.0", + "crypto-ld": "^6.0.0", + "ed2curve": "^0.3.0", + "tweetnacl": "^1.0.3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@digitalcredentials/did-method-web": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@digitalcredentials/did-method-web/-/did-method-web-1.1.0.tgz", + "integrity": "sha512-FgsCNGz6Iniy1fR5G8wcT1EMfQzVPJUhz3ei9Ha0aavN3K3dD2XTIKG83vAV3L9tpmtcQhdwcIG+2JaBO1PBYQ==", + "license": "MIT", + "dependencies": { + "@digitalcredentials/did-io": "^1.0.2", + "@digitalcredentials/did-method-key": "^3.0.0", + "@digitalcredentials/http-client": "^5.0.4", + "klona": "^2.0.6" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@digitalcredentials/ed25519-multikey": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@digitalcredentials/ed25519-multikey/-/ed25519-multikey-1.4.0.tgz", + "integrity": "sha512-BXgNEX42a1EwnUantP6Po7yt43BamajrzVIvips6/egcQIFfXFHwl8yBvmPndsNY1Q9HKv/b743Nl5C3HEt8PA==", + "dependencies": { + "@noble/ed25519": "^1.6.0", + "@stablelib/ed25519": "^2.0.2", + "base58-universal": "^2.0.0", + "base64url-universal": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/@digitalcredentials/ed25519-verification-key-2020": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@digitalcredentials/ed25519-verification-key-2020/-/ed25519-verification-key-2020-3.2.2.tgz", + "integrity": "sha512-ZfxNFZlA379MZpf+gV2tUYyiZ15eGVgjtCQLWlyu3frWxsumUgv++o0OJlMnrDsWGwzFMRrsXcosd5+752rLOA==", + "license": "BSD-3-Clause", + "dependencies": { + "@digitalcredentials/base58-universal": "^1.0.1", + "@stablelib/ed25519": "^1.0.1", + "base64url-universal": "^1.1.0", + "crypto-ld": "^6.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/@digitalcredentials/ed25519-verification-key-2020/node_modules/@stablelib/binary": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/binary/-/binary-1.0.1.tgz", + "integrity": "sha512-ClJWvmL6UBM/wjkvv/7m5VP3GMr9t0osr4yVgLZsLCOz4hGN9gIAFEqnJ0TsSMAN+n840nf2cHZnA5/KFqHC7Q==", + "license": "MIT", + "dependencies": { + "@stablelib/int": "^1.0.1" + } + }, + "node_modules/@digitalcredentials/ed25519-verification-key-2020/node_modules/@stablelib/ed25519": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@stablelib/ed25519/-/ed25519-1.0.3.tgz", + "integrity": "sha512-puIMWaX9QlRsbhxfDc5i+mNPMY+0TmQEskunY1rZEBPi1acBCVQAhnsk/1Hk50DGPtVsZtAWQg4NHGlVaO9Hqg==", + "license": "MIT", + "dependencies": { + "@stablelib/random": "^1.0.2", + "@stablelib/sha512": "^1.0.1", + "@stablelib/wipe": "^1.0.1" + } + }, + "node_modules/@digitalcredentials/ed25519-verification-key-2020/node_modules/@stablelib/hash": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/hash/-/hash-1.0.1.tgz", + "integrity": "sha512-eTPJc/stDkdtOcrNMZ6mcMK1e6yBbqRBaNW55XA1jU8w/7QdnCF0CmMmOD1m7VSkBR44PWrMHU2l6r8YEQHMgg==", + "license": "MIT" + }, + "node_modules/@digitalcredentials/ed25519-verification-key-2020/node_modules/@stablelib/int": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/int/-/int-1.0.1.tgz", + "integrity": "sha512-byr69X/sDtDiIjIV6m4roLVWnNNlRGzsvxw+agj8CIEazqWGOQp2dTYgQhtyVXV9wpO6WyXRQUzLV/JRNumT2w==", + "license": "MIT" + }, + "node_modules/@digitalcredentials/ed25519-verification-key-2020/node_modules/@stablelib/random": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@stablelib/random/-/random-1.0.2.tgz", + "integrity": "sha512-rIsE83Xpb7clHPVRlBj8qNe5L8ISQOzjghYQm/dZ7VaM2KHYwMW5adjQjrzTZCchFnNCNhkwtnOBa9HTMJCI8w==", + "license": "MIT", + "dependencies": { + "@stablelib/binary": "^1.0.1", + "@stablelib/wipe": "^1.0.1" + } + }, + "node_modules/@digitalcredentials/ed25519-verification-key-2020/node_modules/@stablelib/sha512": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/sha512/-/sha512-1.0.1.tgz", + "integrity": "sha512-13gl/iawHV9zvDKciLo1fQ8Bgn2Pvf7OV6amaRVKiq3pjQ3UmEpXxWiAfV8tYjUpeZroBxtyrwtdooQT/i3hzw==", + "license": "MIT", + "dependencies": { + "@stablelib/binary": "^1.0.1", + "@stablelib/hash": "^1.0.1", + "@stablelib/wipe": "^1.0.1" + } + }, + "node_modules/@digitalcredentials/ed25519-verification-key-2020/node_modules/@stablelib/wipe": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/wipe/-/wipe-1.0.1.tgz", + "integrity": "sha512-WfqfX/eXGiAd3RJe4VU2snh/ZPwtSjLG4ynQ/vYzvghTh7dHFcI1wl+nrkWG6lGhukOxOsUHfv8dUXr58D0ayg==", + "license": "MIT" + }, + "node_modules/@digitalcredentials/ed25519-verification-key-2020/node_modules/base64url-universal": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/base64url-universal/-/base64url-universal-1.1.0.tgz", + "integrity": "sha512-WyftvZqye29YQ10ZnuiBeEj0lk8SN8xHU9hOznkLc85wS1cLTp6RpzlMrHxMPD9nH7S55gsBqMqgGyz93rqmkA==", + "license": "BSD-3-Clause", + "dependencies": { + "base64url": "^3.0.0" + }, + "engines": { + "node": ">=8.3.0" + } + }, + "node_modules/@digitalcredentials/http-client": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@digitalcredentials/http-client/-/http-client-5.0.4.tgz", + "integrity": "sha512-TbbfFauhd5fUAcZ/6TDenTuYqkzqdEhxYk1Rqicxcz33B9rzvJcmT+/81KF9DrUXmu6gpoqCranT2UkZftsxZA==", + "license": "BSD-3-Clause", + "dependencies": { + "ky": "^1.0.1", + "undici": "^6.6.2" + }, + "engines": { + "node": ">=18.0" + } + }, + "node_modules/@digitalcredentials/lru-memoize": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@digitalcredentials/lru-memoize/-/lru-memoize-2.1.4.tgz", + "integrity": "sha512-dvgeYYHW8lAWJrGyIY1qhuTahqvVJYXxuSkJ2A1MgenFLb/nWnIcSov0K/5nDnPYA5TilItmMpAxt6iuNtaKQg==", + "license": "BSD-3-Clause", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/@digitalcredentials/open-badges-context": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@digitalcredentials/open-badges-context/-/open-badges-context-3.0.0.tgz", + "integrity": "sha512-pyXirpq29gy+NIaTBozDEm7nk1Oh8Yqie2WR0JuIqRX0ePCbiFeMv2uPEP3TXzyh1Jz++28fD+qjNojlhUmiIw==", + "license": "MIT" + }, + "node_modules/@digitalcredentials/security-document-loader": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@digitalcredentials/security-document-loader/-/security-document-loader-8.0.0.tgz", + "integrity": "sha512-0rURdip0S/L4aegONkef5yzaGqQ35n7TXE0RhtEJa6scEaZssazaADgg9ApMA47kiGRjCn30yKrds9YULwoltA==", + "license": "MIT", + "dependencies": { + "@digitalbazaar/data-integrity-context": "^2.0.0", + "@digitalbazaar/vc-bitstring-status-list-context": "^1.0.0", + "@digitalbazaar/vc-status-list-context": "^3.0.1", + "@digitalcredentials/credentials-v2-context": "^1.0.0", + "@digitalcredentials/crypto-ld": "^7.0.2", + "@digitalcredentials/dcc-context": "^1.0.0", + "@digitalcredentials/did-io": "^1.0.2", + "@digitalcredentials/did-method-key": "^3.0.0", + "@digitalcredentials/did-method-web": "^1.1.0", + "@digitalcredentials/ed25519-multikey": "^1.4.0", + "@digitalcredentials/ed25519-verification-key-2020": "^3.2.2", + "@digitalcredentials/http-client": "^5.0.1", + "@digitalcredentials/open-badges-context": "^3.0.0", + "@digitalcredentials/x25519-key-agreement-key-2020": "^3.0.0", + "credentials-context": "^2.0.0", + "did-context": "^3.1.1", + "ed25519-signature-2020-context": "^1.1.0", + "html-entities": "^2.3.3", + "jsonld-document-loader": "^1.2.1", + "x25519-key-agreement-2020-context": "^1.0.0" + }, + "engines": { + "node": ">=16.0" + } + }, + "node_modules/@digitalcredentials/x25519-key-agreement-key-2020": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@digitalcredentials/x25519-key-agreement-key-2020/-/x25519-key-agreement-key-2020-3.0.0.tgz", + "integrity": "sha512-mCh6eRh6opBZiEtAWZ3RvCGs6JP9QpN2/xPxncQIKBK9WBUxONgL1CEsTUTRcisGvWQrUcqVXRHQ0Tl6b8weSQ==", + "license": "BSD-3-Clause", + "dependencies": { + "@digitalcredentials/base58-universal": "^1.0.0", + "@noble/ed25519": "^1.6.0", + "crypto-ld": "^6.0.0", + "tweetnacl": "^1.0.3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@discoveryjs/json-ext": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-0.6.3.tgz", + "integrity": "sha512-4B4OijXeVNOPZlYA2oEwWOTkzyltLao+xbotHQeqN++Rv27Y6s818+n2Qkp8q+Fxhn0t/5lA5X1Mxktud8eayQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.17.0" + } + }, + "node_modules/@fastify/busboy": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz", + "integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz", + "integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@jsonjoy.com/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-q6XAnWQDIMA3+FTiOYajoYqySkO+JSat0ytXGSuRdq9uXE7o92gzuQwQM14xaCRlBLGq3v5miDGC4vkVTn54xA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/buffers": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/buffers/-/buffers-1.2.1.tgz", + "integrity": "sha512-12cdlDwX4RUM3QxmUbVJWqZ/mrK6dFQH4Zxq6+r1YXKXYBNgZXndx2qbCJwh3+WWkCSn67IjnlG3XYTvmvYtgA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/codegen": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/codegen/-/codegen-1.0.0.tgz", + "integrity": "sha512-E8Oy+08cmCf0EK/NMxpaJZmOxPqM+6iSe2S4nlSBrPZOORoDJILxtbSUEDKQyTamm/BVAhIGllOBNU79/dwf0g==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/json-pack": { + "version": "1.21.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/json-pack/-/json-pack-1.21.0.tgz", + "integrity": "sha512-+AKG+R2cfZMShzrF2uQw34v3zbeDYUqnQ+jg7ORic3BGtfw9p/+N6RJbq/kkV8JmYZaINknaEQ2m0/f693ZPpg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/base64": "^1.1.2", + "@jsonjoy.com/buffers": "^1.2.0", + "@jsonjoy.com/codegen": "^1.0.0", + "@jsonjoy.com/json-pointer": "^1.0.2", + "@jsonjoy.com/util": "^1.9.0", + "hyperdyperid": "^1.2.0", + "thingies": "^2.5.0", + "tree-dump": "^1.1.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/json-pointer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/json-pointer/-/json-pointer-1.0.2.tgz", + "integrity": "sha512-Fsn6wM2zlDzY1U+v4Nc8bo3bVqgfNTGcn6dMgs6FjrEnt4ZCe60o6ByKRjOGlI2gow0aE/Q41QOigdTqkyK5fg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/codegen": "^1.0.0", + "@jsonjoy.com/util": "^1.9.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@jsonjoy.com/util": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/util/-/util-1.9.0.tgz", + "integrity": "sha512-pLuQo+VPRnN8hfPqUTLTHk126wuYdXVxE6aDmjSeV4NCAgyxWbiOIeNJVtID3h1Vzpoi9m4jXezf73I6LgabgQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/buffers": "^1.0.0", + "@jsonjoy.com/codegen": "^1.0.0" + }, + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/@leichtgewicht/ip-codec": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz", + "integrity": "sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@noble/ed25519": { + "version": "1.7.5", + "resolved": "https://registry.npmjs.org/@noble/ed25519/-/ed25519-1.7.5.tgz", + "integrity": "sha512-xuS0nwRMQBvSxDa7UxMb61xTiH3MxTgUfhyPUALVIe0FlOAz4sjELwyDRyUvqeEYfRSG9qNjFIycqLZppg4RSA==", + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "license": "MIT" + }, + "node_modules/@playwright/test": { + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.57.0.tgz", + "integrity": "sha512-6TyEnHgd6SArQO8UO2OMTxshln3QMWBtPGrOCgs3wVEmQmwyuNtB10IZMfmYDE0riwNR1cu4q+pPcxMVtaG3TA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.57.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@stablelib/binary": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/binary/-/binary-2.0.1.tgz", + "integrity": "sha512-U9iAO8lXgEDONsA0zPPSgcf3HUBNAqHiJmSHgZz62OvC3Hi2Bhc5kTnQ3S1/L+sthDTHtCMhcEiklmIly6uQ3w==", + "license": "MIT", + "dependencies": { + "@stablelib/int": "^2.0.1" + } + }, + "node_modules/@stablelib/ed25519": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@stablelib/ed25519/-/ed25519-2.0.2.tgz", + "integrity": "sha512-d/lJ5sgzhtmpMIbKFWfev+i6WebBdIzzBpMzXtZdvUijoksjXosYFNqytoMj7cRshNj+/XTLYnnVMdZfd+penw==", + "license": "MIT", + "dependencies": { + "@stablelib/random": "^2.0.1", + "@stablelib/sha512": "^2.0.1", + "@stablelib/wipe": "^2.0.1" + } + }, + "node_modules/@stablelib/hash": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@stablelib/hash/-/hash-2.0.0.tgz", + "integrity": "sha512-u3WPSqGido8lwJuMcrBgM5K54LrPGhkWAdtsyccf7dGsLixAZUds77zOAbu7bvKPwQlmoByH0txBi5rTmEKuHg==", + "license": "MIT" + }, + "node_modules/@stablelib/int": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/int/-/int-2.0.1.tgz", + "integrity": "sha512-Ht63fQp3wz/F8U4AlXEPb7hfJOIILs8Lq55jgtD7KueWtyjhVuzcsGLSTAWtZs3XJDZYdF1WcSKn+kBtbzupww==", + "license": "MIT" + }, + "node_modules/@stablelib/random": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/random/-/random-2.0.1.tgz", + "integrity": "sha512-W6GAtXEEs7r+dSbuBsvoFmlyL3gLxle41tQkjKu17dDWtDdjhVUbtRfRCQcCUeczwkgjQxMPopgwYEvxXtHXGw==", + "license": "MIT", + "dependencies": { + "@stablelib/binary": "^2.0.1", + "@stablelib/wipe": "^2.0.1" + } + }, + "node_modules/@stablelib/sha512": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/sha512/-/sha512-2.0.1.tgz", + "integrity": "sha512-DUNe5cbnoH3sSIN+MG04RvTCLXtkbyy/SnQxiNO+GgF/KSXkkUSlF6mUVvCUdZBZ2X3NgogR+tAvaRSn8wxnLw==", + "license": "MIT", + "dependencies": { + "@stablelib/binary": "^2.0.1", + "@stablelib/hash": "^2.0.0", + "@stablelib/wipe": "^2.0.1" + } + }, + "node_modules/@stablelib/wipe": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/wipe/-/wipe-2.0.1.tgz", + "integrity": "sha512-1eU2K9EgOcV4qc9jcP6G72xxZxEm5PfeI5H55l08W95b4oRJaqhmlWRc4xZAm6IVSKhVNxMi66V67hCzzuMTAg==", + "license": "MIT" + }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", + "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/bonjour": { + "version": "3.5.13", + "resolved": "https://registry.npmjs.org/@types/bonjour/-/bonjour-3.5.13.tgz", + "integrity": "sha512-z9fJ5Im06zvUL548KvYNecEVlA7cVDkGUi6kZusb04mpyEFKCIZJvloCcmpmLaIahDpOQGHaHmG6imtPMmPXGQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/connect-history-api-fallback": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/@types/connect-history-api-fallback/-/connect-history-api-fallback-1.5.4.tgz", + "integrity": "sha512-n6Cr2xS1h4uAulPRdlw6Jl6s1oG8KrVilPN2yUITEs+K48EzMJJ3W1xy8K5eWuFvjp3R74AOIGSmp2UfBJ8HFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/express-serve-static-core": "*", + "@types/node": "*" + } + }, + "node_modules/@types/eslint": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-9.6.1.tgz", + "integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "*", + "@types/json-schema": "*" + } + }, + "node_modules/@types/eslint-scope": { + "version": "3.7.7", + "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.7.tgz", + "integrity": "sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/eslint": "*", + "@types/estree": "*" + } + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/express": { + "version": "4.17.25", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.25.tgz", + "integrity": "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "^1" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.7", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.7.tgz", + "integrity": "sha512-FvPtiIf1LfhzsaIXhv/PHan/2FeQBbtBDtfX2QfvPxdUelMDEckK08SM6nqo1MIZY3RUlfA+HV8+hFUSio78qg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/html-minifier-terser": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/@types/html-minifier-terser/-/html-minifier-terser-6.1.0.tgz", + "integrity": "sha512-oh/6byDPnL1zeNXFrDXFLyZjkr1MsBG667IM792caf1L2UPOOMf65NFzjUH/ltyfwjAGfs1rsX1eftK0jC/KIg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/http-proxy": { + "version": "1.17.17", + "resolved": "https://registry.npmjs.org/@types/http-proxy/-/http-proxy-1.17.17.tgz", + "integrity": "sha512-ED6LB+Z1AVylNTu7hdzuBqOgMnvG/ld6wGCG8wFnAzKX5uyW2K3WD52v0gnLCTK/VLpXtKckgWuyScYK6cSPaw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "25.0.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.3.tgz", + "integrity": "sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/node-forge": { + "version": "1.3.14", + "resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.3.14.tgz", + "integrity": "sha512-mhVF2BnD4BO+jtOp7z1CdzaK4mbuK0LLQYAvdOLqHTavxFNq4zA1EmYkpnFjP8HOUzedfQkRnp0E2ulSAYSzAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/retry": { + "version": "0.12.2", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.2.tgz", + "integrity": "sha512-XISRgDJ2Tc5q4TRqvgJtzsRkFYNJzZrhTdtMoGVBttwzzQJkPnS3WWTFc7kuDRoPtPakl+T+OfdEUjYJj7Jbow==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", + "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/serve-index": { + "version": "1.9.4", + "resolved": "https://registry.npmjs.org/@types/serve-index/-/serve-index-1.9.4.tgz", + "integrity": "sha512-qLpGZ/c2fhSs5gnYsQxtDEq3Oy8SXPClIXkW5ghvAvsNuVSA8k+gCONcUCS/UjLEYvYps+e8uBtfgXgvhwfNug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/express": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.10", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.10.tgz", + "integrity": "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "<1" + } + }, + "node_modules/@types/serve-static/node_modules/@types/send": { + "version": "0.17.6", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.6.tgz", + "integrity": "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/sockjs": { + "version": "0.3.36", + "resolved": "https://registry.npmjs.org/@types/sockjs/-/sockjs-0.3.36.tgz", + "integrity": "sha512-MK9V6NzAS1+Ud7JV9lJLFqW85VbC9dq3LmwZCuBe4wBDgKC0Kj/jd8Xl+nSviU+Qc3+m7umHHyHg//2KSa0a0Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@webassemblyjs/ast": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.14.1.tgz", + "integrity": "sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/helper-numbers": "1.13.2", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2" + } + }, + "node_modules/@webassemblyjs/floating-point-hex-parser": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.13.2.tgz", + "integrity": "sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-api-error": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.13.2.tgz", + "integrity": "sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-buffer": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.14.1.tgz", + "integrity": "sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-numbers": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.13.2.tgz", + "integrity": "sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/floating-point-hex-parser": "1.13.2", + "@webassemblyjs/helper-api-error": "1.13.2", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.13.2.tgz", + "integrity": "sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-wasm-section": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.14.1.tgz", + "integrity": "sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/wasm-gen": "1.14.1" + } + }, + "node_modules/@webassemblyjs/ieee754": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.13.2.tgz", + "integrity": "sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "node_modules/@webassemblyjs/leb128": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.13.2.tgz", + "integrity": "sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/utf8": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.13.2.tgz", + "integrity": "sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/wasm-edit": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.14.1.tgz", + "integrity": "sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/helper-wasm-section": "1.14.1", + "@webassemblyjs/wasm-gen": "1.14.1", + "@webassemblyjs/wasm-opt": "1.14.1", + "@webassemblyjs/wasm-parser": "1.14.1", + "@webassemblyjs/wast-printer": "1.14.1" + } + }, + "node_modules/@webassemblyjs/wasm-gen": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.14.1.tgz", + "integrity": "sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/ieee754": "1.13.2", + "@webassemblyjs/leb128": "1.13.2", + "@webassemblyjs/utf8": "1.13.2" + } + }, + "node_modules/@webassemblyjs/wasm-opt": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.14.1.tgz", + "integrity": "sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/wasm-gen": "1.14.1", + "@webassemblyjs/wasm-parser": "1.14.1" + } + }, + "node_modules/@webassemblyjs/wasm-parser": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.14.1.tgz", + "integrity": "sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-api-error": "1.13.2", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/ieee754": "1.13.2", + "@webassemblyjs/leb128": "1.13.2", + "@webassemblyjs/utf8": "1.13.2" + } + }, + "node_modules/@webassemblyjs/wast-printer": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.14.1.tgz", + "integrity": "sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webpack-cli/configtest": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-3.0.1.tgz", + "integrity": "sha512-u8d0pJ5YFgneF/GuvEiDA61Tf1VDomHHYMjv/wc9XzYj7nopltpG96nXN5dJRstxZhcNpV1g+nT6CydO7pHbjA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12.0" + }, + "peerDependencies": { + "webpack": "^5.82.0", + "webpack-cli": "6.x.x" + } + }, + "node_modules/@webpack-cli/info": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-3.0.1.tgz", + "integrity": "sha512-coEmDzc2u/ffMvuW9aCjoRzNSPDl/XLuhPdlFRpT9tZHmJ/039az33CE7uH+8s0uL1j5ZNtfdv0HkfaKRBGJsQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12.0" + }, + "peerDependencies": { + "webpack": "^5.82.0", + "webpack-cli": "6.x.x" + } + }, + "node_modules/@webpack-cli/serve": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-3.0.1.tgz", + "integrity": "sha512-sbgw03xQaCLiT6gcY/6u3qBDn01CWw/nbaXl3gTdTFuJJ75Gffv3E3DBpgvY2fkkrdS1fpjaXNOmJlnbtKauKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12.0" + }, + "peerDependencies": { + "webpack": "^5.82.0", + "webpack-cli": "6.x.x" + }, + "peerDependenciesMeta": { + "webpack-dev-server": { + "optional": true + } + } + }, + "node_modules/@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/@xtuc/long": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/accepts/node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.15.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", + "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-import-phases": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/acorn-import-phases/-/acorn-import-phases-1.0.4.tgz", + "integrity": "sha512-wKmbr/DDiIXzEOiWrTTUcDm24kQ2vGfZQvM2fwg2vXqR5uW6aapr7ObPtj1th32b9u90/Pf4AItvdTh42fBmVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.13.0" + }, + "peerDependencies": { + "acorn": "^8.14.0" + } + }, + "node_modules/ajv": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3" + }, + "peerDependencies": { + "ajv": "^8.8.2" + } + }, + "node_modules/ansi-html-community": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/ansi-html-community/-/ansi-html-community-0.0.8.tgz", + "integrity": "sha512-1APHAyr3+PCamwNw3bXCPp4HFLONZt/yIH0sZp0/469KWNTEy+qN5jQ3GVX6DMZ1UXAi34yVwtTeaG/HpBuuzw==", + "dev": true, + "engines": [ + "node >= 0.8.0" + ], + "license": "Apache-2.0", + "bin": { + "ansi-html": "bin/ansi-html" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/anymatch/node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "dev": true, + "license": "MIT" + }, + "node_modules/base58-universal": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base58-universal/-/base58-universal-2.0.0.tgz", + "integrity": "sha512-BgkgF8zVLOAygszG4W8NkLm7iXrw80VYAOcedrzANrIhS14+4W6zVqjyGTFUBM/FpqkHUt8aAYd4DbBBfn3zKg==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=14" + } + }, + "node_modules/base64url": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/base64url/-/base64url-3.0.1.tgz", + "integrity": "sha512-ir1UPr3dkwexU7FdV8qBBbNDRUhMmIekYMFZfi+C/sLNnRESKPl23nB9b2pltqfOQNnGzsDdId90AEtG5tCx4A==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/base64url-universal": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64url-universal/-/base64url-universal-2.0.0.tgz", + "integrity": "sha512-6Hpg7EBf3t148C3+fMzjf+CHnADVDafWzlJUXAqqqbm4MKNXbsoPdOkWeRTjNlkYG7TpyjIpRO1Gk0SnsFD1rw==", + "license": "BSD-3-Clause", + "dependencies": { + "base64url": "^3.0.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.9.11", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.11.tgz", + "integrity": "sha512-Sg0xJUNDU1sJNGdfGWhVHX0kkZ+HWcvmVymJbj6NSgZZmW/8S9Y2HQ5euytnIgakgxN6papOAWiwDo1ctFDcoQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.js" + } + }, + "node_modules/basic-auth": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz", + "integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "5.1.2" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/batch": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/batch/-/batch-0.6.1.tgz", + "integrity": "sha512-x+VAiMRL6UPkx+kudNvxTl6hB2XNNCG2r+7wixVfIYwu/2HKRXimwQyaumLjMveWvT2Hkd/cAJw+QBMfJ/EKVw==", + "dev": true, + "license": "MIT" + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/body-parser": { + "version": "1.20.4", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", + "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.14.0", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/body-parser/node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/body-parser/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true, + "license": "MIT" + }, + "node_modules/bonjour-service": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/bonjour-service/-/bonjour-service-1.3.0.tgz", + "integrity": "sha512-3YuAUiSkWykd+2Azjgyxei8OWf8thdn8AITIog2M4UICzoqfjlqr64WIjEXZllf/W6vK1goqleSR6brGomxQqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "multicast-dns": "^7.2.5" + } + }, + "node_modules/boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", + "dev": true, + "license": "ISC" + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.28.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", + "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.9.0", + "caniuse-lite": "^1.0.30001759", + "electron-to-chromium": "^1.5.263", + "node-releases": "^2.0.27", + "update-browserslist-db": "^1.2.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/bundle-name": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bundle-name/-/bundle-name-4.1.0.tgz", + "integrity": "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "run-applescript": "^7.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/camel-case": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/camel-case/-/camel-case-4.1.2.tgz", + "integrity": "sha512-gxGWBrTT1JuMx6R+o5PTXMmUnhnVzLQ9SNutD4YqKtI6ap897t3tKECYla6gCWEkplXnlNybEkZg9GEGxKFCgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "pascal-case": "^3.1.2", + "tslib": "^2.0.3" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001761", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001761.tgz", + "integrity": "sha512-JF9ptu1vP2coz98+5051jZ4PwQgd2ni8A+gYSN7EA7dPKIMf0pDlSUxhdmVOaV3/fYK5uWBkgSXJaRLr4+3A6g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/canonicalize": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/canonicalize/-/canonicalize-1.0.8.tgz", + "integrity": "sha512-0CNTVCLZggSh7bc5VkX5WWPWO+cyZbNd07IHIsSXLia/eAq+r836hgk+8BKoEh7949Mda87VUOitx5OddVj64A==", + "license": "Apache-2.0" + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chrome-trace-event": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz", + "integrity": "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0" + } + }, + "node_modules/clean-css": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/clean-css/-/clean-css-5.3.3.tgz", + "integrity": "sha512-D5J+kHaVb/wKSFcyyV75uCn8fiY4sV38XJoe4CUyGQ+mOU/fMVYUdH1hJC+CJQ5uY3EnW27SbJYS4X8BiLrAFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "source-map": "~0.6.0" + }, + "engines": { + "node": ">= 10.0" + } + }, + "node_modules/clone-deep": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-4.0.1.tgz", + "integrity": "sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-plain-object": "^2.0.4", + "kind-of": "^6.0.2", + "shallow-clone": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/colorette": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/compressible": { + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz", + "integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": ">= 1.43.0 < 2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/compression": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.1.tgz", + "integrity": "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "compressible": "~2.0.18", + "debug": "2.6.9", + "negotiator": "~0.6.4", + "on-headers": "~1.1.0", + "safe-buffer": "5.2.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/compression/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/compression/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true, + "license": "MIT" + }, + "node_modules/compression/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/connect-history-api-fallback": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/connect-history-api-fallback/-/connect-history-api-fallback-2.0.0.tgz", + "integrity": "sha512-U73+6lQFmfiNPrYbXqr6kZ1i1wiRqXnp2nhMsINseWXO8lDau0LGEffJ8kQi4EjLZympVgRdvqjAgiZ1tgzDDA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-disposition/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "dev": true, + "license": "MIT" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/corser": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/corser/-/corser-2.0.1.tgz", + "integrity": "sha512-utCYNzRSQIZNPIcGZdQc92UVJYAhtGAteCFg0yRaFm8f0P+CPtyGyHXJcGXnffjCybUCEx3FQ2G7U3/o9eIkVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/credentials-context": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/credentials-context/-/credentials-context-2.0.0.tgz", + "integrity": "sha512-/mFKax6FK26KjgV2KW2D4YqKgoJ5DVJpNt87X2Jc9IxT2HBMy7nEIlc+n7pEi+YFFe721XqrvZPd+jbyyBjsvQ==", + "license": "SEE LICENSE IN LICENSE.md" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/crypto-ld": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/crypto-ld/-/crypto-ld-6.0.0.tgz", + "integrity": "sha512-XWL1LslqggNoaCI/m3I7HcvaSt9b2tYzdrXO+jHLUj9G1BvRfvV7ZTFDVY5nifYuIGAPdAGu7unPxLRustw3VA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=8.3.0" + } + }, + "node_modules/css-select": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-4.3.0.tgz", + "integrity": "sha512-wPpOYtnsVontu2mODhA19JrqWxNsfdatRKd64kmpRbQgh1KtItko5sTnEpPdpSaJszTOhEMlF/RPz28qj4HqhQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^6.0.1", + "domhandler": "^4.3.1", + "domutils": "^2.8.0", + "nth-check": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-what": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.2.2.tgz", + "integrity": "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/default-browser": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-5.4.0.tgz", + "integrity": "sha512-XDuvSq38Hr1MdN47EDvYtx3U0MTqpCEn+F6ft8z2vYDzMrvQhVp0ui9oQdqW3MvK3vqUETglt1tVGgjLuJ5izg==", + "dev": true, + "license": "MIT", + "dependencies": { + "bundle-name": "^4.1.0", + "default-browser-id": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/default-browser-id": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/default-browser-id/-/default-browser-id-5.0.1.tgz", + "integrity": "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/define-lazy-prop": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-3.0.0.tgz", + "integrity": "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-node": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz", + "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==", + "dev": true, + "license": "MIT" + }, + "node_modules/did-context": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/did-context/-/did-context-3.1.1.tgz", + "integrity": "sha512-iFpszgSxc7d1kNBJWC+PAzNTpe5LPalzsIunTMIpbG3O37Q7Zi7u4iIaedaM7UhziBhT+Agr9DyvAiXSUyfepQ==", + "license": "SEE LICENSE IN LICENSE.md" + }, + "node_modules/dns-packet": { + "version": "5.6.1", + "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz", + "integrity": "sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@leichtgewicht/ip-codec": "^2.0.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/dom-converter": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/dom-converter/-/dom-converter-0.2.0.tgz", + "integrity": "sha512-gd3ypIPfOMr9h5jIKq8E3sHOTCjeirnl0WK5ZdS1AW0Odt0b1PaWaHdJ4Qk4klv+YB9aJBS7mESXjFoDQPu6DA==", + "dev": true, + "license": "MIT", + "dependencies": { + "utila": "~0.4" + } + }, + "node_modules/dom-serializer": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-1.4.1.tgz", + "integrity": "sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag==", + "dev": true, + "license": "MIT", + "dependencies": { + "domelementtype": "^2.0.1", + "domhandler": "^4.2.0", + "entities": "^2.0.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-4.3.1.tgz", + "integrity": "sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.2.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-2.8.0.tgz", + "integrity": "sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^1.0.1", + "domelementtype": "^2.2.0", + "domhandler": "^4.2.0" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/dot-case": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/dot-case/-/dot-case-3.0.4.tgz", + "integrity": "sha512-Kv5nKlh6yRrdrGvxeJ2e5y2eRUpkUosIW4A2AS38zwSz27zu7ufDwQPi5Jhs3XAlGNetl3bmnGhQsMtkKJnj3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "no-case": "^3.0.4", + "tslib": "^2.0.3" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ed25519-signature-2018-context": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/ed25519-signature-2018-context/-/ed25519-signature-2018-context-1.1.0.tgz", + "integrity": "sha512-ppDWYMNwwp9bploq0fS4l048vHIq41nWsAbPq6H4mNVx9G/GxW3fwg4Ln0mqctP13MoEpREK7Biz8TbVVdYXqA==", + "license": "BSD-3-Clause" + }, + "node_modules/ed25519-signature-2020-context": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/ed25519-signature-2020-context/-/ed25519-signature-2020-context-1.1.0.tgz", + "integrity": "sha512-dBGSmoUIK6h2vadDctrDnhhTO01PR2hJk0mRNEfrRDPCjaIwrfy4J+eziEQ9Q1m8By4f/CSRgKM1h53ydKfdNg==", + "license": "BSD-3-Clause" + }, + "node_modules/ed2curve": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/ed2curve/-/ed2curve-0.3.0.tgz", + "integrity": "sha512-8w2fmmq3hv9rCrcI7g9hms2pMunQr1JINfcjwR9tAyZqhtyaMN991lF/ZfHfr5tzZQ8c7y7aBgZbjfbd0fjFwQ==", + "license": "Unlicense", + "dependencies": { + "tweetnacl": "1.x.x" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "dev": true, + "license": "MIT" + }, + "node_modules/electron-to-chromium": { + "version": "1.5.267", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.267.tgz", + "integrity": "sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==", + "dev": true, + "license": "ISC" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/enhanced-resolve": { + "version": "5.18.4", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.18.4.tgz", + "integrity": "sha512-LgQMM4WXU3QI+SYgEc2liRgznaD5ojbmY3sb8LxyguVkIg5FxdpTkvk72te2R38/TGKxH634oLxXRGY6d7AP+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/entities": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", + "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", + "dev": true, + "license": "BSD-2-Clause", + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/envinfo": { + "version": "7.21.0", + "resolved": "https://registry.npmjs.org/envinfo/-/envinfo-7.21.0.tgz", + "integrity": "sha512-Lw7I8Zp5YKHFCXL7+Dz95g4CcbMEpgvqZNNq3AmlT5XAV6CgAAk6gyAMqn2zjw08K9BHfcNuKrMiCPLByGafow==", + "dev": true, + "license": "MIT", + "bin": { + "envinfo": "dist/cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.0.0.tgz", + "integrity": "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "dev": true, + "license": "MIT" + }, + "node_modules/eslint-scope": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", + "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^4.1.1" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esrecurse/node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", + "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "dev": true, + "license": "MIT" + }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, + "node_modules/express": { + "version": "4.22.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", + "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.3", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.12", + "proxy-addr": "~2.0.7", + "qs": "~6.14.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true, + "license": "MIT" + }, + "node_modules/express/node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fastest-levenshtein": { + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz", + "integrity": "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4.9.1" + } + }, + "node_modules/faye-websocket": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", + "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "websocket-driver": ">=0.5.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true, + "license": "MIT" + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/flat": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz", + "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==", + "dev": true, + "license": "BSD-3-Clause", + "bin": { + "flat": "cli.js" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "license": "MIT", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob-to-regex.js": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/glob-to-regex.js/-/glob-to-regex.js-1.2.0.tgz", + "integrity": "sha512-QMwlOQKU/IzqMUOAZWubUOT8Qft+Y0KQWnX9nK3ch0CJg0tTp4TvGZsTfudYKv2NzoQSyPcnA6TYeIQ3jGichQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/handle-thing": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/handle-thing/-/handle-thing-2.0.1.tgz", + "integrity": "sha512-9Qn4yBxelxoh2Ow62nP+Ka/kMnOXRi8BXnRaUwezLNhqelnN49xKz4F/dPP8OYLxLxq6JDtZb2i9XznUQbNPTg==", + "dev": true, + "license": "MIT" + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "dev": true, + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, + "node_modules/hpack.js": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/hpack.js/-/hpack.js-2.1.6.tgz", + "integrity": "sha512-zJxVehUdMGIKsRaNt7apO2Gqp0BdqW5yaiGHXXmbpvxgBYVZnAql+BJb4RO5ad2MgpbZKn5G6nMnegrH1FcNYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "inherits": "^2.0.1", + "obuf": "^1.0.0", + "readable-stream": "^2.0.1", + "wbuf": "^1.1.0" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-3.0.0.tgz", + "integrity": "sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/html-entities": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.6.0.tgz", + "integrity": "sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/mdevils" + }, + { + "type": "patreon", + "url": "https://patreon.com/mdevils" + } + ], + "license": "MIT" + }, + "node_modules/html-minifier-terser": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/html-minifier-terser/-/html-minifier-terser-6.1.0.tgz", + "integrity": "sha512-YXxSlJBZTP7RS3tWnQw74ooKa6L9b9i9QYXY21eUEvhZ3u9XLfv6OnFsQq6RxkhHygsaUMvYsZRV5rU/OVNZxw==", + "dev": true, + "license": "MIT", + "dependencies": { + "camel-case": "^4.1.2", + "clean-css": "^5.2.2", + "commander": "^8.3.0", + "he": "^1.2.0", + "param-case": "^3.0.4", + "relateurl": "^0.2.7", + "terser": "^5.10.0" + }, + "bin": { + "html-minifier-terser": "cli.js" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/html-minifier-terser/node_modules/commander": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz", + "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/html-webpack-plugin": { + "version": "5.6.5", + "resolved": "https://registry.npmjs.org/html-webpack-plugin/-/html-webpack-plugin-5.6.5.tgz", + "integrity": "sha512-4xynFbKNNk+WlzXeQQ+6YYsH2g7mpfPszQZUi3ovKlj+pDmngQ7vRXjrrmGROabmKwyQkcgcX5hqfOwHbFmK5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/html-minifier-terser": "^6.0.0", + "html-minifier-terser": "^6.0.2", + "lodash": "^4.17.21", + "pretty-error": "^4.0.0", + "tapable": "^2.0.0" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/html-webpack-plugin" + }, + "peerDependencies": { + "@rspack/core": "0.x || 1.x", + "webpack": "^5.20.0" + }, + "peerDependenciesMeta": { + "@rspack/core": { + "optional": true + }, + "webpack": { + "optional": true + } + } + }, + "node_modules/htmlparser2": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-6.1.0.tgz", + "integrity": "sha512-gyyPk6rgonLFEDGoeRgQNaEUvdJ4ktTmmUh/h2t7s+M8oPpIPxgNACWa+6ESR57kXstwqPiCut0V8NRpcwgU7A==", + "dev": true, + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.0.1", + "domhandler": "^4.0.0", + "domutils": "^2.5.2", + "entities": "^2.0.0" + } + }, + "node_modules/http-deceiver": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/http-deceiver/-/http-deceiver-1.2.7.tgz", + "integrity": "sha512-LmpOGxTfbpgtGVxJrj5k7asXHCgNZp5nLfp+hWc8QQRqtb7fUy6kRY3BO1h9ddF6yIPYUARgxGOwB42DnxIaNw==", + "dev": true, + "license": "MIT" + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/http-parser-js": { + "version": "0.5.10", + "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.10.tgz", + "integrity": "sha512-Pysuw9XpUq5dVc/2SMHpuTY01RFl8fttgcyunjL7eEMhGM3cI4eOmiCycJDVCo/7O7ClfQD3SaI6ftDzqOXYMA==", + "dev": true, + "license": "MIT" + }, + "node_modules/http-proxy": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", + "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/http-proxy-middleware": { + "version": "2.0.9", + "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.9.tgz", + "integrity": "sha512-c1IyJYLYppU574+YI7R4QyX2ystMtVXZwIdzazUIPIJsHuWNd+mho2j+bKoHftndicGj9yh+xjd+l0yj7VeT1Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/http-proxy": "^1.17.8", + "http-proxy": "^1.18.1", + "is-glob": "^4.0.1", + "is-plain-obj": "^3.0.0", + "micromatch": "^4.0.2" + }, + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "@types/express": "^4.17.13" + }, + "peerDependenciesMeta": { + "@types/express": { + "optional": true + } + } + }, + "node_modules/http-server": { + "version": "14.1.1", + "resolved": "https://registry.npmjs.org/http-server/-/http-server-14.1.1.tgz", + "integrity": "sha512-+cbxadF40UXd9T01zUHgA+rlo2Bg1Srer4+B4NwIHdaGxAGGv59nYRnGGDJ9LBk7alpS0US+J+bLLdQOOkJq4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "basic-auth": "^2.0.1", + "chalk": "^4.1.2", + "corser": "^2.0.1", + "he": "^1.2.0", + "html-encoding-sniffer": "^3.0.0", + "http-proxy": "^1.18.1", + "mime": "^1.6.0", + "minimist": "^1.2.6", + "opener": "^1.5.1", + "portfinder": "^1.0.28", + "secure-compare": "3.0.1", + "union": "~0.5.0", + "url-join": "^4.0.1" + }, + "bin": { + "http-server": "bin/http-server" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/hyperdyperid": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/hyperdyperid/-/hyperdyperid-1.2.0.tgz", + "integrity": "sha512-Y93lCzHYgGWdrJ66yIktxiaGULYc6oGiABxhcO5AufBeOyoIdZF7bIfLaOrbM0iGIOXQQgxxRrFEnb+Y6w1n4A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.18" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/import-local": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", + "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/interpret": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-3.1.1.tgz", + "integrity": "sha512-6xwYfHbajpoF0xLW+iwLkhwgvLoZDfjYfoFNu8ftMoXINzwuymNLd9u/KmwtdT2GbR+/Cz66otEGEVVUHX9QLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/ipaddr.js": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.3.0.tgz", + "integrity": "sha512-Zv/pA+ciVFbCSBBjGfaKUya/CcGmUHzTydLMaTwrUUEM2DIEO3iZvueGxmacvmN50fGpGVKeTXpb2LcYQxeVdg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-docker": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz", + "integrity": "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==", + "dev": true, + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-inside-container": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz", + "integrity": "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-docker": "^3.0.0" + }, + "bin": { + "is-inside-container": "cli.js" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-network-error": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/is-network-error/-/is-network-error-1.3.0.tgz", + "integrity": "sha512-6oIwpsgRfnDiyEDLMay/GqCl3HoAtH5+RUKW29gYkL0QA+ipzpDLA16yQs7/RHCSu+BwgbJaOUqa4A99qNVQVw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-plain-obj": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-3.0.0.tgz", + "integrity": "sha512-gwsOE28k+23GP1B6vFl1oVh/WOzmawBrKwo5Ev6wMKzPkaXaCDIQKzLnvsA42DRlbVTWorkgTKIviAKCWkfUwA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "license": "MIT", + "dependencies": { + "isobject": "^3.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-wsl": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.0.tgz", + "integrity": "sha512-UcVfVfaK4Sc4m7X3dUSoHoozQGBEFeDC+zVo06t98xe8CzHSZZBekNXH+tu0NalHolcJ/QAGqS46Hef7QXBIMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-inside-container": "^1.0.0" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/jest-worker": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", + "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/jest-worker/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsonld": { + "version": "8.3.3", + "resolved": "https://registry.npmjs.org/jsonld/-/jsonld-8.3.3.tgz", + "integrity": "sha512-9YcilrF+dLfg9NTEof/mJLMtbdX1RJ8dbWtJgE00cMOIohb1lIyJl710vFiTaiHTl6ZYODJuBd32xFvUhmv3kg==", + "license": "BSD-3-Clause", + "dependencies": { + "@digitalbazaar/http-client": "^3.4.1", + "canonicalize": "^1.0.1", + "lru-cache": "^6.0.0", + "rdf-canonize": "^3.4.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/jsonld-document-loader": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/jsonld-document-loader/-/jsonld-document-loader-1.2.1.tgz", + "integrity": "sha512-CtFyIBZApeVvs6QgyS7Gcp8h1dUs+1XNHcV4Sr6O9ItPaL0hVgqe47Tgs3RNH0A5Bc4p3UFPKAJVHKSOQq4mhQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/jsonld-signatures": { + "version": "11.5.0", + "resolved": "https://registry.npmjs.org/jsonld-signatures/-/jsonld-signatures-11.5.0.tgz", + "integrity": "sha512-Kdto+e8uvY/5u3HYkmAbpy52bplWX9uqS8fmqdCv6oxnCFwCTM0hMt6r4rWqlhw5/aHoCHJIRxwYb4QKGC69Jw==", + "license": "BSD-3-Clause", + "dependencies": { + "@digitalbazaar/security-context": "^1.0.0", + "jsonld": "^8.0.0", + "rdf-canonize": "^4.0.1", + "serialize-error": "^8.1.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/jsonld/node_modules/rdf-canonize": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/rdf-canonize/-/rdf-canonize-3.4.0.tgz", + "integrity": "sha512-fUeWjrkOO0t1rg7B2fdyDTvngj+9RlUyL92vOdiB7c0FPguWVsniIMjEtHH+meLBO9rzkUlUzBVXgWrjI8P9LA==", + "license": "BSD-3-Clause", + "dependencies": { + "setimmediate": "^1.0.5" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/klona": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/klona/-/klona-2.0.6.tgz", + "integrity": "sha512-dhG34DXATL5hSxJbIexCft8FChFXtmskoZYnoPWjXQuebWYCNkVeV3KkGegCK9CP1oswI/vQibS2GY7Em/sJJA==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/ky": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/ky/-/ky-1.14.1.tgz", + "integrity": "sha512-hYje4L9JCmpEQBtudo+v52X5X8tgWXUYyPcxKSuxQNboqufecl9VMWjGiucAFH060AwPXHZuH+WB2rrqfkmafw==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sindresorhus/ky?sponsor=1" + } + }, + "node_modules/ky-universal": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/ky-universal/-/ky-universal-0.11.0.tgz", + "integrity": "sha512-65KyweaWvk+uKKkCrfAf+xqN2/epw1IJDtlyCPxYffFCMR8u1sp2U65NtWpnozYfZxQ6IUzIlvUcw+hQ82U2Xw==", + "license": "MIT", + "dependencies": { + "abort-controller": "^3.0.0", + "node-fetch": "^3.2.10" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sindresorhus/ky-universal?sponsor=1" + }, + "peerDependencies": { + "ky": ">=0.31.4", + "web-streams-polyfill": ">=3.2.1" + }, + "peerDependenciesMeta": { + "web-streams-polyfill": { + "optional": true + } + } + }, + "node_modules/launch-editor": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.12.0.tgz", + "integrity": "sha512-giOHXoOtifjdHqUamwKq6c49GzBdLjvxrd2D+Q4V6uOHopJv7p9VJxikDsQ/CBXZbEITgUqSVHXLTG3VhPP1Dg==", + "dev": true, + "license": "MIT", + "dependencies": { + "picocolors": "^1.1.1", + "shell-quote": "^1.8.3" + } + }, + "node_modules/loader-runner": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.1.tgz", + "integrity": "sha512-IWqP2SCPhyVFTBtRcgMHdzlf9ul25NwaFx4wCEH/KjAXuuHY4yNjvPXsBokp8jCB936PyWRaPKUNh8NvylLp2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.11.5" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true, + "license": "MIT" + }, + "node_modules/lower-case": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-2.0.2.tgz", + "integrity": "sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.0.3" + } + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/marked": { + "version": "17.0.1", + "resolved": "https://registry.npmjs.org/marked/-/marked-17.0.1.tgz", + "integrity": "sha512-boeBdiS0ghpWcSwoNm/jJBwdpFaMnZWRzjA6SkUMYb40SVaN1x7mmfGKp0jvexGcx+7y2La5zRZsYFZI6Qpypg==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/memfs": { + "version": "4.51.1", + "resolved": "https://registry.npmjs.org/memfs/-/memfs-4.51.1.tgz", + "integrity": "sha512-Eyt3XrufitN2ZL9c/uIRMyDwXanLI88h/L3MoWqNY747ha3dMR9dWqp8cRT5ntjZ0U1TNuq4U91ZXK0sMBjYOQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jsonjoy.com/json-pack": "^1.11.0", + "@jsonjoy.com/util": "^1.9.0", + "glob-to-regex.js": "^1.0.1", + "thingies": "^2.5.0", + "tree-dump": "^1.0.3", + "tslib": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/micromatch/node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "dev": true, + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "dev": true, + "license": "ISC" + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/multicast-dns": { + "version": "7.2.5", + "resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-7.2.5.tgz", + "integrity": "sha512-2eznPJP8z2BFLX50tf0LuODrpINqP1RVIm/CObbTcBRITQgmC/TjcREF1NeTBzIcR5XO/ukWo+YHOjBbFwIupg==", + "dev": true, + "license": "MIT", + "dependencies": { + "dns-packet": "^5.2.2", + "thunky": "^1.0.2" + }, + "bin": { + "multicast-dns": "cli.js" + } + }, + "node_modules/negotiator": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.4.tgz", + "integrity": "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/neo-async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", + "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", + "dev": true, + "license": "MIT" + }, + "node_modules/no-case": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/no-case/-/no-case-3.0.4.tgz", + "integrity": "sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==", + "dev": true, + "license": "MIT", + "dependencies": { + "lower-case": "^2.0.2", + "tslib": "^2.0.3" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz", + "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", + "license": "MIT", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/node-forge": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.3.3.tgz", + "integrity": "sha512-rLvcdSyRCyouf6jcOIPe/BgwG/d7hKjzMKOas33/pHEr6gbq18IK9zV7DiPvzsz0oBJPme6qr6H6kGZuI9/DZg==", + "dev": true, + "license": "(BSD-3-Clause OR GPL-2.0)", + "engines": { + "node": ">= 6.13.0" + } + }, + "node_modules/node-releases": { + "version": "2.0.27", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz", + "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/nth-check": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", + "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0" + }, + "funding": { + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/obuf": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/obuf/-/obuf-1.1.2.tgz", + "integrity": "sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg==", + "dev": true, + "license": "MIT" + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz", + "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/open": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/open/-/open-10.2.0.tgz", + "integrity": "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==", + "dev": true, + "license": "MIT", + "dependencies": { + "default-browser": "^5.2.1", + "define-lazy-prop": "^3.0.0", + "is-inside-container": "^1.0.0", + "wsl-utils": "^0.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/opener": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz", + "integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==", + "dev": true, + "license": "(WTFPL OR MIT)", + "bin": { + "opener": "bin/opener-bin.js" + } + }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-retry": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-6.2.1.tgz", + "integrity": "sha512-hEt02O4hUct5wtwg4H4KcWgDdm+l1bOaEy/hWzd8xtXB9BqxTWBBhb+2ImAtH4Cv4rPjV76xN3Zumqk3k3AhhQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/retry": "0.12.2", + "is-network-error": "^1.0.0", + "retry": "^0.13.1" + }, + "engines": { + "node": ">=16.17" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/pako": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz", + "integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==", + "license": "(MIT AND Zlib)" + }, + "node_modules/param-case": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/param-case/-/param-case-3.0.4.tgz", + "integrity": "sha512-RXlj7zCYokReqWpOPH9oYivUzLYZ5vAPIfEmCTNViosC78F8F0H9y7T7gG2M39ymgutxF5gcFEsyZQSph9Bp3A==", + "dev": true, + "license": "MIT", + "dependencies": { + "dot-case": "^3.0.4", + "tslib": "^2.0.3" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/pascal-case": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/pascal-case/-/pascal-case-3.1.2.tgz", + "integrity": "sha512-uWlGT3YSnK9x3BQJaOdcZwrnV6hPpd8jFH1/ucpiLRPh/2zCVJKS19E4GvYHvaCcACn3foXZ0cLB9Wrx1KGe5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "no-case": "^3.0.4", + "tslib": "^2.0.3" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-to-regexp": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/playwright": { + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.57.0.tgz", + "integrity": "sha512-ilYQj1s8sr2ppEJ2YVadYBN0Mb3mdo9J0wQ+UuDhzYqURwSoW4n1Xs5vs7ORwgDGmyEh33tRMeS8KhdkMoLXQw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.57.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.57.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.57.0.tgz", + "integrity": "sha512-agTcKlMw/mjBWOnD6kFZttAAGHgi/Nw0CZ2o6JqWSbMlI219lAFLZZCyqByTsvVAJq5XA5H8cA6PrvBRpBWEuQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/playwright/node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/portfinder": { + "version": "1.0.38", + "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.38.tgz", + "integrity": "sha512-rEwq/ZHlJIKw++XtLAO8PPuOQA/zaPJOZJ37BVuN97nLpMJeuDVLVGRwbFoBgLudgdTMP2hdRJP++H+8QOA3vg==", + "dev": true, + "license": "MIT", + "dependencies": { + "async": "^3.2.6", + "debug": "^4.3.6" + }, + "engines": { + "node": ">= 10.12" + } + }, + "node_modules/pretty-error": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-4.0.0.tgz", + "integrity": "sha512-AoJ5YMAcXKYxKhuJGdcvse+Voc6v1RgnsR3nWcYU7q4t6z0Q6T86sv5Zq8VIRbOWWFpvdGE83LtdSMNd+6Y0xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "lodash": "^4.17.20", + "renderkid": "^3.0.0" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "dev": true, + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/proxy-addr/node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/raw-body/node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rdf-canonize": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/rdf-canonize/-/rdf-canonize-4.0.1.tgz", + "integrity": "sha512-B5ynHt4sasbUafzrvYI2GFARgeFcD8Sx9yXPbg7gEyT2EH76rlCv84kyO6tnxzVbxUN/uJDbK1S/MXh+DsnuTA==", + "license": "BSD-3-Clause", + "dependencies": { + "setimmediate": "^1.0.5" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "dev": true, + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/readdirp/node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/rechoir": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.8.0.tgz", + "integrity": "sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve": "^1.20.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/relateurl": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/relateurl/-/relateurl-0.2.7.tgz", + "integrity": "sha512-G08Dxvm4iDN3MLM0EsP62EDV9IuhXPR6blNz6Utcp7zyV3tr4HVNINt6MpaRWbxoOHT3Q7YN2P+jaHX8vUbgog==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/renderkid": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/renderkid/-/renderkid-3.0.0.tgz", + "integrity": "sha512-q/7VIQA8lmM1hF+jn+sFSPWGlMkSAeNYcPLmDQx2zzuiDfaLrOmumR8iaUKlenFgh0XRPIUeSPlH3A+AW3Z5pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-select": "^4.1.3", + "dom-converter": "^0.2.0", + "htmlparser2": "^6.1.0", + "lodash": "^4.17.21", + "strip-ansi": "^6.0.1" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/resolve": { + "version": "1.22.11", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", + "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/run-applescript": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.1.0.tgz", + "integrity": "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/schema-utils": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.3.3.tgz", + "integrity": "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.9", + "ajv": "^8.9.0", + "ajv-formats": "^2.1.1", + "ajv-keywords": "^5.1.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/schema-utils/node_modules/ajv-formats": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", + "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/secure-compare": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/secure-compare/-/secure-compare-3.0.1.tgz", + "integrity": "sha512-AckIIV90rPDcBcglUwXPF3kg0P0qmPsPXAj6BBEENQE1p5yA1xfmDJzfi1Tappj37Pv2mVbKpL3Z1T+Nn7k1Qw==", + "dev": true, + "license": "MIT" + }, + "node_modules/select-hose": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/select-hose/-/select-hose-2.0.0.tgz", + "integrity": "sha512-mEugaLK+YfkijB4fx0e6kImuJdCIt2LxCRcbEYPqRGCs4F2ogyfZU5IAZRdjCP8JPq2AtdNoC/Dux63d9Kiryg==", + "dev": true, + "license": "MIT" + }, + "node_modules/selfsigned": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/selfsigned/-/selfsigned-2.4.1.tgz", + "integrity": "sha512-th5B4L2U+eGLq1TVh7zNRGBapioSORUeymIydxgFpwww9d2qyKvtuPU2jJuHvYAwwqi2Y596QBL3eEqcPEYL8Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node-forge": "^1.3.0", + "node-forge": "^1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true, + "license": "MIT" + }, + "node_modules/serialize-error": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-8.1.0.tgz", + "integrity": "sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==", + "license": "MIT", + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/serialize-javascript": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", + "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/serve-index": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/serve-index/-/serve-index-1.9.1.tgz", + "integrity": "sha512-pXHfKNP4qujrtteMrSBb0rc8HJ9Ms/GrXwcUtUtD5s4ewDJI8bT3Cz2zTVRMKtri49pLx2e0Ya8ziP5Ya2pZZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "accepts": "~1.3.4", + "batch": "0.6.1", + "debug": "2.6.9", + "escape-html": "~1.0.3", + "http-errors": "~1.6.2", + "mime-types": "~2.1.17", + "parseurl": "~1.3.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/serve-index/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/serve-index/node_modules/depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/serve-index/node_modules/http-errors": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz", + "integrity": "sha512-lks+lVC8dgGyh97jxvxeYTWQFvh4uw4yC12gVl63Cg30sjPX4wuGcdkICVXDAESr6OJGjqGA8Iz5mkeN6zlD7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.0", + "statuses": ">= 1.4.0 < 2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/serve-index/node_modules/inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha512-x00IRNXNy63jwGkJmzPigoySHbaqpNuzKbBOmzK+g2OdZpQ9w+sxCN+VSB3ja7IAge2OP2qpfxTjeNcyjmW1uw==", + "dev": true, + "license": "ISC" + }, + "node_modules/serve-index/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true, + "license": "MIT" + }, + "node_modules/serve-index/node_modules/setprototypeof": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", + "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/serve-index/node_modules/statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "dev": true, + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", + "license": "MIT" + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true, + "license": "ISC" + }, + "node_modules/shallow-clone": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz", + "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==", + "dev": true, + "license": "MIT", + "dependencies": { + "kind-of": "^6.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/shell-quote": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz", + "integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/sockjs": { + "version": "0.3.24", + "resolved": "https://registry.npmjs.org/sockjs/-/sockjs-0.3.24.tgz", + "integrity": "sha512-GJgLTZ7vYb/JtPSSZ10hsOYIvEYsjbNU+zPdIHcUaWVNUEPivzxku31865sSSud0Da0W4lEeOPlmw93zLQchuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "faye-websocket": "^0.11.3", + "uuid": "^8.3.2", + "websocket-driver": "^0.7.4" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/spdy": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/spdy/-/spdy-4.0.2.tgz", + "integrity": "sha512-r46gZQZQV+Kl9oItvl1JZZqJKGr+oEkB08A6BzkiR7593/7IbtuncXHd2YoYeTsG4157ZssMu9KYvUHLcjcDoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.1.0", + "handle-thing": "^2.0.0", + "http-deceiver": "^1.2.7", + "select-hose": "^2.0.0", + "spdy-transport": "^3.0.0" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/spdy-transport": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdy-transport/-/spdy-transport-3.0.0.tgz", + "integrity": "sha512-hsLVFE5SjA6TCisWeJXFKniGGOpBgMLmerfO2aCyCU5s7nJ/rpAepqmFifv/GCbSbueEeAJJnmSQ2rKC/g8Fcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.1.0", + "detect-node": "^2.0.4", + "hpack.js": "^2.1.6", + "obuf": "^1.1.2", + "readable-stream": "^3.0.6", + "wbuf": "^1.7.3" + } + }, + "node_modules/spdy-transport/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tapable": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.0.tgz", + "integrity": "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/terser": { + "version": "5.44.1", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.44.1.tgz", + "integrity": "sha512-t/R3R/n0MSwnnazuPpPNVO60LX0SKL45pyl9YlvxIdkH0Of7D5qM2EVe+yASRIlY5pZ73nclYJfNANGWPwFDZw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.15.0", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser-webpack-plugin": { + "version": "5.3.16", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.3.16.tgz", + "integrity": "sha512-h9oBFCWrq78NyWWVcSwZarJkZ01c2AyGrzs1crmHZO3QUg9D61Wu4NPjBy69n7JqylFF5y+CsUZYmYEIZ3mR+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.25", + "jest-worker": "^27.4.5", + "schema-utils": "^4.3.0", + "serialize-javascript": "^6.0.2", + "terser": "^5.31.1" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "uglify-js": { + "optional": true + } + } + }, + "node_modules/thingies": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/thingies/-/thingies-2.5.0.tgz", + "integrity": "sha512-s+2Bwztg6PhWUD7XMfeYm5qliDdSiZm7M7n8KjTkIsm3l/2lgVRc2/Gx/v+ZX8lT4FMA+i8aQvhcWylldc+ZNw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "^2" + } + }, + "node_modules/thunky": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz", + "integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==", + "dev": true, + "license": "MIT" + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tree-dump": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/tree-dump/-/tree-dump-1.1.0.tgz", + "integrity": "sha512-rMuvhU4MCDbcbnleZTFezWsaZXRFemSqAM+7jPnzUl1fo9w3YEKOxAeui0fz3OI4EU4hf23iyA7uQRVko+UaBA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=10.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/streamich" + }, + "peerDependencies": { + "tslib": "2" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD" + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "license": "Unlicense" + }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/undici": { + "version": "6.22.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.22.0.tgz", + "integrity": "sha512-hU/10obOIu62MGYjdskASR3CUAiYaFTtC9Pa6vHyf//mAipSvSQg6od2CnJswq7fvzNS3zJhxoRkgNVaHurWKw==", + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "dev": true, + "license": "MIT" + }, + "node_modules/union": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/union/-/union-0.5.0.tgz", + "integrity": "sha512-N6uOhuW6zO95P3Mel2I2zMsbsanvvtgn6jVqJv4vbVcz/JN0OkL9suomjQGmWtxJQXOCqUJvquc1sMeNz/IwlA==", + "dev": true, + "dependencies": { + "qs": "^6.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/url-join": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-4.0.1.tgz", + "integrity": "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==", + "dev": true, + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/utila": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/utila/-/utila-0.4.0.tgz", + "integrity": "sha512-Z0DbgELS9/L/75wZbro8xAnT50pBVFQZ+hUEueGDU5FN51YSCYM+jdxsfCiHjwNP/4LCDD0i/graKpeBnOXKRA==", + "dev": true, + "license": "MIT" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "dev": true, + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/watchpack": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.5.0.tgz", + "integrity": "sha512-e6vZvY6xboSwLz2GD36c16+O/2Z6fKvIf4pOXptw2rY9MVwE/TXc6RGqxD3I3x0a28lwBY7DE+76uTPSsBrrCA==", + "dev": true, + "license": "MIT", + "dependencies": { + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/wbuf": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/wbuf/-/wbuf-1.7.3.tgz", + "integrity": "sha512-O84QOnr0icsbFGLS0O3bI5FswxzRr8/gHwWkDlQFskhSPryQXvrTMxjxGP4+iWYoauLoBvfDpkrOauZ+0iZpDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "minimalistic-assert": "^1.0.0" + } + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/webpack": { + "version": "5.104.1", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.104.1.tgz", + "integrity": "sha512-Qphch25abbMNtekmEGJmeRUhLDbe+QfiWTiqpKYkpCOWY64v9eyl+KRRLmqOFA2AvKPpc9DC6+u2n76tQLBoaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/eslint-scope": "^3.7.7", + "@types/estree": "^1.0.8", + "@types/json-schema": "^7.0.15", + "@webassemblyjs/ast": "^1.14.1", + "@webassemblyjs/wasm-edit": "^1.14.1", + "@webassemblyjs/wasm-parser": "^1.14.1", + "acorn": "^8.15.0", + "acorn-import-phases": "^1.0.3", + "browserslist": "^4.28.1", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.17.4", + "es-module-lexer": "^2.0.0", + "eslint-scope": "5.1.1", + "events": "^3.2.0", + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.2.11", + "json-parse-even-better-errors": "^2.3.1", + "loader-runner": "^4.3.1", + "mime-types": "^2.1.27", + "neo-async": "^2.6.2", + "schema-utils": "^4.3.3", + "tapable": "^2.3.0", + "terser-webpack-plugin": "^5.3.16", + "watchpack": "^2.4.4", + "webpack-sources": "^3.3.3" + }, + "bin": { + "webpack": "bin/webpack.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/webpack-cli": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-6.0.1.tgz", + "integrity": "sha512-MfwFQ6SfwinsUVi0rNJm7rHZ31GyTcpVE5pgVA3hwFRb7COD4TzjUUwhGWKfO50+xdc2MQPuEBBJoqIMGt3JDw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@discoveryjs/json-ext": "^0.6.1", + "@webpack-cli/configtest": "^3.0.1", + "@webpack-cli/info": "^3.0.1", + "@webpack-cli/serve": "^3.0.1", + "colorette": "^2.0.14", + "commander": "^12.1.0", + "cross-spawn": "^7.0.3", + "envinfo": "^7.14.0", + "fastest-levenshtein": "^1.0.12", + "import-local": "^3.0.2", + "interpret": "^3.1.1", + "rechoir": "^0.8.0", + "webpack-merge": "^6.0.1" + }, + "bin": { + "webpack-cli": "bin/cli.js" + }, + "engines": { + "node": ">=18.12.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.82.0" + }, + "peerDependenciesMeta": { + "webpack-bundle-analyzer": { + "optional": true + }, + "webpack-dev-server": { + "optional": true + } + } + }, + "node_modules/webpack-cli/node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/webpack-dev-middleware": { + "version": "7.4.5", + "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-7.4.5.tgz", + "integrity": "sha512-uxQ6YqGdE4hgDKNf7hUiPXOdtkXvBJXrfEGYSx7P7LC8hnUYGK70X6xQXUvXeNyBDDcsiQXpG2m3G9vxowaEuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "colorette": "^2.0.10", + "memfs": "^4.43.1", + "mime-types": "^3.0.1", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "schema-utils": "^4.0.0" + }, + "engines": { + "node": ">= 18.12.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.0.0" + }, + "peerDependenciesMeta": { + "webpack": { + "optional": true + } + } + }, + "node_modules/webpack-dev-middleware/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/webpack-dev-middleware/node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/webpack-dev-server": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-5.2.2.tgz", + "integrity": "sha512-QcQ72gh8a+7JO63TAx/6XZf/CWhgMzu5m0QirvPfGvptOusAxG12w2+aua1Jkjr7hzaWDnJ2n6JFeexMHI+Zjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/bonjour": "^3.5.13", + "@types/connect-history-api-fallback": "^1.5.4", + "@types/express": "^4.17.21", + "@types/express-serve-static-core": "^4.17.21", + "@types/serve-index": "^1.9.4", + "@types/serve-static": "^1.15.5", + "@types/sockjs": "^0.3.36", + "@types/ws": "^8.5.10", + "ansi-html-community": "^0.0.8", + "bonjour-service": "^1.2.1", + "chokidar": "^3.6.0", + "colorette": "^2.0.10", + "compression": "^1.7.4", + "connect-history-api-fallback": "^2.0.0", + "express": "^4.21.2", + "graceful-fs": "^4.2.6", + "http-proxy-middleware": "^2.0.9", + "ipaddr.js": "^2.1.0", + "launch-editor": "^2.6.1", + "open": "^10.0.3", + "p-retry": "^6.2.0", + "schema-utils": "^4.2.0", + "selfsigned": "^2.4.1", + "serve-index": "^1.9.1", + "sockjs": "^0.3.24", + "spdy": "^4.0.2", + "webpack-dev-middleware": "^7.4.2", + "ws": "^8.18.0" + }, + "bin": { + "webpack-dev-server": "bin/webpack-dev-server.js" + }, + "engines": { + "node": ">= 18.12.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.0.0" + }, + "peerDependenciesMeta": { + "webpack": { + "optional": true + }, + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/webpack-merge": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-6.0.1.tgz", + "integrity": "sha512-hXXvrjtx2PLYx4qruKl+kyRSLc52V+cCvMxRjmKwoA+CBbbF5GfIBtR6kCvl0fYGqTUPKB+1ktVmTHqMOzgCBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "clone-deep": "^4.0.1", + "flat": "^5.0.2", + "wildcard": "^2.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/webpack-sources": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.3.3.tgz", + "integrity": "sha512-yd1RBzSGanHkitROoPFd6qsrxt+oFhg/129YzheDGqeustzX0vTZJZsSsQjVQC4yzBQ56K55XU8gaNCtIzOnTg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/websocket-driver": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz", + "integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "http-parser-js": ">=0.5.1", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/websocket-extensions": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", + "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/whatwg-encoding": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-2.0.0.tgz", + "integrity": "sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wildcard": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/wildcard/-/wildcard-2.0.1.tgz", + "integrity": "sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/ws": { + "version": "8.18.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", + "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/wsl-utils": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-0.1.0.tgz", + "integrity": "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-wsl": "^3.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/x25519-key-agreement-2020-context": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/x25519-key-agreement-2020-context/-/x25519-key-agreement-2020-context-1.0.0.tgz", + "integrity": "sha512-zblYd8oSg6hNAD+fA9X7ek1hJQRircl3jVlEVCaBTNN9Mv9b4G32uJvRZFMQEMmda8iaTtYo9i2dRMdXX8pjpA==", + "license": "BSD-3-Clause" + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "license": "ISC" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..3c03dc8 --- /dev/null +++ b/package.json @@ -0,0 +1,43 @@ +{ + "name": "@digitalcredentials/veri-good", + "version": "0.0.0-beta.3", + "description": "web component for verification", + "module": "src/index.js", + "main": "src/index.js", + "type": "module", + "scripts": { + "start": "http-server -c-1 -p 8080", + "start-wp": "webpack serve --open", + "test": "echo \"Error: no test specified\" && exit 1", + "build": "webpack", + "test:playwright:unit-ui": "playwright test --grep @unit-ui --workers=4 --reporter=html" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/digitalcredentials/veri-good.git" + }, + "author": "James Chartrand", + "license": "MIT", + "bugs": { + "url": "https://github.com/digitalcredentials/veri-good/issues" + }, + "homepage": "https://github.com/digitalcredentials/veri-good#readme", + "devDependencies": { + "@playwright/test": "^1.57.0", + "html-webpack-plugin": "^5.6.5", + "http-server": "^14.1.1", + "webpack": "^5.104.1", + "webpack-cli": "^6.0.1", + "webpack-dev-server": "^5.2.2" + }, + "dependencies": { + "@digitalbazaar/data-integrity": "^2.5.0", + "@digitalbazaar/ed25519-signature-2020": "^5.4.0", + "@digitalbazaar/eddsa-rdfc-2022-cryptosuite": "^1.2.0", + "@digitalbazaar/vc": "^7.2.0", + "@digitalbazaar/vc-bitstring-status-list": "^2.0.1", + "@digitalcredentials/security-document-loader": "^8.0.0", + "jsonld-signatures": "^11.5.0", + "marked": "^17.0.1" + } +} diff --git a/playwright.config.js b/playwright.config.js new file mode 100644 index 0000000..b809e4b --- /dev/null +++ b/playwright.config.js @@ -0,0 +1,21 @@ +import { defineConfig, devices } from '@playwright/test'; + +export default defineConfig({ + testDir: './tests/', + timeout: 30_000, + expect: { timeout: 8_000 }, + use: { + headless: true, + baseURL: process.env.BASE_URL ?? 'http://localhost:8080', + trace: 'on-first-retry', + screenshot: 'only-on-failure', + video: 'retain-on-failure', + }, + projects: [ + { name: 'Chromium', use: { ...devices['Desktop Chrome'] } }, + { name: 'WebKit', use: { ...devices['Desktop Safari'] } }, + { name: 'Firefox', use: { ...devices['Desktop Firefox'] } }, + ], + // Optional: auto-run your dev server for local runs + // webServer: { command: 'npm run dev', port: 3001, reuseExistingServer: !process.env.CI }, +}); \ No newline at end of file diff --git a/src/checkStatusDirectly.js b/src/checkStatusDirectly.js new file mode 100644 index 0000000..62a2f9c --- /dev/null +++ b/src/checkStatusDirectly.js @@ -0,0 +1,56 @@ +import { Ed25519Signature2020 } from '@digitalbazaar/ed25519-signature-2020'; +import { DataIntegrityProof } from '@digitalbazaar/data-integrity'; +import { cryptosuite as eddsaRdfc2022CryptoSuite } from '@digitalbazaar/eddsa-rdfc-2022-cryptosuite'; +const eddsaSuite = new DataIntegrityProof({ cryptosuite: eddsaRdfc2022CryptoSuite }); +const ed25519Suite = new Ed25519Signature2020(); +const suite = [ed25519Suite, eddsaSuite] +import * as vc from '@digitalbazaar/vc'; + +import {extendContextLoader} from 'jsonld-signatures'; +import { checkStatus } from '@digitalbazaar/vc-bitstring-status-list'; + +// we need to use our own document loader +// so we can run the fetch to get the +// status list, without preflight calls +// that cause CORS errors +const {defaultDocumentLoader} = vc; +const statusDocumentLoader = extendContextLoader(async url => { + if(url.startsWith('http')) { + const response = await fetch(url); + const document = await response.json(); + return { + contextUrl: null, + documentUrl: url, + document + }; + } + return defaultDocumentLoader(url); +}); + +const checkStatusDirectly = async (credential) => { + if (credential.credentialStatus) { + const checkStatus = getStatusChecker(credential) + const statusResult = await checkStatus({credential, documentLoader: statusDocumentLoader, suite, verifyMatchingIssuers: false, verifyBitstringStatusListCredential: false}) + // the result.status is 'true' if revoked + const isRevoked = statusResult.results.some(result=>result.status) + if (isRevoked) { + return {valid: false, message: 'Has been revoked'} + } else { + return {valid: true, message: 'Has not been revoked'} + } + } else { + return {valid: true, message: 'Has not been revoked'} + } +} + + +const getStatusChecker = (credential) => { + if (!credential.credentialStatus) return null; + const {credentialStatus} = credential; + const credentialStatuses = [].concat(credentialStatus) + return credentialStatuses.some( status => status.type === 'BitstringStatusListEntry') ? + checkStatus : + ()=>{return {verified:true}} +} + +export default checkStatusDirectly \ No newline at end of file diff --git a/src/constants.js b/src/constants.js new file mode 100644 index 0000000..08d21fc --- /dev/null +++ b/src/constants.js @@ -0,0 +1,3 @@ +export const VERIFYING_SIG_MSG = 'Verifying signature...' +export const VERIFYING_EXP_MSG = 'Checking expiration...' +export const VERIFYING_REV_MSG = 'Checking status...' \ No newline at end of file diff --git a/src/displayResults.js b/src/displayResults.js new file mode 100644 index 0000000..aeb1a02 --- /dev/null +++ b/src/displayResults.js @@ -0,0 +1,89 @@ +import { sleep, showElement, hideElement, getElement, showText, displayError } from "./displayUtils.js"; +import { marked } from "marked"; + +marked.setOptions({ + breaks: true, + gfm: true // The 'breaks' option requires GFM (GitHub Flavored Markdown) to be true +}); + +const dateOptions = { + year: 'numeric', + month: 'short', + day: 'numeric' +}; + +const showStepResultFor = async (stepId, result) => { + await sleep(500); // and a short pause before starting the next spinner + const stepElement = getElement(stepId) + stepElement.style.display = 'flex'; + await sleep(); + const circle = getElement('.circle-loader', stepElement); + circle.classList.add('load-complete'); + // circle.classList.toggle('load-complete'); + if (result.valid) { + showElement('.checkmark', 'block', stepElement) + circle.style.borderColor = '#5cb85c' + } else { + showElement('.cross', 'block', stepElement) + circle.style.borderColor = '#d00' + } + await sleep(200); // and a short pause before showing the success message + showText('.message', result.message, stepElement) + +} +const displayStepResults = async (result) => { + hideElement("#verify-spinner") + // stop everything if either the signature is bad or the + // issuer is unknown, and show an error + if (! (result.signature.valid && result.issuer.valid) ) { + const message = ! result.signature.valid ? + result.signature.message : + result.issuer.message + displayError(message) + return + } + + // now show the credential recipient, credential name, and issuer + showElement("#details-container",'flex') + showText('#holder-name', result.credential.credentialSubject.name) + showText('#cred-name', result.credential.name) + showText('#issuer-name', result.issuer.message) + + // also populate the fields in the 'more...' dialog + // - if we have data + + if (result.credential.credentialSubject.achievement?.name) { + showElement('#more-title-section') + showText('#more-title', result.credential.credentialSubject.achievement?.name) + } + if (result.credential.credentialSubject.achievement?.description) { + showElement('#more-description-section') + showText('#more-description', result.credential.credentialSubject.achievement.description) + } + if (result.credential.issuanceDate || result.credential.validFrom) { + const issuanceDate = (result.credential.issuanceDate || result.credential.validFrom) ? + new Date(result.credential.issuanceDate || result.credential.validFrom) : + null + const formattedDate = new Intl.DateTimeFormat('en-US', dateOptions).format(issuanceDate); + showElement('#more-issued-date-section'); + showText('#more-issued-date', formattedDate); + } + if (result.credential.credentialSubject.achievement?.criteria?.narrative) { + showElement('#more-criteria-section') + const html = marked.parse(result.credential.credentialSubject.achievement.criteria.narrative); + getElement('#more-criteria').innerHTML = html + } + + // now show the results, step by step + showElement("#result-container") + await showStepResultFor('#sigCheck', result.signature) + await showStepResultFor('#expiryCheck', result.expiry) + await showStepResultFor('#statusCheck', result.status) + + // and now show the 'Verify Another' button, + // after a short pause + await sleep(500) + showElement("#verifyAnotherBtn", 'flex') +} + +export default displayStepResults \ No newline at end of file diff --git a/src/displayUtils.js b/src/displayUtils.js new file mode 100644 index 0000000..58df199 --- /dev/null +++ b/src/displayUtils.js @@ -0,0 +1,92 @@ +import {VERIFYING_SIG_MSG, VERIFYING_EXP_MSG, VERIFYING_REV_MSG} from './constants.js' + +const DEFAULT_SLEEP_TIME = 1000 + +let shadowRoot; +let hostElement; + +export const setHostElement = (element) => { + hostElement = element; + // also set the shadowRoot for convenience + shadowRoot = element.shadowRoot +} + +export const sleep = (ms=DEFAULT_SLEEP_TIME) => { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +export const showElement = (selector, displayType='block', ancestor=shadowRoot ) => { + getElement(selector, ancestor).style.display = displayType +} + +export const hideElement = (selector, ancestor=shadowRoot) => { + getElement(selector, ancestor).style.display = 'none' +} + +export const showText = (selector, text, ancestor=shadowRoot) => { + const element = getElement(selector, ancestor) + element.style.display = 'block' + element.textContent = text +} + +export const showDialog = (id) => { + const dialog = getElement(id); + dialog.style.left = `${hostElement.offsetLeft + 40}px`; + dialog.style.top = `${hostElement.offsetTop + 40}px`; + dialog.showModal() + //scroll to top of the dialog + dialog.scrollTo(0, 0); + +} + +export const closeDialog = (id) => { + getElement(id).close() +} + +export const getElement = (selector, ancestor=shadowRoot) => { + return ancestor.querySelector(selector) +} + +export const displayError = (message) => { + hideElement("#verify-spinner") + showElement("#error-container") + showText('#error-message', message) + showElement("#verifyAnotherBtn", 'flex') +} + +export const reset = () => { + + shadowRoot.querySelectorAll('.show-on-reset').forEach(element=> + element.style.display = 'flex' + ); + shadowRoot.querySelectorAll('.hide-on-reset').forEach(element=> + element.style.display = 'none' + ); + shadowRoot.querySelectorAll('.toClear').forEach(element=> + element.textContent = '' + ); + + // criteria shows html rendered from markdown, + // rather than plain text, so have to clear separately + getElement('#more-criteria').innerHTML = '' + + showText('#sig-message', VERIFYING_SIG_MSG) + showText('#rev-message', VERIFYING_REV_MSG) + showText('#exp-message', VERIFYING_EXP_MSG) + getElement('#vc-paste').value = ''; + + shadowRoot.querySelectorAll('.circle-loader').forEach(element=> + { + element.classList.remove('load-complete', 'circle-loader'); + element.classList.add('circle-loader'); + hideElement('.checkmark', element); + hideElement('.cross', element); + element.style.border = '3px solid rgba(0, 0, 0, 0.2)' + element.style.borderLeftColor = '#5cb85c' + } + ); + + + +} + diff --git a/src/events.js b/src/events.js new file mode 100644 index 0000000..12cea51 --- /dev/null +++ b/src/events.js @@ -0,0 +1,7 @@ +export const fireExternalReadyEvent = (theComponent) => { + const event = new CustomEvent('veri-good-is-ready', { + bubbles: true, // Allow the event to bubble up through the DOM + composed: true, // Allow the event to pass through the shadow DOM boundary + }); + theComponent.dispatchEvent(event); +} \ No newline at end of file diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..afa1b95 --- /dev/null +++ b/src/index.js @@ -0,0 +1,52 @@ +import styles from './styles.js' +import render from './render.js' +import { getElement, setTemplate } from './displayUtils.js' +import { processDIDTemplateList, setIssuerDidList } from './issuerDids.js' +import { setHostElement } from './displayUtils.js' +import { initializeListeners, removeListeners } from './listeners.js' +import { fireExternalReadyEvent } from './events.js' + + +export default class VeriGood extends HTMLElement { + + /* static get observedAttributes() { + return ['show']; + } */ + + constructor() { + super(); + this.attachShadow({ mode: 'open' }); + this.shadowRoot.adoptedStyleSheets = [ + ...this.shadowRoot.adoptedStyleSheets, + styles + ]; + } + + verify(vc) { + getElement("#vc-paste").value = vc; + getElement('#verifyBtn').click() + } + + setIssuerDids(list) { + setIssuerDidList(list) + } + + connectedCallback() { + this.shadowRoot.innerHTML = render(); + setHostElement(this); + processDIDTemplateList(this); + initializeListeners(this.shadowRoot); + fireExternalReadyEvent(this); + } + + disconnectedCallback() { + removeListeners() + } + + //attributeChangedCallback(name, oldValue, newValue) { + // this.shadowRoot.innerHTML = render(this); + //} + +} + +customElements.define('veri-good', VeriGood); diff --git a/src/issuerDids.js b/src/issuerDids.js new file mode 100644 index 0000000..3c9445f --- /dev/null +++ b/src/issuerDids.js @@ -0,0 +1,72 @@ +import { getElement } from "./displayUtils.js"; + +/* The did list is passed into the web component as a template with id set to issuer-dids. +See the index.html for an example. +If a did list is passed in to the component (via a template), it overrides the values set here. +*/ +let issuerDids = { + "did:web:digitalcredentials.github.io:testDID": { + "issuerName": "Department of Chemistry", + "url": "https://chemistry.uni.edu" + }, + "did:web:digitalcredentials.github.io:vc-test-fixtures:dids:legacy": { + "issuerName": "Department of Biology", + "url": "https://chemistry.uni.edu" + }, + "did:key:z6MkjoriXdbyWD25YXTed114F8hdJrLXQ567xxPHAUKxpKkS": { + "issuerName": "Department of Economics", + "url": "https://econ.uni.edu" + }, + "did:key:z6MkqBcwQ7qnRBRpgtsJQviLFeYxExMUE2k9nwKkMTF3DdRZ": { + "issuerName": "Department of Computer Science", + "url": "https://compsci.uni.edu" + }, + "did:key:z6MknNQD1WHLGGraFi6zcbGevuAgkVfdyCdtZnQTGWVVvR5Q": { + "issuerName": "Department of History", + "url": "https://history.uni.edu" + } + }; + + +export const processDIDTemplateList = (component) => { + const didListTemplate = component.querySelector('#issuer-dids'); + if (didListTemplate) { + try { + issuerDids = JSON.parse(didListTemplate.content.textContent.trim()); + } catch (e) { + console.error(`Bad, or no