2 lines
267 KiB
JavaScript
2 lines
267 KiB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.N3=f()}})(function(){var define,module,exports;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _Util=require("./Util");const BASE_UNSUPPORTED=/^:?[^:?#]*(?:[?#]|$)|^file:|^[^:]*:\/*[^?#]+?\/(?:\.\.?(?:\/|$)|\/)/i;const SUFFIX_SUPPORTED=/^(?:(?:[^/?#]{3,}|\.?[^/?#.]\.?)(?:\/[^/?#]{3,}|\.?[^/?#.]\.?)*\/?)?(?:[?#]|$)/;const CURRENT="./";const PARENT="../";const QUERY="?";const FRAGMENT="#";class BaseIRI{constructor(base){this.base=base;this._baseLength=0;this._baseMatcher=null;this._pathReplacements=new Array(base.length+1)}static supports(base){return!BASE_UNSUPPORTED.test(base)}_getBaseMatcher(){if(this._baseMatcher)return this._baseMatcher;if(!BaseIRI.supports(this.base))return this._baseMatcher=/.^/;const scheme=/^[^:]*:\/*/.exec(this.base)[0];const regexHead=["^",(0,_Util.escapeRegex)(scheme)];const regexTail=[];const segments=[],segmenter=/[^/?#]*([/?#])/y;let segment,query=0,fragment=0,last=segmenter.lastIndex=scheme.length;while(!query&&!fragment&&(segment=segmenter.exec(this.base))){if(segment[1]===FRAGMENT)fragment=segmenter.lastIndex-1;else{regexHead.push((0,_Util.escapeRegex)(segment[0]),"(?:");regexTail.push(")?");if(segment[1]!==QUERY)segments.push(last=segmenter.lastIndex);else{query=last=segmenter.lastIndex;fragment=this.base.indexOf(FRAGMENT,query);this._pathReplacements[query]=QUERY}}}for(let i=0;i<segments.length;i++)this._pathReplacements[segments[i]]=PARENT.repeat(segments.length-i-1);this._pathReplacements[segments[segments.length-1]]=CURRENT;this._baseLength=fragment>0?fragment:this.base.length;regexHead.push((0,_Util.escapeRegex)(this.base.substring(last,this._baseLength)),query?"(?:#|$)":"(?:[?#]|$)");return this._baseMatcher=new RegExp([...regexHead,...regexTail].join(""))}toRelative(iri){const match=this._getBaseMatcher().exec(iri);if(!match)return iri;const length=match[0].length;if(length===this._baseLength&&length===iri.length)return"";const parentPath=this._pathReplacements[length];if(parentPath){const suffix=iri.substring(length);if(parentPath!==QUERY&&!SUFFIX_SUPPORTED.test(suffix))return iri;if(parentPath===CURRENT&&/^[^?#]/.test(suffix))return suffix;return parentPath+suffix}return iri.substring(length-1)}}exports.default=BaseIRI},{"./Util":13}],2:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;const RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#",XSD="http://www.w3.org/2001/XMLSchema#",SWAP="http://www.w3.org/2000/10/swap/";var _default=exports.default={xsd:{decimal:`${XSD}decimal`,boolean:`${XSD}boolean`,double:`${XSD}double`,integer:`${XSD}integer`,string:`${XSD}string`},rdf:{type:`${RDF}type`,nil:`${RDF}nil`,first:`${RDF}first`,rest:`${RDF}rest`,langString:`${RDF}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${SWAP}reify#forSome`,forAll:`${SWAP}reify#forAll`},log:{implies:`${SWAP}log#implies`,isImpliedBy:`${SWAP}log#isImpliedBy`}}},{}],3:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.Variable=exports.Triple=exports.Term=exports.Quad=exports.NamedNode=exports.Literal=exports.DefaultGraph=exports.BlankNode=void 0;exports.escapeQuotes=escapeQuotes;exports.fromQuad=fromQuad;exports.fromTerm=fromTerm;exports.termFromId=termFromId;exports.termToId=termToId;exports.unescapeQuotes=unescapeQuotes;var _IRIs=_interopRequireDefault(require("./IRIs"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const{rdf,xsd}=_IRIs.default;let DEFAULTGRAPH;let _blankNodeCounter=0;const escapedLiteral=/^"(.*".*)(?="[^"]*$)/;const DataFactory={namedNode:namedNode,blankNode:blankNode,variable:variable,literal:literal,defaultGraph:defaultGraph,quad:quad,triple:quad,fromTerm:fromTerm,fromQuad:fromQuad};var _default=exports.default=DataFactory;class Term{constructor(id){this.id=id}get value(){return this.id}equals(other){if(other instanceof Term)return this.id===other.id;return!!other&&this.termType===other.termType&&this.value===other.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}exports.Term=Term;class NamedNode extends Term{get termType(){return"NamedNode"}}exports.NamedNode=NamedNode;class Literal extends Term{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const id=this.id;let atPos=id.lastIndexOf('"')+1;return atPos<id.length&&id[atPos++]==="@"?id.substr(atPos).toLowerCase():""}get datatype(){return new NamedNode(this.datatypeString)}get datatypeString(){const id=this.id,dtPos=id.lastIndexOf('"')+1;const char=dtPos<id.length?id[dtPos]:"";return char==="^"?id.substr(dtPos+2):char!=="@"?xsd.string:rdf.langString}equals(other){if(other instanceof Literal)return this.id===other.id;return!!other&&!!other.datatype&&this.termType===other.termType&&this.value===other.value&&this.language===other.language&&this.datatype.value===other.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,datatype:{termType:"NamedNode",value:this.datatypeString}}}}exports.Literal=Literal;class BlankNode extends Term{constructor(name){super(`_:${name}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}exports.BlankNode=BlankNode;class Variable extends Term{constructor(name){super(`?${name}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}exports.Variable=Variable;class DefaultGraph extends Term{constructor(){super("");return DEFAULTGRAPH||this}get termType(){return"DefaultGraph"}equals(other){return this===other||!!other&&this.termType===other.termType}}exports.DefaultGraph=DefaultGraph;DEFAULTGRAPH=new DefaultGraph;function termFromId(id,factory,nested){factory=factory||DataFactory;if(!id)return factory.defaultGraph();switch(id[0]){case"?":return factory.variable(id.substr(1));case"_":return factory.blankNode(id.substr(2));case'"':if(factory===DataFactory)return new Literal(id);if(id[id.length-1]==='"')return factory.literal(id.substr(1,id.length-2));const endPos=id.lastIndexOf('"',id.length-1);return factory.literal(id.substr(1,endPos-1),id[endPos+1]==="@"?id.substr(endPos+2):factory.namedNode(id.substr(endPos+3)));case"[":id=JSON.parse(id);break;default:if(!nested||!Array.isArray(id)){return factory.namedNode(id)}}return factory.quad(termFromId(id[0],factory,true),termFromId(id[1],factory,true),termFromId(id[2],factory,true),id[3]&&termFromId(id[3],factory,true))}function termToId(term,nested){if(typeof term==="string")return term;if(term instanceof Term&&term.termType!=="Quad")return term.id;if(!term)return DEFAULTGRAPH.id;switch(term.termType){case"NamedNode":return term.value;case"BlankNode":return`_:${term.value}`;case"Variable":return`?${term.value}`;case"DefaultGraph":return"";case"Literal":return`"${term.value}"${term.language?`@${term.language}`:term.datatype&&term.datatype.value!==xsd.string?`^^${term.datatype.value}`:""}`;case"Quad":const res=[termToId(term.subject,true),termToId(term.predicate,true),termToId(term.object,true)];if(term.graph&&term.graph.termType!=="DefaultGraph"){res.push(termToId(term.graph,true))}return nested?res:JSON.stringify(res);default:throw new Error(`Unexpected termType: ${term.termType}`)}}class Quad extends Term{constructor(subject,predicate,object,graph){super("");this._subject=subject;this._predicate=predicate;this._object=object;this._graph=graph||DEFAULTGRAPH}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(other){return!!other&&this._subject.equals(other.subject)&&this._predicate.equals(other.predicate)&&this._object.equals(other.object)&&this._graph.equals(other.graph)}}exports.Triple=exports.Quad=Quad;function escapeQuotes(id){return id.replace(escapedLiteral,(_,quoted)=>`"${quoted.replace(/"/g,'""')}`)}function unescapeQuotes(id){return id.replace(escapedLiteral,(_,quoted)=>`"${quoted.replace(/""/g,'"')}`)}function namedNode(iri){return new NamedNode(iri)}function blankNode(name){return new BlankNode(name||`n3-${_blankNodeCounter++}`)}function literal(value,languageOrDataType){if(typeof languageOrDataType==="string")return new Literal(`"${value}"@${languageOrDataType.toLowerCase()}`);let datatype=languageOrDataType?languageOrDataType.value:"";if(datatype===""){if(typeof value==="boolean")datatype=xsd.boolean;else if(typeof value==="number"){if(Number.isFinite(value))datatype=Number.isInteger(value)?xsd.integer:xsd.double;else{datatype=xsd.double;if(!Number.isNaN(value))value=value>0?"INF":"-INF"}}}return datatype===""||datatype===xsd.string?new Literal(`"${value}"`):new Literal(`"${value}"^^${datatype}`)}function variable(name){return new Variable(name)}function defaultGraph(){return DEFAULTGRAPH}function quad(subject,predicate,object,graph){return new Quad(subject,predicate,object,graph)}function fromTerm(term){if(term instanceof Term)return term;switch(term.termType){case"NamedNode":return namedNode(term.value);case"BlankNode":return blankNode(term.value);case"Variable":return variable(term.value);case"DefaultGraph":return DEFAULTGRAPH;case"Literal":return literal(term.value,term.language||term.datatype);case"Quad":return fromQuad(term);default:throw new Error(`Unexpected termType: ${term.termType}`)}}function fromQuad(inQuad){if(inQuad instanceof Quad)return inQuad;if(inQuad.termType!=="Quad")throw new Error(`Unexpected termType: ${inQuad.termType}`);return quad(fromTerm(inQuad.subject),fromTerm(inQuad.predicate),fromTerm(inQuad.object),fromTerm(inQuad.graph))}},{"./IRIs":2}],4:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _buffer=require("buffer");var _IRIs=_interopRequireDefault(require("./IRIs"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const{xsd}=_IRIs.default;const escapeSequence=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g;const escapeReplacements={"\\":"\\","'":"'",'"':'"',n:"\n",r:"\r",t:"\t",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"};const illegalIriChars=/[\x00-\x20<>\\"\{\}\|\^\`]/;const lineModeRegExps={_iri:true,_unescapedIri:true,_simpleQuotedString:true,_langcode:true,_blank:true,_newline:true,_comment:true,_whitespace:true,_endOfFile:true};const invalidRegExp=/$0^/;class N3Lexer{constructor(options){this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/;this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/;this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/;this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/;this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i;this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/;this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/;this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/;this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/;this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/;this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/;this._keyword=/^@[a-z]+(?=[\s#<:])/i;this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i;this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/;this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/;this._comment=/#([^\n\r]*)/;this._whitespace=/^[ \t]+/;this._endOfFile=/^(?:#[^\n\r]*)?$/;options=options||{};this._isImpliedBy=options.isImpliedBy;if(this._lineMode=!!options.lineMode){this._n3Mode=false;for(const key in this){if(!(key in lineModeRegExps)&&this[key]instanceof RegExp)this[key]=invalidRegExp}}else{this._n3Mode=options.n3!==false}this.comments=!!options.comments;this._literalClosingPos=0}_tokenizeToEnd(callback,inputFinished){let input=this._input;let currentLineLength=input.length;while(true){let whiteSpaceMatch,comment;while(whiteSpaceMatch=this._newline.exec(input)){if(this.comments&&(comment=this._comment.exec(whiteSpaceMatch[0])))emitToken("comment",comment[1],"",this._line,whiteSpaceMatch[0].length);input=input.substr(whiteSpaceMatch[0].length,input.length);currentLineLength=input.length;this._line++}if(!whiteSpaceMatch&&(whiteSpaceMatch=this._whitespace.exec(input)))input=input.substr(whiteSpaceMatch[0].length,input.length);if(this._endOfFile.test(input)){if(inputFinished){if(this.comments&&(comment=this._comment.exec(input)))emitToken("comment",comment[1],"",this._line,input.length);input=null;emitToken("eof","","",this._line,0)}return this._input=input}const line=this._line,firstChar=input[0];let type="",value="",prefix="",match=null,matchLength=0,inconclusive=false;switch(firstChar){case"^":if(input.length<3)break;else if(input[1]==="^"){this._previousMarker="^^";input=input.substr(2);if(input[0]!=="<"){inconclusive=true;break}}else{if(this._n3Mode){matchLength=1;type="^"}break}case"<":if(match=this._unescapedIri.exec(input))type="IRI",value=match[1];else if(match=this._iri.exec(input)){value=this._unescape(match[1]);if(value===null||illegalIriChars.test(value))return reportSyntaxError(this);type="IRI"}else if(input.length>1&&input[1]==="<")type="<<",matchLength=2;else if(this._n3Mode&&input.length>1&&input[1]==="="){matchLength=2;if(this._isImpliedBy)type="abbreviation",value="<";else type="inverse",value=">"}break;case">":if(input.length>1&&input[1]===">")type=">>",matchLength=2;break;case"_":if((match=this._blank.exec(input))||inputFinished&&(match=this._blank.exec(`${input} `)))type="blank",prefix="_",value=match[1];break;case'"':if(match=this._simpleQuotedString.exec(input))value=match[1];else{({value,matchLength}=this._parseLiteral(input));if(value===null)return reportSyntaxError(this)}if(match!==null||matchLength!==0){type="literal";this._literalClosingPos=0}break;case"'":if(!this._lineMode){if(match=this._simpleApostropheString.exec(input))value=match[1];else{({value,matchLength}=this._parseLiteral(input));if(value===null)return reportSyntaxError(this)}if(match!==null||matchLength!==0){type="literal";this._literalClosingPos=0}}break;case"?":if(this._n3Mode&&(match=this._variable.exec(input)))type="var",value=match[0];break;case"@":if(this._previousMarker==="literal"&&(match=this._langcode.exec(input)))type="langcode",value=match[1];else if(match=this._keyword.exec(input))type=match[0];break;case".":if(input.length===1?inputFinished:input[1]<"0"||input[1]>"9"){type=".";matchLength=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":if(match=this._number.exec(input)||inputFinished&&(match=this._number.exec(`${input} `))){type="literal",value=match[0];prefix=typeof match[1]==="string"?xsd.double:typeof match[2]==="string"?xsd.decimal:xsd.integer}break;case"B":case"b":case"p":case"P":case"G":case"g":if(match=this._sparqlKeyword.exec(input))type=match[0].toUpperCase();else inconclusive=true;break;case"f":case"t":if(match=this._boolean.exec(input))type="literal",value=match[0],prefix=xsd.boolean;else inconclusive=true;break;case"a":if(match=this._shortPredicates.exec(input))type="abbreviation",value="a";else inconclusive=true;break;case"=":if(this._n3Mode&&input.length>1){type="abbreviation";if(input[1]!==">")matchLength=1,value="=";else matchLength=2,value=">"}break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":if(!this._lineMode){matchLength=1;type=firstChar}break;case"{":if(!this._lineMode&&input.length>=2){if(input[1]==="|")type="{|",matchLength=2;else type=firstChar,matchLength=1}break;case"|":if(input.length>=2&&input[1]==="}")type="|}",matchLength=2;break;default:inconclusive=true}if(inconclusive){if((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(match=this._prefix.exec(input)))type="prefix",value=match[1]||"";else if((match=this._prefixed.exec(input))||inputFinished&&(match=this._prefixed.exec(`${input} `)))type="prefixed",prefix=match[1]||"",value=this._unescape(match[2])}if(this._previousMarker==="^^"){switch(type){case"prefixed":type="type";break;case"IRI":type="typeIRI";break;default:type=""}}if(!type){if(inputFinished||!/^'''|^"""/.test(input)&&/\n|\r/.test(input))return reportSyntaxError(this);else return this._input=input}const length=matchLength||match[0].length;const token=emitToken(type,value,prefix,line,length);this.previousToken=token;this._previousMarker=type;input=input.substr(length,input.length)}function emitToken(type,value,prefix,line,length){const start=input?currentLineLength-input.length:currentLineLength;const end=start+length;const token={type:type,value:value,prefix:prefix,line:line,start:start,end:end};callback(null,token);return token}function reportSyntaxError(self){callback(self._syntaxError(/^\S*/.exec(input)[0]))}}_unescape(item){let invalid=false;const replaced=item.replace(escapeSequence,(sequence,unicode4,unicode8,escapedChar)=>{if(typeof unicode4==="string")return String.fromCharCode(Number.parseInt(unicode4,16));if(typeof unicode8==="string"){let charCode=Number.parseInt(unicode8,16);return charCode<=65535?String.fromCharCode(Number.parseInt(unicode8,16)):String.fromCharCode(55296+((charCode-=65536)>>10),56320+(charCode&1023))}if(escapedChar in escapeReplacements)return escapeReplacements[escapedChar];invalid=true;return""});return invalid?null:replaced}_parseLiteral(input){if(input.length>=3){const opening=input.match(/^(?:"""|"|'''|'|)/)[0];const openingLength=opening.length;let closingPos=Math.max(this._literalClosingPos,openingLength);while((closingPos=input.indexOf(opening,closingPos))>0){let backslashCount=0;while(input[closingPos-backslashCount-1]==="\\")backslashCount++;if(backslashCount%2===0){const raw=input.substring(openingLength,closingPos);const lines=raw.split(/\r\n|\r|\n/).length-1;const matchLength=closingPos+openingLength;if(openingLength===1&&lines!==0||openingLength===3&&this._lineMode)break;this._line+=lines;return{value:this._unescape(raw),matchLength:matchLength}}closingPos++}this._literalClosingPos=input.length-openingLength+1}return{value:"",matchLength:0}}_syntaxError(issue){this._input=null;const err=new Error(`Unexpected "${issue}" on line ${this._line}.`);err.context={token:undefined,line:this._line,previousToken:this.previousToken};return err}_readStartingBom(input){return input.startsWith("\ufeff")?input.substr(1):input}tokenize(input,callback){this._line=1;if(typeof input==="string"){this._input=this._readStartingBom(input);if(typeof callback==="function")queueMicrotask(()=>this._tokenizeToEnd(callback,true));else{const tokens=[];let error;this._tokenizeToEnd((e,t)=>e?error=e:tokens.push(t),true);if(error)throw error;return tokens}}else{this._pendingBuffer=null;if(typeof input.setEncoding==="function")input.setEncoding("utf8");input.on("data",data=>{if(this._input!==null&&data.length!==0){if(this._pendingBuffer){data=_buffer.Buffer.concat([this._pendingBuffer,data]);this._pendingBuffer=null}if(data[data.length-1]&128){this._pendingBuffer=data}else{if(typeof this._input==="undefined")this._input=this._readStartingBom(typeof data==="string"?data:data.toString());else this._input+=data;this._tokenizeToEnd(callback,false)}}});input.on("end",()=>{if(typeof this._input==="string")this._tokenizeToEnd(callback,true)});input.on("error",callback)}}}exports.default=N3Lexer},{"./IRIs":2,buffer:17}],5:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _N3Lexer=_interopRequireDefault(require("./N3Lexer"));var _N3DataFactory=_interopRequireDefault(require("./N3DataFactory"));var _IRIs=_interopRequireDefault(require("./IRIs"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}let blankNodePrefix=0;class N3Parser{constructor(options){this._contextStack=[];this._graph=null;options=options||{};this._setBase(options.baseIRI);options.factory&&initDataFactory(this,options.factory);const format=typeof options.format==="string"?options.format.match(/\w*$/)[0].toLowerCase():"",isTurtle=/turtle/.test(format),isTriG=/trig/.test(format),isNTriples=/triple/.test(format),isNQuads=/quad/.test(format),isN3=this._n3Mode=/n3/.test(format),isLineMode=isNTriples||isNQuads;if(!(this._supportsNamedGraphs=!(isTurtle||isN3)))this._readPredicateOrNamedGraph=this._readPredicate;this._supportsQuads=!(isTurtle||isTriG||isNTriples||isN3);this._isImpliedBy=options.isImpliedBy;this._supportsRDFStar=format===""||/star|\*$/.test(format);if(isLineMode)this._resolveRelativeIRI=iri=>{return null};this._blankNodePrefix=typeof options.blankNodePrefix!=="string"?"":options.blankNodePrefix.replace(/^(?!_:)/,"_:");this._lexer=options.lexer||new _N3Lexer.default({lineMode:isLineMode,n3:isN3,isImpliedBy:this._isImpliedBy});this._explicitQuantifiers=!!options.explicitQuantifiers}static _resetBlankNodePrefix(){blankNodePrefix=0}_setBase(baseIRI){if(!baseIRI){this._base="";this._basePath=""}else{const fragmentPos=baseIRI.indexOf("#");if(fragmentPos>=0)baseIRI=baseIRI.substr(0,fragmentPos);this._base=baseIRI;this._basePath=baseIRI.indexOf("/")<0?baseIRI:baseIRI.replace(/[^\/?]*(?:\?.*)?$/,"");baseIRI=baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i);this._baseRoot=baseIRI[0];this._baseScheme=baseIRI[1]}}_saveContext(type,graph,subject,predicate,object){const n3Mode=this._n3Mode;this._contextStack.push({type:type,subject:subject,predicate:predicate,object:object,graph:graph,inverse:n3Mode?this._inversePredicate:false,blankPrefix:n3Mode?this._prefixes._:"",quantified:n3Mode?this._quantified:null});if(n3Mode){this._inversePredicate=false;this._prefixes._=this._graph?`${this._graph.value}.`:".";this._quantified=Object.create(this._quantified)}}_restoreContext(type,token){const context=this._contextStack.pop();if(!context||context.type!==type)return this._error(`Unexpected ${token.type}`,token);this._subject=context.subject;this._predicate=context.predicate;this._object=context.object;this._graph=context.graph;if(this._n3Mode){this._inversePredicate=context.inverse;this._prefixes._=context.blankPrefix;this._quantified=context.quantified}}_readInTopContext(token){switch(token.type){case"eof":if(this._graph!==null)return this._error("Unclosed graph",token);delete this._prefixes._;return this._callback(null,null,this._prefixes);case"PREFIX":this._sparqlStyle=true;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=true;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs){this._graph="";this._subject=null;return this._readSubject}case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(token)}}_readEntity(token,quantifier){let value;switch(token.type){case"IRI":case"typeIRI":const iri=this._resolveIRI(token.value);if(iri===null)return this._error("Invalid IRI",token);value=this._factory.namedNode(iri);break;case"type":case"prefixed":const prefix=this._prefixes[token.prefix];if(prefix===undefined)return this._error(`Undefined prefix "${token.prefix}:"`,token);value=this._factory.namedNode(prefix+token.value);break;case"blank":value=this._factory.blankNode(this._prefixes[token.prefix]+token.value);break;case"var":value=this._factory.variable(token.value.substr(1));break;default:return this._error(`Expected entity but got ${token.type}`,token)}if(!quantifier&&this._n3Mode&&value.id in this._quantified)value=this._quantified[value.id];return value}_readSubject(token){this._predicate=null;switch(token.type){case"[":this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null);return this._readBlankNodeHead;case"(":this._saveContext("list",this._graph,this.RDF_NIL,null,null);this._subject=null;return this._readListItem;case"{":if(!this._n3Mode)return this._error("Unexpected graph",token);this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null);return this._readSubject;case"}":return this._readPunctuation(token);case"@forSome":if(!this._n3Mode)return this._error('Unexpected "@forSome"',token);this._subject=null;this._predicate=this.N3_FORSOME;this._quantifier="blankNode";return this._readQuantifierList;case"@forAll":if(!this._n3Mode)return this._error('Unexpected "@forAll"',token);this._subject=null;this._predicate=this.N3_FORALL;this._quantifier="variable";return this._readQuantifierList;case"literal":if(!this._n3Mode)return this._error("Unexpected literal",token);if(token.prefix.length===0){this._literalValue=token.value;return this._completeSubjectLiteral}else this._subject=this._factory.literal(token.value,this._factory.namedNode(token.prefix));break;case"<<":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",token);this._saveContext("<<",this._graph,null,null,null);this._graph=null;return this._readSubject;default:if((this._subject=this._readEntity(token))===undefined)return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(token){const type=token.type;switch(type){case"inverse":this._inversePredicate=true;case"abbreviation":this._predicate=this.ABBREVIATIONS[token.value];break;case".":case"]":case"}":if(this._predicate===null)return this._error(`Unexpected ${type}`,token);this._subject=null;return type==="]"?this._readBlankNodeTail(token):this._readPunctuation(token);case";":return this._predicate!==null?this._readPredicate:this._error("Expected predicate but got ;",token);case"[":if(this._n3Mode){this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null);return this._readBlankNodeHead}case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",token);default:if((this._predicate=this._readEntity(token))===undefined)return}return this._readObject}_readObject(token){switch(token.type){case"literal":if(token.prefix.length===0){this._literalValue=token.value;return this._readDataTypeOrLang}else this._object=this._factory.literal(token.value,this._factory.namedNode(token.prefix));break;case"[":this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode());return this._readBlankNodeHead;case"(":this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL);this._subject=null;return this._readListItem;case"{":if(!this._n3Mode)return this._error("Unexpected graph",token);this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode());return this._readSubject;case"<<":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",token);this._saveContext("<<",this._graph,this._subject,this._predicate,null);this._graph=null;return this._readSubject;default:if((this._object=this._readEntity(token))===undefined)return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(token){return token.type==="{"?this._readGraph(token):this._readPredicate(token)}_readGraph(token){if(token.type!=="{")return this._error(`Expected graph but got ${token.type}`,token);this._graph=this._subject,this._subject=null;return this._readSubject}_readBlankNodeHead(token){if(token.type==="]"){this._subject=null;return this._readBlankNodeTail(token)}else{this._predicate=null;return this._readPredicate(token)}}_readBlankNodeTail(token){if(token.type!=="]")return this._readBlankNodePunctuation(token);if(this._subject!==null)this._emit(this._subject,this._predicate,this._object,this._graph);const empty=this._predicate===null;this._restoreContext("blank",token);if(this._object!==null)return this._getContextEndReader();else if(this._predicate!==null)return this._readObject;else return empty?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(token){switch(token.type){case".":case"}":this._subject=null;return this._readPunctuation(token);default:return this._readPredicate(token)}}_readListItem(token){let item=null,list=null,next=this._readListItem;const previousList=this._subject,stack=this._contextStack,parent=stack[stack.length-1];switch(token.type){case"[":this._saveContext("blank",this._graph,list=this._factory.blankNode(),this.RDF_FIRST,this._subject=item=this._factory.blankNode());next=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,list=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL);this._subject=null;break;case")":this._restoreContext("list",token);if(stack.length!==0&&stack[stack.length-1].type==="list")this._emit(this._subject,this._predicate,this._object,this._graph);if(this._predicate===null){next=this._readPredicate;if(this._subject===this.RDF_NIL)return next}else{next=this._getContextEndReader();if(this._object===this.RDF_NIL)return next}list=this.RDF_NIL;break;case"literal":if(token.prefix.length===0){this._literalValue=token.value;next=this._readListItemDataTypeOrLang}else{item=this._factory.literal(token.value,this._factory.namedNode(token.prefix));next=this._getContextEndReader()}break;case"{":if(!this._n3Mode)return this._error("Unexpected graph",token);this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode());return this._readSubject;default:if((item=this._readEntity(token))===undefined)return}if(list===null)this._subject=list=this._factory.blankNode();if(previousList===null){if(parent.predicate===null)parent.subject=list;else parent.object=list}else{this._emit(previousList,this.RDF_REST,list,this._graph)}if(item!==null){if(this._n3Mode&&(token.type==="IRI"||token.type==="prefixed")){this._saveContext("item",this._graph,list,this.RDF_FIRST,item);this._subject=item,this._predicate=null;return this._getPathReader(this._readListItem)}this._emit(list,this.RDF_FIRST,item,this._graph)}return next}_readDataTypeOrLang(token){return this._completeObjectLiteral(token,false)}_readListItemDataTypeOrLang(token){return this._completeObjectLiteral(token,true)}_completeLiteral(token){let literal=this._factory.literal(this._literalValue);switch(token.type){case"type":case"typeIRI":const datatype=this._readEntity(token);if(datatype===undefined)return;literal=this._factory.literal(this._literalValue,datatype);token=null;break;case"langcode":literal=this._factory.literal(this._literalValue,token.value);token=null;break}return{token:token,literal:literal}}_completeSubjectLiteral(token){this._subject=this._completeLiteral(token).literal;return this._readPredicateOrNamedGraph}_completeObjectLiteral(token,listItem){const completed=this._completeLiteral(token);if(!completed)return;this._object=completed.literal;if(listItem)this._emit(this._subject,this.RDF_FIRST,this._object,this._graph);if(completed.token===null)return this._getContextEndReader();else{this._readCallback=this._getContextEndReader();return this._readCallback(completed.token)}}_readFormulaTail(token){if(token.type!=="}")return this._readPunctuation(token);if(this._subject!==null)this._emit(this._subject,this._predicate,this._object,this._graph);this._restoreContext("formula",token);return this._object===null?this._readPredicate:this._getContextEndReader()}_readPunctuation(token){let next,graph=this._graph;const subject=this._subject,inversePredicate=this._inversePredicate;switch(token.type){case"}":if(this._graph===null)return this._error("Unexpected graph closing",token);if(this._n3Mode)return this._readFormulaTail(token);this._graph=null;case".":this._subject=null;next=this._contextStack.length?this._readSubject:this._readInTopContext;if(inversePredicate)this._inversePredicate=false;break;case";":next=this._readPredicate;break;case",":next=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",token);const predicate=this._predicate,object=this._object;this._subject=this._factory.quad(subject,predicate,object,this.DEFAULTGRAPH);next=this._readPredicate;break;case"|}":if(this._subject.termType!=="Quad")return this._error("Unexpected asserted triple closing",token);this._subject=null;next=this._readPunctuation;break;default:if(this._supportsQuads&&this._graph===null&&(graph=this._readEntity(token))!==undefined){next=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,token)}if(subject!==null){const predicate=this._predicate,object=this._object;if(!inversePredicate)this._emit(subject,predicate,object,graph);else this._emit(object,predicate,subject,graph)}return next}_readBlankNodePunctuation(token){let next;switch(token.type){case";":next=this._readPredicate;break;case",":next=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,token)}this._emit(this._subject,this._predicate,this._object,this._graph);return next}_readQuadPunctuation(token){if(token.type!==".")return this._error("Expected dot to follow quad",token);return this._readInTopContext}_readPrefix(token){if(token.type!=="prefix")return this._error("Expected prefix to follow @prefix",token);this._prefix=token.value;return this._readPrefixIRI}_readPrefixIRI(token){if(token.type!=="IRI")return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,token);const prefixNode=this._readEntity(token);this._prefixes[this._prefix]=prefixNode.value;this._prefixCallback(this._prefix,prefixNode);return this._readDeclarationPunctuation}_readBaseIRI(token){const iri=token.type==="IRI"&&this._resolveIRI(token.value);if(!iri)return this._error("Expected valid IRI to follow base declaration",token);this._setBase(iri);return this._readDeclarationPunctuation}_readNamedGraphLabel(token){switch(token.type){case"IRI":case"blank":case"prefixed":return this._readSubject(token),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",token)}}_readNamedGraphBlankLabel(token){if(token.type!=="]")return this._error("Invalid graph label",token);this._subject=this._factory.blankNode();return this._readGraph}_readDeclarationPunctuation(token){if(this._sparqlStyle){this._sparqlStyle=false;return this._readInTopContext(token)}if(token.type!==".")return this._error("Expected declaration to end with a dot",token);return this._readInTopContext}_readQuantifierList(token){let entity;switch(token.type){case"IRI":case"prefixed":if((entity=this._readEntity(token,true))!==undefined)break;default:return this._error(`Unexpected ${token.type}`,token)}if(!this._explicitQuantifiers)this._quantified[entity.id]=this._factory[this._quantifier](this._factory.blankNode().value);else{if(this._subject===null)this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH);else this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH);this._emit(this._subject,this.RDF_FIRST,entity,this.QUANTIFIERS_GRAPH)}return this._readQuantifierPunctuation}_readQuantifierPunctuation(token){if(token.type===",")return this._readQuantifierList;else{if(this._explicitQuantifiers){this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH);this._subject=null}this._readCallback=this._getContextEndReader();return this._readCallback(token)}}_getPathReader(afterPath){this._afterPath=afterPath;return this._readPath}_readPath(token){switch(token.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const stack=this._contextStack,parent=stack.length&&stack[stack.length-1];if(parent&&parent.type==="item"){const item=this._subject;this._restoreContext("item",token);this._emit(this._subject,this.RDF_FIRST,item,this._graph)}return this._afterPath(token)}}_readForwardPath(token){let subject,predicate;const object=this._factory.blankNode();if((predicate=this._readEntity(token))===undefined)return;if(this._predicate===null)subject=this._subject,this._subject=object;else subject=this._object,this._object=object;this._emit(subject,predicate,object,this._graph);return this._readPath}_readBackwardPath(token){const subject=this._factory.blankNode();let predicate,object;if((predicate=this._readEntity(token))===undefined)return;if(this._predicate===null)object=this._subject,this._subject=subject;else object=this._object,this._object=subject;this._emit(subject,predicate,object,this._graph);return this._readPath}_readRDFStarTailOrGraph(token){if(token.type!==">>"){if(this._supportsQuads&&this._graph===null&&(this._graph=this._readEntity(token))!==undefined)return this._readRDFStarTail;return this._error(`Expected >> to follow "${this._object.id}"`,token)}return this._readRDFStarTail(token)}_readRDFStarTail(token){if(token.type!==">>")return this._error(`Expected >> but got ${token.type}`,token);const quad=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);this._restoreContext("<<",token);if(this._subject===null){this._subject=quad;return this._readPredicate}else{this._object=quad;return this._getContextEndReader()}}_getContextEndReader(){const contextStack=this._contextStack;if(!contextStack.length)return this._readPunctuation;switch(contextStack[contextStack.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(subject,predicate,object,graph){this._callback(null,this._factory.quad(subject,predicate,object,graph||this.DEFAULTGRAPH))}_error(message,token){const err=new Error(`${message} on line ${token.line}.`);err.context={token:token,line:token.line,previousToken:this._lexer.previousToken};this._callback(err);this._callback=noop}_resolveIRI(iri){return/^[a-z][a-z0-9+.-]*:/i.test(iri)?iri:this._resolveRelativeIRI(iri)}_resolveRelativeIRI(iri){if(!iri.length)return this._base;switch(iri[0]){case"#":return this._base+iri;case"?":return this._base.replace(/(?:\?.*)?$/,iri);case"/":return(iri[1]==="/"?this._baseScheme:this._baseRoot)+this._removeDotSegments(iri);default:return/^[^/:]*:/.test(iri)?null:this._removeDotSegments(this._basePath+iri)}}_removeDotSegments(iri){if(!/(^|\/)\.\.?($|[/#?])/.test(iri))return iri;const length=iri.length;let result="",i=-1,pathStart=-1,segmentStart=0,next="/";while(i<length){switch(next){case":":if(pathStart<0){if(iri[++i]==="/"&&iri[++i]==="/")while((pathStart=i+1)<length&&iri[pathStart]!=="/")i=pathStart}break;case"?":case"#":i=length;break;case"/":if(iri[i+1]==="."){next=iri[++i+1];switch(next){case"/":result+=iri.substring(segmentStart,i-1);segmentStart=i+1;break;case undefined:case"?":case"#":return result+iri.substring(segmentStart,i)+iri.substr(i+1);case".":next=iri[++i+1];if(next===undefined||next==="/"||next==="?"||next==="#"){result+=iri.substring(segmentStart,i-2);if((segmentStart=result.lastIndexOf("/"))>=pathStart)result=result.substr(0,segmentStart);if(next!=="/")return`${result}/${iri.substr(i+1)}`;segmentStart=i+1}}}}next=iri[++i]}return result+iri.substring(segmentStart)}parse(input,quadCallback,prefixCallback){let onQuad,onPrefix,onComment;if(quadCallback&&(quadCallback.onQuad||quadCallback.onPrefix||quadCallback.onComment)){onQuad=quadCallback.onQuad;onPrefix=quadCallback.onPrefix;onComment=quadCallback.onComment}else{onQuad=quadCallback;onPrefix=prefixCallback}this._readCallback=this._readInTopContext;this._sparqlStyle=false;this._prefixes=Object.create(null);this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${blankNodePrefix++}_`;this._prefixCallback=onPrefix||noop;this._inversePredicate=false;this._quantified=Object.create(null);if(!onQuad){const quads=[];let error;this._callback=(e,t)=>{e?error=e:t&&quads.push(t)};this._lexer.tokenize(input).every(token=>{return this._readCallback=this._readCallback(token)});if(error)throw error;return quads}let processNextToken=(error,token)=>{if(error!==null)this._callback(error),this._callback=noop;else if(this._readCallback)this._readCallback=this._readCallback(token)};if(onComment){this._lexer.comments=true;processNextToken=(error,token)=>{if(error!==null)this._callback(error),this._callback=noop;else if(this._readCallback){if(token.type==="comment")onComment(token.value);else this._readCallback=this._readCallback(token)}}}this._callback=onQuad;this._lexer.tokenize(input,processNextToken)}}exports.default=N3Parser;function noop(){}function initDataFactory(parser,factory){parser._factory=factory;parser.DEFAULTGRAPH=factory.defaultGraph();parser.RDF_FIRST=factory.namedNode(_IRIs.default.rdf.first);parser.RDF_REST=factory.namedNode(_IRIs.default.rdf.rest);parser.RDF_NIL=factory.namedNode(_IRIs.default.rdf.nil);parser.N3_FORALL=factory.namedNode(_IRIs.default.r.forAll);parser.N3_FORSOME=factory.namedNode(_IRIs.default.r.forSome);parser.ABBREVIATIONS={a:factory.namedNode(_IRIs.default.rdf.type),"=":factory.namedNode(_IRIs.default.owl.sameAs),">":factory.namedNode(_IRIs.default.log.implies),"<":factory.namedNode(_IRIs.default.log.isImpliedBy)};parser.QUANTIFIERS_GRAPH=factory.namedNode("urn:n3:quantifiers")}initDataFactory(N3Parser.prototype,_N3DataFactory.default)},{"./IRIs":2,"./N3DataFactory":3,"./N3Lexer":4}],6:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;exports.getRulesFromDataset=getRulesFromDataset;var _N3DataFactory=_interopRequireDefault(require("./N3DataFactory"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function getRulesFromDataset(dataset){const rules=[];for(const{subject,object}of dataset.match(null,_N3DataFactory.default.namedNode("http://www.w3.org/2000/10/swap/log#implies"),null,_N3DataFactory.default.defaultGraph())){const premise=[...dataset.match(null,null,null,subject)];const conclusion=[...dataset.match(null,null,null,object)];rules.push({premise:premise,conclusion:conclusion})}return rules}class N3Reasoner{constructor(store){this._store=store}_add(subject,predicate,object,graphItem,cb){if(!this._store._addToIndex(graphItem.subjects,subject,predicate,object))return;this._store._addToIndex(graphItem.predicates,predicate,object,subject);this._store._addToIndex(graphItem.objects,object,subject,predicate);cb()}_evaluatePremise(rule,content,cb,i=0){let v1,v2,value,index1,index2;const[val0,val1,val2]=rule.premise[i].value,index=content[rule.premise[i].content];const v0=!(value=val0.value);for(value in v0?index:{[value]:index[value]}){if(index1=index[value]){if(v0)val0.value=Number(value);v1=!(value=val1.value);for(value in v1?index1:{[value]:index1[value]}){if(index2=index1[value]){if(v1)val1.value=Number(value);v2=!(value=val2.value);for(value in v2?index2:{[value]:index2[value]}){if(v2)val2.value=Number(value);if(i===rule.premise.length-1)rule.conclusion.forEach(c=>{this._add(c.subject.value,c.predicate.value,c.object.value,content,()=>{cb(c)})});else this._evaluatePremise(rule,content,cb,i+1)}if(v2)val2.value=null}}if(v1)val1.value=null}}if(v0)val0.value=null}_evaluateRules(rules,content,cb){for(let i=0;i<rules.length;i++){this._evaluatePremise(rules[i],content,cb)}}_reasonGraphNaive(rules,content){const newRules=[];function addRule(conclusion){if(conclusion.next)conclusion.next.forEach(rule=>{newRules.push([conclusion.subject.value,conclusion.predicate.value,conclusion.object.value,rule])})}const addConclusions=conclusion=>{conclusion.forEach(c=>{this._add(c.subject.value,c.predicate.value,c.object.value,content,()=>{addRule(c)})})};this._evaluateRules(rules,content,addRule);let r;while((r=newRules.pop())!==undefined){const[subject,predicate,object,rule]=r;const v1=rule.basePremise.subject.value;if(!v1)rule.basePremise.subject.value=subject;const v2=rule.basePremise.predicate.value;if(!v2)rule.basePremise.predicate.value=predicate;const v3=rule.basePremise.object.value;if(!v3)rule.basePremise.object.value=object;if(rule.premise.length===0){addConclusions(rule.conclusion)}else{this._evaluatePremise(rule,content,addRule)}if(!v1)rule.basePremise.subject.value=null;if(!v2)rule.basePremise.predicate.value=null;if(!v3)rule.basePremise.object.value=null}}_createRule({premise,conclusion}){const varMapping={};const toId=value=>value.termType==="Variable"?varMapping[value.value]=varMapping[value.value]||{}:{value:this._store._termToNewNumericId(value)};const t=term=>({subject:toId(term.subject),predicate:toId(term.predicate),object:toId(term.object)});return{premise:premise.map(p=>t(p)),conclusion:conclusion.map(p=>t(p)),variables:Object.values(varMapping)}}reason(rules){if(!Array.isArray(rules)){rules=getRulesFromDataset(rules)}rules=rules.map(rule=>this._createRule(rule));for(const r1 of rules){for(const r2 of rules){for(let i=0;i<r2.premise.length;i++){const p=r2.premise[i];for(const c of r1.conclusion){if(termEq(p.subject,c.subject)&&termEq(p.predicate,c.predicate)&&termEq(p.object,c.object)){const set=new Set;const premise=[];p.subject.value=p.subject.value||1;p.object.value=p.object.value||1;p.predicate.value=p.predicate.value||1;for(let j=0;j<r2.premise.length;j++){if(j!==i){premise.push(getIndex(r2.premise[j],set))}}(c.next=c.next||[]).push({premise:premise,conclusion:r2.conclusion,basePremise:p})}r2.variables.forEach(v=>{v.value=null})}}}}for(const rule of rules){const set=new Set;rule.premise=rule.premise.map(p=>getIndex(p,set))}const graphs=this._store._getGraphs();for(const graphId in graphs){this._reasonGraphNaive(rules,graphs[graphId])}this._store._size=null}}exports.default=N3Reasoner;function getIndex({subject,predicate,object},set){const s=subject.value||set.has(subject)||(set.add(subject),false);const p=predicate.value||set.has(predicate)||(set.add(predicate),false);const o=object.value||set.has(object)||(set.add(object),false);return!s&&p?{content:"predicates",value:[predicate,object,subject]}:o?{content:"objects",value:[object,subject,predicate]}:{content:"subjects",value:[subject,predicate,object]}}function termEq(t1,t2){if(t1.value===null){t1.value=t2.value}return t1.value===t2.value}},{"./N3DataFactory":3}],7:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.N3EntityIndex=void 0;var _readableStream=require("readable-stream");var _N3DataFactory=_interopRequireWildcard(require("./N3DataFactory"));var _IRIs=_interopRequireDefault(require("./IRIs"));var _N3Util=require("./N3Util");var _N3Writer=_interopRequireDefault(require("./N3Writer"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap,n=new WeakMap;return(_interopRequireWildcard=function(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f)}for(const t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(i.get||i.set)?o(f,t,i):f[t]=e[t]);return f})(e,t)}const ITERATOR=Symbol("iter");function merge(target,source,depth=4){if(depth===0)return Object.assign(target,source);for(const key in source)target[key]=merge(target[key]||Object.create(null),source[key],depth-1);return target}function intersect(s1,s2,depth=4){let target=false;for(const key in s1){if(key in s2){const intersection=depth===0?null:intersect(s1[key],s2[key],depth-1);if(intersection!==false){target=target||Object.create(null);target[key]=intersection}else if(depth===3){return false}}}return target}function difference(s1,s2,depth=4){let target=false;for(const key in s1){if(!(key in s2)){target=target||Object.create(null);target[key]=depth===0?null:merge({},s1[key],depth-1)}else if(depth!==0){const diff=difference(s1[key],s2[key],depth-1);if(diff!==false){target=target||Object.create(null);target[key]=diff}else if(depth===3){return false}}}return target}class N3EntityIndex{constructor(options={}){this._id=1;this._ids=Object.create(null);this._ids[""]=1;this._entities=Object.create(null);this._entities[1]="";this._blankNodeIndex=0;this._factory=options.factory||_N3DataFactory.default}_termFromId(id){if(id[0]==="."){const entities=this._entities;const terms=id.split(".");const q=this._factory.quad(this._termFromId(entities[terms[1]]),this._termFromId(entities[terms[2]]),this._termFromId(entities[terms[3]]),terms[4]&&this._termFromId(entities[terms[4]]));return q}return(0,_N3DataFactory.termFromId)(id,this._factory)}_termToNumericId(term){if(term.termType==="Quad"){const s=this._termToNumericId(term.subject),p=this._termToNumericId(term.predicate),o=this._termToNumericId(term.object);let g;return s&&p&&o&&((0,_N3Util.isDefaultGraph)(term.graph)||(g=this._termToNumericId(term.graph)))&&this._ids[g?`.${s}.${p}.${o}.${g}`:`.${s}.${p}.${o}`]}return this._ids[(0,_N3DataFactory.termToId)(term)]}_termToNewNumericId(term){const str=term&&term.termType==="Quad"?`.${this._termToNewNumericId(term.subject)}.${this._termToNewNumericId(term.predicate)}.${this._termToNewNumericId(term.object)}${(0,_N3Util.isDefaultGraph)(term.graph)?"":`.${this._termToNewNumericId(term.graph)}`}`:(0,_N3DataFactory.termToId)(term);return this._ids[str]||(this._ids[this._entities[++this._id]=str]=this._id)}createBlankNode(suggestedName){let name,index;if(suggestedName){name=suggestedName=`_:${suggestedName}`,index=1;while(this._ids[name])name=suggestedName+index++}else{do{name=`_:b${this._blankNodeIndex++}`}while(this._ids[name])}this._ids[name]=++this._id;this._entities[this._id]=name;return this._factory.blankNode(name.substr(2))}}exports.N3EntityIndex=N3EntityIndex;class N3Store{constructor(quads,options){this._size=0;this._graphs=Object.create(null);if(!options&&quads&&!quads[0]&&!(typeof quads.match==="function"))options=quads,quads=null;options=options||{};this._factory=options.factory||_N3DataFactory.default;this._entityIndex=options.entityIndex||new N3EntityIndex({factory:this._factory});this._entities=this._entityIndex._entities;this._termFromId=this._entityIndex._termFromId.bind(this._entityIndex);this._termToNumericId=this._entityIndex._termToNumericId.bind(this._entityIndex);this._termToNewNumericId=this._entityIndex._termToNewNumericId.bind(this._entityIndex);if(quads)this.addAll(quads)}get size(){let size=this._size;if(size!==null)return size;size=0;const graphs=this._graphs;let subjects,subject;for(const graphKey in graphs)for(const subjectKey in subjects=graphs[graphKey].subjects)for(const predicateKey in subject=subjects[subjectKey])size+=Object.keys(subject[predicateKey]).length;return this._size=size}_addToIndex(index0,key0,key1,key2){const index1=index0[key0]||(index0[key0]={});const index2=index1[key1]||(index1[key1]={});const existed=key2 in index2;if(!existed)index2[key2]=null;return!existed}_removeFromIndex(index0,key0,key1,key2){const index1=index0[key0],index2=index1[key1];delete index2[key2];for(const key in index2)return;delete index1[key1];for(const key in index1)return;delete index0[key0]}*_findInIndex(index0,key0,key1,key2,name0,name1,name2,graphId){let tmp,index1,index2;const entityKeys=this._entities;const graph=this._termFromId(entityKeys[graphId]);const parts={subject:null,predicate:null,object:null};if(key0)(tmp=index0,index0={})[key0]=tmp[key0];for(const value0 in index0){if(index1=index0[value0]){parts[name0]=this._termFromId(entityKeys[value0]);if(key1)(tmp=index1,index1={})[key1]=tmp[key1];for(const value1 in index1){if(index2=index1[value1]){parts[name1]=this._termFromId(entityKeys[value1]);const values=key2?key2 in index2?[key2]:[]:Object.keys(index2);for(let l=0;l<values.length;l++){parts[name2]=this._termFromId(entityKeys[values[l]]);yield this._factory.quad(parts.subject,parts.predicate,parts.object,graph)}}}}}}_loop(index0,callback){for(const key0 in index0)callback(key0)}_loopByKey0(index0,key0,callback){let index1,key1;if(index1=index0[key0]){for(key1 in index1)callback(key1)}}_loopByKey1(index0,key1,callback){let key0,index1;for(key0 in index0){index1=index0[key0];if(index1[key1])callback(key0)}}_loopBy2Keys(index0,key0,key1,callback){let index1,index2,key2;if((index1=index0[key0])&&(index2=index1[key1])){for(key2 in index2)callback(key2)}}_countInIndex(index0,key0,key1,key2){let count=0,tmp,index1,index2;if(key0)(tmp=index0,index0={})[key0]=tmp[key0];for(const value0 in index0){if(index1=index0[value0]){if(key1)(tmp=index1,index1={})[key1]=tmp[key1];for(const value1 in index1){if(index2=index1[value1]){if(key2)key2 in index2&&count++;else count+=Object.keys(index2).length}}}}return count}_getGraphs(graph){graph=graph===""?1:graph&&(this._termToNumericId(graph)||-1);return typeof graph!=="number"?this._graphs:{[graph]:this._graphs[graph]}}_uniqueEntities(callback){const uniqueIds=Object.create(null);return id=>{if(!(id in uniqueIds)){uniqueIds[id]=true;callback(this._termFromId(this._entities[id],this._factory))}}}add(quad){this.addQuad(quad);return this}addQuad(subject,predicate,object,graph){if(!predicate)graph=subject.graph,object=subject.object,predicate=subject.predicate,subject=subject.subject;graph=graph?this._termToNewNumericId(graph):1;let graphItem=this._graphs[graph];if(!graphItem){graphItem=this._graphs[graph]={subjects:{},predicates:{},objects:{}};Object.freeze(graphItem)}subject=this._termToNewNumericId(subject);predicate=this._termToNewNumericId(predicate);object=this._termToNewNumericId(object);if(!this._addToIndex(graphItem.subjects,subject,predicate,object))return false;this._addToIndex(graphItem.predicates,predicate,object,subject);this._addToIndex(graphItem.objects,object,subject,predicate);this._size=null;return true}addQuads(quads){for(let i=0;i<quads.length;i++)this.addQuad(quads[i])}delete(quad){this.removeQuad(quad);return this}has(subjectOrQuad,predicate,object,graph){if(subjectOrQuad&&subjectOrQuad.subject)({subject:subjectOrQuad,predicate,object,graph}=subjectOrQuad);return!this.readQuads(subjectOrQuad,predicate,object,graph).next().done}import(stream){stream.on("data",quad=>{this.addQuad(quad)});return stream}removeQuad(subject,predicate,object,graph){if(!predicate)({subject,predicate,object,graph}=subject);graph=graph?this._termToNumericId(graph):1;const graphs=this._graphs;let graphItem,subjects,predicates;if(!(subject=subject&&this._termToNumericId(subject))||!(predicate=predicate&&this._termToNumericId(predicate))||!(object=object&&this._termToNumericId(object))||!(graphItem=graphs[graph])||!(subjects=graphItem.subjects[subject])||!(predicates=subjects[predicate])||!(object in predicates))return false;this._removeFromIndex(graphItem.subjects,subject,predicate,object);this._removeFromIndex(graphItem.predicates,predicate,object,subject);this._removeFromIndex(graphItem.objects,object,subject,predicate);if(this._size!==null)this._size--;for(subject in graphItem.subjects)return true;delete graphs[graph];return true}removeQuads(quads){for(let i=0;i<quads.length;i++)this.removeQuad(quads[i])}remove(stream){stream.on("data",quad=>{this.removeQuad(quad)});return stream}removeMatches(subject,predicate,object,graph){const stream=new _readableStream.Readable({objectMode:true});const iterable=this.readQuads(subject,predicate,object,graph);stream._read=size=>{while(--size>=0){const{done,value}=iterable.next();if(done){stream.push(null);return}stream.push(value)}};return this.remove(stream)}deleteGraph(graph){return this.removeMatches(null,null,null,graph)}getQuads(subject,predicate,object,graph){return[...this.readQuads(subject,predicate,object,graph)]}*readQuads(subject,predicate,object,graph){const graphs=this._getGraphs(graph);let content,subjectId,predicateId,objectId;if(subject&&!(subjectId=this._termToNumericId(subject))||predicate&&!(predicateId=this._termToNumericId(predicate))||object&&!(objectId=this._termToNumericId(object)))return;for(const graphId in graphs){if(content=graphs[graphId]){if(subjectId){if(objectId)yield*this._findInIndex(content.objects,objectId,subjectId,predicateId,"object","subject","predicate",graphId);else yield*this._findInIndex(content.subjects,subjectId,predicateId,null,"subject","predicate","object",graphId)}else if(predicateId)yield*this._findInIndex(content.predicates,predicateId,objectId,null,"predicate","object","subject",graphId);else if(objectId)yield*this._findInIndex(content.objects,objectId,null,null,"object","subject","predicate",graphId);else yield*this._findInIndex(content.subjects,null,null,null,"subject","predicate","object",graphId)}}}match(subject,predicate,object,graph){return new DatasetCoreAndReadableStream(this,subject,predicate,object,graph,{entityIndex:this._entityIndex})}countQuads(subject,predicate,object,graph){const graphs=this._getGraphs(graph);let count=0,content,subjectId,predicateId,objectId;if(subject&&!(subjectId=this._termToNumericId(subject))||predicate&&!(predicateId=this._termToNumericId(predicate))||object&&!(objectId=this._termToNumericId(object)))return 0;for(const graphId in graphs){if(content=graphs[graphId]){if(subject){if(object)count+=this._countInIndex(content.objects,objectId,subjectId,predicateId);else count+=this._countInIndex(content.subjects,subjectId,predicateId,objectId)}else if(predicate){count+=this._countInIndex(content.predicates,predicateId,objectId,subjectId)}else{count+=this._countInIndex(content.objects,objectId,subjectId,predicateId)}}}return count}forEach(callback,subject,predicate,object,graph){this.some(quad=>{callback(quad,this);return false},subject,predicate,object,graph)}every(callback,subject,predicate,object,graph){return!this.some(quad=>!callback(quad,this),subject,predicate,object,graph)}some(callback,subject,predicate,object,graph){for(const quad of this.readQuads(subject,predicate,object,graph))if(callback(quad,this))return true;return false}getSubjects(predicate,object,graph){const results=[];this.forSubjects(s=>{results.push(s)},predicate,object,graph);return results}forSubjects(callback,predicate,object,graph){const graphs=this._getGraphs(graph);let content,predicateId,objectId;callback=this._uniqueEntities(callback);if(predicate&&!(predicateId=this._termToNumericId(predicate))||object&&!(objectId=this._termToNumericId(object)))return;for(graph in graphs){if(content=graphs[graph]){if(predicateId){if(objectId)this._loopBy2Keys(content.predicates,predicateId,objectId,callback);else this._loopByKey1(content.subjects,predicateId,callback)}else if(objectId)this._loopByKey0(content.objects,objectId,callback);else this._loop(content.subjects,callback)}}}getPredicates(subject,object,graph){const results=[];this.forPredicates(p=>{results.push(p)},subject,object,graph);return results}forPredicates(callback,subject,object,graph){const graphs=this._getGraphs(graph);let content,subjectId,objectId;callback=this._uniqueEntities(callback);if(subject&&!(subjectId=this._termToNumericId(subject))||object&&!(objectId=this._termToNumericId(object)))return;for(graph in graphs){if(content=graphs[graph]){if(subjectId){if(objectId)this._loopBy2Keys(content.objects,objectId,subjectId,callback);else this._loopByKey0(content.subjects,subjectId,callback)}else if(objectId)this._loopByKey1(content.predicates,objectId,callback);else this._loop(content.predicates,callback)}}}getObjects(subject,predicate,graph){const results=[];this.forObjects(o=>{results.push(o)},subject,predicate,graph);return results}forObjects(callback,subject,predicate,graph){const graphs=this._getGraphs(graph);let content,subjectId,predicateId;callback=this._uniqueEntities(callback);if(subject&&!(subjectId=this._termToNumericId(subject))||predicate&&!(predicateId=this._termToNumericId(predicate)))return;for(graph in graphs){if(content=graphs[graph]){if(subjectId){if(predicateId)this._loopBy2Keys(content.subjects,subjectId,predicateId,callback);else this._loopByKey1(content.objects,subjectId,callback)}else if(predicateId)this._loopByKey0(content.predicates,predicateId,callback);else this._loop(content.objects,callback)}}}getGraphs(subject,predicate,object){const results=[];this.forGraphs(g=>{results.push(g)},subject,predicate,object);return results}forGraphs(callback,subject,predicate,object){for(const graph in this._graphs){this.some(quad=>{callback(quad.graph);return true},subject,predicate,object,this._termFromId(this._entities[graph]))}}createBlankNode(suggestedName){return this._entityIndex.createBlankNode(suggestedName)}extractLists({remove=false,ignoreErrors=false}={}){const lists={};const onError=ignoreErrors?()=>true:(node,message)=>{throw new Error(`${node.value} ${message}`)};const tails=this.getQuads(null,_IRIs.default.rdf.rest,_IRIs.default.rdf.nil,null);const toRemove=remove?[...tails]:[];tails.forEach(tailQuad=>{const items=[];let malformed=false;let head;let headPos;const graph=tailQuad.graph;let current=tailQuad.subject;while(current&&!malformed){const objectQuads=this.getQuads(null,null,current,null);const subjectQuads=this.getQuads(current,null,null,null);let quad,first=null,rest=null,parent=null;for(let i=0;i<subjectQuads.length&&!malformed;i++){quad=subjectQuads[i];if(!quad.graph.equals(graph))malformed=onError(current,"not confined to single graph");else if(head)malformed=onError(current,"has non-list arcs out");else if(quad.predicate.value===_IRIs.default.rdf.first){if(first)malformed=onError(current,"has multiple rdf:first arcs");else toRemove.push(first=quad)}else if(quad.predicate.value===_IRIs.default.rdf.rest){if(rest)malformed=onError(current,"has multiple rdf:rest arcs");else toRemove.push(rest=quad)}else if(objectQuads.length)malformed=onError(current,"can't be subject and object");else{head=quad;headPos="subject"}}for(let i=0;i<objectQuads.length&&!malformed;++i){quad=objectQuads[i];if(head)malformed=onError(current,"can't have coreferences");else if(quad.predicate.value===_IRIs.default.rdf.rest){if(parent)malformed=onError(current,"has incoming rdf:rest arcs");else parent=quad}else{head=quad;headPos="object"}}if(!first)malformed=onError(current,"has no list head");else items.unshift(first.object);current=parent&&parent.subject}if(malformed)remove=false;else if(head)lists[head[headPos].value]=items});if(remove)this.removeQuads(toRemove);return lists}addAll(quads){if(quads instanceof DatasetCoreAndReadableStream)quads=quads.filtered;if(Array.isArray(quads))this.addQuads(quads);else if(quads instanceof N3Store&&quads._entityIndex===this._entityIndex){if(quads._size!==0){this._graphs=merge(this._graphs,quads._graphs);this._size=null}}else{for(const quad of quads)this.add(quad)}return this}contains(other){if(other instanceof DatasetCoreAndReadableStream)other=other.filtered;if(other===this)return true;if(!(other instanceof N3Store)||this._entityIndex!==other._entityIndex)return other.every(quad=>this.has(quad));const g1=this._graphs,g2=other._graphs;let s1,s2,p1,p2,o1;for(const graph in g2){if(!(s1=g1[graph]))return false;s1=s1.subjects;for(const subject in s2=g2[graph].subjects){if(!(p1=s1[subject]))return false;for(const predicate in p2=s2[subject]){if(!(o1=p1[predicate]))return false;for(const object in p2[predicate])if(!(object in o1))return false}}}return true}deleteMatches(subject,predicate,object,graph){for(const quad of this.match(subject,predicate,object,graph))this.removeQuad(quad);return this}difference(other){if(other&&other instanceof DatasetCoreAndReadableStream)other=other.filtered;if(other===this)return new N3Store({entityIndex:this._entityIndex});if(other instanceof N3Store&&other._entityIndex===this._entityIndex){const store=new N3Store({entityIndex:this._entityIndex});const graphs=difference(this._graphs,other._graphs);if(graphs){store._graphs=graphs;store._size=null}return store}return this.filter(quad=>!other.has(quad))}equals(other){if(other instanceof DatasetCoreAndReadableStream)other=other.filtered;return other===this||this.size===other.size&&this.contains(other)}filter(iteratee){const store=new N3Store({entityIndex:this._entityIndex});for(const quad of this)if(iteratee(quad,this))store.add(quad);return store}intersection(other){if(other instanceof DatasetCoreAndReadableStream)other=other.filtered;if(other===this){const store=new N3Store({entityIndex:this._entityIndex});store._graphs=merge(Object.create(null),this._graphs);store._size=this._size;return store}else if(other instanceof N3Store&&this._entityIndex===other._entityIndex){const store=new N3Store({entityIndex:this._entityIndex});const graphs=intersect(other._graphs,this._graphs);if(graphs){store._graphs=graphs;store._size=null}return store}return this.filter(quad=>other.has(quad))}map(iteratee){const store=new N3Store({entityIndex:this._entityIndex});for(const quad of this)store.add(iteratee(quad,this));return store}reduce(callback,initialValue){const iter=this.readQuads();let accumulator=initialValue===undefined?iter.next().value:initialValue;for(const quad of iter)accumulator=callback(accumulator,quad,this);return accumulator}toArray(){return this.getQuads()}toCanonical(){throw new Error("not implemented")}toStream(){return this.match()}toString(){return(new _N3Writer.default).quadsToString(this)}union(quads){const store=new N3Store({entityIndex:this._entityIndex});store._graphs=merge(Object.create(null),this._graphs);store._size=this._size;store.addAll(quads);return store}*[Symbol.iterator](){yield*this.readQuads()}}exports.default=N3Store;function indexMatch(index,ids,depth=0){const ind=ids[depth];if(ind&&!(ind in index))return false;let target=false;for(const key in ind?{[ind]:index[ind]}:index){const result=depth===2?null:indexMatch(index[key],ids,depth+1);if(result!==false){target=target||Object.create(null);target[key]=result}}return target}class DatasetCoreAndReadableStream extends _readableStream.Readable{constructor(n3Store,subject,predicate,object,graph,options){super({objectMode:true});Object.assign(this,{n3Store:n3Store,subject:subject,predicate:predicate,object:object,graph:graph,options:options})}get filtered(){if(!this._filtered){const{n3Store,graph,object,predicate,subject}=this;const newStore=this._filtered=new N3Store({factory:n3Store._factory,entityIndex:this.options.entityIndex});let subjectId,predicateId,objectId;if(subject&&!(subjectId=newStore._termToNumericId(subject))||predicate&&!(predicateId=newStore._termToNumericId(predicate))||object&&!(objectId=newStore._termToNumericId(object)))return newStore;const graphs=n3Store._getGraphs(graph);for(const graphKey in graphs){let subjects,predicates,objects,content;if(content=graphs[graphKey]){if(!subjectId&&predicateId){if(predicates=indexMatch(content.predicates,[predicateId,objectId,subjectId])){subjects=indexMatch(content.subjects,[subjectId,predicateId,objectId]);objects=indexMatch(content.objects,[objectId,subjectId,predicateId])}}else if(objectId){if(objects=indexMatch(content.objects,[objectId,subjectId,predicateId])){subjects=indexMatch(content.subjects,[subjectId,predicateId,objectId]);predicates=indexMatch(content.predicates,[predicateId,objectId,subjectId])}}else if(subjects=indexMatch(content.subjects,[subjectId,predicateId,objectId])){predicates=indexMatch(content.predicates,[predicateId,objectId,subjectId]);objects=indexMatch(content.objects,[objectId,subjectId,predicateId])}if(subjects)newStore._graphs[graphKey]={subjects:subjects,predicates:predicates,objects:objects}}}newStore._size=null}return this._filtered}get size(){return this.filtered.size}_read(size){if(size>0&&!this[ITERATOR])this[ITERATOR]=this[Symbol.iterator]();const iterable=this[ITERATOR];while(--size>=0){const{done,value}=iterable.next();if(done){this.push(null);return}this.push(value)}}addAll(quads){return this.filtered.addAll(quads)}contains(other){return this.filtered.contains(other)}deleteMatches(subject,predicate,object,graph){return this.filtered.deleteMatches(subject,predicate,object,graph)}difference(other){return this.filtered.difference(other)}equals(other){return this.filtered.equals(other)}every(callback,subject,predicate,object,graph){return this.filtered.every(callback,subject,predicate,object,graph)}filter(iteratee){return this.filtered.filter(iteratee)}forEach(callback,subject,predicate,object,graph){return this.filtered.forEach(callback,subject,predicate,object,graph)}import(stream){return this.filtered.import(stream)}intersection(other){return this.filtered.intersection(other)}map(iteratee){return this.filtered.map(iteratee)}some(callback,subject,predicate,object,graph){return this.filtered.some(callback,subject,predicate,object,graph)}toCanonical(){return this.filtered.toCanonical()}toStream(){return this._filtered?this._filtered.toStream():this.n3Store.match(this.subject,this.predicate,this.object,this.graph)}union(quads){return this._filtered?this._filtered.union(quads):this.n3Store.match(this.subject,this.predicate,this.object,this.graph).addAll(quads)}toArray(){return this._filtered?this._filtered.toArray():this.n3Store.getQuads(this.subject,this.predicate,this.object,this.graph)}reduce(callback,initialValue){return this.filtered.reduce(callback,initialValue)}toString(){return(new _N3Writer.default).quadsToString(this)}add(quad){return this.filtered.add(quad)}delete(quad){return this.filtered.delete(quad)}has(quad){return this.filtered.has(quad)}match(subject,predicate,object,graph){return new DatasetCoreAndReadableStream(this.filtered,subject,predicate,object,graph,this.options)}*[Symbol.iterator](){yield*this._filtered||this.n3Store.readQuads(this.subject,this.predicate,this.object,this.graph)}}},{"./IRIs":2,"./N3DataFactory":3,"./N3Util":11,"./N3Writer":12,"readable-stream":39}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _N3Store=_interopRequireDefault(require("./N3Store"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}class N3DatasetCoreFactory{dataset(quads){return new _N3Store.default(quads)}}exports.default=N3DatasetCoreFactory},{"./N3Store":7}],9:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _readableStream=require("readable-stream");var _N3Parser=_interopRequireDefault(require("./N3Parser"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}class N3StreamParser extends _readableStream.Transform{constructor(options){super({decodeStrings:true});this._readableState.objectMode=true;const parser=new _N3Parser.default(options);let onData,onEnd;const callbacks={onQuad:(error,quad)=>{error&&this.emit("error",error)||quad&&this.push(quad)},onPrefix:(prefix,uri)=>{this.emit("prefix",prefix,uri)}};if(options&&options.comments)callbacks.onComment=comment=>{this.emit("comment",comment)};parser.parse({on:(event,callback)=>{switch(event){case"data":onData=callback;break;case"end":onEnd=callback;break}}},callbacks);this._transform=(chunk,encoding,done)=>{onData(chunk);done()};this._flush=done=>{onEnd();done()}}import(stream){stream.on("data",chunk=>{this.write(chunk)});stream.on("end",()=>{this.end()});stream.on("error",error=>{this.emit("error",error)});return this}}exports.default=N3StreamParser},{"./N3Parser":5,"readable-stream":39}],10:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _readableStream=require("readable-stream");var _N3Writer=_interopRequireDefault(require("./N3Writer"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}class N3StreamWriter extends _readableStream.Transform{constructor(options){super({encoding:"utf8",writableObjectMode:true});const writer=this._writer=new _N3Writer.default({write:(quad,encoding,callback)=>{this.push(quad);callback&&callback()},end:callback=>{this.push(null);callback&&callback()}},options);this._transform=(quad,encoding,done)=>{writer.addQuad(quad,done)};this._flush=done=>{writer.end(done)}}import(stream){stream.on("data",quad=>{this.write(quad)});stream.on("end",()=>{this.end()});stream.on("error",error=>{this.emit("error",error)});stream.on("prefix",(prefix,iri)=>{this._writer.addPrefix(prefix,iri)});return this}}exports.default=N3StreamWriter},{"./N3Writer":12,"readable-stream":39}],11:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.inDefaultGraph=inDefaultGraph;exports.isBlankNode=isBlankNode;exports.isDefaultGraph=isDefaultGraph;exports.isLiteral=isLiteral;exports.isNamedNode=isNamedNode;exports.isQuad=isQuad;exports.isVariable=isVariable;exports.prefix=prefix;exports.prefixes=prefixes;var _N3DataFactory=_interopRequireDefault(require("./N3DataFactory"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function isNamedNode(term){return!!term&&term.termType==="NamedNode"}function isBlankNode(term){return!!term&&term.termType==="BlankNode"}function isLiteral(term){return!!term&&term.termType==="Literal"}function isVariable(term){return!!term&&term.termType==="Variable"}function isQuad(term){return!!term&&term.termType==="Quad"}function isDefaultGraph(term){return!!term&&term.termType==="DefaultGraph"}function inDefaultGraph(quad){return isDefaultGraph(quad.graph)}function prefix(iri,factory){return prefixes({"":iri.value||iri},factory)("")}function prefixes(defaultPrefixes,factory){const prefixes=Object.create(null);for(const prefix in defaultPrefixes)processPrefix(prefix,defaultPrefixes[prefix]);factory=factory||_N3DataFactory.default;function processPrefix(prefix,iri){if(typeof iri==="string"){const cache=Object.create(null);prefixes[prefix]=local=>{return cache[local]||(cache[local]=factory.namedNode(iri+local))}}else if(!(prefix in prefixes)){throw new Error(`Unknown prefix: ${prefix}`)}return prefixes[prefix]}return processPrefix}},{"./N3DataFactory":3}],12:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _IRIs=_interopRequireDefault(require("./IRIs"));var _N3DataFactory=_interopRequireWildcard(require("./N3DataFactory"));var _N3Util=require("./N3Util");var _BaseIRI=_interopRequireDefault(require("./BaseIRI"));var _Util=require("./Util");function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap,n=new WeakMap;return(_interopRequireWildcard=function(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f)}for(const t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(i.get||i.set)?o(f,t,i):f[t]=e[t]);return f})(e,t)}function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const DEFAULTGRAPH=_N3DataFactory.default.defaultGraph();const{rdf,xsd}=_IRIs.default;const escape=/["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,escapeAll=/["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,escapedCharacters={"\\":"\\\\",'"':'\\"',"\t":"\\t","\n":"\\n","\r":"\\r","\b":"\\b","\f":"\\f"};class SerializedTerm extends _N3DataFactory.Term{equals(other){return other===this}}class N3Writer{constructor(outputStream,options){this._prefixRegex=/$0^/;if(outputStream&&typeof outputStream.write!=="function")options=outputStream,outputStream=null;options=options||{};this._lists=options.lists;if(!outputStream){let output="";this._outputStream={write(chunk,encoding,done){output+=chunk;done&&done()},end:done=>{done&&done(null,output)}};this._endStream=true}else{this._outputStream=outputStream;this._endStream=options.end===undefined?true:!!options.end}this._subject=null;if(!/triple|quad/i.test(options.format)){this._lineMode=false;this._graph=DEFAULTGRAPH;this._prefixIRIs=Object.create(null);options.prefixes&&this.addPrefixes(options.prefixes);if(options.baseIRI){this._baseIri=new _BaseIRI.default(options.baseIRI)}}else{this._lineMode=true;this._writeQuad=this._writeQuadLine}}get _inDefaultGraph(){return DEFAULTGRAPH.equals(this._graph)}_write(string,callback){this._outputStream.write(string,"utf8",callback)}_writeQuad(subject,predicate,object,graph,done){try{if(!graph.equals(this._graph)){this._write((this._subject===null?"":this._inDefaultGraph?".\n":"\n}\n")+(DEFAULTGRAPH.equals(graph)?"":`${this._encodeIriOrBlank(graph)} {\n`));this._graph=graph;this._subject=null}if(subject.equals(this._subject)){if(predicate.equals(this._predicate))this._write(`, ${this._encodeObject(object)}`,done);else this._write(`;\n ${this._encodePredicate(this._predicate=predicate)} ${this._encodeObject(object)}`,done)}else this._write(`${(this._subject===null?"":".\n")+this._encodeSubject(this._subject=subject)} ${this._encodePredicate(this._predicate=predicate)} ${this._encodeObject(object)}`,done)}catch(error){done&&done(error)}}_writeQuadLine(subject,predicate,object,graph,done){delete this._prefixMatch;this._write(this.quadToString(subject,predicate,object,graph),done)}quadToString(subject,predicate,object,graph){return`${this._encodeSubject(subject)} ${this._encodeIriOrBlank(predicate)} ${this._encodeObject(object)}${graph&&graph.value?` ${this._encodeIriOrBlank(graph)} .\n`:" .\n"}`}quadsToString(quads){let quadsString="";for(const quad of quads)quadsString+=this.quadToString(quad.subject,quad.predicate,quad.object,quad.graph);return quadsString}_encodeSubject(entity){return entity.termType==="Quad"?this._encodeQuad(entity):this._encodeIriOrBlank(entity)}_encodeIriOrBlank(entity){if(entity.termType!=="NamedNode"){if(this._lists&&entity.value in this._lists)entity=this.list(this._lists[entity.value]);return"id"in entity?entity.id:`_:${entity.value}`}let iri=entity.value;if(this._baseIri){iri=this._baseIri.toRelative(iri)}if(escape.test(iri))iri=iri.replace(escapeAll,characterReplacer);const prefixMatch=this._prefixRegex.exec(iri);return!prefixMatch?`<${iri}>`:!prefixMatch[1]?iri:this._prefixIRIs[prefixMatch[1]]+prefixMatch[2]}_encodeLiteral(literal){let value=literal.value;if(escape.test(value))value=value.replace(escapeAll,characterReplacer);if(literal.language)return`"${value}"@${literal.language}`;if(this._lineMode){if(literal.datatype.value===xsd.string)return`"${value}"`}else{switch(literal.datatype.value){case xsd.string:return`"${value}"`;case xsd.boolean:if(value==="true"||value==="false")return value;break;case xsd.integer:if(/^[+-]?\d+$/.test(value))return value;break;case xsd.decimal:if(/^[+-]?\d*\.\d+$/.test(value))return value;break;case xsd.double:if(/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(value))return value;break}}return`"${value}"^^${this._encodeIriOrBlank(literal.datatype)}`}_encodePredicate(predicate){return predicate.value===rdf.type?"a":this._encodeIriOrBlank(predicate)}_encodeObject(object){switch(object.termType){case"Quad":return this._encodeQuad(object);case"Literal":return this._encodeLiteral(object);default:return this._encodeIriOrBlank(object)}}_encodeQuad({subject,predicate,object,graph}){return`<<${this._encodeSubject(subject)} ${this._encodePredicate(predicate)} ${this._encodeObject(object)}${(0,_N3Util.isDefaultGraph)(graph)?"":` ${this._encodeIriOrBlank(graph)}`}>>`}_blockedWrite(){throw new Error("Cannot write because the writer has been closed.")}addQuad(subject,predicate,object,graph,done){if(object===undefined)this._writeQuad(subject.subject,subject.predicate,subject.object,subject.graph,predicate);else if(typeof graph==="function")this._writeQuad(subject,predicate,object,DEFAULTGRAPH,graph);else this._writeQuad(subject,predicate,object,graph||DEFAULTGRAPH,done)}addQuads(quads){for(let i=0;i<quads.length;i++)this.addQuad(quads[i])}addPrefix(prefix,iri,done){const prefixes={};prefixes[prefix]=iri;this.addPrefixes(prefixes,done)}addPrefixes(prefixes,done){if(!this._prefixIRIs)return done&&done();let hasPrefixes=false;for(let prefix in prefixes){let iri=prefixes[prefix];if(typeof iri!=="string")iri=iri.value;hasPrefixes=true;if(this._subject!==null){this._write(this._inDefaultGraph?".\n":"\n}\n");this._subject=null,this._graph=""}this._prefixIRIs[iri]=prefix+=":";this._write(`@prefix ${prefix} <${iri}>.\n`)}if(hasPrefixes){let IRIlist="",prefixList="";for(const prefixIRI in this._prefixIRIs){IRIlist+=IRIlist?`|${prefixIRI}`:prefixIRI;prefixList+=(prefixList?"|":"")+this._prefixIRIs[prefixIRI]}IRIlist=(0,_Util.escapeRegex)(IRIlist,/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&");this._prefixRegex=new RegExp(`^(?:${prefixList})[^\/]*$|`+`^(${IRIlist})([_a-zA-Z0-9][\\-_a-zA-Z0-9]*)$`)}this._write(hasPrefixes?"\n":"",done)}blank(predicate,object){let children=predicate,child,length;if(predicate===undefined)children=[];else if(predicate.termType)children=[{predicate:predicate,object:object}];else if(!("length"in predicate))children=[predicate];switch(length=children.length){case 0:return new SerializedTerm("[]");case 1:child=children[0];if(!(child.object instanceof SerializedTerm))return new SerializedTerm(`[ ${this._encodePredicate(child.predicate)} ${this._encodeObject(child.object)} ]`);default:let contents="[";for(let i=0;i<length;i++){child=children[i];if(child.predicate.equals(predicate))contents+=`, ${this._encodeObject(child.object)}`;else{contents+=`${(i?";\n ":"\n ")+this._encodePredicate(child.predicate)} ${this._encodeObject(child.object)}`;predicate=child.predicate}}return new SerializedTerm(`${contents}\n]`)}}list(elements){const length=elements&&elements.length||0,contents=new Array(length);for(let i=0;i<length;i++)contents[i]=this._encodeObject(elements[i]);return new SerializedTerm(`(${contents.join(" ")})`)}end(done){if(this._subject!==null){this._write(this._inDefaultGraph?".\n":"\n}\n");this._subject=null}this._write=this._blockedWrite;let singleDone=done&&((error,result)=>{singleDone=null,done(error,result)});if(this._endStream){try{return this._outputStream.end(singleDone)}catch(error){}}singleDone&&singleDone()}}exports.default=N3Writer;function characterReplacer(character){let result=escapedCharacters[character];if(result===undefined){if(character.length===1){result=character.charCodeAt(0).toString(16);result="\\u0000".substr(0,6-result.length)+result}else{result=((character.charCodeAt(0)-55296)*1024+character.charCodeAt(1)+9216).toString(16);result="\\U00000000".substr(0,10-result.length)+result}}return result}},{"./BaseIRI":1,"./IRIs":2,"./N3DataFactory":3,"./N3Util":11,"./Util":13}],13:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.escapeRegex=escapeRegex;function escapeRegex(regex){return regex.replace(/[\]\/\(\)\*\+\?\.\\\$]/g,"\\$&")}},{}],14:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"BaseIRI",{enumerable:true,get:function(){return _BaseIRI.default}});Object.defineProperty(exports,"BlankNode",{enumerable:true,get:function(){return _N3DataFactory.BlankNode}});Object.defineProperty(exports,"DataFactory",{enumerable:true,get:function(){return _N3DataFactory.default}});Object.defineProperty(exports,"DefaultGraph",{enumerable:true,get:function(){return _N3DataFactory.DefaultGraph}});Object.defineProperty(exports,"EntityIndex",{enumerable:true,get:function(){return _N3Store.N3EntityIndex}});Object.defineProperty(exports,"Lexer",{enumerable:true,get:function(){return _N3Lexer.default}});Object.defineProperty(exports,"Literal",{enumerable:true,get:function(){return _N3DataFactory.Literal}});Object.defineProperty(exports,"NamedNode",{enumerable:true,get:function(){return _N3DataFactory.NamedNode}});Object.defineProperty(exports,"Parser",{enumerable:true,get:function(){return _N3Parser.default}});Object.defineProperty(exports,"Quad",{enumerable:true,get:function(){return _N3DataFactory.Quad}});Object.defineProperty(exports,"Reasoner",{enumerable:true,get:function(){return _N3Reasoner.default}});Object.defineProperty(exports,"Store",{enumerable:true,get:function(){return _N3Store.default}});Object.defineProperty(exports,"StoreFactory",{enumerable:true,get:function(){return _N3StoreFactory.default}});Object.defineProperty(exports,"StreamParser",{enumerable:true,get:function(){return _N3StreamParser.default}});Object.defineProperty(exports,"StreamWriter",{enumerable:true,get:function(){return _N3StreamWriter.default}});Object.defineProperty(exports,"Term",{enumerable:true,get:function(){return _N3DataFactory.Term}});Object.defineProperty(exports,"Triple",{enumerable:true,get:function(){return _N3DataFactory.Triple}});exports.Util=void 0;Object.defineProperty(exports,"Variable",{enumerable:true,get:function(){return _N3DataFactory.Variable}});Object.defineProperty(exports,"Writer",{enumerable:true,get:function(){return _N3Writer.default}});exports.default=void 0;Object.defineProperty(exports,"getRulesFromDataset",{enumerable:true,get:function(){return _N3Reasoner.getRulesFromDataset}});Object.defineProperty(exports,"termFromId",{enumerable:true,get:function(){return _N3DataFactory.termFromId}});Object.defineProperty(exports,"termToId",{enumerable:true,get:function(){return _N3DataFactory.termToId}});var _N3Lexer=_interopRequireDefault(require("./N3Lexer"));var _N3Parser=_interopRequireDefault(require("./N3Parser"));var _N3Writer=_interopRequireDefault(require("./N3Writer"));var _N3Store=_interopRequireWildcard(require("./N3Store"));var _N3StoreFactory=_interopRequireDefault(require("./N3StoreFactory"));var _N3Reasoner=_interopRequireWildcard(require("./N3Reasoner"));var _N3StreamParser=_interopRequireDefault(require("./N3StreamParser"));var _N3StreamWriter=_interopRequireDefault(require("./N3StreamWriter"));var Util=_interopRequireWildcard(require("./N3Util"));exports.Util=Util;var _BaseIRI=_interopRequireDefault(require("./BaseIRI"));var _N3DataFactory=_interopRequireWildcard(require("./N3DataFactory"));function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap,n=new WeakMap;return(_interopRequireWildcard=function(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,default:e};if(null===e||"object"!=typeof e&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f)}for(const t in e)"default"!==t&&{}.hasOwnProperty.call(e,t)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(i.get||i.set)?o(f,t,i):f[t]=e[t]);return f})(e,t)}function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}var _default=exports.default={Lexer:_N3Lexer.default,Parser:_N3Parser.default,Writer:_N3Writer.default,Store:_N3Store.default,StoreFactory:_N3StoreFactory.default,EntityIndex:_N3Store.N3EntityIndex,StreamParser:_N3StreamParser.default,StreamWriter:_N3StreamWriter.default,Util:Util,Reasoner:_N3Reasoner.default,BaseIRI:_BaseIRI.default,DataFactory:_N3DataFactory.default,Term:_N3DataFactory.Term,NamedNode:_N3DataFactory.NamedNode,Literal:_N3DataFactory.Literal,BlankNode:_N3DataFactory.BlankNode,Variable:_N3DataFactory.Variable,DefaultGraph:_N3DataFactory.DefaultGraph,Quad:_N3DataFactory.Quad,Triple:_N3DataFactory.Triple,termFromId:_N3DataFactory.termFromId,termToId:_N3DataFactory.termToId}},{"./BaseIRI":1,"./N3DataFactory":3,"./N3Lexer":4,"./N3Parser":5,"./N3Reasoner":6,"./N3Store":7,"./N3StoreFactory":8,"./N3StreamParser":9,"./N3StreamWriter":10,"./N3Util":11,"./N3Writer":12}],15:[function(require,module,exports){"use strict";const{AbortController,AbortSignal}=typeof self!=="undefined"?self:typeof window!=="undefined"?window:undefined;module.exports=AbortController;module.exports.AbortSignal=AbortSignal;module.exports.default=AbortController},{}],16:[function(require,module,exports){"use strict";exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i<len;++i){lookup[i]=code[i];revLookup[code.charCodeAt(i)]=i}revLookup["-".charCodeAt(0)]=62;revLookup["_".charCodeAt(0)]=63;function getLens(b64){var len=b64.length;if(len%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var validLen=b64.indexOf("=");if(validLen===-1)validLen=len;var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;var len=placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i<len;i+=4){tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)];arr[curByte++]=tmp>>16&255;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&255}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;i<end;i+=3){tmp=(uint8[i]<<16&16711680)+(uint8[i+1]<<8&65280)+(uint8[i+2]&255);output.push(tripletToBase64(tmp))}return output.join("")}function fromByteArray(uint8){var tmp;var len=uint8.length;var extraBytes=len%3;var parts=[];var maxChunkLength=16383;for(var i=0,len2=len-extraBytes;i<len2;i+=maxChunkLength){parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")}return parts.join("")}},{}],17:[function(require,module,exports){(function(Buffer){(function(){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;var K_MAX_LENGTH=2147483647;exports.kMaxLength=K_MAX_LENGTH;Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport();if(!Buffer.TYPED_ARRAY_SUPPORT&&typeof console!=="undefined"&&typeof console.error==="function"){console.error("This browser lacks typed array (Uint8Array) support which is required by "+"`buffer` v5.x. Use `buffer` v4.x if you require old browser support.")}function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42}catch(e){return false}}Object.defineProperty(Buffer.prototype,"parent",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.buffer}});Object.defineProperty(Buffer.prototype,"offset",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.byteOffset}});function createBuffer(length){if(length>K_MAX_LENGTH){throw new RangeError('The value "'+length+'" is invalid for option "size"')}var buf=new Uint8Array(length);buf.__proto__=Buffer.prototype;return buf}function Buffer(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new TypeError('The "string" argument must be of type string. Received type number')}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species!=null&&Buffer[Symbol.species]===Buffer){Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="string"){return fromString(value,encodingOrOffset)}if(ArrayBuffer.isView(value)){return fromArrayLike(value)}if(value==null){throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('The "value" argument must not be of type number. Received type number')}var valueOf=value.valueOf&&value.valueOf();if(valueOf!=null&&valueOf!==value){return Buffer.from(valueOf,encodingOrOffset,length)}var b=fromObject(value);if(b)return b;if(typeof Symbol!=="undefined"&&Symbol.toPrimitive!=null&&typeof value[Symbol.toPrimitive]==="function"){return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length)}throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array;function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be of type number')}else if(size<0){throw new RangeError('The value "'+size+'" is invalid for option "size"')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==undefined){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer.allocUnsafe=function(size){return allocUnsafe(size)};Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i<length;i+=1){buf[i]=array[i]&255}return buf}function fromArrayBuffer(array,byteOffset,length){if(byteOffset<0||array.byteLength<byteOffset){throw new RangeError('"offset" is outside of buffer bounds')}if(array.byteLength<byteOffset+(length||0)){throw new RangeError('"length" is outside of buffer bounds')}var buf;if(byteOffset===undefined&&length===undefined){buf=new Uint8Array(array)}else if(length===undefined){buf=new Uint8Array(array,byteOffset)}else{buf=new Uint8Array(array,byteOffset,length)}buf.__proto__=Buffer.prototype;return buf}function fromObject(obj){if(Buffer.isBuffer(obj)){var len=checked(obj.length)|0;var buf=createBuffer(len);if(buf.length===0){return buf}obj.copy(buf,0,0,len);return buf}if(obj.length!==undefined){if(typeof obj.length!=="number"||numberIsNaN(obj.length)){return createBuffer(0)}return fromArrayLike(obj)}if(obj.type==="Buffer"&&Array.isArray(obj.data)){return fromArrayLike(obj.data)}}function checked(length){if(length>=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true&&b!==Buffer.prototype};Buffer.compare=function compare(a,b){if(isInstance(a,Uint8Array))a=Buffer.from(a,a.offset,a.byteLength);if(isInstance(b,Uint8Array))b=Buffer.from(b,b.offset,b.byteLength);if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array')}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len;++i){if(a[i]!==b[i]){x=a[i];y=b[i];break}}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function isEncoding(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function concat(list,length){if(!Array.isArray(list)){throw new TypeError('"list" argument must be an Array of Buffers')}if(list.length===0){return Buffer.alloc(0)}var i;if(length===undefined){length=0;for(i=0;i<list.length;++i){length+=list[i].length}}var buffer=Buffer.allocUnsafe(length);var pos=0;for(i=0;i<list.length;++i){var buf=list[i];if(isInstance(buf,Uint8Array)){buf=Buffer.from(buf)}if(!Buffer.isBuffer(buf)){throw new TypeError('"list" argument must be an Array of Buffers')}buf.copy(buffer,pos);pos+=buf.length}return buffer};function byteLength(string,encoding){if(Buffer.isBuffer(string)){return string.length}if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer)){return string.byteLength}if(typeof string!=="string"){throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. '+"Received type "+typeof string)}var len=string.length;var mustMatch=arguments.length>2&&arguments[2]===true;if(!mustMatch&&len===0)return 0;var loweredCase=false;for(;;){switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return len*2;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase){return mustMatch?-1:utf8ToBytes(string).length}encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i<len;i+=2){swap(this,i,i+1)}return this};Buffer.prototype.swap32=function swap32(){var len=this.length;if(len%4!==0){throw new RangeError("Buffer size must be a multiple of 32-bits")}for(var i=0;i<len;i+=4){swap(this,i,i+3);swap(this,i+1,i+2)}return this};Buffer.prototype.swap64=function swap64(){var len=this.length;if(len%8!==0){throw new RangeError("Buffer size must be a multiple of 64-bits")}for(var i=0;i<len;i+=8){swap(this,i,i+7);swap(this,i+1,i+6);swap(this,i+2,i+5);swap(this,i+3,i+4)}return this};Buffer.prototype.toString=function toString(){var length=this.length;if(length===0)return"";if(arguments.length===0)return utf8Slice(this,0,length);return slowToString.apply(this,arguments)};Buffer.prototype.toLocaleString=Buffer.prototype.toString;Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");if(this===b)return true;return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function inspect(){var str="";var max=exports.INSPECT_MAX_BYTES;str=this.toString("hex",0,max).replace(/(.{2})/g,"$1 ").trim();if(this.length>max)str+=" ... ";return"<Buffer "+str+">"};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)){target=Buffer.from(target,target.offset,target.byteLength)}if(!Buffer.isBuffer(target)){throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. '+"Received type "+typeof target)}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i<len;++i){if(thisCopy[i]!==targetCopy[i]){x=thisCopy[i];y=targetCopy[i];break}}if(x<y)return-1;if(y<x)return 1;return 0};function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(buffer.length===0)return-1;if(typeof byteOffset==="string"){encoding=byteOffset;byteOffset=0}else if(byteOffset>2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;i<arrLength;i++){if(read(arr,i)===read(val,foundIndex===-1?0:i-foundIndex)){if(foundIndex===-1)foundIndex=i;if(i-foundIndex+1===valLength)return foundIndex*indexSize}else{if(foundIndex!==-1)i-=i-foundIndex;foundIndex=-1}}}else{if(byteOffset+valLength>arrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;j<valLength;j++){if(read(arr,i+j)!==read(val,j)){found=false;break}}if(found)return i}}return-1}Buffer.prototype.includes=function includes(val,byteOffset,encoding){return this.indexOf(val,byteOffset,encoding)!==-1};Buffer.prototype.indexOf=function indexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,true)};Buffer.prototype.lastIndexOf=function lastIndexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,false)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(length>strLen/2){length=strLen/2}for(var i=0;i<length;++i){var parsed=parseInt(string.substr(i*2,2),16);if(numberIsNaN(parsed))return i;buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function latin1Write(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}Buffer.prototype.write=function write(string,offset,length,encoding){if(offset===undefined){encoding="utf8";length=this.length;offset=0}else if(length===undefined&&typeof offset==="string"){encoding=offset;length=this.length;offset=0}else if(isFinite(offset)){offset=offset>>>0;if(isFinite(length)){length=length>>>0;if(encoding===undefined)encoding="utf8"}else{encoding=length;length=undefined}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i<end){var firstByte=buf[i];var codePoint=null;var bytesPerSequence=firstByte>239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(i<len){res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH))}return res}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i){ret+=String.fromCharCode(buf[i]&127)}return ret}function latin1Slice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i){ret+=String.fromCharCode(buf[i])}return ret}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;++i){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function slice(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;var newBuf=this.subarray(start,end);newBuf.__proto__=Buffer.prototype;return newBuf};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256)){val+=this[offset+i]*mul}return val};Buffer.prototype.readUIntBE=function readUIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){checkOffset(offset,byteLength,this.length)}var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256)){val+=this[offset+i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||value<min)throw new RangeError('"value" argument is out of bounds');if(offset+ext>buf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUIntBE=function writeUIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256)){if(value<0&&sub===0&&this[offset+i-1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end<start)end=start;if(end===start)return 0;if(target.length===0||this.length===0)return 0;if(targetStart<0){throw new RangeError("targetStart out of bounds")}if(start<0||start>=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart<end-start){end=target.length-targetStart+start}var len=end-start;if(this===target&&typeof Uint8Array.prototype.copyWithin==="function"){this.copyWithin(targetStart,start,end)}else if(this===target&&start<targetStart&&targetStart<end){for(var i=len-1;i>=0;--i){target[i+targetStart]=this[i+start]}}else{Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart)}return len};Buffer.prototype.fill=function fill(val,start,end,encoding){if(typeof val==="string"){if(typeof start==="string"){encoding=start;start=0;end=this.length}else if(typeof end==="string"){encoding=end;end=this.length}if(encoding!==undefined&&typeof encoding!=="string"){throw new TypeError("encoding must be a string")}if(typeof encoding==="string"&&!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}if(val.length===1){var code=val.charCodeAt(0);if(encoding==="utf8"&&code<128||encoding==="latin1"){val=code}}}else if(typeof val==="number"){val=val&255}if(start<0||this.length<start||this.length<end){throw new RangeError("Out of range index")}if(end<=start){return this}start=start>>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i<end;++i){this[i]=val}}else{var bytes=Buffer.isBuffer(val)?val:Buffer.from(val,encoding);var len=bytes.length;if(len===0){throw new TypeError('The value "'+val+'" is invalid for argument "value"')}for(i=0;i<end-start;++i){this[i+start]=bytes[i%len]}}return this};var INVALID_BASE64_RE=/[^+/0-9A-Za-z-_]/g;function base64clean(str){str=str.split("=")[0];str=str.trim().replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0){str=str+"="}return str}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(string,units){units=units||Infinity;var codePoint;var length=string.length;var leadSurrogate=null;var bytes=[];for(var i=0;i<length;++i){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;++i){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;++i){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;++i){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isInstance(obj,type){return obj instanceof type||obj!=null&&obj.constructor!=null&&obj.constructor.name!=null&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}}).call(this)}).call(this,require("buffer").Buffer)},{"base64-js":16,buffer:17,ieee754:19}],18:[function(require,module,exports){"use strict";var R=typeof Reflect==="object"?Reflect:null;var ReflectApply=R&&typeof R.apply==="function"?R.apply:function ReflectApply(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)};var ReflectOwnKeys;if(R&&typeof R.ownKeys==="function"){ReflectOwnKeys=R.ownKeys}else if(Object.getOwnPropertySymbols){ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}}else{ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target)}}function ProcessEmitWarning(warning){if(console&&console.warn)console.warn(warning)}var NumberIsNaN=Number.isNaN||function NumberIsNaN(value){return value!==value};function EventEmitter(){EventEmitter.init.call(this)}module.exports=EventEmitter;module.exports.once=once;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._eventsCount=0;EventEmitter.prototype._maxListeners=undefined;var defaultMaxListeners=10;function checkListener(listener){if(typeof listener!=="function"){throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof listener)}}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:true,get:function(){return defaultMaxListeners},set:function(arg){if(typeof arg!=="number"||arg<0||NumberIsNaN(arg)){throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+arg+".")}defaultMaxListeners=arg}});EventEmitter.init=function(){if(this._events===undefined||this._events===Object.getPrototypeOf(this)._events){this._events=Object.create(null);this._eventsCount=0}this._maxListeners=this._maxListeners||undefined};EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if(typeof n!=="number"||n<0||NumberIsNaN(n)){throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+n+".")}this._maxListeners=n;return this};function _getMaxListeners(that){if(that._maxListeners===undefined)return EventEmitter.defaultMaxListeners;return that._maxListeners}EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)};EventEmitter.prototype.emit=function emit(type){var args=[];for(var i=1;i<arguments.length;i++)args.push(arguments[i]);var doError=type==="error";var events=this._events;if(events!==undefined)doError=doError&&events.error===undefined;else if(!doError)return false;if(doError){var er;if(args.length>0)er=args[0];if(er instanceof Error){throw er}var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));err.context=er;throw err}var handler=events[type];if(handler===undefined)return false;if(typeof handler==="function"){ReflectApply(handler,this,args)}else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i<len;++i)ReflectApply(listeners[i],this,args)}return true};function _addListener(target,type,listener,prepend){var m;var events;var existing;checkListener(listener);events=target._events;if(events===undefined){events=target._events=Object.create(null);target._eventsCount=0}else{if(events.newListener!==undefined){target.emit("newListener",type,listener.listener?listener.listener:listener);events=target._events}existing=events[type]}if(existing===undefined){existing=events[type]=listener;++target._eventsCount}else{if(typeof existing==="function"){existing=events[type]=prepend?[listener,existing]:[existing,listener]}else if(prepend){existing.unshift(listener)}else{existing.push(listener)}m=_getMaxListeners(target);if(m>0&&existing.length>m&&!existing.warned){existing.warned=true;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners "+"added. Use emitter.setMaxListeners() to "+"increase limit");w.name="MaxListenersExceededWarning";w.emitter=target;w.type=type;w.count=existing.length;ProcessEmitWarning(w)}}return target}EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,false)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,true)};function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=true;if(arguments.length===0)return this.listener.call(this.target);return this.listener.apply(this.target,arguments)}}function _onceWrap(target,type,listener){var state={fired:false,wrapFn:undefined,target:target,type:type,listener:listener};var wrapped=onceWrapper.bind(state);wrapped.listener=listener;state.wrapFn=wrapped;return wrapped}EventEmitter.prototype.once=function once(type,listener){checkListener(listener);this.on(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){checkListener(listener);this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;checkListener(listener);events=this._events;if(events===undefined)return this;list=events[type];if(list===undefined)return this;if(list===listener||list.listener===listener){if(--this._eventsCount===0)this._events=Object.create(null);else{delete events[type];if(events.removeListener)this.emit("removeListener",type,list.listener||listener)}}else if(typeof list!=="function"){position=-1;for(i=list.length-1;i>=0;i--){if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener;position=i;break}}if(position<0)return this;if(position===0)list.shift();else{spliceOne(list,position)}if(list.length===1)events[type]=list[0];if(events.removeListener!==undefined)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;events=this._events;if(events===undefined)return this;if(events.removeListener===undefined){if(arguments.length===0){this._events=Object.create(null);this._eventsCount=0}else if(events[type]!==undefined){if(--this._eventsCount===0)this._events=Object.create(null);else delete events[type]}return this}if(arguments.length===0){var keys=Object.keys(events);var key;for(i=0;i<keys.length;++i){key=keys[i];if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events=Object.create(null);this._eventsCount=0;return this}listeners=events[type];if(typeof listeners==="function"){this.removeListener(type,listeners)}else if(listeners!==undefined){for(i=listeners.length-1;i>=0;i--){this.removeListener(type,listeners[i])}}return this};function _listeners(target,type,unwrap){var events=target._events;if(events===undefined)return[];var evlistener=events[type];if(evlistener===undefined)return[];if(typeof evlistener==="function")return unwrap?[evlistener.listener||evlistener]:[evlistener];return unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,true)};EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,false)};EventEmitter.listenerCount=function(emitter,type){if(typeof emitter.listenerCount==="function"){return emitter.listenerCount(type)}else{return listenerCount.call(emitter,type)}};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(type){var events=this._events;if(events!==undefined){var evlistener=events[type];if(typeof evlistener==="function"){return 1}else if(evlistener!==undefined){return evlistener.length}}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(arr,n){var copy=new Array(n);for(var i=0;i<n;++i)copy[i]=arr[i];return copy}function spliceOne(list,index){for(;index+1<list.length;index++)list[index]=list[index+1];list.pop()}function unwrapListeners(arr){var ret=new Array(arr.length);for(var i=0;i<ret.length;++i){ret[i]=arr[i].listener||arr[i]}return ret}function once(emitter,name){return new Promise(function(resolve,reject){function errorListener(err){emitter.removeListener(name,resolver);reject(err)}function resolver(){if(typeof emitter.removeListener==="function"){emitter.removeListener("error",errorListener)}resolve([].slice.call(arguments))}eventTargetAgnosticAddListener(emitter,name,resolver,{once:true});if(name!=="error"){addErrorHandlerIfEventEmitter(emitter,errorListener,{once:true})}})}function addErrorHandlerIfEventEmitter(emitter,handler,flags){if(typeof emitter.on==="function"){eventTargetAgnosticAddListener(emitter,"error",handler,flags)}}function eventTargetAgnosticAddListener(emitter,name,listener,flags){if(typeof emitter.on==="function"){if(flags.once){emitter.once(name,listener)}else{emitter.on(name,listener)}}else if(typeof emitter.addEventListener==="function"){emitter.addEventListener(name,function wrapListener(arg){if(flags.once){emitter.removeEventListener(name,wrapListener)}listener(arg)})}else{throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof emitter)}}},{}],19:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],20:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run()}}queueIndex=-1;len=queue.length}currentQueue=null;draining=false;runClearTimeout(timeout)}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i]}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){runTimeout(drainQueue)}};function Item(fun,array){this.fun=fun;this.array=array}Item.prototype.run=function(){this.fun.apply(null,this.array)};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.prependListener=noop;process.prependOnceListener=noop;process.listeners=function(name){return[]};process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}],21:[function(require,module,exports){"use strict";const{SymbolDispose}=require("../../ours/primordials");const{AbortError,codes}=require("../../ours/errors");const{isNodeStream,isWebStream,kControllerErrorFunction}=require("./utils");const eos=require("./end-of-stream");const{ERR_INVALID_ARG_TYPE}=codes;let addAbortListener;const validateAbortSignal=(signal,name)=>{if(typeof signal!=="object"||!("aborted"in signal)){throw new ERR_INVALID_ARG_TYPE(name,"AbortSignal",signal)}};module.exports.addAbortSignal=function addAbortSignal(signal,stream){validateAbortSignal(signal,"signal");if(!isNodeStream(stream)&&!isWebStream(stream)){throw new ERR_INVALID_ARG_TYPE("stream",["ReadableStream","WritableStream","Stream"],stream)}return module.exports.addAbortSignalNoValidate(signal,stream)};module.exports.addAbortSignalNoValidate=function(signal,stream){if(typeof signal!=="object"||!("aborted"in signal)){return stream}const onAbort=isNodeStream(stream)?()=>{stream.destroy(new AbortError(undefined,{cause:signal.reason}))}:()=>{stream[kControllerErrorFunction](new AbortError(undefined,{cause:signal.reason}))};if(signal.aborted){onAbort()}else{addAbortListener=addAbortListener||require("../../ours/util").addAbortListener;const disposable=addAbortListener(signal,onAbort);eos(stream,disposable[SymbolDispose])}return stream}},{"../../ours/errors":40,"../../ours/primordials":41,"../../ours/util":42,"./end-of-stream":27,"./utils":36}],22:[function(require,module,exports){"use strict";const{StringPrototypeSlice,SymbolIterator,TypedArrayPrototypeSet,Uint8Array}=require("../../ours/primordials");const{Buffer}=require("buffer");const{inspect}=require("../../ours/util");module.exports=class BufferList{constructor(){this.head=null;this.tail=null;this.length=0}push(v){const entry={data:v,next:null};if(this.length>0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length}unshift(v){const entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length}shift(){if(this.length===0)return;const ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret}clear(){this.head=this.tail=null;this.length=0}join(s){if(this.length===0)return"";let p=this.head;let ret=""+p.data;while((p=p.next)!==null)ret+=s+p.data;return ret}concat(n){if(this.length===0)return Buffer.alloc(0);const ret=Buffer.allocUnsafe(n>>>0);let p=this.head;let i=0;while(p){TypedArrayPrototypeSet(ret,p.data,i);i+=p.data.length;p=p.next}return ret}consume(n,hasStrings){const data=this.head.data;if(n<data.length){const slice=data.slice(0,n);this.head.data=data.slice(n);return slice}if(n===data.length){return this.shift()}return hasStrings?this._getString(n):this._getBuffer(n)}first(){return this.head.data}*[SymbolIterator](){for(let p=this.head;p;p=p.next){yield p.data}}_getString(n){let ret="";let p=this.head;let c=0;do{const str=p.data;if(n>str.length){ret+=str;n-=str.length}else{if(n===str.length){ret+=str;++c;if(p.next)this.head=p.next;else this.head=this.tail=null}else{ret+=StringPrototypeSlice(str,0,n);this.head=p;p.data=StringPrototypeSlice(str,n)}break}++c}while((p=p.next)!==null);this.length-=c;return ret}_getBuffer(n){const ret=Buffer.allocUnsafe(n);const retLen=n;let p=this.head;let c=0;do{const buf=p.data;if(n>buf.length){TypedArrayPrototypeSet(ret,buf,retLen-n);n-=buf.length}else{if(n===buf.length){TypedArrayPrototypeSet(ret,buf,retLen-n);++c;if(p.next)this.head=p.next;else this.head=this.tail=null}else{TypedArrayPrototypeSet(ret,new Uint8Array(buf.buffer,buf.byteOffset,n),retLen-n);this.head=p;p.data=buf.slice(n)}break}++c}while((p=p.next)!==null);this.length-=c;return ret}[Symbol.for("nodejs.util.inspect.custom")](_,options){return inspect(this,{...options,depth:0,customInspect:false})}}},{"../../ours/primordials":41,"../../ours/util":42,buffer:17}],23:[function(require,module,exports){"use strict";const{pipeline}=require("./pipeline");const Duplex=require("./duplex");const{destroyer}=require("./destroy");const{isNodeStream,isReadable,isWritable,isWebStream,isTransformStream,isWritableStream,isReadableStream}=require("./utils");const{AbortError,codes:{ERR_INVALID_ARG_VALUE,ERR_MISSING_ARGS}}=require("../../ours/errors");const eos=require("./end-of-stream");module.exports=function compose(...streams){if(streams.length===0){throw new ERR_MISSING_ARGS("streams")}if(streams.length===1){return Duplex.from(streams[0])}const orgStreams=[...streams];if(typeof streams[0]==="function"){streams[0]=Duplex.from(streams[0])}if(typeof streams[streams.length-1]==="function"){const idx=streams.length-1;streams[idx]=Duplex.from(streams[idx])}for(let n=0;n<streams.length;++n){if(!isNodeStream(streams[n])&&!isWebStream(streams[n])){continue}if(n<streams.length-1&&!(isReadable(streams[n])||isReadableStream(streams[n])||isTransformStream(streams[n]))){throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`,orgStreams[n],"must be readable")}if(n>0&&!(isWritable(streams[n])||isWritableStream(streams[n])||isTransformStream(streams[n]))){throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`,orgStreams[n],"must be writable")}}let ondrain;let onfinish;let onreadable;let onclose;let d;function onfinished(err){const cb=onclose;onclose=null;if(cb){cb(err)}else if(err){d.destroy(err)}else if(!readable&&!writable){d.destroy()}}const head=streams[0];const tail=pipeline(streams,onfinished);const writable=!!(isWritable(head)||isWritableStream(head)||isTransformStream(head));const readable=!!(isReadable(tail)||isReadableStream(tail)||isTransformStream(tail));d=new Duplex({writableObjectMode:!!(head!==null&&head!==undefined&&head.writableObjectMode),readableObjectMode:!!(tail!==null&&tail!==undefined&&tail.readableObjectMode),writable:writable,readable:readable});if(writable){if(isNodeStream(head)){d._write=function(chunk,encoding,callback){if(head.write(chunk,encoding)){callback()}else{ondrain=callback}};d._final=function(callback){head.end();onfinish=callback};head.on("drain",function(){if(ondrain){const cb=ondrain;ondrain=null;cb()}})}else if(isWebStream(head)){const writable=isTransformStream(head)?head.writable:head;const writer=writable.getWriter();d._write=async function(chunk,encoding,callback){try{await writer.ready;writer.write(chunk).catch(()=>{});callback()}catch(err){callback(err)}};d._final=async function(callback){try{await writer.ready;writer.close().catch(()=>{});onfinish=callback}catch(err){callback(err)}}}const toRead=isTransformStream(tail)?tail.readable:tail;eos(toRead,()=>{if(onfinish){const cb=onfinish;onfinish=null;cb()}})}if(readable){if(isNodeStream(tail)){tail.on("readable",function(){if(onreadable){const cb=onreadable;onreadable=null;cb()}});tail.on("end",function(){d.push(null)});d._read=function(){while(true){const buf=tail.read();if(buf===null){onreadable=d._read;return}if(!d.push(buf)){return}}}}else if(isWebStream(tail)){const readable=isTransformStream(tail)?tail.readable:tail;const reader=readable.getReader();d._read=async function(){while(true){try{const{value,done}=await reader.read();if(!d.push(value)){return}if(done){d.push(null);return}}catch{return}}}}}d._destroy=function(err,callback){if(!err&&onclose!==null){err=new AbortError}onreadable=null;ondrain=null;onfinish=null;if(onclose===null){callback(err)}else{onclose=callback;if(isNodeStream(tail)){destroyer(tail,err)}}};return d}},{"../../ours/errors":40,"./destroy":24,"./duplex":25,"./end-of-stream":27,"./pipeline":32,"./utils":36}],24:[function(require,module,exports){"use strict";const process=require("process/");const{aggregateTwoErrors,codes:{ERR_MULTIPLE_CALLBACK},AbortError}=require("../../ours/errors");const{Symbol}=require("../../ours/primordials");const{kIsDestroyed,isDestroyed,isFinished,isServerRequest}=require("./utils");const kDestroy=Symbol("kDestroy");const kConstruct=Symbol("kConstruct");function checkError(err,w,r){if(err){err.stack;if(w&&!w.errored){w.errored=err}if(r&&!r.errored){r.errored=err}}}function destroy(err,cb){const r=this._readableState;const w=this._writableState;const s=w||r;if(w!==null&&w!==undefined&&w.destroyed||r!==null&&r!==undefined&&r.destroyed){if(typeof cb==="function"){cb()}return this}checkError(err,w,r);if(w){w.destroyed=true}if(r){r.destroyed=true}if(!s.constructed){this.once(kDestroy,function(er){_destroy(this,aggregateTwoErrors(er,err),cb)})}else{_destroy(this,err,cb)}return this}function _destroy(self,err,cb){let called=false;function onDestroy(err){if(called){return}called=true;const r=self._readableState;const w=self._writableState;checkError(err,w,r);if(w){w.closed=true}if(r){r.closed=true}if(typeof cb==="function"){cb(err)}if(err){process.nextTick(emitErrorCloseNT,self,err)}else{process.nextTick(emitCloseNT,self)}}try{self._destroy(err||null,onDestroy)}catch(err){onDestroy(err)}}function emitErrorCloseNT(self,err){emitErrorNT(self,err);emitCloseNT(self)}function emitCloseNT(self){const r=self._readableState;const w=self._writableState;if(w){w.closeEmitted=true}if(r){r.closeEmitted=true}if(w!==null&&w!==undefined&&w.emitClose||r!==null&&r!==undefined&&r.emitClose){self.emit("close")}}function emitErrorNT(self,err){const r=self._readableState;const w=self._writableState;if(w!==null&&w!==undefined&&w.errorEmitted||r!==null&&r!==undefined&&r.errorEmitted){return}if(w){w.errorEmitted=true}if(r){r.errorEmitted=true}self.emit("error",err)}function undestroy(){const r=this._readableState;const w=this._writableState;if(r){r.constructed=true;r.closed=false;r.closeEmitted=false;r.destroyed=false;r.errored=null;r.errorEmitted=false;r.reading=false;r.ended=r.readable===false;r.endEmitted=r.readable===false}if(w){w.constructed=true;w.destroyed=false;w.closed=false;w.closeEmitted=false;w.errored=null;w.errorEmitted=false;w.finalCalled=false;w.prefinished=false;w.ended=w.writable===false;w.ending=w.writable===false;w.finished=w.writable===false}}function errorOrDestroy(stream,err,sync){const r=stream._readableState;const w=stream._writableState;if(w!==null&&w!==undefined&&w.destroyed||r!==null&&r!==undefined&&r.destroyed){return this}if(r!==null&&r!==undefined&&r.autoDestroy||w!==null&&w!==undefined&&w.autoDestroy)stream.destroy(err);else if(err){err.stack;if(w&&!w.errored){w.errored=err}if(r&&!r.errored){r.errored=err}if(sync){process.nextTick(emitErrorNT,stream,err)}else{emitErrorNT(stream,err)}}}function construct(stream,cb){if(typeof stream._construct!=="function"){return}const r=stream._readableState;const w=stream._writableState;if(r){r.constructed=false}if(w){w.constructed=false}stream.once(kConstruct,cb);if(stream.listenerCount(kConstruct)>1){return}process.nextTick(constructNT,stream)}function constructNT(stream){let called=false;function onConstruct(err){if(called){errorOrDestroy(stream,err!==null&&err!==undefined?err:new ERR_MULTIPLE_CALLBACK);return}called=true;const r=stream._readableState;const w=stream._writableState;const s=w||r;if(r){r.constructed=true}if(w){w.constructed=true}if(s.destroyed){stream.emit(kDestroy,err)}else if(err){errorOrDestroy(stream,err,true)}else{process.nextTick(emitConstructNT,stream)}}try{stream._construct(err=>{process.nextTick(onConstruct,err)})}catch(err){process.nextTick(onConstruct,err)}}function emitConstructNT(stream){stream.emit(kConstruct)}function isRequest(stream){return(stream===null||stream===undefined?undefined:stream.setHeader)&&typeof stream.abort==="function"}function emitCloseLegacy(stream){stream.emit("close")}function emitErrorCloseLegacy(stream,err){stream.emit("error",err);process.nextTick(emitCloseLegacy,stream)}function destroyer(stream,err){if(!stream||isDestroyed(stream)){return}if(!err&&!isFinished(stream)){err=new AbortError}if(isServerRequest(stream)){stream.socket=null;stream.destroy(err)}else if(isRequest(stream)){stream.abort()}else if(isRequest(stream.req)){stream.req.abort()}else if(typeof stream.destroy==="function"){stream.destroy(err)}else if(typeof stream.close==="function"){stream.close()}else if(err){process.nextTick(emitErrorCloseLegacy,stream,err)}else{process.nextTick(emitCloseLegacy,stream)}if(!stream.destroyed){stream[kIsDestroyed]=true}}module.exports={construct:construct,destroyer:destroyer,destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}},{"../../ours/errors":40,"../../ours/primordials":41,"./utils":36,"process/":20}],25:[function(require,module,exports){"use strict";const{ObjectDefineProperties,ObjectGetOwnPropertyDescriptor,ObjectKeys,ObjectSetPrototypeOf}=require("../../ours/primordials");module.exports=Duplex;const Readable=require("./readable");const Writable=require("./writable");ObjectSetPrototypeOf(Duplex.prototype,Readable.prototype);ObjectSetPrototypeOf(Duplex,Readable);{const keys=ObjectKeys(Writable.prototype);for(let i=0;i<keys.length;i++){const method=keys[i];if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method]}}function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options);Writable.call(this,options);if(options){this.allowHalfOpen=options.allowHalfOpen!==false;if(options.readable===false){this._readableState.readable=false;this._readableState.ended=true;this._readableState.endEmitted=true}if(options.writable===false){this._writableState.writable=false;this._writableState.ending=true;this._writableState.ended=true;this._writableState.finished=true}}else{this.allowHalfOpen=true}}ObjectDefineProperties(Duplex.prototype,{writable:{__proto__:null,...ObjectGetOwnPropertyDescriptor(Writable.prototype,"writable")},writableHighWaterMark:{__proto__:null,...ObjectGetOwnPropertyDescriptor(Writable.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...ObjectGetOwnPropertyDescriptor(Writable.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...ObjectGetOwnPropertyDescriptor(Writable.prototype,"writableBuffer")},writableLength:{__proto__:null,...ObjectGetOwnPropertyDescriptor(Writable.prototype,"writableLength")},writableFinished:{__proto__:null,...ObjectGetOwnPropertyDescriptor(Writable.prototype,"writableFinished")},writableCorked:{__proto__:null,...ObjectGetOwnPropertyDescriptor(Writable.prototype,"writableCorked")},writableEnded:{__proto__:null,...ObjectGetOwnPropertyDescriptor(Writable.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...ObjectGetOwnPropertyDescriptor(Writable.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){if(this._readableState===undefined||this._writableState===undefined){return false}return this._readableState.destroyed&&this._writableState.destroyed},set(value){if(this._readableState&&this._writableState){this._readableState.destroyed=value;this._writableState.destroyed=value}}}});let webStreamsAdapters;function lazyWebStreams(){if(webStreamsAdapters===undefined)webStreamsAdapters={};return webStreamsAdapters}Duplex.fromWeb=function(pair,options){return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair,options)};Duplex.toWeb=function(duplex){return lazyWebStreams().newReadableWritablePairFromDuplex(duplex)};let duplexify;Duplex.from=function(body){if(!duplexify){duplexify=require("./duplexify")}return duplexify(body,"body")}},{"../../ours/primordials":41,"./duplexify":26,"./readable":33,"./writable":37}],26:[function(require,module,exports){const process=require("process/");"use strict";const bufferModule=require("buffer");const{isReadable,isWritable,isIterable,isNodeStream,isReadableNodeStream,isWritableNodeStream,isDuplexNodeStream,isReadableStream,isWritableStream}=require("./utils");const eos=require("./end-of-stream");const{AbortError,codes:{ERR_INVALID_ARG_TYPE,ERR_INVALID_RETURN_VALUE}}=require("../../ours/errors");const{destroyer}=require("./destroy");const Duplex=require("./duplex");const Readable=require("./readable");const Writable=require("./writable");const{createDeferredPromise}=require("../../ours/util");const from=require("./from");const Blob=globalThis.Blob||bufferModule.Blob;const isBlob=typeof Blob!=="undefined"?function isBlob(b){return b instanceof Blob}:function isBlob(b){return false};const AbortController=globalThis.AbortController||require("abort-controller").AbortController;const{FunctionPrototypeCall}=require("../../ours/primordials");class Duplexify extends Duplex{constructor(options){super(options);if((options===null||options===undefined?undefined:options.readable)===false){this._readableState.readable=false;this._readableState.ended=true;this._readableState.endEmitted=true}if((options===null||options===undefined?undefined:options.writable)===false){this._writableState.writable=false;this._writableState.ending=true;this._writableState.ended=true;this._writableState.finished=true}}}module.exports=function duplexify(body,name){if(isDuplexNodeStream(body)){return body}if(isReadableNodeStream(body)){return _duplexify({readable:body})}if(isWritableNodeStream(body)){return _duplexify({writable:body})}if(isNodeStream(body)){return _duplexify({writable:false,readable:false})}if(isReadableStream(body)){return _duplexify({readable:Readable.fromWeb(body)})}if(isWritableStream(body)){return _duplexify({writable:Writable.fromWeb(body)})}if(typeof body==="function"){const{value,write,final,destroy}=fromAsyncGen(body);if(isIterable(value)){return from(Duplexify,value,{objectMode:true,write:write,final:final,destroy:destroy})}const then=value===null||value===undefined?undefined:value.then;if(typeof then==="function"){let d;const promise=FunctionPrototypeCall(then,value,val=>{if(val!=null){throw new ERR_INVALID_RETURN_VALUE("nully","body",val)}},err=>{destroyer(d,err)});return d=new Duplexify({objectMode:true,readable:false,write:write,final(cb){final(async()=>{try{await promise;process.nextTick(cb,null)}catch(err){process.nextTick(cb,err)}})},destroy:destroy})}throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or AsyncFunction",name,value)}if(isBlob(body)){return duplexify(body.arrayBuffer())}if(isIterable(body)){return from(Duplexify,body,{objectMode:true,writable:false})}if(isReadableStream(body===null||body===undefined?undefined:body.readable)&&isWritableStream(body===null||body===undefined?undefined:body.writable)){return Duplexify.fromWeb(body)}if(typeof(body===null||body===undefined?undefined:body.writable)==="object"||typeof(body===null||body===undefined?undefined:body.readable)==="object"){const readable=body!==null&&body!==undefined&&body.readable?isReadableNodeStream(body===null||body===undefined?undefined:body.readable)?body===null||body===undefined?undefined:body.readable:duplexify(body.readable):undefined;const writable=body!==null&&body!==undefined&&body.writable?isWritableNodeStream(body===null||body===undefined?undefined:body.writable)?body===null||body===undefined?undefined:body.writable:duplexify(body.writable):undefined;return _duplexify({readable:readable,writable:writable})}const then=body===null||body===undefined?undefined:body.then;if(typeof then==="function"){let d;FunctionPrototypeCall(then,body,val=>{if(val!=null){d.push(val)}d.push(null)},err=>{destroyer(d,err)});return d=new Duplexify({objectMode:true,writable:false,read(){}})}throw new ERR_INVALID_ARG_TYPE(name,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],body)};function fromAsyncGen(fn){let{promise,resolve}=createDeferredPromise();const ac=new AbortController;const signal=ac.signal;const value=fn(async function*(){while(true){const _promise=promise;promise=null;const{chunk,done,cb}=await _promise;process.nextTick(cb);if(done)return;if(signal.aborted)throw new AbortError(undefined,{cause:signal.reason});({promise,resolve}=createDeferredPromise());yield chunk}}(),{signal:signal});return{value:value,write(chunk,encoding,cb){const _resolve=resolve;resolve=null;_resolve({chunk:chunk,done:false,cb:cb})},final(cb){const _resolve=resolve;resolve=null;_resolve({done:true,cb:cb})},destroy(err,cb){ac.abort();cb(err)}}}function _duplexify(pair){const r=pair.readable&&typeof pair.readable.read!=="function"?Readable.wrap(pair.readable):pair.readable;const w=pair.writable;let readable=!!isReadable(r);let writable=!!isWritable(w);let ondrain;let onfinish;let onreadable;let onclose;let d;function onfinished(err){const cb=onclose;onclose=null;if(cb){cb(err)}else if(err){d.destroy(err)}}d=new Duplexify({readableObjectMode:!!(r!==null&&r!==undefined&&r.readableObjectMode),writableObjectMode:!!(w!==null&&w!==undefined&&w.writableObjectMode),readable:readable,writable:writable});if(writable){eos(w,err=>{writable=false;if(err){destroyer(r,err)}onfinished(err)});d._write=function(chunk,encoding,callback){if(w.write(chunk,encoding)){callback()}else{ondrain=callback}};d._final=function(callback){w.end();onfinish=callback};w.on("drain",function(){if(ondrain){const cb=ondrain;ondrain=null;cb()}});w.on("finish",function(){if(onfinish){const cb=onfinish;onfinish=null;cb()}})}if(readable){eos(r,err=>{readable=false;if(err){destroyer(r,err)}onfinished(err)});r.on("readable",function(){if(onreadable){const cb=onreadable;onreadable=null;cb()}});r.on("end",function(){d.push(null)});d._read=function(){while(true){const buf=r.read();if(buf===null){onreadable=d._read;return}if(!d.push(buf)){return}}}}d._destroy=function(err,callback){if(!err&&onclose!==null){err=new AbortError}onreadable=null;ondrain=null;onfinish=null;if(onclose===null){callback(err)}else{onclose=callback;destroyer(w,err);destroyer(r,err)}};return d}},{"../../ours/errors":40,"../../ours/primordials":41,"../../ours/util":42,"./destroy":24,"./duplex":25,"./end-of-stream":27,"./from":28,"./readable":33,"./utils":36,"./writable":37,"abort-controller":15,buffer:17,"process/":20}],27:[function(require,module,exports){"use strict";const process=require("process/");const{AbortError,codes}=require("../../ours/errors");const{ERR_INVALID_ARG_TYPE,ERR_STREAM_PREMATURE_CLOSE}=codes;const{kEmptyObject,once}=require("../../ours/util");const{validateAbortSignal,validateFunction,validateObject,validateBoolean}=require("../validators");const{Promise,PromisePrototypeThen,SymbolDispose}=require("../../ours/primordials");const{isClosed,isReadable,isReadableNodeStream,isReadableStream,isReadableFinished,isReadableErrored,isWritable,isWritableNodeStream,isWritableStream,isWritableFinished,isWritableErrored,isNodeStream,willEmitClose:_willEmitClose,kIsClosedPromise}=require("./utils");let addAbortListener;function isRequest(stream){return stream.setHeader&&typeof stream.abort==="function"}const nop=()=>{};function eos(stream,options,callback){var _options$readable,_options$writable;if(arguments.length===2){callback=options;options=kEmptyObject}else if(options==null){options=kEmptyObject}else{validateObject(options,"options")}validateFunction(callback,"callback");validateAbortSignal(options.signal,"options.signal");callback=once(callback);if(isReadableStream(stream)||isWritableStream(stream)){return eosWeb(stream,options,callback)}if(!isNodeStream(stream)){throw new ERR_INVALID_ARG_TYPE("stream",["ReadableStream","WritableStream","Stream"],stream)}const readable=(_options$readable=options.readable)!==null&&_options$readable!==undefined?_options$readable:isReadableNodeStream(stream);const writable=(_options$writable=options.writable)!==null&&_options$writable!==undefined?_options$writable:isWritableNodeStream(stream);const wState=stream._writableState;const rState=stream._readableState;const onlegacyfinish=()=>{if(!stream.writable){onfinish()}};let willEmitClose=_willEmitClose(stream)&&isReadableNodeStream(stream)===readable&&isWritableNodeStream(stream)===writable;let writableFinished=isWritableFinished(stream,false);const onfinish=()=>{writableFinished=true;if(stream.destroyed){willEmitClose=false}if(willEmitClose&&(!stream.readable||readable)){return}if(!readable||readableFinished){callback.call(stream)}};let readableFinished=isReadableFinished(stream,false);const onend=()=>{readableFinished=true;if(stream.destroyed){willEmitClose=false}if(willEmitClose&&(!stream.writable||writable)){return}if(!writable||writableFinished){callback.call(stream)}};const onerror=err=>{callback.call(stream,err)};let closed=isClosed(stream);const onclose=()=>{closed=true;const errored=isWritableErrored(stream)||isReadableErrored(stream);if(errored&&typeof errored!=="boolean"){return callback.call(stream,errored)}if(readable&&!readableFinished&&isReadableNodeStream(stream,true)){if(!isReadableFinished(stream,false))return callback.call(stream,new ERR_STREAM_PREMATURE_CLOSE)}if(writable&&!writableFinished){if(!isWritableFinished(stream,false))return callback.call(stream,new ERR_STREAM_PREMATURE_CLOSE)}callback.call(stream)};const onclosed=()=>{closed=true;const errored=isWritableErrored(stream)||isReadableErrored(stream);if(errored&&typeof errored!=="boolean"){return callback.call(stream,errored)}callback.call(stream)};const onrequest=()=>{stream.req.on("finish",onfinish)};if(isRequest(stream)){stream.on("complete",onfinish);if(!willEmitClose){stream.on("abort",onclose)}if(stream.req){onrequest()}else{stream.on("request",onrequest)}}else if(writable&&!wState){stream.on("end",onlegacyfinish);stream.on("close",onlegacyfinish)}if(!willEmitClose&&typeof stream.aborted==="boolean"){stream.on("aborted",onclose)}stream.on("end",onend);stream.on("finish",onfinish);if(options.error!==false){stream.on("error",onerror)}stream.on("close",onclose);if(closed){process.nextTick(onclose)}else if(wState!==null&&wState!==undefined&&wState.errorEmitted||rState!==null&&rState!==undefined&&rState.errorEmitted){if(!willEmitClose){process.nextTick(onclosed)}}else if(!readable&&(!willEmitClose||isReadable(stream))&&(writableFinished||isWritable(stream)===false)){process.nextTick(onclosed)}else if(!writable&&(!willEmitClose||isWritable(stream))&&(readableFinished||isReadable(stream)===false)){process.nextTick(onclosed)}else if(rState&&stream.req&&stream.aborted){process.nextTick(onclosed)}const cleanup=()=>{callback=nop;stream.removeListener("aborted",onclose);stream.removeListener("complete",onfinish);stream.removeListener("abort",onclose);stream.removeListener("request",onrequest);if(stream.req)stream.req.removeListener("finish",onfinish);stream.removeListener("end",onlegacyfinish);stream.removeListener("close",onlegacyfinish);stream.removeListener("finish",onfinish);stream.removeListener("end",onend);stream.removeListener("error",onerror);stream.removeListener("close",onclose)};if(options.signal&&!closed){const abort=()=>{const endCallback=callback;cleanup();endCallback.call(stream,new AbortError(undefined,{cause:options.signal.reason}))};if(options.signal.aborted){process.nextTick(abort)}else{addAbortListener=addAbortListener||require("../../ours/util").addAbortListener;const disposable=addAbortListener(options.signal,abort);const originalCallback=callback;callback=once((...args)=>{disposable[SymbolDispose]();originalCallback.apply(stream,args)})}}return cleanup}function eosWeb(stream,options,callback){let isAborted=false;let abort=nop;if(options.signal){abort=()=>{isAborted=true;callback.call(stream,new AbortError(undefined,{cause:options.signal.reason}))};if(options.signal.aborted){process.nextTick(abort)}else{addAbortListener=addAbortListener||require("../../ours/util").addAbortListener;const disposable=addAbortListener(options.signal,abort);const originalCallback=callback;callback=once((...args)=>{disposable[SymbolDispose]();originalCallback.apply(stream,args)})}}const resolverFn=(...args)=>{if(!isAborted){process.nextTick(()=>callback.apply(stream,args))}};PromisePrototypeThen(stream[kIsClosedPromise].promise,resolverFn,resolverFn);return nop}function finished(stream,opts){var _opts;let autoCleanup=false;if(opts===null){opts=kEmptyObject}if((_opts=opts)!==null&&_opts!==undefined&&_opts.cleanup){validateBoolean(opts.cleanup,"cleanup");autoCleanup=opts.cleanup}return new Promise((resolve,reject)=>{const cleanup=eos(stream,opts,err=>{if(autoCleanup){cleanup()}if(err){reject(err)}else{resolve()}})})}module.exports=eos;module.exports.finished=finished},{"../../ours/errors":40,"../../ours/primordials":41,"../../ours/util":42,"../validators":38,"./utils":36,"process/":20}],28:[function(require,module,exports){"use strict";const process=require("process/");const{PromisePrototypeThen,SymbolAsyncIterator,SymbolIterator}=require("../../ours/primordials");const{Buffer}=require("buffer");const{ERR_INVALID_ARG_TYPE,ERR_STREAM_NULL_VALUES}=require("../../ours/errors").codes;function from(Readable,iterable,opts){let iterator;if(typeof iterable==="string"||iterable instanceof Buffer){return new Readable({objectMode:true,...opts,read(){this.push(iterable);this.push(null)}})}let isAsync;if(iterable&&iterable[SymbolAsyncIterator]){isAsync=true;iterator=iterable[SymbolAsyncIterator]()}else if(iterable&&iterable[SymbolIterator]){isAsync=false;iterator=iterable[SymbolIterator]()}else{throw new ERR_INVALID_ARG_TYPE("iterable",["Iterable"],iterable)}const readable=new Readable({objectMode:true,highWaterMark:1,...opts});let reading=false;readable._read=function(){if(!reading){reading=true;next()}};readable._destroy=function(error,cb){PromisePrototypeThen(close(error),()=>process.nextTick(cb,error),e=>process.nextTick(cb,e||error))};async function close(error){const hadError=error!==undefined&&error!==null;const hasThrow=typeof iterator.throw==="function";if(hadError&&hasThrow){const{value,done}=await iterator.throw(error);await value;if(done){return}}if(typeof iterator.return==="function"){const{value}=await iterator.return();await value}}async function next(){for(;;){try{const{value,done}=isAsync?await iterator.next():iterator.next();if(done){readable.push(null)}else{const res=value&&typeof value.then==="function"?await value:value;if(res===null){reading=false;throw new ERR_STREAM_NULL_VALUES}else if(readable.push(res)){continue}else{reading=false}}}catch(err){readable.destroy(err)}break}}return readable}module.exports=from},{"../../ours/errors":40,"../../ours/primordials":41,buffer:17,"process/":20}],29:[function(require,module,exports){"use strict";const{ArrayIsArray,ObjectSetPrototypeOf}=require("../../ours/primordials");const{EventEmitter:EE}=require("events");function Stream(opts){EE.call(this,opts)}ObjectSetPrototypeOf(Stream.prototype,EE.prototype);ObjectSetPrototypeOf(Stream,EE);Stream.prototype.pipe=function(dest,options){const source=this;function ondata(chunk){if(dest.writable&&dest.write(chunk)===false&&source.pause){source.pause()}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}let didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){this.emit("error",er)}}prependListener(source,"error",onerror);prependListener(dest,"error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest};function prependListener(emitter,event,fn){if(typeof emitter.prependListener==="function")return emitter.prependListener(event,fn);if(!emitter._events||!emitter._events[event])emitter.on(event,fn);else if(ArrayIsArray(emitter._events[event]))emitter._events[event].unshift(fn);else emitter._events[event]=[fn,emitter._events[event]]}module.exports={Stream:Stream,prependListener:prependListener}},{"../../ours/primordials":41,events:18}],30:[function(require,module,exports){"use strict";const AbortController=globalThis.AbortController||require("abort-controller").AbortController;const{codes:{ERR_INVALID_ARG_VALUE,ERR_INVALID_ARG_TYPE,ERR_MISSING_ARGS,ERR_OUT_OF_RANGE},AbortError}=require("../../ours/errors");const{validateAbortSignal,validateInteger,validateObject}=require("../validators");const kWeakHandler=require("../../ours/primordials").Symbol("kWeak");const kResistStopPropagation=require("../../ours/primordials").Symbol("kResistStopPropagation");const{finished}=require("./end-of-stream");const staticCompose=require("./compose");const{addAbortSignalNoValidate}=require("./add-abort-signal");const{isWritable,isNodeStream}=require("./utils");const{deprecate}=require("../../ours/util");const{ArrayPrototypePush,Boolean,MathFloor,Number,NumberIsNaN,Promise,PromiseReject,PromiseResolve,PromisePrototypeThen,Symbol}=require("../../ours/primordials");const kEmpty=Symbol("kEmpty");const kEof=Symbol("kEof");function compose(stream,options){if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}if(isNodeStream(stream)&&!isWritable(stream)){throw new ERR_INVALID_ARG_VALUE("stream",stream,"must be writable")}const composedStream=staticCompose(this,stream);if(options!==null&&options!==undefined&&options.signal){addAbortSignalNoValidate(options.signal,composedStream)}return composedStream}function map(fn,options){if(typeof fn!=="function"){throw new ERR_INVALID_ARG_TYPE("fn",["Function","AsyncFunction"],fn)}if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}let concurrency=1;if((options===null||options===undefined?undefined:options.concurrency)!=null){concurrency=MathFloor(options.concurrency)}let highWaterMark=concurrency-1;if((options===null||options===undefined?undefined:options.highWaterMark)!=null){highWaterMark=MathFloor(options.highWaterMark)}validateInteger(concurrency,"options.concurrency",1);validateInteger(highWaterMark,"options.highWaterMark",0);highWaterMark+=concurrency;return async function*map(){const signal=require("../../ours/util").AbortSignalAny([options===null||options===undefined?undefined:options.signal].filter(Boolean));const stream=this;const queue=[];const signalOpt={signal:signal};let next;let resume;let done=false;let cnt=0;function onCatch(){done=true;afterItemProcessed()}function afterItemProcessed(){cnt-=1;maybeResume()}function maybeResume(){if(resume&&!done&&cnt<concurrency&&queue.length<highWaterMark){resume();resume=null}}async function pump(){try{for await(let val of stream){if(done){return}if(signal.aborted){throw new AbortError}try{val=fn(val,signalOpt);if(val===kEmpty){continue}val=PromiseResolve(val)}catch(err){val=PromiseReject(err)}cnt+=1;PromisePrototypeThen(val,afterItemProcessed,onCatch);queue.push(val);if(next){next();next=null}if(!done&&(queue.length>=highWaterMark||cnt>=concurrency)){await new Promise(resolve=>{resume=resolve})}}queue.push(kEof)}catch(err){const val=PromiseReject(err);PromisePrototypeThen(val,afterItemProcessed,onCatch);queue.push(val)}finally{done=true;if(next){next();next=null}}}pump();try{while(true){while(queue.length>0){const val=await queue[0];if(val===kEof){return}if(signal.aborted){throw new AbortError}if(val!==kEmpty){yield val}queue.shift();maybeResume()}await new Promise(resolve=>{next=resolve})}}finally{done=true;if(resume){resume();resume=null}}}.call(this)}function asIndexedPairs(options=undefined){if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}return async function*asIndexedPairs(){let index=0;for await(const val of this){var _options$signal;if(options!==null&&options!==undefined&&(_options$signal=options.signal)!==null&&_options$signal!==undefined&&_options$signal.aborted){throw new AbortError({cause:options.signal.reason})}yield[index++,val]}}.call(this)}async function some(fn,options=undefined){for await(const unused of filter.call(this,fn,options)){return true}return false}async function every(fn,options=undefined){if(typeof fn!=="function"){throw new ERR_INVALID_ARG_TYPE("fn",["Function","AsyncFunction"],fn)}return!await some.call(this,async(...args)=>{return!await fn(...args)},options)}async function find(fn,options){for await(const result of filter.call(this,fn,options)){return result}return undefined}async function forEach(fn,options){if(typeof fn!=="function"){throw new ERR_INVALID_ARG_TYPE("fn",["Function","AsyncFunction"],fn)}async function forEachFn(value,options){await fn(value,options);return kEmpty}for await(const unused of map.call(this,forEachFn,options));}function filter(fn,options){if(typeof fn!=="function"){throw new ERR_INVALID_ARG_TYPE("fn",["Function","AsyncFunction"],fn)}async function filterFn(value,options){if(await fn(value,options)){return value}return kEmpty}return map.call(this,filterFn,options)}class ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}}async function reduce(reducer,initialValue,options){var _options$signal2;if(typeof reducer!=="function"){throw new ERR_INVALID_ARG_TYPE("reducer",["Function","AsyncFunction"],reducer)}if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}let hasInitialValue=arguments.length>1;if(options!==null&&options!==undefined&&(_options$signal2=options.signal)!==null&&_options$signal2!==undefined&&_options$signal2.aborted){const err=new AbortError(undefined,{cause:options.signal.reason});this.once("error",()=>{});await finished(this.destroy(err));throw err}const ac=new AbortController;const signal=ac.signal;if(options!==null&&options!==undefined&&options.signal){const opts={once:true,[kWeakHandler]:this,[kResistStopPropagation]:true};options.signal.addEventListener("abort",()=>ac.abort(),opts)}let gotAnyItemFromStream=false;try{for await(const value of this){var _options$signal3;gotAnyItemFromStream=true;if(options!==null&&options!==undefined&&(_options$signal3=options.signal)!==null&&_options$signal3!==undefined&&_options$signal3.aborted){throw new AbortError}if(!hasInitialValue){initialValue=value;hasInitialValue=true}else{initialValue=await reducer(initialValue,value,{signal:signal})}}if(!gotAnyItemFromStream&&!hasInitialValue){throw new ReduceAwareErrMissingArgs}}finally{ac.abort()}return initialValue}async function toArray(options){if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}const result=[];for await(const val of this){var _options$signal4;if(options!==null&&options!==undefined&&(_options$signal4=options.signal)!==null&&_options$signal4!==undefined&&_options$signal4.aborted){throw new AbortError(undefined,{cause:options.signal.reason})}ArrayPrototypePush(result,val)}return result}function flatMap(fn,options){const values=map.call(this,fn,options);return async function*flatMap(){for await(const val of values){yield*val}}.call(this)}function toIntegerOrInfinity(number){number=Number(number);if(NumberIsNaN(number)){return 0}if(number<0){throw new ERR_OUT_OF_RANGE("number",">= 0",number)}return number}function drop(number,options=undefined){if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}number=toIntegerOrInfinity(number);return async function*drop(){var _options$signal5;if(options!==null&&options!==undefined&&(_options$signal5=options.signal)!==null&&_options$signal5!==undefined&&_options$signal5.aborted){throw new AbortError}for await(const val of this){var _options$signal6;if(options!==null&&options!==undefined&&(_options$signal6=options.signal)!==null&&_options$signal6!==undefined&&_options$signal6.aborted){throw new AbortError}if(number--<=0){yield val}}}.call(this)}function take(number,options=undefined){if(options!=null){validateObject(options,"options")}if((options===null||options===undefined?undefined:options.signal)!=null){validateAbortSignal(options.signal,"options.signal")}number=toIntegerOrInfinity(number);return async function*take(){var _options$signal7;if(options!==null&&options!==undefined&&(_options$signal7=options.signal)!==null&&_options$signal7!==undefined&&_options$signal7.aborted){throw new AbortError}for await(const val of this){var _options$signal8;if(options!==null&&options!==undefined&&(_options$signal8=options.signal)!==null&&_options$signal8!==undefined&&_options$signal8.aborted){throw new AbortError}if(number-- >0){yield val}if(number<=0){return}}}.call(this)}module.exports.streamReturningOperators={asIndexedPairs:deprecate(asIndexedPairs,"readable.asIndexedPairs will be removed in a future version."),drop:drop,filter:filter,flatMap:flatMap,map:map,take:take,compose:compose};module.exports.promiseReturningOperators={every:every,forEach:forEach,reduce:reduce,toArray:toArray,some:some,find:find}},{"../../ours/errors":40,"../../ours/primordials":41,"../../ours/util":42,"../validators":38,"./add-abort-signal":21,"./compose":23,"./end-of-stream":27,"./utils":36,"abort-controller":15}],31:[function(require,module,exports){"use strict";const{ObjectSetPrototypeOf}=require("../../ours/primordials");module.exports=PassThrough;const Transform=require("./transform");ObjectSetPrototypeOf(PassThrough.prototype,Transform.prototype);ObjectSetPrototypeOf(PassThrough,Transform);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"../../ours/primordials":41,"./transform":35}],32:[function(require,module,exports){const process=require("process/");"use strict";const{ArrayIsArray,Promise,SymbolAsyncIterator,SymbolDispose}=require("../../ours/primordials");const eos=require("./end-of-stream");const{once}=require("../../ours/util");const destroyImpl=require("./destroy");const Duplex=require("./duplex");const{aggregateTwoErrors,codes:{ERR_INVALID_ARG_TYPE,ERR_INVALID_RETURN_VALUE,ERR_MISSING_ARGS,ERR_STREAM_DESTROYED,ERR_STREAM_PREMATURE_CLOSE},AbortError}=require("../../ours/errors");const{validateFunction,validateAbortSignal}=require("../validators");const{isIterable,isReadable,isReadableNodeStream,isNodeStream,isTransformStream,isWebStream,isReadableStream,isReadableFinished}=require("./utils");const AbortController=globalThis.AbortController||require("abort-controller").AbortController;let PassThrough;let Readable;let addAbortListener;function destroyer(stream,reading,writing){let finished=false;stream.on("close",()=>{finished=true});const cleanup=eos(stream,{readable:reading,writable:writing},err=>{finished=!err});return{destroy:err=>{if(finished)return;finished=true;destroyImpl.destroyer(stream,err||new ERR_STREAM_DESTROYED("pipe"))},cleanup:cleanup}}function popCallback(streams){validateFunction(streams[streams.length-1],"streams[stream.length - 1]");return streams.pop()}function makeAsyncIterable(val){if(isIterable(val)){return val}else if(isReadableNodeStream(val)){return fromReadable(val)}throw new ERR_INVALID_ARG_TYPE("val",["Readable","Iterable","AsyncIterable"],val)}async function*fromReadable(val){if(!Readable){Readable=require("./readable")}yield*Readable.prototype[SymbolAsyncIterator].call(val)}async function pumpToNode(iterable,writable,finish,{end}){let error;let onresolve=null;const resume=err=>{if(err){error=err}if(onresolve){const callback=onresolve;onresolve=null;callback()}};const wait=()=>new Promise((resolve,reject)=>{if(error){reject(error)}else{onresolve=()=>{if(error){reject(error)}else{resolve()}}}});writable.on("drain",resume);const cleanup=eos(writable,{readable:false},resume);try{if(writable.writableNeedDrain){await wait()}for await(const chunk of iterable){if(!writable.write(chunk)){await wait()}}if(end){writable.end();await wait()}finish()}catch(err){finish(error!==err?aggregateTwoErrors(error,err):err)}finally{cleanup();writable.off("drain",resume)}}async function pumpToWeb(readable,writable,finish,{end}){if(isTransformStream(writable)){writable=writable.writable}const writer=writable.getWriter();try{for await(const chunk of readable){await writer.ready;writer.write(chunk).catch(()=>{})}await writer.ready;if(end){await writer.close()}finish()}catch(err){try{await writer.abort(err);finish(err)}catch(err){finish(err)}}}function pipeline(...streams){return pipelineImpl(streams,once(popCallback(streams)))}function pipelineImpl(streams,callback,opts){if(streams.length===1&&ArrayIsArray(streams[0])){streams=streams[0]}if(streams.length<2){throw new ERR_MISSING_ARGS("streams")}const ac=new AbortController;const signal=ac.signal;const outerSignal=opts===null||opts===undefined?undefined:opts.signal;const lastStreamCleanup=[];validateAbortSignal(outerSignal,"options.signal");function abort(){finishImpl(new AbortError)}addAbortListener=addAbortListener||require("../../ours/util").addAbortListener;let disposable;if(outerSignal){disposable=addAbortListener(outerSignal,abort)}let error;let value;const destroys=[];let finishCount=0;function finish(err){finishImpl(err,--finishCount===0)}function finishImpl(err,final){var _disposable;if(err&&(!error||error.code==="ERR_STREAM_PREMATURE_CLOSE")){error=err}if(!error&&!final){return}while(destroys.length){destroys.shift()(error)}(_disposable=disposable)===null||_disposable===undefined?undefined:_disposable[SymbolDispose]();ac.abort();if(final){if(!error){lastStreamCleanup.forEach(fn=>fn())}process.nextTick(callback,error,value)}}let ret;for(let i=0;i<streams.length;i++){const stream=streams[i];const reading=i<streams.length-1;const writing=i>0;const end=reading||(opts===null||opts===undefined?undefined:opts.end)!==false;const isLastStream=i===streams.length-1;if(isNodeStream(stream)){if(end){const{destroy,cleanup}=destroyer(stream,reading,writing);destroys.push(destroy);if(isReadable(stream)&&isLastStream){lastStreamCleanup.push(cleanup)}}function onError(err){if(err&&err.name!=="AbortError"&&err.code!=="ERR_STREAM_PREMATURE_CLOSE"){finish(err)}}stream.on("error",onError);if(isReadable(stream)&&isLastStream){lastStreamCleanup.push(()=>{stream.removeListener("error",onError)})}}if(i===0){if(typeof stream==="function"){ret=stream({signal:signal});if(!isIterable(ret)){throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or Stream","source",ret)}}else if(isIterable(stream)||isReadableNodeStream(stream)||isTransformStream(stream)){ret=stream}else{ret=Duplex.from(stream)}}else if(typeof stream==="function"){if(isTransformStream(ret)){var _ret;ret=makeAsyncIterable((_ret=ret)===null||_ret===undefined?undefined:_ret.readable)}else{ret=makeAsyncIterable(ret)}ret=stream(ret,{signal:signal});if(reading){if(!isIterable(ret,true)){throw new ERR_INVALID_RETURN_VALUE("AsyncIterable",`transform[${i-1}]`,ret)}}else{var _ret2;if(!PassThrough){PassThrough=require("./passthrough")}const pt=new PassThrough({objectMode:true});const then=(_ret2=ret)===null||_ret2===undefined?undefined:_ret2.then;if(typeof then==="function"){finishCount++;then.call(ret,val=>{value=val;if(val!=null){pt.write(val)}if(end){pt.end()}process.nextTick(finish)},err=>{pt.destroy(err);process.nextTick(finish,err)})}else if(isIterable(ret,true)){finishCount++;pumpToNode(ret,pt,finish,{end:end})}else if(isReadableStream(ret)||isTransformStream(ret)){const toRead=ret.readable||ret;finishCount++;pumpToNode(toRead,pt,finish,{end:end})}else{throw new ERR_INVALID_RETURN_VALUE("AsyncIterable or Promise","destination",ret)}ret=pt;const{destroy,cleanup}=destroyer(ret,false,true);destroys.push(destroy);if(isLastStream){lastStreamCleanup.push(cleanup)}}}else if(isNodeStream(stream)){if(isReadableNodeStream(ret)){finishCount+=2;const cleanup=pipe(ret,stream,finish,{end:end});if(isReadable(stream)&&isLastStream){lastStreamCleanup.push(cleanup)}}else if(isTransformStream(ret)||isReadableStream(ret)){const toRead=ret.readable||ret;finishCount++;pumpToNode(toRead,stream,finish,{end:end})}else if(isIterable(ret)){finishCount++;pumpToNode(ret,stream,finish,{end:end})}else{throw new ERR_INVALID_ARG_TYPE("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ret)}ret=stream}else if(isWebStream(stream)){if(isReadableNodeStream(ret)){finishCount++;pumpToWeb(makeAsyncIterable(ret),stream,finish,{end:end})}else if(isReadableStream(ret)||isIterable(ret)){finishCount++;pumpToWeb(ret,stream,finish,{end:end})}else if(isTransformStream(ret)){finishCount++;pumpToWeb(ret.readable,stream,finish,{end:end})}else{throw new ERR_INVALID_ARG_TYPE("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],ret)}ret=stream}else{ret=Duplex.from(stream)}}if(signal!==null&&signal!==undefined&&signal.aborted||outerSignal!==null&&outerSignal!==undefined&&outerSignal.aborted){process.nextTick(abort)}return ret}function pipe(src,dst,finish,{end}){let ended=false;dst.on("close",()=>{if(!ended){finish(new ERR_STREAM_PREMATURE_CLOSE)}});src.pipe(dst,{end:false});if(end){function endFn(){ended=true;dst.end()}if(isReadableFinished(src)){process.nextTick(endFn)}else{src.once("end",endFn)}}else{finish()}eos(src,{readable:true,writable:false},err=>{const rState=src._readableState;if(err&&err.code==="ERR_STREAM_PREMATURE_CLOSE"&&rState&&rState.ended&&!rState.errored&&!rState.errorEmitted){src.once("end",finish).once("error",finish)}else{finish(err)}});return eos(dst,{readable:false,writable:true},finish)}module.exports={pipelineImpl:pipelineImpl,pipeline:pipeline}},{"../../ours/errors":40,"../../ours/primordials":41,"../../ours/util":42,"../validators":38,"./destroy":24,"./duplex":25,"./end-of-stream":27,"./passthrough":31,"./readable":33,"./utils":36,"abort-controller":15,"process/":20}],33:[function(require,module,exports){"use strict";const process=require("process/");const{ArrayPrototypeIndexOf,NumberIsInteger,NumberIsNaN,NumberParseInt,ObjectDefineProperties,ObjectKeys,ObjectSetPrototypeOf,Promise,SafeSet,SymbolAsyncDispose,SymbolAsyncIterator,Symbol}=require("../../ours/primordials");module.exports=Readable;Readable.ReadableState=ReadableState;const{EventEmitter:EE}=require("events");const{Stream,prependListener}=require("./legacy");const{Buffer}=require("buffer");const{addAbortSignal}=require("./add-abort-signal");const eos=require("./end-of-stream");let debug=require("../../ours/util").debuglog("stream",fn=>{debug=fn});const BufferList=require("./buffer_list");const destroyImpl=require("./destroy");const{getHighWaterMark,getDefaultHighWaterMark}=require("./state");const{aggregateTwoErrors,codes:{ERR_INVALID_ARG_TYPE,ERR_METHOD_NOT_IMPLEMENTED,ERR_OUT_OF_RANGE,ERR_STREAM_PUSH_AFTER_EOF,ERR_STREAM_UNSHIFT_AFTER_END_EVENT},AbortError}=require("../../ours/errors");const{validateObject}=require("../validators");const kPaused=Symbol("kPaused");const{StringDecoder}=require("string_decoder/");const from=require("./from");ObjectSetPrototypeOf(Readable.prototype,Stream.prototype);ObjectSetPrototypeOf(Readable,Stream);const nop=()=>{};const{errorOrDestroy}=destroyImpl;const kObjectMode=1<<0;const kEnded=1<<1;const kEndEmitted=1<<2;const kReading=1<<3;const kConstructed=1<<4;const kSync=1<<5;const kNeedReadable=1<<6;const kEmittedReadable=1<<7;const kReadableListening=1<<8;const kResumeScheduled=1<<9;const kErrorEmitted=1<<10;const kEmitClose=1<<11;const kAutoDestroy=1<<12;const kDestroyed=1<<13;const kClosed=1<<14;const kCloseEmitted=1<<15;const kMultiAwaitDrain=1<<16;const kReadingMore=1<<17;const kDataEmitted=1<<18;function makeBitMapDescriptor(bit){return{enumerable:false,get(){return(this.state&bit)!==0},set(value){if(value)this.state|=bit;else this.state&=~bit}}}ObjectDefineProperties(ReadableState.prototype,{objectMode:makeBitMapDescriptor(kObjectMode),ended:makeBitMapDescriptor(kEnded),endEmitted:makeBitMapDescriptor(kEndEmitted),reading:makeBitMapDescriptor(kReading),constructed:makeBitMapDescriptor(kConstructed),sync:makeBitMapDescriptor(kSync),needReadable:makeBitMapDescriptor(kNeedReadable),emittedReadable:makeBitMapDescriptor(kEmittedReadable),readableListening:makeBitMapDescriptor(kReadableListening),resumeScheduled:makeBitMapDescriptor(kResumeScheduled),errorEmitted:makeBitMapDescriptor(kErrorEmitted),emitClose:makeBitMapDescriptor(kEmitClose),autoDestroy:makeBitMapDescriptor(kAutoDestroy),destroyed:makeBitMapDescriptor(kDestroyed),closed:makeBitMapDescriptor(kClosed),closeEmitted:makeBitMapDescriptor(kCloseEmitted),multiAwaitDrain:makeBitMapDescriptor(kMultiAwaitDrain),readingMore:makeBitMapDescriptor(kReadingMore),dataEmitted:makeBitMapDescriptor(kDataEmitted)});function ReadableState(options,stream,isDuplex){if(typeof isDuplex!=="boolean")isDuplex=stream instanceof require("./duplex");this.state=kEmitClose|kAutoDestroy|kConstructed|kSync;if(options&&options.objectMode)this.state|=kObjectMode;if(isDuplex&&options&&options.readableObjectMode)this.state|=kObjectMode;this.highWaterMark=options?getHighWaterMark(this,options,"readableHighWaterMark",isDuplex):getDefaultHighWaterMark(false);this.buffer=new BufferList;this.length=0;this.pipes=[];this.flowing=null;this[kPaused]=null;if(options&&options.emitClose===false)this.state&=~kEmitClose;if(options&&options.autoDestroy===false)this.state&=~kAutoDestroy;this.errored=null;this.defaultEncoding=options&&options.defaultEncoding||"utf8";this.awaitDrainWriters=null;this.decoder=null;this.encoding=null;if(options&&options.encoding){this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){if(!(this instanceof Readable))return new Readable(options);const isDuplex=this instanceof require("./duplex");this._readableState=new ReadableState(options,this,isDuplex);if(options){if(typeof options.read==="function")this._read=options.read;if(typeof options.destroy==="function")this._destroy=options.destroy;if(typeof options.construct==="function")this._construct=options.construct;if(options.signal&&!isDuplex)addAbortSignal(options.signal,this)}Stream.call(this,options);destroyImpl.construct(this,()=>{if(this._readableState.needReadable){maybeReadMore(this,this._readableState)}})}Readable.prototype.destroy=destroyImpl.destroy;Readable.prototype._undestroy=destroyImpl.undestroy;Readable.prototype._destroy=function(err,cb){cb(err)};Readable.prototype[EE.captureRejectionSymbol]=function(err){this.destroy(err)};Readable.prototype[SymbolAsyncDispose]=function(){let error;if(!this.destroyed){error=this.readableEnded?null:new AbortError;this.destroy(error)}return new Promise((resolve,reject)=>eos(this,err=>err&&err!==error?reject(err):resolve(null)))};Readable.prototype.push=function(chunk,encoding){return readableAddChunk(this,chunk,encoding,false)};Readable.prototype.unshift=function(chunk,encoding){return readableAddChunk(this,chunk,encoding,true)};function readableAddChunk(stream,chunk,encoding,addToFront){debug("readableAddChunk",chunk);const state=stream._readableState;let err;if((state.state&kObjectMode)===0){if(typeof chunk==="string"){encoding=encoding||state.defaultEncoding;if(state.encoding!==encoding){if(addToFront&&state.encoding){chunk=Buffer.from(chunk,encoding).toString(state.encoding)}else{chunk=Buffer.from(chunk,encoding);encoding=""}}}else if(chunk instanceof Buffer){encoding=""}else if(Stream._isUint8Array(chunk)){chunk=Stream._uint8ArrayToBuffer(chunk);encoding=""}else if(chunk!=null){err=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer","Uint8Array"],chunk)}}if(err){errorOrDestroy(stream,err)}else if(chunk===null){state.state&=~kReading;onEofChunk(stream,state)}else if((state.state&kObjectMode)!==0||chunk&&chunk.length>0){if(addToFront){if((state.state&kEndEmitted)!==0)errorOrDestroy(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT);else if(state.destroyed||state.errored)return false;else addChunk(stream,state,chunk,true)}else if(state.ended){errorOrDestroy(stream,new ERR_STREAM_PUSH_AFTER_EOF)}else if(state.destroyed||state.errored){return false}else{state.state&=~kReading;if(state.decoder&&!encoding){chunk=state.decoder.write(chunk);if(state.objectMode||chunk.length!==0)addChunk(stream,state,chunk,false);else maybeReadMore(stream,state)}else{addChunk(stream,state,chunk,false)}}}else if(!addToFront){state.state&=~kReading;maybeReadMore(stream,state)}return!state.ended&&(state.length<state.highWaterMark||state.length===0)}function addChunk(stream,state,chunk,addToFront){if(state.flowing&&state.length===0&&!state.sync&&stream.listenerCount("data")>0){if((state.state&kMultiAwaitDrain)!==0){state.awaitDrainWriters.clear()}else{state.awaitDrainWriters=null}state.dataEmitted=true;stream.emit("data",chunk)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if((state.state&kNeedReadable)!==0)emitReadable(stream)}maybeReadMore(stream,state)}Readable.prototype.isPaused=function(){const state=this._readableState;return state[kPaused]===true||state.flowing===false};Readable.prototype.setEncoding=function(enc){const decoder=new StringDecoder(enc);this._readableState.decoder=decoder;this._readableState.encoding=this._readableState.decoder.encoding;const buffer=this._readableState.buffer;let content="";for(const data of buffer){content+=decoder.write(data)}buffer.clear();if(content!=="")buffer.push(content);this._readableState.length=content.length;return this};const MAX_HWM=1073741824;function computeNewHighWaterMark(n){if(n>MAX_HWM){throw new ERR_OUT_OF_RANGE("size","<= 1GiB",n)}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if((state.state&kObjectMode)!==0)return 1;if(NumberIsNaN(n)){if(state.flowing&&state.length)return state.buffer.first().length;return state.length}if(n<=state.length)return n;return state.ended?state.length:0}Readable.prototype.read=function(n){debug("read",n);if(n===undefined){n=NaN}else if(!NumberIsInteger(n)){n=NumberParseInt(n,10)}const state=this._readableState;const nOrig=n;if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n!==0)state.state&=~kEmittedReadable;if(n===0&&state.needReadable&&((state.highWaterMark!==0?state.length>=state.highWaterMark:state.length>0)||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}let doRead=(state.state&kNeedReadable)!==0;debug("need readable",doRead);if(state.length===0||state.length-n<state.highWaterMark){doRead=true;debug("length less than watermark",doRead)}if(state.ended||state.reading||state.destroyed||state.errored||!state.constructed){doRead=false;debug("reading, ended or constructing",doRead)}else if(doRead){debug("do read");state.state|=kReading|kSync;if(state.length===0)state.state|=kNeedReadable;try{this._read(state.highWaterMark)}catch(err){errorOrDestroy(this,err)}state.state&=~kSync;if(!state.reading)n=howMuchToRead(nOrig,state)}let ret;if(n>0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=state.length<=state.highWaterMark;n=0}else{state.length-=n;if(state.multiAwaitDrain){state.awaitDrainWriters.clear()}else{state.awaitDrainWriters=null}}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null&&!state.errorEmitted&&!state.closeEmitted){state.dataEmitted=true;this.emit("data",ret)}return ret};function onEofChunk(stream,state){debug("onEofChunk");if(state.ended)return;if(state.decoder){const chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;if(state.sync){emitReadable(stream)}else{state.needReadable=false;state.emittedReadable=true;emitReadable_(stream)}}function emitReadable(stream){const state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable);state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;process.nextTick(emitReadable_,stream)}}function emitReadable_(stream){const state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended);if(!state.destroyed&&!state.errored&&(state.length||state.ended)){stream.emit("readable");state.emittedReadable=false}state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark;flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore&&state.constructed){state.readingMore=true;process.nextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){while(!state.reading&&!state.ended&&(state.length<state.highWaterMark||state.flowing&&state.length===0)){const len=state.length;debug("maybeReadMore read 0");stream.read(0);if(len===state.length)break}state.readingMore=false}Readable.prototype._read=function(n){throw new ERR_METHOD_NOT_IMPLEMENTED("_read()")};Readable.prototype.pipe=function(dest,pipeOpts){const src=this;const state=this._readableState;if(state.pipes.length===1){if(!state.multiAwaitDrain){state.multiAwaitDrain=true;state.awaitDrainWriters=new SafeSet(state.awaitDrainWriters?[state.awaitDrainWriters]:[])}}state.pipes.push(dest);debug("pipe count=%d opts=%j",state.pipes.length,pipeOpts);const doEnd=(!pipeOpts||pipeOpts.end!==false)&&dest!==process.stdout&&dest!==process.stderr;const endFn=doEnd?onend:unpipe;if(state.endEmitted)process.nextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable,unpipeInfo){debug("onunpipe");if(readable===src){if(unpipeInfo&&unpipeInfo.hasUnpiped===false){unpipeInfo.hasUnpiped=true;cleanup()}}}function onend(){debug("onend");dest.end()}let ondrain;let cleanedUp=false;function cleanup(){debug("cleanup");dest.removeListener("close",onclose);dest.removeListener("finish",onfinish);if(ondrain){dest.removeListener("drain",ondrain)}dest.removeListener("error",onerror);dest.removeListener("unpipe",onunpipe);src.removeListener("end",onend);src.removeListener("end",unpipe);src.removeListener("data",ondata);cleanedUp=true;if(ondrain&&state.awaitDrainWriters&&(!dest._writableState||dest._writableState.needDrain))ondrain()}function pause(){if(!cleanedUp){if(state.pipes.length===1&&state.pipes[0]===dest){debug("false write response, pause",0);state.awaitDrainWriters=dest;state.multiAwaitDrain=false}else if(state.pipes.length>1&&state.pipes.includes(dest)){debug("false write response, pause",state.awaitDrainWriters.size);state.awaitDrainWriters.add(dest)}src.pause()}if(!ondrain){ondrain=pipeOnDrain(src,dest);dest.on("drain",ondrain)}}src.on("data",ondata);function ondata(chunk){debug("ondata");const ret=dest.write(chunk);debug("dest.write",ret);if(ret===false){pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(dest.listenerCount("error")===0){const s=dest._writableState||dest._readableState;if(s&&!s.errorEmitted){errorOrDestroy(dest,er)}else{dest.emit("error",er)}}}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(dest.writableNeedDrain===true){pause()}else if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src,dest){return function pipeOnDrainFunctionResult(){const state=src._readableState;if(state.awaitDrainWriters===dest){debug("pipeOnDrain",1);state.awaitDrainWriters=null}else if(state.multiAwaitDrain){debug("pipeOnDrain",state.awaitDrainWriters.size);state.awaitDrainWriters.delete(dest)}if((!state.awaitDrainWriters||state.awaitDrainWriters.size===0)&&src.listenerCount("data")){src.resume()}}}Readable.prototype.unpipe=function(dest){const state=this._readableState;const unpipeInfo={hasUnpiped:false};if(state.pipes.length===0)return this;if(!dest){const dests=state.pipes;state.pipes=[];this.pause();for(let i=0;i<dests.length;i++)dests[i].emit("unpipe",this,{hasUnpiped:false});return this}const index=ArrayPrototypeIndexOf(state.pipes,dest);if(index===-1)return this;state.pipes.splice(index,1);if(state.pipes.length===0)this.pause();dest.emit("unpipe",this,unpipeInfo);return this};Readable.prototype.on=function(ev,fn){const res=Stream.prototype.on.call(this,ev,fn);const state=this._readableState;if(ev==="data"){state.readableListening=this.listenerCount("readable")>0;if(state.flowing!==false)this.resume()}else if(ev==="readable"){if(!state.endEmitted&&!state.readableListening){state.readableListening=state.needReadable=true;state.flowing=false;state.emittedReadable=false;debug("on readable",state.length,state.reading);if(state.length){emitReadable(this)}else if(!state.reading){process.nextTick(nReadingNextTick,this)}}}return res};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.removeListener=function(ev,fn){const res=Stream.prototype.removeListener.call(this,ev,fn);if(ev==="readable"){process.nextTick(updateReadableListening,this)}return res};Readable.prototype.off=Readable.prototype.removeListener;Readable.prototype.removeAllListeners=function(ev){const res=Stream.prototype.removeAllListeners.apply(this,arguments);if(ev==="readable"||ev===undefined){process.nextTick(updateReadableListening,this)}return res};function updateReadableListening(self){const state=self._readableState;state.readableListening=self.listenerCount("readable")>0;if(state.resumeScheduled&&state[kPaused]===false){state.flowing=true}else if(self.listenerCount("data")>0){self.resume()}else if(!state.readableListening){state.flowing=null}}function nReadingNextTick(self){debug("readable nexttick read 0");self.read(0)}Readable.prototype.resume=function(){const state=this._readableState;if(!state.flowing){debug("resume");state.flowing=!state.readableListening;resume(this,state)}state[kPaused]=false;return this};function resume(stream,state){if(!state.resumeScheduled){state.resumeScheduled=true;process.nextTick(resume_,stream,state)}}function resume_(stream,state){debug("resume",state.reading);if(!state.reading){stream.read(0)}state.resumeScheduled=false;stream.emit("resume");flow(stream);if(state.flowing&&!state.reading)stream.read(0)}Readable.prototype.pause=function(){debug("call pause flowing=%j",this._readableState.flowing);if(this._readableState.flowing!==false){debug("pause");this._readableState.flowing=false;this.emit("pause")}this._readableState[kPaused]=true;return this};function flow(stream){const state=stream._readableState;debug("flow",state.flowing);while(state.flowing&&stream.read()!==null);}Readable.prototype.wrap=function(stream){let paused=false;stream.on("data",chunk=>{if(!this.push(chunk)&&stream.pause){paused=true;stream.pause()}});stream.on("end",()=>{this.push(null)});stream.on("error",err=>{errorOrDestroy(this,err)});stream.on("close",()=>{this.destroy()});stream.on("destroy",()=>{this.destroy()});this._read=()=>{if(paused&&stream.resume){paused=false;stream.resume()}};const streamKeys=ObjectKeys(stream);for(let j=1;j<streamKeys.length;j++){const i=streamKeys[j];if(this[i]===undefined&&typeof stream[i]==="function"){this[i]=stream[i].bind(stream)}}return this};Readable.prototype[SymbolAsyncIterator]=function(){return streamToAsyncIterator(this)};Readable.prototype.iterator=function(options){if(options!==undefined){validateObject(options,"options")}return streamToAsyncIterator(this,options)};function streamToAsyncIterator(stream,options){if(typeof stream.read!=="function"){stream=Readable.wrap(stream,{objectMode:true})}const iter=createAsyncIterator(stream,options);iter.stream=stream;return iter}async function*createAsyncIterator(stream,options){let callback=nop;function next(resolve){if(this===stream){callback();callback=nop}else{callback=resolve}}stream.on("readable",next);let error;const cleanup=eos(stream,{writable:false},err=>{error=err?aggregateTwoErrors(error,err):null;callback();callback=nop});try{while(true){const chunk=stream.destroyed?null:stream.read();if(chunk!==null){yield chunk}else if(error){throw error}else if(error===null){return}else{await new Promise(next)}}}catch(err){error=aggregateTwoErrors(error,err);throw error}finally{if((error||(options===null||options===undefined?undefined:options.destroyOnReturn)!==false)&&(error===undefined||stream._readableState.autoDestroy)){destroyImpl.destroyer(stream,null)}else{stream.off("readable",next);cleanup()}}}ObjectDefineProperties(Readable.prototype,{readable:{__proto__:null,get(){const r=this._readableState;return!!r&&r.readable!==false&&!r.destroyed&&!r.errorEmitted&&!r.endEmitted},set(val){if(this._readableState){this._readableState.readable=!!val}}},readableDidRead:{__proto__:null,enumerable:false,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:false,get:function(){return!!(this._readableState.readable!==false&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:false,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:false,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:false,get:function(){return this._readableState.flowing},set:function(state){if(this._readableState){this._readableState.flowing=state}}},readableLength:{__proto__:null,enumerable:false,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:false,get(){return this._readableState?this._readableState.objectMode:false}},readableEncoding:{__proto__:null,enumerable:false,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:false,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:false}},destroyed:{__proto__:null,enumerable:false,get(){return this._readableState?this._readableState.destroyed:false},set(value){if(!this._readableState){return}this._readableState.destroyed=value}},readableEnded:{__proto__:null,enumerable:false,get(){return this._readableState?this._readableState.endEmitted:false}}});ObjectDefineProperties(ReadableState.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[kPaused]!==false},set(value){this[kPaused]=!!value}}});Readable._fromList=fromList;function fromList(n,state){if(state.length===0)return null;let ret;if(state.objectMode)ret=state.buffer.shift();else if(!n||n>=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.first();else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=state.buffer.consume(n,state.decoder)}return ret}function endReadable(stream){const state=stream._readableState;debug("endReadable",state.endEmitted);if(!state.endEmitted){state.ended=true;process.nextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){debug("endReadableNT",state.endEmitted,state.length);if(!state.errored&&!state.closeEmitted&&!state.endEmitted&&state.length===0){state.endEmitted=true;stream.emit("end");if(stream.writable&&stream.allowHalfOpen===false){process.nextTick(endWritableNT,stream)}else if(state.autoDestroy){const wState=stream._writableState;const autoDestroy=!wState||wState.autoDestroy&&(wState.finished||wState.writable===false);if(autoDestroy){stream.destroy()}}}}function endWritableNT(stream){const writable=stream.writable&&!stream.writableEnded&&!stream.destroyed;if(writable){stream.end()}}Readable.from=function(iterable,opts){return from(Readable,iterable,opts)};let webStreamsAdapters;function lazyWebStreams(){if(webStreamsAdapters===undefined)webStreamsAdapters={};return webStreamsAdapters}Readable.fromWeb=function(readableStream,options){return lazyWebStreams().newStreamReadableFromReadableStream(readableStream,options)};Readable.toWeb=function(streamReadable,options){return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable,options)};Readable.wrap=function(src,options){var _ref,_src$readableObjectMo;return new Readable({objectMode:(_ref=(_src$readableObjectMo=src.readableObjectMode)!==null&&_src$readableObjectMo!==undefined?_src$readableObjectMo:src.objectMode)!==null&&_ref!==undefined?_ref:true,...options,destroy(err,callback){destroyImpl.destroyer(src,err);callback(err)}}).wrap(src)}},{"../../ours/errors":40,"../../ours/primordials":41,"../../ours/util":42,"../validators":38,"./add-abort-signal":21,"./buffer_list":22,"./destroy":24,"./duplex":25,"./end-of-stream":27,"./from":28,"./legacy":29,"./state":34,buffer:17,events:18,"process/":20,"string_decoder/":47}],34:[function(require,module,exports){"use strict";const{MathFloor,NumberIsInteger}=require("../../ours/primordials");const{validateInteger}=require("../validators");const{ERR_INVALID_ARG_VALUE}=require("../../ours/errors").codes;let defaultHighWaterMarkBytes=16*1024;let defaultHighWaterMarkObjectMode=16;function highWaterMarkFrom(options,isDuplex,duplexKey){return options.highWaterMark!=null?options.highWaterMark:isDuplex?options[duplexKey]:null}function getDefaultHighWaterMark(objectMode){return objectMode?defaultHighWaterMarkObjectMode:defaultHighWaterMarkBytes}function setDefaultHighWaterMark(objectMode,value){validateInteger(value,"value",0);if(objectMode){defaultHighWaterMarkObjectMode=value}else{defaultHighWaterMarkBytes=value}}function getHighWaterMark(state,options,duplexKey,isDuplex){const hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(hwm!=null){if(!NumberIsInteger(hwm)||hwm<0){const name=isDuplex?`options.${duplexKey}`:"options.highWaterMark";throw new ERR_INVALID_ARG_VALUE(name,hwm)}return MathFloor(hwm)}return getDefaultHighWaterMark(state.objectMode)}module.exports={getHighWaterMark:getHighWaterMark,getDefaultHighWaterMark:getDefaultHighWaterMark,setDefaultHighWaterMark:setDefaultHighWaterMark}},{"../../ours/errors":40,"../../ours/primordials":41,"../validators":38}],35:[function(require,module,exports){"use strict";const{ObjectSetPrototypeOf,Symbol}=require("../../ours/primordials");module.exports=Transform;const{ERR_METHOD_NOT_IMPLEMENTED}=require("../../ours/errors").codes;const Duplex=require("./duplex");const{getHighWaterMark}=require("./state");ObjectSetPrototypeOf(Transform.prototype,Duplex.prototype);ObjectSetPrototypeOf(Transform,Duplex);const kCallback=Symbol("kCallback");function Transform(options){if(!(this instanceof Transform))return new Transform(options);const readableHighWaterMark=options?getHighWaterMark(this,options,"readableHighWaterMark",true):null;if(readableHighWaterMark===0){options={...options,highWaterMark:null,readableHighWaterMark:readableHighWaterMark,writableHighWaterMark:options.writableHighWaterMark||0}}Duplex.call(this,options);this._readableState.sync=false;this[kCallback]=null;if(options){if(typeof options.transform==="function")this._transform=options.transform;if(typeof options.flush==="function")this._flush=options.flush}this.on("prefinish",prefinish)}function final(cb){if(typeof this._flush==="function"&&!this.destroyed){this._flush((er,data)=>{if(er){if(cb){cb(er)}else{this.destroy(er)}return}if(data!=null){this.push(data)}this.push(null);if(cb){cb()}})}else{this.push(null);if(cb){cb()}}}function prefinish(){if(this._final!==final){final.call(this)}}Transform.prototype._final=final;Transform.prototype._transform=function(chunk,encoding,callback){throw new ERR_METHOD_NOT_IMPLEMENTED("_transform()")};Transform.prototype._write=function(chunk,encoding,callback){const rState=this._readableState;const wState=this._writableState;const length=rState.length;this._transform(chunk,encoding,(err,val)=>{if(err){callback(err);return}if(val!=null){this.push(val)}if(wState.ended||length===rState.length||rState.length<rState.highWaterMark){callback()}else{this[kCallback]=callback}})};Transform.prototype._read=function(){if(this[kCallback]){const callback=this[kCallback];this[kCallback]=null;callback()}}},{"../../ours/errors":40,"../../ours/primordials":41,"./duplex":25,"./state":34}],36:[function(require,module,exports){"use strict";const{SymbolAsyncIterator,SymbolIterator,SymbolFor}=require("../../ours/primordials");const kIsDestroyed=SymbolFor("nodejs.stream.destroyed");const kIsErrored=SymbolFor("nodejs.stream.errored");const kIsReadable=SymbolFor("nodejs.stream.readable");const kIsWritable=SymbolFor("nodejs.stream.writable");const kIsDisturbed=SymbolFor("nodejs.stream.disturbed");const kIsClosedPromise=SymbolFor("nodejs.webstream.isClosedPromise");const kControllerErrorFunction=SymbolFor("nodejs.webstream.controllerErrorFunction");function isReadableNodeStream(obj,strict=false){var _obj$_readableState;return!!(obj&&typeof obj.pipe==="function"&&typeof obj.on==="function"&&(!strict||typeof obj.pause==="function"&&typeof obj.resume==="function")&&(!obj._writableState||((_obj$_readableState=obj._readableState)===null||_obj$_readableState===undefined?undefined:_obj$_readableState.readable)!==false)&&(!obj._writableState||obj._readableState))}function isWritableNodeStream(obj){var _obj$_writableState;return!!(obj&&typeof obj.write==="function"&&typeof obj.on==="function"&&(!obj._readableState||((_obj$_writableState=obj._writableState)===null||_obj$_writableState===undefined?undefined:_obj$_writableState.writable)!==false))}function isDuplexNodeStream(obj){return!!(obj&&typeof obj.pipe==="function"&&obj._readableState&&typeof obj.on==="function"&&typeof obj.write==="function")}function isNodeStream(obj){return obj&&(obj._readableState||obj._writableState||typeof obj.write==="function"&&typeof obj.on==="function"||typeof obj.pipe==="function"&&typeof obj.on==="function")}function isReadableStream(obj){return!!(obj&&!isNodeStream(obj)&&typeof obj.pipeThrough==="function"&&typeof obj.getReader==="function"&&typeof obj.cancel==="function")}function isWritableStream(obj){return!!(obj&&!isNodeStream(obj)&&typeof obj.getWriter==="function"&&typeof obj.abort==="function")}function isTransformStream(obj){return!!(obj&&!isNodeStream(obj)&&typeof obj.readable==="object"&&typeof obj.writable==="object")}function isWebStream(obj){return isReadableStream(obj)||isWritableStream(obj)||isTransformStream(obj)}function isIterable(obj,isAsync){if(obj==null)return false;if(isAsync===true)return typeof obj[SymbolAsyncIterator]==="function";if(isAsync===false)return typeof obj[SymbolIterator]==="function";return typeof obj[SymbolAsyncIterator]==="function"||typeof obj[SymbolIterator]==="function"}function isDestroyed(stream){if(!isNodeStream(stream))return null;const wState=stream._writableState;const rState=stream._readableState;const state=wState||rState;return!!(stream.destroyed||stream[kIsDestroyed]||state!==null&&state!==undefined&&state.destroyed)}function isWritableEnded(stream){if(!isWritableNodeStream(stream))return null;if(stream.writableEnded===true)return true;const wState=stream._writableState;if(wState!==null&&wState!==undefined&&wState.errored)return false;if(typeof(wState===null||wState===undefined?undefined:wState.ended)!=="boolean")return null;return wState.ended}function isWritableFinished(stream,strict){if(!isWritableNodeStream(stream))return null;if(stream.writableFinished===true)return true;const wState=stream._writableState;if(wState!==null&&wState!==undefined&&wState.errored)return false;if(typeof(wState===null||wState===undefined?undefined:wState.finished)!=="boolean")return null;return!!(wState.finished||strict===false&&wState.ended===true&&wState.length===0)}function isReadableEnded(stream){if(!isReadableNodeStream(stream))return null;if(stream.readableEnded===true)return true;const rState=stream._readableState;if(!rState||rState.errored)return false;if(typeof(rState===null||rState===undefined?undefined:rState.ended)!=="boolean")return null;return rState.ended}function isReadableFinished(stream,strict){if(!isReadableNodeStream(stream))return null;const rState=stream._readableState;if(rState!==null&&rState!==undefined&&rState.errored)return false;if(typeof(rState===null||rState===undefined?undefined:rState.endEmitted)!=="boolean")return null;return!!(rState.endEmitted||strict===false&&rState.ended===true&&rState.length===0)}function isReadable(stream){if(stream&&stream[kIsReadable]!=null)return stream[kIsReadable];if(typeof(stream===null||stream===undefined?undefined:stream.readable)!=="boolean")return null;if(isDestroyed(stream))return false;return isReadableNodeStream(stream)&&stream.readable&&!isReadableFinished(stream)}function isWritable(stream){if(stream&&stream[kIsWritable]!=null)return stream[kIsWritable];if(typeof(stream===null||stream===undefined?undefined:stream.writable)!=="boolean")return null;if(isDestroyed(stream))return false;return isWritableNodeStream(stream)&&stream.writable&&!isWritableEnded(stream)}function isFinished(stream,opts){if(!isNodeStream(stream)){return null}if(isDestroyed(stream)){return true}if((opts===null||opts===undefined?undefined:opts.readable)!==false&&isReadable(stream)){return false}if((opts===null||opts===undefined?undefined:opts.writable)!==false&&isWritable(stream)){return false}return true}function isWritableErrored(stream){var _stream$_writableStat,_stream$_writableStat2;if(!isNodeStream(stream)){return null}if(stream.writableErrored){return stream.writableErrored}return(_stream$_writableStat=(_stream$_writableStat2=stream._writableState)===null||_stream$_writableStat2===undefined?undefined:_stream$_writableStat2.errored)!==null&&_stream$_writableStat!==undefined?_stream$_writableStat:null}function isReadableErrored(stream){var _stream$_readableStat,_stream$_readableStat2;if(!isNodeStream(stream)){return null}if(stream.readableErrored){return stream.readableErrored}return(_stream$_readableStat=(_stream$_readableStat2=stream._readableState)===null||_stream$_readableStat2===undefined?undefined:_stream$_readableStat2.errored)!==null&&_stream$_readableStat!==undefined?_stream$_readableStat:null}function isClosed(stream){if(!isNodeStream(stream)){return null}if(typeof stream.closed==="boolean"){return stream.closed}const wState=stream._writableState;const rState=stream._readableState;if(typeof(wState===null||wState===undefined?undefined:wState.closed)==="boolean"||typeof(rState===null||rState===undefined?undefined:rState.closed)==="boolean"){return(wState===null||wState===undefined?undefined:wState.closed)||(rState===null||rState===undefined?undefined:rState.closed)}if(typeof stream._closed==="boolean"&&isOutgoingMessage(stream)){return stream._closed}return null}function isOutgoingMessage(stream){return typeof stream._closed==="boolean"&&typeof stream._defaultKeepAlive==="boolean"&&typeof stream._removedConnection==="boolean"&&typeof stream._removedContLen==="boolean"}function isServerResponse(stream){return typeof stream._sent100==="boolean"&&isOutgoingMessage(stream)}function isServerRequest(stream){var _stream$req;return typeof stream._consuming==="boolean"&&typeof stream._dumped==="boolean"&&((_stream$req=stream.req)===null||_stream$req===undefined?undefined:_stream$req.upgradeOrConnect)===undefined}function willEmitClose(stream){if(!isNodeStream(stream))return null;const wState=stream._writableState;const rState=stream._readableState;const state=wState||rState;return!state&&isServerResponse(stream)||!!(state&&state.autoDestroy&&state.emitClose&&state.closed===false)}function isDisturbed(stream){var _stream$kIsDisturbed;return!!(stream&&((_stream$kIsDisturbed=stream[kIsDisturbed])!==null&&_stream$kIsDisturbed!==undefined?_stream$kIsDisturbed:stream.readableDidRead||stream.readableAborted))}function isErrored(stream){var _ref,_ref2,_ref3,_ref4,_ref5,_stream$kIsErrored,_stream$_readableStat3,_stream$_writableStat3,_stream$_readableStat4,_stream$_writableStat4;return!!(stream&&((_ref=(_ref2=(_ref3=(_ref4=(_ref5=(_stream$kIsErrored=stream[kIsErrored])!==null&&_stream$kIsErrored!==undefined?_stream$kIsErrored:stream.readableErrored)!==null&&_ref5!==undefined?_ref5:stream.writableErrored)!==null&&_ref4!==undefined?_ref4:(_stream$_readableStat3=stream._readableState)===null||_stream$_readableStat3===undefined?undefined:_stream$_readableStat3.errorEmitted)!==null&&_ref3!==undefined?_ref3:(_stream$_writableStat3=stream._writableState)===null||_stream$_writableStat3===undefined?undefined:_stream$_writableStat3.errorEmitted)!==null&&_ref2!==undefined?_ref2:(_stream$_readableStat4=stream._readableState)===null||_stream$_readableStat4===undefined?undefined:_stream$_readableStat4.errored)!==null&&_ref!==undefined?_ref:(_stream$_writableStat4=stream._writableState)===null||_stream$_writableStat4===undefined?undefined:_stream$_writableStat4.errored))}module.exports={isDestroyed:isDestroyed,kIsDestroyed:kIsDestroyed,isDisturbed:isDisturbed,kIsDisturbed:kIsDisturbed,isErrored:isErrored,kIsErrored:kIsErrored,isReadable:isReadable,kIsReadable:kIsReadable,kIsClosedPromise:kIsClosedPromise,kControllerErrorFunction:kControllerErrorFunction,kIsWritable:kIsWritable,isClosed:isClosed,isDuplexNodeStream:isDuplexNodeStream,isFinished:isFinished,isIterable:isIterable,isReadableNodeStream:isReadableNodeStream,isReadableStream:isReadableStream,isReadableEnded:isReadableEnded,isReadableFinished:isReadableFinished,isReadableErrored:isReadableErrored,isNodeStream:isNodeStream,isWebStream:isWebStream,isWritable:isWritable,isWritableNodeStream:isWritableNodeStream,isWritableStream:isWritableStream,isWritableEnded:isWritableEnded,isWritableFinished:isWritableFinished,isWritableErrored:isWritableErrored,isServerRequest:isServerRequest,isServerResponse:isServerResponse,willEmitClose:willEmitClose,isTransformStream:isTransformStream}},{"../../ours/primordials":41}],37:[function(require,module,exports){"use strict";const process=require("process/");const{ArrayPrototypeSlice,Error,FunctionPrototypeSymbolHasInstance,ObjectDefineProperty,ObjectDefineProperties,ObjectSetPrototypeOf,StringPrototypeToLowerCase,Symbol,SymbolHasInstance}=require("../../ours/primordials");module.exports=Writable;Writable.WritableState=WritableState;const{EventEmitter:EE}=require("events");const Stream=require("./legacy").Stream;const{Buffer}=require("buffer");const destroyImpl=require("./destroy");const{addAbortSignal}=require("./add-abort-signal");const{getHighWaterMark,getDefaultHighWaterMark}=require("./state");const{ERR_INVALID_ARG_TYPE,ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK,ERR_STREAM_CANNOT_PIPE,ERR_STREAM_DESTROYED,ERR_STREAM_ALREADY_FINISHED,ERR_STREAM_NULL_VALUES,ERR_STREAM_WRITE_AFTER_END,ERR_UNKNOWN_ENCODING}=require("../../ours/errors").codes;const{errorOrDestroy}=destroyImpl;ObjectSetPrototypeOf(Writable.prototype,Stream.prototype);ObjectSetPrototypeOf(Writable,Stream);function nop(){}const kOnFinished=Symbol("kOnFinished");function WritableState(options,stream,isDuplex){if(typeof isDuplex!=="boolean")isDuplex=stream instanceof require("./duplex");this.objectMode=!!(options&&options.objectMode);if(isDuplex)this.objectMode=this.objectMode||!!(options&&options.writableObjectMode);this.highWaterMark=options?getHighWaterMark(this,options,"writableHighWaterMark",isDuplex):getDefaultHighWaterMark(false);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=false;const noDecode=!!(options&&options.decodeStrings===false);this.decodeStrings=!noDecode;this.defaultEncoding=options&&options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=onwrite.bind(undefined,stream);this.writecb=null;this.writelen=0;this.afterWriteTickInfo=null;resetBuffer(this);this.pendingcb=0;this.constructed=true;this.prefinished=false;this.errorEmitted=false;this.emitClose=!options||options.emitClose!==false;this.autoDestroy=!options||options.autoDestroy!==false;this.errored=null;this.closed=false;this.closeEmitted=false;this[kOnFinished]=[]}function resetBuffer(state){state.buffered=[];state.bufferedIndex=0;state.allBuffers=true;state.allNoop=true}WritableState.prototype.getBuffer=function getBuffer(){return ArrayPrototypeSlice(this.buffered,this.bufferedIndex)};ObjectDefineProperty(WritableState.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Writable(options){const isDuplex=this instanceof require("./duplex");if(!isDuplex&&!FunctionPrototypeSymbolHasInstance(Writable,this))return new Writable(options);this._writableState=new WritableState(options,this,isDuplex);if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev;if(typeof options.destroy==="function")this._destroy=options.destroy;if(typeof options.final==="function")this._final=options.final;if(typeof options.construct==="function")this._construct=options.construct;if(options.signal)addAbortSignal(options.signal,this)}Stream.call(this,options);destroyImpl.construct(this,()=>{const state=this._writableState;if(!state.writing){clearBuffer(this,state)}finishMaybe(this,state)})}ObjectDefineProperty(Writable,SymbolHasInstance,{__proto__:null,value:function(object){if(FunctionPrototypeSymbolHasInstance(this,object))return true;if(this!==Writable)return false;return object&&object._writableState instanceof WritableState}});Writable.prototype.pipe=function(){errorOrDestroy(this,new ERR_STREAM_CANNOT_PIPE)};function _write(stream,chunk,encoding,cb){const state=stream._writableState;if(typeof encoding==="function"){cb=encoding;encoding=state.defaultEncoding}else{if(!encoding)encoding=state.defaultEncoding;else if(encoding!=="buffer"&&!Buffer.isEncoding(encoding))throw new ERR_UNKNOWN_ENCODING(encoding);if(typeof cb!=="function")cb=nop}if(chunk===null){throw new ERR_STREAM_NULL_VALUES}else if(!state.objectMode){if(typeof chunk==="string"){if(state.decodeStrings!==false){chunk=Buffer.from(chunk,encoding);encoding="buffer"}}else if(chunk instanceof Buffer){encoding="buffer"}else if(Stream._isUint8Array(chunk)){chunk=Stream._uint8ArrayToBuffer(chunk);encoding="buffer"}else{throw new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer","Uint8Array"],chunk)}}let err;if(state.ending){err=new ERR_STREAM_WRITE_AFTER_END}else if(state.destroyed){err=new ERR_STREAM_DESTROYED("write")}if(err){process.nextTick(cb,err);errorOrDestroy(stream,err,true);return err}state.pendingcb++;return writeOrBuffer(stream,state,chunk,encoding,cb)}Writable.prototype.write=function(chunk,encoding,cb){return _write(this,chunk,encoding,cb)===true};Writable.prototype.cork=function(){this._writableState.corked++};Writable.prototype.uncork=function(){const state=this._writableState;if(state.corked){state.corked--;if(!state.writing)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=StringPrototypeToLowerCase(encoding);if(!Buffer.isEncoding(encoding))throw new ERR_UNKNOWN_ENCODING(encoding);this._writableState.defaultEncoding=encoding;return this};function writeOrBuffer(stream,state,chunk,encoding,callback){const len=state.objectMode?1:chunk.length;state.length+=len;const ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing||state.corked||state.errored||!state.constructed){state.buffered.push({chunk:chunk,encoding:encoding,callback:callback});if(state.allBuffers&&encoding!=="buffer"){state.allBuffers=false}if(state.allNoop&&callback!==nop){state.allNoop=false}}else{state.writelen=len;state.writecb=callback;state.writing=true;state.sync=true;stream._write(chunk,encoding,state.onwrite);state.sync=false}return ret&&!state.errored&&!state.destroyed}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len;state.writecb=cb;state.writing=true;state.sync=true;if(state.destroyed)state.onwrite(new ERR_STREAM_DESTROYED("write"));else if(writev)stream._writev(chunk,state.onwrite);else stream._write(chunk,encoding,state.onwrite);state.sync=false}function onwriteError(stream,state,er,cb){--state.pendingcb;cb(er);errorBuffer(state);errorOrDestroy(stream,er)}function onwrite(stream,er){const state=stream._writableState;const sync=state.sync;const cb=state.writecb;if(typeof cb!=="function"){errorOrDestroy(stream,new ERR_MULTIPLE_CALLBACK);return}state.writing=false;state.writecb=null;state.length-=state.writelen;state.writelen=0;if(er){er.stack;if(!state.errored){state.errored=er}if(stream._readableState&&!stream._readableState.errored){stream._readableState.errored=er}if(sync){process.nextTick(onwriteError,stream,state,er,cb)}else{onwriteError(stream,state,er,cb)}}else{if(state.buffered.length>state.bufferedIndex){clearBuffer(stream,state)}if(sync){if(state.afterWriteTickInfo!==null&&state.afterWriteTickInfo.cb===cb){state.afterWriteTickInfo.count++}else{state.afterWriteTickInfo={count:1,cb:cb,stream:stream,state:state};process.nextTick(afterWriteTick,state.afterWriteTickInfo)}}else{afterWrite(stream,state,1,cb)}}}function afterWriteTick({stream,state,count,cb}){state.afterWriteTickInfo=null;return afterWrite(stream,state,count,cb)}function afterWrite(stream,state,count,cb){const needDrain=!state.ending&&!stream.destroyed&&state.length===0&&state.needDrain;if(needDrain){state.needDrain=false;stream.emit("drain")}while(count-- >0){state.pendingcb--;cb()}if(state.destroyed){errorBuffer(state)}finishMaybe(stream,state)}function errorBuffer(state){if(state.writing){return}for(let n=state.bufferedIndex;n<state.buffered.length;++n){var _state$errored;const{chunk,callback}=state.buffered[n];const len=state.objectMode?1:chunk.length;state.length-=len;callback((_state$errored=state.errored)!==null&&_state$errored!==undefined?_state$errored:new ERR_STREAM_DESTROYED("write"))}const onfinishCallbacks=state[kOnFinished].splice(0);for(let i=0;i<onfinishCallbacks.length;i++){var _state$errored2;onfinishCallbacks[i]((_state$errored2=state.errored)!==null&&_state$errored2!==undefined?_state$errored2:new ERR_STREAM_DESTROYED("end"))}resetBuffer(state)}function clearBuffer(stream,state){if(state.corked||state.bufferProcessing||state.destroyed||!state.constructed){return}const{buffered,bufferedIndex,objectMode}=state;const bufferedLength=buffered.length-bufferedIndex;if(!bufferedLength){return}let i=bufferedIndex;state.bufferProcessing=true;if(bufferedLength>1&&stream._writev){state.pendingcb-=bufferedLength-1;const callback=state.allNoop?nop:err=>{for(let n=i;n<buffered.length;++n){buffered[n].callback(err)}};const chunks=state.allNoop&&i===0?buffered:ArrayPrototypeSlice(buffered,i);chunks.allBuffers=state.allBuffers;doWrite(stream,state,true,state.length,chunks,"",callback);resetBuffer(state)}else{do{const{chunk,encoding,callback}=buffered[i];buffered[i++]=null;const len=objectMode?1:chunk.length;doWrite(stream,state,false,len,chunk,encoding,callback)}while(i<buffered.length&&!state.writing);if(i===buffered.length){resetBuffer(state)}else if(i>256){buffered.splice(0,i);state.bufferedIndex=0}else{state.bufferedIndex=i}}state.bufferProcessing=false}Writable.prototype._write=function(chunk,encoding,cb){if(this._writev){this._writev([{chunk:chunk,encoding:encoding}],cb)}else{throw new ERR_METHOD_NOT_IMPLEMENTED("_write()")}};Writable.prototype._writev=null;Writable.prototype.end=function(chunk,encoding,cb){const state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}let err;if(chunk!==null&&chunk!==undefined){const ret=_write(this,chunk,encoding);if(ret instanceof Error){err=ret}}if(state.corked){state.corked=1;this.uncork()}if(err){}else if(!state.errored&&!state.ending){state.ending=true;finishMaybe(this,state,true);state.ended=true}else if(state.finished){err=new ERR_STREAM_ALREADY_FINISHED("end")}else if(state.destroyed){err=new ERR_STREAM_DESTROYED("end")}if(typeof cb==="function"){if(err||state.finished){process.nextTick(cb,err)}else{state[kOnFinished].push(cb)}}return this};function needFinish(state){return state.ending&&!state.destroyed&&state.constructed&&state.length===0&&!state.errored&&state.buffered.length===0&&!state.finished&&!state.writing&&!state.errorEmitted&&!state.closeEmitted}function callFinal(stream,state){let called=false;function onFinish(err){if(called){errorOrDestroy(stream,err!==null&&err!==undefined?err:ERR_MULTIPLE_CALLBACK());return}called=true;state.pendingcb--;if(err){const onfinishCallbacks=state[kOnFinished].splice(0);for(let i=0;i<onfinishCallbacks.length;i++){onfinishCallbacks[i](err)}errorOrDestroy(stream,err,state.sync)}else if(needFinish(state)){state.prefinished=true;stream.emit("prefinish");state.pendingcb++;process.nextTick(finish,stream,state)}}state.sync=true;state.pendingcb++;try{stream._final(onFinish)}catch(err){onFinish(err)}state.sync=false}function prefinish(stream,state){if(!state.prefinished&&!state.finalCalled){if(typeof stream._final==="function"&&!state.destroyed){state.finalCalled=true;callFinal(stream,state)}else{state.prefinished=true;stream.emit("prefinish")}}}function finishMaybe(stream,state,sync){if(needFinish(state)){prefinish(stream,state);if(state.pendingcb===0){if(sync){state.pendingcb++;process.nextTick((stream,state)=>{if(needFinish(state)){finish(stream,state)}else{state.pendingcb--}},stream,state)}else if(needFinish(state)){state.pendingcb++;finish(stream,state)}}}}function finish(stream,state){state.pendingcb--;state.finished=true;const onfinishCallbacks=state[kOnFinished].splice(0);for(let i=0;i<onfinishCallbacks.length;i++){onfinishCallbacks[i]()}stream.emit("finish");if(state.autoDestroy){const rState=stream._readableState;const autoDestroy=!rState||rState.autoDestroy&&(rState.endEmitted||rState.readable===false);if(autoDestroy){stream.destroy()}}}ObjectDefineProperties(Writable.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:false}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:false},set(value){if(this._writableState){this._writableState.destroyed=value}}},writable:{__proto__:null,get(){const w=this._writableState;return!!w&&w.writable!==false&&!w.destroyed&&!w.errored&&!w.ending&&!w.ended},set(val){if(this._writableState){this._writableState.writable=!!val}}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:false}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:false}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:false}},writableNeedDrain:{__proto__:null,get(){const wState=this._writableState;if(!wState)return false;return!wState.destroyed&&!wState.ending&&wState.needDrain}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:false,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:false,get:function(){return!!(this._writableState.writable!==false&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});const destroy=destroyImpl.destroy;Writable.prototype.destroy=function(err,cb){const state=this._writableState;if(!state.destroyed&&(state.bufferedIndex<state.buffered.length||state[kOnFinished].length)){process.nextTick(errorBuffer,state)}destroy.call(this,err,cb);return this};Writable.prototype._undestroy=destroyImpl.undestroy;Writable.prototype._destroy=function(err,cb){cb(err)};Writable.prototype[EE.captureRejectionSymbol]=function(err){this.destroy(err)};let webStreamsAdapters;function lazyWebStreams(){if(webStreamsAdapters===undefined)webStreamsAdapters={};return webStreamsAdapters}Writable.fromWeb=function(writableStream,options){return lazyWebStreams().newStreamWritableFromWritableStream(writableStream,options)};Writable.toWeb=function(streamWritable){return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable)}},{"../../ours/errors":40,"../../ours/primordials":41,"./add-abort-signal":21,"./destroy":24,"./duplex":25,"./legacy":29,"./state":34,buffer:17,events:18,"process/":20}],38:[function(require,module,exports){"use strict";const{ArrayIsArray,ArrayPrototypeIncludes,ArrayPrototypeJoin,ArrayPrototypeMap,NumberIsInteger,NumberIsNaN,NumberMAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER,NumberParseInt,ObjectPrototypeHasOwnProperty,RegExpPrototypeExec,String,StringPrototypeToUpperCase,StringPrototypeTrim}=require("../ours/primordials");const{hideStackFrames,codes:{ERR_SOCKET_BAD_PORT,ERR_INVALID_ARG_TYPE,ERR_INVALID_ARG_VALUE,ERR_OUT_OF_RANGE,ERR_UNKNOWN_SIGNAL}}=require("../ours/errors");const{normalizeEncoding}=require("../ours/util");const{isAsyncFunction,isArrayBufferView}=require("../ours/util").types;const signals={};function isInt32(value){return value===(value|0)}function isUint32(value){return value===value>>>0}const octalReg=/^[0-7]+$/;const modeDesc="must be a 32-bit unsigned integer or an octal string";function parseFileMode(value,name,def){if(typeof value==="undefined"){value=def}if(typeof value==="string"){if(RegExpPrototypeExec(octalReg,value)===null){throw new ERR_INVALID_ARG_VALUE(name,value,modeDesc)}value=NumberParseInt(value,8)}validateUint32(value,name);return value}const validateInteger=hideStackFrames((value,name,min=NumberMIN_SAFE_INTEGER,max=NumberMAX_SAFE_INTEGER)=>{if(typeof value!=="number")throw new ERR_INVALID_ARG_TYPE(name,"number",value);if(!NumberIsInteger(value))throw new ERR_OUT_OF_RANGE(name,"an integer",value);if(value<min||value>max)throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)});const validateInt32=hideStackFrames((value,name,min=-2147483648,max=2147483647)=>{if(typeof value!=="number"){throw new ERR_INVALID_ARG_TYPE(name,"number",value)}if(!NumberIsInteger(value)){throw new ERR_OUT_OF_RANGE(name,"an integer",value)}if(value<min||value>max){throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}});const validateUint32=hideStackFrames((value,name,positive=false)=>{if(typeof value!=="number"){throw new ERR_INVALID_ARG_TYPE(name,"number",value)}if(!NumberIsInteger(value)){throw new ERR_OUT_OF_RANGE(name,"an integer",value)}const min=positive?1:0;const max=4294967295;if(value<min||value>max){throw new ERR_OUT_OF_RANGE(name,`>= ${min} && <= ${max}`,value)}});function validateString(value,name){if(typeof value!=="string")throw new ERR_INVALID_ARG_TYPE(name,"string",value)}function validateNumber(value,name,min=undefined,max){if(typeof value!=="number")throw new ERR_INVALID_ARG_TYPE(name,"number",value);if(min!=null&&value<min||max!=null&&value>max||(min!=null||max!=null)&&NumberIsNaN(value)){throw new ERR_OUT_OF_RANGE(name,`${min!=null?`>= ${min}`:""}${min!=null&&max!=null?" && ":""}${max!=null?`<= ${max}`:""}`,value)}}const validateOneOf=hideStackFrames((value,name,oneOf)=>{if(!ArrayPrototypeIncludes(oneOf,value)){const allowed=ArrayPrototypeJoin(ArrayPrototypeMap(oneOf,v=>typeof v==="string"?`'${v}'`:String(v)),", ");const reason="must be one of: "+allowed;throw new ERR_INVALID_ARG_VALUE(name,value,reason)}});function validateBoolean(value,name){if(typeof value!=="boolean")throw new ERR_INVALID_ARG_TYPE(name,"boolean",value)}function getOwnPropertyValueOrDefault(options,key,defaultValue){return options==null||!ObjectPrototypeHasOwnProperty(options,key)?defaultValue:options[key]}const validateObject=hideStackFrames((value,name,options=null)=>{const allowArray=getOwnPropertyValueOrDefault(options,"allowArray",false);const allowFunction=getOwnPropertyValueOrDefault(options,"allowFunction",false);const nullable=getOwnPropertyValueOrDefault(options,"nullable",false);if(!nullable&&value===null||!allowArray&&ArrayIsArray(value)||typeof value!=="object"&&(!allowFunction||typeof value!=="function")){throw new ERR_INVALID_ARG_TYPE(name,"Object",value)}});const validateDictionary=hideStackFrames((value,name)=>{if(value!=null&&typeof value!=="object"&&typeof value!=="function"){throw new ERR_INVALID_ARG_TYPE(name,"a dictionary",value)}});const validateArray=hideStackFrames((value,name,minLength=0)=>{if(!ArrayIsArray(value)){throw new ERR_INVALID_ARG_TYPE(name,"Array",value)}if(value.length<minLength){const reason=`must be longer than ${minLength}`;throw new ERR_INVALID_ARG_VALUE(name,value,reason)}});function validateStringArray(value,name){validateArray(value,name);for(let i=0;i<value.length;i++){validateString(value[i],`${name}[${i}]`)}}function validateBooleanArray(value,name){validateArray(value,name);for(let i=0;i<value.length;i++){validateBoolean(value[i],`${name}[${i}]`)}}function validateAbortSignalArray(value,name){validateArray(value,name);for(let i=0;i<value.length;i++){const signal=value[i];const indexedName=`${name}[${i}]`;if(signal==null){throw new ERR_INVALID_ARG_TYPE(indexedName,"AbortSignal",signal)}validateAbortSignal(signal,indexedName)}}function validateSignalName(signal,name="signal"){validateString(signal,name);if(signals[signal]===undefined){if(signals[StringPrototypeToUpperCase(signal)]!==undefined){throw new ERR_UNKNOWN_SIGNAL(signal+" (signals must use all capital letters)")}throw new ERR_UNKNOWN_SIGNAL(signal)}}const validateBuffer=hideStackFrames((buffer,name="buffer")=>{if(!isArrayBufferView(buffer)){throw new ERR_INVALID_ARG_TYPE(name,["Buffer","TypedArray","DataView"],buffer)}});function validateEncoding(data,encoding){const normalizedEncoding=normalizeEncoding(encoding);const length=data.length;if(normalizedEncoding==="hex"&&length%2!==0){throw new ERR_INVALID_ARG_VALUE("encoding",encoding,`is invalid for data of length ${length}`)}}function validatePort(port,name="Port",allowZero=true){if(typeof port!=="number"&&typeof port!=="string"||typeof port==="string"&&StringPrototypeTrim(port).length===0||+port!==+port>>>0||port>65535||port===0&&!allowZero){throw new ERR_SOCKET_BAD_PORT(name,port,allowZero)}return port|0}const validateAbortSignal=hideStackFrames((signal,name)=>{if(signal!==undefined&&(signal===null||typeof signal!=="object"||!("aborted"in signal))){throw new ERR_INVALID_ARG_TYPE(name,"AbortSignal",signal)}});const validateFunction=hideStackFrames((value,name)=>{if(typeof value!=="function")throw new ERR_INVALID_ARG_TYPE(name,"Function",value)});const validatePlainFunction=hideStackFrames((value,name)=>{if(typeof value!=="function"||isAsyncFunction(value))throw new ERR_INVALID_ARG_TYPE(name,"Function",value)});const validateUndefined=hideStackFrames((value,name)=>{if(value!==undefined)throw new ERR_INVALID_ARG_TYPE(name,"undefined",value)});function validateUnion(value,name,union){if(!ArrayPrototypeIncludes(union,value)){throw new ERR_INVALID_ARG_TYPE(name,`('${ArrayPrototypeJoin(union,"|")}')`,value)}}const linkValueRegExp=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function validateLinkHeaderFormat(value,name){if(typeof value==="undefined"||!RegExpPrototypeExec(linkValueRegExp,value)){throw new ERR_INVALID_ARG_VALUE(name,value,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}}function validateLinkHeaderValue(hints){if(typeof hints==="string"){validateLinkHeaderFormat(hints,"hints");return hints}else if(ArrayIsArray(hints)){const hintsLength=hints.length;let result="";if(hintsLength===0){return result}for(let i=0;i<hintsLength;i++){const link=hints[i];validateLinkHeaderFormat(link,"hints");result+=link;if(i!==hintsLength-1){result+=", "}}return result}throw new ERR_INVALID_ARG_VALUE("hints",hints,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}module.exports={isInt32:isInt32,isUint32:isUint32,parseFileMode:parseFileMode,validateArray:validateArray,validateStringArray:validateStringArray,validateBooleanArray:validateBooleanArray,validateAbortSignalArray:validateAbortSignalArray,validateBoolean:validateBoolean,validateBuffer:validateBuffer,validateDictionary:validateDictionary,validateEncoding:validateEncoding,validateFunction:validateFunction,validateInt32:validateInt32,validateInteger:validateInteger,validateNumber:validateNumber,validateObject:validateObject,validateOneOf:validateOneOf,validatePlainFunction:validatePlainFunction,validatePort:validatePort,validateSignalName:validateSignalName,validateString:validateString,validateUint32:validateUint32,validateUndefined:validateUndefined,validateUnion:validateUnion,validateAbortSignal:validateAbortSignal,validateLinkHeaderValue:validateLinkHeaderValue}},{"../ours/errors":40,"../ours/primordials":41,"../ours/util":42}],39:[function(require,module,exports){"use strict";const CustomStream=require("../stream");const promises=require("../stream/promises");const originalDestroy=CustomStream.Readable.destroy;module.exports=CustomStream.Readable;module.exports._uint8ArrayToBuffer=CustomStream._uint8ArrayToBuffer;module.exports._isUint8Array=CustomStream._isUint8Array;module.exports.isDisturbed=CustomStream.isDisturbed;module.exports.isErrored=CustomStream.isErrored;module.exports.isReadable=CustomStream.isReadable;module.exports.Readable=CustomStream.Readable;module.exports.Writable=CustomStream.Writable;module.exports.Duplex=CustomStream.Duplex;module.exports.Transform=CustomStream.Transform;module.exports.PassThrough=CustomStream.PassThrough;module.exports.addAbortSignal=CustomStream.addAbortSignal;module.exports.finished=CustomStream.finished;module.exports.destroy=CustomStream.destroy;module.exports.destroy=originalDestroy;module.exports.pipeline=CustomStream.pipeline;module.exports.compose=CustomStream.compose;Object.defineProperty(CustomStream,"promises",{configurable:true,enumerable:true,get(){return promises}});module.exports.Stream=CustomStream.Stream;module.exports.default=module.exports},{"../stream":44,"../stream/promises":45}],40:[function(require,module,exports){"use strict";const{format,inspect}=require("./util/inspect");const{AggregateError:CustomAggregateError}=require("./primordials");const AggregateError=globalThis.AggregateError||CustomAggregateError;const kIsNodeError=Symbol("kIsNodeError");const kTypes=["string","function","number","object","Function","Object","boolean","bigint","symbol"];const classRegExp=/^([A-Z][a-z0-9]*)+$/;const nodeInternalPrefix="__node_internal_";const codes={};function assert(value,message){if(!value){throw new codes.ERR_INTERNAL_ASSERTION(message)}}function addNumericalSeparator(val){let res="";let i=val.length;const start=val[0]==="-"?1:0;for(;i>=start+4;i-=3){res=`_${val.slice(i-3,i)}${res}`}return`${val.slice(0,i)}${res}`}function getMessage(key,msg,args){if(typeof msg==="function"){assert(msg.length<=args.length,`Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`);return msg(...args)}const expectedLength=(msg.match(/%[dfijoOs]/g)||[]).length;assert(expectedLength===args.length,`Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`);if(args.length===0){return msg}return format(msg,...args)}function E(code,message,Base){if(!Base){Base=Error}class NodeError extends Base{constructor(...args){super(getMessage(code,message,args))}toString(){return`${this.name} [${code}]: ${this.message}`}}Object.defineProperties(NodeError.prototype,{name:{value:Base.name,writable:true,enumerable:false,configurable:true},toString:{value(){return`${this.name} [${code}]: ${this.message}`},writable:true,enumerable:false,configurable:true}});NodeError.prototype.code=code;NodeError.prototype[kIsNodeError]=true;codes[code]=NodeError}function hideStackFrames(fn){const hidden=nodeInternalPrefix+fn.name;Object.defineProperty(fn,"name",{value:hidden});return fn}function aggregateTwoErrors(innerError,outerError){if(innerError&&outerError&&innerError!==outerError){if(Array.isArray(outerError.errors)){outerError.errors.push(innerError);return outerError}const err=new AggregateError([outerError,innerError],outerError.message);err.code=outerError.code;return err}return innerError||outerError}class AbortError extends Error{constructor(message="The operation was aborted",options=undefined){if(options!==undefined&&typeof options!=="object"){throw new codes.ERR_INVALID_ARG_TYPE("options","Object",options)}super(message,options);this.code="ABORT_ERR";this.name="AbortError"}}E("ERR_ASSERTION","%s",Error);E("ERR_INVALID_ARG_TYPE",(name,expected,actual)=>{assert(typeof name==="string","'name' must be a string");if(!Array.isArray(expected)){expected=[expected]}let msg="The ";if(name.endsWith(" argument")){msg+=`${name} `}else{msg+=`"${name}" ${name.includes(".")?"property":"argument"} `}msg+="must be ";const types=[];const instances=[];const other=[];for(const value of expected){assert(typeof value==="string","All expected entries have to be of type string");if(kTypes.includes(value)){types.push(value.toLowerCase())}else if(classRegExp.test(value)){instances.push(value)}else{assert(value!=="object",'The value "object" should be written as "Object"');other.push(value)}}if(instances.length>0){const pos=types.indexOf("object");if(pos!==-1){types.splice(types,pos,1);instances.push("Object")}}if(types.length>0){switch(types.length){case 1:msg+=`of type ${types[0]}`;break;case 2:msg+=`one of type ${types[0]} or ${types[1]}`;break;default:{const last=types.pop();msg+=`one of type ${types.join(", ")}, or ${last}`}}if(instances.length>0||other.length>0){msg+=" or "}}if(instances.length>0){switch(instances.length){case 1:msg+=`an instance of ${instances[0]}`;break;case 2:msg+=`an instance of ${instances[0]} or ${instances[1]}`;break;default:{const last=instances.pop();msg+=`an instance of ${instances.join(", ")}, or ${last}`}}if(other.length>0){msg+=" or "}}switch(other.length){case 0:break;case 1:if(other[0].toLowerCase()!==other[0]){msg+="an "}msg+=`${other[0]}`;break;case 2:msg+=`one of ${other[0]} or ${other[1]}`;break;default:{const last=other.pop();msg+=`one of ${other.join(", ")}, or ${last}`}}if(actual==null){msg+=`. Received ${actual}`}else if(typeof actual==="function"&&actual.name){msg+=`. Received function ${actual.name}`}else if(typeof actual==="object"){var _actual$constructor;if((_actual$constructor=actual.constructor)!==null&&_actual$constructor!==undefined&&_actual$constructor.name){msg+=`. Received an instance of ${actual.constructor.name}`}else{const inspected=inspect(actual,{depth:-1});msg+=`. Received ${inspected}`}}else{let inspected=inspect(actual,{colors:false});if(inspected.length>25){inspected=`${inspected.slice(0,25)}...`}msg+=`. Received type ${typeof actual} (${inspected})`}return msg},TypeError);E("ERR_INVALID_ARG_VALUE",(name,value,reason="is invalid")=>{let inspected=inspect(value);if(inspected.length>128){inspected=inspected.slice(0,128)+"..."}const type=name.includes(".")?"property":"argument";return`The ${type} '${name}' ${reason}. Received ${inspected}`},TypeError);E("ERR_INVALID_RETURN_VALUE",(input,name,value)=>{var _value$constructor;const type=value!==null&&value!==undefined&&(_value$constructor=value.constructor)!==null&&_value$constructor!==undefined&&_value$constructor.name?`instance of ${value.constructor.name}`:`type ${typeof value}`;return`Expected ${input} to be returned from the "${name}"`+` function but got ${type}.`},TypeError);E("ERR_MISSING_ARGS",(...args)=>{assert(args.length>0,"At least one arg needs to be specified");let msg;const len=args.length;args=(Array.isArray(args)?args:[args]).map(a=>`"${a}"`).join(" or ");switch(len){case 1:msg+=`The ${args[0]} argument`;break;case 2:msg+=`The ${args[0]} and ${args[1]} arguments`;break;default:{const last=args.pop();msg+=`The ${args.join(", ")}, and ${last} arguments`}break}return`${msg} must be specified`},TypeError);E("ERR_OUT_OF_RANGE",(str,range,input)=>{assert(range,'Missing "range" argument');let received;if(Number.isInteger(input)&&Math.abs(input)>2**32){received=addNumericalSeparator(String(input))}else if(typeof input==="bigint"){received=String(input);const limit=BigInt(2)**BigInt(32);if(input>limit||input<-limit){received=addNumericalSeparator(received)}received+="n"}else{received=inspect(input)}return`The value of "${str}" is out of range. It must be ${range}. Received ${received}`},RangeError);E("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);E("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);E("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);E("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);E("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);E("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);E("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);E("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);E("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);E("ERR_STREAM_WRITE_AFTER_END","write after end",Error);E("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);module.exports={AbortError:AbortError,aggregateTwoErrors:hideStackFrames(aggregateTwoErrors),hideStackFrames:hideStackFrames,codes:codes}},{"./primordials":41,"./util/inspect":43}],41:[function(require,module,exports){"use strict";class AggregateError extends Error{constructor(errors){if(!Array.isArray(errors)){throw new TypeError(`Expected input to be an Array, got ${typeof errors}`)}let message="";for(let i=0;i<errors.length;i++){message+=` ${errors[i].stack}\n`}super(message);this.name="AggregateError";this.errors=errors}}module.exports={AggregateError:AggregateError,ArrayIsArray(self){return Array.isArray(self)},ArrayPrototypeIncludes(self,el){return self.includes(el)},ArrayPrototypeIndexOf(self,el){return self.indexOf(el)},ArrayPrototypeJoin(self,sep){return self.join(sep)},ArrayPrototypeMap(self,fn){return self.map(fn)},ArrayPrototypePop(self,el){return self.pop(el)},ArrayPrototypePush(self,el){return self.push(el)},ArrayPrototypeSlice(self,start,end){return self.slice(start,end)},Error:Error,FunctionPrototypeCall(fn,thisArgs,...args){return fn.call(thisArgs,...args)},FunctionPrototypeSymbolHasInstance(self,instance){return Function.prototype[Symbol.hasInstance].call(self,instance)},MathFloor:Math.floor,Number:Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(self,props){return Object.defineProperties(self,props)},ObjectDefineProperty(self,name,prop){return Object.defineProperty(self,name,prop)},ObjectGetOwnPropertyDescriptor(self,name){return Object.getOwnPropertyDescriptor(self,name)},ObjectKeys(obj){return Object.keys(obj)},ObjectSetPrototypeOf(target,proto){return Object.setPrototypeOf(target,proto)},Promise:Promise,PromisePrototypeCatch(self,fn){return self.catch(fn)},PromisePrototypeThen(self,thenFn,catchFn){return self.then(thenFn,catchFn)},PromiseReject(err){return Promise.reject(err)},PromiseResolve(val){return Promise.resolve(val)},ReflectApply:Reflect.apply,RegExpPrototypeTest(self,value){return self.test(value)},SafeSet:Set,String:String,StringPrototypeSlice(self,start,end){return self.slice(start,end)},StringPrototypeToLowerCase(self){return self.toLowerCase()},StringPrototypeToUpperCase(self){return self.toUpperCase()},StringPrototypeTrim(self){return self.trim()},Symbol:Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(self,buf,len){return self.set(buf,len)},Boolean:Boolean,Uint8Array:Uint8Array}},{}],42:[function(require,module,exports){"use strict";const bufferModule=require("buffer");const{format,inspect}=require("./util/inspect");const{codes:{ERR_INVALID_ARG_TYPE}}=require("./errors");const{kResistStopPropagation,AggregateError,SymbolDispose}=require("./primordials");const AbortSignal=globalThis.AbortSignal||require("abort-controller").AbortSignal;const AbortController=globalThis.AbortController||require("abort-controller").AbortController;const AsyncFunction=Object.getPrototypeOf(async function(){}).constructor;const Blob=globalThis.Blob||bufferModule.Blob;const isBlob=typeof Blob!=="undefined"?function isBlob(b){return b instanceof Blob}:function isBlob(b){return false};const validateAbortSignal=(signal,name)=>{if(signal!==undefined&&(signal===null||typeof signal!=="object"||!("aborted"in signal))){throw new ERR_INVALID_ARG_TYPE(name,"AbortSignal",signal)}};const validateFunction=(value,name)=>{if(typeof value!=="function"){throw new ERR_INVALID_ARG_TYPE(name,"Function",value)}};module.exports={AggregateError:AggregateError,kEmptyObject:Object.freeze({}),once(callback){let called=false;return function(...args){if(called){return}called=true;callback.apply(this,args)}},createDeferredPromise:function(){let resolve;let reject;const promise=new Promise((res,rej)=>{resolve=res;reject=rej});return{promise:promise,resolve:resolve,reject:reject}},promisify(fn){return new Promise((resolve,reject)=>{fn((err,...args)=>{if(err){return reject(err)}return resolve(...args)})})},debuglog(){return function(){}},format:format,inspect:inspect,types:{isAsyncFunction(fn){return fn instanceof AsyncFunction},isArrayBufferView(arr){return ArrayBuffer.isView(arr)}},isBlob:isBlob,deprecate(fn,message){return fn},addAbortListener:require("events").addAbortListener||function addAbortListener(signal,listener){if(signal===undefined){throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",signal)}validateAbortSignal(signal,"signal");validateFunction(listener,"listener");let removeEventListener;if(signal.aborted){queueMicrotask(()=>listener())}else{signal.addEventListener("abort",listener,{__proto__:null,once:true,[kResistStopPropagation]:true});removeEventListener=()=>{signal.removeEventListener("abort",listener)}}return{__proto__:null,[SymbolDispose](){var _removeEventListener;(_removeEventListener=removeEventListener)===null||_removeEventListener===undefined?undefined:_removeEventListener()}}},AbortSignalAny:AbortSignal.any||function AbortSignalAny(signals){if(signals.length===1){return signals[0]}const ac=new AbortController;const abort=()=>ac.abort();signals.forEach(signal=>{validateAbortSignal(signal,"signals");signal.addEventListener("abort",abort,{once:true})});ac.signal.addEventListener("abort",()=>{signals.forEach(signal=>signal.removeEventListener("abort",abort))},{once:true});return ac.signal}};module.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")},{"./errors":40,"./primordials":41,"./util/inspect":43,"abort-controller":15,buffer:17,events:18}],43:[function(require,module,exports){"use strict";module.exports={format(format,...args){return format.replace(/%([sdifj])/g,function(...[_unused,type]){const replacement=args.shift();if(type==="f"){return replacement.toFixed(6)}else if(type==="j"){return JSON.stringify(replacement)}else if(type==="s"&&typeof replacement==="object"){const ctor=replacement.constructor!==Object?replacement.constructor.name:"";return`${ctor} {}`.trim()}else{return replacement.toString()}})},inspect(value){switch(typeof value){case"string":if(value.includes("'")){if(!value.includes('"')){return`"${value}"`}else if(!value.includes("`")&&!value.includes("${")){return`\`${value}\``}}return`'${value}'`;case"number":if(isNaN(value)){return"NaN"}else if(Object.is(value,-0)){return String(value)}return value;case"bigint":return`${String(value)}n`;case"boolean":case"undefined":return String(value);case"object":return"{}"}}}},{}],44:[function(require,module,exports){"use strict";const{Buffer}=require("buffer");const{ObjectDefineProperty,ObjectKeys,ReflectApply}=require("./ours/primordials");const{promisify:{custom:customPromisify}}=require("./ours/util");const{streamReturningOperators,promiseReturningOperators}=require("./internal/streams/operators");const{codes:{ERR_ILLEGAL_CONSTRUCTOR}}=require("./ours/errors");const compose=require("./internal/streams/compose");const{setDefaultHighWaterMark,getDefaultHighWaterMark}=require("./internal/streams/state");const{pipeline}=require("./internal/streams/pipeline");const{destroyer}=require("./internal/streams/destroy");const eos=require("./internal/streams/end-of-stream");const internalBuffer={};const promises=require("./stream/promises");const utils=require("./internal/streams/utils");const Stream=module.exports=require("./internal/streams/legacy").Stream;Stream.isDestroyed=utils.isDestroyed;Stream.isDisturbed=utils.isDisturbed;Stream.isErrored=utils.isErrored;Stream.isReadable=utils.isReadable;Stream.isWritable=utils.isWritable;Stream.Readable=require("./internal/streams/readable");for(const key of ObjectKeys(streamReturningOperators)){const op=streamReturningOperators[key];function fn(...args){if(new.target){throw ERR_ILLEGAL_CONSTRUCTOR()}return Stream.Readable.from(ReflectApply(op,this,args))}ObjectDefineProperty(fn,"name",{__proto__:null,value:op.name});ObjectDefineProperty(fn,"length",{__proto__:null,value:op.length});ObjectDefineProperty(Stream.Readable.prototype,key,{__proto__:null,value:fn,enumerable:false,configurable:true,writable:true})}for(const key of ObjectKeys(promiseReturningOperators)){const op=promiseReturningOperators[key];function fn(...args){if(new.target){throw ERR_ILLEGAL_CONSTRUCTOR()}return ReflectApply(op,this,args)}ObjectDefineProperty(fn,"name",{__proto__:null,value:op.name});ObjectDefineProperty(fn,"length",{__proto__:null,value:op.length});ObjectDefineProperty(Stream.Readable.prototype,key,{__proto__:null,value:fn,enumerable:false,configurable:true,writable:true})}Stream.Writable=require("./internal/streams/writable");Stream.Duplex=require("./internal/streams/duplex");Stream.Transform=require("./internal/streams/transform");Stream.PassThrough=require("./internal/streams/passthrough");Stream.pipeline=pipeline;const{addAbortSignal}=require("./internal/streams/add-abort-signal");Stream.addAbortSignal=addAbortSignal;Stream.finished=eos;Stream.destroy=destroyer;Stream.compose=compose;Stream.setDefaultHighWaterMark=setDefaultHighWaterMark;Stream.getDefaultHighWaterMark=getDefaultHighWaterMark;ObjectDefineProperty(Stream,"promises",{__proto__:null,configurable:true,enumerable:true,get(){return promises}});ObjectDefineProperty(pipeline,customPromisify,{__proto__:null,enumerable:true,get(){return promises.pipeline}});ObjectDefineProperty(eos,customPromisify,{__proto__:null,enumerable:true,get(){return promises.finished}});Stream.Stream=Stream;Stream._isUint8Array=function isUint8Array(value){return value instanceof Uint8Array};Stream._uint8ArrayToBuffer=function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk.buffer,chunk.byteOffset,chunk.byteLength)}},{"./internal/streams/add-abort-signal":21,"./internal/streams/compose":23,"./internal/streams/destroy":24,"./internal/streams/duplex":25,"./internal/streams/end-of-stream":27,"./internal/streams/legacy":29,"./internal/streams/operators":30,"./internal/streams/passthrough":31,"./internal/streams/pipeline":32,"./internal/streams/readable":33,"./internal/streams/state":34,"./internal/streams/transform":35,"./internal/streams/utils":36,"./internal/streams/writable":37,"./ours/errors":40,"./ours/primordials":41,"./ours/util":42,"./stream/promises":45,buffer:17}],45:[function(require,module,exports){"use strict";const{ArrayPrototypePop,Promise}=require("../ours/primordials");const{isIterable,isNodeStream,isWebStream}=require("../internal/streams/utils");const{pipelineImpl:pl}=require("../internal/streams/pipeline");const{finished}=require("../internal/streams/end-of-stream");require("../../lib/stream.js");function pipeline(...streams){return new Promise((resolve,reject)=>{let signal;let end;const lastArg=streams[streams.length-1];if(lastArg&&typeof lastArg==="object"&&!isNodeStream(lastArg)&&!isIterable(lastArg)&&!isWebStream(lastArg)){const options=ArrayPrototypePop(streams);signal=options.signal;end=options.end}pl(streams,(err,value)=>{if(err){reject(err)}else{resolve(value)}},{signal:signal,end:end})})}module.exports={finished:finished,pipeline:pipeline}},{"../../lib/stream.js":44,"../internal/streams/end-of-stream":27,"../internal/streams/pipeline":32,"../internal/streams/utils":36,"../ours/primordials":41}],46:[function(require,module,exports){var buffer=require("buffer");var Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src){dst[key]=src[key]}}if(Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow){module.exports=buffer}else{copyProps(buffer,exports);exports.Buffer=SafeBuffer}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}SafeBuffer.prototype=Object.create(Buffer.prototype);copyProps(Buffer,SafeBuffer);SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg==="number"){throw new TypeError("Argument must not be a number")}return Buffer(arg,encodingOrOffset,length)};SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}var buf=Buffer(size);if(fill!==undefined){if(typeof encoding==="string"){buf.fill(fill,encoding)}else{buf.fill(fill)}}else{buf.fill(0)}return buf};SafeBuffer.allocUnsafe=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return Buffer(size)};SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return buffer.SlowBuffer(size)}},{buffer:17}],47:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer;var isEncoding=Buffer.isEncoding||function(encoding){encoding=""+encoding;switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function _normalizeEncoding(enc){if(!enc)return"utf8";var retried;while(true){switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase();retried=true}}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if(typeof nenc!=="string"&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}exports.StringDecoder=StringDecoder;function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;nb=4;break;case"utf8":this.fillLast=utf8FillLast;nb=4;break;case"base64":this.text=base64Text;this.end=base64End;nb=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=Buffer.allocUnsafe(nb)}StringDecoder.prototype.write=function(buf){if(buf.length===0)return"";var r;var i;if(this.lastNeed){r=this.fillLast(buf);if(r===undefined)return"";i=this.lastNeed;this.lastNeed=0}else{i=0}if(i<buf.length)return r?r+this.text(buf,i):this.text(buf,i);return r||""};StringDecoder.prototype.end=utf8End;StringDecoder.prototype.text=utf8Text;StringDecoder.prototype.fillLast=function(buf){if(this.lastNeed<=buf.length){buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,buf.length);this.lastNeed-=buf.length};function utf8CheckByte(byte){if(byte<=127)return 0;else if(byte>>5===6)return 2;else if(byte>>4===14)return 3;else if(byte>>3===30)return 4;return byte>>6===2?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j<i)return 0;var nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0)self.lastNeed=nb-1;return nb}if(--j<i||nb===-2)return 0;nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0)self.lastNeed=nb-2;return nb}if(--j<i||nb===-2)return 0;nb=utf8CheckByte(buf[j]);if(nb>=0){if(nb>0){if(nb===2)nb=0;else self.lastNeed=nb-3}return nb}return 0}function utf8CheckExtraBytes(self,buf,p){if((buf[0]&192)!==128){self.lastNeed=0;return"<22>"}if(self.lastNeed>1&&buf.length>1){if((buf[1]&192)!==128){self.lastNeed=1;return"<22>"}if(self.lastNeed>2&&buf.length>2){if((buf[2]&192)!==128){self.lastNeed=2;return"<22>"}}}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,buf,p);if(r!==undefined)return r;if(this.lastNeed<=buf.length){buf.copy(this.lastChar,p,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}buf.copy(this.lastChar,p,0,buf.length);this.lastNeed-=buf.length}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);buf.copy(this.lastChar,0,end);return buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed)return r+"<22>";return r}function utf16Text(buf,i){if((buf.length-i)%2===0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=buf[buf.length-2];this.lastChar[1]=buf[buf.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=buf[buf.length-1];return buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;if(n===0)return buf.toString("base64",i);this.lastNeed=3-n;this.lastTotal=3;if(n===1){this.lastChar[0]=buf[buf.length-1]}else{this.lastChar[0]=buf[buf.length-2];this.lastChar[1]=buf[buf.length-1]}return buf.toString("base64",i,buf.length-n)}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed)return r+this.lastChar.toString("base64",0,3-this.lastNeed);return r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}},{"safe-buffer":46}]},{},[14])(14)});
|