@influxdata/influxdb-client 1.33.0 → 1.33.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,5 +2,5 @@
2
2
  \r `,["\\,","\\ ","\\n","\\r","\\t"]),quoted:st('"\\',['\\"',"\\\\"]),tag:ie(`, =
3
3
  \r `,["\\,","\\ ","\\=","\\n","\\r","\\t"])};var k="000000000",ae=!1;function Fe(r){return ae=r&&process&&typeof process.hrtime=="function"}Fe(!0);var Oe,V,Ae=Date.now(),se=0;function oe(){if(ae){let r=process.hrtime(),e=Date.now();V?(r[0]=r[0]-V[0],r[1]=r[1]-V[1],r[1]<0&&(r[0]-=1,r[1]+=1e9),e=Oe+r[0]*1e3+Math.floor(r[1]/1e6)):(V=r,Oe=e);let t=String(r[1]%1e6);return String(e)+k.substr(0,6-t.length)+t}else{let r=Date.now();r!==Ae?(Ae=r,se=0):se++;let e=String(se);return String(r)+k.substr(0,6-e.length)+e}}function Ee(){if(ae){let r=process.hrtime(),e=String(Math.trunc(r[1]/1e3)%1e3);return String(Date.now())+k.substr(0,3-e.length)+e}else return String(Date.now())+k.substr(0,3)}function De(){return String(Date.now())}function Pe(){return String(Math.floor(Date.now()/1e3))}var le={s:Pe,ms:De,us:Ee,ns:oe,seconds:Pe,millis:De,micros:Ee,nanos:oe},ue={s:r=>`${Math.floor(r.getTime()/1e3)}`,ms:r=>`${r.getTime()}`,us:r=>`${r.getTime()}000`,ns:r=>`${r.getTime()}000000`};function fe(r){return r===void 0?oe():typeof r=="string"?r.length>0?r:void 0:r instanceof Date?`${r.getTime()}000000`:String(typeof r=="number"?Math.floor(r):r)}var Le={error(r,e){console.error("ERROR: "+r,e||"")},warn(r,e){console.warn("WARN: "+r,e||"")}},W=Le,h={error(r,e){W.error(r,e)},warn(r,e){W.warn(r,e)}};function ot(r){let e=W;return W=r,e}var E=Symbol("FLUX_VALUE"),g=class{constructor(e){this.fluxValue=e}toString(){return this.fluxValue}[E](){return this.fluxValue}};function at(r){return typeof r=="object"&&typeof r[E]=="function"}function D(r){if(r==null)return"";r=r.toString();let e,t=0;function n(){e===void 0&&(e=r.substring(0,t))}for(;t<r.length;t++){let i=r.charAt(t);switch(i){case"\r":n(),e+="\\r";break;case`
4
4
  `:n(),e+="\\n";break;case" ":n(),e+="\\t";break;case'"':case"\\":n(),e=e+"\\"+i;break;case"$":if(t+1<r.length&&r.charAt(t+1)==="{"){n(),t++,e+="\\${";break}e!=null&&(e+=i);break;default:e!=null&&(e+=i)}}return e!==void 0?e:r}function lt(r){return new g(`"${D(r)}"`)}function ce(r){let e=Number(r);if(!isFinite(e)){if(typeof r=="number")return`float(v: "${e}")`;throw new Error(`not a flux float: ${r}`)}let t=e.toString(),n=!1;for(let i of t)if(!(i>="0"&&i<="9"||i=="-")){if(i==="."){n=!0;continue}return`float(v: "${t}")`}return n?t:t+".0"}function ut(r){return new g(ce(r))}function de(r){let e=String(r),t=e.startsWith("-"),n=t?e.substring(1):e;if(n.length===0||n.length>19)throw new Error(`not a flux integer: ${e}`);for(let i of n)if(i<"0"||i>"9")throw new Error(`not a flux integer: ${e}`);if(n.length===19){if(t&&n>"9223372036854775808")throw new Error(`flux integer out of bounds: ${e}`);if(!t&&n>"9223372036854775807")throw new Error(`flux integer out of bounds: ${e}`)}return e}function ft(r){return new g(de(r))}function pt(r){return`time(v: "${D(r)}")`}function ct(r){return new g(pt(r))}function dt(r){return new g(`duration(v: "${D(r)}")`)}function Ie(r){return r instanceof RegExp?r.toString():new RegExp(r).toString()}function mt(r){return new g(Ie(r))}function ht(r){return r==="true"||r==="false"?new g(r):new g((!!r).toString())}function pe(r){return new g(String(r))}function N(r){if(r===void 0)return"";if(r===null)return"null";if(typeof r=="boolean")return r.toString();if(typeof r=="string")return`"${D(r)}"`;if(typeof r=="number")return Number.isSafeInteger(r)?de(r):ce(r);if(typeof r=="object"){if(typeof r[E]=="function")return r[E]();if(r instanceof Date)return r.toISOString();if(r instanceof RegExp)return Ie(r);if(Array.isArray(r))return`[${r.map(N).join(",")}]`}else if(typeof r=="bigint")return`${r}.0`;return N(r.toString())}function gt(r,...e){if(r.length==1&&e.length===0)return pe(r[0]);let t=new Array(r.length+e.length),n=0;for(let i=0;i<r.length;i++){let s=r[i];if(t[n++]=s,i<e.length){let a=e[i],o;if(s.endsWith('"')&&i+1<r.length&&r[i+1].startsWith('"'))o=D(a);else if(o=N(a),o===""&&!at(a))throw new Error(`Unsupported parameter literal '${a}' at index: ${i}, type: ${typeof a}`);t[n++]=o}else if(i<r.length-1)throw new Error("Too few parameters supplied!")}return pe(t.join(""))}var me=class{constructor(e){this.tags={};this.fields={};e&&(this.name=e)}measurement(e){return this.name=e,this}tag(e,t){return this.tags[e]=t,this}booleanField(e,t){return this.fields[e]=t?"T":"F",this}intField(e,t){let n;if(typeof t=="number"?n=t:n=parseInt(String(t)),isNaN(n)||n<=-9223372036854776e3||n>=9223372036854776e3)throw new Error(`invalid integer value for field '${e}': '${t}'!`);return this.fields[e]=`${Math.floor(n)}i`,this}uintField(e,t){if(typeof t=="number"){if(isNaN(t)||t<0||t>Number.MAX_SAFE_INTEGER)throw new Error(`uint value for field '${e}' out of range: ${t}`);this.fields[e]=`${Math.floor(t)}u`}else{let n=String(t);for(let i=0;i<n.length;i++){let s=n.charCodeAt(i);if(s<48||s>57)throw new Error(`uint value has an unsupported character at pos ${i}: ${t}`)}if(n.length>20||n.length===20&&n.localeCompare("18446744073709551615")>0)throw new Error(`uint value for field '${e}' out of range: ${n}`);this.fields[e]=`${n}u`}return this}floatField(e,t){let n;if(typeof t=="number"?n=t:n=parseFloat(t),!isFinite(n))throw new Error(`invalid float value for field '${e}': ${t}`);return this.fields[e]=String(n),this}stringField(e,t){return t!=null&&(typeof t!="string"&&(t=String(t)),this.fields[e]=w.quoted(t)),this}timestamp(e){return this.time=e,this}toLineProtocol(e){if(!this.name)return;let t="";if(Object.keys(this.fields).sort().forEach(a=>{if(a){let o=this.fields[a];t.length>0&&(t+=","),t+=`${w.tag(a)}=${o}`}}),t.length===0)return;let n="",i=e&&e.defaultTags?{...e.defaultTags,...this.tags}:this.tags;Object.keys(i).sort().forEach(a=>{if(a){let o=i[a];o&&(n+=",",n+=`${w.tag(a)}=${w.tag(o)}`)}});let s=this.time;return e&&e.convertTime?s=e.convertTime(s):s=fe(s),`${w.measurement(this.name)}${n} ${t}${s!==void 0?" "+s:""}`}toString(){let e=this.toLineProtocol(void 0);return e||`invalid point: ${JSON.stringify(this,void 0)}`}};var he=class{constructor(e){this.options={...re,...e},this.success()}nextDelay(e,t){let n=X(e);if(n&&n>0)return n+Math.round(Math.random()*this.options.retryJitter);if(t&&t>0){if(this.options.randomRetry){let s=Math.max(this.options.minRetryDelay,1),a=s*this.options.exponentialBase;for(let o=1;o<t;o++)if(s=a,a=a*this.options.exponentialBase,a>=this.options.maxRetryDelay){a=this.options.maxRetryDelay;break}return s+Math.round(Math.random()*(a-s)+Math.random()*this.options.retryJitter)}let i=Math.max(this.options.minRetryDelay,1);for(let s=1;s<t;s++)if(i=i*this.options.exponentialBase,i>=this.options.maxRetryDelay){i=this.options.maxRetryDelay;break}return i+Math.round(Math.random()*this.options.retryJitter)}else this.currentDelay?this.currentDelay=Math.min(Math.max(this.currentDelay*this.options.exponentialBase,1)+Math.round(Math.random()*this.options.retryJitter),this.options.maxRetryDelay):this.currentDelay=this.options.minRetryDelay+Math.round(Math.random()*this.options.retryJitter);return this.currentDelay}success(){this.currentDelay=void 0}};function Ue(r){return new he(r)}function yt(r){let e,t=r,n=r;for(;n.next;)n.next.expires<t.expires&&(e=n,t=n.next),n=n.next;return[t,e]}var P=class{constructor(e,t,n=()=>{}){this.maxLines=e;this.retryLines=t;this.onShrink=n;this.size=0;this.closed=!1;this._timeoutHandle=void 0}addLines(e,t,n,i){if(this.closed||!e.length)return;let s=Date.now()+n;if(i<s&&(s=i),this.first&&this.size+e.length>this.maxLines){let f=this.size,l=f*.7;do{let[p,c]=yt(this.first);this.size-=p.lines.length,c?c.next=p.next:(this.first=p.next,this.first&&this.scheduleRetry(this.first.retryTime-Date.now())),p.next=void 0,this.onShrink(p)}while(this.first&&this.size+e.length>l);h.error(`RetryBuffer: ${f-this.size} oldest lines removed to keep buffer size under the limit of ${this.maxLines} lines.`)}let a={lines:e,retryCount:t,retryTime:s,expires:i},o=this.first,u;for(;;){if(!o||o.retryTime>s){a.next=o,u?u.next=a:(this.first=a,this.scheduleRetry(s-Date.now()));break}u=o,o=o.next}this.size+=e.length}removeLines(){if(this.first){let e=this.first;return this.first=this.first.next,e.next=void 0,this.size-=e.lines.length,e}}scheduleRetry(e){this._timeoutHandle&&clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{let t=this.removeLines();t?this.retryLines(t.lines,t.retryCount,t.expires).catch(()=>{}).finally(()=>{this.first&&this.scheduleRetry(this.first.retryTime-Date.now())}):this._timeoutHandle=void 0},Math.max(e,0))}async flush(){let e;for(;e=this.removeLines();)await this.retryLines(e.lines,e.retryCount,e.expires)}close(){return this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),this.closed=!0,this.size}};function ge(r){let e=r.length;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);n<128||(n>=128&&n<=2047?e++:n>=2048&&n<=65535?n>=55296&&n<=57343?e++:e+=2:e+=3)}return e}var ye=class{constructor(e,t,n,i){this.maxChunkRecords=e;this.maxBatchBytes=t;this.flushFn=n;this.scheduleSend=i;this.length=0;this.bytes=-1;this.lines=new Array(e)}add(e){let t=ge(e);this.length===0?this.scheduleSend():this.bytes+t+1>=this.maxBatchBytes&&this.flush().catch(n=>{}),this.lines[this.length]=e,this.length++,this.bytes+=t+1,(this.length>=this.maxChunkRecords||this.bytes>=this.maxBatchBytes)&&this.flush().catch(n=>{})}flush(){let e=this.reset();return e.length>0?this.flushFn(e):Promise.resolve()}reset(){let e=this.lines.slice(0,this.length);return this.length=0,this.bytes=-1,e}},F=class{constructor(e,t,n,i,s){this.transport=e;this.closed=!1;this._timeoutHandle=void 0;this.path=`/api/v2/write?org=${encodeURIComponent(t)}&bucket=${encodeURIComponent(n)}&precision=${i}`,s!=null&&s.consistency&&(this.path+=`&consistency=${encodeURIComponent(s.consistency)}`),this.writeOptions={...ne,...s},this.currentTime=le[i],this.dateToProtocolTimestamp=ue[i],this.writeOptions.defaultTags&&this.useDefaultTags(this.writeOptions.defaultTags),this.sendOptions={method:"POST",headers:{"content-type":"text/plain; charset=utf-8",...s==null?void 0:s.headers},gzipThreshold:this.writeOptions.gzipThreshold};let a=()=>{this.writeOptions.flushInterval>0&&(this._clearFlushTimeout(),this.closed||(this._timeoutHandle=setTimeout(()=>this.sendBatch(this.writeBuffer.reset(),this.writeOptions.maxRetries).catch(o=>{}),this.writeOptions.flushInterval)))};this.writeBuffer=new ye(this.writeOptions.batchSize,this.writeOptions.maxBatchBytes,o=>(this._clearFlushTimeout(),this.sendBatch(o,this.writeOptions.maxRetries)),a),this.sendBatch=this.sendBatch.bind(this),this.retryStrategy=Ue(this.writeOptions),this.retryBuffer=new P(this.writeOptions.maxBufferLines,this.sendBatch,this.writeOptions.writeRetrySkipped)}sendBatch(e,t,n=Date.now()+this.writeOptions.maxRetryTime){let i=this,s=i.writeOptions.maxRetries+1-t;if(!this.closed&&e.length>0){if(n<=Date.now()){let a=new Error("Max retry time exceeded."),o=i.writeOptions.writeFailed.call(i,a,e,s,n);return o||(h.error(`Write to InfluxDB failed (attempt: ${s}).`,a),Promise.reject(a))}return new Promise((a,o)=>{let u,f={responseStarted(l,p){u=p},error(l){let p=i.writeOptions.writeFailed.call(i,l,e,s,n);if(p){p.then(a,o);return}if(l instanceof m&&l.json&&typeof l.json.error=="string"&&l.json.error.includes("hinted handoff queue not empty")){h.warn("Write to InfluxDB returns: "+l.json.error),u=204,f.complete();return}if(!i.closed&&t>0&&(!(l instanceof m)||l.statusCode>=429)){h.warn(`Write to InfluxDB failed (attempt: ${s}).`,l),i.retryBuffer.addLines(e,t-1,i.retryStrategy.nextDelay(l,s),n),o(l);return}h.error("Write to InfluxDB failed.",l),o(l)},complete(){if(u==204||u==null)i.writeOptions.writeSuccess.call(i,e),i.retryStrategy.success(),a();else{let l=`204 HTTP response status code expected, but ${u} returned`,p=new m(u,l,void 0,"0");p.message=l,f.error(p)}}};this.transport.send(this.path,e.join(`
5
- `),this.sendOptions,f)})}else return Promise.resolve()}_clearFlushTimeout(){this._timeoutHandle!==void 0&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0)}writeRecord(e){if(this.closed)throw new Error("writeApi: already closed!");this.writeBuffer.add(e)}writeRecords(e){if(this.closed)throw new Error("writeApi: already closed!");for(let t=0;t<e.length;t++)this.writeBuffer.add(e[t])}writePoint(e){if(this.closed)throw new Error("writeApi: already closed!");let t=e.toLineProtocol(this);t&&this.writeBuffer.add(t)}writePoints(e){if(this.closed)throw new Error("writeApi: already closed!");for(let t=0;t<e.length;t++){let n=e[t].toLineProtocol(this);n&&this.writeBuffer.add(n)}}async flush(e){if(await this.writeBuffer.flush(),e)return await this.retryBuffer.flush()}close(){return this.writeBuffer.flush().finally(()=>{let t=this.retryBuffer.close();t&&h.error(`Retry buffer closed with ${t} items that were not written to InfluxDB!`,null),this.closed=!0})}dispose(){return this._clearFlushTimeout(),this.closed=!0,this.retryBuffer.close()+this.writeBuffer.length}useDefaultTags(e){return this.defaultTags=e,this}convertTime(e){return e===void 0?this.currentTime():typeof e=="string"?e.length>0?e:void 0:e instanceof Date?this.dateToProtocolTimestamp(e):String(typeof e=="number"?Math.floor(e):e)}};var Re=require("url"),$e=Q(require("http")),Me=Q(require("https")),H=require("buffer");var be=require("buffer"),bt={concat(r,e){return be.Buffer.concat([r,e])},toUtf8String(r,e,t){return r.toString("utf-8",e,t)},copy(r,e,t){let n=be.Buffer.allocUnsafe(t-e);return r.copy(n,0,e,t),n}},_e=bt;var L=Q(require("zlib"));function xe(r={}){let e=0,t={next:n=>{if(e===0&&r.next&&n!==null&&n!==void 0)return r.next(n)},error:n=>{e===0&&(e=1,r.error&&r.error(n))},complete:()=>{e===0&&(e=2,r.complete&&r.complete())},responseStarted:(n,i)=>{r.responseStarted&&r.responseStarted(n,i)}};return r.useCancellable&&(t.useCancellable=r.useCancellable.bind(r)),r.useResume&&(t.useResume=r.useResume.bind(r)),t}var Be="1.33.0";var ze=require("stream"),xt={flush:L.default.constants.Z_SYNC_FLUSH,finishFlush:L.default.constants.Z_SYNC_FLUSH},Rt=H.Buffer.allocUnsafe(0),we=class{constructor(){this.cancelled=!1}cancel(){this.cancelled=!0,this.resume&&(this.resume(),this.resume=void 0)}isCancelled(){return this.cancelled}},Te=class{constructor(e){this.chunkCombiner=_e;var u,f,l,p,c,d,_;let{url:t,proxyUrl:n,token:i,transportOptions:s,...a}=e,o=(0,Re.parse)(n||t);if(this.token=i,this.defaultOptions={...te,...a,...s,port:o.port,protocol:o.protocol,hostname:o.hostname},this.contextPath=n?t:(u=o.path)!=null?u:"",this.contextPath.endsWith("/")&&(this.contextPath=this.contextPath.substring(0,this.contextPath.length-1)),Object.keys(this.defaultOptions).forEach(Ce=>this.defaultOptions[Ce]===void 0&&delete this.defaultOptions[Ce]),this.contextPath.endsWith("/api/v2")&&(h.warn(`Please remove '/api/v2' context path from InfluxDB base url, using ${o.protocol}//${o.hostname}:${o.port} !`),this.contextPath=""),o.protocol==="http:")this.requestApi=(p=(l=(f=this.defaultOptions["follow-redirects"])==null?void 0:f.http)==null?void 0:l.request)!=null?p:$e.request;else if(o.protocol==="https:")this.requestApi=(_=(d=(c=this.defaultOptions["follow-redirects"])==null?void 0:c.https)==null?void 0:d.request)!=null?_:Me.request;else throw new Error(`Unsupported protocol "${o.protocol} in URL: "${e.url}"`);this.headers={"User-Agent":`influxdb-client-js/${Be}`,...e.headers},n&&(this.headers.Host=(0,Re.parse)(t).host)}send(e,t,n,i){let s=new we;i&&i.useCancellable&&i.useCancellable(s),this.createRequestMessage(e,t,n,a=>{this._request(a,s,i)},a=>(i==null?void 0:i.error)&&i.error(a))}request(e,t,n,i){t?typeof t!="string"&&(t=JSON.stringify(t)):t="";let s=Rt,a,o;return new Promise((u,f)=>{this.send(e,t,n,{responseStarted(l,p){i&&i(l,p),a=String(l["content-type"]),o=p},next:l=>{s=H.Buffer.concat([s,l])},complete:()=>{var p,c;let l=(c=(p=n.headers)==null?void 0:p.accept)!=null?c:a;try{o===204&&u(void 0),l.includes("json")?s.length?u(JSON.parse(s.toString("utf8"))):u(void 0):l.includes("text")||l.startsWith("application/csv")?u(s.toString("utf8")):u(s)}catch(d){f(d)}},error:l=>{f(l)}})})}async*iterate(e,t,n){var l;let i,s;function a(p){i=p,s(p)}let o=await new Promise((p,c)=>{s=c,this.createRequestMessage(e,t,n,p,a)});(l=o.signal)!=null&&l.addEventListener&&o.signal.addEventListener("abort",()=>{a(new b)});let u=await new Promise((p,c)=>{s=c;let d=this.requestApi(o,p);d.on("timeout",()=>a(new x)),d.on("error",a),d.write(o.body),d.end()}),f=await new Promise((p,c)=>{s=c,this._prepareResponse(u,p,a)});for await(let p of f){if(i)throw i;yield p}}createRequestMessage(e,t,n,i,s){let a=H.Buffer.from(t,"utf-8"),o={"content-type":"application/json; charset=utf-8",...this.headers};this.token&&(o.authorization="Token "+this.token);let u={...this.defaultOptions,path:this.contextPath+e,method:n.method,headers:{...o,...n.headers}};if(n.signal&&(u.signal=n.signal),n.gzipThreshold!==void 0&&n.gzipThreshold<a.length){L.default.gzip(a,(f,l)=>{if(f)return s(f);u.headers["content-encoding"]="gzip",u.body=l,i(u)});return}u.body=a,u.headers["content-length"]=u.body.length,i(u)}_prepareResponse(e,t,n){var o;e.on("aborted",()=>{n(new b)}),e.on("error",n);let i=(o=e.statusCode)!=null?o:600,s=e.headers["content-encoding"],a;if(s==="gzip"?(a=L.default.createGunzip(xt),a=(0,ze.pipeline)(e,a,u=>u&&n(u))):a=e,i>=300){let u="",f=String(e.headers["content-type"]).startsWith("application/json");a.on("data",l=>{u+=l.toString(),!f&&u.length>1e3&&(u=u.slice(0,1e3),e.resume())}),a.on("end",()=>{u===""&&!!e.headers["x-influxdb-error"]&&(u=e.headers["x-influxdb-error"].toString()),n(new m(i,e.statusMessage,u,e.headers["retry-after"],e.headers["content-type"]))})}else t(a)}_request(e,t,n){var a;let i=xe(n);if(t.isCancelled()){i.complete();return}(a=e.signal)!=null&&a.addEventListener&&e.signal.addEventListener("abort",()=>{i.error(new b)});let s=this.requestApi(e,o=>{if(t.isCancelled()){o.resume(),i.complete();return}i.responseStarted(o.headers,o.statusCode),this._prepareResponse(o,u=>{u.on("data",f=>{if(t.isCancelled())o.resume();else if(i.next(f)===!1){if(!i.useResume){i.error(new Error("Unable to pause, useResume is not configured!")),o.resume();return}o.pause();let l=()=>{o.resume()};t.resume=l,i.useResume(l)}}),u.on("end",i.complete)},i.error)});typeof s.setTimeout=="function"&&e.timeout&&s.setTimeout(e.timeout),s.on("timeout",()=>{i.error(new x)}),s.on("error",o=>{i.error(o)}),e.body&&s.write(e.body),s.end()}},Ve=Te;var ke={header:!0,delimiter:",",quoteChar:'"',commentPrefix:"#",annotations:["datatype","group","default"]},I=class{constructor(e,t,n){this.transport=e;this.createCSVResponse=t;this.options=typeof n=="string"?{org:n}:n}with(e){return new I(this.transport,this.createCSVResponse,{...this.options,...e})}response(e){let{org:t,type:n,gzip:i,headers:s}=this.options,a=`/api/v2/query?org=${encodeURIComponent(t)}`,o=JSON.stringify(this.decorateRequest({query:e.toString(),dialect:ke,type:n})),u={method:"POST",headers:{"content-type":"application/json; encoding=utf-8","accept-encoding":i?"gzip":"identity",...s}};return this.createCSVResponse(f=>this.transport.send(a,o,u,f),()=>this.transport.iterate(a,o,u))}iterateLines(e){return this.response(e).iterateLines()}iterateRows(e){return this.response(e).iterateRows()}lines(e){return this.response(e).lines()}rows(e){return this.response(e).rows()}queryLines(e,t){return this.response(e).consumeLines(t)}queryRows(e,t){return this.response(e).consumeRows(t)}collectRows(e,t){return this.response(e).collectRows(t)}collectLines(e){return this.response(e).collectLines()}queryRaw(e){let{org:t,type:n,gzip:i,headers:s}=this.options;return this.transport.request(`/api/v2/query?org=${encodeURIComponent(t)}`,JSON.stringify(this.decorateRequest({query:e.toString(),dialect:ke,type:n})),{method:"POST",headers:{accept:"text/csv","accept-encoding":i?"gzip":"identity","content-type":"application/json; encoding=utf-8",...s}})}decorateRequest(e){var t;return typeof this.options.now=="function"&&(e.now=this.options.now()),e.type=(t=this.options.type)!=null?t:"flux",e}},We=I;function wt(r,e){return e.toObject(r)}var q=class{constructor(e,t,n){this.executor=e;this.iterableResultExecutor=t;this.chunkCombiner=n}iterateLines(){return $(this.iterableResultExecutor())}iterateRows(){return G($(this.iterableResultExecutor()))}lines(){return new S(this.executor,e=>T(e,this.chunkCombiner))}rows(){return new S(this.executor,e=>T(z({next(t,n){e.next({values:t,tableMeta:n})},error(t){e.error(t)},complete(){e.complete()}}),this.chunkCombiner))}consumeLines(e){this.executor(T(e,this.chunkCombiner))}consumeRows(e){this.executor(T(z(e),this.chunkCombiner))}collectRows(e=wt){let t=[];return new Promise((n,i)=>{this.consumeRows({next(s,a){let o=e.call(this,s,a);o!==void 0&&t.push(o)},error(s){i(s)},complete(){n(t)}})})}collectLines(){let e=[];return new Promise((t,n)=>{this.consumeLines({next(i){e.push(i)},error(i){n(i)},complete(){t(e)}})})}};var U=class{constructor(e){var n;if(typeof e=="string")this._options={url:e};else if(e!==null&&typeof e=="object")this._options=e;else throw new y("No url or configuration specified!");let t=this._options.url;if(typeof t!="string")throw new y("No url specified!");t.endsWith("/")&&(this._options.url=t.substring(0,t.length-1)),this.transport=(n=this._options.transport)!=null?n:new Ve(this._options),this.processCSVResponse=(i,s)=>new q(i,s,this.transport.chunkCombiner)}getWriteApi(e,t,n="ns",i){return new F(this.transport,e,t,n,i!=null?i:this._options.writeOptions)}getQueryApi(e){return new We(this.transport,this.processCSVResponse,e)}};0&&(module.exports={AbortError,DEFAULT_ConnectionOptions,DEFAULT_RetryDelayStrategyOptions,DEFAULT_WriteOptions,FLUX_VALUE,HttpError,IllegalArgumentError,InfluxDB,LineSplitter,Log,Point,RequestTimedOutError,UNKNOWN_COLUMN,canRetryHttpCall,chunksToLines,chunksToLinesIterable,consoleLogger,convertTimeToNanos,createFluxTableColumn,createFluxTableMetaData,createTextDecoderCombiner,currentTime,dateToProtocolTimestamp,escape,flux,fluxBool,fluxDateTime,fluxDuration,fluxExpression,fluxFloat,fluxInteger,fluxRegExp,fluxString,getRetryDelay,isStatusCodeRetriable,linesToRowsIterable,linesToTables,newFluxTableColumn,sanitizeFloat,sanitizeInteger,serializeDateTimeAsDate,serializeDateTimeAsNumber,serializeDateTimeAsString,setLogger,stringToLines,symbolObservable,toFluxValue,typeSerializers,useProcessHrtime});
5
+ `),this.sendOptions,f)})}else return Promise.resolve()}_clearFlushTimeout(){this._timeoutHandle!==void 0&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0)}writeRecord(e){if(this.closed)throw new Error("writeApi: already closed!");this.writeBuffer.add(e)}writeRecords(e){if(this.closed)throw new Error("writeApi: already closed!");for(let t=0;t<e.length;t++)this.writeBuffer.add(e[t])}writePoint(e){if(this.closed)throw new Error("writeApi: already closed!");let t=e.toLineProtocol(this);t&&this.writeBuffer.add(t)}writePoints(e){if(this.closed)throw new Error("writeApi: already closed!");for(let t=0;t<e.length;t++){let n=e[t].toLineProtocol(this);n&&this.writeBuffer.add(n)}}async flush(e){if(await this.writeBuffer.flush(),e)return await this.retryBuffer.flush()}close(){return this.writeBuffer.flush().finally(()=>{let t=this.retryBuffer.close();t&&h.error(`Retry buffer closed with ${t} items that were not written to InfluxDB!`,null),this.closed=!0})}dispose(){return this._clearFlushTimeout(),this.closed=!0,this.retryBuffer.close()+this.writeBuffer.length}useDefaultTags(e){return this.defaultTags=e,this}convertTime(e){return e===void 0?this.currentTime():typeof e=="string"?e.length>0?e:void 0:e instanceof Date?this.dateToProtocolTimestamp(e):String(typeof e=="number"?Math.floor(e):e)}};var Re=require("url"),$e=Q(require("http")),Me=Q(require("https")),H=require("buffer");var be=require("buffer"),bt={concat(r,e){return be.Buffer.concat([r,e])},toUtf8String(r,e,t){return r.toString("utf-8",e,t)},copy(r,e,t){let n=be.Buffer.allocUnsafe(t-e);return r.copy(n,0,e,t),n}},_e=bt;var L=Q(require("zlib"));function xe(r={}){let e=0,t={next:n=>{if(e===0&&r.next&&n!==null&&n!==void 0)return r.next(n)},error:n=>{e===0&&(e=1,r.error&&r.error(n))},complete:()=>{e===0&&(e=2,r.complete&&r.complete())},responseStarted:(n,i)=>{r.responseStarted&&r.responseStarted(n,i)}};return r.useCancellable&&(t.useCancellable=r.useCancellable.bind(r)),r.useResume&&(t.useResume=r.useResume.bind(r)),t}var Be="1.33.2";var ze=require("stream"),xt={flush:L.default.constants.Z_SYNC_FLUSH,finishFlush:L.default.constants.Z_SYNC_FLUSH},Rt=H.Buffer.allocUnsafe(0),we=class{constructor(){this.cancelled=!1}cancel(){this.cancelled=!0,this.resume&&(this.resume(),this.resume=void 0)}isCancelled(){return this.cancelled}},Te=class{constructor(e){this.chunkCombiner=_e;var u,f,l,p,c,d,_;let{url:t,proxyUrl:n,token:i,transportOptions:s,...a}=e,o=(0,Re.parse)(n||t);if(this.token=i,this.defaultOptions={...te,...a,...s,port:o.port,protocol:o.protocol,hostname:o.hostname},this.contextPath=n?t:(u=o.path)!=null?u:"",this.contextPath.endsWith("/")&&(this.contextPath=this.contextPath.substring(0,this.contextPath.length-1)),Object.keys(this.defaultOptions).forEach(Ce=>this.defaultOptions[Ce]===void 0&&delete this.defaultOptions[Ce]),this.contextPath.endsWith("/api/v2")&&(h.warn(`Please remove '/api/v2' context path from InfluxDB base url, using ${o.protocol}//${o.hostname}:${o.port} !`),this.contextPath=""),o.protocol==="http:")this.requestApi=(p=(l=(f=this.defaultOptions["follow-redirects"])==null?void 0:f.http)==null?void 0:l.request)!=null?p:$e.request;else if(o.protocol==="https:")this.requestApi=(_=(d=(c=this.defaultOptions["follow-redirects"])==null?void 0:c.https)==null?void 0:d.request)!=null?_:Me.request;else throw new Error(`Unsupported protocol "${o.protocol} in URL: "${e.url}"`);this.headers={"User-Agent":`influxdb-client-js/${Be}`,...e.headers},n&&(this.headers.Host=(0,Re.parse)(t).host)}send(e,t,n,i){let s=new we;i&&i.useCancellable&&i.useCancellable(s),this.createRequestMessage(e,t,n,a=>{this._request(a,s,i)},a=>(i==null?void 0:i.error)&&i.error(a))}request(e,t,n,i){t?typeof t!="string"&&(t=JSON.stringify(t)):t="";let s=Rt,a,o;return new Promise((u,f)=>{this.send(e,t,n,{responseStarted(l,p){i&&i(l,p),a=String(l["content-type"]),o=p},next:l=>{s=H.Buffer.concat([s,l])},complete:()=>{var p,c;let l=(c=(p=n.headers)==null?void 0:p.accept)!=null?c:a;try{o===204&&u(void 0),l.includes("json")?s.length?u(JSON.parse(s.toString("utf8"))):u(void 0):l.includes("text")||l.startsWith("application/csv")?u(s.toString("utf8")):u(s)}catch(d){f(d)}},error:l=>{f(l)}})})}async*iterate(e,t,n){var l;let i,s;function a(p){i=p,s(p)}let o=await new Promise((p,c)=>{s=c,this.createRequestMessage(e,t,n,p,a)});(l=o.signal)!=null&&l.addEventListener&&o.signal.addEventListener("abort",()=>{a(new b)});let u=await new Promise((p,c)=>{s=c;let d=this.requestApi(o,p);d.on("timeout",()=>a(new x)),d.on("error",a),d.write(o.body),d.end()}),f=await new Promise((p,c)=>{s=c,this._prepareResponse(u,p,a)});for await(let p of f){if(i)throw i;yield p}}createRequestMessage(e,t,n,i,s){let a=H.Buffer.from(t,"utf-8"),o={"content-type":"application/json; charset=utf-8",...this.headers};this.token&&(o.authorization="Token "+this.token);let u={...this.defaultOptions,path:this.contextPath+e,method:n.method,headers:{...o,...n.headers}};if(n.signal&&(u.signal=n.signal),n.gzipThreshold!==void 0&&n.gzipThreshold<a.length){L.default.gzip(a,(f,l)=>{if(f)return s(f);u.headers["content-encoding"]="gzip",u.body=l,i(u)});return}u.body=a,u.headers["content-length"]=u.body.length,i(u)}_prepareResponse(e,t,n){var o;e.on("aborted",()=>{n(new b)}),e.on("error",n);let i=(o=e.statusCode)!=null?o:600,s=e.headers["content-encoding"],a;if(s==="gzip"?(a=L.default.createGunzip(xt),a=(0,ze.pipeline)(e,a,u=>u&&n(u))):a=e,i>=300){let u="",f=String(e.headers["content-type"]).startsWith("application/json");a.on("data",l=>{u+=l.toString(),!f&&u.length>1e3&&(u=u.slice(0,1e3),e.resume())}),a.on("end",()=>{u===""&&!!e.headers["x-influxdb-error"]&&(u=e.headers["x-influxdb-error"].toString()),n(new m(i,e.statusMessage,u,e.headers["retry-after"],e.headers["content-type"]))})}else t(a)}_request(e,t,n){var a;let i=xe(n);if(t.isCancelled()){i.complete();return}(a=e.signal)!=null&&a.addEventListener&&e.signal.addEventListener("abort",()=>{i.error(new b)});let s=this.requestApi(e,o=>{if(t.isCancelled()){o.resume(),i.complete();return}i.responseStarted(o.headers,o.statusCode),this._prepareResponse(o,u=>{u.on("data",f=>{if(t.isCancelled())o.resume();else if(i.next(f)===!1){if(!i.useResume){i.error(new Error("Unable to pause, useResume is not configured!")),o.resume();return}o.pause();let l=()=>{o.resume()};t.resume=l,i.useResume(l)}}),u.on("end",i.complete)},i.error)});typeof s.setTimeout=="function"&&e.timeout&&s.setTimeout(e.timeout),s.on("timeout",()=>{i.error(new x)}),s.on("error",o=>{i.error(o)}),e.body&&s.write(e.body),s.end()}},Ve=Te;var ke={header:!0,delimiter:",",quoteChar:'"',commentPrefix:"#",annotations:["datatype","group","default"]},I=class{constructor(e,t,n){this.transport=e;this.createCSVResponse=t;this.options=typeof n=="string"?{org:n}:n}with(e){return new I(this.transport,this.createCSVResponse,{...this.options,...e})}response(e){let{org:t,type:n,gzip:i,headers:s}=this.options,a=`/api/v2/query?org=${encodeURIComponent(t)}`,o=JSON.stringify(this.decorateRequest({query:e.toString(),dialect:ke,type:n})),u={method:"POST",headers:{"content-type":"application/json; encoding=utf-8","accept-encoding":i?"gzip":"identity",...s}};return this.createCSVResponse(f=>this.transport.send(a,o,u,f),()=>this.transport.iterate(a,o,u))}iterateLines(e){return this.response(e).iterateLines()}iterateRows(e){return this.response(e).iterateRows()}lines(e){return this.response(e).lines()}rows(e){return this.response(e).rows()}queryLines(e,t){return this.response(e).consumeLines(t)}queryRows(e,t){return this.response(e).consumeRows(t)}collectRows(e,t){return this.response(e).collectRows(t)}collectLines(e){return this.response(e).collectLines()}queryRaw(e){let{org:t,type:n,gzip:i,headers:s}=this.options;return this.transport.request(`/api/v2/query?org=${encodeURIComponent(t)}`,JSON.stringify(this.decorateRequest({query:e.toString(),dialect:ke,type:n})),{method:"POST",headers:{accept:"text/csv","accept-encoding":i?"gzip":"identity","content-type":"application/json; encoding=utf-8",...s}})}decorateRequest(e){var t;return typeof this.options.now=="function"&&(e.now=this.options.now()),e.type=(t=this.options.type)!=null?t:"flux",e}},We=I;function wt(r,e){return e.toObject(r)}var q=class{constructor(e,t,n){this.executor=e;this.iterableResultExecutor=t;this.chunkCombiner=n}iterateLines(){return $(this.iterableResultExecutor())}iterateRows(){return G($(this.iterableResultExecutor()))}lines(){return new S(this.executor,e=>T(e,this.chunkCombiner))}rows(){return new S(this.executor,e=>T(z({next(t,n){e.next({values:t,tableMeta:n})},error(t){e.error(t)},complete(){e.complete()}}),this.chunkCombiner))}consumeLines(e){this.executor(T(e,this.chunkCombiner))}consumeRows(e){this.executor(T(z(e),this.chunkCombiner))}collectRows(e=wt){let t=[];return new Promise((n,i)=>{this.consumeRows({next(s,a){let o=e.call(this,s,a);o!==void 0&&t.push(o)},error(s){i(s)},complete(){n(t)}})})}collectLines(){let e=[];return new Promise((t,n)=>{this.consumeLines({next(i){e.push(i)},error(i){n(i)},complete(){t(e)}})})}};var U=class{constructor(e){var n;if(typeof e=="string")this._options={url:e};else if(e!==null&&typeof e=="object")this._options=e;else throw new y("No url or configuration specified!");let t=this._options.url;if(typeof t!="string")throw new y("No url specified!");t.endsWith("/")&&(this._options.url=t.substring(0,t.length-1)),this.transport=(n=this._options.transport)!=null?n:new Ve(this._options),this.processCSVResponse=(i,s)=>new q(i,s,this.transport.chunkCombiner)}getWriteApi(e,t,n="ns",i){return new F(this.transport,e,t,n,i!=null?i:this._options.writeOptions)}getQueryApi(e){return new We(this.transport,this.processCSVResponse,e)}};0&&(module.exports={AbortError,DEFAULT_ConnectionOptions,DEFAULT_RetryDelayStrategyOptions,DEFAULT_WriteOptions,FLUX_VALUE,HttpError,IllegalArgumentError,InfluxDB,LineSplitter,Log,Point,RequestTimedOutError,UNKNOWN_COLUMN,canRetryHttpCall,chunksToLines,chunksToLinesIterable,consoleLogger,convertTimeToNanos,createFluxTableColumn,createFluxTableMetaData,createTextDecoderCombiner,currentTime,dateToProtocolTimestamp,escape,flux,fluxBool,fluxDateTime,fluxDuration,fluxExpression,fluxFloat,fluxInteger,fluxRegExp,fluxString,getRetryDelay,isStatusCodeRetriable,linesToRowsIterable,linesToTables,newFluxTableColumn,sanitizeFloat,sanitizeInteger,serializeDateTimeAsDate,serializeDateTimeAsNumber,serializeDateTimeAsString,setLogger,stringToLines,symbolObservable,toFluxValue,typeSerializers,useProcessHrtime});
6
6
  //# sourceMappingURL=index.js.map
package/dist/index.js.gz CHANGED
Binary file