@rootintf/protocol-2phw 0.7.5-api-0.7 → 1.0.28-api-0.8

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.
@@ -1,23 +1,82 @@
1
- const validate_Msg2PhW = validate10;const pattern0 = new RegExp("0\\.7", "u");function validate10(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data["2PhW"] === undefined) && (missing0 = "2PhW")){validate10.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data["2PhW"] !== undefined){let data0 = data["2PhW"];{if(typeof data0 === "string"){if(!pattern0.test(data0)){validate10.errors = [{instancePath:instancePath+"/2PhW",schemaPath:"#/properties/2PhW/pattern",keyword:"pattern",params:{pattern: "0\\.7"},message:"must match pattern \""+"0\\.7"+"\""}];return false;}}else {validate10.errors = [{instancePath:instancePath+"/2PhW",schemaPath:"#/properties/2PhW/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}}}}}else {validate10.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate10.errors = vErrors;return errors === 0;}const validate_MsgOptions = validate11;function validate11(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.options === undefined) && (missing0 = "options")){validate11.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.options !== undefined){let data0 = data.options;if(!(data0 && typeof data0 == "object" && !Array.isArray(data0))){validate11.errors = [{instancePath:instancePath+"/options",schemaPath:"#/properties/options/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}}}else {validate11.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate11.errors = vErrors;return errors === 0;}const validate_Options_delay = validate12;function validate12(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.ttl_msec_incr === undefined) && (missing0 = "ttl_msec_incr")){validate12.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.ttl_msec_incr !== undefined){let data0 = data.ttl_msec_incr;const _errs1 = errors;{if(Array.isArray(data0)){var valid1 = true;const len0 = data0.length;for(let i0=0; i0<len0; i0++){let data1 = data0[i0];const _errs3 = errors;if(!(((typeof data1 == "number") && (!(data1 % 1) && !isNaN(data1))) && (isFinite(data1)))){validate12.errors = [{instancePath:instancePath+"/ttl_msec_incr/" + i0,schemaPath:"#/properties/ttl_msec_incr/items/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];return false;}var valid1 = _errs3 === errors;if(!valid1){break;}}}else {validate12.errors = [{instancePath:instancePath+"/ttl_msec_incr",schemaPath:"#/properties/ttl_msec_incr/type",keyword:"type",params:{type: "array"},message:"must be array"}];return false;}}var valid0 = _errs1 === errors;}else {var valid0 = true;}if(valid0){if(data.reason !== undefined){const _errs5 = errors;if(typeof data.reason !== "string"){validate12.errors = [{instancePath:instancePath+"/reason",schemaPath:"#/properties/reason/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid0 = _errs5 === errors;}else {var valid0 = true;}}}}else {validate12.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate12.errors = vErrors;return errors === 0;}const validate_MsgWarp = validate13;function validate13(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.warp === undefined) && (missing0 = "warp")){validate13.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.warp !== undefined){let data0 = data.warp;{if(data0 && typeof data0 == "object" && !Array.isArray(data0)){let missing1;if(((data0.user === undefined) && (missing1 = "user")) || ((data0.hyperport === undefined) && (missing1 = "hyperport"))){validate13.errors = [{instancePath:instancePath+"/warp",schemaPath:"#/properties/warp/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];return false;}else {if(data0.ttl_msec !== undefined){let data1 = data0.ttl_msec;const _errs3 = errors;if(!(((typeof data1 == "number") && (!(data1 % 1) && !isNaN(data1))) && (isFinite(data1)))){validate13.errors = [{instancePath:instancePath+"/warp/ttl_msec",schemaPath:"#/properties/warp/properties/ttl_msec/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];return false;}var valid1 = _errs3 === errors;}else {var valid1 = true;}if(valid1){if(data0.instantaneous !== undefined){const _errs5 = errors;if(typeof data0.instantaneous !== "boolean"){validate13.errors = [{instancePath:instancePath+"/warp/instantaneous",schemaPath:"#/properties/warp/properties/instantaneous/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];return false;}var valid1 = _errs5 === errors;}else {var valid1 = true;}}}}else {validate13.errors = [{instancePath:instancePath+"/warp",schemaPath:"#/properties/warp/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}}}}else {validate13.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate13.errors = vErrors;return errors === 0;}const validate_MsgEngage = validate14;function validate14(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.engage === undefined) && (missing0 = "engage")){validate14.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.engage !== undefined){let data0 = data.engage;{if(data0 && typeof data0 == "object" && !Array.isArray(data0)){let missing1;if(((data0.user === undefined) && (missing1 = "user")) || ((data0.hyperport === undefined) && (missing1 = "hyperport"))){validate14.errors = [{instancePath:instancePath+"/engage",schemaPath:"#/properties/engage/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];return false;}}else {validate14.errors = [{instancePath:instancePath+"/engage",schemaPath:"#/properties/engage/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}}}}else {validate14.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate14.errors = vErrors;return errors === 0;}
1
+ const schema_MsgWarp = validate19;function validate19(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){let vErrors = null;let errors = 0;const evaluated0 = validate19.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.warp === undefined) && (missing0 = "warp")){validate19.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.warp !== undefined){let data0 = data.warp;const _errs1 = errors;{if(data0 && typeof data0 == "object" && !Array.isArray(data0)){let missing1;if(((((data0.id === undefined) && (missing1 = "id")) || ((data0.user === undefined) && (missing1 = "user"))) || ((data0.hyperport === undefined) && (missing1 = "hyperport"))) || ((data0.ttl_msec === undefined) && (missing1 = "ttl_msec"))){validate19.errors = [{instancePath:instancePath+"/warp",schemaPath:"#/properties/warp/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];return false;}else {if(data0.id !== undefined){const _errs3 = errors;if(typeof data0.id !== "string"){validate19.errors = [{instancePath:instancePath+"/warp/id",schemaPath:"definitions_2PhW#/definitions/warp_id/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid1 = _errs3 === errors;}else {var valid1 = true;}if(valid1){if(data0.ttl_msec !== undefined){let data2 = data0.ttl_msec;const _errs6 = errors;if(!(((typeof data2 == "number") && (!(data2 % 1) && !isNaN(data2))) && (isFinite(data2)))){validate19.errors = [{instancePath:instancePath+"/warp/ttl_msec",schemaPath:"#/properties/warp/properties/ttl_msec/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];return false;}var valid1 = _errs6 === errors;}else {var valid1 = true;}if(valid1){if(data0.instantaneous !== undefined){const _errs8 = errors;if(typeof data0.instantaneous !== "boolean"){validate19.errors = [{instancePath:instancePath+"/warp/instantaneous",schemaPath:"#/properties/warp/properties/instantaneous/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];return false;}var valid1 = _errs8 === errors;}else {var valid1 = true;}}}}}else {validate19.errors = [{instancePath:instancePath+"/warp",schemaPath:"#/properties/warp/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}var valid0 = _errs1 === errors;}else {var valid0 = true;}if(valid0){if(data["2PhW"] !== undefined){const _errs10 = errors;if("0.8" !== data["2PhW"]){validate19.errors = [{instancePath:instancePath+"/2PhW",schemaPath:"definitions_2PhW#/definitions/2PhW/const",keyword:"const",params:{allowedValue: "0.8"},message:"must be equal to constant"}];return false;}var valid0 = _errs10 === errors;}else {var valid0 = true;}}}}else {validate19.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate19.errors = vErrors;return errors === 0;}validate19.evaluated = {"props":{"warp":true,"2PhW":true},"dynamicProps":false,"dynamicItems":false};const schema_MsgEngage = validate20;function validate20(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){let vErrors = null;let errors = 0;const evaluated0 = validate20.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.engage === undefined) && (missing0 = "engage")){validate20.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.engage !== undefined){let data0 = data.engage;const _errs1 = errors;{if(data0 && typeof data0 == "object" && !Array.isArray(data0)){let missing1;if(((data0.ok === undefined) && (missing1 = "ok")) || ((data0.rtt_msec === undefined) && (missing1 = "rtt_msec"))){validate20.errors = [{instancePath:instancePath+"/engage",schemaPath:"#/properties/engage/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];return false;}else {if(data0.ok !== undefined){const _errs3 = errors;if(typeof data0.ok !== "boolean"){validate20.errors = [{instancePath:instancePath+"/engage/ok",schemaPath:"#/properties/engage/properties/ok/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];return false;}var valid1 = _errs3 === errors;}else {var valid1 = true;}if(valid1){if(data0.rtt_msec !== undefined){let data2 = data0.rtt_msec;const _errs5 = errors;if(!(((typeof data2 == "number") && (!(data2 % 1) && !isNaN(data2))) && (isFinite(data2)))){validate20.errors = [{instancePath:instancePath+"/engage/rtt_msec",schemaPath:"#/properties/engage/properties/rtt_msec/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];return false;}var valid1 = _errs5 === errors;}else {var valid1 = true;}}}}else {validate20.errors = [{instancePath:instancePath+"/engage",schemaPath:"#/properties/engage/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}var valid0 = _errs1 === errors;}else {var valid0 = true;}if(valid0){if(data["2PhW"] !== undefined){const _errs7 = errors;if("0.8" !== data["2PhW"]){validate20.errors = [{instancePath:instancePath+"/2PhW",schemaPath:"definitions_2PhW#/definitions/2PhW/const",keyword:"const",params:{allowedValue: "0.8"},message:"must be equal to constant"}];return false;}var valid0 = _errs7 === errors;}else {var valid0 = true;}}}}else {validate20.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate20.errors = vErrors;return errors === 0;}validate20.evaluated = {"props":{"engage":true,"2PhW":true},"dynamicProps":false,"dynamicItems":false};const schema_MsgOptions = validate21;function validate21(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){let vErrors = null;let errors = 0;const evaluated0 = validate21.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.options === undefined) && (missing0 = "options")){validate21.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.options !== undefined){let data0 = data.options;const _errs1 = errors;if(!(data0 && typeof data0 == "object" && !Array.isArray(data0))){validate21.errors = [{instancePath:instancePath+"/options",schemaPath:"#/properties/options/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}var valid0 = _errs1 === errors;}else {var valid0 = true;}if(valid0){if(data["2PhW"] !== undefined){const _errs3 = errors;if("0.8" !== data["2PhW"]){validate21.errors = [{instancePath:instancePath+"/2PhW",schemaPath:"definitions_2PhW#/definitions/2PhW/const",keyword:"const",params:{allowedValue: "0.8"},message:"must be equal to constant"}];return false;}var valid0 = _errs3 === errors;}else {var valid0 = true;}}}}else {validate21.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate21.errors = vErrors;return errors === 0;}validate21.evaluated = {"props":{"options":true,"2PhW":true},"dynamicProps":false,"dynamicItems":false};
2
2
 
3
3
  // console.log('OUT', __name({variableName}) );
4
4
 
5
- function l_toBigInt_(ref, obj, ignore= false) {
6
- console.assert(ref !== BigInt(0), 'no labels initialized');
7
- let bigInt = BigInt(0);
8
- for (const [k,v] of Object.entries(obj)) {
9
- if ( ( ignore || v ) && ref[k])
10
- bigInt|= BigInt( ref[k] );
11
- // console.log('0b'+ bigInt.toString(2) );
12
- }
13
- return bigInt;
5
+ //-------------------------------------------------------------------------------------------------
6
+
7
+ function l_length_(obj_labels) {
8
+ if (! obj_labels || typeof obj_labels !== 'object')
9
+ throw new Error('obj_labels must be an object');
10
+ const obj_1label = Object.values(obj_labels);
11
+ if (! obj_1label.every(v => typeof v === 'number' && Number.isFinite(v)))
12
+ throw new Error('All values must be finite numbers');
13
+
14
+ const labels = Object.values(obj_labels);
15
+ if (labels.length === 0)
16
+ return 1; // Empty object case, start at 1
17
+
18
+ const value_max = Math.max(...labels);
19
+ if (value_max <= 0) return 1
20
+
21
+ const bit_highest = Math.floor(Math.log2(value_max));
22
+ return 1 << (bit_highest + 1);
14
23
  }
15
24
 
16
- function l_LL_(obj, x) {
17
- let obj_new= {};
18
- for (var [k,v] of Object.entries(obj))
19
- obj_new[k]= v<<x;
20
- return obj_new;
25
+ function l_array_(arr_labels, start = 1) {
26
+ if (! Array.isArray(arr_labels))
27
+ throw new Error('arr_labels must be an array');
28
+ if (! Number.isSafeInteger(start) || start < 0)
29
+ throw new Error('start must be a safe, non-negative integer');
30
+
31
+ return Object.freeze(arr_labels.reduce((acc, key, index) => {
32
+ acc[key] = start << index;
33
+ return acc;
34
+ }, {}));
35
+ }
36
+
37
+ function l_concat_(obj_labels, arg) {
38
+ if (! obj_labels || typeof obj_labels !== 'object')
39
+ throw new Error('obj_labels must be an object');
40
+ const obj_1label = Object.values(obj_labels);
41
+ if (! obj_1label.every(v => typeof v === 'number' && Number.isFinite(v)))
42
+ throw new Error('All values must be finite numbers');
43
+ if (! arg || (typeof arg !== 'object' && ! Array.isArray(arg)))
44
+ throw new Error('arg must be an object or array');
45
+
46
+ if (Array.isArray(arg)) {
47
+ const len = l_length_(obj_labels);
48
+ const arr_labels_new = l_array_(arg, len);
49
+ return l_concat_(obj_labels, arr_labels_new);
50
+ }
51
+
52
+ const next_pos = l_length_(obj_labels);
53
+ const arg_entries = Object.entries(arg);
54
+ const result = Object.create(null);
55
+ Object.entries(obj_labels).forEach(([k, v]) => {
56
+ if (k !== '__proto__' && k !== 'constructor')
57
+ result[k] = v;
58
+ });
59
+
60
+ let min_arg = Infinity;
61
+ for (const [, value] of arg_entries) {
62
+ if (typeof value !== 'number' || ! Number.isFinite(value))
63
+ continue; // Skip non-numeric
64
+
65
+ if (value > 0 && value < min_arg)
66
+ min_arg = value;
67
+ }
68
+ // Shift only if min_arg is less than next_pos
69
+ const shift = min_arg === Infinity || min_arg >= next_pos
70
+ ? 0
71
+ : Math.floor(Math.log2(next_pos / min_arg));
72
+
73
+ for (const [key, value] of arg_entries) {
74
+ if (!(key in result)) {
75
+ result[key] = value === 0 ? 0 : value << shift;
76
+ }
77
+ }
78
+
79
+ return Object.freeze(result);
21
80
  }
22
81
 
23
82
  //-------------------------------------------------------------------------------------------------
@@ -30,56 +89,85 @@ function handler_default_( /* ... */ ) {
30
89
 
31
90
  //-------------------------------------------------------------------------------------------------
32
91
 
33
- class BitLogr {
34
- constructor() {
35
- this._handler_log= handler_default_;
36
- this._Bint_labels= BigInt(0);
37
- this._Bint_toggled= BigInt(0);
38
-
39
- BitLogr.prototype['log']= function (nr_logged, /* ... */ ) {
40
- // console.log('NOP')
41
- };
42
- }
92
+ function l_toBigInt_(obj_labels, obj, ignore= false) {
93
+ if (! obj_labels || typeof obj_labels !== 'object')
94
+ throw new Error('obj_labels must be an object');
95
+ if (! obj || typeof obj !== 'object')
96
+ throw new Error('obj must be an object');
43
97
 
44
- set handler(fx) {
45
- this._handler_log= fx;
46
- }
47
-
48
- get labels() { return this._Bint_labels; }
49
- set labels(obj) {
50
- this._Bint_labels= obj;
51
- this._Bint_toggled= BigInt(0);
98
+ let bigInt = BigInt(0);
99
+ for (const [k,v] of Object.entries(obj)) {
100
+ if ( ( ignore || v ) && obj_labels[k] !== undefined && typeof obj_labels[k] === 'number')
101
+ bigInt|= BigInt( obj_labels[k] );
102
+ // console.log('0b'+ bigInt.toString(2) );
52
103
  }
104
+ return bigInt;
105
+ }
53
106
 
54
- // put= function(label, abbrv) {
55
- // let name= __name(label);
56
- // _labels[name]= label[name];
57
- // console.log(_labels);
58
- // }
107
+ // console.log(l_toBigInt_({},{}))
59
108
 
60
- get toggled() { return this._Bint_toggled; }
61
- set toggled(obj) {
62
- this._Bint_toggled= l_toBigInt_(this._Bint_labels, obj);
109
+ const LOGR = (function () {
110
+ let _instance; // Private variable to hold the single instance
63
111
 
64
- if (this._Bint_toggled === BigInt(0)) {
65
- console.log('adlkjasdlfk');
66
- return;
67
- }
112
+ function _create_instance() {
113
+ // Private state (replacing constructor properties)
114
+ let _handler_log = handler_default_;
115
+ let _obj_labels = undefined;
116
+ let _Bint_toggled = BigInt(0);
68
117
 
69
- BitLogr.prototype['log']= function (nr_logged, /* ... */ ) {
70
- if ( (BigInt(nr_logged) & this._Bint_toggled) === BigInt(0))
118
+ function _log_fxn(nr_logged, argsFn /* args */) {
119
+ if ((BigInt(nr_logged) & _Bint_toggled) === BigInt(0))
71
120
  return false;
72
-
73
- var args = Array.prototype.slice.call(arguments);
74
- args.shift(); // remove first arg: nr_logged
75
- this._handler_log.apply(this, args);
76
-
121
+
122
+ const args = argsFn();
123
+ _handler_log.apply(this, args);
124
+ // _handler_log.apply(this, args);
77
125
  return true;
126
+ }
127
+
128
+ return {
129
+ set handler(fx) {
130
+ _handler_log = fx;
131
+ },
132
+ get handler() {
133
+ return _handler_log;
134
+ },
135
+
136
+ get labels() { return _obj_labels; },
137
+ set labels(obj) {
138
+ _obj_labels = obj;
139
+ _Bint_toggled = BigInt(0);
140
+ },
141
+
142
+ // put= function(label, abbrv) {
143
+ // let name= __name(label);
144
+ // _labels[name]= label[name];
145
+ // console.log(_labels);
146
+ // }
147
+
148
+ get toggled() { return _Bint_toggled; },
149
+ set toggled(obj_toggled) {
150
+ _Bint_toggled= l_toBigInt_(_obj_labels, obj_toggled);
151
+ },
152
+
153
+ log(nr_logged, argsFn) {
154
+
155
+ return _log_fxn.call(this, nr_logged, argsFn); // Pass the thunk
156
+ }
78
157
  };
79
158
  }
80
159
 
81
- // log= function (nr_logged, /* ... */ ) {}
82
- }
160
+ // Public interface
161
+ return {
162
+ get_instance() {
163
+ if (!_instance) {
164
+ _instance = _create_instance(); // Lazy initialization
165
+ }
166
+ return _instance;
167
+ }
168
+ };
169
+
170
+ })();
83
171
 
84
172
  var jsonMsg_cjs = {};
85
173
 
@@ -89,63 +177,62 @@ function requireJsonMsg_cjs () {
89
177
  if (hasRequiredJsonMsg_cjs) return jsonMsg_cjs;
90
178
  hasRequiredJsonMsg_cjs = 1;
91
179
 
92
- Object.defineProperty(jsonMsg_cjs, '__esModule', { value: true });
180
+ const schema_Msg = validate18;function validate18(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){let vErrors = null;let errors = 0;const evaluated0 = validate18.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((((data.id === undefined) && (missing0 = "id")) || ((data.referer === undefined) && (missing0 = "referer"))) || ((data.dt === undefined) && (missing0 = "dt"))){validate18.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.id !== undefined){const _errs1 = errors;if(typeof data.id !== "string"){validate18.errors = [{instancePath:instancePath+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid0 = _errs1 === errors;}else {var valid0 = true;}if(valid0){if(data.dt !== undefined){const _errs3 = errors;if(typeof data.dt !== "string"){validate18.errors = [{instancePath:instancePath+"/dt",schemaPath:"#/properties/dt/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid0 = _errs3 === errors;}else {var valid0 = true;}}}}else {validate18.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate18.errors = vErrors;return errors === 0;}validate18.evaluated = {"props":{"id":true,"dt":true},"dynamicProps":false,"dynamicItems":false};const schema_Msg_msg = validate19;function validate19(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){let vErrors = null;let errors = 0;const evaluated0 = validate19.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data._msg === undefined) && (missing0 = "_msg")){validate19.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}}else {validate19.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate19.errors = vErrors;return errors === 0;}validate19.evaluated = {"dynamicProps":false,"dynamicItems":false};const schema_MsgAck_msg = validate20;function validate20(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){let vErrors = null;let errors = 0;const evaluated0 = validate20.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.ack === undefined) && (missing0 = "ack")){validate20.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.ack !== undefined){let data0 = data.ack;{if(data0 && typeof data0 == "object" && !Array.isArray(data0)){let missing1;if((data0.ok === undefined) && (missing1 = "ok")){validate20.errors = [{instancePath:instancePath+"/ack",schemaPath:"#/properties/ack/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];return false;}else {if(data0.ok !== undefined){if(typeof data0.ok !== "boolean"){validate20.errors = [{instancePath:instancePath+"/ack/ok",schemaPath:"#/properties/ack/properties/ok/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];return false;}}}}else {validate20.errors = [{instancePath:instancePath+"/ack",schemaPath:"#/properties/ack/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}}}}else {validate20.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate20.errors = vErrors;return errors === 0;}validate20.evaluated = {"props":{"ack":true},"dynamicProps":false,"dynamicItems":false};
93
181
 
94
- const validate_Msg = validate10;function validate10(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((((data.id === undefined) && (missing0 = "id")) || ((data.referer === undefined) && (missing0 = "referer"))) || ((data.dt === undefined) && (missing0 = "dt"))){validate10.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.id !== undefined){const _errs1 = errors;if(typeof data.id !== "string"){validate10.errors = [{instancePath:instancePath+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid0 = _errs1 === errors;}else {var valid0 = true;}if(valid0){if(data.referer !== undefined){let data1 = data.referer;const _errs3 = errors;{if(Array.isArray(data1)){if(data1.length > 2){validate10.errors = [{instancePath:instancePath+"/referer",schemaPath:"#/properties/referer/maxItems",keyword:"maxItems",params:{limit: 2},message:"must NOT have more than 2 items"}];return false;}else {if(data1.length < 2){validate10.errors = [{instancePath:instancePath+"/referer",schemaPath:"#/properties/referer/minItems",keyword:"minItems",params:{limit: 2},message:"must NOT have fewer than 2 items"}];return false;}else {var valid1 = true;const len0 = data1.length;for(let i0=0; i0<len0; i0++){const _errs5 = errors;if(typeof data1[i0] !== "string"){validate10.errors = [{instancePath:instancePath+"/referer/" + i0,schemaPath:"#/properties/referer/items/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid1 = _errs5 === errors;if(!valid1){break;}}}}}else {validate10.errors = [{instancePath:instancePath+"/referer",schemaPath:"#/properties/referer/type",keyword:"type",params:{type: "array"},message:"must be array"}];return false;}}var valid0 = _errs3 === errors;}else {var valid0 = true;}if(valid0){if(data.dt !== undefined){const _errs7 = errors;if(typeof data.dt !== "string"){validate10.errors = [{instancePath:instancePath+"/dt",schemaPath:"#/properties/dt/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid0 = _errs7 === errors;}else {var valid0 = true;}}}}}else {validate10.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate10.errors = vErrors;return errors === 0;}const validate_Msg_msg = validate11;function validate11(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data._msg === undefined) && (missing0 = "_msg")){validate11.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}}else {validate11.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate11.errors = vErrors;return errors === 0;}const validate_MsgAck = validate12;function validate12(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.ack === undefined) && (missing0 = "ack")){validate12.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.ack !== undefined){let data0 = data.ack;{if(data0 && typeof data0 == "object" && !Array.isArray(data0)){let missing1;if((data0.ok === undefined) && (missing1 = "ok")){validate12.errors = [{instancePath:instancePath+"/ack",schemaPath:"#/properties/ack/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];return false;}else {if(data0.ok !== undefined){if(typeof data0.ok !== "boolean"){validate12.errors = [{instancePath:instancePath+"/ack/ok",schemaPath:"#/properties/ack/properties/ok/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];return false;}}}}else {validate12.errors = [{instancePath:instancePath+"/ack",schemaPath:"#/properties/ack/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}}}}else {validate12.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate12.errors = vErrors;return errors === 0;}
182
+ const byteToHex = [];
183
+ for (let i = 0; i < 256; ++i) {
184
+ byteToHex.push((i + 0x100).toString(16).slice(1));
185
+ }
186
+ function unsafeStringify(arr, offset = 0) {
187
+ return (byteToHex[arr[offset + 0]] +
188
+ byteToHex[arr[offset + 1]] +
189
+ byteToHex[arr[offset + 2]] +
190
+ byteToHex[arr[offset + 3]] +
191
+ '-' +
192
+ byteToHex[arr[offset + 4]] +
193
+ byteToHex[arr[offset + 5]] +
194
+ '-' +
195
+ byteToHex[arr[offset + 6]] +
196
+ byteToHex[arr[offset + 7]] +
197
+ '-' +
198
+ byteToHex[arr[offset + 8]] +
199
+ byteToHex[arr[offset + 9]] +
200
+ '-' +
201
+ byteToHex[arr[offset + 10]] +
202
+ byteToHex[arr[offset + 11]] +
203
+ byteToHex[arr[offset + 12]] +
204
+ byteToHex[arr[offset + 13]] +
205
+ byteToHex[arr[offset + 14]] +
206
+ byteToHex[arr[offset + 15]]).toLowerCase();
207
+ }
95
208
 
96
- // Unique ID creation requires a high quality random # generator. In the browser we therefore
97
- // require the crypto API and do not support built-in fallback to lower quality random number
98
- // generators (like Math.random()).
99
209
  let getRandomValues;
100
210
  const rnds8 = new Uint8Array(16);
101
211
  function rng() {
102
- // lazy load so that environments that need to polyfill have a chance to do so
103
- if (!getRandomValues) {
104
- // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
105
- getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
106
-
107
212
  if (!getRandomValues) {
108
- throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
213
+ if (typeof crypto === 'undefined' || !crypto.getRandomValues) {
214
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
215
+ }
216
+ getRandomValues = crypto.getRandomValues.bind(crypto);
109
217
  }
110
- }
111
-
112
- return getRandomValues(rnds8);
113
- }
114
-
115
- /**
116
- * Convert array of 16 byte values to UUID string format of the form:
117
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
118
- */
119
-
120
- const byteToHex = [];
121
-
122
- for (let i = 0; i < 256; ++i) {
123
- byteToHex.push((i + 0x100).toString(16).slice(1));
124
- }
125
-
126
- function unsafeStringify(arr, offset = 0) {
127
- // Note: Be careful editing this code! It's been tuned for performance
128
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
129
- return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
218
+ return getRandomValues(rnds8);
130
219
  }
131
220
 
132
221
  const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
133
- var native = {
134
- randomUUID
135
- };
222
+ var native = { randomUUID };
136
223
 
137
224
  function v4(options, buf, offset) {
138
- if (native.randomUUID && true && !options) {
139
- return native.randomUUID();
140
- }
141
-
142
- options = options || {};
143
- const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
144
-
145
- rnds[6] = rnds[6] & 0x0f | 0x40;
146
- rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
147
-
148
- return unsafeStringify(rnds);
225
+ if (native.randomUUID && true && !options) {
226
+ return native.randomUUID();
227
+ }
228
+ options = options || {};
229
+ const rnds = options.random ?? options.rng?.() ?? rng();
230
+ if (rnds.length < 16) {
231
+ throw new Error('Random bytes length must be >= 16');
232
+ }
233
+ rnds[6] = (rnds[6] & 0x0f) | 0x40;
234
+ rnds[8] = (rnds[8] & 0x3f) | 0x80;
235
+ return unsafeStringify(rnds);
149
236
  }
150
237
 
151
238
  // console.log('OUT', __name({variableName}) );
@@ -233,25 +320,19 @@ function requireJsonMsg_cjs () {
233
320
  // "module" pattern to avoid "static" and "#" private : https://stackoverflow.com/a/1479341/298545
234
321
  var JSON_Msg = (function() {
235
322
  return {
236
- merge : function(json) {
237
- const dt_Msg= new Date();
238
- let json_msg= {
239
- id : v4(),
240
- referer : null,
241
- dt : dt_Msg.toISOString(),
242
- };
243
- // https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object
244
- for (var key of Object.keys(json)) {
245
- json_msg[key]= json[key];
246
- }
247
- return json_msg;
323
+ merge: function(json) {
324
+ return Object.assign({
325
+ id: v4(),
326
+ referer: null,
327
+ dt: new Date().toISOString()
328
+ }, json || {});
248
329
  },
249
- validate : function(json) {
250
- const b_valid= validate_Msg(json);
251
- if (!b_valid)
252
- LOGR_.log(l_.VALIDATION, 'JSON_Msg: validate: ', validate_Msg.errors);
330
+ validate : function (json) {
331
+ const b_valid = schema_Msg(json);
332
+ if (!b_valid)
333
+ LOGR_.log(l_.VALIDATION, 'JSON_Msg: validate: ', schema_Msg.errors);
253
334
  return b_valid;
254
- }
335
+ },
255
336
  // TODO: requires a separate ajv module require, and JTD specific schema
256
337
  // https://ajv.js.org/guide/getting-started.html#parsing-and-serializing-json
257
338
  // static #ajv_parse_= ajv.compileParser(this.#schema_json_Msg);
@@ -260,26 +341,24 @@ function requireJsonMsg_cjs () {
260
341
  // }
261
342
  }
262
343
  })();
263
-
344
+
264
345
  var JSON_Msg_msg = (function() {
265
346
  return {
266
- create_with_msg_merge : function(_msg, json) {
267
- let json_msg= JSON_Msg.merge(json);
268
- json_msg._msg= _msg;
269
- return json_msg;
347
+ create_with_msg_merge: function(_msg, json) {
348
+ return Object.assign(JSON_Msg.merge(json), { _msg });
270
349
  },
271
350
  validate : function(json) {
272
351
  if (! JSON_Msg.validate(json))
273
352
  return false;
274
- const b_valid= validate_Msg_msg(json);
353
+ const b_valid= schema_Msg_msg(json);
275
354
  if (!b_valid)
276
- LOGR_.log(l_.VALIDATION, 'JSON_Msg_msg: validate: ', validate_Msg_msg.errors);
355
+ LOGR_.log(l_.VALIDATION, 'JSON_Msg_msg: validate: ', schema_Msg_msg.errors);
277
356
  return b_valid;
278
357
  }
279
358
  }
280
359
  })();
281
360
 
282
- var JSON_MsgAck = (function() {
361
+ var JSON_MsgAck_msg = (function() {
283
362
  return {
284
363
  create_with_msgOk : function(_msg, b_ok= true) {
285
364
  return JSON_Msg_msg.create_with_msg_merge(_msg, {
@@ -299,53 +378,177 @@ function requireJsonMsg_cjs () {
299
378
  validate : function(json) {
300
379
  if (! JSON_Msg_msg.validate(json))
301
380
  return false;
302
- const b_valid= validate_MsgAck(json);
381
+ const b_valid= schema_MsgAck_msg(json);
303
382
  if (!b_valid)
304
- LOGR_.log(l_.VALIDATION, 'JSON_MsgAck: validate: ', validate_MsgAck.errors);
383
+ LOGR_.log(l_.VALIDATION, 'JSON_MsgAck: validate: ', schema_MsgAck_msg.errors);
305
384
  return b_valid;
306
385
  }
307
386
  }
308
387
  })();
309
388
 
310
389
  jsonMsg_cjs.JSON_Msg = JSON_Msg;
311
- jsonMsg_cjs.JSON_MsgAck = JSON_MsgAck;
390
+ jsonMsg_cjs.JSON_MsgAck_msg = JSON_MsgAck_msg;
312
391
  jsonMsg_cjs.JSON_Msg_msg = JSON_Msg_msg;
313
392
  return jsonMsg_cjs;
314
393
  }
315
394
 
316
395
  var jsonMsg_cjsExports = requireJsonMsg_cjs();
317
396
 
397
+ //-------------------------------------------------------------------------------------------------
398
+
399
+ let LOGR_$1= LOGR.get_instance();
400
+ const log_$1= LOGR_$1.log;
401
+
402
+ const l_$1= {
403
+ EVENTS : 0b1 << 0,
404
+ TIMEOUTS : 0b1 << 1,
405
+ };
406
+ LOGR_$1.labels= l_$1;
407
+ // LOGR_.toggled= {
408
+ // EVENTS : 1
409
+ // }
410
+
411
+
412
+ //-------------------------------------------------------------------------------------------------
413
+
414
+ class EventLog {
415
+ constructor() {
416
+ this.arr_events = []; // In-memory event store
417
+ this.map_index_id = new Map(); // Map of id -> array of indices into arr_events; arr_events[idx]
418
+ this.map_timeouts = new Map(); // Store timeout references: idx -> timeout_id
419
+ }
420
+
421
+ addEvent(type, id, data, timeout_ms = null, timeout_callback = null) {
422
+ const evt = {
423
+ type,
424
+ dt: Date.now(),
425
+ id,
426
+ data,
427
+ timeout_id: null // Will store timeout reference if set
428
+ };
429
+ const idx = this.arr_events.push(evt) - 1; // More efficient than .length before push
430
+
431
+ let arr_indices = this.map_index_id.get(id);
432
+ if (! arr_indices) {
433
+ arr_indices = [];
434
+ this.map_index_id.set(id, arr_indices);
435
+ }
436
+ arr_indices.push(idx);
437
+
438
+ // Set timeout if specified
439
+ if (timeout_ms && timeout_callback) {
440
+ evt.timeout_id = setTimeout(() => {
441
+ if (this.map_timeouts.delete(idx)) {
442
+ evt.timeout_id = null;
443
+ timeout_callback(evt);
444
+ log_$1(l_$1.EVENTS, `Event DELETED[${idx}]: ${type}`, evt);
445
+ }
446
+ }, timeout_ms);
447
+
448
+ this.map_timeouts.set(idx, evt.timeout_id);
449
+ }
450
+
451
+ log_$1(l_$1.EVENTS, `Event added[${idx}] @${Date(evt.dt).toISOString()}: ${type}`, evt);
452
+ return { idx, evt };
453
+ }
454
+
455
+ cancelTimeout(idx) {
456
+ const timeout_id = this.map_timeouts.get(idx);
457
+ if (timeout_id) {
458
+ clearTimeout(timeout_id);
459
+ this.map_timeouts.delete(idx);
460
+ if (this.arr_events[idx])
461
+ this.arr_events[idx].timeout_id = null;
462
+ return true;
463
+ }
464
+ return false;
465
+ }
466
+
467
+ cancelAllTimeouts() {
468
+ for (const [idx, timeout_id] of this.map_timeouts) {
469
+ clearTimeout(timeout_id);
470
+ if (this.arr_events[idx])
471
+ this.arr_events[idx].timeout_id = null;
472
+ }
473
+ this.map_timeouts.clear();
474
+ }
475
+
476
+ getEventById(id, lookback_ms = null) {
477
+ const arr_indices = this.map_index_id.get(id);
478
+ if (!arr_indices?.length) return [];
479
+
480
+ const result = [];
481
+ const cutoff = lookback_ms !== null ? Date.now() - lookback_ms : -Infinity;
482
+
483
+ // Single loop with early cutoff
484
+ for (let i = arr_indices.length - 1; i >= 0; i--) {
485
+ const idx = arr_indices[i];
486
+ const evt = this.arr_events[idx];
487
+ if (evt.dt < cutoff)
488
+ break;
489
+ result.push({ idx, evt });
490
+ }
491
+
492
+ return result; // Newest to oldest order
493
+ }
494
+
495
+ // getRecentEvents(id, lookbackMs) {
496
+ // const cutoff = Date.now() - lookbackMs;
497
+ // return this.events.filter(e => e.id === id && e.dt >= cutoff);
498
+ // }
499
+
500
+ getEvents(lookback_ms, predicate) {
501
+ const cutoff = Date.now() - lookback_ms;
502
+ const result = [];
503
+
504
+ // Iterate backwards from the end
505
+ for (let idx = this.arr_events.length - 1; idx >= 0; idx--) {
506
+ const evt = this.arr_events[idx];
507
+ if (evt.dt < cutoff) {
508
+ break; // Stop once we pass the cutoff
509
+ }
510
+ if (predicate(evt)) {
511
+ result.push({ idx, evt });
512
+ }
513
+ }
514
+
515
+ return result; // Newest to oldest order
516
+ }
517
+
518
+ // setLogr(obj_logr) {
519
+ // this.logr.toggled = obj_logr;
520
+ // }
521
+
522
+ clear() {
523
+ this.cancelAllTimeouts(); // Clear all timeouts before clearing events
524
+ this.arr_events.length = 0;
525
+ this.map_index_id.clear();
526
+ }
527
+ }
528
+
318
529
  const k_TTL= 20000;
319
530
 
320
531
  //-------------------------------------------------------------------------------------------------
321
532
 
322
- let LOGR_= new BitLogr();
533
+ // LOGR
534
+ // - l_LL and l_RR should accept 0b1 << 0 style shift
535
+ // - function to debug output bit values of labels instead of binary
536
+ // - rollup example in READMNE
323
537
 
324
- const l_msgs_ = {
325
- MSG : 0b1 << 0,
326
- WARP : 0b1 << 1,
327
- ENGAGE : 0b1 << 2,
328
- ACK : 0b1 << 3,
329
- };
538
+ const LOGR_= LOGR.get_instance();
539
+ const log_= LOGR_.log;
330
540
 
331
- const l_= {
332
- HANDLERS : 0b1 << 0,
333
- DROPS : 0b1 << 1,
334
- VALIDATION : 0b1 << 2,
335
- ... l_LL_(l_msgs_, 8)
336
- };
541
+ const l_msgs_ = l_array_(['PROTOCOL_STATE','RECVER','SENDER']); // b0, b1, b2
542
+
543
+ Object.assign(l_$1, l_array_(['EVENTS','TIMEOUTS'], 0b1 << 3)); // b3, b4
544
+
545
+ const l_= l_concat_( l_msgs_, l_concat_(l_$1, l_array_(['HANDLERS','DROPS','VALIDATION'])) );
337
546
  LOGR_.labels= l_;
338
547
 
339
548
  //-------------------------------------------------------------------------------------------------
340
549
 
341
550
  let map_Context_= new Map();
342
551
 
343
- function set_ctx(key, ctx) {
344
- map_Context_.set(key, ctx);
345
- // console.log(map_Context_);
346
- return ctx;
347
- }
348
-
349
552
  function get_ctx(key) {
350
553
  return map_Context_.get(key);
351
554
  }
@@ -353,20 +556,30 @@ function get_ctx(key) {
353
556
  //-------------------------------------------------------------------------------------------------
354
557
 
355
558
  class Config {
356
- receiver(callback_msgWarp,callback_msgEngage) {
559
+ constructor() {
560
+ // Initialize callbacks as no-op functions
561
+ this._callback_msgWarp = () => { console.assert(false, 'callback_msgWarp uninitialized'); };
562
+ this._callback_msgEngage = () => { console.assert(false, 'callback_msgEngage uninitialized'); };
563
+ this._callback_msgAckWarp = () => { console.assert(false, 'callback_msgAckWarp uninitialized'); };
564
+ this._callback_msgAckEngage = () => { console.assert(false, 'callback_msgAckEngage uninitialized'); };
565
+ this._callback_msg_sent_expired = () => { console.assert(false, '_callback_msg_sent_expired uninitialized'); };
566
+ this._callback_msgOptions = () => { console.assert(false, 'callback_msgOptions uninitialized'); };
567
+ }
568
+
569
+ receiver(callback_msgWarp, callback_msgEngage, callback_msg_sent_expired) {
357
570
  this._callback_msgWarp= callback_msgWarp;
358
571
  this._callback_msgEngage= callback_msgEngage;
572
+ this._callback_msg_sent_expired= callback_msg_sent_expired;
359
573
  }
360
- sender(callback_msgAckWarp,callback_msgAckEngage ) {
574
+ sender(callback_msgAckWarp, callback_msgAckEngage, callback_msg_sent_expired ) {
361
575
  this._callback_msgAckWarp= callback_msgAckWarp;
362
576
  this._callback_msgAckEngage= callback_msgAckEngage;
577
+ this._callback_msg_sent_expired= callback_msg_sent_expired;
363
578
  }
579
+
364
580
  set callback_msgOptions(callback) {
365
581
  this._callback_msgOptions= callback;
366
582
  }
367
- set logr(obj_logr) {
368
- LOGR_.toggled= obj_logr;
369
- }
370
583
  }
371
584
 
372
585
  // var config = (function() {
@@ -385,11 +598,21 @@ class Config {
385
598
 
386
599
  //-------------------------------------------------------------------------------------------------
387
600
 
388
- let k_VERSION= "0.7";
601
+ let k_VERSION= "0.8";
602
+
603
+ function t_ttl_rtt_(ttl_msec, rtt_msec) {
604
+ if (ttl_msec === undefined)
605
+ return undefined;
606
+ if (rtt_msec === undefined)
607
+ return ttl_msec *2;
608
+
609
+ console.assert(rtt_msec <= ttl_msec *2, `t_ttl_rtt_: INVALID rtt_msec ttl_msec[${ttl_msec}] rtt_msec[${rtt_msec}]`);
610
+ return (ttl_msec *2) + rtt_msec;
611
+ }
389
612
 
390
613
  var JSON_MsgOptions = (function() {
391
614
  return {
392
- create_with_msg_options : function(_msg, options) {
615
+ create_with_msg_options : function(_msg, options) {
393
616
  return jsonMsg_cjsExports.JSON_Msg_msg.create_with_msg_merge(_msg, {
394
617
  options: options,
395
618
  "2PhW": k_VERSION
@@ -398,12 +621,8 @@ var JSON_MsgOptions = (function() {
398
621
  validate : function(json) {
399
622
  if (! jsonMsg_cjsExports.JSON_Msg_msg.validate(json))
400
623
  return false;
401
- if (! validate_Msg2PhW(json)) {
402
- LOGR_.log(l_.VALIDATION, 'JSON_MsgWarp: validate_Msg2PhW_: ', validate_Msg2PhW.errors);
403
- return false;
404
- }
405
- if (! validate_MsgOptions(json)) {
406
- LOGR_.log(l_.VALIDATION, 'JSON_MsgOptions: validate_MsgOptions_: ', validate_MsgOptions.errors);
624
+ if (! schema_MsgOptions(json)) {
625
+ log_(l_.VALIDATION, () => ['JSON_MsgOptions: schema_MsgOptions_: ', schema_MsgOptions.errors]);
407
626
  return false;
408
627
  }
409
628
  return true;
@@ -413,9 +632,10 @@ var JSON_MsgOptions = (function() {
413
632
 
414
633
  var JSON_MsgWarp = (function() {
415
634
  return {
416
- create_with_user_hyperport : function(json_user, json_hyperport, nr_ttl_msec) {
635
+ create_with_id_user_hyperport : function(json_warp_id, json_user, json_hyperport, nr_ttl_msec) {
417
636
  return jsonMsg_cjsExports.JSON_Msg.merge({
418
637
  warp : {
638
+ id : json_warp_id,
419
639
  user : json_user,
420
640
  hyperport : json_hyperport,
421
641
  ttl_msec : nr_ttl_msec
@@ -423,15 +643,22 @@ var JSON_MsgWarp = (function() {
423
643
  "2PhW": k_VERSION
424
644
  });
425
645
  },
646
+ compare : function(json_L, json_R) {
647
+ if (json_L.dt !== json_R.dt)
648
+ return false;
649
+ if (json_L.warp.id !== json_R.warp.id)
650
+ return false;
651
+ if (json_L.referer[0] !== json_R.referer[0])
652
+ return false;
653
+ if (json_L.referer[1] !== json_R.referer[1])
654
+ return false;
655
+ return true;
656
+ },
426
657
  validate : function(json) {
427
658
  if (! jsonMsg_cjsExports.JSON_Msg.validate(json))
428
659
  return false;
429
- if (! validate_Msg2PhW(json)) {
430
- LOGR_.log(l_.VALIDATION, 'JSON_MsgWarp: validate_Msg2PhW_: ', validate_Msg2PhW.errors);
431
- return false;
432
- }
433
- if (! validate_MsgWarp(json)) {
434
- LOGR_.log(l_.VALIDATION, 'JSON_MsgWarp: validate_MsgWarp_: ', validate_MsgWarp.errors);
660
+ if (! schema_MsgWarp(json)) {
661
+ log_(l_.VALIDATION, () => ['JSON_MsgWarp: schema_MsgWarp_: ', schema_MsgWarp.errors]);
435
662
  return false;
436
663
  }
437
664
  return true;
@@ -440,32 +667,29 @@ var JSON_MsgWarp = (function() {
440
667
  })();
441
668
 
442
669
  var JSON_MsgEngage = (function() {
443
- return {
670
+ return {
444
671
  create_with_MsgWarp : function(json_msgWarp) {
445
- let json_msgEngage= jsonMsg_cjsExports.JSON_Msg.merge({
672
+ console.assert(json_msgWarp.ack === undefined, "Engage with a Warp, not an Ack");
673
+ return jsonMsg_cjsExports.JSON_Msg_msg.create_with_msg_merge(json_msgWarp, {
446
674
  engage : {
447
- user : json_msgWarp.warp.user,
448
- hyperport : json_msgWarp.warp.hyperport,
675
+ "ok" : true,
676
+ "rtt_msec" : Date.now() - Date.parse(json_msgWarp.dt)
449
677
  },
450
678
  "2PhW": k_VERSION
451
679
  });
452
- json_msgEngage["id"]= json_msgWarp.id;
453
- return json_msgEngage;
454
680
  },
455
681
  validate : function(json) {
456
- if (! jsonMsg_cjsExports.JSON_Msg.validate(json))
682
+ if (! jsonMsg_cjsExports.JSON_Msg_msg.validate(json))
457
683
  return false;
458
- if (! validate_Msg2PhW(json)) {
459
- LOGR_.log(l_.VALIDATION, 'JSON_MsgWarp: validate_Msg2PhW_: ', validate_Msg2PhW.errors);
684
+ if (! JSON_MsgWarp.validate(json._msg))
460
685
  return false;
461
- }
462
- if (! validate_MsgEngage(json)) {
463
- LOGR_.log(l_.VALIDATION, 'JSON_MsgEngage: validate_MsgEngage_: ', validate_MsgEngage.errors);
686
+ if (! schema_MsgEngage(json)) {
687
+ log_(l_.VALIDATION, () => ['JSON_MsgEngage: schema_MsgEngage_: ', schema_MsgEngage.errors]);
464
688
  return false;
465
689
  }
466
690
  return true;
467
691
  }
468
- }
692
+ };
469
693
  })();
470
694
 
471
695
  var JSON_MsgAckWarp = (function() {
@@ -476,21 +700,17 @@ var JSON_MsgAckWarp = (function() {
476
700
  // return json_msgAckWarp;
477
701
  // }
478
702
  create_with_msgOk : function(json_msgWarp, b_ok= true) {
479
- const json_msgAck= jsonMsg_cjsExports.JSON_MsgAck.create_with_msgOk(json_msgWarp, b_ok);
480
- json_msgAck["2PhW"]= k_VERSION;
481
- return json_msgAck;
703
+ const json_msgAck_msg= jsonMsg_cjsExports.JSON_MsgAck_msg.create_with_msgOk(json_msgWarp, b_ok);
704
+ json_msgAck_msg["2PhW"]= k_VERSION;
705
+ return json_msgAck_msg;
482
706
  },
483
707
  create_with_msgExpired : function( json_msgWarp ) {
484
- const json_msgAck= jsonMsg_cjsExports.JSON_MsgAck.create_with_msgExpired( json_msgWarp );
485
- json_msgAck["2PhW"]= k_VERSION;
486
- return json_msgAck;
708
+ const json_msgAck_msg= jsonMsg_cjsExports.JSON_MsgAck_msg.create_with_msgExpired( json_msgWarp );
709
+ json_msgAck_msg["2PhW"]= k_VERSION;
710
+ return json_msgAck_msg;
487
711
  },
488
712
  validate : function(json) {
489
- if (! validate_Msg2PhW(json)) {
490
- LOGR_.log(l_.VALIDATION, 'JSON_MsgAckWarp: validate_Msg2PhW_: ', validate_Msg2PhW.errors);
491
- return false;
492
- }
493
- if (! jsonMsg_cjsExports.JSON_MsgAck.validate(json))
713
+ if (! jsonMsg_cjsExports.JSON_MsgAck_msg.validate(json))
494
714
  return false;
495
715
  if (! JSON_MsgWarp.validate(json._msg))
496
716
  return false;
@@ -507,21 +727,17 @@ var JSON_MsgAckEngage = (function() {
507
727
  // return json_msgAckEngage;
508
728
  // }
509
729
  create_with_msgOk : function(json_msgEngage, b_ok= true) {
510
- const json_msgAck= jsonMsg_cjsExports.JSON_MsgAck.create_with_msgOk(json_msgEngage, b_ok);
511
- json_msgAck["2PhW"]= k_VERSION;
512
- return json_msgAck;
730
+ const json_msgAck_msg= jsonMsg_cjsExports.JSON_MsgAck_msg.create_with_msgOk(json_msgEngage, b_ok);
731
+ json_msgAck_msg["2PhW"]= k_VERSION;
732
+ return json_msgAck_msg;
513
733
  },
514
734
  create_with_msgExpired : function( json_msgEngage ) {
515
- const json_msgAck= jsonMsg_cjsExports.JSON_MsgAck.create_with_msgExpired( json_msgEngage );
516
- json_msgAck["2PhW"]= k_VERSION;
517
- return json_msgAck;
735
+ const json_msgAck_msg= jsonMsg_cjsExports.JSON_MsgAck_msg.create_with_msgExpired( json_msgEngage );
736
+ json_msgAck_msg["2PhW"]= k_VERSION;
737
+ return json_msgAck_msg;
518
738
  },
519
739
  validate : function(json) {
520
- if (! validate_Msg2PhW(json)) {
521
- LOGR_.log(l_.VALIDATION, 'JSON_MsgAckEngage: validate_Msg2PhW_: ', validate_Msg2PhW.errors);
522
- return false;
523
- }
524
- if (! jsonMsg_cjsExports.JSON_MsgAck.validate(json))
740
+ if (! jsonMsg_cjsExports.JSON_MsgAck_msg.validate(json))
525
741
  return false;
526
742
  if (! JSON_MsgEngage.validate(json._msg))
527
743
  return false;
@@ -530,305 +746,508 @@ var JSON_MsgAckEngage = (function() {
530
746
  }
531
747
  })();
532
748
 
533
-
534
749
  //-------------------------------------------------------------------------------------------------
535
- // State
750
+ // States
536
751
 
537
752
  class StateState {
538
- constructor(initState) {
539
- this.state_current_ = initState;
540
- this.dt_start_= null;
541
- this.nr_timeout_id_= -1;
542
- this.nr_remaining_msec_= 0;
543
- this.f_callback_= undefined;
544
- }
545
- start() {
546
- this.dt_start_= Date.now();
547
- console.log(`setTimeout: start ${this.dt_start_}, remaining ${this.nr_remaining_msec_}`);
548
- this.nr_timeout_id_= setTimeout(this.f_callback_, this.nr_remaining_msec_);
549
- }
550
- changeState(newState, nr_ttl_msec, f_callback) {
551
- if (! this.state_current_.changeState(newState))
552
- return false;
553
- this.state_current_ = newState;
554
-
555
- clearTimeout(this.nr_timeout_id_);
556
- if (nr_ttl_msec != undefined && f_callback != undefined) {
557
- this.f_callback_= f_callback;
558
- this.nr_remaining_msec_= nr_ttl_msec;
559
- this.start();
560
- }
561
- return true;
753
+ constructor(idx_event, event) {
754
+ this._protocol_parent = null;
755
+ this._idx_event = idx_event;
756
+ this._event = event;
757
+ }
758
+ get protocol() {
759
+ return this._protocol_parent;
562
760
  }
563
- delayTimeout(nr_delay_msec) {
564
- clearTimeout(this.nr_timeout_id_);
565
- const nr_elapsed_ms= Date.now() - this.dt_start_;
566
- this.nr_remaining_msec_= Math.max(this.nr_remaining_msec_ - nr_elapsed_ms, 0) + nr_delay_msec;
567
- this.start();
761
+ set protocol(parent) {
762
+ this._protocol_parent = parent;
568
763
  }
569
- inState(stateClass) {
570
- return this.state_current_ instanceof stateClass;
764
+ get idx_event() {
765
+ return this._idx_event;
766
+ }
767
+ get event() {
768
+ return this._event;
769
+ }
770
+ get json_msg() {
771
+ return this._event.data;
772
+ }
773
+ changeState(state_new) {
774
+ if (this.canChangeState(state_new))
775
+ this.protocol.state = state_new;
776
+ else
777
+ this.protocol.state = new StateINVALID(state_new._idx_event, state_new._event);
778
+ }
779
+ canChangeState(_state_new) {
780
+ throw new Error("Subclass must implement canChangeState()");
571
781
  }
572
782
  }
573
783
 
574
- class StateInitialState {
575
- changeState(newState) {
576
- return true;
784
+ class StateAckEngage extends StateState {
785
+ constructor(idx_event, event) { super(idx_event, event); }
786
+ get evt_AckEngage() { return this.event }
787
+ get json_msgAckEngage() { return this.json_msg }
788
+ canChangeState(_state_new) {
789
+ return false;
577
790
  }
578
791
  }
579
-
580
- // class State<Name> {
581
- // changeState= function(newState) {
582
- // return false;
583
- // }
584
- // }
585
792
 
586
- // if (newState instanceof State<Name>)
587
- // return true;
793
+ class StateEngage extends StateState {
794
+ constructor(idx_event, event) { super(idx_event, event); }
795
+ get evt_Engage() { return this.event }
796
+ get json_msgEngage() { return this.json_msg }
797
+ canChangeState(state_new) {
798
+ if (false === state_new instanceof StateAckEngage)
799
+ return false;
588
800
 
589
- // if (! <Class>.inState( State<Name> ))
590
- // if (! <Class>.changeState( new State<Name>() ))
591
-
592
- //-------------------------------------------------------------------------------------------------
801
+ // The Engage gets to live for THE WARP'S creation time + TTL*2 + RTT
802
+ const json_msgWarp= this.json_msgEngage._msg;
803
+ const timeout_ms= t_ttl_rtt_(json_msgWarp.warp.ttl_msec, this.json_msgEngage.engage.rtt_msec);
804
+ log_(l_.PROTOCOL_STATE, () => [`StateEngage: evt_AckEngage.dt@${state_new.evt_AckEngage.dt}, msgWarp.dt@${Date.parse(json_msgWarp.dt)} + ${timeout_ms}`]);
805
+ if (state_new.evt_AckEngage.dt >= Date.parse(json_msgWarp.dt) + timeout_ms)
806
+ return false;
593
807
 
594
- class ProtocolStateState extends StateState {
595
- constructor(initState= new StateInitialState() ) {
596
- super(initState);
808
+ return true;
597
809
  }
598
810
  }
599
811
 
600
- class StateWarp {
601
- changeState(newState) {
602
- if (newState instanceof StateAckWarp)
603
- return true;
604
- if (newState instanceof StateComplete)
605
- return true;
606
- return false;
607
- }
608
- }
812
+ class StateAckWarp extends StateState {
813
+ constructor(idx_event, event) { super(idx_event, event); }
814
+ get evt_AckWarp() { return this.event }
815
+ get json_msgAckWarp() { return this.json_msg }
816
+ canChangeState(state_new) {
817
+ if (false === state_new instanceof StateEngage)
818
+ return false;
609
819
 
610
- class StateAckWarp {
611
- changeState(newState) {
612
- if (newState instanceof StateEngage)
613
- return true;
614
- if (newState instanceof StateComplete)
615
- return true;
616
- return false;
820
+ if (! this.json_msgAckWarp.ack.ok)
821
+ return false;
822
+
823
+ if (this.json_msgAckWarp._msg.warp.instantaneous)
824
+ return false;
825
+
826
+ // The Ack gets to live for THE ACK'S creation time + TTL*2 + STT
827
+ // +STT, so lines up with the Engage timeout
828
+ // - Engage: T0 +2TTL +RTT; RTT= STT+STT
829
+ // - AckWarp: TAckWarp +2TLL +STT; TAckWarp= T0 +STT;
830
+ // - STT: Date of the Ack minus date of the Warp.
831
+ const timeout_ms= t_ttl_rtt_(this.json_msgAckWarp._msg.warp.ttl_msec) + Date.parse(this.json_msgAckWarp.dt) - Date.parse(this.json_msgAckWarp._msg.dt);
832
+ log_(l_.PROTOCOL_STATE, () => [`StateAckWarp: evt_Engage.dt@${state_new.evt_Engage.dt}, msgAckWarp.dt@${Date.parse(this.json_msgAckWarp.dt)} + ${timeout_ms}`]);
833
+ if (state_new.evt_Engage.dt >= Date.parse(this.json_msgAckWarp.dt) + timeout_ms)
834
+ return false;
835
+
836
+ return true;
617
837
  }
618
838
  }
619
839
 
620
- class StateEngage {
621
- changeState(newState) {
622
- if (newState instanceof StateComplete)
623
- return true;
624
- return false;
840
+ class StateWarp extends StateState {
841
+ constructor(idx_event, event) { super(idx_event, event); }
842
+ get evt_Warp() { return this.event }
843
+ get json_msgWarp() { return this.json_msg }
844
+ canChangeState(state_new) {
845
+ if (false === state_new instanceof StateAckWarp)
846
+ return false;
847
+
848
+ // The Warp gets to live for THE WARP'S creation time + TTL*2
849
+ const timeout_ms= t_ttl_rtt_(this.json_msgWarp.warp.ttl_msec);
850
+ log_(l_.PROTOCOL_STATE, () => [`StateWarp: evt_AckWarp.dt@${state_new.evt_AckWarp.dt}, msgWarp.dt@${Date.parse(this.json_msgWarp.dt)} + ${timeout_ms}`]);
851
+ if (state_new.evt_AckWarp.dt >= Date.parse(this.json_msgWarp.dt) + timeout_ms)
852
+ return false;
853
+
854
+ return true;
625
855
  }
626
856
  }
627
857
 
628
- class StateComplete {
629
- changeState(newState) {
858
+ class StateINVALID extends StateState {
859
+ constructor(idx_event, event) { super(idx_event, event); }
860
+ canChangeState(_state_new) {
861
+ // INVALID can't transition to any state
630
862
  return false;
631
863
  }
632
864
  }
633
865
 
634
- //-------------------------------------------------------------------------------------------------
635
-
636
- function handler_msgOptions_(cfg, msg, json_msgOptions)
637
- {
638
- LOGR_.log(l_.HANDLERS, 'handler_msgOptions_: ...');
639
-
640
- if (! validate_Options_delay(json_msgOptions.options))
641
- return false;
642
-
643
- if (JSON_MsgWarp.validate(json_msgOptions._msg)) {
644
- const json_msgWarp= json_msgOptions._msg;
645
-
646
- const ctx= get_ctx(json_msgWarp.id);
647
- if (!ctx )
866
+ class StateInitialState extends StateState {
867
+ constructor() { super(null, null); }
868
+ canChangeState(state_new) {
869
+ if (false === state_new instanceof StateWarp)
648
870
  return false;
649
871
 
650
- json_msgOptions.options.ttl_msec_incr[0];
651
- const ttl_incr= json_msgOptions.options.ttl_msec_incr[1];
652
-
653
- //TODO: double check ttl_msec is the same as current accummulated ttl for idempotence.
872
+ // The NEWLY created Warp only gets to live for its creation time + TTL
873
+ const timeout_ms= state_new.json_msgWarp.warp.ttl_msec;
874
+ log_(l_.PROTOCOL_STATE, () => [`StateInitialState: evt_Warp.dt@${state_new.evt_Warp.dt}, msgWarp.dt@${Date.parse(state_new.json_msgWarp.dt)} + ${timeout_ms}`]);
875
+ if (state_new.evt_Warp.dt >= Date.parse(state_new.json_msgWarp.dt) + timeout_ms)
876
+ return false;
654
877
 
655
- LOGR_.log(l_.HANDLERS, 'handler_msgOptions_: ', json_msgOptions);
878
+ return true;
879
+ }
880
+ }
656
881
 
657
- ctx.protocol.delayTimeout(ttl_incr);
882
+ //----
658
883
 
659
- if (cfg._callback_msgOptions)
660
- return cfg._callback_msgOptions(msg, json_msgOptions);
884
+ class ProtocolStateState {
885
+ constructor(state_initial) {
886
+ this.state = state_initial || new StateInitialState();
887
+ }
661
888
 
662
- return true;
889
+ set state(state_new) {
890
+ if (! (state_new instanceof StateState)) {
891
+ throw new Error("initState must be an instance of StateState or its subclasses");
892
+ }
893
+ this._state = state_new;
894
+ if (state_new && state_new.protocol !== this) {
895
+ state_new.protocol = this;
896
+ }
897
+ }
898
+ get state() {
899
+ return this._state;
663
900
  }
664
901
 
665
- return false;
902
+ canChangeState(state_new) {
903
+ return this._state.canChangeState(state_new);
904
+ }
666
905
  }
667
906
 
668
907
  //-------------------------------------------------------------------------------------------------
669
- // Sender
670
908
 
671
- function handler_msgAckWarp_(cfg, msg, json_msgAckWarp)
672
- {
673
- // NOTE: json_msgAck here has a string as _msg, instead of JSON.
909
+ class TwoPhW_EventLog {
910
+ constructor(eventLog) {
911
+ this._eventLog = eventLog;
912
+ }
674
913
 
675
- LOGR_.log(l_.HANDLERS, 'handler_msgAckWarp: ...');
914
+ _warp(json_msg) {
915
+ const b_Ack = json_msg.ack !== undefined;
916
+ const json = b_Ack ? json_msg["_msg"] : json_msg;
676
917
 
677
- const json_msgWarp= json_msgAckWarp._msg;
918
+ if (json.warp) {
919
+ return {
920
+ str_type: `2PhW[JSON_Msg${b_Ack ? 'Ack' : ''}Warp]`,
921
+ json_msgWarp: json
922
+ };
923
+ }
924
+ if (json.engage) {
925
+ return {
926
+ str_type: `2PhW[JSON_Msg${b_Ack ? 'Ack' : ''}Engage]`,
927
+ json_msgWarp: json["_msg"]
928
+ };
929
+ }
930
+ return null; // Explicit default for invalid cases
931
+ }
678
932
 
679
- const ctx= get_ctx(json_msgWarp.id);
680
- if (!ctx || !ctx.protocol.changeState( new StateAckWarp() ))
681
- return false;
933
+ _addEvent(json_msg, timeout_ms, timeout_callback) {
934
+ const { str_type, json_msgWarp }= this._warp(json_msg);
935
+ const { idx }= this._eventLog.addEvent(str_type, json_msgWarp.warp.id, json_msg, timeout_ms, timeout_callback);
936
+ log_(l_.PROTOCOL_STATE, () => [`_addEvent: [${idx}] timeout:${Date.now()}+${timeout_ms} `, json_msg]);
937
+ }
682
938
 
683
- //TODO: check if multiple warps have been sent out with the same destination
939
+ _dropEvent(json_msg) {
940
+ const { json_msgWarp }= this._warp(json_msg);
941
+ this._eventLog.addEvent('2PhW[DROPPED!]', json_msgWarp.warp.id, json_msg);
942
+ }
684
943
 
685
- LOGR_.log(l_.HANDLERS, 'handler_msgAckWarp: ', json_msgAckWarp);
944
+ _cancelTimeout(idx_event) {
945
+ log_(l_.PROTOCOL_STATE, () => [`_cancelTimeout: [${idx_event}] timeout cancelled`]);
946
+ this._eventLog.cancelTimeout(idx_event);
947
+ }
686
948
 
687
- // const json_msgAckWarp= JSON_MsgAckWarp.createWith_msgAck_msg(json_msgAck, json_msgWarp);
949
+ get_protocolState(json_msgWarp) {
950
+ const protocolState = new ProtocolStateState();
951
+
952
+ const arr_evts= this._eventLog.getEventById(json_msgWarp.warp.id, k_TTL);
953
+ log_(l_.EVENTS, () => ['get_protocolState: arr_evts: ', arr_evts]);
954
+
955
+ for (let i = arr_evts.length - 1; i >= 0; i--) {
956
+ const { idx, evt } = arr_evts[i];
957
+
958
+ if (evt.type === '2PhW[DROPPED!]')
959
+ continue;
960
+
961
+ const json_msg= evt.data;
962
+ if (! JSON_MsgWarp.compare(json_msgWarp, this._warp(json_msg).json_msgWarp) )
963
+ protocolState.state.changeState( new StateINVALID(idx, evt) );
964
+
965
+ switch(evt.type) {
966
+ case '2PhW[JSON_MsgWarp]' :
967
+ protocolState.state.changeState( new StateWarp(idx, evt) );
968
+ break;
969
+ case '2PhW[JSON_MsgAckWarp]' :
970
+ protocolState.state.changeState( new StateAckWarp(idx, evt) );
971
+ break;
972
+ case '2PhW[JSON_MsgEngage]' :
973
+ protocolState.state.changeState( new StateEngage(idx, evt) );
974
+ break;
975
+ case '2PhW[JSON_MsgAckEngage]' :
976
+ protocolState.state.changeState( new StateAckEngage(idx, evt) );
977
+ break;
978
+ default :
979
+ protocolState.state.changeState( new StateINVALID(idx, evt) );
980
+ break;
981
+ }
982
+ log_(l_.PROTOCOL_STATE, () => ['get_protocolState: type,state: ',
983
+ evt.type,
984
+ (protocolState.state.json_msg.ack?.ok === false) ? '--NACK--' : '',
985
+ protocolState.state
986
+ ]);
987
+ }
988
+ return protocolState;
989
+ }
688
990
 
689
- if (! cfg._callback_msgAckWarp(msg, json_msgAckWarp))
690
- return false;
991
+ }
691
992
 
692
- if (json_msgWarp.warp.instantaneous) {
693
- const b_res= ctx.protocol.changeState( new StateComplete() );
694
- console.assert(b_res);
695
-
696
- return true;
993
+ class TwoPhW {
994
+ constructor(eventLog) {
995
+ this._2PhW_eventLog = new TwoPhW_EventLog(eventLog);
996
+ this._config= new Config();
697
997
  }
698
998
 
699
- const b_res= ctx.protocol.changeState( new StateEngage() );
700
- console.assert(b_res);
999
+ get config() {
1000
+ return this._config;
1001
+ }
701
1002
 
702
- return true;
703
- }
1003
+ get eventLog() {
1004
+ return this._2PhW_eventLog;
1005
+ }
1006
+
1007
+ //-------------------------------------------------------------------------------------------------
704
1008
 
705
- function handler_msgAckEngage_(cfg, msg, json_msgAckEngage)
706
- {
707
- // NOTE: json_msgAck here has a string as _msg, instead of JSON.
1009
+ _handler_msgOptions(cfg, msg, json_msgOptions)
1010
+ {
1011
+ log_(l_.HANDLERS, () => ['handler_msgOptions_: ...']);
1012
+
1013
+ if (! validate_Options_delay_(json_msgOptions.options))
1014
+ return false;
1015
+
1016
+ if (JSON_MsgWarp.validate(json_msgOptions._msg)) {
1017
+ const json_msgWarp= json_msgOptions._msg;
1018
+
1019
+ const ctx= get_ctx(json_msgWarp.id);
1020
+ if (!ctx )
1021
+ return false;
1022
+
1023
+ json_msgOptions.options.ttl_msec_incr[0];
1024
+ const ttl_incr= json_msgOptions.options.ttl_msec_incr[1];
1025
+
1026
+ //TODO: double check ttl_msec is the same as current accummulated ttl for idempotence.
1027
+
1028
+ log_(l_.HANDLERS, () => ['handler_msgOptions_: ', json_msgOptions]);
1029
+
1030
+ ctx.protocol.delayTimeout(ttl_incr);
1031
+
1032
+ if (cfg._callback_msgOptions)
1033
+ return cfg._callback_msgOptions(msg, json_msgOptions);
1034
+
1035
+ return true;
1036
+ }
1037
+
1038
+ return false;
1039
+ }
1040
+
1041
+ //-------------------------------------------------------------------------------------------------
1042
+ // sender Source (src)
1043
+
1044
+ register_msgWarp(json_msgWarp)
1045
+ {
1046
+ log_(l_.SENDER, () => ['register_msgWarp: ', json_msgWarp]);
708
1047
 
709
- LOGR_.log(l_.HANDLERS, 'handler_msgAckEngage: ...');
1048
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1049
+ const b_changeState= protocolState.canChangeState( new StateWarp(null, {
1050
+ dt: Date.now(),
1051
+ data: json_msgWarp
1052
+ }) );
710
1053
 
711
- const json_msgEngage= json_msgAckEngage._msg;
1054
+ log_(l_.HANDLERS | l_.SENDER, () => ['register_msgWarp: protocolState.canChangeState ', b_changeState]);
1055
+ if (! b_changeState)
1056
+ return false;
712
1057
 
713
- const ctx= get_ctx(json_msgEngage.id);
714
- if (!ctx || !ctx.protocol.changeState( new StateAckEngage() ))
715
- return false;
1058
+ const timeout_ms= t_ttl_rtt_(json_msgWarp.warp.ttl_msec);
1059
+ const elapsed_ms= Date.now() - Date.parse(json_msgWarp.dt);
716
1060
 
717
- LOGR_.log(l_.HANDLERS, 'handler_msgAckEngage: ', json_msgAckEngage);
1061
+ this.eventLog._addEvent(json_msgWarp, timeout_ms-elapsed_ms, () => {
1062
+ this.config._callback_msg_sent_expired(json_msgWarp);
1063
+ });
1064
+ }
718
1065
 
719
- // const json_msgAckEngage= JSON_MsgAckEngage.createWith_msgAck_msg(json_msgAck, json_msgEngage);
1066
+ _handler_msgAckWarp(msg, json_msgAckWarp)
1067
+ {
1068
+ log_(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckWarp: ', json_msgAckWarp]);
1069
+
1070
+ const json_msgWarp= json_msgAckWarp._msg;
1071
+
1072
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1073
+ const b_changeState= protocolState.canChangeState( new StateAckWarp(null, {
1074
+ dt: Date.now(),
1075
+ data: json_msgAckWarp
1076
+ }) );
1077
+
1078
+ log_(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckWarp: protocolState.canChangeState ', b_changeState]);
1079
+ if (! b_changeState)
1080
+ return false;
720
1081
 
721
- if (! cfg._callback_msgAckEngage(msg, json_msgAckEngage))
722
- return false;
1082
+ this.eventLog._cancelTimeout(protocolState.state.idx_event);
1083
+ this.eventLog._addEvent(json_msgAckWarp);
1084
+ if (! this.config._callback_msgAckWarp(msg, json_msgAckWarp))
1085
+ return false;
1086
+
1087
+ return true;
1088
+ }
723
1089
 
724
- return true;
725
- }
1090
+ register_msgEngage(json_msgEngage)
1091
+ {
1092
+ log_(l_.SENDER, () => ['register_msgEngage: ', json_msgEngage]);
726
1093
 
727
- //-------------------------------------------------------------------------------------------------
728
- // Receiver
1094
+ const json_msgWarp= json_msgEngage._msg;
729
1095
 
730
- function handler_msgWarp_(cfg, msg, json_msgWarp)
731
- {
732
- LOGR_.log(l_.HANDLERS, 'handler_msgWarp: ...');
1096
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1097
+ const b_changeState= protocolState.canChangeState( new StateEngage(null, {
1098
+ dt: Date.now(),
1099
+ data : json_msgEngage
1100
+ }) );
733
1101
 
734
- let ctx= get_ctx(json_msgWarp.id);
735
- if (ctx === undefined)
736
- ctx= set_ctx(json_msgWarp.id, { protocol: new ProtocolStateState() });
1102
+ log_(l_.HANDLERS | l_.SENDER, () => ['register_msgEngage: protocolState.canChangeState ', b_changeState]);
1103
+ if (! b_changeState)
1104
+ return false;
1105
+
1106
+ const timeout_ms= t_ttl_rtt_(json_msgWarp.warp.ttl_msec, json_msgEngage.engage.rtt_msec);
1107
+ const elapsed_ms= Date.now() - Date.parse(json_msgWarp.dt);
737
1108
 
738
- if (!ctx || !ctx.protocol.changeState( new StateWarp() ))
739
- return false;
1109
+ this.eventLog._addEvent(json_msgEngage, timeout_ms-elapsed_ms, () => {
1110
+ this.config._callback_msg_sent_expired(json_msgEngage);
1111
+ });
1112
+ }
1113
+
1114
+ _handler_msgAckEngage(msg, json_msgAckEngage)
1115
+ {
1116
+ log_(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckEngage: ', json_msgAckEngage]);
1117
+
1118
+ const json_msgWarp= json_msgAckEngage._msg._msg;
740
1119
 
741
- LOGR_.log(l_.HANDLERS, 'handler_msgWarp: ', json_msgWarp);
1120
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1121
+ const b_changeState= protocolState.canChangeState( new StateAckEngage(null, {
1122
+ dt: Date.now(),
1123
+ data : json_msgAckEngage
1124
+ }) );
742
1125
 
743
- if (! cfg._callback_msgWarp(msg, json_msgWarp))
744
- return false;
1126
+ log_(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckEngage_: protocolState.canChangeState ', b_changeState]);
1127
+ if (! b_changeState)
1128
+ return false;
745
1129
 
746
- if (json_msgWarp.warp.instantaneous) {
747
- const b_res= ctx.protocol.changeState( new StateComplete() );
748
- console.assert(b_res);
1130
+ this.eventLog._cancelTimeout(protocolState.state.idx_event);
1131
+ this.eventLog._addEvent(json_msgAckEngage);
1132
+ if (! this.config._callback_msgAckEngage(msg, json_msgAckEngage))
1133
+ return false;
749
1134
 
750
1135
  return true;
751
1136
  }
1137
+
1138
+ //-------------------------------------------------------------------------------------------------
1139
+ // receiver Destination (dst)
752
1140
 
753
- const b_res= ctx.protocol.changeState( new StateAckWarp() );
754
- console.assert(b_res);
1141
+ _handler_msgWarp(msg, json_msgWarp)
1142
+ {
1143
+ log_(l_.HANDLERS | l_.RECVER, () => ['handler_msgWarp: ', json_msgWarp]);
1144
+
1145
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1146
+ const b_changeState= protocolState.canChangeState( new StateWarp(null, {
1147
+ dt: Date.now(),
1148
+ data: json_msgWarp
1149
+ }) );
1150
+
1151
+ log_(l_.HANDLERS | l_.RECVER, () => ['handler_msgWarp: protocolState.canChangeState: ', b_changeState]);
1152
+ if (! b_changeState)
1153
+ return false;
755
1154
 
756
- return true;
757
- }
1155
+ this.eventLog._addEvent(json_msgWarp);
1156
+ if (! this.config._callback_msgWarp(msg, json_msgWarp))
1157
+ return false;
1158
+
1159
+ return true;
1160
+ }
1161
+
1162
+ register_msgAckWarp(json_msgAckWarp)
1163
+ {
1164
+ log_(l_.RECVER, () => ['register_msgAckWarp: ', json_msgAckWarp]);
758
1165
 
759
- function handler_msgEngage_(cfg, msg, json_msgEngage)
760
- {
761
- LOGR_.log(l_.HANDLERS, 'handler_msgEngage: ...');
1166
+ const json_msgWarp= json_msgAckWarp._msg;
762
1167
 
763
- const ctx= get_ctx(json_msgEngage.id);
764
- if (!ctx || !ctx.protocol.changeState( new StateEngage() ))
765
- return false;
1168
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1169
+ const b_changeState= protocolState.canChangeState( new StateAckWarp(null, {
1170
+ dt: Date.now(),
1171
+ data: json_msgAckWarp
1172
+ }) );
766
1173
 
767
- LOGR_.log(l_.HANDLERS, 'handler_msgEngage: ', json_msgEngage);
1174
+ log_(l_.HANDLERS | l_.RECVER, () => ['register_msgAckWarp: protocolState.canChangeState: ', b_changeState]);
1175
+ if (! b_changeState)
1176
+ return false;
768
1177
 
769
- if (! cfg._callback_msgEngage(msg, json_msgEngage))
770
- return false;
1178
+ const elapsed_ms= Date.now() - Date.parse(json_msgAckWarp.dt);
1179
+ const timeout_ms= t_ttl_rtt_(json_msgWarp.warp.ttl_msec) + Date.parse(json_msgAckWarp.dt) - Date.parse(json_msgWarp.dt);
771
1180
 
772
- const b_res= ctx.protocol.changeState( new StateComplete() );
773
- console.assert(b_res);
1181
+ this.eventLog._addEvent(json_msgAckWarp, timeout_ms-elapsed_ms, () => {
1182
+ this.config._callback_msg_sent_expired(json_msgAckWarp);
1183
+ });
1184
+ }
774
1185
 
775
- return true;
776
- }
1186
+ _handler_msgEngage(msg, json_msgEngage)
1187
+ {
1188
+ log_(l_.HANDLERS | l_.RECVER, () => ['handler_msgEngage: ', json_msgEngage]);
777
1189
 
778
- //-------------------------------------------------------------------------------------------------
1190
+ const json_msgWarp= json_msgEngage["_msg"];
779
1191
 
780
- class TwoPhW {
781
- constructor() {
782
- this._config= new Config();
783
- }
1192
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1193
+ const b_changeState= protocolState.canChangeState( new StateEngage(null, {
1194
+ dt: Date.now(),
1195
+ data: json_msgEngage
1196
+ }) );
784
1197
 
785
- get config() {
786
- return this._config;
1198
+ log_(l_.HANDLERS | l_.RECVER, () => ['handler_msgEngage: protocolState.canChangeState: ', b_changeState]);
1199
+ if (! b_changeState)
1200
+ return false;
1201
+
1202
+ this.eventLog._cancelTimeout(protocolState.state.idx_event);
1203
+ this.eventLog._addEvent(json_msgEngage);
1204
+ if (! this.config._callback_msgEngage(msg, json_msgEngage))
1205
+ return false;
1206
+
1207
+ return true;
787
1208
  }
788
1209
 
789
- // this function need to be removed when a microservice db is used instead of a state machine
790
- create_MsgWarp_out(str_id, json_user, json_hyperport, nr_ttl_msec, b_instantaneous)
1210
+ register_msgAckEngage(json_msgAckEngage)
791
1211
  {
792
- if (nr_ttl_msec === undefined)
793
- nr_ttl_msec= k_TTL;
1212
+ log_(l_.RECVER, () => ['register_msgAckEngage: ', json_msgAckEngage]);
794
1213
 
795
- const json_msgWarp= JSON_MsgWarp.create_with_user_hyperport(json_user, json_hyperport, nr_ttl_msec);
796
- json_msgWarp.id= str_id;
797
-
798
- if (b_instantaneous !== undefined)
799
- json_msgWarp.warp.instantaneous= b_instantaneous;
1214
+ const json_msgWarp= json_msgAckEngage._msg._msg;
800
1215
 
801
- const ctx= set_ctx(json_msgWarp.id, { protocol: new ProtocolStateState() });
802
- const b_res= ctx.protocol.changeState( new StateWarp(), nr_ttl_msec, function() {
803
- const json_Nack= JSON_MsgAckWarp.create_with_msgExpired( json_msgWarp );
804
- //TODO: the referer is NULL here !
805
- this._config._callback_msgAckWarp(json_Nack, json_Nack);
806
- }.bind(this) );
1216
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1217
+ const b_changeState= protocolState.canChangeState( new StateAckEngage(null, {
1218
+ dt: Date.now(),
1219
+ data: json_msgAckEngage
1220
+ }) );
1221
+
1222
+ log_(l_.HANDLERS | l_.RECVER, () => ['register_msgAckEngage: protocolState.canChangeState: ', b_changeState]);
1223
+ if (! b_changeState)
1224
+ return false;
807
1225
 
808
- console.assert(b_res);
809
- return json_msgWarp;
1226
+ this.eventLog._addEvent(json_msgAckEngage);
810
1227
  }
811
1228
 
1229
+ //-------------------------------------------------------------------------------------------------
1230
+
812
1231
  handler_msg_json(msg, json_msg)
813
1232
  {
814
- LOGR_.log(l_.HANDLERS, 'handler_msg_json: ', json_msg);
1233
+ log_(l_.HANDLERS, () => ['handler_msg_json: ', json_msg]);
815
1234
 
816
1235
  // ADR: I could parse json_Msg_msg first and then MsgAck or MsgOptions, but
817
1236
  // doing so means super classes get parsed multiple times for no reason
818
1237
 
819
- if (JSON_MsgOptions.validate(json_msg) && handler_msgOptions_(this._config, msg, json_msg))
820
- return true;
1238
+ // if (JSON_MsgOptions.validate(json_msg) && this.handler_msgOptions_(this._config, msg, json_msg))
1239
+ // return true;
821
1240
 
822
- if (JSON_MsgWarp.validate(json_msg) && handler_msgWarp_(this._config, msg, json_msg))
1241
+ if (JSON_MsgWarp.validate(json_msg) && this._handler_msgWarp(msg, json_msg))
823
1242
  return true;
824
1243
 
825
- if (JSON_MsgEngage.validate(json_msg) && handler_msgEngage_(this._config, msg, json_msg))
1244
+ if (JSON_MsgEngage.validate(json_msg) && this._handler_msgEngage(msg, json_msg))
826
1245
  return true;
827
1246
 
828
- if (JSON_MsgAckWarp.validate(json_msg) && handler_msgAckWarp_(this._config, msg, json_msg))
1247
+ if (JSON_MsgAckWarp.validate(json_msg) && this._handler_msgAckWarp(msg, json_msg))
829
1248
  return true;
830
1249
 
831
- if (JSON_MsgAckEngage.validate(json_msg) && handler_msgAckEngage_(this._config, msg, json_msg))
1250
+ if (JSON_MsgAckEngage.validate(json_msg) && this._handler_msgAckEngage(msg, json_msg))
832
1251
  return true;
833
1252
 
834
1253
  // https://attacomsian.com/blog/javascript-iterate-objects
@@ -840,12 +1259,14 @@ class TwoPhW {
840
1259
  // console.log(`${key}: ${json_msg[key]}`);
841
1260
  // });
842
1261
 
1262
+ this.eventLog._dropEvent(json_msg);
1263
+ log_(l_.DROPS, () => ["TwoPhW: handler_msg: DROP! ", msg]);
843
1264
  return false;
844
1265
  }
845
1266
 
846
1267
  handler_msg_str(msg, str_msg)
847
1268
  {
848
- LOGR_.log(l_.HANDLERS, 'handler_msg_str: ['+ str_msg +']');
1269
+ log_(l_.HANDLERS, () => ['handler_msg_str: ['+ str_msg +']']);
849
1270
 
850
1271
  // ... test strings here
851
1272
 
@@ -862,18 +1283,17 @@ class TwoPhW {
862
1283
 
863
1284
  handler_msg(msg)
864
1285
  {
865
- LOGR_.log(l_.HANDLERS, 'handler_msg: ', msg);
1286
+ log_(l_.HANDLERS, () => ['handler_msg: ', msg]);
866
1287
 
867
1288
  if (typeof (msg) === 'string' && this.handler_msg_str(msg, msg))
868
1289
  return true;
869
1290
 
870
1291
  if (typeof (msg) === 'object' && this.handler_msg_json(msg, msg))
871
1292
  return true;
872
-
873
- LOGR_.log(l_.DROPS, "handler_msg: DROP! ", msg);
1293
+
874
1294
  return false
875
1295
  }
876
1296
 
877
1297
  }
878
1298
 
879
- export { JSON_MsgAckEngage, JSON_MsgAckWarp, JSON_MsgEngage, JSON_MsgOptions, JSON_MsgWarp, TwoPhW, l_ as l };
1299
+ export { EventLog, JSON_MsgAckEngage, JSON_MsgAckWarp, JSON_MsgEngage, JSON_MsgOptions, JSON_MsgWarp, StateAckEngage, StateAckWarp, StateEngage, StateINVALID, StateInitialState, StateWarp, TwoPhW, l_ as l, t_ttl_rtt_ as t_ttl_rtt };