├── .github └── FUNDING.yml ├── .gitignore ├── .travis.yml ├── azure-search.js ├── azure-search.min.js ├── index.js ├── package.json ├── readme.md └── test.js /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: richorama 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .idea/ 3 | package-lock.json -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "node" 4 | - "lts/*" -------------------------------------------------------------------------------- /azure-search.js: -------------------------------------------------------------------------------- 1 | // entry point for the browser 2 | global.AzureSearch = require('./index') 3 | -------------------------------------------------------------------------------- /azure-search.min.js: -------------------------------------------------------------------------------- 1 | (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;i206;if(!(overrides&&overrides.Accept==="text/plain")){try{result=result?JSON.parse(result):{}}catch(err){return cb("failed to parse JSON:\n"+err+"\n "+result,null,res)}if(result.error){errorResponse=true;result=result.error}if(errorResponse){result.code=result.code||res.statusCode}}if(errorResponse){cb(result,null,res)}else{cb(null,result,res)}});res.on("error",function(err){if(cb){cb(err,null,res);cb=undefined}})});try{if(payload){req.write(payload)}req.end();req.on("error",function(err){if(cb){cb(err,null,req);cb=undefined}})}catch(err){if(cb){cb(err);cb=undefined}}};return{listIndexes:function(cb){get(["indexes"],null,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data.value,data)})},createIndex:function(schema,cb){if(!schema)throw new Error("schema is not defined");post(["indexes"],schema,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},getIndex:function(indexName,cb){if(!indexName)throw new Error("indexName is not defined");get(["indexes",indexName],null,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},testAnalyzer:function(indexName,data,cb){if(!indexName)throw new Error("indexName is not defined");post(["indexes",indexName,"analyze"],data,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data.tokens,data)})},getIndexStats:function(indexName,cb){if(!indexName)throw new Error("indexName is not defined");get(["indexes",indexName,"stats"],null,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},deleteIndex:function(indexName,cb){if(!indexName)throw new Error("indexName is not defined");del(["indexes",indexName],function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},listIndexers:function(cb){get(["indexers"],null,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data.value,data)})},createIndexer:function(schema,cb){if(!schema)throw new Error("schema is not defined");post(["indexers"],schema,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},updateIndexer:function(indexerName,schema,cb){if(!indexerName)throw new Error("indexName is not defined");if(!schema)throw new Error("schema is not defined");put(["indexers",indexerName],schema,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},getIndexer:function(indexerName,cb){if(!indexerName)throw new Error("indexName is not defined");get(["indexers",indexerName],null,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},getIndexerStatus:function(indexerName,cb){if(!indexerName)throw new Error("indexerName is not defined");get(["indexers",indexerName,"status"],null,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},deleteIndexer:function(indexerName,cb){if(!indexerName)throw new Error("indexerName is not defined");del(["indexers",indexerName],function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},runIndexer:function(indexerName,cb){if(!indexerName)throw new Error("indexerName is not defined");post(["indexers",indexerName,"run"],null,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},resetIndexer:function(indexerName,cb){if(!indexerName)throw new Error("indexerName is not defined");post(["indexers",indexerName,"reset"],null,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},getDataSource:function(dataSourceName,cb){if(!dataSourceName)throw new Error("dataSourceName is not defined");get(["datasources",dataSourceName],null,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},createDataSource:function(options,cb){if(!options)throw new Error("options is not defined");post(["datasources"],options,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},updateDataSource:function(options,cb){if(!options)throw new Error("options is not defined");if(!options.name)throw new Error("options.name is not defined");put(["datasources",options.name],options,function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},deleteDataSource:function(dataSourceName,cb){del(["datasources",dataSourceName],function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data,data)})},addDocuments:function(indexName,documents,cb){if(!indexName)throw new Error("indexName is not defined");if(!documents)throw new Error("documents is not defined");post(["indexes",indexName,"docs","index"],{value:documents},function(err,data){if(err)return cb(err,null,data);if(data&&data.error)return cb(data.error,null,data);cb(null,data.value,data)})},updateDocuments:function(indexName,documents,cb){if(!indexName)throw new Error("indexName is not defined");if(!documents)throw new Error("documents is not defined");for(var i=0;i0){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;for(var i=0;i>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;ilen2?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("")}},{}],4:[function(require,module,exports){},{}],5:[function(require,module,exports){(function(global){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("isarray");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();exports.kMaxLength=kMaxLength();function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42&&typeof arr.subarray==="function"&&arr.subarray(1,1).byteLength===0}catch(e){return false}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().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)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return 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;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}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;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(isNaN(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(Buffer.TYPED_ARRAY_SUPPORT&&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;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;iremaining)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 2 | ;while(i239?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(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)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(++i0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){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){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=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){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){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){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){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){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){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){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||valuebuf.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=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);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}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);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}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);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}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>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(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);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);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}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);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}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);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}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;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}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){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}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){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}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(!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=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&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>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=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isnan(val){return val!==val}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":3,ieee754:10,isarray:13}],6:[function(require,module,exports){module.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},{}],7:[function(require,module,exports){(function(Buffer){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=Buffer.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":12}],8:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{var err=new Error('Uncaught, unspecified "error" event. ('+er+")");err.context=er;throw err}}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],9:[function(require,module,exports){var http=require("http");var https=module.exports;for(var key in http){if(http.hasOwnProperty(key))https[key]=http[key]}https.request=function(params,cb){if(!params)params={};params.scheme="https";params.protocol="https:";return http.request.call(this,params,cb)}},{http:31}],10:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>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<>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<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],11:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],12:[function(require,module,exports){module.exports=function(obj){return obj!=null&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)};function isBuffer(obj){return!!obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return typeof obj.readFloatLE==="function"&&typeof obj.slice==="function"&&isBuffer(obj.slice(0,0))}},{}],13:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],14:[function(require,module,exports){(function(process){"use strict";if(!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){module.exports={nextTick:nextTick}}else{module.exports=process}function nextTick(fn,arg1,arg2,arg3){if(typeof fn!=="function"){throw new TypeError('"callback" argument must be a function')}var len=arguments.length;var args,i;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function afterTickOne(){fn.call(null,arg1)});case 3:return process.nextTick(function afterTickTwo(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function afterTickThree(){fn.call(null,arg1,arg2,arg3)});default:args=new Array(len-1);i=0;while(i1){for(var i=1;i= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,key;function error(type){throw new RangeError(errors[type])}function map(array,fn){var length=array.length;var result=[];while(length--){result[length]=fn(array[length])}return result}function mapDomain(string,fn){var parts=string.split("@");var result="";if(parts.length>1){result=parts[0]+"@";string=parts[1]}string=string.replace(regexSeparators,".");var labels=string.split(".");var encoded=map(labels,fn).join(".");return result+encoded}function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter=55296&&value<=56319&&counter65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value);return output}).join("")}function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22}if(codePoint-65<26){return codePoint-65}if(codePoint-97<26){return codePoint-97}return base}function digitToBasic(digit,flag){return digit+22+75*(digit<26)-((flag!=0)<<5)}function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin)}return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}function decode(input){var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,baseMinusT;basic=input.lastIndexOf(delimiter);if(basic<0){basic=0}for(j=0;j=128){error("not-basic")}output.push(input.charCodeAt(j))}for(index=basic>0?basic+1:0;index=inputLength){error("invalid-input")}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error("overflow")}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digitfloor(maxInt/baseMinusT)){error("overflow")}w*=baseMinusT}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);if(floor(i/out)>maxInt-n){error("overflow")}n+=floor(i/out);i%=out;output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],inputLength,handledCPCountPlusOne,baseMinusT,qMinusT;input=ucs2decode(input);inputLength=input.length;n=initialN;delta=0;bias=initialBias;for(j=0;j=n&¤tValuefloor((maxInt-delta)/handledCPCountPlusOne)){error("overflow")}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;jmaxInt){error("overflow")}if(currentValue==n){for(q=delta,k=base;;k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q0&&len>maxKeys){len=maxKeys}for(var i=0;i=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1)}else{kstr=x;vstr=""}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v}else if(isArray(obj[k])){obj[k].push(v)}else{obj[k]=[obj[k],v]}}return obj};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"}},{}],18:[function(require,module,exports){"use strict";var stringifyPrimitive=function(v){switch(typeof v){case"string":return v;case"boolean":return v?"true":"false";case"number":return isFinite(v)?v:"";default:return""}};module.exports=function(obj,sep,eq,name){sep=sep||"&";eq=eq||"=";if(obj===null){obj=undefined}if(typeof obj==="object"){return map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v))}).join(sep)}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]))}}).join(sep)}if(!name)return"";return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj))};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==="[object Array]"};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i0){if(typeof chunk!=="string"&&!state.objectMode&&Object.getPrototypeOf(chunk)!==Buffer.prototype){chunk=_uint8ArrayToBuffer(chunk)}if(addToFront){if(state.endEmitted)stream.emit("error",new Error("stream.unshift() after end event"));else addChunk(stream,state,chunk,true)}else if(state.ended){stream.emit("error",new Error("stream.push() after EOF"))}else{state.reading=false;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.reading=false}}return needMoreData(state)}function addChunk(stream,state,chunk,addToFront){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;if(!_isUint8Array(chunk)&&typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}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.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||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}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)pna.nextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;pna.nextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)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(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;var unpipeInfo={hasUnpiped:false};if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this,unpipeInfo);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var i=0;i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=Buffer.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;pna.nextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function indexOf(xs,x){for(var i=0,l=xs.length;i-1?setImmediate:pna.nextTick;var Duplex;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream=require("./internal/streams/stream");var Buffer=require("safe-buffer").Buffer;var OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var destroyImpl=require("./internal/streams/destroy");util.inherits(Writable,Stream);function nop(){}function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};var isDuplex=stream instanceof Duplex;this.objectMode=!!options.objectMode;if(isDuplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var writableHwm=options.writableHighWaterMark;var defaultHwm=this.objectMode?16:16*1024;if(hwm||hwm===0)this.highWaterMark=hwm;else if(isDuplex&&(writableHwm||writableHwm===0))this.highWaterMark=writableHwm;else this.highWaterMark=defaultHwm;this.highWaterMark=Math.floor(this.highWaterMark);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.","DEP0003")})}catch(_){}})();var realHasInstance;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){realHasInstance=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){if(realHasInstance.call(this,object))return true;if(this!==Writable)return false;return object&&object._writableState instanceof WritableState}})}else{realHasInstance=function(object){return object instanceof this}}function Writable(options){Duplex=Duplex||require("./_stream_duplex");if(!realHasInstance.call(Writable,this)&&!(this instanceof Duplex)){return new Writable(options)}this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write 4 | ;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}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);pna.nextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);pna.nextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=!state.objectMode&&_isUint8Array(chunk);if(isBuf&&!Buffer.isBuffer(chunk)){chunk=_uint8ArrayToBuffer(chunk)}if(typeof encoding==="function"){cb=encoding;encoding=null}if(isBuf)encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(isBuf||validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=Buffer.from(chunk,encoding)}return chunk}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);if(chunk!==newChunk){isBuf=true;encoding="buffer";chunk=newChunk}}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function unshift(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function shift(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function clear(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function join(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function concat(n){if(this.length===0)return Buffer.alloc(0);if(this.length===1)return this.head.data;var ret=Buffer.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){copyBuffer(p.data,ret,i);i+=p.data.length;p=p.next}return ret};return BufferList}();if(util&&util.inspect&&util.inspect.custom){module.exports.prototype[util.inspect.custom]=function(){var obj=util.inspect({length:this.length});return this.constructor.name+" "+obj}}},{"safe-buffer":30,util:4}],26:[function(require,module,exports){"use strict";var pna=require("process-nextick-args");function destroy(err,cb){var _this=this;var readableDestroyed=this._readableState&&this._readableState.destroyed;var writableDestroyed=this._writableState&&this._writableState.destroyed;if(readableDestroyed||writableDestroyed){if(cb){cb(err)}else if(err&&(!this._writableState||!this._writableState.errorEmitted)){pna.nextTick(emitErrorNT,this,err)}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(err||null,function(err){if(!cb&&err){pna.nextTick(emitErrorNT,_this,err);if(_this._writableState){_this._writableState.errorEmitted=true}}else if(cb){cb(err)}});return this}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(self,err){self.emit("error",err)}module.exports={destroy:destroy,undestroy:undestroy}},{"process-nextick-args":14}],27:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:8}],28:[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>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=0){if(nb>0)self.lastNeed=nb-1;return nb}if(--j=0){if(nb>0)self.lastNeed=nb-2;return nb}if(--j=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"�"}if(self.lastNeed>1&&buf.length>1){if((buf[1]&192)!==128){self.lastNeed=1;return"�"}if(self.lastNeed>2&&buf.length>2){if((buf[2]&192)!==128){self.lastNeed=2;return"�"}}}}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+"�";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":30}],29:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=exports;exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":20,"./lib/_stream_passthrough.js":21,"./lib/_stream_readable.js":22,"./lib/_stream_transform.js":23,"./lib/_stream_writable.js":24}],30:[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)}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:5}],31:[function(require,module,exports){(function(global){var ClientRequest=require("./lib/request");var response=require("./lib/response");var extend=require("xtend");var statusCodes=require("builtin-status-codes");var url=require("url");var http=exports;http.request=function(opts,cb){if(typeof opts==="string")opts=url.parse(opts);else opts=extend(opts);var defaultProtocol=global.location.protocol.search(/^https?:$/)===-1?"http:":"";var protocol=opts.protocol||defaultProtocol;var host=opts.hostname||opts.host;var port=opts.port;var path=opts.path||"/";if(host&&host.indexOf(":")!==-1)host="["+host+"]";opts.url=(host?protocol+"//"+host:"")+(port?":"+port:"")+path;opts.method=(opts.method||"GET").toUpperCase();opts.headers=opts.headers||{};var req=new ClientRequest(opts);if(cb)req.on("response",cb);return req};http.get=function get(opts,cb){var req=http.request(opts,cb);req.end();return req};http.ClientRequest=ClientRequest;http.IncomingMessage=response.IncomingMessage;http.Agent=function(){};http.Agent.defaultMaxSockets=4;http.globalAgent=new http.Agent;http.STATUS_CODES=statusCodes;http.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./lib/request":33,"./lib/response":34,"builtin-status-codes":6,url:37,xtend:40}],32:[function(require,module,exports){(function(global){exports.fetch=isFunction(global.fetch)&&isFunction(global.ReadableStream);exports.writableStream=isFunction(global.WritableStream);exports.abortController=isFunction(global.AbortController);exports.blobConstructor=false;try{new Blob([new ArrayBuffer(1)]);exports.blobConstructor=true}catch(e){}var xhr;function getXHR(){if(xhr!==undefined)return xhr;if(global.XMLHttpRequest){xhr=new global.XMLHttpRequest;try{xhr.open("GET",global.XDomainRequest?"/":"https://example.com")}catch(e){xhr=null}}else{xhr=null}return xhr}function checkTypeSupport(type){var xhr=getXHR();if(!xhr)return false;try{xhr.responseType=type;return xhr.responseType===type}catch(e){}return false}var haveArrayBuffer=typeof global.ArrayBuffer!=="undefined";var haveSlice=haveArrayBuffer&&isFunction(global.ArrayBuffer.prototype.slice);exports.arraybuffer=exports.fetch||haveArrayBuffer&&checkTypeSupport("arraybuffer");exports.msstream=!exports.fetch&&haveSlice&&checkTypeSupport("ms-stream");exports.mozchunkedarraybuffer=!exports.fetch&&haveArrayBuffer&&checkTypeSupport("moz-chunked-arraybuffer");exports.overrideMimeType=exports.fetch||(getXHR()?isFunction(getXHR().overrideMimeType):false);exports.vbArray=isFunction(global.VBArray);function isFunction(value){return typeof value==="function"}xhr=null}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],33:[function(require,module,exports){(function(process,global,Buffer){var capability=require("./capability");var inherits=require("inherits");var response=require("./response");var stream=require("readable-stream");var toArrayBuffer=require("to-arraybuffer");var IncomingMessage=response.IncomingMessage;var rStates=response.readyStates;function decideMode(preferBinary,useFetch){if(capability.fetch&&useFetch){return"fetch"}else if(capability.mozchunkedarraybuffer){return"moz-chunked-arraybuffer"}else if(capability.msstream){return"ms-stream"}else if(capability.arraybuffer&&preferBinary){return"arraybuffer"}else if(capability.vbArray&&preferBinary){return"text:vbarray"}else{return"text"}}var ClientRequest=module.exports=function(opts){var self=this;stream.Writable.call(self);self._opts=opts;self._body=[];self._headers={};if(opts.auth)self.setHeader("Authorization","Basic "+new Buffer(opts.auth).toString("base64"));Object.keys(opts.headers).forEach(function(name){self.setHeader(name,opts.headers[name])});var preferBinary;var useFetch=true;if(opts.mode==="disable-fetch"||"requestTimeout"in opts&&!capability.abortController){useFetch=false;preferBinary=true}else if(opts.mode==="prefer-streaming"){preferBinary=false}else if(opts.mode==="allow-wrong-content-type"){preferBinary=!capability.overrideMimeType}else if(!opts.mode||opts.mode==="default"||opts.mode==="prefer-fast"){preferBinary=true}else{throw new Error("Invalid value for opts.mode")}self._mode=decideMode(preferBinary,useFetch);self._fetchTimer=null;self.on("finish",function(){self._onFinish()})};inherits(ClientRequest,stream.Writable);ClientRequest.prototype.setHeader=function(name,value){var self=this;var lowerName=name.toLowerCase();if(unsafeHeaders.indexOf(lowerName)!==-1)return;self._headers[lowerName]={name:name,value:value}};ClientRequest.prototype.getHeader=function(name){var header=this._headers[name.toLowerCase()];if(header)return header.value;return null};ClientRequest.prototype.removeHeader=function(name){var self=this;delete self._headers[name.toLowerCase()]};ClientRequest.prototype._onFinish=function(){var self=this;if(self._destroyed)return;var opts=self._opts;var headersObj=self._headers;var body=null;if(opts.method!=="GET"&&opts.method!=="HEAD"){if(capability.arraybuffer){body=toArrayBuffer(Buffer.concat(self._body))}else if(capability.blobConstructor){body=new global.Blob(self._body.map(function(buffer){return toArrayBuffer(buffer)}),{type:(headersObj["content-type"]||{}).value||""})}else{body=Buffer.concat(self._body).toString()}}var headersList=[];Object.keys(headersObj).forEach(function(keyName){var name=headersObj[keyName].name;var value=headersObj[keyName].value;if(Array.isArray(value)){value.forEach(function(v){headersList.push([name,v])})}else{headersList.push([name,value])}});if(self._mode==="fetch"){var signal=null;var fetchTimer=null;if(capability.abortController){var controller=new AbortController;signal=controller.signal;self._fetchAbortController=controller;if("requestTimeout"in opts&&opts.requestTimeout!==0){self._fetchTimer=global.setTimeout(function(){self.emit("requestTimeout");if(self._fetchAbortController)self._fetchAbortController.abort()},opts.requestTimeout)}}global.fetch(self._opts.url,{method:self._opts.method,headers:headersList,body:body||undefined,mode:"cors",credentials:opts.withCredentials?"include":"same-origin",signal:signal}).then(function(response){self._fetchResponse=response;self._connect()},function(reason){global.clearTimeout(self._fetchTimer);if(!self._destroyed)self.emit("error",reason)})}else{var xhr=self._xhr=new global.XMLHttpRequest;try{xhr.open(self._opts.method,self._opts.url,true)}catch(err){process.nextTick(function(){self.emit("error",err)});return}if("responseType"in xhr)xhr.responseType=self._mode.split(":")[0];if("withCredentials"in xhr)xhr.withCredentials=!!opts.withCredentials;if(self._mode==="text"&&"overrideMimeType"in xhr)xhr.overrideMimeType("text/plain; charset=x-user-defined");if("requestTimeout"in opts){xhr.timeout=opts.requestTimeout;xhr.ontimeout=function(){self.emit("requestTimeout")}}headersList.forEach(function(header){xhr.setRequestHeader(header[0],header[1])});self._response=null;xhr.onreadystatechange=function(){switch(xhr.readyState){case rStates.LOADING:case rStates.DONE:self._onXHRProgress();break}};if(self._mode==="moz-chunked-arraybuffer"){xhr.onprogress=function(){self._onXHRProgress()}}xhr.onerror=function(){if(self._destroyed)return;self.emit("error",new Error("XHR error"))};try{xhr.send(body)}catch(err){process.nextTick(function(){self.emit("error",err)});return}}};function statusValid(xhr){try{var status=xhr.status;return status!==null&&status!==0}catch(e){return false}}ClientRequest.prototype._onXHRProgress=function(){var self=this;if(!statusValid(self._xhr)||self._destroyed)return;if(!self._response)self._connect();self._response._onXHRProgress()};ClientRequest.prototype._connect=function(){var self=this;if(self._destroyed)return;self._response=new IncomingMessage(self._xhr,self._fetchResponse,self._mode,self._fetchTimer);self._response.on("error",function(err){self.emit("error",err)});self.emit("response",self._response)};ClientRequest.prototype._write=function(chunk,encoding,cb){var self=this;self._body.push(chunk);cb()};ClientRequest.prototype.abort=ClientRequest.prototype.destroy=function(){var self=this;self._destroyed=true;global.clearTimeout(self._fetchTimer);if(self._response)self._response._destroyed=true;if(self._xhr)self._xhr.abort();else if(self._fetchAbortController)self._fetchAbortController.abort()};ClientRequest.prototype.end=function(data,encoding,cb){var self=this;if(typeof data==="function"){cb=data;data=undefined}stream.Writable.prototype.end.call(self,data,encoding,cb)};ClientRequest.prototype.flushHeaders=function(){};ClientRequest.prototype.setTimeout=function(){};ClientRequest.prototype.setNoDelay=function(){};ClientRequest.prototype.setSocketKeepAlive=function(){};var unsafeHeaders=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{"./capability":32,"./response":34,_process:15,buffer:5,inherits:11,"readable-stream":29,"to-arraybuffer":36}],34:[function(require,module,exports){(function(process,global,Buffer){var capability=require("./capability");var inherits=require("inherits");var stream=require("readable-stream");var rStates=exports.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4};var IncomingMessage=exports.IncomingMessage=function(xhr,response,mode,fetchTimer){var self=this;stream.Readable.call(self);self._mode=mode;self.headers={};self.rawHeaders=[];self.trailers={};self.rawTrailers=[];self.on("end",function(){process.nextTick(function(){self.emit("close")})});if(mode==="fetch"){self._fetchResponse=response;self.url=response.url;self.statusCode=response.status;self.statusMessage=response.statusText;response.headers.forEach(function(header,key){self.headers[key.toLowerCase()]=header;self.rawHeaders.push(key,header)});if(capability.writableStream){var writable=new WritableStream({write:function(chunk){return new Promise(function(resolve,reject){if(self._destroyed){reject()}else if(self.push(new Buffer(chunk))){resolve()}else{self._resumeFetch=resolve}})},close:function(){global.clearTimeout(fetchTimer);if(!self._destroyed)self.push(null)},abort:function(err){if(!self._destroyed)self.emit("error",err)}});try{response.body.pipeTo(writable).catch(function(err){global.clearTimeout(fetchTimer);if(!self._destroyed)self.emit("error",err)});return}catch(e){}}var reader=response.body.getReader();function read(){reader.read().then(function(result){if(self._destroyed)return;if(result.done){global.clearTimeout(fetchTimer);self.push(null);return}self.push(new Buffer(result.value));read()}).catch(function(err){global.clearTimeout(fetchTimer);if(!self._destroyed)self.emit("error",err)})}read()}else{self._xhr=xhr;self._pos=0;self.url=xhr.responseURL;self.statusCode=xhr.status;self.statusMessage=xhr.statusText;var headers=xhr.getAllResponseHeaders().split(/\r?\n/);headers.forEach(function(header){var matches=header.match(/^([^:]+):\s*(.*)/);if(matches){var key=matches[1].toLowerCase();if(key==="set-cookie"){if(self.headers[key]===undefined){self.headers[key]=[]}self.headers[key].push(matches[2])}else if(self.headers[key]!==undefined){self.headers[key]+=", "+matches[2]}else{self.headers[key]=matches[2]}self.rawHeaders.push(matches[1],matches[2])}});self._charset="x-user-defined";if(!capability.overrideMimeType){var mimeType=self.rawHeaders["mime-type"];if(mimeType){var charsetMatch=mimeType.match(/;\s*charset=([^;])(;|$)/);if(charsetMatch){self._charset=charsetMatch[1].toLowerCase()}}if(!self._charset)self._charset="utf-8"}}};inherits(IncomingMessage,stream.Readable);IncomingMessage.prototype._read=function(){var self=this;var resolve=self._resumeFetch;if(resolve){self._resumeFetch=null;resolve()}};IncomingMessage.prototype._onXHRProgress=function(){var self=this;var xhr=self._xhr;var response=null;switch(self._mode){case"text:vbarray":if(xhr.readyState!==rStates.DONE)break;try{response=new global.VBArray(xhr.responseBody).toArray()}catch(e){}if(response!==null){self.push(new Buffer(response));break}case"text":try{response=xhr.responseText}catch(e){self._mode="text:vbarray";break}if(response.length>self._pos){var newData=response.substr(self._pos);if(self._charset==="x-user-defined"){var buffer=new Buffer(newData.length);for(var i=0;iself._pos){self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos))));self._pos=reader.result.byteLength}};reader.onload=function(){self.push(null)};reader.readAsArrayBuffer(response);break}if(self._xhr.readyState===rStates.DONE&&self._mode!=="ms-stream"){self.push(null)}}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{"./capability":32,_process:15,buffer:5,inherits:11,"readable-stream":29}],35:[function(require,module,exports){(function(setImmediate,clearImmediate){var nextTick=require("process/browser.js").nextTick;var apply=Function.prototype.apply;var slice=Array.prototype.slice;var immediateIds={};var nextImmediateId=0;exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)};exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)};exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()};function Timeout(id,clearFn){this._id=id;this._clearFn=clearFn}Timeout.prototype.unref=Timeout.prototype.ref=function(){};Timeout.prototype.close=function(){this._clearFn.call(window,this._id)};exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId);item._idleTimeout=msecs};exports.unenroll=function(item){ 5 | clearTimeout(item._idleTimeoutId);item._idleTimeout=-1};exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;if(msecs>=0){item._idleTimeoutId=setTimeout(function onTimeout(){if(item._onTimeout)item._onTimeout()},msecs)}};exports.setImmediate=typeof setImmediate==="function"?setImmediate:function(fn){var id=nextImmediateId++;var args=arguments.length<2?false:slice.call(arguments,1);immediateIds[id]=true;nextTick(function onNextTick(){if(immediateIds[id]){if(args){fn.apply(null,args)}else{fn.call(null)}exports.clearImmediate(id)}});return id};exports.clearImmediate=typeof clearImmediate==="function"?clearImmediate:function(id){delete immediateIds[id]}}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":15,timers:35}],36:[function(require,module,exports){var Buffer=require("buffer").Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(buf.byteOffset===0&&buf.byteLength===buf.buffer.byteLength){return buf.buffer}else if(typeof buf.buffer.slice==="function"){return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}}if(Buffer.isBuffer(buf)){var arrayCopy=new Uint8Array(buf.length);var len=buf.length;for(var i=0;i",'"',"`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:true,"javascript:":true},hostlessProtocol={javascript:true,"javascript:":true},slashedProtocol={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true},querystring=require("querystring");function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;u.parse(url,parseQueryString,slashesDenoteHost);return u}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url)){throw new TypeError("Parameter 'url' must be a string, not "+typeof url)}var queryIndex=url.indexOf("?"),splitter=queryIndex!==-1&&queryIndex127){newpart+="x"}else{newpart+=part[j]}}if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2])}if(notHost.length){rest="/"+notHost.join(".")+rest}this.hostname=validParts.join(".");break}}}}if(this.hostname.length>hostnameMaxLen){this.hostname=""}else{this.hostname=this.hostname.toLowerCase()}if(!ipv6Hostname){this.hostname=punycode.toASCII(this.hostname)}var p=this.port?":"+this.port:"";var h=this.hostname||"";this.host=h+p;this.href+=this.host;if(ipv6Hostname){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(rest[0]!=="/"){rest="/"+rest}}}if(!unsafeProtocol[lowerProto]){for(var i=0,l=autoEscape.length;i0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}result.search=relative.search;result.query=relative.query;if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.href=result.format();return result}if(!srcPath.length){result.pathname=null;if(result.search){result.path="/"+result.search}else{result.path=null}result.href=result.format();return result}var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&(last==="."||last==="..")||last==="";var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last==="."){srcPath.splice(i,1)}else if(last===".."){srcPath.splice(i,1);up++}else if(up){srcPath.splice(i,1);up--}}if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift("..")}}if(mustEndAbs&&srcPath[0]!==""&&(!srcPath[0]||srcPath[0].charAt(0)!=="/")){srcPath.unshift("")}if(hasTrailingSlash&&srcPath.join("/").substr(-1)!=="/"){srcPath.push("")}var isAbsolute=srcPath[0]===""||srcPath[0]&&srcPath[0].charAt(0)==="/";if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift()}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift("")}if(!srcPath.length){result.pathname=null;result.path=null}else{result.pathname=srcPath.join("/")}if(!util.isNull(result.pathname)||!util.isNull(result.search)){result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==":"){this.port=port.substr(1)}host=host.substr(0,host.length-port.length)}if(host)this.hostname=host}},{"./util":38,punycode:16,querystring:19}],38:[function(require,module,exports){"use strict";module.exports={isString:function(arg){return typeof arg==="string"},isObject:function(arg){return typeof arg==="object"&&arg!==null},isNull:function(arg){return arg===null},isNullOrUndefined:function(arg){return arg==null}}},{}],39:[function(require,module,exports){(function(global){module.exports=deprecate;function deprecate(fn,msg){if(config("noDeprecation")){return fn}var warned=false;function deprecated(){if(!warned){if(config("throwDeprecation")){throw new Error(msg)}else if(config("traceDeprecation")){console.trace(msg)}else{console.warn(msg)}warned=true}return fn.apply(this,arguments)}return deprecated}function config(name){try{if(!global.localStorage)return false}catch(_){return false}var val=global.localStorage[name];if(null==val)return false;return String(val).toLowerCase()==="true"}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],40:[function(require,module,exports){module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){var target={};for(var i=0;i 206) 69 | 70 | // Requires result parsing 71 | if (!(overrides && overrides.Accept === 'text/plain')) { 72 | try { 73 | result = result ? JSON.parse(result) : {} 74 | } catch (err) { 75 | return cb('failed to parse JSON:\n' + err + '\n ' + result, null, res) 76 | } 77 | 78 | // Azure Errors 79 | if (result.error) { 80 | errorResponse = true 81 | result = result.error 82 | } 83 | 84 | // Inject response status code 85 | // This is currently not populated by azure 86 | if (errorResponse) { 87 | result.code = result.code || res.statusCode 88 | } 89 | } 90 | 91 | if (errorResponse) { 92 | cb(result, null, res) 93 | } else { 94 | cb(null, result, res) 95 | } 96 | }) 97 | 98 | res.on('error', function (err) { 99 | if (cb) { 100 | cb(err, null, res) 101 | cb = undefined 102 | } 103 | }) 104 | }) 105 | try { 106 | if (payload) { 107 | req.write(payload) 108 | } 109 | req.end() 110 | req.on('error', function (err) { 111 | if (cb) { 112 | cb(err, null, req) 113 | cb = undefined 114 | } 115 | }) 116 | } catch (err) { 117 | if (cb) { 118 | cb(err) 119 | cb = undefined 120 | } 121 | } 122 | } 123 | 124 | return { 125 | listIndexes: function (cb) { 126 | get(['indexes'], null, function (err, data) { 127 | if (err) return cb(err, null, data) 128 | if (data && data.error) return cb(data.error, null, data) 129 | cb(null, data.value, data) 130 | }) 131 | }, 132 | createIndex: function (schema, cb) { 133 | if (!schema) throw new Error('schema is not defined') 134 | post(['indexes'], schema, function (err, data) { 135 | if (err) return cb(err, null, data) 136 | if (data && data.error) return cb(data.error, null, data) 137 | cb(null, data, data) 138 | }) 139 | }, 140 | getIndex: function (indexName, cb) { 141 | if (!indexName) throw new Error('indexName is not defined') 142 | get(['indexes', indexName], null, function (err, data) { 143 | if (err) return cb(err, null, data) 144 | if (data && data.error) return cb(data.error, null, data) 145 | cb(null, data, data) 146 | }) 147 | }, 148 | testAnalyzer: function (indexName, data, cb) { 149 | if (!indexName) throw new Error('indexName is not defined') 150 | post(['indexes', indexName, 'analyze'], data, function (err, data) { 151 | if (err) return cb(err, null, data) 152 | if (data && data.error) return cb(data.error, null, data) 153 | cb(null, data.tokens, data) 154 | }) 155 | }, 156 | getIndexStats: function (indexName, cb) { 157 | if (!indexName) throw new Error('indexName is not defined') 158 | get(['indexes', indexName, 'stats'], null, function (err, data) { 159 | if (err) return cb(err, null, data) 160 | if (data && data.error) return cb(data.error, null, data) 161 | cb(null, data, data) 162 | }) 163 | }, 164 | deleteIndex: function (indexName, cb) { 165 | if (!indexName) throw new Error('indexName is not defined') 166 | del(['indexes', indexName], function (err, data) { 167 | if (err) return cb(err, null, data) 168 | if (data && data.error) return cb(data.error, null, data) 169 | cb(null, data, data) 170 | }) 171 | }, 172 | 173 | listIndexers: function (cb) { 174 | get(['indexers'], null, function (err, data) { 175 | if (err) return cb(err, null, data) 176 | if (data && data.error) return cb(data.error, null, data) 177 | cb(null, data.value, data) 178 | }) 179 | }, 180 | createIndexer: function (schema, cb) { 181 | if (!schema) throw new Error('schema is not defined') 182 | post(['indexers'], schema, function (err, data) { 183 | if (err) return cb(err, null, data) 184 | if (data && data.error) return cb(data.error, null, data) 185 | cb(null, data, data) 186 | }) 187 | }, 188 | updateIndexer: function (indexerName, schema, cb) { 189 | if (!indexerName) throw new Error('indexName is not defined') 190 | if (!schema) throw new Error('schema is not defined') 191 | put(['indexers', indexerName], schema, function (err, data) { 192 | if (err) return cb(err, null, data) 193 | if (data && data.error) return cb(data.error, null, data) 194 | cb(null, data, data) 195 | }) 196 | }, 197 | getIndexer: function (indexerName, cb) { 198 | if (!indexerName) throw new Error('indexName is not defined') 199 | get(['indexers', indexerName], null, function (err, data) { 200 | if (err) return cb(err, null, data) 201 | if (data && data.error) return cb(data.error, null, data) 202 | cb(null, data, data) 203 | }) 204 | }, 205 | getIndexerStatus: function (indexerName, cb) { 206 | if (!indexerName) throw new Error('indexerName is not defined') 207 | get(['indexers', indexerName, 'status'], null, function (err, data) { 208 | if (err) return cb(err, null, data) 209 | if (data && data.error) return cb(data.error, null, data) 210 | cb(null, data, data) 211 | }) 212 | }, 213 | deleteIndexer: function (indexerName, cb) { 214 | if (!indexerName) throw new Error('indexerName is not defined') 215 | del(['indexers', indexerName], function (err, data) { 216 | if (err) return cb(err, null, data) 217 | if (data && data.error) return cb(data.error, null, data) 218 | cb(null, data, data) 219 | }) 220 | }, 221 | runIndexer: function (indexerName, cb) { 222 | if (!indexerName) throw new Error('indexerName is not defined') 223 | post(['indexers', indexerName, 'run'], null, function (err, data) { 224 | if (err) return cb(err, null, data) 225 | if (data && data.error) return cb(data.error, null, data) 226 | cb(null, data, data) 227 | }) 228 | }, 229 | resetIndexer: function (indexerName, cb) { 230 | if (!indexerName) throw new Error('indexerName is not defined') 231 | post(['indexers', indexerName, 'reset'], null, function (err, data) { 232 | if (err) return cb(err, null, data) 233 | if (data && data.error) return cb(data.error, null, data) 234 | cb(null, data, data) 235 | }) 236 | }, 237 | 238 | getDataSource: function (dataSourceName, cb) { 239 | if (!dataSourceName) throw new Error('dataSourceName is not defined') 240 | get(['datasources', dataSourceName], null, function (err, data) { 241 | if (err) return cb(err, null, data) 242 | if (data && data.error) return cb(data.error, null, data) 243 | cb(null, data, data) 244 | }) 245 | }, 246 | 247 | createDataSource: function (options, cb) { 248 | if (!options) throw new Error('options is not defined') 249 | post(['datasources'], options, function (err, data) { 250 | if (err) return cb(err, null, data) 251 | if (data && data.error) return cb(data.error, null, data) 252 | cb(null, data, data) 253 | }) 254 | }, 255 | 256 | updateDataSource: function (options, cb) { 257 | if (!options) throw new Error('options is not defined') 258 | if (!options.name) throw new Error('options.name is not defined') 259 | put(['datasources', options.name], options, function (err, data) { 260 | if (err) return cb(err, null, data) 261 | if (data && data.error) return cb(data.error, null, data) 262 | cb(null, data, data) 263 | }) 264 | }, 265 | 266 | deleteDataSource: function (dataSourceName, cb) { 267 | del(['datasources', dataSourceName], function (err, data) { 268 | if (err) return cb(err, null, data) 269 | if (data && data.error) return cb(data.error, null, data) 270 | cb(null, data, data) 271 | }) 272 | }, 273 | 274 | addDocuments: function (indexName, documents, cb) { 275 | if (!indexName) throw new Error('indexName is not defined') 276 | if (!documents) throw new Error('documents is not defined') 277 | post(['indexes', indexName, 'docs', 'index'], { 278 | value: documents 279 | }, function (err, data) { 280 | if (err) return cb(err, null, data) 281 | if (data && data.error) return cb(data.error, null, data) 282 | cb(null, data.value, data) 283 | }) 284 | }, 285 | updateDocuments: function (indexName, documents, cb) { 286 | if (!indexName) throw new Error('indexName is not defined') 287 | if (!documents) throw new Error('documents is not defined') 288 | 289 | for (var i = 0; i < documents.length; i++) { 290 | documents[i]['@search.action'] = 'merge' 291 | } 292 | 293 | post(['indexes', indexName, 'docs', 'index'], { 294 | value: documents 295 | }, function (err, data) { 296 | if (err) return cb(err, null, data) 297 | if (data && data.error) return cb(data.error, null, data) 298 | cb(null, data.value, data) 299 | }) 300 | }, 301 | uploadDocuments: function (indexName, documents, cb) { 302 | if (!indexName) throw new Error('indexName is not defined') 303 | if (!documents) throw new Error('documents is not defined') 304 | 305 | for (var i = 0; i < documents.length; i++) { 306 | documents[i]['@search.action'] = 'upload' 307 | } 308 | 309 | post(['indexes', indexName, 'docs', 'index'], { 310 | value: documents 311 | }, function (err, data) { 312 | if (err) return cb(err, null, data) 313 | if (data && data.error) return cb(data.error, null, data) 314 | cb(null, data.value, data) 315 | }) 316 | }, 317 | deleteDocuments: function (indexName, keys, cb) { 318 | if (!indexName) throw new Error('indexName is not defined') 319 | if (!keys) throw new Error('keys is not defined') 320 | 321 | for (var i = 0; i < keys.length; i++) { 322 | keys[i]['@search.action'] = 'delete' 323 | } 324 | 325 | post(['indexes', indexName, 'docs', 'index'], { 326 | value: keys 327 | }, function (err, data) { 328 | if (err) return cb(err, null, data) 329 | if (data && data.error) return cb(data.error, null, data) 330 | cb(null, data.value, data) 331 | }) 332 | }, 333 | updateOrUploadDocuments: function (indexName, documents, cb) { 334 | if (!indexName) throw new Error('indexName is not defined') 335 | if (!documents) throw new Error('documents is not defined') 336 | 337 | for (var i = 0; i < documents.length; i++) { 338 | documents[i]['@search.action'] = 'mergeOrUpload ' 339 | } 340 | 341 | post(['indexes', indexName, 'docs', 'index'], { 342 | value: documents 343 | }, function (err, data) { 344 | if (err) return cb(err, null, data) 345 | if (data && data.error) return cb(data.error, null, data) 346 | cb(null, data.value, data) 347 | }) 348 | }, 349 | search: function (indexName, query, cb) { 350 | if (!indexName) throw new Error('indexName is not defined') 351 | if (!query) throw new Error('query is not defined') 352 | 353 | post(['indexes', indexName, 'docs', 'search'], query, function (err, results, res) { 354 | if (err) return cb(err, null, results) 355 | if (results && results.error) return cb(results.error, null, results) 356 | cb(null, results.value, results, res) 357 | }) 358 | }, 359 | 360 | lookup: function (indexName, key, cb) { 361 | if (!indexName) throw new Error('indexName is not defined') 362 | if (!key) throw new Error('key is not defined') 363 | 364 | get(['indexes', indexName, "docs('" + key + "')"], null, function (err, data) { 365 | if (err) return cb(err, null, data) 366 | if (data && data.error) return cb(data.error, null, data) 367 | cb(null, data, data) 368 | }) 369 | }, 370 | 371 | count: function (indexName, cb) { 372 | if (!indexName) throw new Error('indexName is not defined') 373 | 374 | get(['indexes', indexName, 'docs', '$count'], { 375 | 'Accept': 'text/plain' 376 | }, function (err, data) { 377 | if (err) return cb(err, null, data) 378 | cb(null, parseInt(data.trim()), data) 379 | }) 380 | }, 381 | 382 | suggest: function (indexName, query, cb) { 383 | if (!indexName) throw new Error('indexName is not defined') 384 | if (!query) throw new Error('query is not defined') 385 | 386 | get(['indexes', indexName, 'docs', 'suggest', query], null, function (err, results) { 387 | if (err) return cb(err, null, results) 388 | if (results && results.error) return cb(results.error, null, results) 389 | cb(null, results.value, results) 390 | }) 391 | }, 392 | updateIndex: function (indexName, schema, cb) { 393 | if (!indexName) throw new Error('indexName is not defined') 394 | if (!schema) throw new Error('schema is not defined') 395 | put(['indexes', indexName], schema, function (err, data) { 396 | if (err) return cb(err, null, data) 397 | if (data && data.error) return cb(data.error, null, data) 398 | cb(null, null, data) 399 | }) 400 | }, 401 | 402 | createSynonymMap: function (schema, cb) { 403 | if (!schema) throw new Error('schema is not defined') 404 | post(['synonymmaps'], schema, function (err, data) { 405 | if (err) return cb(err, null, data) 406 | if (data && data.error) return cb(data.error, null, data) 407 | cb(null, data, data) 408 | }) 409 | }, 410 | updateOrCreateSynonymMap: function (mapName, schema, cb) { 411 | if (!mapName) throw new Error('mapName is not defined') 412 | if (!schema) throw new Error('schema is not defined') 413 | put(['synonymmaps', mapName], schema, function (err, data) { 414 | if (err) return cb(err, null, data) 415 | if (data && data.error) return cb(data.error, null, data) 416 | cb(null, data, data) 417 | }) 418 | }, 419 | getSynonymMap: function (mapName, cb) { 420 | if (!mapName) throw new Error('mapName is not defined') 421 | get(['synonymmaps', mapName], null, function (err, data) { 422 | if (err) return cb(err, null, data) 423 | if (data && data.error) return cb(data.error, null, data) 424 | cb(null, data, data) 425 | }) 426 | }, 427 | listSynonymMaps: function (cb) { 428 | get(['synonymmaps'], null, function (err, data) { 429 | if (err) return cb(err, null, data) 430 | if (data && data.error) return cb(data.error, null, data) 431 | cb(null, data.value, data) 432 | }) 433 | }, 434 | deleteSynonymMap: function (mapName, cb) { 435 | if (!mapName) throw new Error('mapName is not defined') 436 | del(['synonymmaps', mapName], function (err, data) { 437 | if (err) return cb(err, null, data) 438 | if (data && data.error) return cb(data.error, null, data) 439 | cb(null, null, data) 440 | }) 441 | }, 442 | 443 | createSkillset: function (schema, cb) { 444 | if (!schema) throw new Error('schema is not defined') 445 | post(['skillsets'], schema, function (err, data) { 446 | if (err) return cb(err, null, data) 447 | if (data && data.error) return cb(data.error, null, data) 448 | cb(null, data, data) 449 | }) 450 | }, 451 | updateOrCreateSkillset: function (skillsetName, schema, cb) { 452 | if (!skillsetName) throw new Error('skillsetName is not defined') 453 | if (!schema) throw new Error('schema is not defined') 454 | put(['skillsets', skillsetName], schema, function (err, data) { 455 | if (err) return cb(err, null, data) 456 | if (data && data.error) return cb(data.error, null, data) 457 | cb(null, data, data) 458 | }) 459 | }, 460 | getSkillset: function (skillsetName, cb) { 461 | if (!skillsetName) throw new Error('skillsetName is not defined') 462 | get(['skillsets', skillsetName], null, function (err, data) { 463 | if (err) return cb(err, null, data) 464 | if (data && data.error) return cb(data.error, null, data) 465 | cb(null, data, data) 466 | }) 467 | }, 468 | listSkillsets: function (cb) { 469 | get(['skillsets'], null, function (err, data) { 470 | if (err) return cb(err, null, data) 471 | if (data && data.error) return cb(data.error, null, data) 472 | cb(null, data.value, data) 473 | }) 474 | }, 475 | deleteSkillset: function (skillsetName, cb) { 476 | if (!skillsetName) throw new Error('skillsetName is not defined') 477 | del(['skillsets', skillsetName], function (err, data) { 478 | if (err) return cb(err, null, data) 479 | if (data && data.error) return cb(data.error, null, data) 480 | cb(null, null, data) 481 | }) 482 | }, 483 | 484 | then: function (res, rej) { 485 | var ret = {} 486 | var self = this 487 | Object.keys(this).forEach(function (key) { 488 | if (key !== 'then' && key !== 'catch') { 489 | ret[key] = function () { 490 | var args = Array.from(arguments) 491 | var fn = self[key] 492 | return new Promise(function (resolve, reject) { 493 | args.push(function (err, value, data) { 494 | if (err) reject(err) 495 | else resolve(value) 496 | }) 497 | fn.apply(self, args) 498 | }) 499 | } 500 | } 501 | }) 502 | return Promise.resolve(ret).then(res, rej) 503 | }, 504 | catch: function (rej) { 505 | return this.then(null, rej) 506 | } 507 | } 508 | } 509 | 510 | // converts this ["hello","world", {format:"json", facet: ["a", "b"]}] into this "hello/world?format=json&facet=a&facet=b" 511 | function arrayToPath (array) { 512 | var path = array.filter(function (x) { 513 | return typeof x !== 'object' 514 | }) 515 | var filter = array.filter(function (x) { 516 | return typeof x === 'object' 517 | }) 518 | var qs = [] 519 | filter.forEach(function (x) { 520 | for (var key in x) { 521 | if (x[key] instanceof Array) { 522 | x[key].forEach(function (y) { 523 | qs.push(key + '=' + encodeURIComponent(y)) 524 | }) 525 | } else { 526 | qs.push(key + '=' + encodeURIComponent(x[key])) 527 | } 528 | } 529 | }) 530 | return path.join('/') + '?' + qs.join('&') 531 | } 532 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "azure-search", 3 | "version": "0.0.21", 4 | "description": "A client for the Azure Search service", 5 | "main": "index.js", 6 | "scripts": { 7 | "browserify": "browserify azure-search.js | uglifyjs > azure-search.min.js", 8 | "build": "npm run clean && npm run lint && npm run browserify", 9 | "clean": "rimraf *.min.js", 10 | "lint": "standard", 11 | "test": "mocha" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/azure-contrib/node-azure-search.git" 16 | }, 17 | "author": "richard astbury", 18 | "license": "MIT", 19 | "devDependencies": { 20 | "browserify": "^13.1.0", 21 | "mocha": "^5.2.0", 22 | "rimraf": "^2.5.0", 23 | "standard": "^7.1.0", 24 | "uglify-js": "^2.4.0" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/azure-contrib/node-azure-search.svg?branch=master)](https://travis-ci.org/azure-contrib/node-azure-search) 2 | 3 | # node-azure-search 4 | 5 | A JavaScript client library for the Azure Search service, which works from either from Node.js or the browser. The module is browserify compatible. 6 | 7 | This module calls the Azure Search REST API. The documentation for the API is available [here](http://msdn.microsoft.com/library/azure/dn798935.aspx). 8 | 9 | ## Installation 10 | 11 | Use npm: 12 | 13 | ``` 14 | $ npm install azure-search 15 | ``` 16 | 17 | ## Usage 18 | 19 | If using from node: 20 | 21 | ```js 22 | var AzureSearch = require('azure-search'); 23 | var client = AzureSearch({ 24 | url: "https://XXX.search.windows.net", 25 | key: "YYY", 26 | version: "2016-09-01", // optional, can be used to enable preview apis 27 | headers: { // optional, for example to enable searchId in telemetry in logs 28 | "x-ms-azs-return-searchid": "true", 29 | "Access-Control-Expose-Headers": "x-ms-azs-searchid" 30 | 31 | } 32 | }); 33 | ``` 34 | 35 | If using in the browser: 36 | 37 | ```html 38 | 39 | 40 | 41 | 42 | 43 | 51 | 52 | 53 | ``` 54 | > Note that from the browser, you must have the `corsOptions` set in the index schema, and only `search`, `suggest`, `lookup` and `count` will work. 55 | 56 | A client object can then be used to create, update, list, get and delete indexes: 57 | 58 | ```js 59 | var schema = { 60 | name: 'myindex', 61 | fields: 62 | [ { name: 'id', 63 | type: 'Edm.String', 64 | searchable: false, 65 | filterable: true, 66 | retrievable: true, 67 | sortable: true, 68 | facetable: true, 69 | key: true }, 70 | { name: 'description', 71 | type: 'Edm.String', 72 | searchable: true, 73 | filterable: false, 74 | retrievable: true, 75 | sortable: false, 76 | facetable: false, 77 | key: false } ], 78 | scoringProfiles: [], 79 | defaultScoringProfile: null, 80 | corsOptions: null }; 81 | 82 | // create/update an index 83 | client.createIndex(schema, function(err, schema){ 84 | // optional error, or the schema object back from the service 85 | }); 86 | 87 | // update an index 88 | client.updateIndex('myindex', schema, function(err){ 89 | // optional error 90 | }); 91 | 92 | // get an index 93 | client.getIndex('myindex', function(err, schema){ 94 | // optional error, or the schema object back from the service 95 | }); 96 | 97 | // list the indexes 98 | client.listIndexes(function(err, schemas){ 99 | // optional error, or the list of schemas from the service 100 | }); 101 | 102 | // get the stats for an index 103 | client.getIndexStats('myindex', function(err, stats){ 104 | // optional error, or the list of index stats from the service 105 | }); 106 | 107 | var data = { 108 | 'text': 'Text to analyze', 109 | 'analyzer': 'standard' 110 | } 111 | // shows how an analyzer breaks text into tokens 112 | client.testAnalyzer('myindex', data, function (err, tokens) { 113 | //optional error, or array of tokens 114 | } 115 | 116 | // delete an index 117 | client.deleteIndex('myindex', function(err){ 118 | // optional error 119 | }); 120 | ``` 121 | 122 | You can also add documents to the index, and search it: 123 | 124 | ```js 125 | var doc1 = { 126 | "id": "document1", 127 | "description": "this is the description of my document" 128 | } 129 | 130 | // add documents to an index 131 | client.addDocuments('myindex', [doc1], function(err, results){ 132 | // optional error, or confirmation of each document being added 133 | }); 134 | 135 | // retrieve a document from an index 136 | client.lookup('myindex', 'document1', function(){ 137 | // optional error, or the document 138 | }); 139 | 140 | // count the number of documents in the index 141 | client.count('myindex', function(err, count){ 142 | // optional error, or the number of documents in the index 143 | }); 144 | 145 | // search the index (note that multiple arguments can be passed as an array) 146 | client.search('myindex', {search: "document", top: 10, facets: ["facet1", "facet2"]}, function(err, results){ 147 | // optional error, or an array of matching results 148 | }); 149 | 150 | // suggest results based on partial input 151 | client.suggest('myindex', {search: "doc"}, function(err, results){ 152 | // optional error, or an array of matching results 153 | }); 154 | ``` 155 | 156 | You can get, create, update and delete data sources: 157 | 158 | ```js 159 | var options = { 160 | name : "blob-datasource", 161 | type : "azureblob", 162 | credentials : { connectionString : "DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=yyy" }, 163 | container : { name : "mycontainer", query : "" } 164 | } 165 | 166 | client.createDataSource(options, function(err, data){ 167 | // data source created 168 | }); 169 | 170 | client.updateDataSource(options, function(err, data){ 171 | // data source updated 172 | }); 173 | 174 | client.deleteDataSource("blob-datasource", function(err, data){ 175 | // data source deleted 176 | }); 177 | 178 | client.getDataSource("dataSourceName", function(err, data) { 179 | //data source returned 180 | }); 181 | ``` 182 | 183 | You can also create, update, list, get, delete, run and reset indexers: 184 | 185 | ```js 186 | var schema = { 187 | name: 'myindexer', 188 | description: 'Anything', //Optional. Anything you want, or null 189 | dataSourceName: 'myDSName', //Required. The name of an existing data source 190 | targetIndexName: 'myIndexName', //Required. The name of an existing index 191 | schedule: { //Optional. All of the parameters below are required. 192 | interval: 'PT15M', //The pattern for this is: "P[nD][T[nH][nM]]". Examples: PT15M for every 15 minutes, PT2H for every 2 hours. 193 | startTime: '2016-06-01T00:00:00Z' //A UTC datetime when the indexer should start running. 194 | }, 195 | parameters: { //Optional. All of the parameters below are optional. 196 | 'maxFailedItems' : 10, //Default is 0 197 | 'maxFailedItemsPerBatch' : 5, //Default is 0 198 | 'base64EncodeKeys': false, //Default is false 199 | 'batchSize': 500 //The default depends on the data source type: it is 1000 for Azure SQL and DocumentDB, and 10 for Azure Blob Storage 200 | }}; 201 | 202 | // create/update an indexer 203 | client.createIndexer(schema, function(err, schema){ 204 | // optional error, or the schema object back from the service 205 | }); 206 | 207 | // update an indexer 208 | client.updateIndexer('myindexer', schema, function(err){ 209 | // optional error 210 | }); 211 | 212 | // get an indexer 213 | client.getIndexer('myindexer', function(err, schema){ 214 | // optional error, or the schema object back from the service 215 | }); 216 | 217 | // list the indexers 218 | client.listIndexers(function(err, schemas){ 219 | // optional error, or the list of schemas from the service 220 | }); 221 | 222 | // get the status for an indexer 223 | client.getIndexerStatus('myindexer', function(err, status){ 224 | // optional error, or the indexer status object 225 | }); 226 | 227 | // delete an indexer 228 | client.deleteIndexer('myindexer', function(err){ 229 | // optional error 230 | }); 231 | 232 | // run an indexer 233 | client.runIndexer('myindexer', function(err){ 234 | // optional error 235 | }); 236 | 237 | // reset an indexer 238 | client.resetIndexer('myindexer', function(err){ 239 | // optional error 240 | }); 241 | ``` 242 | 243 | It is also possible to work with Synonym Maps: 244 | 245 | ```js 246 | var client = require('azure-search')({ 247 | url: 'https://xxx.search.windows.net', 248 | key: 'your key goes here', 249 | // Mandatory in order to enable preview support of synonyms 250 | version: '2017-11-11' 251 | }) 252 | 253 | var schema = { 254 | name: 'mysynonmap', 255 | // only the 'solr' format is supported for now 256 | format: 'solr', 257 | synonyms: 'a=>b\nb=>c', 258 | } 259 | 260 | client.createSynonymMap(schema, function(err, data) { 261 | // optional error or the created map data 262 | }); 263 | 264 | client.updateOrCreateSynonymMap('mysynonmap', schema, function(err, data) { 265 | // optional error or 266 | // when updating - data is empty 267 | // when creating - data would contain the created map 268 | }); 269 | 270 | client.getSynonymMap('mysynonmap', function(err, data) { 271 | // optional error or the synonym map data 272 | }); 273 | 274 | client.listSynonymMaps(function (err, maps) { 275 | // optional error or the list of maps defined under the account 276 | }) 277 | 278 | client.deleteSynonymMap('mysynonmap', function (err) { 279 | // optional error 280 | }); 281 | ``` 282 | 283 | It is also possible to work with Skillsets for Cognitive Search, currently in preview version '2017-11-11-Preview': 284 | 285 | ```js 286 | var client = require('azure-search')({ 287 | url: 'https://xxx.search.windows.net', 288 | key: 'your key goes here', 289 | // Mandatory in order to enable preview support of skillsets 290 | version: '2017-11-11-Preview' 291 | }) 292 | 293 | var schema = { 294 | name: 'myskillset', // Required for using the POST method 295 | description: 'My skillset description', // Optional 296 | skills: [{ // Required array of skills 297 | '@odata.type': '#Microsoft.Skills.Text.SentimentSkill', 298 | inputs: [{ 299 | name: 'text', 300 | source: '/document/content' 301 | }], 302 | outputs: [{ 303 | name: 'score', 304 | targetName: 'myScore' 305 | }] 306 | }] 307 | } 308 | 309 | client.createSkillset(schema, function(err, data) { 310 | // optional error or the created skillset data 311 | }); 312 | 313 | client.updateOrCreateSkillset('myskillset', schema, function(err, data) { 314 | // optional error or 315 | // when updating - data is empty 316 | // when creating - data would contain the created skillset data 317 | }); 318 | 319 | client.getSkillset('myskillset', function(err, data) { 320 | // optional error or the skillset data 321 | }); 322 | 323 | client.listSkillsets(function (err, maps) { 324 | // optional error or the list of skillsets defined under the account 325 | }) 326 | 327 | client.deleteSynonymMap('myskillset', function (err) { 328 | // optional error 329 | }); 330 | ``` 331 | 332 | ### Accessing the Raw Response 333 | 334 | The raw response body is always returned as the 3rd argument in the callback. 335 | 336 | i.e. 337 | 338 | ```js 339 | // search the index 340 | client.search('myindex', {search: "document", top: 10}, function(err, results, raw){ 341 | // raw argument contains response body as described here: 342 | // https://msdn.microsoft.com/en-gb/library/azure/dn798927.aspx 343 | }); 344 | 345 | ``` 346 | 347 | ### Using Promises 348 | 349 | To use promises, invoke `azureSearch` as a function instead of a constructor. 350 | 351 | i.e. 352 | 353 | ```js 354 | var azureSearch = require('azure-search'); 355 | azureSearch({ 356 | url: "https://XXX.search.windows.net", 357 | key: "YYY" 358 | }) 359 | .then(client => client.listIndexes()) 360 | .then(console.log, console.error) 361 | ``` 362 | 363 | *If you need access to the raw response body, use [callback syntax](#accessing-the-raw-response) instead.* 364 | 365 | ## Contributing 366 | 367 | Contributions are very welcome. 368 | 369 | To download the dependencies: 370 | 371 | ``` 372 | > npm install 373 | ``` 374 | 375 | To build the minified JavaScript: 376 | 377 | ``` 378 | > npm run build 379 | ``` 380 | 381 | To run the tests: 382 | 383 | ``` 384 | > npm run test 385 | ``` 386 | 387 | Please note that you will have to update your `clientConfiguration` and `storageConnectionString` variables in order to run the tests. 388 | 389 | ## License 390 | 391 | MIT 392 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | /* globals describe, it */ 2 | 3 | // to test, first create a search service in azure, and set the url and key here. 4 | var clientConfiguration = { 5 | url: process.env.URL || 'https://xxx.search.windows.net', 6 | key: process.env.KEY || 'your key goes here', 7 | // This API version is required for all tests to pass 8 | version: '2017-11-11-Preview' 9 | } 10 | 11 | // You would also need a storage account (fill in the connection string for that account below) 12 | // Please, also create a container named 'azuresearchtest' in that account (can have private access, and be empty) 13 | var storageConnectionString = process.env.CONNECTION_STRING || 'DefaultEndpointsProtocol=https;AccountName=aaa;AccountKey=bbb' 14 | 15 | var clientFactory = require('./index') 16 | var client = clientFactory(clientConfiguration) 17 | 18 | describe('search service', function () { 19 | this.timeout(5000) 20 | it('creates an index', function (done) { 21 | var schema = { 22 | name: 'myindex', 23 | fields: [ 24 | { 25 | name: 'id', 26 | type: 'Edm.String', 27 | searchable: false, 28 | filterable: true, 29 | retrievable: true, 30 | sortable: true, 31 | facetable: true, 32 | key: true 33 | }, 34 | { 35 | name: 'description', 36 | type: 'Edm.String', 37 | searchable: true, 38 | filterable: false, 39 | retrievable: true, 40 | sortable: false, 41 | facetable: false, 42 | key: false 43 | }, 44 | { 45 | name: 'category', 46 | type: 'Edm.String', 47 | searchable: true, 48 | filterable: false, 49 | retrievable: true, 50 | sortable: false, 51 | facetable: true, 52 | key: false, 53 | analyzer: 'phonetic_area_analyzer' 54 | } 55 | ], 56 | 'analyzers': [ 57 | { 58 | 'name': 'phonetic_area_analyzer', 59 | '@odata.type': '#Microsoft.Azure.Search.CustomAnalyzer', 60 | 'tokenizer': 'area_standard', 61 | 'tokenFilters': ['lowercase', 'asciifolding', 'areas_phonetc'] 62 | } 63 | ], 64 | 'charFilters': [], 65 | 'tokenizers': [ 66 | { 67 | 'name': 'area_standard', 68 | '@odata.type': '#Microsoft.Azure.Search.StandardTokenizerV2' 69 | }, 70 | { 71 | 'name': 'area_keyword', 72 | '@odata.type': '#Microsoft.Azure.Search.KeywordTokenizerV2' 73 | } 74 | ], 75 | 'tokenFilters': [ 76 | { 77 | 'name': 'area_edge', 78 | '@odata.type': '#Microsoft.Azure.Search.EdgeNGramTokenFilterV2', 79 | 'minGram': 2, 80 | 'maxGram': 50 81 | }, 82 | { 83 | 'name': 'area_token_edge', 84 | '@odata.type': '#Microsoft.Azure.Search.EdgeNGramTokenFilterV2', 85 | 'minGram': 2, 86 | 'maxGram': 20 87 | }, 88 | { 89 | 'name': 'areas_phonetc', 90 | '@odata.type': '#Microsoft.Azure.Search.PhoneticTokenFilter', 91 | 'encoder': 'doubleMetaphone' 92 | } 93 | ], 94 | suggesters: [ 95 | { 96 | name: 'sg', 97 | searchMode: 'analyzingInfixMatching', 98 | sourceFields: ['description', 'id'] 99 | } 100 | ], 101 | scoringProfiles: [], 102 | defaultScoringProfile: null, 103 | corsOptions: { allowedOrigins: ['*'] } 104 | } 105 | 106 | client.createIndex(schema, function (err, data) { 107 | if (err) return done('error returned ' + err.message) 108 | if (!data) return done('data is not defined') 109 | if (data.name !== 'myindex') return done('no index name') 110 | if (data.fields.length !== 3) return done('wrong number of fields') 111 | return done() 112 | }) 113 | }) 114 | 115 | it('get index stats', function (done) { 116 | client.getIndexStats('myindex', function (err, index) { 117 | if (err) return done('error returned') 118 | if (!index) return done('index is null') 119 | if (index.documentCount !== 0) return done('wrong document size') 120 | return done() 121 | }) 122 | }) 123 | 124 | it('runs test analyzer', function (done) { 125 | var data = { 126 | 'text': 'Text to analyze', 127 | 'analyzer': 'standard' 128 | } 129 | client.testAnalyzer('myindex', data, function (err, tokens) { 130 | if (err) return done('error returned') 131 | if (!tokens) return done('tokens is null') 132 | if (tokens.length === 0) return done('no tokens returned') 133 | return done() 134 | }) 135 | }) 136 | 137 | it('indexes a document', function (done) { 138 | var doc1 = { 139 | 'id': 'document1', 140 | 'description': 'this is the description of my unique document', 141 | 'category': 'mycategory' 142 | } 143 | client.addDocuments('myindex', [doc1], function (err, data) { 144 | if (err) return done('error returned') 145 | if (!data) return done('data is null') 146 | return done() 147 | }) 148 | }) 149 | 150 | it('deletes a document', function (done) { 151 | var doc2 = { 152 | 'id': 'document2', 153 | 'description': 'this is the description of my document' 154 | } 155 | 156 | client.addDocuments('myindex', [doc2], function (err, data) { 157 | if (err) return done('error returned') 158 | if (!data) return done('data is null') 159 | 160 | var key = { 'id': 'document2' } 161 | 162 | client.deleteDocuments('myindex', [key], function (err, data) { 163 | if (err) return done('error returned') 164 | if (!data) return done('data is null') 165 | return done() 166 | }) 167 | }) 168 | }) 169 | 170 | it('updates a document', function (done) { 171 | var doc3 = { 172 | 'id': 'document3', 173 | 'description': 'this is the description of my document' 174 | } 175 | 176 | client.addDocuments('myindex', [doc3], function (err, data) { 177 | if (err) return done('error returned') 178 | if (!data) return done('data is null') 179 | // update description field 180 | doc3.description = 'updated description' 181 | 182 | client.updateDocuments('myindex', [doc3], function (err, data) { 183 | if (err) return done('error returned') 184 | if (!data) return done('data is null') 185 | 186 | // ensure changes were saved 187 | client.lookup('myindex', 'document3', function (err, results) { 188 | if (err) return done('error returned') 189 | if (!results) return done('results is null') 190 | if (results.description !== doc3.description) return done('document not updated') 191 | return done() 192 | }) 193 | }) 194 | }) 195 | }) 196 | 197 | it('updates or uploads a document', function (done) { 198 | var doc5 = { 199 | 'id': 'document5', 200 | 'description': 'this is the description of my document' 201 | } 202 | 203 | client.updateOrUploadDocuments('myindex', [doc5], function (err, data) { 204 | if (err) return done('error returned') 205 | if (!data) return done('data is null') 206 | // update description field 207 | doc5.description = 'updated description' 208 | 209 | client.updateOrUploadDocuments('myindex', [doc5], function (err, data) { 210 | if (err) return done('error returned') 211 | if (!data) return done('data is null') 212 | 213 | // ensure changes were saved 214 | client.lookup('myindex', 'document5', function (err, results) { 215 | if (err) return done('error returned') 216 | if (!results) return done('results is null') 217 | if (results.description !== doc5.description) return done('document not updated') 218 | return done() 219 | }) 220 | }) 221 | }) 222 | }) 223 | 224 | it('updates a document', function (done) { 225 | var doc3 = { 226 | 'id': 'document3', 227 | 'description': 'this is the description of my document' 228 | } 229 | 230 | client.addDocuments('myindex', [doc3], function (err, data) { 231 | if (err) return done('error returned') 232 | if (!data) return done('data is null') 233 | // update description field 234 | doc3.description = 'updated description' 235 | 236 | client.updateDocuments('myindex', [doc3], function (err, data) { 237 | if (err) return done('error returned') 238 | if (!data) return done('data is null') 239 | 240 | // ensure changes were saved 241 | client.lookup('myindex', 'document3', function (err, results) { 242 | if (err) return done('error returned') 243 | if (!results) return done('results is null') 244 | if (results.description !== doc3.description) return done('document not updated') 245 | return done() 246 | }) 247 | }) 248 | }) 249 | }) 250 | 251 | it('lists the indexes', function (done) { 252 | client.listIndexes(function (err, indexes) { 253 | if (err) return done('error returned', err) 254 | if (!Array.isArray(indexes)) return done('indexes is not an array') 255 | var found = false 256 | for (var idx = 0; idx < indexes.length && !found; idx++) { 257 | if (indexes[idx].name === 'myindex') { 258 | found = true 259 | } 260 | } 261 | if (!found) { 262 | return done('Expected index "myindex" was not found') 263 | } 264 | return done() 265 | }) 266 | }) 267 | 268 | it('get an index', function (done) { 269 | client.getIndex('myindex', function (err, index) { 270 | if (err) return done('error returned', err) 271 | if (!index) return done('index is null') 272 | if (index.name !== 'myindex') return done('index has the wrong name') 273 | return done() 274 | }) 275 | }) 276 | 277 | it('searches with no result', function (done) { 278 | client.search('myindex', { search: '1234' }, function (err, results) { 279 | if (err) return done('error returned') 280 | if (!results) return done('results is null') 281 | if (!Array.isArray(results)) return done('results is not an array') 282 | if (results.length !== 0) return done('results is not the right length') 283 | return done() 284 | }) 285 | }) 286 | 287 | it('looks up a document', function (done) { 288 | client.lookup('myindex', 'document1', function (err, results) { 289 | if (err) return done('error returned') 290 | if (!results) return done('results is null') 291 | if (results.id !== 'document1') return done('wrong results') 292 | return done() 293 | }) 294 | }) 295 | 296 | it('counts documents in an index', function (done) { 297 | client.count('myindex', function (err, count) { 298 | if (err) return done('error returned') 299 | // if (count !== 1) return done('wrong results') 300 | return done() 301 | }) 302 | }) 303 | 304 | it('suggestions', function (done) { 305 | client.suggest('myindex', { search: 'doc', suggesterName: 'sg' }, function (err, results) { 306 | if (err) return done('error returned') 307 | if (!results) return done('results is null') 308 | if (!Array.isArray(results)) return done('results is not an array') 309 | return done() 310 | }) 311 | }) 312 | 313 | it('searches', function (done) { 314 | client.search('myindex', { search: 'unique' }, function (err, results) { 315 | if (err) return done('error returned') 316 | if (!results) return done('results is null') 317 | if (!Array.isArray(results)) return done('results is not an array') 318 | if (results.length !== 1) return done('results is not the right length') 319 | if (results[0].id !== 'document1') return done('doc 1 is not returned') 320 | return done() 321 | }) 322 | }) 323 | 324 | it('updates an index', function (done) { 325 | var schema = { 326 | name: 'myindex', 327 | fields: [ 328 | { 329 | name: 'id', 330 | type: 'Edm.String', 331 | searchable: false, 332 | filterable: true, 333 | retrievable: true, 334 | sortable: true, 335 | facetable: true, 336 | key: true 337 | }, 338 | { 339 | name: 'description', 340 | type: 'Edm.String', 341 | searchable: true, 342 | filterable: false, 343 | retrievable: true, 344 | sortable: false, 345 | facetable: false, 346 | key: false 347 | }, 348 | { 349 | name: 'category', 350 | type: 'Edm.String', 351 | searchable: true, 352 | filterable: false, 353 | retrievable: true, 354 | sortable: false, 355 | facetable: true, 356 | key: false, 357 | analyzer: 'phonetic_area_analyzer' 358 | }, 359 | { 360 | name: 'foo', 361 | type: 'Edm.String', 362 | searchable: true, 363 | filterable: false, 364 | retrievable: true, 365 | sortable: false, 366 | facetable: false, 367 | key: false 368 | } 369 | ], 370 | 'analyzers': [ 371 | { 372 | 'name': 'phonetic_area_analyzer', 373 | '@odata.type': '#Microsoft.Azure.Search.CustomAnalyzer', 374 | 'tokenizer': 'area_standard', 375 | 'tokenFilters': ['lowercase', 'asciifolding', 'areas_phonetc'] 376 | } 377 | ], 378 | 'charFilters': [], 379 | 'tokenizers': [ 380 | { 381 | 'name': 'area_standard', 382 | '@odata.type': '#Microsoft.Azure.Search.StandardTokenizerV2' 383 | }, 384 | { 385 | 'name': 'area_keyword', 386 | '@odata.type': '#Microsoft.Azure.Search.KeywordTokenizerV2' 387 | } 388 | ], 389 | 'tokenFilters': [ 390 | { 391 | 'name': 'area_edge', 392 | '@odata.type': '#Microsoft.Azure.Search.EdgeNGramTokenFilterV2', 393 | 'minGram': 2, 394 | 'maxGram': 50 395 | }, 396 | { 397 | 'name': 'area_token_edge', 398 | '@odata.type': '#Microsoft.Azure.Search.EdgeNGramTokenFilterV2', 399 | 'minGram': 2, 400 | 'maxGram': 20 401 | }, 402 | { 403 | 'name': 'areas_phonetc', 404 | '@odata.type': '#Microsoft.Azure.Search.PhoneticTokenFilter', 405 | 'encoder': 'doubleMetaphone' 406 | } 407 | ], 408 | suggesters: [ 409 | { 410 | name: 'sg', 411 | searchMode: 'analyzingInfixMatching', 412 | sourceFields: ['description', 'id'] 413 | } 414 | ], 415 | scoringProfiles: [], 416 | defaultScoringProfile: null, 417 | corsOptions: { allowedOrigins: ['*'] } 418 | } 419 | 420 | client.updateIndex('myindex', schema, function (err) { 421 | if (err) return done('error returned ' + err.message) 422 | return done() 423 | }) 424 | }) 425 | 426 | it('creates a blob data source', function (done) { 427 | var options = { 428 | name: 'blob-datasource', 429 | type: 'azureblob', 430 | credentials: { connectionString: storageConnectionString }, 431 | container: { name: 'azuresearchtest', query: '' } 432 | } 433 | client.createDataSource(options, function (err, data) { 434 | if (err) return done('error returned ' + err.message) 435 | return done() 436 | }) 437 | }) 438 | 439 | it('gets data source', function (done) { 440 | client.getDataSource('blob-datasource', function (err, data) { 441 | if (err) return done('error returned') 442 | if (!data) return done('datasource is null') 443 | return done() 444 | }) 445 | }) 446 | 447 | it('updates a blob data source', function (done) { 448 | var options = { 449 | name: 'blob-datasource', 450 | type: 'azureblob', 451 | credentials: { connectionString: storageConnectionString }, 452 | container: { name: 'azuresearchtest', query: '' } 453 | } 454 | client.updateDataSource(options, function (err, data) { 455 | if (err) return done('error returned ' + err.message) 456 | return done() 457 | }) 458 | }) 459 | 460 | it('creates a table data source', function (done) { 461 | var options = { 462 | name: 'table-datasource', 463 | type: 'azuretable', 464 | credentials: { connectionString: storageConnectionString }, 465 | container: { name: 'azuresearchtest', query: '' } 466 | } 467 | client.createDataSource(options, function (err, data) { 468 | if (err) return done('error returned ' + err.message) 469 | return done() 470 | }) 471 | }) 472 | 473 | it('updates a table data source', function (done) { 474 | var options = { 475 | name: 'table-datasource', 476 | type: 'azuretable', 477 | credentials: { connectionString: storageConnectionString }, 478 | container: { name: 'azuresearchtest', query: '' } 479 | } 480 | client.updateDataSource(options, function (err, data) { 481 | if (err) return done('error returned ' + err.message) 482 | return done() 483 | }) 484 | }) 485 | 486 | it('creates an indexer', function (done) { 487 | var schema = { 488 | name: 'myindexer', 489 | description: 'Anything', // Optional. Anything you want, or null 490 | dataSourceName: 'blob-datasource', // Required. The name of an existing data source 491 | targetIndexName: 'myindex' // Required. The name of an existing index 492 | } 493 | 494 | client.createIndexer(schema, function (err) { 495 | if (err) return done('error returned ' + err.message) 496 | return done() 497 | }) 498 | }) 499 | 500 | it('updates an indexer', function (done) { 501 | var schema = { 502 | name: 'myindexer', 503 | description: 'Anything Different', // Optional. Anything you want, or null 504 | dataSourceName: 'blob-datasource', // Required. The name of an existing data source 505 | targetIndexName: 'myindex', // Required. The name of an existing index 506 | schedule: { // Optional. All of the parameters below are required. 507 | interval: 'PT15M', // The pattern for this is: 'P[nD][T[nH][nM]]'. Examples: PT15M for every 15 minutes, PT2H for every 2 hours. 508 | startTime: '2016-06-01T00:00:00Z' // A UTC datetime when the indexer should start running. 509 | } 510 | } 511 | 512 | client.updateIndexer('myindexer', schema, function (err) { 513 | if (err) return done('error returned ' + err.message) 514 | return done() 515 | }) 516 | }) 517 | 518 | it('runs an indexer', function (done) { 519 | client.runIndexer('myindexer', function (err, indexer) { 520 | if (err) return done('error returned', err) 521 | return done() 522 | }) 523 | }) 524 | 525 | it('resets an indexer', function (done) { 526 | client.resetIndexer('myindexer', function (err, indexer) { 527 | if (err) return done('error returned', err) 528 | return done() 529 | }) 530 | }) 531 | 532 | it('deletes an indexer', function (done) { 533 | client.deleteIndexer('myindexer', function (err, indexer) { 534 | if (err) return done('error returned', err) 535 | return done() 536 | }) 537 | }) 538 | 539 | it('deletes a blob data source', function (done) { 540 | client.deleteDataSource('blob-datasource', function (err, indexer) { 541 | if (err) return done('error returned', err) 542 | return done() 543 | }) 544 | }) 545 | 546 | it('deletes a table data source', function (done) { 547 | client.deleteDataSource('table-datasource', function (err, indexer) { 548 | if (err) return done('error returned', err) 549 | return done() 550 | }) 551 | }) 552 | 553 | it('deletes an index', function (done) { 554 | client.deleteIndex('myindex', function (err, index) { 555 | if (err) return done('error returned', err) 556 | return done() 557 | }) 558 | }) 559 | 560 | it('creates a synonymmap', function (done) { 561 | var schema = { 562 | name: 'mysynonmap', 563 | format: 'solr', 564 | synonyms: 'a=>b\nb=>c' 565 | } 566 | 567 | client.createSynonymMap(schema, function (err, data) { 568 | if (err) return done('error returned ' + err.message) 569 | if (!data) return done('data is not defined') 570 | if (data.name !== 'mysynonmap') return done('wrong synonym map name') 571 | if (data.format !== 'solr') return done('wrong synonym map format') 572 | if (data.synonyms.split('\n').length !== 2) return done('wrong synonym rows') 573 | return done() 574 | }) 575 | }) 576 | 577 | it('updates a synonymmap', function (done) { 578 | var schema = { 579 | name: 'mysynonmap', 580 | format: 'solr', 581 | synonyms: 'd=>e\ng=>h\nz=>x' 582 | } 583 | 584 | client.updateOrCreateSynonymMap('mysynonmap', schema, function (err, data) { 585 | if (err) return done('error returned ' + err.message) 586 | return done() 587 | }) 588 | }) 589 | 590 | it('gets a synonymmap', function (done) { 591 | client.getSynonymMap('mysynonmap', function (err, data) { 592 | if (err) return done('error returned ' + err.message) 593 | if (!data) return done('data is not defined') 594 | if (data.name !== 'mysynonmap') return done('wrong synonym map name') 595 | if (data.format !== 'solr') return done('wrong synonym map format') 596 | if (data.synonyms.split('\n').length !== 3) return done('wrong synonym rows') 597 | return done() 598 | }) 599 | }) 600 | 601 | it('lists synonymmaps', function (done) { 602 | client.listSynonymMaps(function (err, maps) { 603 | if (err) return done('error returned', err) 604 | if (!Array.isArray(maps)) return done('indexes is not an array') 605 | var found = false 606 | for (var idx = 0; idx < maps.length && !found; idx++) { 607 | if (maps[idx].name === 'mysynonmap') { 608 | found = true 609 | } 610 | } 611 | if (!found) { 612 | return done('Expected synonym map "mysynonmap" was not found') 613 | } 614 | return done() 615 | }) 616 | }) 617 | 618 | it('deletes a synonymmap', function (done) { 619 | client.deleteSynonymMap('mysynonmap', function (err) { 620 | if (err) return done('error returned', err) 621 | return done() 622 | }) 623 | }) 624 | 625 | it('creates while updating a non existant synonymmap', function (done) { 626 | var schema = { 627 | name: 'mysynonmap2', 628 | format: 'solr', 629 | synonyms: 'd=>e\ng=>h\nz=>x' 630 | } 631 | 632 | client.updateOrCreateSynonymMap(schema.name, schema, function (err, data) { 633 | if (err) return done('error returned ' + err.message) 634 | if (!data) return done('data is not defined') 635 | if (data.name !== schema.name) return done('wrong synonym map name') 636 | if (data.format !== 'solr') return done('wrong synonym map format') 637 | if (data.synonyms.split('\n').length !== 3) return done('wrong synonym rows') 638 | return done() 639 | }) 640 | }) 641 | 642 | it('deletes a synonymmap - again', function (done) { 643 | client.deleteSynonymMap('mysynonmap2', function (err, index) { 644 | if (err) return done('error returned', err) 645 | return done() 646 | }) 647 | }) 648 | 649 | it('creates a skillset', function (done) { 650 | var schema = { 651 | name: 'myskillset', 652 | description: 'My skillset', 653 | skills: [{ 654 | '@odata.type': '#Microsoft.Skills.Text.SentimentSkill', 655 | inputs: [{ 656 | name: 'text', 657 | source: '/document/content' 658 | }], 659 | outputs: [{ 660 | name: 'score', 661 | targetName: 'myScore' 662 | }] 663 | }] 664 | } 665 | 666 | client.createSkillset(schema, function (err, data) { 667 | if (err) return done('error returned ' + err.message) 668 | if (!data) return done('data is not defined') 669 | if (data.name !== 'myskillset') return done('wrong skillset name') 670 | if (data.description !== 'My skillset') return done('wrong skillset description') 671 | if (data.skills.length !== 1) return done('wrong number of skills') 672 | return done() 673 | }) 674 | }) 675 | 676 | it('updates a skillset', function (done) { 677 | var schema = { 678 | name: 'myskillset', 679 | description: 'My updated skillset', 680 | skills: [{ 681 | '@odata.type': '#Microsoft.Skills.Text.SentimentSkill', 682 | inputs: [{ 683 | name: 'text', 684 | source: '/document/content' 685 | }], 686 | outputs: [{ 687 | name: 'score', 688 | targetName: 'myScore' 689 | }] 690 | }] 691 | } 692 | 693 | client.updateOrCreateSkillset('myskillset', schema, function (err, data) { 694 | if (err) return done('error returned ' + err.message) 695 | return done() 696 | }) 697 | }) 698 | 699 | it('gets a skillset', function (done) { 700 | client.getSkillset('myskillset', function (err, data) { 701 | if (err) return done('error returned ' + err.message) 702 | if (data.name !== 'myskillset') return done('wrong skillset name') 703 | if (data.description !== 'My updated skillset') return done('wrong skillset description') 704 | if (data.skills.length !== 1) return done('wrong number of skills') 705 | return done() 706 | }) 707 | }) 708 | 709 | it('lists skillsets', function (done) { 710 | client.listSkillsets(function (err, skillsets) { 711 | if (err) return done('error returned', err) 712 | if (!Array.isArray(skillsets)) return done('indexes is not an array') 713 | var found = false 714 | for (var idx = 0; idx < skillsets.length && !found; idx++) { 715 | if (skillsets[idx].name === 'myskillset') { 716 | found = true 717 | } 718 | } 719 | if (!found) { 720 | return done('Expected skillset "myskillset" was not found') 721 | } 722 | return done() 723 | }) 724 | }) 725 | 726 | it('deletes a skillset', function (done) { 727 | client.deleteSkillset('myskillset', function (err) { 728 | if (err) return done('error returned', err) 729 | return done() 730 | }) 731 | }) 732 | 733 | it('handles azure errors', function (done) { 734 | client.getSynonymMap('nonexistant', function (err, data) { 735 | if (!err) return done('expected error is missing') 736 | if (err && !err.code) return done('error code not provided') 737 | if (err && !err.message) return done('error message not provided') 738 | return done() 739 | }) 740 | }) 741 | 742 | it('handles http errors', function (done) { 743 | var badClientConfiguration = { 744 | url: 'https://no.no.no.nothing.here.zz', 745 | key: clientConfiguration.key 746 | } 747 | var badClient = clientFactory(badClientConfiguration) 748 | badClient.getSynonymMap('nonexistant', function (err, data) { 749 | if (!err) return done('expected error is missing') 750 | if (err && !err.code) return done('error code not provided') 751 | if (err && !err.message) return done('error message not provided') 752 | return done() 753 | }) 754 | }) 755 | 756 | it('handles plain text errors', function (done) { 757 | client.count('nosuchindex', function (err, count) { 758 | if (!err) return done('expected error is missing') 759 | return done() 760 | }) 761 | }) 762 | 763 | // This is an edge case 764 | // happens when accessing an API endppoint from an API version which is too old 765 | it('handles error status codes with a response body', function (done) { 766 | var oldClientConfiguration = { 767 | url: clientConfiguration.url, 768 | key: clientConfiguration.key, 769 | version: '2016-09-01' 770 | } 771 | var oldClient = clientFactory(oldClientConfiguration) 772 | oldClient.getSynonymMap('mysynonmap', function (err, data) { 773 | if (!err) return done('expected error is missing') 774 | if (err && !err.code) return done('error code not provided') 775 | return done() 776 | }) 777 | }) 778 | }) 779 | --------------------------------------------------------------------------------