@itee/client 10.0.0
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/CHANGELOG.md +251 -0
- package/LICENSE.md +23 -0
- package/README.md +76 -0
- package/builds/itee-client.cjs.js +6517 -0
- package/builds/itee-client.cjs.js.map +1 -0
- package/builds/itee-client.cjs.min.js +125 -0
- package/builds/itee-client.esm.js +6468 -0
- package/builds/itee-client.esm.js.map +1 -0
- package/builds/itee-client.esm.min.js +124 -0
- package/builds/itee-client.iife.js +6524 -0
- package/builds/itee-client.iife.js.map +1 -0
- package/builds/itee-client.iife.min.js +125 -0
- package/package.json +87 -0
- package/sources/client.js +14 -0
- package/sources/cores/TAbstractFactory.js +42 -0
- package/sources/cores/TCloningFactory.js +39 -0
- package/sources/cores/TConstants.js +433 -0
- package/sources/cores/TInstancingFactory.js +41 -0
- package/sources/cores/TStore.js +303 -0
- package/sources/cores/_cores.js +13 -0
- package/sources/input_devices/TKeyboardController.js +158 -0
- package/sources/input_devices/TMouseController.js +31 -0
- package/sources/input_devices/_inputDevices.js +11 -0
- package/sources/loaders/TBinaryConverter.js +35 -0
- package/sources/loaders/TBinaryReader.js +1029 -0
- package/sources/loaders/TBinarySerializer.js +258 -0
- package/sources/loaders/TBinaryWriter.js +429 -0
- package/sources/loaders/_loaders.js +21 -0
- package/sources/loaders/converters/ArrayBinaryConverter.js +33 -0
- package/sources/loaders/converters/BooleanBinaryConverter.js +24 -0
- package/sources/loaders/converters/DateBinaryConverter.js +21 -0
- package/sources/loaders/converters/NullBinaryConverter.js +13 -0
- package/sources/loaders/converters/NumberBinaryConverter.js +15 -0
- package/sources/loaders/converters/ObjectBinaryConverter.js +101 -0
- package/sources/loaders/converters/RegExBinaryConverter.js +11 -0
- package/sources/loaders/converters/StringBinaryConverter.js +26 -0
- package/sources/loaders/converters/UndefinedBinaryConverter.js +13 -0
- package/sources/managers/TDataBaseManager.js +1649 -0
- package/sources/managers/_managers.js +10 -0
- package/sources/utils/TIdFactory.js +84 -0
- package/sources/utils/_utils.js +9 -0
- package/sources/webapis/WebAPI.js +773 -0
- package/sources/webapis/WebAPIOrigin.js +141 -0
- package/sources/webapis/_webapis.js +10 -0
- package/sources/webapis/messages/WebAPIMessage.js +75 -0
- package/sources/webapis/messages/WebAPIMessageData.js +51 -0
- package/sources/webapis/messages/WebAPIMessageError.js +79 -0
- package/sources/webapis/messages/WebAPIMessageEvent.js +58 -0
- package/sources/webapis/messages/WebAPIMessageProgress.js +91 -0
- package/sources/webapis/messages/WebAPIMessageReady.js +66 -0
- package/sources/webapis/messages/WebAPIMessageRequest.js +94 -0
- package/sources/webapis/messages/WebAPIMessageResponse.js +80 -0
- package/sources/webapis/messages/_messages.js +16 -0
- package/sources/workers/AbstractWorker.js +149 -0
- package/sources/workers/_workers.js +10 -0
- package/sources/workers/messages/WorkerMessage.js +33 -0
- package/sources/workers/messages/WorkerMessageData.js +30 -0
- package/sources/workers/messages/WorkerMessageError.js +32 -0
- package/sources/workers/messages/WorkerMessageMethodCall.js +60 -0
- package/sources/workers/messages/WorkerMessageProgress.js +67 -0
- package/sources/workers/messages/_messages.js +14 -0
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"use strict";var e=require("itee-utils"),t=require("itee-validators"),s=require("itee-core");const r=e.toEnum({Asc:{value:"asc"},Dae:{value:"dae"},Dbf:{value:"dbf"},Fbx:{value:"fbx"},Mtl:{value:"mtl"},Json:{value:"json"},Obj:{value:"obj"},Shp:{value:"shp"},Stl:{value:"stl"}}),i=e.toEnum({Continue:{value:100},SwitchingProtocols:{value:101},Processing:{value:102},Ok:{value:200},Created:{value:201},Accepted:{value:202},NonAuthoritativeInformation:{value:203},NoContent:{value:204},ResetContent:{value:205},PartialContent:{value:206},MultiStatus:{value:207},AlreadyReported:{value:208},ContentDifferent:{value:210},IMUsed:{value:226},MultipleChoices:{value:300},MovedPermanently:{value:301},Found:{value:302},SeeOther:{value:303},NotModified:{value:304},UseProxy:{value:305},Unused:{value:306},TemporaryRedirect:{value:307},PermanentRedirect:{value:308},TooManyRedirects:{value:310},BadRequest:{value:400},Unauthorized:{value:401},PaymentRequired:{value:402},Forbidden:{value:403},NotFound:{value:404},MethodNotAllowed:{value:405},NotAcceptable:{value:406},ProxyAuthenticationRequired:{value:407},RequestTimeOut:{value:408},Conflict:{value:409},Gone:{value:410},LengthRequired:{value:411},PreconditionFailed:{value:412},RequestEntityTooLarge:{value:413},RequestRangeUnsatisfiable:{value:416},ExpectationFailed:{value:417},ImATeapot:{value:418},BadMapping:{value:421},UnprocessableEntity:{value:422},Locked:{value:423},MethodFailure:{value:424},UnorderedCollection:{value:425},UpgradeRequired:{value:426},PreconditionRequired:{value:428},TooManyRequests:{value:429},RequestHeaderFieldsTooLarge:{value:431},NoResponse:{value:444},RetryWith:{value:449},BlockedByWindowsParentalControls:{value:450},UnavailableForLegalReasons:{value:451},UnrecoverableError:{value:456},SSLCertificateError:{value:495},SSLCertificateRequired:{value:496},HTTPRequestSentToHTTPSPort:{value:497},ClientClosedRequest:{value:499},InternalServerError:{value:500},NotImplemented:{value:501},BadGateway:{value:502},ServiceUnavailable:{value:503},GatewayTimeOut:{value:504},HTTPVersionNotSupported:{value:505},VariantAlsoNegotiates:{value:506},InsufficientStorage:{value:507},LoopDetected:{value:508},BandwidthLimitExceeded:{value:509},NotExtended:{value:510},NetworkAuthenticationRequired:{value:511},UnknownError:{value:520},WebServerIsDown:{value:521},ConnectionTimedOut:{value:522},OriginIsUnreachable:{value:523},ATimeoutOccured:{value:524},SSLHandshakeFailed:{value:525},InvalidSSLCertificate:{value:526},RailgunError:{value:527}}),n=e.toEnum({Create:{value:"PUT"},Read:{value:"POST"},Update:{value:"PATCH"},Delete:{value:"DELETE"}}),o=e.toEnum({BACKSPACE:{value:8},TAB:{value:9},ENTER:{value:13},SHIFT:{value:16},CTRL:{value:17},ALT:{value:18},PAUSE:{value:19},CAPS_LOCK:{value:20},ESCAPE:{value:27},SPACE:{value:32},PAGE_UP:{value:33},PAGE_DOWN:{value:34},END:{value:35},HOME:{value:36},LEFT_ARROW:{value:37},UP_ARROW:{value:38},RIGHT_ARROW:{value:39},DOWN_ARROW:{value:40},INSERT:{value:45},DELETE:{value:46},ZERO:{value:48},ONE:{value:49},TWO:{value:50},THREE:{value:51},FOUR:{value:52},FIVE:{value:53},SIX:{value:54},SEVEN:{value:55},HEIGHT:{value:56},NINE:{value:57},A:{value:65},B:{value:66},C:{value:67},D:{value:68},E:{value:69},F:{value:70},G:{value:71},H:{value:72},I:{value:73},J:{value:74},K:{value:75},L:{value:76},M:{value:77},N:{value:78},O:{value:79},P:{value:80},Q:{value:81},R:{value:82},S:{value:83},T:{value:84},U:{value:85},V:{value:86},W:{value:87},X:{value:88},Y:{value:89},Z:{value:90},LEFT_WINDOW_KEY:{value:91},RIGHT_WINDOW_KEY:{value:92},SELECT_KEY:{value:93},NUMPAD_0:{value:96},NUMPAD_1:{value:97},NUMPAD_2:{value:98},NUMPAD_3:{value:99},NUMPAD_4:{value:100},NUMPAD_5:{value:101},NUMPAD_6:{value:102},NUMPAD_7:{value:103},NUMPAD_8:{value:104},NUMPAD_9:{value:105},MULTIPLY:{value:106},ADD:{value:107},SUBSTRACT:{value:109},DECIMAL_POINT:{value:110},DIVIDE:{value:111},F1:{value:112},F2:{value:113},F3:{value:114},F4:{value:115},F5:{value:116},F6:{value:117},F7:{value:118},F8:{value:119},F9:{value:120},F10:{value:121},F11:{value:122},F12:{value:123},NUM_LOCK:{value:144},SCROLL_LOCK:{value:145},SEMICOLON:{value:186},EQUAL:{value:187},COMMA:{value:188},DASH:{value:189},PERIODE:{value:190},SLASH:{value:191},GRAVE_ACCENT:{value:192},OPEN_SQUARE_BRACKET:{value:219},BACKSLASH:{value:220},CLOSE_SQUARE_BRACKET:{value:221},SINGLE_QUOTE:{value:222}}),a=e.toEnum({}),u=e.toEnum({Wheel:{value:-1},Left:{value:0},Middle:{value:1},Right:{value:2}}),l=e.toEnum({ArrayBuffer:{value:"arraybuffer"},Blob:{value:"blob"},Document:{value:"document"},Json:{value:"json"},DOMString:{value:"text"},Default:{value:""}});
|
|
2
|
+
/**
|
|
3
|
+
* @class
|
|
4
|
+
* @classdesc TStore is a simple javascript object whose purpose is to store some ket/value data to future usage. It could be enable/disable.
|
|
5
|
+
*
|
|
6
|
+
* @example {@lang javascript}
|
|
7
|
+
* var cache = new TCache()
|
|
8
|
+
* cache.add( 'foo', 'bar' )
|
|
9
|
+
* TLogger.log( cache.get('foo') ) // 'bar'
|
|
10
|
+
*
|
|
11
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
12
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
13
|
+
*/
|
|
14
|
+
class h{constructor(e={}){const t={collection:{},allowOverride:!1,keyValidators:[],valueValidators:[],...e};this.collection=t.collection,this.allowOverride=t.allowOverride,this.keyValidators=t.keyValidators,this.valueValidators=t.valueValidators}get collection(){return this._collection}set collection(e){const s="Collection",r="Expect an object.";if(t.isNull(e))throw new TypeError(`${s} cannot be null ! ${r}`);if(t.isUndefined(e))throw new TypeError(`${s} cannot be undefined ! ${r}`);if(t.isNotObject(e))throw new TypeError(`${s} cannot be an instance of ${e.constructor.name} ! ${r}`);this._collection=e}get allowOverride(){return this._allowOverride}set allowOverride(e){const s="Allow override",r="Expect a boolean.";if(t.isNull(e))throw new TypeError(`${s} cannot be null ! ${r}`);if(t.isUndefined(e))throw new TypeError(`${s} cannot be undefined ! ${r}`);if(t.isNotBoolean(e))throw new TypeError(`${s} cannot be an instance of ${e.constructor.name} ! ${r}`);this._allowOverride=e}get keyValidators(){return this._keyValidators}set keyValidators(e){const s="Keys validators",r="Expect an array of TValidator or an empty array.";if(t.isNull(e))throw new TypeError(`${s} cannot be null ! ${r}`);if(t.isUndefined(e))throw new TypeError(`${s} cannot be undefined ! ${r}`);if(t.isNotArray(e))throw new TypeError(`${s} cannot be an instance of ${e.constructor.name} ! ${r}`);this._keyValidators=e}get valueValidators(){return this._valueValidators}set valueValidators(e){const s="Values validators",r="Expect an array of TValidator or an empty array.";if(t.isNull(e))throw new TypeError(`${s} cannot be null ! ${r}`);if(t.isUndefined(e))throw new TypeError(`${s} cannot be undefined ! ${r}`);if(t.isNotArray(e))throw new TypeError(`${s} cannot be an instance of ${e.constructor.name} ! ${r}`);this._valueValidators=e}get keys(){return Object.keys(this._collection)}get values(){return Object.values(this._collection)}static _validate(e,s){for(let r=0,i=s.length;r<i;r++){let i=s[r];if(!i.validator(e)){const s=i.error;throw t.isString(s)?new TypeError(s):t.isFunction(s)?new TypeError(s(e)):new TypeError(`${e} is invalid.`)}}}setCollection(e){return this.collection=e,this}setAllowOverride(e){return this.allowOverride=e,this}setKeyValidators(e){return this.keyValidators(e),this}setValueValidators(e){return this.valueValidators(e),this}add(e,t,s=!1){if(this.contain(e)&&!this._allowOverride&&!s)throw new TypeError(`Item with key (${e}) already exist in collection !`);return h._validate(e,this._keyValidators),h._validate(t,this._valueValidators),this._collection[e]=t,this}contain(e){return t.isNotUndefined(this._collection[e])}get(e){return this._collection[e]}remove(e){return delete this._collection[e],this}clear(){return this._collection={},this}}
|
|
15
|
+
/**
|
|
16
|
+
* @class
|
|
17
|
+
* @classdesc The abstract class to create factory
|
|
18
|
+
* @abstract
|
|
19
|
+
* @extends TStore
|
|
20
|
+
*
|
|
21
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
22
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
23
|
+
*/class d extends h{constructor(e={}){super({...e})}create(e,...t){}}
|
|
24
|
+
/**
|
|
25
|
+
* @class
|
|
26
|
+
* @classdesc The TCloningFactory is a kind a factory that performe instanciation by cloning a base instance.
|
|
27
|
+
* @extends TAbstractFactory
|
|
28
|
+
*
|
|
29
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
30
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
31
|
+
*/
|
|
32
|
+
/**
|
|
33
|
+
* @class
|
|
34
|
+
* @classdesc TKeyboardController allow single source of thruth for keyboard state checking (based on Lee Stemkoski work).
|
|
35
|
+
* See TKeyboardController.k object data below for names of keys whose state can be polled
|
|
36
|
+
*
|
|
37
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
38
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
39
|
+
* @example {@lang javascript}
|
|
40
|
+
* // (1) create a global variable:
|
|
41
|
+
* var keyboard = new TKeyboardController();
|
|
42
|
+
*
|
|
43
|
+
* // (2) during main loop:
|
|
44
|
+
* keyboard.update();
|
|
45
|
+
*
|
|
46
|
+
* // (3) check state of keys:
|
|
47
|
+
* keyboard.down("A") -- true for one update cycle after key is pressed
|
|
48
|
+
* keyboard.pressed("A") -- true as long as key is being pressed
|
|
49
|
+
* keyboard.up("A") -- true for one update cycle after key is released
|
|
50
|
+
*/
|
|
51
|
+
class c{constructor(e={}){document.addEventListener("keydown",c.onKeyDown,!1),document.addEventListener("keyup",c.onKeyUp,!1)}static keyName(e){return null!==c.k[e]?c.k[e]:String.fromCharCode(e)}static onKeyUp(e){var t=c.keyName(e.keyCode);c.status[t]&&(c.status[t].pressed=!1)}static onKeyDown(e){var t=c.keyName(e.keyCode);c.status[t]||(c.status[t]={down:!1,pressed:!1,up:!1,updatedPreviously:!1})}update(){for(var e in c.status)c.status[e].updatedPreviously?c.status[e].down=!1:(c.status[e].down=!0,c.status[e].pressed=!0,c.status[e].updatedPreviously=!0),c.status[e].up?delete c.status[e]:c.status[e].pressed||(c.status[e].up=!0)}down(e){return c.status[e]&&c.status[e].down}pressed(e){return c.status[e]&&c.status[e].pressed}up(e){return c.status[e]&&c.status[e].up}debug(){var e="Keys active: ";for(var t in c.status)e+=" "+t;s.DefaultLogger.log(e)}}c.k=o,c.status={};class f{constructor(e,t=null){this.targetCtor=e,this.serializer=t}to(e,t,s={}){}from(e,t={}){return new this.targetCtor}}const g=e.toEnum({Little:!0,Big:!1}),p=e.toEnum({One:1,Two:2,Four:4,Eight:8});
|
|
52
|
+
/**
|
|
53
|
+
* @class
|
|
54
|
+
* @classdesc TBinaryReader is design to perform fast binary read/write
|
|
55
|
+
*
|
|
56
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
57
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
58
|
+
*/
|
|
59
|
+
class _{constructor(e={}){const t={buffer:new ArrayBuffer(0),offset:0,length:0,endianness:g.Little,...e};this.buffer=t.buffer,this.endianness=t.endianness,this._bits={buffer:null,offset:0,length:0},this._updateDataView()}get buffer(){return this._buffer}set buffer(e){const s="Buffer",r="Expect an instance of ArrayBuffer.";if(t.isNull(e))throw new TypeError(`${s} cannot be null ! ${r}`);if(t.isUndefined(e))throw new TypeError(`${s} cannot be undefined ! ${r}`);if(t.isNotArrayBuffer(e))throw new TypeError(`${s} cannot be an instance of ${e.constructor.name} ! ${r}`);this._buffer=e,this._offset=0,this._length=e.byteLength,this._updateDataView()}get offset(){return this._offset}set offset(e){const s="Offset",r="Expect a number.";if(t.isNull(e))throw new TypeError(`${s} cannot be null ! ${r}`);if(t.isUndefined(e))throw new TypeError(`${s} cannot be undefined ! ${r}`);if(t.isNotNumber(e))throw new TypeError(`${s} cannot be an instance of ${e.constructor.name} ! ${r}`);this._offset=e,this._updateDataView()}get length(){return this._length}set length(e){const s="Length",r="Expect a number.";if(t.isNull(e))throw new TypeError(`${s} cannot be null ! ${r}`);if(t.isUndefined(e))throw new TypeError(`${s} cannot be undefined ! ${r}`);if(t.isNotNumber(e))throw new TypeError(`${s} cannot be an instance of ${e.constructor.name} ! ${r}`);this._length=e,this._updateDataView()}get endianness(){return this._endianness}set endianness(e){const s="Endianness",r="Expect a boolean.";if(t.isNull(e))throw new TypeError(`${s} cannot be null ! ${r}`);if(t.isUndefined(e))throw new TypeError(`${s} cannot be undefined ! ${r}`);if(t.isNotBoolean(e))throw new TypeError(`${s} cannot be an instance of ${e.constructor.name} ! ${r}`);this._endianness=e}setBuffer(e,t,s){return this.buffer=e,this.offset=t||0,this.length=s||e.byteLength,this}setOffset(e){return this.offset=e,this}setLength(e){return this.length=e,this}setEndianness(e){return this.endianness=e,this}_getAndUpdateOffsetBy(e){const t=this._offset;return this._offset+=e,t}_updateDataView(){this._dataView=new DataView(this._buffer,this._offset,this._length)}isEndOfFile(){return this._offset===this._length}_isNullBitBuffer(){return null===this._bits.buffer}_nextBit(){this._bits.offset+=1}_isEndOfBitBuffer(){return this._bits.offset===this._bits.length}_isOutOfRangeBitOffset(e){return e>this._bits.length}_readBit8(){this._bits.buffer=this.getUint8(),this._bits.length=8,this._bits.offset=0}_readBit16(){this._bits.buffer=this.getUint16(),this._bits.length=16,this._bits.offset=0}_readBit32(){this._bits.buffer=this.getUint32(),this._bits.length=32,this._bits.offset=0}_getBitAt(e){return this._bits.buffer&1<<e?1:0}_resetBits(){this._bits.buffer=null,this._bits.length=0,this._bits.offset=0}skipBitOffsetTo(e){if(this._isNullBitBuffer())if(e<=8)this._readBit8();else if(8<e&&e<=16)this._readBit16();else{if(!(16<e&&e<=32))throw new RangeError("You cannot skip more than 32 bits. Please use skipOffsetOf instead !");this._readBit32()}else if(this._isOutOfRangeBitOffset(e))throw new RangeError("Bit offset is out of range of the current bits field.");this._bits.offset=e,this._isEndOfBitBuffer()&&this._resetBits()}skipBitOffsetOf(e){this.skipBitOffsetTo(this._bits.offset+e)}getBit8(e=!0){this._isNullBitBuffer()&&this._readBit8();const t=this._getBitAt(this._bits.offset);return e&&(this._nextBit(),this._isEndOfBitBuffer()&&this._resetBits()),t}getBits8(e,t=!0){const s=this._bits.offset;let r=0;for(let s=0;s<e;s++)r|=s===e-1?this.getBit8(t)<<s:this.getBit8()<<s;return t||this.skipBitOffsetTo(s),r}getBit16(e=!0){this._isNullBitBuffer()&&this._readBit16();const t=this._getBitAt(this._bits.offset);return e&&(this._nextBit(),this._isEndOfBitBuffer()&&this._resetBits()),t}getBits16(e,t=!0){const s=this._bits.offset;let r=0;for(let s=0;s<e;s++)r|=s===e-1?this.getBit16(t)<<s:this.getBit16()<<s;return t||this.skipBitOffsetTo(s),r}getBit32(e=!0){this._isNullBitBuffer()&&this._readBit32();const t=this._getBitAt(this._bits.offset);return e&&(this._nextBit(),this._isEndOfBitBuffer()&&this._resetBits()),t}getBits32(e,t=!0){const s=this._bits.offset;let r=0;for(let s=0;s<e;s++)r|=s===e-1?this.getBit32(t)<<s:this.getBit32()<<s;return t||this.skipBitOffsetTo(s),r}skipOffsetTo(e){this._offset=e}skipOffsetOf(e){this._offset+=e}getBoolean(e=!0){return!(1&~this.getUint8(e))}getBooleanArray(e,t=!0){const s=this._offset,r=[];for(let t=0;t<e;t++)r.push(this.getBoolean());return t||(this._offset=s),r}getInt8(e=!0){const t=e?this._getAndUpdateOffsetBy(p.One):this._offset;return this._dataView.getInt8(t)}getInt8Array(e,t=!0){const s=this._offset,r=[];for(let t=0;t<e;t++)r.push(this.getInt8());return t||(this._offset=s),r}getUint8(e=!0){const t=e?this._getAndUpdateOffsetBy(p.One):this._offset;return this._dataView.getUint8(t)}getUint8Array(e,t=!0){const s=this._offset,r=[];for(let t=0;t<e;t++)r.push(this.getUint8());return t||(this._offset=s),r}getInt16(e=!0){const t=e?this._getAndUpdateOffsetBy(p.Two):this._offset;return this._dataView.getInt16(t,this._endianness)}getInt16Array(e,t=!0){const s=this._offset,r=[];for(let t=0;t<e;t++)r.push(this.getInt16());return t||(this._offset=s),r}getUint16(e=!0){const t=e?this._getAndUpdateOffsetBy(p.Two):this._offset;return this._dataView.getUint16(t,this._endianness)}getUint16Array(e,t=!0){const s=this._offset,r=[];for(let t=0;t<e;t++)r.push(this.getUint16());return t||(this._offset=s),r}getInt32(e=!0){const t=e?this._getAndUpdateOffsetBy(p.Four):this._offset;return this._dataView.getInt32(t,this._endianness)}getInt32Array(e,t=!0){const s=this._offset,r=[];for(let t=0;t<e;t++)r.push(this.getInt32());return t||(this._offset=s),r}getUint32(e=!0){const t=e?this._getAndUpdateOffsetBy(p.Four):this._offset;return this._dataView.getUint32(t,this._endianness)}getUint32Array(e,t=!0){const s=this._offset,r=[];for(let t=0;t<e;t++)r.push(this.getUint32());return t||(this._offset=s),r}getInt64(e=!0){let t=null,s=null;if(this._endianness===g.Little)if(e)t=this.getUint32(),s=this.getUint32();else{const e=this._offset;t=this.getUint32(),s=this.getUint32(),this.skipOffsetTo(e)}else if(e)s=this.getUint32(),t=this.getUint32();else{const e=this._offset;s=this.getUint32(),t=this.getUint32(),this.skipOffsetTo(e)}return 2147483648&s?(s=4294967295&~s,t=4294967295&~t,4294967295===t&&(s=s+1&4294967295),t=t+1&4294967295,-(4294967296*s+t)):4294967296*s+t}getInt64Array(e,t=!0){const s=this._offset,r=[];for(let t=0;t<e;t++)r.push(this.getInt64());return t||(this._offset=s),r}getUint64(e=!0){let t=null,s=null;if(this._endianness===g.Little)if(e)t=this.getUint32(),s=this.getUint32();else{const e=this._offset;t=this.getUint32(),s=this.getUint32(),this.skipOffsetTo(e)}else if(e)s=this.getUint32(),t=this.getUint32();else{const e=this._offset;s=this.getUint32(),t=this.getUint32(),this.skipOffsetTo(e)}return 4294967296*s+t}getUint64Array(e,t=!0){const s=this._offset,r=[];for(let t=0;t<e;t++)r.push(this.getUint64());return t||(this._offset=s),r}getFloat32(e=!0){const t=e?this._getAndUpdateOffsetBy(p.Four):this._offset;return this._dataView.getFloat32(t,this._endianness)}getFloat32Array(e,t=!0){const s=this._offset,r=[];for(let t=0;t<e;t++)r.push(this.getFloat32());return t||(this._offset=s),r}getFloat64(e=!0){const t=e?this._getAndUpdateOffsetBy(p.Eight):this._offset;return this._dataView.getFloat64(t,this._endianness)}getFloat64Array(e,t=!0){const s=this._offset,r=[];for(let t=0;t<e;t++)r.push(this.getFloat64());return t||(this._offset=s),r}getChar(e=!0){return String.fromCharCode(this.getUint8(e))}getString(e,t=!0){const s=this._offset;let r="";for(let t=0;t<e;t++)r+=String.fromCharCode(this.getUint8());return t||(this._offset=s),r}getArrayBuffer(e){const t=this._getAndUpdateOffsetBy(e);return this._dataView.buffer.slice(t,t+e)}}class y extends f{constructor(e){super(Array,e)}to(e,t,s={}){const r=t.length;e.setUint32(r);for(let e of t)this.serializer._serialize(e)}from(e,t={}){const s=e.getUint32(),r=[];for(let e=0;e<s;e++){const e=this.serializer._deserialize();r.push(e)}return r}}
|
|
60
|
+
/**
|
|
61
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
62
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
63
|
+
*/class w extends f{constructor(e){super(Boolean,e)}to(e,t,s={}){e.setBoolean(t)}from(e,t={}){return e.getBoolean()}}class b extends f{constructor(e){super(Date,e)}to(e,t,s={}){const r=t.toUTCString();this.serializer._serialize(r)}from(e,t={}){const s=this.serializer._deserialize();return new Date(s)}}class m extends f{constructor(e){super(null,e)}to(e,t,s={}){}from(e,t={}){return null}}class v extends f{constructor(e){super(Number,e)}to(e,t,s={}){e.setFloat64(t)}from(e,t={}){return e.getFloat64()}}class E extends f{constructor(e,t){super(e||Object,t)}to(e,t,s={}){const r=Object.getOwnPropertyDescriptors(t),i=Object.values(r).filter(e=>e.writable&&e.enumerable);e.setUint8(i.length);for(let[t,s]of i)e.setUint32(t.length),e.setString(t),this.serializer._serialize(s.value)}from(e,t={}){const s=super.from(e,t),r=e.getUint8();for(let t=0;t<r;t++){const t=e.getUint32();s[e.getString(t)]=this.serializer._deserialize()}return s}}class T extends f{constructor(e){super(RegExp,e)}from(e,t={}){return new RegExp}}
|
|
64
|
+
/**
|
|
65
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
66
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
67
|
+
*/class O extends f{constructor(e){super(String,e)}to(e,t,s={}){e.setUint32(t.length),e.setString(t)}from(e,t={}){const s=e.getUint32();return e.getString(s)}}class A extends f{constructor(e){super(null,e)}to(e,t,s={}){}from(e,t={}){}}
|
|
68
|
+
/**
|
|
69
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
70
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
71
|
+
*/class N{constructor({buffer:e=new ArrayBuffer(1024),endianness:t=g.Little}={}){this.buffer=e,this.endianness=t,this._updateDataView()}get buffer(){return this._buffer}set buffer(e){const s="Buffer",r="Expect an instance of ArrayBuffer.";if(t.isNull(e))throw new TypeError(`${s} cannot be null ! ${r}`);if(t.isUndefined(e))throw new TypeError(`${s} cannot be undefined ! ${r}`);if(t.isNotArrayBuffer(e))throw new TypeError(`${s} cannot be an instance of ${e.constructor.name} ! ${r}`);this._buffer=e,this._offset=0,this._length=e.byteLength,this._updateDataView()}get offset(){return this._offset}set offset(e){const s="Offset",r="Expect a number.";if(t.isNull(e))throw new TypeError(`${s} cannot be null ! ${r}`);if(t.isUndefined(e))throw new TypeError(`${s} cannot be undefined ! ${r}`);if(t.isNotNumber(e))throw new TypeError(`${s} cannot be an instance of ${e.constructor.name} ! ${r}`);this._offset=e,this._updateDataView()}get length(){return this._length}set length(e){const s="Length",r="Expect a number.";if(t.isNull(e))throw new TypeError(`${s} cannot be null ! ${r}`);if(t.isUndefined(e))throw new TypeError(`${s} cannot be undefined ! ${r}`);if(t.isNotNumber(e))throw new TypeError(`${s} cannot be an instance of ${e.constructor.name} ! ${r}`);this._length=e,this._updateDataView()}get endianness(){return this._endianness}set endianness(e){const s="Endianness",r="Expect a boolean.";if(t.isNull(e))throw new TypeError(`${s} cannot be null ! ${r}`);if(t.isUndefined(e))throw new TypeError(`${s} cannot be undefined ! ${r}`);if(t.isNotBoolean(e))throw new TypeError(`${s} cannot be an instance of ${e.constructor.name} ! ${r}`);this._endianness=e}setBuffer(e,t,s){return this.buffer=e,this.offset=t||0,this.length=s||e.byteLength,this}setOffset(e){return this.offset=e,this}setLength(e){return this.length=e,this}setEndianess(e){return this.endianness=e,this}_getAndUpdateOffsetBy(e){const t=this._offset;this._offset+=e;const s=this._buffer.byteLength;if(this._offset>=s){const e=new ArrayBuffer(s+1024),t=new DataView(e,0,e.byteLength);for(let e=0;e<s;e++)t.setUint8(e,this._dataView.getUint8(e));this._buffer=e,this._dataView=t}return t}_updateDataView(){this._dataView=new DataView(this._buffer,this._offset,this._length)}isEndOfFile(){return this._offset===this._length}_iterArray(e,t,s){const r=this._offset;for(let s of e)t(s);s||(this._offset=r)}skipOffsetTo(e){this._offset=e}skipOffsetOf(e){this._offset+=e}setBoolean(e,t=!0){this.setUint8(!(1&~e),t)}setBooleanArray(e,t=!0){this._iterArray(e,this.setBoolean.bind(this),t)}setInt8(e,t=!0){const s=t?this._getAndUpdateOffsetBy(p.One):this._offset;this._dataView.setInt8(s,e)}setInt8Array(e,t=!0){this._iterArray(e,this.setInt8.bind(this),t)}setUint8(e,t=!0){const s=t?this._getAndUpdateOffsetBy(p.One):this._offset;this._dataView.setUint8(s,e)}setUint8Array(e,t=!0){this._iterArray(e,this.setUint8.bind(this),t)}setInt16(e,t=!0){const s=t?this._getAndUpdateOffsetBy(p.Two):this._offset;this._dataView.setInt16(s,e,this._endianness)}setInt16Array(e,t=!0){this._iterArray(e,this.setInt16.bind(this),t)}setUint16(e,t=!0){const s=t?this._getAndUpdateOffsetBy(p.Two):this._offset;this._dataView.setUint16(s,e,this._endianness)}setUint16Array(e,t=!0){this._iterArray(e,this.setUint16.bind(this),t)}setInt32(e,t=!0){const s=t?this._getAndUpdateOffsetBy(p.Four):this._offset;this._dataView.setInt32(s,e,this._endianness)}setInt32Array(e,t=!0){this._iterArray(e,this.setInt32.bind(this),t)}setUint32(e,t=!0){const s=t?this._getAndUpdateOffsetBy(p.Four):this._offset;this._dataView.setUint32(s,e,this._endianness)}setUint32Array(e,t=!0){this._iterArray(e,this.setUint32.bind(this),t)}setInt64(){throw new Error("Not implemented, sorry... any help is welcome !")}setInt64Array(e,t=!0){this._iterArray(e,this.setInt64.bind(this),t)}setUint64(){throw new Error("Not implemented, sorry... any help is welcome !")}setUint64Array(e,t=!0){this._iterArray(e,this.setUint64.bind(this),t)}setFloat32(e,t=!0){const s=t?this._getAndUpdateOffsetBy(p.Four):this._offset;this._dataView.setFloat32(s,e,this._endianness)}setFloat32Array(e,t=!0){this._iterArray(e,this.setFloat32.bind(this),t)}setFloat64(e,t=!0){const s=t?this._getAndUpdateOffsetBy(p.Eight):this._offset;this._dataView.setFloat64(s,e,this._endianness)}setFloat64Array(e,t=!0){this._iterArray(e,this.setFloat64.bind(this),t)}setChar(e,t=!0){this.setUint8(e.charCodeAt(0),t)}setString(e,t=!0){this._iterArray(e,this.setChar.bind(this),t)}}
|
|
72
|
+
/**
|
|
73
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
74
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
75
|
+
*/const U={Null:0,Undefined:1,Boolean:2,Number:3,String:4,Date:5,RegEx:6,Array:7,Object:8,UserDefined:255};function R(e){if(t.isNotDefined(e))return!1;switch(typeof e){case"number":return!0;case"string":return!isNaN(Date.parse(e));case"object":return e instanceof Date&&!isNaN(e.getTime());default:return!1}}function B(e){return!t.isNotDefined(e)&&e instanceof RegExp}class S{constructor(){this.reader=new _,this.writer=new N,this.converters=new Map([[U.Null,new m(this)],[U.Undefined,new A(this)],[U.Boolean,new w(this)],[U.Number,new v(this)],[U.String,new O(this)],[U.Date,new b(this)],[U.RegEx,new T(this)],[U.Array,new y(this)],[U.Object,new E(null,this)],[U.UserDefined,new Map([])]])}addConverter(e){e.serializer=this;this.converters.get(U.UserDefined).set(e.targetCtor.name,e)}removeConverter(e){this.converters.get(U.UserDefined).remove(e.targetCtor.name)}serialize(e,t={}){this.writer.buffer=new ArrayBuffer(1024);return this._serialize(e).slice(0,this.writer.offset)}_serialize(e){const t=this._getBinaryTypeOf(e);this.writer.setUint8(t);let s=this.converters.get(t);if(t===U.UserDefined){const t=e.constructor,r=t.name;this.writer.setUint8(r.length),this.writer.setString(r),s.has(r)||(console.info(`Need to create new converter for ${r} serialization. The serialization of this class could be optimized using it's own dedicated serializer that extend TBinaryConverter and add it to serializer converters.`),s.set(r,new E(t,this))),s=s.get(r)}return s.to(this.writer,e),this.writer.buffer}_getBinaryTypeOf(e){let s;return s=t.isNull(e)?U.Null:t.isUndefined(e)?U.Undefined:t.isBoolean(e)?U.Boolean:t.isNumber(e)?U.Number:t.isString(e)?U.String:R(e)?U.Date:B(e)?U.RegEx:t.isArray(e)?U.Array:t.isObject(e)?U.Object:U.UserDefined,s}deserialize(e){if(!t.isNotDefined(e)&&0!==e.length)return this.reader.setBuffer(e,0,e.length),this._deserialize()}_deserialize(){const e=this.reader.getUint8();let t=this.converters.get(e);if(e===U.UserDefined){const e=this.reader.getUint8(),s=this.reader.getString(e);t=t.has(s)?t.get(s):null}if(!t)throw new TypeError(`Unable to found appropriate converter for deserialize type: ${e}`);return t.from(this.reader)}}const M=new S;
|
|
76
|
+
/**
|
|
77
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
78
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
79
|
+
*
|
|
80
|
+
* @class TDataBaseManager
|
|
81
|
+
* @classdesc The base class of database managers. Give the basic interface about database call.
|
|
82
|
+
*
|
|
83
|
+
* @requires {@link HttpVerb}
|
|
84
|
+
* @requires {@link ResponseType}
|
|
85
|
+
* @requires {@link HttpStatusCode}
|
|
86
|
+
* @requires {@link TOrchestrator}
|
|
87
|
+
* @requires {@link TStore}
|
|
88
|
+
*
|
|
89
|
+
* @example Todo
|
|
90
|
+
*
|
|
91
|
+
*/const x=new class{constructor(){this._id=0}get id(){return this._id+=1,this._id}},$=e.toEnum({CreateOne:0,CreateMany:1,ReadOne:2,ReadMany:3,ReadWhere:4,ReadAll:5,UpdateOne:6,UpdateMany:7,UpdateWhere:8,UpdateAll:9,DeleteOne:10,DeleteMany:11,DeleteWhere:12,DeleteAll:13});class D{constructor(e={}){const t={basePath:"/",responseType:l.Json,bunchSize:500,requestAggregationTime:200,requestsConcurrency:6,logger:s.DefaultLogger,...e};this.basePath=t.basePath,this.responseType=t.responseType,this.bunchSize=t.bunchSize,this.requestAggregationTime=t.requestAggregationTime,this.requestsConcurrency=t.requestsConcurrency,this.logger=t.logger,this._cache=new h,this._waitingQueue=[],this._aggregateQueue=[],this._requestQueue=[],this._processQueue=[],this._aggregationTimeoutId=null,this._idToRequest=[]}static get requestId(){return D._requestId++,D._requestId}get basePath(){return this._basePath}set basePath(e){if(t.isNull(e))throw new TypeError("Base path cannot be null ! Expect a non empty string.");if(t.isUndefined(e))throw new TypeError("Base path cannot be undefined ! Expect a non empty string.");if(t.isNotString(e))throw new TypeError(`Base path cannot be an instance of ${e.constructor.name} ! Expect a non empty string.`);if(t.isEmptyString(e))throw new TypeError("Base path cannot be empty ! Expect a non empty string.");if(t.isBlankString(e))throw new TypeError("Base path cannot contain only whitespace ! Expect a non empty string.");this._basePath=e}get responseType(){return this._responseType}set responseType(e){if(t.isNull(e))throw new Error("TDataBaseManager: responseType cannot be null !");if(t.isNull(e))throw new TypeError("Response type cannot be null ! Expect a non empty string.");if(t.isUndefined(e))throw new TypeError("Response type cannot be undefined ! Expect a non empty string.");this._responseType=e}get bunchSize(){return this._bunchSize}set bunchSize(e){if(t.isNull(e))throw new TypeError("Bunch size cannot be null ! Expect a positive number.");if(t.isUndefined(e))throw new TypeError("Bunch size cannot be undefined ! Expect a positive number.");if(t.isNotNumber(e))throw new TypeError(`Bunch size cannot be an instance of ${e.constructor.name} ! Expect a positive number.`);if(!t.isNumberPositive(e))throw new TypeError("Bunch size cannot be lower or equal to zero ! Expect a positive number.");this._bunchSize=e}get requestAggregationTime(){return this._requestAggregationTime}set requestAggregationTime(e){if(t.isNull(e))throw new TypeError("Requests aggregation time cannot be null ! Expect a positive number.");if(t.isUndefined(e))throw new TypeError("Requests aggregation time cannot be undefined ! Expect a positive number.");if(t.isNotNumber(e))throw new TypeError(`Requests aggregation time cannot be an instance of ${e.constructor.name} ! Expect a positive number.`);if(t.isNumberNegative(e))throw new TypeError("Requests aggregation time cannot be lower or equal to zero ! Expect a positive number.");this._requestAggregationTime=e}get requestsConcurrency(){return this._requestsConcurrency}set requestsConcurrency(e){if(t.isNull(e))throw new TypeError("Minimum of simultaneous request cannot be null ! Expect a positive number.");if(t.isUndefined(e))throw new TypeError("Minimum of simultaneous request cannot be undefined ! Expect a positive number.");if(t.isNotNumber(e))throw new TypeError(`Minimum of simultaneous request cannot be an instance of ${e.constructor.name} ! Expect a positive number.`);if(t.isZero(e)||t.isNumberNegative(e))throw new TypeError("Minimum of simultaneous request cannot be lower or equal to zero ! Expect a positive number.");this._requestsConcurrency=e}get logger(){return this._logger}set logger(e){if(t.isNull(e))throw new TypeError("Progress manager cannot be null ! Expect an instance of TProgressManager.");if(t.isUndefined(e))throw new TypeError("Progress manager cannot be undefined ! Expect an instance of TProgressManager.");if(!(e instanceof s.TLogger))throw new TypeError(`Progress manager cannot be an instance of ${e.constructor.name} ! Expect an instance of TProgressManager.`);this._logger=e}setBasePath(e){return this.basePath=e,this}setResponseType(e){return this.responseType=e,this}setBunchSize(e){return this.bunchSize=e,this}setRequestAggregationTime(e){return this.requestAggregationTime=e,this}setRequestsConcurrency(e){return this.requestsConcurrency=e,this}setLogger(e){return this.logger=e,this}aggregateQueue(){clearTimeout(this._aggregationTimeoutId),this._aggregationTimeoutId=setTimeout(()=>{const e=this._idToRequest;let t=[];for(let s=e.length-1;s>=0;s--)t.push(e.pop()),t.length!==this._bunchSize&&0!==s||(this._requestQueue.push({_id:`readMany_${x.id}`,_timeStart:new Date,_type:$.ReadMany,method:n.Read.value,url:this._basePath,data:{ids:t},responseType:this._responseType}),t=[]);this.processQueue.call(this)},this._requestAggregationTime)}processQueue(){for(;this._requestQueue.length>0&&this._processQueue.length<this._requestsConcurrency;){const n=this._requestQueue.pop();this._processQueue.push(n);const o=new XMLHttpRequest;o.onloadstart=e.bind(this),o.onload=this._onLoad.bind(this,n,this._onEnd.bind(this,n,n.onLoad),this._onProgress.bind(this,n.onProgress),this._onError.bind(this,n,n.onError)),o.onloadend=t.bind(this),o.onprogress=this._onProgress.bind(this,n.onProgress),o.onreadystatechange=s.bind(this),o.onabort=r.bind(this),o.onerror=this._onError.bind(this,n,n.onError),o.ontimeout=i.bind(this),o.open(n.method,n.url,!0),o.setRequestHeader("Content-Type","application/json"),o.setRequestHeader("Accept","application/json"),o.responseType=n.responseType.value;const a=n.data&&n.responseType===l.Json?JSON.stringify(n.data):n.data;o.send(a)}function e(e){this.logger.progress(e)}function t(e){this.logger.progress(e)}function s(e){this.logger.debug(e)}function r(e){this.logger.error(e)}function i(e){this.logger.error(e)}}create(e,s,r,i){t.isArray(e)&&t.isNotEmptyArray(e)?t.isArrayOfSingleElement(e)?this._createOne(e[0],s,r,i):this._createMany(e,s,r,i):t.isObject(e)&&t.isNotEmptyObject(e)?this._createOne(e,s,r,i):i("TDataBaseManager.create: Invalid data type, expect object or array of objects.")}read(e,s,r,i,n){t.isString(e)&&t.isNotEmptyString(e)&&t.isNotBlankString(e)?this._readOne(e,s,r,i,n):t.isArray(e)&&t.isNotEmptyArray(e)?t.isArrayOfSingleElement(e)?this._readOne(e[0],s,r,i,n):this._readMany(e,s,r,i,n):t.isObject(e)?t.isEmptyObject(e)?this._readAll(s,r,i,n):this._readWhere(e,s,r,i,n):n("TDataBaseManager.read: Invalid data type, expect string, object or array of objects.")}update(e,s,r,i,n){t.isNotDefined(s)?n("TDataBaseManager.update: Update data cannot be null or undefined !"):t.isNotObject(s)?n("TDataBaseManager.update: Invalid update data type. Expect an object."):t.isString(e)&&t.isNotEmptyString(e)&&t.isNotBlankString(e)?this._updateOne(e,s,r,i,n):t.isArray(e)&&t.isNotEmptyArray(e)?t.isArrayOfSingleElement(e)?this._updateOne(e[0],s,r,i,n):this._updateMany(e,s,r,i,n):t.isObject(e)?t.isEmptyObject(e)?this._updateAll(s,r,i,n):this._updateWhere(e,s,r,i,n):n("TDataBaseManager.update: Invalid data type, expect string, object or array of objects.")}delete(e,s,r,i){t.isString(e)&&t.isNotEmptyString(e)&&t.isNotBlankString(e)?this._deleteOne(e,s,r,i):t.isArray(e)&&t.isNotEmptyArray(e)?t.isArrayOfSingleElement(e)?this._deleteOne(e[0],s,r,i):this._deleteMany(e,s,r,i):t.isObject(e)?t.isEmptyObject(e)?this._deleteAll(s,r,i):this._deleteWhere(e,s,r,i):i("TDataBaseManager.delete: Invalid data type, expect null, string, object or array of objects.")}_onLoad(e,t,s,r,n){const o=n.target,a=o.status,u=o.response,l=o.responseType;switch(a){case i.Ok.value:this._dispatchResponse(u,l,t,s,r);break;case i.NonAuthoritativeInformation.value:case i.NoContent.value:case i.ResetContent.value:case i.PartialContent.value:case i.MultiStatus.value:case i.AlreadyReported.value:case i.ContentDifferent.value:case i.IMUsed.value:case i.MultipleChoices.value:case i.MovedPermanently.value:case i.Found.value:case i.SeeOther.value:case i.NotModified.value:case i.UseProxy.value:case i.Unused.value:case i.TemporaryRedirect.value:case i.PermanentRedirect.value:case i.TooManyRedirects.value:case i.BadRequest.value:case i.Unauthorized.value:case i.PaymentRequired.value:case i.Forbidden.value:case i.NotFound.value:case i.MethodNotAllowed.value:case i.NotAcceptable.value:case i.ProxyAuthenticationRequired.value:case i.RequestTimeOut.value:case i.Conflict.value:case i.Gone.value:case i.LengthRequired.value:case i.PreconditionFailed.value:case i.RequestEntityTooLarge.value:case i.RequestRangeUnsatisfiable.value:case i.ExpectationFailed.value:case i.ImATeapot.value:case i.BadMapping.value:case i.UnprocessableEntity.value:case i.Locked.value:case i.MethodFailure.value:case i.UnorderedCollection.value:case i.UpgradeRequired.value:case i.PreconditionRequired.value:case i.TooManyRequests.value:case i.RequestHeaderFieldsTooLarge.value:case i.NoResponse.value:case i.RetryWith.value:case i.BlockedByWindowsParentalControls.value:case i.UnavailableForLegalReasons.value:case i.UnrecoverableError.value:case i.SSLCertificateError.value:case i.SSLCertificateRequired.value:case i.HTTPRequestSentToHTTPSPort.value:case i.ClientClosedRequest.value:case i.InternalServerError.value:case i.NotImplemented.value:case i.BadGateway.value:case i.ServiceUnavailable.value:case i.GatewayTimeOut.value:case i.HTTPVersionNotSupported.value:case i.VariantAlsoNegotiates.value:case i.InsufficientStorage.value:case i.LoopDetected.value:case i.BandwidthLimitExceeded.value:case i.NotExtended.value:case i.NetworkAuthenticationRequired.value:case i.UnknownError.value:case i.WebServerIsDown.value:case i.ConnectionTimedOut.value:case i.OriginIsUnreachable.value:case i.ATimeoutOccured.value:case i.SSLHandshakeFailed.value:case i.InvalidSSLCertificate.value:case i.RailgunError.value:r(u);break;default:throw new RangeError(`Unmanaged HttpStatusCode: ${a}`)}}_onProgress(e,s){t.isDefined(this.logger)?this.logger.progress(s,e):t.isDefined(e)&&e(s)}_onError(e,s,r){this._closeRequest(e),t.isDefined(this.logger)?this.logger.error(r,s):t.isDefined(s)&&s(r)}_onEnd(e,t,s){const r=e._type;switch(r){case $.ReadOne:case $.ReadMany:this._updateCache(s),this._updateWaitingQueue();break;case $.ReadWhere:case $.ReadAll:this._updateCache(s),this._updateWaitingQueue(),t(s);break;case $.CreateOne:case $.CreateMany:case $.UpdateOne:case $.UpdateMany:case $.UpdateWhere:case $.UpdateAll:case $.DeleteOne:case $.DeleteMany:case $.DeleteWhere:case $.DeleteAll:t(s);break;default:throw new RangeError(`Invalid request type: ${r}`)}this._closeRequest(e)}_dispatchResponse(e,t,s,r,i){switch(t){case l.ArrayBuffer.value:this._onArrayBuffer(e,s,r,i);break;case l.Blob.value:this._onBlob(e,s,r,i);break;case l.Json.value:this._onJson(e,s,r,i);break;case l.DOMString.value:case l.Default.value:this._onText(e,s,r,i);break;default:throw new Error(`Unknown response type: ${t}`)}}_closeRequest(e){if(this._processQueue.splice(this._processQueue.indexOf(e),1),Window.Itee&&Window.Itee.Debug){const t=(new Date).valueOf()-e._timeStart.valueOf(),s=`${this.constructor.name} close request [${e._id}] on ${t}ms.Waiting queue: ${this._waitingQueue.length}Request queue: ${this._requestQueue.length}Process queue: ${this._processQueue.length}==========================`;this.logger.debug(s)}this.processQueue()}_retrieveCachedValues(e){let s={},r=[],i=[];for(let n=0,o=e.length;n<o;n++){const o=e[n],a=this._cache.get(o);t.isDefined(a)?s[o]=a:t.isNull(a)?r.push(o):i.push(o)}return{results:s,underRequest:r,toRequest:i}}_updateCache(e){if(t.isNull(e))throw new TypeError("Data cannot be null ! Expect an array of object.");if(t.isUndefined(e))throw new TypeError("Data cannot be undefined ! Expect an array of object.");let s={};if(t.isArray(e))for(let t in e)s[e[t]._id]=e[t];else s=e;for(let[e,r]of Object.entries(s)){const s=this._cache.get(e);t.isNull(s)?this._cache.add(e,r,!0):t.isUndefined(s)?(this.logger.warn("Cache was not pre-allocated with null value."),this._cache.add(e,r)):this.logger.error("Cached value already exist !")}}_updateWaitingQueue(){const e=0===this._requestQueue.length&&0===this._processQueue.length;for(let s=this._waitingQueue.length-1;s>=0;s--){const r=this._waitingQueue[s];for(let e=r.underRequest.length-1;e>=0;e--){const s=r.underRequest[e],i=this._cache.get(s);t.isNotDefined(i)||(r.results[s]=i,r.underRequest.splice(r.underRequest.indexOf(s),1))}const i=0===r.underRequest.length;i?(this._waitingQueue.splice(s,1),r.onLoadCallback(r.results)):!i&&e&&(this.logger.warn("Incomplet demand but empty request/process queue"),this._waitingQueue.splice(s,1),r.onLoadCallback(r.results))}}_onArrayBuffer(e,t,s,r){}_onBlob(e,t,s,r){}_onJson(e,t,s,r){}_onText(e,t,s,r){}_createOne(e,t,s,r){this._requestQueue.push({_id:`createOne_${x.id}`,_timeStart:new Date,_type:$.CreateOne,method:n.Create.value,url:this._basePath,data:e,onLoad:t,onProgress:s,onError:r,responseType:this._responseType}),this.processQueue()}_createMany(e,t,s,r){this._requestQueue.push({_id:`createMany_${x.id}`,_timeStart:new Date,_type:$.CreateMany,method:n.Create.value,url:this._basePath,data:e,onLoad:t,onProgress:s,onError:r,responseType:this._responseType}),this.processQueue()}_readOne(e,t,s,r,i){const n=this._retrieveCachedValues([e]);if(0===n.toRequest.length)0===n.underRequest.length?s(n.results):(n.onLoadCallback=s,n.onProgressCallback=r,n.onErrorCallback=i,this._waitingQueue.push(n));else{n.onLoadCallback=s,n.onProgressCallback=r,n.onErrorCallback=i,this._waitingQueue.push(n);try{this._cache.add(e,null),n.underRequest.push(e),n.toRequest.splice(n.toRequest.indexOf(e),1)}catch(e){this.logger.error(e)}this._idToRequest.push(e),this.aggregateQueue()}}_readMany(e,t,s,r,i){const n=this._retrieveCachedValues(e);if(0===n.toRequest.length)0===n.underRequest.length?s(n.results):(n.onLoadCallback=s,n.onProgressCallback=r,n.onErrorCallback=i,this._waitingQueue.push(n));else{n.onLoadCallback=s,n.onProgressCallback=r,n.onErrorCallback=i,this._waitingQueue.push(n);const e=n.toRequest;let t;for(let s=e.length-1;s>=0;s--){t=e[s];try{this._cache.add(t,null),n.underRequest.push(t),n.toRequest.splice(n.toRequest.indexOf(t),1)}catch(e){this.logger.error(e)}this._idToRequest.push(t)}this.aggregateQueue()}}_readWhere(e,t,s,r,i){this._requestQueue.push({_id:`readWhere_${x.id}`,_timeStart:new Date,_type:$.ReadWhere,method:n.Read.value,url:this._basePath,data:{query:e,projection:t},onLoad:s,onProgress:r,onError:i,responseType:this._responseType}),this.processQueue()}_readAll(e,t,s,r){this._requestQueue.push({_id:`readAll_${x.id}`,_timeStart:new Date,_type:$.ReadAll,method:n.Read.value,url:this._basePath,data:{query:{},projection:e},onLoad:t,onProgress:s,onError:r,responseType:this._responseType}),this.processQueue()}_updateOne(e,t,s,r,i){this._requestQueue.push({_id:`updateOne_${x.id}`,_timeStart:new Date,_type:$.UpdateOne,method:n.Update.value,url:`${this._basePath}/${e}`,data:{update:t},onLoad:s,onProgress:r,onError:i,responseType:this._responseType}),this.processQueue()}_updateMany(e,t,s,r,i){this._requestQueue.push({_id:`updateMany_${x.id}`,_timeStart:new Date,_type:$.UpdateMany,method:n.Update.value,url:this._basePath,data:{ids:e,update:t},onLoad:s,onProgress:r,onError:i,responseType:this._responseType}),this.processQueue()}_updateWhere(e,t,s,r,i){this._requestQueue.push({_id:`updateWhere_${x.id}`,_timeStart:new Date,_type:$.UpdateWhere,method:n.Update.value,url:this._basePath,data:{query:e,update:t},onLoad:s,onProgress:r,onError:i,responseType:this._responseType}),this.processQueue()}_updateAll(e,t,s,r){this._requestQueue.push({_id:`updateAll_${x.id}`,_timeStart:new Date,_type:$.UpdateAll,method:n.Update.value,url:this._basePath,data:{query:{},update:e},onLoad:t,onProgress:s,onError:r,responseType:this._responseType}),this.processQueue()}_deleteOne(e,t,s,r){this._requestQueue.push({_id:`deleteOne_${x.id}`,_timeStart:new Date,_type:$.DeleteOne,method:n.Delete.value,url:`${this._basePath}/${e}`,data:null,onLoad:t,onProgress:s,onError:r,responseType:this._responseType}),this.processQueue()}_deleteMany(e,t,s,r){this._requestQueue.push({_id:`deleteMany_${x.id}`,_timeStart:new Date,_type:$.DeleteMany,method:n.Delete.value,url:this._basePath,data:{ids:e},onLoad:t,onProgress:s,onError:r,responseType:this._responseType}),this.processQueue()}_deleteWhere(e,t,s,r){this._requestQueue.push({_id:`deleteWhere_${x.id}`,_timeStart:new Date,_type:$.DeleteWhere,method:n.Delete.value,url:this._basePath,data:{query:e},onLoad:t,onProgress:s,onError:r,responseType:this._responseType}),this.processQueue()}_deleteAll(e,t,s){this._requestQueue.push({_id:`deleteAll_${x.id}`,_timeStart:new Date,_type:$.DeleteAll,method:n.Delete.value,url:this._basePath,data:{query:{}},onLoad:e,onProgress:t,onError:s,responseType:this._responseType}),this.processQueue()}}D._requestId=0,D._requests={waitingQueue:{},toProcess:{create:{},read:{},update:{},delete:{}},underProcess:{create:{},read:{},update:{},delete:{}},processed:{create:{},read:{},update:{},delete:{}}};const q=e.toEnum({Number:0,String:1,Uuid:2});const C=[];for(let e=0;e<256;++e)C.push((e+256).toString(16).slice(1));let I;const P=new Uint8Array(16);var k={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function L(e,t,s){const r=(e=e||{}).random??e.rng?.()??function(){if(!I){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");I=crypto.getRandomValues.bind(crypto)}return I(P)}();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(e,t=0){return(C[e[t+0]]+C[e[t+1]]+C[e[t+2]]+C[e[t+3]]+"-"+C[e[t+4]]+C[e[t+5]]+"-"+C[e[t+6]]+C[e[t+7]]+"-"+C[e[t+8]]+C[e[t+9]]+"-"+C[e[t+10]]+C[e[t+11]]+C[e[t+12]]+C[e[t+13]]+C[e[t+14]]+C[e[t+15]]).toLowerCase()}(r)}function F(e,t,s){return k.randomUUID&&!e?k.randomUUID():L(e)}class W{static isWebAPIMessage=!0;constructor(e){this._id=F(),this.type=e}get id(){return this._id}get type(){return this._type}set type(e){if(t.isNotString(e))throw new ReferenceError("WebAPIMessage type cannot be null or undefined !");if(t.isEmptyString(e))throw new TypeError("WebAPIMessage type cannot be an empty string !");this._type=e}toJSON(){return{id:this.id,type:this.type}}}class Q extends W{static isWebAPIMessageData=!0;constructor(e){super("_data"),this.data=e}toJSON(){const e=this.data===Object(this.data);return{...super.toJSON(),data:e?JSON.stringify(this.data):this.data}}}class V extends W{static isWebAPIMessageError=!0;constructor(e){super("_error"),this.error=e}get error(){return this._error}set error(e){if(t.isNotDefined(e))throw new ReferenceError(`Expect a string, or Error like. But got value of '${typeof e}' type: ${JSON.stringify(e,null,4)}`);if(t.isString(e))this._error={name:"UnknownError",message:e};else{if(!V.isError(e))throw new TypeError(`Expect a string, or Error like. But got value of '${typeof e}' type: ${JSON.stringify(e,null,4)}`);this._error={name:e.name,message:e.message,stack:e.stack}}}static isError(e){return e instanceof Error||t.isObject(e)&&(t.isDefined(e.name)||t.isDefined(e.message)||t.isDefined(e.stack))}toJSON(){return{...super.toJSON(),error:this.error}}}
|
|
92
|
+
/**
|
|
93
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
94
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
95
|
+
*/class j extends W{static isWebAPIMessageEvent=!0;constructor(e,t){super("_event"),this.name=e,this.data=t}toJSON(){const e=this.data===Object(this.data);return{...super.toJSON(),name:this.name,data:e?JSON.stringify(this.data):this.data}}}class J extends W{static isWebAPIMessageReady=!0;constructor(e={}){super("_ready");const t={isBind:!1,...e};this.isBind=t.isBind}get isBind(){return this._isBind}set isBind(e){if(t.isNotDefined(e))throw new ReferenceError("WebAPIMessageReady isBind cannot be null or undefined ! Expect a boolean value.");if(t.isNotBoolean(e))throw new TypeError("WebAPIMessageReady isBind expect a boolean value.");this._isBind=e}toJSON(){return{...super.toJSON(),isBind:this.isBind}}}class z extends W{static isWebAPIMessageRequest=!0;constructor(e,t=[]){super("_request"),this.method=e,this.parameters=t}get method(){return this._method}set method(e){if(t.isNotDefined(e))throw new ReferenceError("Expect a string that represent a api method name, but got undefined or null value.");if(t.isNotString(e))throw new TypeError(`Expect a string that represent a api method name, but got value of '${typeof e}' type: ${JSON.stringify(e,null,4)}`);if(t.isEmptyString(e)||t.isBlankString(e))throw new TypeError("Expect a string that represent a api method name, but got empty or blank string.");this._method=e}get parameters(){return this._parameters}set parameters(e){if(t.isNotArray(e))throw new TypeError(`Expect an array of parameters, but got value of '${typeof e}' type: ${JSON.stringify(e,null,4)}`);this._parameters=e}toJSON(){return{...super.toJSON(),method:this.method,parameters:this.parameters}}}class H extends W{static isWebApiMessageResponse=!0;constructor(e,t){super("_response"),this.request=e,this.result=t}get request(){return this._request}set request(e){t.isNull(e)||t.isUndefined(e)||(this._request=e)}get result(){return this._result}set result(e){this._result=e}toJSON(){return{...super.toJSON(),request:this.request,result:this.result}}}
|
|
96
|
+
/**
|
|
97
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
98
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
99
|
+
*/class G{constructor(e={}){const s={uri:"",allowedMethods:["*"],window:null,messageQueue:[],isReachable:!0,isReady:!1,...e,id:t.isDefined(e.id)?e.id:F()};this._id=s.id,this.uri=s.uri,this.allowedMethods=s.allowedMethods,this.window=s.window,this.isReachable=s.isReachable,this.isReady=s.isReady,this.messageQueue=s.messageQueue}get id(){return this._id}get uri(){return this._uri}set uri(e){if(t.isNotDefined(e))throw new ReferenceError("WebAPIOrigin uri cannot be null or undefined !");if(t.isNotString(e))throw new TypeError(`WebAPIOrigin uri expect to be a string. Got '${typeof e}' !`);if(t.isEmptyString(e))throw new RangeError("WebAPIOrigin uri cannot be an empty string !");this._uri=e}get allowedMethods(){return this._allowedMethods}set allowedMethods(e){if(t.isNotDefined(e))throw new ReferenceError("WebAPIOrigin methods cannot be null or undefined ! Expect an array of method name.");if(t.isNotArray(e))throw new TypeError(`WebAPIOrigin methods expect to be an array of method name (string).Got '${typeof e}' !`);if(t.isEmptyArray(e))throw new RangeError("WebAPIOrigin methods cannot be an empty array ! Expect an array of method name.");this._allowedMethods=e}get window(){return this._window}set window(e){this._window=e}get isReady(){return this._isReady}set isReady(e){if(t.isNotDefined(e))throw new ReferenceError("WebAPIOrigin isReady cannot be null or undefined !");if(t.isNotBoolean(e))throw new TypeError(`WebAPIOrigin isReady expect a Boolean. Got '${typeof e}' !`);this._isReady=e}get isReachable(){return this._isReachable}set isReachable(e){if(t.isNotDefined(e))throw new ReferenceError("WebAPIOrigin isReachable cannot be null or undefined !");if(t.isNotBoolean(e))throw new TypeError(`WebAPIOrigin isReachable expect a Boolean. Got '${typeof e}' !`);this._isReachable=e}get messageQueue(){return this._messageQueue}set messageQueue(e){this._messageQueue=e}setUri(e){return this.uri=e,this}setAllowedMethods(e){return this.allowedMethods=e,this}addAllowedMethod(e){return this.allowedMethods.includes(e)||this.allowedMethods.push(e),this}removeAllowedMethod(e){const t=this.allowedMethods.indexOf(e);return t>=0&&this.allowedMethods.slice(t,e),this}setWindow(e){return this.window=e,this}setReadyState(e){return this.isReady=e,this}setReachableState(e){return this.isReachable=e,this}}class K{static isWorkerMessage=!0;constructor(e){this.type=e}get type(){return this._type}set type(e){this._type=e}toJSON(){return{type:this.type}}}class X extends K{static isWorkerMessageData=!0;constructor(e,t){super(e),this.buffer=t}toJSON(){return{...super.toJSON(),buffer:this.buffer}}}class Y extends K{static isWorkerMessageError=!0;constructor(e){super("error"),this.message=e.message,this.stack=e.stack}toJSON(){return{...super.toJSON(),message:this.message,stack:this.stack}}}class Z extends K{static isWorkerMessageProgress=!0;constructor(e=0,t=0){super("progress"),this.lengthComputable=!1,this.loaded=e,this.total=t}get loaded(){return this._loaded}set loaded(e){this._loaded=e,this._checkIfLengthComputable()}get total(){return this._total}set total(e){this._total=e,this._checkIfLengthComputable()}_checkIfLengthComputable(){this.lengthComputable=!1,this._total>0&&this._total<Number.MAX_SAFE_INTEGER&&this._loaded>=0&&this._loaded<Number.MAX_SAFE_INTEGER&&(this.lengthComputable=!0)}toJSON(){return{...super.toJSON(),lengthComputable:this.lengthComputable,loaded:this.loaded,total:this.total}}}exports.AbstractWorker=class{postProgress(e){e.isWorkerMessageProgress?postMessage(e.toJSON()):postMessage(new Z(e.loaded,e.total).toJSON())}postError(e){e.isWorkerMessageError?postMessage(e.toJSON()):postMessage(new Y(e).toJSON())}postData(e,s){if(t.isArray(s))postMessage(new X(e,s).toJSON(),[...s]);else{if(!t.isArrayBuffer(s))throw new TypeError(`AbstractWorker.postData: Unable to post data of type [${e}].`);postMessage(new X(e,s).toJSON(),[s])}}onMessage(e){if(t.isNotDefined(e))return this.postError(new Error("Message event cannot be null or undefined !")),!0;const s=e.data;if(t.isNotDefined(s))return this.postError(new Error("Message data cannot be null or undefined !")),!0;const r=s.type;if(t.isNotDefined(r))return this.postError(new Error("Message data type cannot be null or undefined !")),!0;if("methodCall"===s.type){const e=s.method;if(t.isNotDefined(e))return this.postError(new Error('Message of type "methodCall" cannot have null, undefined or empty name !')),!0;if(t.isNotString(e))return this.postError(new Error('Message of type "methodCall" expect name to be a string !')),!0;if(t.isEmptyString(e))return this.postError(new Error('Message of type "methodCall" expect name to be a non empty string !')),!0;const r=s.parameters||[];return t.isNotArray(r)?(this.postError(new Error('Message of type "methodCall" expect parameters to be an array !')),!0):(this._invoke(e,r),!0)}}_invoke(e,t=[]){try{const s=this[e](...t);s&&postMessage({type:e,result:s})}catch(e){this.postError(e)}}},exports.ArrayBinaryConverter=y,exports.BinaryType=U,exports.Byte=p,exports.DateBinaryConverter=b,exports.DefaultBinarySerializer=M,exports.Endianness=g,exports.FileFormat=r,exports.HttpStatusCode=i,exports.HttpVerb=n,exports.Keys=o,exports.MimeType=a,exports.Mouse=u,exports.NullBinaryConverter=m,exports.NumberBinaryConverter=v,exports.ObjectBinaryConverter=E,exports.RegExBinaryConverter=T,exports.ResponseType=l,exports.StringBinaryConverter=O,exports.TAbstractFactory=d,exports.TBinaryConverter=f,exports.TBinaryReader=_,exports.TBinarySerializer=S,exports.TBinaryWriter=N,exports.TCloningFactory=class extends d{constructor(e={}){super({...e})}create(e,...t){return super.create(e,...t),this.get(e).clone(...t)}}
|
|
100
|
+
/**
|
|
101
|
+
* @class
|
|
102
|
+
* @classdesc The TInstancingFactory is a kind a factory that performe instanciation based on registred constructor.
|
|
103
|
+
* @extends TAbstractFactory
|
|
104
|
+
*
|
|
105
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
106
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
107
|
+
*/,exports.TDataBaseManager=D,exports.TIdFactory=class{constructor(e=q.Number,t=null){this.type=e,this.base=t,this._counter=0}get type(){return this._type}set type(e){if(t.isNull(e))throw new Error(`Type cannot be null ! Expect an value from TIdFactoryType enum: ${q.types()}`);if(t.isUndefined(e))throw new Error(`Type cannot be undefined ! Expect an value from TIdFactoryType enum: ${q.types()}`);if(!q.includes(e))throw new Error(`Invalide type ! Expect an value from TIdFactoryType enum: ${q.types()}`);this._type=e}get base(){return this._base}set base(e){if(t.isUndefined(e))throw new Error("Base cannot be undefined ! Expect an instance of Object3D.");if(this._type===q.Number&&t.isNotNumber(e))throw new Error("Invalide Base ! It does not match the type.");if(this._type===q.String&&t.isNotString(e))throw new Error("Invalide Base ! It does not match the type.");this._base=e}setType(e){return this.type=e,this}setBase(e){return this.base=e,this}createId(){return this._base+this._counter++}},exports.TIdFactoryType=q,exports.TInstancingFactory=class extends d{constructor(e={}){super({...e})}create(e,...t){return super.create(e,...t),new this.get(e)(...t)}},exports.TKeyboardController=c,exports.TMouseController=
|
|
108
|
+
/**
|
|
109
|
+
* @class
|
|
110
|
+
* @classdesc TMouseController allow single source of thruth for mouse state checking
|
|
111
|
+
* @author [Tristan Valcke]{@link https://github.com/Itee}
|
|
112
|
+
* @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause}
|
|
113
|
+
* @example
|
|
114
|
+
* (1) create a global variable:
|
|
115
|
+
* var keyboard = new TKeyboardController();
|
|
116
|
+
* (2) during main loop:
|
|
117
|
+
* keyboard.update();
|
|
118
|
+
* (3) check state of keys:
|
|
119
|
+
* keyboard.down("A") -- true for one update cycle after key is pressed
|
|
120
|
+
* keyboard.pressed("A") -- true as long as key is being pressed
|
|
121
|
+
* keyboard.up("A") -- true for one update cycle after key is released
|
|
122
|
+
*
|
|
123
|
+
* See TKeyboardController.k object data below for names of keys whose state can be polled
|
|
124
|
+
*/
|
|
125
|
+
class{constructor(){}},exports.TStore=h,exports.UndefinedBinaryConverter=A,exports.WebAPI=class{constructor(e={}){const t={logger:s.DefaultLogger,allowedOrigins:[],requestTimeout:2e3,methods:this,broadcastReadyOnInit:!0,...e};this._localOriginUri=window.location.origin,this._awaitingRequest=new Map,this._eventListeners={},window.addEventListener("message",this._onMessage.bind(this),!1),this.logger=t.logger,this.allowedOrigins=t.allowedOrigins,this.requestTimeout=t.requestTimeout,this.methods=t.methods,t.broadcastReadyOnInit&&this._broadcastReadyMessage()}get logger(){return this._logger}set logger(e){if(t.isNull(e))throw new ReferenceError(`[${this._localOriginUri}]: The logger cannot be null, expect a TLogger.`);if(t.isUndefined(e))throw new ReferenceError(`[${this._localOriginUri}]: The logger cannot be undefined, expect a TLogger.`);if(!e.isLogger)throw new ReferenceError(`[${this._localOriginUri}]: The logger cannot be undefined, expect a TLogger.`);this._logger=e}get allowedOrigins(){return this._allowedOrigins}set allowedOrigins(t){this._allowedOrigins=[];const s=e.toArray(t);if(s.includes("*"))return this.logger.warn(`[${this._localOriginUri}]: This webApi is allowed for all origin and could lead to security concerne !`),void this._allowedOrigins.push("*");for(let e of s){const t=new G({id:e.id,uri:e.uri,methods:e.methods,window:this._getOriginWindow(e.uri)});this._allowedOrigins.push(t)}}get requestTimeout(){return this._requestTimeout}set requestTimeout(e){if(t.isNull(e))throw new ReferenceError(`[${this._localOriginUri}]: The request timeout cannot be null, expect to be 0 or a positive number.`);if(t.isUndefined(e))throw new ReferenceError(`[${this._localOriginUri}]: The request timeout cannot be undefined, expect to be 0 or a positive number.`);if(t.isNotNumber(e))throw new ReferenceError(`[${this._localOriginUri}]: The request timeout expect to be 0 or a positive number.`);if(t.isNumberNegative(e)&&!t.isZero(e))throw new ReferenceError(`[${this._localOriginUri}]: The request timeout expect to be 0 or a positive number.`);this._requestTimeout=e}get methods(){return this._methods}set methods(e){if(t.isNull(e))throw new ReferenceError(`[${this._localOriginUri}]: The methods cannot be null, expect any keyed collection of function.`);if(t.isUndefined(e))throw new ReferenceError(`[${this._localOriginUri}]: The methods cannot be undefined, expect any keyed collection of function.`);this._methods=e}setLogger(e){return this.logger=e,this}setAllowedOrigins(e){return this.allowedOrigins=e,this}setRequestTimeout(e){return this.requestTimeout=e,this}setMethods(e){return this.methods=e,this}addEventListener(e,s){t.isNotDefined(this._eventListeners[e])&&(this._eventListeners[e]=[]),this._eventListeners[e].push(s)}removeListener(e,s){if(t.isNotDefined(this._eventListeners[e]))return;const r=this._eventListeners[e].indexOf(s);r>-1&&this._eventListeners[e].splice(r,1)}_isInIframe(){try{return window.self!==window.top}catch(e){return!0}}_isNotAllowedForAllOrigins(){return!this._allowedOrigins.includes("*")}_isNotAllowedOrigin(e){return!this._allowedOrigins.filter(e=>"*"!==e).map(e=>e.uri).includes(e)}_isSameOrigin(e){return this._localOriginUri===e}_isNotAllowedForAllMethods(e){return-1===e.allowedMethods.indexOf("*")}_isNotAllowedMethod(e,t){return-1===e.allowedMethods.indexOf(t)}_methodNotExist(e){return t.isNotDefined(this.methods[e])}_getAllowedOriginBy(e,t){return this.allowedOrigins.find(s=>s[e]===t)}_getOriginWindow(e){let s;if(this._isInIframe())s=window.parent;else{const r=document.getElementsByTagName("iframe"),i=Array.from(r).find(t=>t.src.includes(e));t.isNotDefined(i)?(this.logger.warn(`[${this._localOriginUri}]: Unable to find iframe element for [${e}] URI !`),s=null):s=i.contentWindow}return s}_processMessageQueueOf(e){const t=e.messageQueue;for(let s=t.length-1;s>=0;s--)this.postMessageTo(e.id,t.shift())}_broadcastReadyMessage(){const e=new J;let s=250;const r=()=>{const i=this.allowedOrigins.filter(e=>!e.isReady&&e.isReachable);if(!t.isEmptyArray(i)){for(let t of i)this.postReadyTo(t.id,e);s+=s,setTimeout(r,s)}};r()}async _onMessage(e){if(this._isNotAllowedForAllOrigins()&&this._isNotAllowedOrigin(e.origin))return void this.logger.warn(`[${this._localOriginUri}]: An unallowed origin [${e.origin}] try to access the web api.`);if(this._isSameOrigin(e.origin))return void this.logger.warn(`[${this._localOriginUri}]: A local origin try to access the web api... \n or... Am i talking to myself ?\n Said i (${t.isString(e.data)?e.data:JSON.stringify(e.data)}) ?\n Hummm... Ehhooo ! Who's there ?\n `);let s=this._getAllowedOriginBy("uri",e.origin);t.isNotDefined(s)?(s=new G({uri:e.origin,window:e.source}),this.allowedOrigins.push(s)):t.isNull(s.window)&&(s.window=e.source);const r=e.data,i=t.isObject(r)?r:JSON.parse(r);t.isNotDefined(i)?this.logger.error(`[${this._localOriginUri}]: Recieve null or undefined message from [${s.uri}] ! Expect a json object.`):await this._dispatchMessageFrom(s,i)}async _dispatchMessageFrom(e,t){switch(this.logger.log(`[${this._localOriginUri}]: Recieve message of type '${t.type}' from [${e.uri}].`),t.type){case"_ready":this._onReadyFrom(e,t);break;case"_request":await this._onRequestFrom(e,t);break;case"_response":this._onResponseFrom(e,t);break;case"_data":this.onDataFrom(e,t);break;case"_event":this.onEventFrom(e,t);break;case"_error":this.onErrorFrom(e,t);break;default:this.onMessageFrom(e,t)}}_onReadyFrom(e,t){if(!e.isReady&&(e.isReady=!0,!t.isBind)){const t=new J({isBind:!0});this.postMessageTo(e.id,t,!0)}this._processMessageQueueOf(e)}async _onRequestFrom(e,t){let s;const r=t.method,i=t.parameters;if(this._isNotAllowedForAllMethods(e)&&this._isNotAllowedMethod(e,r))this.logger.error(`[${this._localOriginUri}]: Origin [${e.uri}] try to access an unallowed method named '${r}'.`),s=new V(new RangeError(`Trying to access an unallowed method named '${r}'.`));else if(this._methodNotExist(r))this.logger.error(`[${this._localOriginUri}]: Origin [${e.uri}] try to access an unexisting method named '${r}'.`),s=new V(new RangeError(`Trying to access an unexisting method named '${r}'.`));else try{const e=await this.methods[r](...i);s=new Q(e)}catch(e){s=new V(e)}this.postResponseTo(e.id,t,s)}_onResponseFrom(e,s){const r=s.request.id;if(!this._awaitingRequest.has(r))return;const i=this._awaitingRequest.get(r);this._awaitingRequest.delete(r),clearTimeout(i.timeoutId);const n=s.result;t.isDefined(n)?"_error"===n.type?i.reject(n.error):"_data"===n.type?i.resolve(n.data):i.resolve(n):i.resolve()}onErrorFrom(e,t){this.logger.error(`[${this._localOriginUri}]: the origin [${e.uri}] send error => ${JSON.stringify(t.error,null,4)}. Need you to reimplement this method ?`)}onDataFrom(e,t){this.logger.log(`[${this._localOriginUri}]: the origin [${e.uri}] send data => ${JSON.stringify(t.data,null,4)}. Need you to reimplement this method ?`)}onMessageFrom(e,t){this.logger.log(`[${this._localOriginUri}]: the origin [${e.uri}] send custom message => ${JSON.stringify(t,null,4)}. Need you to reimplement this method ?`)}onEventFrom(e,t){const s=this._eventListeners[t.name];for(const e of s)e(t.data)}postReadyTo(e,t){const s=t&&t.constructor.isWebAPIMessageReady?t:new J;this.postMessageTo(e,s,!0)}postRequestTo(e,t,...s){const r=t&&t.constructor.isWebAPIMessageRequest?t:new z(t,s);return new Promise((t,s)=>{try{this._awaitingRequest.set(r.id,{request:r,resolve:t,reject:s,timeoutId:setTimeout(()=>{this._awaitingRequest.delete(r.id),s(new Error(`Request timeout for ${JSON.stringify(r,null,4)}`))},this.requestTimeout)}),this.postMessageTo(e,r)}catch(e){s(e)}})}postResponseTo(e,t,s){const r=s&&s.constructor.isWebAPIMessageResponse?s:new H(t,s);this.postMessageTo(e,r)}postErrorTo(e,t){const s=t&&t.constructor.isWebAPIMessageError?t:new V(t);this.postMessageTo(e,s)}postDataTo(e,t){const s=t&&t.constructor.isWebAPIMessageData?t:new Q(t);this.postMessageTo(e,s)}postMessageTo(e,s,r=!1){if(t.isNotDefined(e))throw new ReferenceError(`[${this._localOriginUri}]: Unable to post message to null or undefined origin id !`);if(t.isNotDefined(s))throw new ReferenceError(`[${this._localOriginUri}]: Unable to post null or undefined message !`);const i=this._getAllowedOriginBy("id",e);if(t.isNotDefined(i))throw new ReferenceError(`[${this._localOriginUri}]: Unable to retrieved origin with id: ${e}`);try{r||i.isReady?r&&!i.window?(this.logger.error(`[${this._localOriginUri}]: Origin [${i.uri}] is unreachable !`),i.messageQueue.push(s)):(this.logger.log(`[${this._localOriginUri}]: Send message of type '${s.type}' to [${i.uri}]`),i.window.postMessage(JSON.stringify(s),i.uri)):(this.logger.warn(`[${this._localOriginUri}]: Origin [${i.uri}] is not ready yet !`),i.messageQueue.push(s))}catch(e){this.logger.error(e)}}postEvent(e="DefaultEventName",t){const s=t&&t.constructor.isWebAPIMessageEvent?t:new j(e,t),r=this._allowedOrigins.filter(e=>"*"!==e);for(let e=0;e<r.length;e++){const t=r[e].id;this.postMessageTo(t,s)}}},exports.WebAPIMessage=W,exports.WebAPIMessageData=Q,exports.WebAPIMessageError=V,exports.WebAPIMessageProgress=class extends W{static isWebAPIMessageProgress=!0;constructor(e=0,t=0){super("_progress"),this.lengthComputable=!1,this.loaded=e,this.total=t}get loaded(){return this._loaded}set loaded(e){this._loaded=e,this._checkIfLengthComputable()}get total(){return this._total}set total(e){this._total=e,this._checkIfLengthComputable()}_checkIfLengthComputable(){this.lengthComputable=!1,this._total>0&&this._total<Number.MAX_SAFE_INTEGER&&this._loaded>=0&&this._loaded<Number.MAX_SAFE_INTEGER&&(this.lengthComputable=!0)}toJSON(){return{...super.toJSON(),lengthComputable:this.lengthComputable,loaded:this.loaded,total:this.total}}},exports.WebAPIMessageReady=J,exports.WebAPIMessageRequest=z,exports.WebAPIMessageResponse=H,exports.WorkerMessage=K,exports.WorkerMessageData=X,exports.WorkerMessageError=Y,exports.WorkerMessageMethodCall=class extends K{static isWorkerMessageMethodCall=!0;constructor(e,t=[]){super("methodCall"),this.method=e,this.parameters=t}get method(){return this._method}set method(e){t.isNull(e)||t.isUndefined(e)||t.isNotString(e)||(this._method=e)}get parameters(){return this._parameters}set parameters(e){t.isNotArray(e)||(this._parameters=e)}toJSON(){return{...super.toJSON(),method:this.method,parameters:this.parameters}}},exports.WorkerMessageProgress=Z,exports.isDate=R,exports.isRegEx=B;
|