-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
2965 lines (2664 loc) · 106 KB
/
index.js
File metadata and controls
2965 lines (2664 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var protobuf; // resolved at runtime – see initEnvironment()
(function initEnvironment() {
const isNode = (typeof process !== 'undefined') && process.versions && process.versions.node && (typeof window === 'undefined');
if (isNode) {
// ──────────────────────────────── Node.js ──────────────────────────────
try {
protobuf = require('protobufjs');
} catch (e) {
console.error('[studioapi] Error loading protobufjs:', e.message);
throw new Error('[studioapi] Missing dependency "protobufjs" in Node.js: ' + e.message);
}
try {
if (typeof globalThis.p === 'undefined') {
globalThis.p = require('./studioapi.proto.js');
}
} catch (e) {
throw new Error('[studioapi] Unable to load "./studioapi.proto.js"');
}
const g = globalThis;
if (typeof g.WebSocket === 'undefined') {
try { g.WebSocket = require('ws'); } catch (_) { /* optional */ }
}
if (!g.crypto || !g.crypto.subtle) {
try { g.crypto = require('crypto').webcrypto; } catch (_) { /* optional */ }
}
if (typeof g.TextEncoder === 'undefined' || typeof g.TextDecoder === 'undefined') {
try {
const util = require('util');
g.TextEncoder = util.TextEncoder;
g.TextDecoder = util.TextDecoder;
} catch (_) { /* optional */ }
}
if (typeof g.URL === 'undefined') {
try { g.URL = require('url').URL; } catch (_) { /* optional */ }
}
if (typeof g.location === 'undefined') {
g.location = { protocol: 'ws:' };
}
} else {
// ─────────────────────────────── Browser ───────────────────────────────
if (typeof window !== 'undefined') {
protobuf = window.protobuf;
} else {
throw new Error('[studioapi] Neither Node.js nor Browser environment detected properly');
}
}
})();
/**
* The studio namespace.
* @exports studio
* @namespace
* @expose
*/
var studio = (function() {
return {};
})();
/**
* The studio.protocol namespace.
* @exports studio.protocol
* @namespace
*/
studio.protocol = (function(ProtoBuf) {
var obj = {};
var root = ProtoBuf.parse(globalThis.p).root;
obj.Hello = root.lookupType("Hello");
obj.AuthRequest = root.lookupType("AuthRequest");
obj.AuthRequestChallengeResponse = root.lookupType("AuthRequest.ChallengeResponse");
obj.AdditionalChallengeResponseRequired = root.lookupType("AdditionalChallengeResponseRequired");
obj.AuthResponse = root.lookupType("AuthResponse");
obj.AuthResultCode = root.lookupEnum("AuthResponse.AuthResultCode").values;
obj.Container = root.lookupType("Container");
obj.ContainerType = root.lookupEnum("Container.Type").values;
obj.Error = root.lookupType("Error");
obj.RemoteErrorCode = root.lookupEnum("RemoteErrorCode").values;
obj.CDPNodeType = root.lookupEnum("CDPNodeType").values;
obj.CDPValueType = root.lookupEnum("CDPValueType").values;
obj.Info = root.lookupType("Info");
obj.InfoFlags = root.lookupEnum("Info.Flags").values;
obj.Node = root.lookupType("Node");
obj.VariantValue = root.lookupType("VariantValue");
obj.ValueRequest = root.lookupType("ValueRequest");
obj.EventRequest = root.lookupType("EventRequest");
obj.EventInfo = root.lookupType("EventInfo");
obj.EventCode = root.lookupEnum("EventInfo.CodeFlags").values;
obj.EventStatus = {
eStatusOK: 0x0,
eNotifySet: 0x1,
eWarningSet: 0x10,
eLowLevelSet: 0x20,
eHighLevelSet: 0x40,
eErrorSet: 0x100,
eLowLowLevelSet: 0x200,
eHighHighLevelSet: 0x400,
eEmergencySet: 0x800,
eValueForced: 0x1000,
eRepeatBlocked: 0x2000,
eProcessBlocked: 0x4000,
eOperatorBlocked: 0x8000,
eNotifyUnacked: 0x10000,
eWarningUnacked: 0x100000,
eErrorUnacked: 0x1000000,
eEmergencyUnacked: 0x8000000,
eDisabled: 0x20000000,
eSignalFault: 0x40000000,
eComponentSuspended: 0x80000000
};
obj.ChildAdd = root.lookupType("ChildAdd");
obj.ChildRemove = root.lookupType("ChildRemove");
obj.ServicesRequest = root.lookupType("ServicesRequest");
obj.ServicesNotification = root.lookupType("ServicesNotification");
obj.ServiceInfo = root.lookupType("ServiceInfo");
obj.ServiceMessage = root.lookupType("ServiceMessage");
obj.ServiceMessageKind = root.lookupEnum("ServiceMessage.Kind").values;
obj.valueToVariant = function (variantValue, type, value) {
switch (type) {
case obj.CDPValueType.eDOUBLE:
variantValue.dValue = value;
break;
case obj.CDPValueType.eFLOAT:
variantValue.fValue = value;
break;
case obj.CDPValueType.eUINT64:
variantValue.ui64Value = value;
break;
case obj.CDPValueType.eINT64:
variantValue.i64Value = value;
break;
case obj.CDPValueType.eUINT:
variantValue.uiValue = value;
break;
case obj.CDPValueType.eINT:
variantValue.iValue = value;
break;
case obj.CDPValueType.eUSHORT:
variantValue.usValue = value;
break;
case obj.CDPValueType.eSHORT:
variantValue.sValue = value;
break;
case obj.CDPValueType.eUCHAR:
variantValue.ucValue = value;
break;
case obj.CDPValueType.eCHAR:
variantValue.cValue = value;
break;
case obj.CDPValueType.eBOOL:
variantValue.bValue = value;
break;
case obj.CDPValueType.eSTRING:
variantValue.strValue = value;
break;
}
};
obj.valueFromVariant = function(variantValue, type) {
switch(type) {
case obj.CDPValueType.eDOUBLE:
return variantValue.dValue;
case obj.CDPValueType.eFLOAT:
return variantValue.fValue;
case obj.CDPValueType.eUINT64:
return variantValue.ui64Value;
case obj.CDPValueType.eINT64:
return variantValue.i64Value;
case obj.CDPValueType.eUINT:
return variantValue.uiValue;
case obj.CDPValueType.eINT:
return variantValue.iValue;
case obj.CDPValueType.eUSHORT:
return variantValue.usValue;
case obj.CDPValueType.eSHORT:
return variantValue.sValue;
case obj.CDPValueType.eUCHAR:
return variantValue.ucValue;
case obj.CDPValueType.eCHAR:
return variantValue.cValue;
case obj.CDPValueType.eBOOL:
return variantValue.bValue;
case obj.CDPValueType.eSTRING:
return variantValue.strValue;
default:
return 0;
}
};
obj.appendBuffer = function ( array1, array2 ) {
var tmp = new Uint8Array( array1.byteLength + array2.byteLength );
tmp.set( new Uint8Array( array1 ), 0 );
tmp.set( new Uint8Array( array2 ), array1.byteLength );
return tmp.buffer;
}
obj.CreateAuthRequest = function (dict, challenge) {
return new Promise(function(resolve, reject) {
var authReq = obj.AuthRequest.create();
var username = dict.Username || '';
var password = dict.Password || '';
var credentials = new TextEncoder().encode(username.toLowerCase() + ':' + password); // encode to utf-8 byte array
authReq.userId = username.toLowerCase();
crypto.subtle.digest('SHA-256', credentials.buffer)
.then(function(digest) {
var colon = new Uint8Array([':'.charCodeAt(0)]);
var buffer = obj.appendBuffer(obj.appendBuffer(challenge, colon), digest);
return crypto.subtle.digest('SHA-256', buffer)
})
.then(function(challenge_digest) {
var response = obj.AuthRequestChallengeResponse.create();
response.type = "PasswordHash";
response.response = new Uint8Array(challenge_digest);
authReq.challengeResponse = [];
authReq.challengeResponse.push(response);
resolve(authReq);
})
.catch(function(err){
reject(err)
});
});
}
function ErrorHandler(){
this.name = "Error";
this.handle = function(message){
return new Promise(function(resolve, reject) {
console.log("ProtocolError: "+message+"\n");
resolve(this);
}.bind(this));
}.bind(this);
}
// Minimum compat version required for proxy protocol support
const PROXY_MIN_COMPAT_VERSION = 4;
obj.PROXY_MIN_COMPAT_VERSION = PROXY_MIN_COMPAT_VERSION;
// Create encoded ServicesRequest container bytes for proxy protocol
obj.createServicesRequestBytes = function() {
var servicesReq = obj.Container.create();
servicesReq.messageType = obj.ContainerType.eServicesRequest;
servicesReq.servicesRequest = obj.ServicesRequest.create({
subscribe: true,
inactivityResendInterval: 120
});
return obj.Container.encode(servicesReq).finish();
};
// Helper to send ServicesRequest for proxy protocol (compat >= 4)
function sendServicesRequest(socket, metadata) {
if (metadata.compatVersion >= PROXY_MIN_COMPAT_VERSION) {
socket.send(obj.createServicesRequestBytes());
}
}
function ContainerHandler(onContainer, onError, metadata){
this.name = "Container";
this.metadata = metadata;
this.handle = function(message){
return new Promise(function(resolve, reject) {
try {
var container = obj.Container.decode(new Uint8Array(message));
} catch (err) {
console.log("Container Error: "+err+"\n");
onError();
return resolve(new ErrorHandler());
}
onContainer(container, metadata);
resolve(this);
}.bind(this));
}.bind(this);
}
function AuthHandler(socket, metadata, credentialsRequested, onContainer, onError){
this.name = "AuthResponse";
this.metadata = metadata;
this.sendAuthRequest = function(userAuthResult){
var request = new studio.api.Request(this.metadata.systemName, this.metadata.applicationName, this.metadata.cdpVersion, metadata.systemUseNotification, userAuthResult);
credentialsRequested(request)
.then(function(dict){
return obj.CreateAuthRequest(dict, metadata.challenge);
})
.then(function(request){
socket.send(obj.AuthRequest.encode(request).finish());
})
.catch(function(err){
console.log("Authentication cancelled.", err)
});
}.bind(this);
this.handle = function(message){
return new Promise(function(resolve, reject) {
try {
var authResponse = obj.AuthResponse.decode(new Uint8Array(message));
} catch (err) {
console.log("AuthResponse Error: "+err+"\n");
onError();
return resolve(new ErrorHandler());
}
if (authResponse.resultCode == obj.AuthResultCode.eGranted)
{
var container = obj.Container.create();
container.messageType = obj.ContainerType.eStructureRequest;
socket.send(obj.Container.encode(container).finish());
sendServicesRequest(socket, metadata);
resolve(new ContainerHandler(onContainer, onError, metadata));
} else {
console.log("Unable to login with existing user, password.", authResponse.resultText);
var userAuthResult = new studio.api.UserAuthResult(authResponse.resultCode, authResponse.resultText);
this.sendAuthRequest(userAuthResult);
resolve(this);
}
}.bind(this));
}.bind(this);
}
function HelloHandler(socket, notificationListener, onContainer, onError){
this.name = "Hello";
this.handle = function(message){
return new Promise(function(resolve, reject) {
try {
var hello = obj.Hello.decode(new Uint8Array(message));
} catch (err) {
console.log("Hello Error: "+err+"\n");
onError();
return resolve(new ErrorHandler());
}
function applicationAcceptanceRequested(request){
return new Promise(function(resolve, reject) {
if (request.systemUseNotification()) {
// In browser, use window.confirm; in Node.js, auto-accept
if (typeof window !== 'undefined' && typeof window.confirm === 'function') {
window.confirm(metadata.systemUseNotification) ? resolve() : reject();
} else {
// Node.js: auto-accept system use notification
console.log("System use notification: " + metadata.systemUseNotification);
resolve();
}
} else {
resolve();
}
});
}
var metadata = {}
metadata.systemName = hello.systemName;
metadata.applicationName = hello.applicationName;
metadata.cdpVersion = hello.cdpVersionMajor + '.' + hello.cdpVersionMinor + '.' + hello.cdpVersionPatch;
metadata.systemUseNotification = hello.systemUseNotification;
metadata.challenge = hello.challenge;
metadata.compatVersion = hello.compatVersion;
var request = new studio.api.Request(metadata.systemName, metadata.applicationName, metadata.cdpVersion, metadata.systemUseNotification, null);
var applicationAccepted = {}
if (notificationListener && notificationListener.applicationAcceptanceRequested)
applicationAccepted = notificationListener.applicationAcceptanceRequested;
else
applicationAccepted = applicationAcceptanceRequested;
applicationAccepted(request)
.then(function(){
if (hello.challenge && hello.challenge.length) {
if (!notificationListener || !notificationListener.credentialsRequested)
{
console.log("No notificationListener.credentialsRequested callback provided to studio.api.Client constructor. Can't authenticate connection!");
resolve(new ErrorHandler());
return;
}
var authHandler = new AuthHandler(socket, metadata, notificationListener.credentialsRequested, onContainer, onError);
var userAuthResult = new studio.api.UserAuthResult(obj.AuthResultCode.eCredentialsRequired, 'Credentials required');
authHandler.sendAuthRequest(userAuthResult);
resolve(authHandler);
}
else {
var container = obj.Container.create();
container.messageType = obj.ContainerType.eStructureRequest;
socket.send(obj.Container.encode(container).finish());
sendServicesRequest(socket, metadata);
resolve(new ContainerHandler(onContainer, onError, metadata));
}
})
.catch(function(err){
console.error("Application acceptance failed:", err);
resolve(this);
}.bind(this));
}.bind(this));
};
}
obj.Handler = function(socket, notificationListener) {
this.onContainer = undefined;
this.onError = undefined;
var onContainer = function(container, metadata) {(this.onContainer && this.onContainer(container, metadata));}.bind(this);
var onError = function(){(this.onError && this.onError());}.bind(this);
var handler = new HelloHandler(socket, notificationListener, onContainer, onError);
var messageQueue = [];
var processing = false;
var processQueue = function() {
if (processing || messageQueue.length === 0) return;
processing = true;
var message = messageQueue.shift();
handler.handle(message).then(function(newHandler) {
handler = newHandler;
processing = false;
processQueue();
}).catch(function(err) {
console.error("Handler error:", err);
processing = false;
processQueue();
});
};
this.handle = function(message){
messageQueue.push(message);
processQueue();
};
};
return obj;
})(protobuf);
studio.protocol.SYSTEM_NODE_ID = 0;
studio.protocol.WS_PREFIX = "ws://";
studio.protocol.WSS_PREFIX = "wss://";
studio.protocol.BINARY_TYPE = "arraybuffer";
/**
* The studio.internal namespace.
* @exports studio.internal
* @namespace
*/
studio.internal = (function(proto) {
var obj = {};
obj.structure = {
REMOVE: 0,
ADD: 1,
RECONNECT: 2,
DISCONNECT: 3
};
const STRUCTURE_REQUEST_TIMEOUT_MS = 30000;
const MAX_RECONNECT_DELAY_MS = 30000;
const INITIAL_RECONNECT_DELAY_MS = 1000;
const INACTIVITY_RESEND_INTERVAL_S = 120;
const EVENT_HISTORY_WAIT_NS = 120e9; // 120s — accept old events during this window after subscribe
const EVENT_DEDUP_WINDOW_NS = 30e9; // 30s — trim entries older than this after history wait
// Helper to remove first matching item from array (shared by AppNode and SystemNode)
function removeFirst(array, predicate) {
var idx = array.findIndex(predicate);
if (idx >= 0) array.splice(idx, 1);
}
function AppNode(appConnection, nodeId) {
var parent = undefined;
var id = nodeId;
var app = appConnection;
var structureFetched = false;
var childMap = new Map();
var givenPromises = new Map();
var childIterators = [];
var valueSubscriptions = [];
var structureSubscriptions = [];
var eventSubscriptions = [];
var lastValue;
var lastInfo = null; //when we get this, if there are any child requests we need to fetch child fetch too
var valid = true;
var hasActiveValueSubscription = false; // track if we've sent a getter request to server
var lastServerTimestamp = null; // for value dedup after reconnect
var lastEventTimestamp = 0; // track last received event timestamp for reconnect resume
this.path = function() {
var path = "";
if (parent && parent.id())
path = parent.path();
if (path.length)
path = path + "." + lastInfo.name;
else
path = lastInfo.name;
return path;
};
this.id = function() {
return id;
};
this.name = function() {
return lastInfo.name;
};
this.isStructureFetched = function() {
return structureFetched;
};
this.isValid = function() {
return valid;
};
this.invalidate = function() {
valid = false;
givenPromises.forEach(function(promiseHandlers, apiNode) {
promiseHandlers.forEach(function(promiseHandler) {
try {
clearTimeout(promiseHandler.timer);
promiseHandler.reject(apiNode);
} catch (e) { /* ignore */ }
});
});
givenPromises.clear();
};
this.hasSubscriptions = function() {
return valueSubscriptions.length > 0 || eventSubscriptions.length > 0;
};
this.info = function() {
return lastInfo;
};
this.lastValue = function() {
return lastValue;
};
this.forEachChild = function(iteratorFunction) {
if (structureFetched) {
childMap.forEach(iteratorFunction);
} else {
childIterators.push(iteratorFunction);
app.makeStructureRequest(id);
}
};
// Internal: iterate children immediately without structureFetched check
// Used during structure parsing to detect removed children
this.forEachChildImmediate = function(iteratorFunction) {
childMap.forEach(iteratorFunction);
};
this.update = function(nodeParent, protoInfo) {
parent = nodeParent;
lastInfo = protoInfo;
id = protoInfo.nodeId;
// Keep lastServerTimestamp across reconnect — filters the server's
// cached last-known-value replay (which has the original timestamp).
// Per-listener recentEvents preserved across reconnect — the server
// replays from lastEventTimestamp (inclusive), and preserving each
// listener's cache prevents boundary events from being duplicated.
this.async._makeGetterRequest();
for (var i = 0; i < eventSubscriptions.length; i++) {
// Resume from last received event timestamp (not original startingFrom) to avoid duplicates
var resumeFrom = lastEventTimestamp > 0 ? lastEventTimestamp : eventSubscriptions[i].startingFrom;
app.makeEventRequest(id, resumeFrom, false);
}
};
this.add = function(node) {
childMap.set(node.name(), node);
for (var i = 0; i < structureSubscriptions.length; i++) {
structureSubscriptions[i](node.name(), obj.structure.ADD);
}
};
this.remove = function(node) {
for (var i = 0; i < structureSubscriptions.length; i++) {
structureSubscriptions[i](node.name(), obj.structure.REMOVE);
}
node.invalidate();
childMap.delete(node.name());
};
this.child = function(name) {
return childMap.get(name);
};
this.done = function() {
structureFetched = true;
valid = true; // Re-validate node when structure is successfully fetched
givenPromises.forEach(function (promiseHandlers, apiNode) {
promiseHandlers.forEach(function(promiseHandler) {
if (apiNode.isValid()) {
promiseHandler.resolve(apiNode);
} else {
promiseHandler.reject(apiNode);
}
});
});
givenPromises.clear();
for (var i = 0; i < childIterators.length; i++) {
childMap.forEach(childIterators[i]);
}
childIterators.length = 0;
};
this.receiveValue = function (nodeValue, nodeTimestamp) {
// Skip values with older timestamps (filters reconnect replay where
// the server resends the last known value with its original timestamp).
if (nodeTimestamp !== undefined) {
var ts = Number(nodeTimestamp);
if (ts > 0) {
if (lastServerTimestamp !== null && ts < lastServerTimestamp)
return;
lastServerTimestamp = ts;
}
}
lastValue = nodeValue;
for (var i = 0; i < valueSubscriptions.length; i++) {
valueSubscriptions[i][0](nodeValue, nodeTimestamp);
}
};
this.receiveEvent = function (event) {
// Per-listener event dedup — each subscriber has independent dedup state.
var hasId = event.id !== undefined;
var ts = event.timestamp !== undefined ? Number(event.timestamp) : undefined;
var eventKey = hasId ? String(event.id) : null;
var nowNs = hasId ? Date.now() * 1e6 : 0;
if (ts !== undefined && ts > lastEventTimestamp) lastEventTimestamp = ts;
for (var i = 0; i < eventSubscriptions.length; i++) {
var sub = eventSubscriptions[i];
if (hasId && ts !== undefined) {
var isPastHistoryWait = nowNs > sub.dedupStartNs + EVENT_HISTORY_WAIT_NS;
// Reject events older than lowest tracked timestamp after history wait.
// When Map is empty (lowestTs 0), any event passes (nothing to compare against).
var lowestTs = sub.recentEvents.size > 0 ? sub.lowestTs : 0;
if (ts < lowestTs && isPastHistoryWait) continue;
// Exact (eventId, timestamp) duplicate check using composite key.
// Composite key allows multiple timestamps per eventId (recurring alarms).
var compositeKey = eventKey + ':' + event.timestamp;
if (sub.recentEvents.has(compositeKey)) continue;
sub.recentEvents.set(compositeKey, ts);
if (sub.recentEvents.size === 1 || ts < sub.lowestTs) sub.lowestTs = ts;
// Trim expired entries after history wait. At high event rates, the adaptive
// threshold (trimAt) amortizes the O(n) scan. At low rates (below threshold),
// check if the oldest entry has expired to keep the dedup window accurate.
if (isPastHistoryWait) {
var cutoff = ts - EVENT_DEDUP_WINDOW_NS;
if (sub.recentEvents.size > sub.trimAt
|| (sub.recentEvents.size <= sub.trimAt && sub.lowestTs > 0 && sub.lowestTs < cutoff)) {
sub.lowestTs = 0;
sub.recentEvents.forEach(function(storedTs, key) {
if (storedTs < cutoff) sub.recentEvents.delete(key);
else if (sub.lowestTs === 0 || storedTs < sub.lowestTs) sub.lowestTs = storedTs;
});
sub.trimAt = Math.max(100, sub.recentEvents.size * 2);
}
}
}
sub.callback(event);
}
};
this.async = {};
this.async.onDone = function(resolve, reject, apiNode) {
if (!structureFetched) {
// Support multiple callbacks per node (e.g., registerConnection + connectViaProxy)
if (!givenPromises.has(apiNode)) {
givenPromises.set(apiNode, []);
}
var settled = false;
var entry = {
resolve: function(v) { if (!settled) { settled = true; clearTimeout(entry.timer); resolve(v); } },
reject: function(v) { if (!settled) { settled = true; clearTimeout(entry.timer); reject(v); } },
timer: setTimeout(function() {
if (!settled) {
settled = true;
// Remove from givenPromises to prevent double-fire
var arr = givenPromises.get(apiNode);
var idx = arr.indexOf(entry);
if (idx >= 0) arr.splice(idx, 1);
if (arr.length === 0) givenPromises.delete(apiNode);
reject(new Error("Structure request timed out after " + STRUCTURE_REQUEST_TIMEOUT_MS + "ms"));
}
}, STRUCTURE_REQUEST_TIMEOUT_MS)
};
givenPromises.get(apiNode).push(entry);
} else {
if (apiNode.isValid()) {
resolve(apiNode);
} else {
reject(apiNode);
}
}
};
this.async.subscribeToStructure = function(structureConsumer) {
structureSubscriptions.push(structureConsumer);
};
this.async.unsubscribeFromStructure = function(structureConsumer) {
removeFirst(structureSubscriptions, function(s) { return s === structureConsumer; });
};
this.async.fetch = function() {
structureFetched = false;
app.makeStructureRequest(id);
};
this.async.subscribeToValues = function(valueConsumer, fs, sampleRate) {
valueSubscriptions.push([valueConsumer, fs, sampleRate]);
this._makeGetterRequest();
};
this.async.unsubscribeFromValues = function(valueConsumer) {
removeFirst(valueSubscriptions, function(s) { return s[0] === valueConsumer; });
this._makeGetterRequest();
};
this.async.subscribeToEvents = function(eventConsumer, startingFrom) {
var existing = null;
for (var si = 0; si < eventSubscriptions.length; si++) {
if (eventSubscriptions[si].callback === eventConsumer) { existing = eventSubscriptions[si]; break; }
}
if (existing) {
existing.startingFrom = startingFrom;
existing.recentEvents = new Map();
existing.lowestTs = 0;
existing.trimAt = 100;
existing.dedupStartNs = Date.now() * 1e6;
} else {
eventSubscriptions.push({
callback: eventConsumer,
startingFrom: startingFrom,
recentEvents: new Map(),
lowestTs: 0,
trimAt: 100,
dedupStartNs: Date.now() * 1e6
});
}
app.makeEventRequest(id, startingFrom, false);
};
this.async.unsubscribeFromEvents = function(eventConsumer) {
removeFirst(eventSubscriptions, function(s) { return s.callback === eventConsumer; });
if (eventSubscriptions.length === 0)
app.makeEventRequest(id, 0, true);
};
this.async.addChild = function(name, modelName) {
app.makeChildAddRequest(id, name, modelName);
};
this.async.removeChild = function(name) {
app.makeChildRemoveRequest(id, name);
};
this.async.sendValue = function(value, timestamp) {
lastValue = value;
app.makeSetterRequest(id, lastInfo.valueType, value, timestamp);
//when offline must queue or update pending set request and call set callbacks ...???
};
this.async._makeGetterRequest = function() {
if (valueSubscriptions.length > 0) {
var maxFs = Math.max.apply(Math, valueSubscriptions.map(v => v[1]));
var maxSampleRate = Math.max.apply(Math, valueSubscriptions.map(v => v[2]));
//by studio api protocol 0 is the highest sample rate (all samples), so override maxSampleRate if 0 is found
const zeroRate = valueSubscriptions.find(e => e[2] === 0);
maxSampleRate = zeroRate ? zeroRate[2] : maxSampleRate;
app.makeGetterRequest(id, maxFs, maxSampleRate, false);
hasActiveValueSubscription = true;
} else if (hasActiveValueSubscription) {
// Only send stop request if we previously subscribed
app.makeGetterRequest(id, 1, 0, true);
hasActiveValueSubscription = false;
}
}
}
obj.SystemNode = function(studioURL, notificationListener, onStructureChange) {
var appConnections = [];
var pendingConnects = [];
var connected = false;
var connecting = false;
var connectGeneration = 0;
var isClosed = false;
var structureSubscriptions = [];
var announcedApps = new Set();
var everSeenApps = new Set();
var pendingFindWaiters = []; // for find() waiting on late apps
var pendingFetches = [];
var connectionLocalApps = new Map(); // Maps AppConnection → local app name
var this_ = this;
function isApplicationNode(node) {
var info = node.info();
return info && info.isLocal && info.nodeType === proto.CDPNodeType.CDP_APPLICATION;
}
function appAddress(info) {
return info.serverAddr + ':' + info.serverPort;
}
function notifyStructure(name, change) {
// Notify internal cache invalidation callback (constructor param)
if (onStructureChange) {
try {
onStructureChange(name);
} catch (e) {
console.error("onStructureChange callback threw:", e);
}
}
// Notify user structure subscriptions
structureSubscriptions.forEach(function (cb) {
try {
cb(name, change);
} catch (e) {
console.error("Structure subscription callback threw:", e);
}
});
}
// Wake up find() callers waiting for a specific app to appear
function notifyFindWaiters(appName) {
pendingFindWaiters = pendingFindWaiters.filter(function(waiter) {
if (waiter.appName === appName) {
waiter.resolve();
return false; // remove from list
}
return true;
});
}
// Check if an app is currently connected and announced
this.isAppAvailable = function(appName) {
return announcedApps.has(appName);
};
// Check if an app was ever seen (used to distinguish "not yet discovered" from "disconnected")
this.wasAppSeen = function(appName) {
return everSeenApps.has(appName);
};
// Check if client is in direct mode (no proxy protocol)
this.isDirectMode = function() {
return appConnections.length > 0 && !appConnections[0].supportsProxyProtocol();
};
// Request a structure refresh from the primary connection (direct mode only).
// In proxy mode, discovery is push-based via ServicesNotification so this is a no-op.
function requestStructureRefresh() {
if (appConnections[0] && !appConnections[0].supportsProxyProtocol()) {
appConnections[0].makeStructureRequest(0);
}
}
// Register a waiter for a specific app name, with timeout
this.waitForApp = function(appName, timeoutMs) {
// Check if already available
if (announcedApps.has(appName)) {
return Promise.resolve();
}
// In direct mode, ask the server now to trigger immediate discovery.
// After this, the server will push eStructureChangeResponse (id 0)
// when siblings start/stop.
requestStructureRefresh();
return new Promise(function(resolve, reject) {
var waiter = { appName: appName };
var timer = timeoutMs > 0 ? setTimeout(function() {
pendingFindWaiters = pendingFindWaiters.filter(function(w) { return w !== waiter; });
reject(new Error(appName + " not found within " + timeoutMs + "ms"));
}, timeoutMs) : null;
waiter.resolve = function() { clearTimeout(timer); resolve(); };
waiter.reject = function(err) { clearTimeout(timer); reject(err); };
pendingFindWaiters.push(waiter);
});
};
// Announce an app as ADD (first time) or RECONNECT (seen before).
// No-op if already announced or not a valid application node.
function announceApp(appName, node) {
if (announcedApps.has(appName)) return;
if (!everSeenApps.has(appName) && (!node || !isApplicationNode(node))) return;
var change = everSeenApps.has(appName) ? obj.structure.RECONNECT : obj.structure.ADD;
announcedApps.add(appName);
everSeenApps.add(appName);
notifyStructure(appName, change);
notifyFindWaiters(appName);
}
function unannounceApp(appName) {
if (!announcedApps.has(appName)) return;
announcedApps.delete(appName);
notifyStructure(appName, obj.structure.DISCONNECT);
}
function notifyApplications(connection) {
connection.root().forEachChild(function (node) {
announceApp(node.name(), node);
});
}
function registerConnection(connection, resolve, reject) {
var sys = connection.root();
sys.async.onDone(function (system) {
notifyApplications(connection);
var primaryConn = appConnections[0];
var isProxyMode = primaryConn && primaryConn.supportsProxyProtocol();
// Track which app this connection owns (needed for DISCONNECT on connection loss)
system.forEachChild(function(app) {
if (isApplicationNode(app)) {
connectionLocalApps.set(connection, app.name());
}
});
if (isProxyMode) {
// Proxy mode: handle server-side child REMOVE here. ADD/RECONNECT is deferred to
// notifyApplications() after the proxy tunnel connects (via
// tryConnectPendingSiblings → connectViaProxy), ensuring the sibling
// is actually reachable before announcing it.
system.async.subscribeToStructure(function(appName, change) {
if (change === obj.structure.REMOVE) {
unannounceApp(appName);
}
});
}
resolve(system);
}, reject, sys);
}
this.onAppConnect = function(url, notificationListener, autoConnect) {
return new Promise(function (resolve, reject) {
var appConnection = new obj.AppConnection(url, notificationListener, autoConnect);
appConnections.push(appConnection);
// Direct mode lifecycle: connection close → DISCONNECT, reconnect → RECONNECT
appConnection.onDisconnected = function() {
var localApp = connectionLocalApps.get(appConnection);
if (localApp) unannounceApp(localApp);
};
appConnection.onReconnected = function() {
if (!connectionLocalApps.has(appConnection)) {
// Initial registration may have timed out — populate now
appConnection.root().forEachChild(function(app) {
if (isApplicationNode(app)) {
connectionLocalApps.set(appConnection, app.name());
}
});
}
notifyApplications(appConnection);
};
appConnection.onServiceConnectionEstablished = function(serviceConnection, instanceKey) {
serviceConnection.instanceKey = instanceKey;
appConnections.push(serviceConnection);
registerConnection(serviceConnection, function(){}, function(){});
};
appConnection.onServiceConnectionRemoved = function(instanceKey, closedByUser) {
var removed = appConnections.filter(function(con) { return con.instanceKey === instanceKey; });
removed.forEach(function(con) {
if (con.siblingKey) {
connectedSiblings.delete(con.siblingKey);
}
con.root().forEachChild(function(node) {
if (isApplicationNode(node)) {
unannounceApp(node.name());
}
});
if (closedByUser) {
con.invalidateAllNodes();
appConnections = appConnections.filter(function(c) { return c.instanceKey !== instanceKey; });
}
// Unintentional disconnect — keep AppConnection alive for reconnection
});
};
registerConnection(appConnection, resolve, reject);
});
};
var knownSiblings = new Set();