@iotize/tap
Version:
IoTize Device client for Javascript
16 lines (14 loc) • 39.9 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@iotize/tap/client/api"),require("@iotize/common/byte-converter"),require("@iotize/common/byte-stream"),require("@iotize/common/debug"),require("@iotize/common/error"),require("rxjs"),require("rxjs/operators"),require("buffer"),require("@iotize/common/tlv")):"function"==typeof define&&define.amd?define("@iotize/tap/client/impl",["exports","@iotize/tap/client/api","@iotize/common/byte-converter","@iotize/common/byte-stream","@iotize/common/debug","@iotize/common/error","rxjs","rxjs/operators","buffer","@iotize/common/tlv"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).iotize=e.iotize||{},e.iotize.tap=e.iotize.tap||{},e.iotize.tap.client=e.iotize.tap.client||{},e.iotize.tap.client.impl={}),e.iotize.tap.client.api,e.byteConverter,e.byteStream,e.debug$1,e.error,e.rxjs,e.rxjs.operators,e.buffer,e.tlv)}(this,(function(e,t,r,n,o,i,a,u,s,c){"use strict";
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */var p=function(e,t){return p=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},p(e,t)};function d(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}p(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}Object.create;function f(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function l(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)a.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return a}Object.create;var h,y,v=o.createDebugger("@iotize/tap/client/impl");e.ConverterError=function(e){function t(t,r,n){var o=e.call(this,r,t)||this;return o.cause=n,o}return d(t,e),t.unexpectedBufferSize=function(e,r){return new t(t.Code.UnexpectedBufferSizeError,"Expected buffer of "+e+" byte(s) but found only "+r.length+" byte(s)")},t.nullBufferError=function(e){return new t(t.Code.NullBufferError,e)},t.valueTooBigError=function(e,r){return new t(t.Code.ValueTooBigError,"Value "+e+" is not acceptable. Maximum authorized value is "+r+".")},t}(i.CodeError),y=e.ConverterError||(e.ConverterError={}),(h=y.Code||(y.Code={})).UnexpectedBufferSizeError="UnexpectedBufferSizeError",h.NullBufferError="NullBufferError",h.ValueTooBigError="ConverterErrorValueTooBigError";var m,g=function(){function t(e){this.options=e}return t.uint8=function(e){return void 0===e&&(e=!1),new t({signed:!1,sizeOf:8,leastSignificantBitFirst:e})},t.uint16=function(e){return void 0===e&&(e=!1),new t({signed:!1,sizeOf:16,leastSignificantBitFirst:e})},t.uint32=function(e){return void 0===e&&(e=!1),new t({signed:!1,sizeOf:32,leastSignificantBitFirst:e})},t.int8=function(e){return void 0===e&&(e=!1),new t({signed:!0,sizeOf:8,leastSignificantBitFirst:e})},t.int16=function(e){return void 0===e&&(e=!1),new t({signed:!0,sizeOf:16,leastSignificantBitFirst:e})},t.int32=function(e){return void 0===e&&(e=!1),new t({signed:!0,sizeOf:32,leastSignificantBitFirst:e})},t.prototype.decode=function(r){if(8*r.length<this.options.sizeOf)throw e.ConverterError.unexpectedBufferSize(this.options.sizeOf/8,r);return t.fromBytes(r,this.options.sizeOf/8,this.options.signed,this.options.leastSignificantBitFirst)},t.prototype.encode=function(t){var r=Math.pow(2,this.options.sizeOf)-1;if(t>r)throw e.ConverterError.valueTooBigError(t,r);for(var n=new Uint8Array(this.options.sizeOf>>3),o=0;o<n.length;o++){var i=8*(n.length-o-1);n[o]=t>>i&255}return this.options.leastSignificantBitFirst&&n.reverse(),n},t.toOpaqueMsb=function(t,r){var n=Math.pow(2,r)-1;if(t>n)throw e.ConverterError.valueTooBigError(t,n);if(8===r)return new Uint8Array([255&t]);if(16===r)return new Uint8Array([t>>8&255,255&t]);if(32===r)return new Uint8Array([t>>24&255,t>>16&255,t>>8&255,255&t]);throw new Error("Invalid size "+r+". Must be 8, 16 or 32")},t.fromOpaqueMsb=function(e,t){if(t||(t=8*e.length),8===t)return 255&e[0];if(16===t)return(255&e[1])+((255&e[0])<<8);if(32===t)return(255&e[3])+((255&e[2])<<8)+((255&e[1])<<16)+((255&e[0])<<24);throw new Error("Invalid size "+t+". Must be 8, 16 or 32")},t.fromBytes=function(e,t,r,n){n&&(e=e.reverse());for(var o,i=0,a=0,u=0;u<t;u++){if(o=8*(t-u-1),a>(i+=(255&e[u])<<o>>>0)&&!r)throw new Error("Overflow. Last value: "+a+" but new is "+i);a=i}return r&&128==(128&e[0])&&(i=-(Math.pow(2,8*t)-i)),i},t}(),w=function(){function e(e){this.polynomial=e}return e.mpeg2=function(){return m||(m=new e(e.POLYNOMIAL_CRC32_MPEG2)),m},e.prototype.compute=function(t,r){return void 0===r&&(r=e.FIRST_VALUE),t instanceof Uint32Array?e.fromWord(t,r,this.polynomial):e.fromBytes(t,r,this.polynomial)},e.fromBytes=function(t,r,n){if(void 0===r&&(r=e.FIRST_VALUE),void 0===n&&(n=e.POLYNOMIAL_CRC32_MPEG2),t.length%e.MODULO!=0)throw new Error("Cannot compute CRC, input size must be a multiple of 4. Length is "+t.length+" % "+e.MODULO+" = "+t.length%e.MODULO);for(var o=new Uint32Array(t.length/4),i=0;i<o.byteLength;i++)o[i]=g.fromOpaqueMsb(t.slice(4*i,4*(i+1)),32);return e.fromWord(o,r,n)},e.fromWord=function(t,r,n){if(void 0===r&&(r=e.FIRST_VALUE),void 0===n&&(n=e.POLYNOMIAL_CRC32_MPEG2),!t)throw new Error("Buffer is null");if(t.byteLength>16777216)throw new Error("Buffers larger than 16MB");for(var o,i=0;i<t.length;i++)o=t[i],r=e.appendCrcNumber(r,o,n);return r},e.appendCrcNumber=function(e,t,r){e^=t;for(var n=0;n<32;n++)e=2147483648&e?(e<<1^r)>>>0:e<<1>>>0;return e},e}();function T(e,t){return"string"==typeof e?t[e]:e}w.POLYNOMIAL_CRC32_MPEG2=79764919,w.MODULO=4,w.FIRST_VALUE=4294967295;var E=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return d(t,e),t.fromArray=function(e){return new t(r.typedArrayToBuffer(e))},t.create=function(e){return e instanceof Uint8Array?t.fromArray(e):e},t.prototype.readStr=function(e){return String.fromCharCode.apply(null,this.readBytes(e))},t.prototype.readString=function(e){return void 0===e&&(e=this.byteLeft),this.readStr(e)},t.prototype.readStringTerminator=function(e){for(var t="";;){var r=this.readU1(),n=String.fromCharCode(r);if(n===e)break;t+=n}return t},t.prototype.readU2=function(){return this._isBigEndian?this.readU2be():this.readU2le()},t.prototype.readU4=function(){return this._isBigEndian?this.readU4be():this.readU4le()},t.prototype.readF4=function(){return this._isBigEndian?this.readF4be():this.readF4le()},t.prototype.subStream=function(e){return t.fromArray(this.readBytes(e))},t}(n.KaitaiStreamReader),C=function(e){function t(t,r,n){void 0===t&&(t=512),void 0===n&&(n=!0);return"number"==typeof t&&(t=new ArrayBuffer(t)),e.call(this,t,r,n)||this}return d(t,e),t.create=function(e){return new t(new ArrayBuffer(e))},t.prototype.writeFunction=function(e,t,r,n){switch(e){case"crc32":return this.addCRC(t);case"padding":if(r)return v("Padding is already set"),this.writeBytes(r);if(null==typeof n)throw new Error("Padding function expect padding size as a second argument. Args: "+JSON.stringify(arguments));return this.addPadding(n);default:throw new Error("Invalid writer function type: "+e)}},t.prototype.addPadding=function(e){return this.writeBytes(new Uint8Array(e)),this},t.prototype.addCRC=function(e){var t=this.toBytes;e&&e.offset&&(t=t.slice(e.offset));var r=w.fromBytes(t);return this.writeU4(r),this},t.prototype.writeUnsigned=function(e,t){return this.writeU(e,t),this},t.prototype.writeU4=function(e){return this.writeU(e,4),this},t.prototype.writeU2=function(e){return this.writeU(e,2),this},t.prototype.writeU1=function(e){return this.writeU(e,1),this},t.prototype.writeF4=function(e){return this.writeF(e,4),this},t.prototype.writeFloat=function(e,t){return this.writeF(e,t),this},t.prototype.writeSigned=function(e,t){return this.writeSigned(e,t),this},t.prototype.writeString=function(e,t){return void 0===t&&(t=(null==e?void 0:e.length)||0),this.writeStr(e||"",t)},t.prototype.writeStr=function(e,t){void 0===t&&(t=e.length);for(var r=1,n=Math.min(e.length,t);r<=n;r++)this.writeByte(e.charCodeAt(r-1));var o=t-n;return o>0&&this.writeBytes(new Uint8Array(o)),this},t.prototype.writeBitsInt=function(e,t){return this.writeB(e,t),this},t.prototype.writeBits=function(e,t){return this.writeB(e,t),this},t.prototype.writeBoolean=function(e,t){return this.writeBits(e?1:0,t),this},t}(n.KaitaiStreamWriter);E.prototype.readApduRequest=function(){var e={};return e.header=this.readApduRequestHeader(),e.data=this.readBytes(e.header.lc),e},E.prototype.readApduRequestHeader=function(){var e={};return e.cla=this.readUnsigned(1),e.ins=this.readUnsigned(1),e.p1=this.readUnsigned(1),e.p2=this.readUnsigned(1),e.lc=this.readUnsigned(1),e},E.prototype.readApduResponse=function(){var e={};return e.data=this.readBytes(this.getStreamSize()-2),e.status=this.readUnsigned(2),e},E.prototype.readTapRequestEncrypted=function(){var e={};return e.header=this.readApduRequestHeader(),e.request=this.readTapRequestFrame(),e},E.prototype.readTapApduRequest=function(){return{}},E.prototype.readTapEncryptedFrame=function(){var e={};return e.id=this.readUnsigned(2),e.len=this.readUnsigned(2),e.payload=this.readBytes(e.len),e.padding=this.readBytes((16-(4+(void 0===e.len?0:e.len)+4)%16)%16),e.crc=this.readUnsigned(4),e},E.prototype.readTapRequestFrame=function(){var e={};return e.header=this.readTapRequestFrameHeader(),e.payload=this.readBytes(),e},E.prototype.readTapRequestFrameHeader=function(){var e={};return e.methodType=this.readUnsigned(1),e.path=this.readTapRequestFramePath(),e},E.prototype.readTapRequestFramePath=function(){var e={};return e.objectId=this.readUnsigned(2),e.objectInstanceId=this.readUnsigned(2),e.resourceId=this.readUnsigned(2),e},E.prototype.readTapResponseFrame=function(){var e={};return e.status=this.readUnsigned(1),e.data=this.readBytes(),e},C.prototype.writeApduRequest=function(e){return this.writeApduRequestHeader(e.header),this.writeBytes(e.data,e.header.lc),this},C.prototype.writeApduRequestHeader=function(e){return this.writeUnsigned(e.cla,1),this.writeUnsigned(e.ins,1),this.writeUnsigned(e.p1,1),this.writeUnsigned(e.p2,1),this.writeUnsigned(e.lc,1),this},C.prototype.writeApduResponse=function(e){return this.writeBytes(e.data,void 0),this.writeUnsigned(e.status,2),this},C.prototype.writeTapRequestEncrypted=function(e){return this.writeApduRequestHeader(e.header),this.writeTapRequestFrame(e.request),this},C.prototype.writeTapApduRequest=function(e){return this},C.prototype.writeTapEncryptedFrame=function(e){return this.writeUnsigned(e.id,2),this.writeUnsigned(e.len,2),this.writeBytes(e.payload,e.len),this.writeFunction("padding",void 0,e.padding,(16-(4+(void 0===e.len?0:e.len)+4)%16)%16),this.writeFunction("crc32",void 0,e.crc,4),this},C.prototype.writeTapRequestFrame=function(e){return this.writeTapRequestFrameHeader(e.header),this.writeBytes(e.payload),this},C.prototype.writeTapRequestFrameHeader=function(e){return this.writeBitsInt(T(e.methodType,t.TapRequestFrame.MethodType),8),this.writeTapRequestFramePath(e.path),this},C.prototype.writeTapRequestFramePath=function(e){return this.writeUnsigned(e.objectId,2),this.writeUnsigned(e.objectInstanceId,2),this.writeUnsigned(e.resourceId,2),this},C.prototype.writeTapResponseFrame=function(e){return this.writeUnsigned(e.status,1),this.writeBytes(e.data),this};var b=function(){function e(){}return e.prototype.encode=function(e,t){return void 0===t&&(t=new C),t.writeApduRequest(e),t.toBytes},e.prototype.decode=function(e){return(e instanceof E?e:E.create(e)).readApduRequest()},e}(),R=function(){function e(){}return e.prototype.encode=function(e,t){return void 0===t&&(t=new C),t.writeApduResponse(e),t.toBytes},e.prototype.decode=function(e){return(e instanceof E?e:E.create(e)).readApduResponse()},e}(),S=function(){function e(){}return e.prototype.encode=function(e,t){return void 0===t&&(t=new C),t.writeTapRequestEncrypted(e),t.toBytes},e.prototype.decode=function(e){return(e instanceof E?e:E.create(e)).readTapRequestEncrypted()},e}(),A=(function(){function e(){}e.prototype.encode=function(e,t){return void 0===t&&(t=new C),t.writeTapApduRequest(e),t.toBytes},e.prototype.decode=function(e){return(e instanceof E?e:E.create(e)).readTapApduRequest()}}(),function(){function e(){}return e.prototype.encode=function(e,t){return void 0===t&&(t=new C),t.writeTapEncryptedFrame(e),t.toBytes},e.prototype.decode=function(e){return(e instanceof E?e:E.create(e)).readTapEncryptedFrame()},e}()),I=function(){function e(){}return e.prototype.encode=function(e,t){return void 0===t&&(t=new C),t.writeTapRequestFrame(e),t.toBytes},e.prototype.decode=function(e){return(e instanceof E?e:E.create(e)).readTapRequestFrame()},e}(),U=function(){function e(){}return e.prototype.encode=function(e,t){return void 0===t&&(t=new C),t.writeTapResponseFrame(e),t.toBytes},e.prototype.decode=function(e){return(e instanceof E?e:E.create(e)).readTapResponseFrame()},e}();function _(e){var r,n=(new I).encode(e);switch(e.header.methodType){case t.TapRequestFrame.MethodType.GET:r=t.TapApduRequest.MethodType.GET;break;case t.TapRequestFrame.MethodType.PUT:case t.TapRequestFrame.MethodType.POST:r=t.TapApduRequest.MethodType.PUT_OR_POST;break;default:throw new Error('Internal error: request type "'+e.header.methodType+'" is invalid')}return{header:{cla:t.TapApduRequest.Default.CLA,ins:r,p1:0,p2:0,lc:n.length},data:n}}e.TapRequestFrameBuilder=function(){function e(){}return e.parsePath=function(t){if(!t||0===t.length)throw new Error("Missing LWM2M path, it must not be empty");var r=(t=t.trim()).match(e.PATH_EXPRESSION);if(!r||0===r.length)throw new Error('Invalid LWM2M path "'+t+'", it does not match expected format');var n={objectId:this.validateId(parseInt(r[1])),objectInstanceId:r[2]?parseInt(r[2]):65535,resourceId:parseInt(r[3])};return r[4]&&(n.resourceInstanceId=parseInt(r[4],10)),n},e.GET=function(r,n){return e.create(t.TapRequestFrame.MethodType.GET,r,n)},e.PUT=function(r,n){return e.create(t.TapRequestFrame.MethodType.PUT,r,n)},e.POST=function(r,n){return e.create(t.TapRequestFrame.MethodType.POST,r,n)},e.create=function(t,r,n){return{header:{path:e.parsePath(r),methodType:t},payload:n||new Uint8Array}},e.validateId=function(t){if(t<0||t>e.MAX_ID)throw new Error('Invalid identifier "'+t+'". It must be a number between '+t+" and "+e.MAX_ID);return t},e}(),e.TapRequestFrameBuilder.MAX_ID=65535,(e.TapRequestFrameBuilder||(e.TapRequestFrameBuilder={})).PATH_EXPRESSION=/^\/?([0-9]+)\/([0-9]+)?\/([0-9]+)\/?([0-9]+)?$/;var q,B=function(){function n(){}return n.toString=function(e,o){var i=t.TapRequestFrame.MethodType[e.header.methodType]+" "+n.pathToString(e.header.path,o);return e.payload&&e.payload.length>0&&(i+=" 0x"+r.bufferToHexString(e.payload)),i},n.pathToString=function(t,r){var n=t.resourceInstanceId;return"/"+t.objectId+"/"+(t.objectInstanceId===e.TapRequestFrameBuilder.MAX_ID?(null==r?void 0:r.printMaxId)?t.objectInstanceId:"":t.objectInstanceId)+"/"+t.resourceId+(n?"/"+n:"")},n}(),x={0:"The request was successful",65:"Create request was successful",66:"Delete request was successful",68:"Update request was successful",69:"The server has fulfilled the request and sent a response",70:"The server is busy",128:"Bad request. Meaning device cannot understand your request.",129:"Current user is not authorized to access this ressource",132:"The server has not found anything matching the Request",133:"Current user is not authorized to access this ressource",134:"Given parameters are not acceptable",135:"Given resource is not available with the current TAP configuration.",160:"Internal server error",161:"This resource has not been implemented yet",163:"Service is currently unavailable. Try again later.",164:"Writing non volatible memory failed",165:"Tap was not able to connect to the target",166:"Target power failure",167:"Non volatile memory is full",168:"It means we can't access this resource because someone is already connected to this device and he has the priority over us.",169:"Response is bigger than you current protocol limit",176:"Target protocol error",177:"Target protocol is busy",178:"Target protocol error",179:"Target protocol parameters are not valid",180:"Target protocol is forbidden",181:"Target protocol data are not the one expected. For example a CRC error.",182:"Target protocol communication error",183:"Target protocol lost communication",184:"Target protocol invalid parameter",185:"Internal error with target communication",186:"Operation aborted because one of the command did not return the expected result code.",187:"Target protocol is not implemented"};e.TapClientError=function(e){function n(t,r,n){var o=e.call(this,r,t)||this;return o.cause=n,o}return d(n,e),n.illegalArgument=function(e){return new n(n.Code.IllegalArgumentError,e)},n.illegalStateError=function(e){return new n(n.Code.IllegalStateError,e)},n.encodeRequestError=function(e,t){return new n(n.Code.EncodeRequestError,"Cannot encode this request: "+e+". Cause: "+t,t)},n.decodeResponseError=function(e,t){return new n(n.Code.DecodeResponseError,"Cannot decode response to command "+(t instanceof Uint8Array?"0x"+r.bufferToHexString(t):B.toString(t))+". Cause: "+e,e)},n.notConnectedError=function(){return new n(n.Code.NotConnectedError,"Trying to execute command but device is not connected")},n.cannotDecodeResponseError=function(e,t){return new n(n.Code.UnexpectedTapResponse,"Received from device an unexpected response that cannot be decoded ("+e.message+"). Frame: 0x"+r.bufferToHexString(t))},n.unexpectedApduStatusCode=function(e){return new n(n.Code.UnexpectedApduResponseStatus,"Received from device an unexpected response with an invalid APDU status code 0x"+e.status.toString(16)+"\n but expecting 0x"+t.ApduResponse.Status.OK.toString(16))},n.cannotEncodeRequest=function(e,t){return new n(n.Code.CannotEncodeRequest,"Cannot encode request "+t+": "+e.message)},n}(i.CodeError),function(e){e.NotConnectedError="TapClientErrorNotConnected",e.EncodeRequestError="TapClientErrorEncodeRequest",e.IllegalArgumentError="TapClientErrorIllegalArgument",e.IllegalStateError="TapClientErrorIllegalState",e.DecodeResponseError="TapClientErrorDecodeResponse",e.UnexpectedTapResponse="TapClientErrorUnexpectedTapResponse",e.UnexpectedApduResponseStatus="TapClientErrorUnexpectedApduResponseStatus",e.CannotEncodeRequest="TapClientErrorCannotEncodeRequest",e.TapClientResponseStatusError="TapClientErrorResponseStatus"}((q=e.TapClientError||(e.TapClientError={})).Code||(q.Code={}));!function(t){function r(n,o){var i=t.call(this,e.TapClientError.Code.TapClientResponseStatusError,r.createErrorMessage(n,o))||this;return i.response=n,i.request=o,i}d(r,t),r.createErrorMessage=function(e,t){var r=e.status,n="Tap request failed. ";return t&&(n="Tap request "+B.toString(t)+" failed. "),n+=(r in x?x[r]:"an unknown error")+" (code=0x"+r.toString(16)+")"}}(e.TapClientError);var O=function(){function t(){}return t.prototype.encode=function(t){try{var r=new C(6+t.payload.length+1);return r.writeApduRequest(_(t)),r.toBytes}catch(r){throw r instanceof e.TapClientError?r:e.TapClientError.cannotEncodeRequest(r,t)}},t.prototype.decode=function(e){var t=e instanceof E?e:E.create(e);t.readApduRequestHeader();return t.readTapRequestFrame()},t}(),F=function(){function r(){}return r.prototype.encode=function(e){var r=new C,n=new C;return n.writeTapResponseFrame(e),r.writeApduResponse({data:n.toBytes,status:t.ApduResponse.Status.OK}),r.toBytes},r.prototype.decode=function(r){try{var n=(r instanceof E?r:E.create(r)).readApduResponse();if(n.status!==t.ApduResponse.Status.OK)throw e.TapClientError.unexpectedApduStatusCode(n);return E.fromArray(n.data).readTapResponseFrame()}catch(t){throw t instanceof e.TapClientError?t:e.TapClientError.cannotDecodeResponseError(t,r instanceof E?r.toBytes:r)}},r}(),P=new O,z=new F,M=function(){function e(e){this.target=e,this.interceptors=[]}return e.prototype.addInterceptor=function(e){return this.interceptors.push("function"==typeof e?{intercept:e}:e),this},e.prototype.execute=function(e){var t=this,r={index:0,run:function(e){return r.index<t.interceptors.length?(r.index++,t.interceptors[r.index-1].intercept(e,{handle:function(e){return r.run(e)}})):t.target(e)}};return r.run(e)},e}(),L="Client",N=function(){function t(e,t){var r=this;this._onProtocolChange=new a.Subject,this._commandEncoder=e,this._responseDecoder=t,this.protocols={},this._interceptorChain=new M((function(e){try{var t=e.request;return r._command(t)}catch(e){return a.throwError(e)}}))}return t.create=function(e){var r=new t(P,z);return e&&r.addComProtocol(e),r},Object.defineProperty(t.prototype,"interceptorChain",{get:function(){return this._interceptorChain},enumerable:!1,configurable:!0}),t.prototype.addInterceptor=function(e){return this.interceptorChain.addInterceptor(e),this},t.prototype.isConnected=function(){return this.hasProtocol(this.currentProtocolId)&&this.getCurrentProtocol().isConnected()},Object.defineProperty(t.prototype,"protocol",{get:function(){return this.getCurrentProtocol()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"commandEncoder",{get:function(){return this._commandEncoder},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"responseDecoder",{get:function(){return this._responseDecoder},enumerable:!1,configurable:!0}),t.prototype.getCurrentProtocol=function(){if(!this.currentProtocolId)throw e.TapClientError.illegalStateError("Tap client protocol is required");if(!this.hasProtocol(this.currentProtocolId))throw e.TapClientError.illegalArgument("Protocol "+this.currentProtocolId+" does not exist");return this.protocols[this.currentProtocolId]},t.prototype.addComProtocol=function(e,t){return void 0===t&&(t="default"),this.protocols[t]=e,this.currentProtocolId||(this.currentProtocolId=t),this},t.prototype.switchProtocol=function(t){if(!this.hasProtocol(t))throw e.TapClientError.illegalArgument("Unkonwn protocol: "+t);var r=this.getCurrentProtocol();return this.currentProtocolId=t,v(L,"Changing protocol to: "+t),this._onProtocolChange.next({newProtocol:this.getCurrentProtocol(),oldProtocol:r}),this},t.prototype.useComProtocol=function(e){var t;return"string"==typeof e?t=e:(t=e.constructor.name,this.addComProtocol(e,t)),this.switchProtocol(t),this},t.prototype.hasProtocol=function(e){return e in this.protocols},t.prototype.connect=function(){try{return this.getCurrentProtocol().connect()}catch(e){return a.throwError(e)}},t.prototype.disconnect=function(){try{return this.getCurrentProtocol().disconnect()}catch(e){return a.throwError(e)}},t.prototype.request=function(e){return this._interceptorChain.execute({request:e,client:this})},t.prototype.send=function(t){var r=this;try{return this.getCurrentProtocol().send(t).pipe(u.map((function(n){try{return r._responseDecoder.decode(n)}catch(r){throw e.TapClientError.decodeResponseError(r,t)}})))}catch(e){return a.throwError(e)}},t.prototype.onConnectionStateChange=function(){try{return this.getCurrentProtocol().onConnectionStateChange()}catch(e){return a.throwError(e)}},t.prototype.onProtocolChange=function(){try{return this._onProtocolChange.asObservable()}catch(e){return a.throwError(e)}},t.prototype._command=function(t){var n=this;try{if(!this.isConnected())return a.throwError(e.TapClientError.notConnectedError());var o=void 0;try{o=this._commandEncoder.encode(t)}catch(r){return a.throwError(e.TapClientError.encodeRequestError(t,r))}return v(L,"Sending "+B.toString(t)+" ("+o.length+" bytes 0x"+r.bufferToHexString(o)+")"),this.getCurrentProtocol().send(o).pipe(u.map((function(r){try{return n._responseDecoder.decode(r)}catch(r){throw e.TapClientError.decodeResponseError(r,t)}})))}catch(e){return a.throwError(e)}},t}(),j=function(){function e(){}return e.SUCCESS=function(r){return e.create(t.ResultCode.OK,r)},e.ERROR=function(r,n){return void 0===r&&(r=t.ResultCode.BAD_REQUEST),e.create(r,n)},e.create=function(e,t){return{status:e,data:t||new Uint8Array}},e}();var D=function(){function e(e,t){this._itemConverter=e,this.options=t}return Object.defineProperty(e.prototype,"itemConverter",{get:function(){return this._itemConverter},enumerable:!1,configurable:!0}),e.prototype.decode=function(e){for(var t=[],r=this.options.sizeOfItem,n=0;n<e.length;n+=r){var o=e.subarray(n,n+r),i=this._itemConverter.decode(o);t.push(i)}return t},e.prototype.encode=function(e){var t,r,n=new Uint8Array(this.options.sizeOfItem*e.length),o=0;try{for(var i=f(e),a=i.next();!a.done;a=i.next()){var u=a.value,s=this._itemConverter.encode(u);if(s.length>this.options.sizeOfItem)throw new Error("Encoded item size overflow: "+s.length+" (max is "+this.options.sizeOfItem+")");n.set(s,o),o+=this.options.sizeOfItem}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return n},e}(),H=function(){function e(e){void 0===e&&(e=1),this._mask=e}return e.prototype.decode=function(t){var r=g.fromBytes(t,t.length,!1,e.IS_LEAST_SIGNIFICANT_BIT_FIRST);return e.decodeFromNumber(this._mask,r)},e.prototype.encode=function(e){return Uint8Array.from([e?this._mask:0])},e.decodeFromNumber=function(e,t){return 0==e&&0==t||0!=(t&e)},e.instanceBit0=function(){return e._instance||(e._instance=new e(1)),e._instance},e}();H.IS_LEAST_SIGNIFICANT_BIT_FIRST=!0,H._instance=void 0;var V=/^(B[0-9]+)(_B[0-9]+)*$/,k=function(){function e(e){this.order=e}return e.prototype.encode=function(e){return function(e,t){if(!t.match(V))throw new Error('swatpBytes error, invalid byte order "'+t+'". Should match regex '+V);for(var r=t.split("_"),n=new Uint8Array(r.length),o=0;o<n.length;o++){var i=parseInt(r[o].substr(1));if(i>=e.length)throw new Error("swapBytes error, byte index "+i+" is out of range (input length is "+e.length+" byte(s))");n[o]=e[e.length-i-1]}return n}(e,this.order)},e.prototype.decode=function(e){return this.encode(e)},e}();function G(e,t,r){return{id:e,len:t.length,payload:t}}var W=function(){function t(e){this.frameIdGenerator=e}return t.prototype.encode=function(e){var t=G(this.frameIdGenerator.next(),e);return(new C).writeTapEncryptedFrame(t).toBytes},t.prototype.decode=function(t){if(!t)throw e.ConverterError.nullBufferError("Illegal data: frame is null");return E.fromArray(t).readTapEncryptedFrame().payload},t}(),K=function(){function e(e){this.mapping=e}return e.prototype.decode=function(e){var t=this.decodeToLiteral(e);if(!this.mapping[t])throw new Error("Unknown litteral value "+t+".");return t},e.prototype.encode=function(e){if("number"!=typeof e)throw Error("Illegal argument when encoding enum value. Expecting number but found "+typeof e);return this.encodeToLiteral(e)},e}(),X=function(e){function t(t,r){void 0===r&&(r=1);var n=e.call(this,t)||this;return n.mapping=t,n.size=r,n}return d(t,e),t.prototype.decodeToLiteral=function(e){return E.fromArray(e).readU(this.size)},t.prototype.encodeToLiteral=function(e){return new C(this.size).writeU(e,this.size).toBytes},t}(K),Y=function(){function e(e,t){this.size=e,this.mapping=t}return e.prototype.decode=function(e){var t,r,n=this,o=this.decodeToLiteral(E.create(e)),i=[],a=Object.keys(this.mapping).filter((function(e){return!isNaN(Number(n.mapping[e]))}));try{for(var u=f(a),s=u.next();!s.done;s=u.next()){var c=s.value,p=this.mapping[c],d=parseInt(p);0==d?0==o&&i.push(p):(o&d)==d&&i.push(p)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=u.return)&&r.call(u)}finally{if(t)throw t.error}}return i},e.prototype.encode=function(e){var t,r,n=0;try{for(var o=f(e),i=o.next();!i.done;i=o.next()){var a=i.value;if("number"!=typeof a)throw Error("Illegal argument when encoding enum value. Expecting number but found "+typeof a);n|=a}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return new C(this.size).writeU(n,this.size).toBytes},e.prototype.decodeToLiteral=function(e){return e.readU(this.size)},e}(),$=function(){function e(e){this.options=e}return e.prototype.encode=function(t){return g.toOpaqueMsb(e.toArray(t),32)},e.prototype.decode=function(t){return e.toFloat(t)},e.toArray=function(e){var t,r,n,o,i,a=(d=+e)!=d||d==-1/0||d==1/0?d:0,u=0,s=281,c=new Array(s),p=(d=0!==a?0:d)<0,d=Math.abs(d),f=Math.floor(d),l=d-f;if(0!==a){if(d!=d)return 2143289344;if(d===1/0)return 2139095040;if(d===-1/0)return 4286578688}for(t=s;t;)c[--t]=0;for(t=129;f&&t;)c[--t]=f%2,f=Math.floor(f/2);for(t=128;l>0&&t;)(c[++t]=(l*=2)>=1?1:0)&&--l;for(t=-1;++t<s&&!c[t];);if(c[(r=22+(t=(u=128-t)>=-126&&u<=127?t+1:128-(u=-127)))+1]){if(!(n=c[r]))for(o=r+2;!n&&o<s;)n=c[o++];for(o=r+1;n&&--o>=0;)(c[o]=!c[o]-0)&&(n=0)}for(t=t-2<0?-1:t-3;++t<s&&!c[t];);for((u=128-t)>=-126&&u<=127?++t:u<-126&&(t=255,u=-127),(f||0!==a)&&(u=128,t=129,a==-1/0?p=!0:a!=a&&(c[t]=1)),d=Math.abs(u+127),i=0,o=0;o<8;)i+=d%2<<o,d>>=1,o++;var h=0;for(d=t+23;t<d;t++)h=(h<<1)+c[t];return(p?2147483648:0)+(i<<23)+h|0},e.toFloat=function(t){return e.numberToFloat(g.fromOpaqueMsb(t,32))},e.numberToFloat=function(e){var t=1*e,r=(2139095040&t)>>23,n=8388607&t,o=(0==(2147483648&t)?1:-1)*(n|=8388608)*Math.pow(2,r-150)*1;return parseFloat(o.toFixed(5))},e.instance32=function(){return e._instance32||(e._instance32=new e),e._instance32},e}();$._instance32=void 0;var Q=function(){function e(){}return e.prototype.decode=function(e){return r.bufferToHexString(e)},e.prototype.encode=function(e){if(!e||0==e.length)return new Uint8Array(0);e.length%2>0&&(e="0"+e);for(var t=[],r=0,n=e.length;r<n;r+=2)t.push(parseInt(e.substr(r,2),16));return new Uint8Array(t)},e.instance=function(){return e._instance||(e._instance=new e),e._instance},e}();Q._instance=void 0;var J=function(){function t(){}return t.prototype.decode=function(t){var r,n;if(null==t||4!=t.length)throw e.ConverterError.unexpectedBufferSize(4,t);var o="",i=Array.from(t);try{for(var a=f(i),u=a.next();!u.done;u=a.next()){o+=u.value.toString()+"."}}catch(e){r={error:e}}finally{try{u&&!u.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return o.substr(0,o.length-1)},t.prototype.encode=function(e){var t=e.split(".");if(4!=t.length)throw new Error("Invalid ip format. Should be x.x.x.x");var r=new Uint8Array(4);return t.map((function(e,t){r[t]=255&parseInt(e)})),r},t.instance=function(){return t._instance||(t._instance=new t),t._instance},t}();J._instance=void 0;var Z=function(){function t(){}return t.prototype.decode=function(t){if(!t||6!==t.length)throw e.ConverterError.unexpectedBufferSize(6,t);for(var n="",o=t.length-1;o>=0;o--){var i=t.slice(o,o+1);n+=r.bufferToHexString(i).toUpperCase()+":"}return n.substring(0,n.length-1)},t.prototype.encode=function(e){var t=e.split(":").map((function(e){return 255&parseInt(e,16)})).reverse();if(6!==t.length)throw new Error("Invalid mac address format: "+e);return Uint8Array.from(t)},t.instance=function(){return t._instance||(t._instance=new t),t._instance},t}();Z._instance=void 0;var ee=function(){function e(e){this._mapping=e}return e.prototype.decode=function(t){return e.decodeAll(t,this._mapping)},e.prototype.encode=function(t){return e.encodeAll(t,this._mapping)},e.encodeAll=function(e,t){var r,n,o=function(e){var t={};for(var r in e)t[e[r]]=r;return t}(t),i=0;try{for(var a=f(e),u=a.next();!u.done;u=a.next()){var s=u.value;if(s in o)i|=parseInt(o[s])}}catch(e){r={error:e}}finally{try{u&&!u.done&&(n=a.return)&&n.call(a)}finally{if(r)throw r.error}}return Uint8Array.from([255&i])},e.decodeAll=function(e,t){var r=[];for(var n in"number"!=typeof e&&(e=g.fromOpaqueMsb(e,Math.min(8*e.length,32))),t){var o=parseInt(n);(0==o&&0==e||0!=(o&e))&&r.push(t[o])}return r},e}(),te=function(){function e(e){void 0===e&&(e={}),this.aliases=e}return e.prototype.pipe=function(e){return new re([],this.aliases).pipe(e)},e}(),re=function(){function e(e,t){void 0===t&&(t={}),this.converters=e,this.aliases=t}return e.prototype.decode=function(e){var t,r,n=e;try{for(var o=f(this.converters),i=o.next();!i.done;i=o.next()){var a=i.value;n="function"==typeof a?a(n):a.decode(n)}}catch(e){t={error:e}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return n},e.prototype.encode=function(e){var t,r,n=e,o=function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}([],l(this.converters)).reverse();try{for(var i=f(o),a=i.next();!a.done;a=i.next()){var u=a.value;n="function"==typeof u?u(n):u.encode(n)}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return n},e.prototype.pipe=function(e){if("string"==typeof e){if(!(e in this.aliases))throw new Error("Illegal argument, missing converter id: "+e);e=this.aliases[e]}return this.converters.push(e),this},e.pipe=function(t){return new e([t],{})},e}(),ne=function(){function e(e,t){void 0===e&&(e="ascii"),void 0===t&&(t={stripEndOfStringCharacter:!0,replaceEmptyStringWithEndOfLineChar:!1,addEndOfStringCharacter:!1}),this.encoding=e,this.options=t}return e.prototype.encode=function(e){if("number"==typeof e&&(e=e.toString()),"string"!=typeof e&&(e=""),this.options.addEndOfStringCharacter)e+="\0";else if(!e&&this.options.replaceEmptyStringWithEndOfLineChar)return Uint8Array.from([0]);var t=s.Buffer.from(e,this.encoding);return Uint8Array.from(t)},e.prototype.decode=function(e){var t=s.Buffer.from(e).toString(this.encoding);if(this.options.stripEndOfStringCharacter){var r=t.indexOf("\0");r>=0&&(t=t.substring(0,r))}return t},e.ascii=function(){return e._ascii||(e._ascii=new e("ascii",{replaceEmptyStringWithEndOfLineChar:!0,stripEndOfStringCharacter:!0})),e._ascii},e}();ne._ascii=void 0;var oe=function(){function e(){this.serializer=new c.TLV.Serializer,this.parser=new c.TLV.Parser}return e.prototype.encode=function(e){return this.serializer.serialize(e)},e.prototype.decode=function(e){return this.parser.parse(e)},e}(),ie=function(){function e(e,t){void 0===e&&(e=[]),void 0===t&&(t=new oe),this.variables=e,this.tlvConverter=t,this.bundleId=0}return e.prototype.decode=function(e,t){e instanceof Uint8Array&&(e=this.tlvConverter.decode(e));var r=this._convertFromTlvTree(e);if(!r||"object"!=typeof r||r instanceof Uint8Array)throw new Error("Invalid TLV frame");return r},e.prototype.encode=function(e){var t,r={header:{id:this.bundleId,len:0,type:c.TLV.IdentifierType.MULTIPLE_RESOURCE},children:[]},n=0,o=function(o){var a=e[o],u=void 0,s=i.variables.find((function(e){return e.name===o}));if(s||(s=i.variables.find((function(e){return e.id===parseInt(o,10)}))),null==s?void 0:s.converter)u=null===(t=s.converter)||void 0===t?void 0:t.encode(a);else{if(!(a instanceof Uint8Array))throw new Error('Add converter for variable with identifier "'+o+'"');u=a}r.children||(r.children=[]);var p=(null==s?void 0:s.id)||parseInt(o,10);if(isNaN(p))throw new Error('Cannot find variable by identifier "'+o+'"');r.children.push({header:{id:p,len:u.length,type:c.TLV.IdentifierType.RESOURCE_VALUE},payload:u}),n+=u.length+2},i=this;for(var a in e)o(a);return r.header.len=n,this.tlvConverter.encode(r)},e.prototype._convertFromTlvTree=function(e,t){var r,n,o={};if(e.children){o={};var i=function(e){var t,r,n=a.variables.filter((function(t){return t.id==e.header.id}));0==n.length&&n.push({id:e.header.id});try{for(var i=(t=void 0,f(n)),u=i.next();!u.done;u=i.next()){var s=u.value,c=s&&s.name?s.name:e.header.id.toString();o[c]=a._convertFromTlvTree(e,s)}}catch(e){t={error:e}}finally{try{u&&!u.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},a=this;try{for(var u=f(e.children),s=u.next();!s.done;s=u.next()){i(s.value)}}catch(e){r={error:e}}finally{try{s&&!s.done&&(n=u.return)&&n.call(u)}finally{if(r)throw r.error}}}else if(e.payload){var c=t?t.converter:void 0;o=c?c.decode(e.payload):Uint8Array.from(e.payload)}return o},e}(),ae=function(){function e(e){this._mapping=e}return e.prototype.decode=function(t){return e.decodeOne(t,this._mapping)},e.prototype.encode=function(t){return e.encodeOneAsBuffer(t,this._mapping)},e.decodeOneExact=function(e,t){for(var n in"number"!=typeof e&&(e=g.fromOpaqueMsb(e)),t){var o=parseInt(n);if(e==o)return t[o]}throw new Error("Cannot decode "+("number"==typeof e?"number "+e:"0x"+r.bufferToHexString(e))+". Available keys are "+Object.keys(t))},e.decodeOne=function(e,t){var n=ee.decodeAll(e,t);if(0==n.length)throw new Error("Cannot decode value "+("number"==typeof e?e:"0x"+r.bufferToHexString(e))+". Available keys are "+Object.keys(t));return n.length>1&&v("Converter","Multiple result for data : ",n,e,t),n[0]},e.encodeOneAsNumber=function(t,r){var n=e.swapKeyValue(r),o=t.toString();if(!(o in n))throw new Error("Key "+o+" does not exist in mapping. Available keys are "+Object.keys(n));return parseInt(n[o])},e.encodeOneAsBuffer=function(t,r){var n=new Uint8Array(1),o=e.encodeOneAsNumber(t,r);return n[0]=255&o,n},e.swapKeyValue=function(e){var t={};for(var r in e)t[e[r]]=r;return t},e}();function ue(e){var t=parseInt(e);if(isNaN(t))throw se(e);return t}function se(e){return new Error('Invalid string version format for "'+e+'". Should be x.x.x. For example: 1.0.3.')}var ce=function(){function e(){}return e.prototype.encode=function(e,t){void 0===t&&(t=new C);var r=e.split(".");if(3!==r.length)throw se(e);return t.writeUnsigned(ue(r[0]),1),t.writeUnsigned(ue(r[1]),1),t.writeUnsigned(ue(r[2]),2),t.toBytes},e.prototype.decode=function(e){var t=e instanceof E?e:E.create(e);return t.readUnsigned(1)+"."+t.readUnsigned(1)+"."+t.readUnsigned(2)},e}(),pe=function(){function e(){}return e.compute=function(e){for(var t=0,r=0;r<e.length;r++)t+=e[r];return t},e}();e.ApduRequestConverter=b,e.ApduResponseConverter=R,e.ArrayConverter=D,e.BooleanConverter=H,e.ByteSwapConverter=k,e.CRC=w,e.Checksum=pe,e.CryptedFrameConverter=W,e.EnumConverter=K,e.EnumListConverter=Y,e.FixedSizeEnumConverter=X,e.FloatConverter=$,e.HexStringConverter=Q,e.Ipv4StringConverter=J,e.MacAddressStringConverter=Z,e.MultipleMaskConverter=ee,e.NumberConverter=g,e.PipeConverter=re,e.PipeConverterBuilder=te,e.ResultCodeTranslation=x,e.StringConverter=ne,e.StringVersionConverter=ce,e.TAP_REQUEST_FRAME_CONVERTER=P,e.TAP_RESPONSE_FRAME_CONVERTER=z,e.TLVConverter=oe,e.TapApduRequestConverter=O,e.TapApduResponseConverter=F,e.TapClient=N,e.TapEncryptedFrameConverter=A,e.TapRequestEncryptedConverter=S,e.TapRequestFrameConverter=I,e.TapRequestHelper=B,e.TapResponseFrameBuilder=j,e.TapResponseFrameConverter=U,e.TapStreamReader=E,e.TapStreamWriter=C,e.TlvBundleConverter=ie,e.UniqMaskConverter=ae,e.createApduFromTapRequest=_,e.createTapEncryptedFrame=G,e.enumKeyOrValueToNumber=T,e.tapResponseStatusToString=function(e){return x[e]?x[e]:"Unknown tap response status"},Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=iotize-tap-client-impl.umd.min.js.map