@inyourarea/aard-client-js
Version:
A JavaScript tracking library for the Aard Platform at InYourArea.co.uk. Record and track activity across the different services of the platform.
2 lines (1 loc) • 25.5 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("stream"),require("http"),require("url"),require("https"),require("zlib")):"function"==typeof define&&define.amd?define(["exports","stream","http","url","https","zlib"],t):t((e=e||self)["aard-client-recorder"]={},e.Stream,e.http,e.Url,e.https,e.zlib)}(this,function(e,t,r,n,o,i){"use strict";t=t&&t.hasOwnProperty("default")?t.default:t,r=r&&r.hasOwnProperty("default")?r.default:r,n=n&&n.hasOwnProperty("default")?n.default:n,o=o&&o.hasOwnProperty("default")?o.default:o,i=i&&i.hasOwnProperty("default")?i.default:i;var s=function(e){return{name:"transform.parse_url",input:{url:e}}},u=function(e){return{name:"transform.user_agent",input:{ua_string:e}}},a=function(e,t){return void 0===t&&(t="*"),{name:"extension.dstore",input:{hash:e},output:t}},c=function(e,t,r){return{name:"extension.idstore",input:{ns:e,key:t},output:r}},l=Object.freeze({parseUrl:s,parseUserAgent:u,restoreFragment:a,remoteJoin:c}),f=function(){return(f=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};function d(e,t,r,n){return new(r||(r=Promise))(function(o,i){function s(e){try{a(n.next(e))}catch(e){i(e)}}function u(e){try{a(n.throw(e))}catch(e){i(e)}}function a(e){e.done?o(e.value):new r(function(t){t(e.value)}).then(s,u)}a((n=n.apply(e,t||[])).next())})}function p(e,t){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,n=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],n=0}finally{r=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}}var h=function(e){return"undefined"!=typeof window?f({},e,{dimensions:f({},e.dimensions,{page:f({},"object"==typeof e.dimensions.page?e.dimensions.page:{},{url:window.location.href})}),plugins:e.plugins.concat([s("page.url")])}):e},y=function(e){return"undefined"!=typeof window?f({},e,{dimensions:f({},e.dimensions,{page:f({},"object"==typeof e.dimensions.page?e.dimensions.page:{},{referrer:window.document.referrer})}),plugins:e.plugins.concat([s("page.referrer")])}):e},m=function(e){return"undefined"!=typeof window&&window.navigator?f({},e,{dimensions:f({},e.dimensions,{userAgent:window.navigator.userAgent}),plugins:e.plugins.concat([u("userAgent")])}):e},b=function(e){return"undefined"!=typeof window&&window.navigator?f({},e,{dimensions:f({},e.dimensions,{language:window.navigator.language})}):e},g=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return function(t){return e.reduce(function(e,t){return t(e)},t)}},w=function(e,t){return function(r){return f({},r,{plugins:r.plugins.concat([a(e,t)])})}},v=[h,y,b,m],j=Object.freeze({DEFAULT_TRANSFORMER:v,composeTransformers:g,addParseUrlPlugin:function(e){return function(t){return f({},t,{plugins:t.plugins.concat([s(e)])})}},addParseUserAgentPlugin:function(e){return function(t){return f({},t,{plugins:t.plugins.concat([u(e)])})}},addRestoreFragmentPlugin:w,addRemoteJoinPlugin:function(e,t,r){return function(n){return f({},n,{plugins:n.plugins.concat([c(e,t,r)])})}},addCurrentPageDetails:h,addPageReferrer:y,addUserAgent:m,addBrowserLanguage:b,addAppName:function(e){return function(t){return f({},t,{dimensions:f({},t.dimensions,{app:f({},"object"==typeof t.dimensions.app?t.dimensions.app:{},{name:e})})})}}});const O=Symbol("buffer"),T=Symbol("type");class P{constructor(){this[T]="";const e=arguments[0],t=arguments[1],r=[];if(e){const t=e,n=Number(t.length);for(let e=0;e<n;e++){const n=t[e];let o;o=n instanceof Buffer?n:ArrayBuffer.isView(n)?Buffer.from(n.buffer,n.byteOffset,n.byteLength):n instanceof ArrayBuffer?Buffer.from(n):n instanceof P?n[O]:Buffer.from("string"==typeof n?n:String(n)),r.push(o)}}this[O]=Buffer.concat(r);let n=t&&void 0!==t.type&&String(t.type).toLowerCase();n&&!/[^\u0020-\u007E]/.test(n)&&(this[T]=n)}get size(){return this[O].length}get type(){return this[T]}slice(){const e=this.size,t=arguments[0],r=arguments[1];let n,o;n=void 0===t?0:t<0?Math.max(e+t,0):Math.min(t,e),o=void 0===r?e:r<0?Math.max(e+r,0):Math.min(r,e);const i=Math.max(o-n,0),s=this[O].slice(n,n+i),u=new P([],{type:arguments[2]});return u[O]=s,u}}function S(e,t,r){Error.call(this,e),this.message=e,this.type=t,r&&(this.code=this.errno=r.code),Error.captureStackTrace(this,this.constructor)}let E;Object.defineProperties(P.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}}),Object.defineProperty(P.prototype,Symbol.toStringTag,{value:"Blob",writable:!1,enumerable:!1,configurable:!0}),S.prototype=Object.create(Error.prototype),S.prototype.constructor=S,S.prototype.name="FetchError";try{E=require("encoding").convert}catch(e){}const x=Symbol("Body internals"),B=t.PassThrough;function A(e){var r=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=n.size;let i=void 0===o?0:o;var s=n.timeout;let u=void 0===s?0:s;null==e?e=null:"string"==typeof e||L(e)||e instanceof P||Buffer.isBuffer(e)||"[object ArrayBuffer]"===Object.prototype.toString.call(e)||ArrayBuffer.isView(e)||e instanceof t||(e=String(e)),this[x]={body:e,disturbed:!1,error:null},this.size=i,this.timeout=u,e instanceof t&&e.on("error",function(e){const t="AbortError"===e.name?e:new S(`Invalid response body while trying to fetch ${r.url}: ${e.message}`,"system",e);r[x].error=t})}function C(){var e=this;if(this[x].disturbed)return A.Promise.reject(new TypeError(`body used already for: ${this.url}`));if(this[x].disturbed=!0,this[x].error)return A.Promise.reject(this[x].error);if(null===this.body)return A.Promise.resolve(Buffer.alloc(0));if("string"==typeof this.body)return A.Promise.resolve(Buffer.from(this.body));if(this.body instanceof P)return A.Promise.resolve(this.body[O]);if(Buffer.isBuffer(this.body))return A.Promise.resolve(this.body);if("[object ArrayBuffer]"===Object.prototype.toString.call(this.body))return A.Promise.resolve(Buffer.from(this.body));if(ArrayBuffer.isView(this.body))return A.Promise.resolve(Buffer.from(this.body.buffer,this.body.byteOffset,this.body.byteLength));if(!(this.body instanceof t))return A.Promise.resolve(Buffer.alloc(0));let r=[],n=0,o=!1;return new A.Promise(function(t,i){let s;e.timeout&&(s=setTimeout(function(){o=!0,i(new S(`Response timeout while trying to fetch ${e.url} (over ${e.timeout}ms)`,"body-timeout"))},e.timeout)),e.body.on("error",function(t){"AbortError"===t.name?(o=!0,i(t)):i(new S(`Invalid response body while trying to fetch ${e.url}: ${t.message}`,"system",t))}),e.body.on("data",function(t){if(!o&&null!==t){if(e.size&&n+t.length>e.size)return o=!0,void i(new S(`content size at ${e.url} over limit: ${e.size}`,"max-size"));n+=t.length,r.push(t)}}),e.body.on("end",function(){if(!o){clearTimeout(s);try{t(Buffer.concat(r))}catch(t){i(new S(`Could not create Buffer from response body for ${e.url}: ${t.message}`,"system",t))}}})})}function L(e){return"object"==typeof e&&"function"==typeof e.append&&"function"==typeof e.delete&&"function"==typeof e.get&&"function"==typeof e.getAll&&"function"==typeof e.has&&"function"==typeof e.set&&("URLSearchParams"===e.constructor.name||"[object URLSearchParams]"===Object.prototype.toString.call(e)||"function"==typeof e.sort)}function R(e){let r,n,o=e.body;if(e.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof t&&"function"!=typeof o.getBoundary&&(r=new B,n=new B,o.pipe(r),o.pipe(n),e[x].body=r,o=n),o}function $(e){const t=e.body;return null===t?0:"string"==typeof t?Buffer.byteLength(t):L(t)?Buffer.byteLength(String(t)):t instanceof P?t.size:Buffer.isBuffer(t)?t.length:"[object ArrayBuffer]"===Object.prototype.toString.call(t)?t.byteLength:ArrayBuffer.isView(t)?t.byteLength:t&&"function"==typeof t.getLengthSync&&(t._lengthRetrievers&&0==t._lengthRetrievers.length||t.hasKnownLength&&t.hasKnownLength())?t.getLengthSync():null}A.prototype={get body(){return this[x].body},get bodyUsed(){return this[x].disturbed},arrayBuffer(){return C.call(this).then(function(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)})},blob(){let e=this.headers&&this.headers.get("content-type")||"";return C.call(this).then(function(t){return Object.assign(new P([],{type:e.toLowerCase()}),{[O]:t})})},json(){var e=this;return C.call(this).then(function(t){try{return JSON.parse(t.toString())}catch(t){return A.Promise.reject(new S(`invalid json response body at ${e.url} reason: ${t.message}`,"invalid-json"))}})},text(){return C.call(this).then(function(e){return e.toString()})},buffer(){return C.call(this)},textConverted(){var e=this;return C.call(this).then(function(t){return function(e,t){if("function"!=typeof E)throw new Error("The package `encoding` must be installed to use the textConverted() function");const r=t.get("content-type");let n,o,i="utf-8";r&&(n=/charset=([^;]*)/i.exec(r));o=e.slice(0,1024).toString(),!n&&o&&(n=/<meta.+?charset=(['"])(.+?)\1/i.exec(o));!n&&o&&(n=/<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(o))&&(n=/charset=(.*)/i.exec(n.pop()));!n&&o&&(n=/<\?xml.+?encoding=(['"])(.+?)\1/i.exec(o));n&&("gb2312"!==(i=n.pop())&&"gbk"!==i||(i="gb18030"));return E(e,"UTF-8",i).toString()}(t,e.headers)})}},Object.defineProperties(A.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}}),A.mixIn=function(e){for(const t of Object.getOwnPropertyNames(A.prototype))if(!(t in e)){const r=Object.getOwnPropertyDescriptor(A.prototype,t);Object.defineProperty(e,t,r)}},A.Promise=global.Promise;const z=/[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/,U=/[^\t\x20-\x7e\x80-\xff]/;function k(e){if(e=`${e}`,z.test(e))throw new TypeError(`${e} is not a legal HTTP header name`)}function F(e){if(e=`${e}`,U.test(e))throw new TypeError(`${e} is not a legal HTTP header value`)}function _(e,t){t=t.toLowerCase();for(const r in e)if(r.toLowerCase()===t)return r}const H=Symbol("map");class q{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0;if(this[H]=Object.create(null),e instanceof q){const t=e.raw(),r=Object.keys(t);for(const e of r)for(const r of t[e])this.append(e,r)}else if(null==e);else{if("object"!=typeof e)throw new TypeError("Provided initializer must be an object");{const t=e[Symbol.iterator];if(null!=t){if("function"!=typeof t)throw new TypeError("Header pairs must be iterable");const r=[];for(const t of e){if("object"!=typeof t||"function"!=typeof t[Symbol.iterator])throw new TypeError("Each header pair must be iterable");r.push(Array.from(t))}for(const e of r){if(2!==e.length)throw new TypeError("Each header pair must be a name/value tuple");this.append(e[0],e[1])}}else for(const t of Object.keys(e)){const r=e[t];this.append(t,r)}}}}get(e){k(e=`${e}`);const t=_(this[H],e);return void 0===t?null:this[H][t].join(", ")}forEach(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,r=N(this),n=0;for(;n<r.length;){var o=r[n];const i=o[0],s=o[1];e.call(t,s,i,this),r=N(this),n++}}set(e,t){t=`${t}`,k(e=`${e}`),F(t);const r=_(this[H],e);this[H][void 0!==r?r:e]=[t]}append(e,t){t=`${t}`,k(e=`${e}`),F(t);const r=_(this[H],e);void 0!==r?this[H][r].push(t):this[H][e]=[t]}has(e){return k(e=`${e}`),void 0!==_(this[H],e)}delete(e){k(e=`${e}`);const t=_(this[H],e);void 0!==t&&delete this[H][t]}raw(){return this[H]}keys(){return I(this,"key")}values(){return I(this,"value")}[Symbol.iterator](){return I(this,"key+value")}}function N(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"key+value";return Object.keys(e[H]).sort().map("key"===t?function(e){return e.toLowerCase()}:"value"===t?function(t){return e[H][t].join(", ")}:function(t){return[t.toLowerCase(),e[H][t].join(", ")]})}q.prototype.entries=q.prototype[Symbol.iterator],Object.defineProperty(q.prototype,Symbol.toStringTag,{value:"Headers",writable:!1,enumerable:!1,configurable:!0}),Object.defineProperties(q.prototype,{get:{enumerable:!0},forEach:{enumerable:!0},set:{enumerable:!0},append:{enumerable:!0},has:{enumerable:!0},delete:{enumerable:!0},keys:{enumerable:!0},values:{enumerable:!0},entries:{enumerable:!0}});const Q=Symbol("internal");function I(e,t){const r=Object.create(M);return r[Q]={target:e,kind:t,index:0},r}const M=Object.setPrototypeOf({next(){if(!this||Object.getPrototypeOf(this)!==M)throw new TypeError("Value of `this` is not a HeadersIterator");var e=this[Q];const t=e.target,r=e.kind,n=e.index,o=N(t,r);return n>=o.length?{value:void 0,done:!0}:(this[Q].index=n+1,{value:o[n],done:!1})}},Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));function D(e){const t=Object.assign({__proto__:null},e[H]),r=_(e[H],"Host");return void 0!==r&&(t[r]=t[r][0]),t}Object.defineProperty(M,Symbol.toStringTag,{value:"HeadersIterator",writable:!1,enumerable:!1,configurable:!0});const V=Symbol("Response internals"),G=r.STATUS_CODES;class K{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};A.call(this,e,t);const r=t.status||200;this[V]={url:t.url,status:r,statusText:t.statusText||G[r],headers:new q(t.headers)}}get url(){return this[V].url}get status(){return this[V].status}get ok(){return this[V].status>=200&&this[V].status<300}get statusText(){return this[V].statusText}get headers(){return this[V].headers}clone(){return new K(R(this),{url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok})}}A.mixIn(K.prototype),Object.defineProperties(K.prototype,{url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}}),Object.defineProperty(K.prototype,Symbol.toStringTag,{value:"Response",writable:!1,enumerable:!1,configurable:!0});const J=Symbol("Request internals"),Z=n.parse,Y=n.format,W="destroy"in t.Readable.prototype;function X(e){return"object"==typeof e&&"object"==typeof e[J]}class ee{constructor(e){let t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};X(e)?t=Z(e.url):(t=e&&e.href?Z(e.href):Z(`${e}`),e={});let n=r.method||e.method||"GET";if(n=n.toUpperCase(),(null!=r.body||X(e)&&null!==e.body)&&("GET"===n||"HEAD"===n))throw new TypeError("Request with GET/HEAD method cannot have body");let o=null!=r.body?r.body:X(e)&&null!==e.body?R(e):null;A.call(this,o,{timeout:r.timeout||e.timeout||0,size:r.size||e.size||0});const i=new q(r.headers||e.headers||{});if(null!=r.body){const e=function(e){const t=e.body;return null===t?null:"string"==typeof t?"text/plain;charset=UTF-8":L(t)?"application/x-www-form-urlencoded;charset=UTF-8":t instanceof P?t.type||null:Buffer.isBuffer(t)?null:"[object ArrayBuffer]"===Object.prototype.toString.call(t)?null:ArrayBuffer.isView(t)?null:"function"==typeof t.getBoundary?`multipart/form-data;boundary=${t.getBoundary()}`:null}(this);null===e||i.has("Content-Type")||i.append("Content-Type",e)}let s=X(e)?e.signal:null;if("signal"in r&&(s=r.signal),null!=s&&!function(e){const t=e&&"object"==typeof e&&Object.getPrototypeOf(e);return!(!t||"AbortSignal"!==t.constructor.name)}(s))throw new TypeError("Expected signal to be an instanceof AbortSignal");this[J]={method:n,redirect:r.redirect||e.redirect||"follow",headers:i,parsedURL:t,signal:s},this.follow=void 0!==r.follow?r.follow:void 0!==e.follow?e.follow:20,this.compress=void 0!==r.compress?r.compress:void 0===e.compress||e.compress,this.counter=r.counter||e.counter||0,this.agent=r.agent||e.agent}get method(){return this[J].method}get url(){return Y(this[J].parsedURL)}get headers(){return this[J].headers}get redirect(){return this[J].redirect}get signal(){return this[J].signal}clone(){return new ee(this)}}function te(e){Error.call(this,e),this.type="aborted",this.message=e,Error.captureStackTrace(this,this.constructor)}A.mixIn(ee.prototype),Object.defineProperty(ee.prototype,Symbol.toStringTag,{value:"Request",writable:!1,enumerable:!1,configurable:!0}),Object.defineProperties(ee.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0}}),te.prototype=Object.create(Error.prototype),te.prototype.constructor=te,te.prototype.name="AbortError";const re=t.PassThrough,ne=n.resolve;function oe(e,n){if(!oe.Promise)throw new Error("native promise missing, set fetch.Promise to your favorite alternative");return A.Promise=oe.Promise,new oe.Promise(function(s,u){const a=new ee(e,n),c=function(e){const r=e[J].parsedURL,n=new q(e[J].headers);if(n.has("Accept")||n.set("Accept","*/*"),!r.protocol||!r.hostname)throw new TypeError("Only absolute URLs are supported");if(!/^https?:$/.test(r.protocol))throw new TypeError("Only HTTP(S) protocols are supported");if(e.signal&&e.body instanceof t.Readable&&!W)throw new Error("Cancellation of streamed requests with AbortSignal is not supported in node < 8");let o=null;if(null==e.body&&/^(POST|PUT)$/i.test(e.method)&&(o="0"),null!=e.body){const t=$(e);"number"==typeof t&&(o=String(t))}return o&&n.set("Content-Length",o),n.has("User-Agent")||n.set("User-Agent","node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"),e.compress&&!n.has("Accept-Encoding")&&n.set("Accept-Encoding","gzip,deflate"),n.has("Connection")||e.agent||n.set("Connection","close"),Object.assign({},r,{method:e.method,headers:D(n),agent:e.agent})}(a),l=("https:"===c.protocol?o:r).request,f=a.signal;let d=null;const p=function(){let e=new te("The user aborted a request.");u(e),a.body&&a.body instanceof t.Readable&&a.body.destroy(e),d&&d.body&&d.body.emit("error",e)};if(f&&f.aborted)return void p();const h=function(){p(),b()},y=l(c);let m;function b(){y.abort(),f&&f.removeEventListener("abort",h),clearTimeout(m)}f&&f.addEventListener("abort",h),a.timeout&&y.once("socket",function(e){m=setTimeout(function(){u(new S(`network timeout at: ${a.url}`,"request-timeout")),b()},a.timeout)}),y.on("error",function(e){u(new S(`request to ${a.url} failed, reason: ${e.message}`,"system",e)),b()}),y.on("response",function(e){clearTimeout(m);const t=function(e){const t=new q;for(const r of Object.keys(e))if(!z.test(r))if(Array.isArray(e[r]))for(const n of e[r])U.test(n)||(void 0===t[H][r]?t[H][r]=[n]:t[H][r].push(n));else U.test(e[r])||(t[H][r]=[e[r]]);return t}(e.headers);if(oe.isRedirect(e.statusCode)){const r=t.get("Location"),n=null===r?null:ne(a.url,r);switch(a.redirect){case"error":return u(new S(`redirect mode is set to error: ${a.url}`,"no-redirect")),void b();case"manual":if(null!==n)try{t.set("Location",n)}catch(e){u(e)}break;case"follow":if(null===n)break;if(a.counter>=a.follow)return u(new S(`maximum redirect reached at: ${a.url}`,"max-redirect")),void b();const r={headers:new q(a.headers),follow:a.follow,counter:a.counter+1,agent:a.agent,compress:a.compress,method:a.method,body:a.body,signal:a.signal};return 303!==e.statusCode&&a.body&&null===$(a)?(u(new S("Cannot follow redirect with body being a readable stream","unsupported-redirect")),void b()):(303!==e.statusCode&&(301!==e.statusCode&&302!==e.statusCode||"POST"!==a.method)||(r.method="GET",r.body=void 0,r.headers.delete("content-length")),s(oe(new ee(n,r))),void b())}}e.once("end",function(){f&&f.removeEventListener("abort",h)});let r=e.pipe(new re);const n={url:a.url,status:e.statusCode,statusText:e.statusMessage,headers:t,size:a.size,timeout:a.timeout},o=t.get("Content-Encoding");if(!a.compress||"HEAD"===a.method||null===o||204===e.statusCode||304===e.statusCode)return d=new K(r,n),void s(d);const c={flush:i.Z_SYNC_FLUSH,finishFlush:i.Z_SYNC_FLUSH};if("gzip"==o||"x-gzip"==o)return r=r.pipe(i.createGunzip(c)),d=new K(r,n),void s(d);if("deflate"!=o&&"x-deflate"!=o)d=new K(r,n),s(d);else{e.pipe(new re).once("data",function(e){r=8==(15&e[0])?r.pipe(i.createInflate()):r.pipe(i.createInflateRaw()),d=new K(r,n),s(d)})}}),function(e,t){const r=t.body;null===r?e.end():"string"==typeof r?(e.write(r),e.end()):L(r)?(e.write(Buffer.from(String(r))),e.end()):r instanceof P?(e.write(r[O]),e.end()):Buffer.isBuffer(r)?(e.write(r),e.end()):"[object ArrayBuffer]"===Object.prototype.toString.call(r)?(e.write(Buffer.from(r)),e.end()):ArrayBuffer.isView(r)?(e.write(Buffer.from(r.buffer,r.byteOffset,r.byteLength)),e.end()):r.pipe(e)}(y,a)})}function ie(e,t){return void 0===t&&(t=3),d(this,void 0,void 0,function(){var r,n;return p(this,function(o){switch(o.label){case 0:r=--t,o.label=1;case 1:return o.trys.push([1,3,,4]),[4,e()];case 2:return[2,o.sent()];case 3:if(n=o.sent(),r>0)return[2,ie(e,r)];throw n;case 4:return[2]}})})}oe.isRedirect=function(e){return 301===e||302===e||303===e||307===e||308===e},oe.Promise=global.Promise;var se=function(e){var t=e.baseUrl,r=e.apiKey,n=e.fetchFn,o=e.maxRetries,i=void 0===o?3:o,s=e.debug;if(!t)throw new Error("BaseUrl is mandatory");if(!r)throw new Error("apiKey is mandatory");var u=oe;n?u=n:"undefined"!=typeof window&&(u=window.fetch);var a,c=(a=!!s,function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];a&&console.log.apply(console,e)}),l={Authorization:r};c("Aard client inizialized with:\n","- api key "+r+"\n","- base url "+t+"\n","- max retries "+i+"\n");return{transformEvent:function(e,t){return g.apply(void 0,t)(e)},saveFragment:function(e){return ie(function(){return u(t+"/fragments",{method:"POST",headers:f({},l,{"Content-Type":"application/json; charset=utf-8"}),body:JSON.stringify(e)}).then(function(e){return e.json()}).then(function(e){return e.hash})},i).then(function(t){return c("Fragment saved with hash "+t,e),t}).catch(function(t){c("ERROR: Failed to save Fragment",e,t)})},sendEvent:function(e){return ie(function(){return u(t+"/records",{method:"POST",headers:f({},l,{"Content-Type":"application/json; charset=utf-8"}),body:JSON.stringify(e)}).then(function(e){return e.json()}).then(function(e){return e.accepted})},i).then(function(t){return c("Event "+(t?"recorder":"not recorded"),e),t}).catch(function(t){c("ERROR: Failed to send event",e,t)})}}},ue="stag",ae=function(e){return"https://aard-gateway-"+e+".inyourarea.co.uk"},ce=function(){function e(e){var t=this,r=e.projectName,n=e.apiKey,o=e.session,i=void 0===o||o,s=e.fetchFn,u=e.maxRetries,a=e.environment,c=void 0===a?ue:a,l=e.baseUrlCreator,f=void 0===l?ae:l,d=e.transformers,p=void 0===d?[]:d,h=e.debug;if(this.fragments=new Map,this.eventQueue=[],this.busyCount=0,this.getClient=function(){return t.client},!r)throw new Error("ProjectName is mandatory");var y=f(c);this.projectName=r,this.session=i,this.transformers=new Set(p),this.client=se({apiKey:n,baseUrl:y,fetchFn:s,maxRetries:u,debug:h})}return e.prototype.registerFragment=function(e,t){return d(this,void 0,void 0,function(){var r;return p(this,function(n){switch(n.label){case 0:return this.busyCount++,[4,this.client.saveFragment(t)];case 1:return(r=n.sent())&&this.fragments.set(e,r),this.busyCount--,this.tryConsumeQueue(),[2]}})})},e.prototype.addFragmentHash=function(e,t){this.fragments.set(e,t)},e.prototype.getFragments=function(){return this.fragments},e.prototype.getFragment=function(e){return this.fragments.get(e)},e.prototype.getFragmentsHashes=function(){return Array.from(this.fragments.values())},e.prototype.removeFragment=function(e){this.fragments.delete(e)},e.prototype.addTransformer=function(e){this.transformers.add(e)},e.prototype.removeTransformer=function(e){this.transformers.delete(e)},e.prototype.getTransformersList=function(){return Array.from(this.transformers.values())},e.prototype.sendEvent=function(e,t,r){var n=t.dimensions,o=t.plugins,i=t.unit,s=void 0===i?"Unit":i,u=t.value,a=void 0===u?1:u;return this.addEventToQueue(e,{dimensions:n,plugins:o,unit:s,value:a},r)},e.prototype.sendPageView=function(e,t){var r=e.dimensions,n=e.plugins,o=void 0===n?[]:n;return this.addEventToQueue("pageview",{dimensions:r,plugins:o,unit:"Unit",value:1},t)},e.prototype.transformEvent=function(e,t){void 0===t&&(t=[]);var r=this.getTransformersList().concat(this.getFragmentsHashes().map(function(e){return w(e)}),t);return this.client.transformEvent(e,r)},e.prototype.addEventToQueue=function(e,t,r){var n=t.dimensions,o=t.plugins,i=void 0===o?[]:o,s=t.unit,u=void 0===s?"Unit":s,a=t.value,c=void 0===a?1:a,l=this.projectName,f=this.session,d=new Date,p={projectName:l,metricName:e,dimensions:n,plugins:i,timestamp:d.valueOf()+6e4*d.getTimezoneOffset(),timezone:d.getTimezoneOffset()/60*-1,session:f,unit:u,value:c};this.eventQueue.push([p,r||[]]),this.tryConsumeQueue()},e.prototype.tryConsumeQueue=function(){if(!this.busyCount){var e=this.eventQueue.shift();if(e){var t=e[0],r=e[1],n=this.transformEvent(t,r);this.client.sendEvent(n),this.tryConsumeQueue()}}},e}();e.Recorder=ce,e.plugins=l,e.transformers=j,Object.defineProperty(e,"__esModule",{value:!0})});