@vuu-ui/vuu-data-remote 0.8.18-debug

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.js ADDED
@@ -0,0 +1,3517 @@
1
+ var __accessCheck = (obj, member, msg) => {
2
+ if (!member.has(obj))
3
+ throw TypeError("Cannot " + msg);
4
+ };
5
+ var __privateGet = (obj, member, getter) => {
6
+ __accessCheck(obj, member, "read from private field");
7
+ return getter ? getter.call(obj) : member.get(obj);
8
+ };
9
+ var __privateAdd = (obj, member, value) => {
10
+ if (member.has(obj))
11
+ throw TypeError("Cannot add the same private member more than once");
12
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
13
+ };
14
+ var __privateSet = (obj, member, value, setter) => {
15
+ __accessCheck(obj, member, "write to private field");
16
+ setter ? setter.call(obj, value) : member.set(obj, value);
17
+ return value;
18
+ };
19
+
20
+ // src/authenticate.ts
21
+ var defaultAuthUrl = "api/authn";
22
+ var authenticate = async (username, password, authUrl = defaultAuthUrl) => fetch(authUrl, {
23
+ method: "POST",
24
+ credentials: "include",
25
+ headers: {
26
+ "Content-Type": "application/json",
27
+ "access-control-allow-origin": location.host
28
+ },
29
+ body: JSON.stringify({ username, password })
30
+ }).then((response) => {
31
+ if (response.ok) {
32
+ const authToken = response.headers.get("vuu-auth-token");
33
+ if (typeof authToken === "string" && authToken.length > 0) {
34
+ return authToken;
35
+ } else {
36
+ throw Error(`Authentication failed auth token not returned by server`);
37
+ }
38
+ } else {
39
+ throw Error(
40
+ `Authentication failed ${response.status} ${response.statusText}`
41
+ );
42
+ }
43
+ });
44
+
45
+ // src/connection-manager.ts
46
+ import {
47
+ EventEmitter,
48
+ getLoggingConfigForWorker,
49
+ isConnectionQualityMetrics,
50
+ isConnectionStatusMessage,
51
+ isTableSchema,
52
+ messageHasResult,
53
+ uuid
54
+ } from "@vuu-ui/vuu-utils";
55
+
56
+ // src/data-source.ts
57
+ var isSizeOnly = (message) => message.type === "viewport-update" && message.mode === "size-only";
58
+ var toDataSourceConfig = (message) => {
59
+ switch (message.type) {
60
+ case "aggregate":
61
+ return { aggregations: message.aggregations };
62
+ case "columns":
63
+ return { columns: message.columns };
64
+ case "filter":
65
+ return { filter: message.filter };
66
+ case "groupBy":
67
+ return { groupBy: message.groupBy };
68
+ case "sort":
69
+ return { sort: message.sort };
70
+ case "config":
71
+ return message.config;
72
+ }
73
+ };
74
+ var datasourceMessages = [
75
+ "config",
76
+ "aggregate",
77
+ "viewport-update",
78
+ "columns",
79
+ "debounce-begin",
80
+ "disabled",
81
+ "enabled",
82
+ "filter",
83
+ "groupBy",
84
+ "vuu-link-created",
85
+ "vuu-link-removed",
86
+ "vuu-links",
87
+ "vuu-menu",
88
+ "sort",
89
+ "subscribed"
90
+ ];
91
+ var shouldMessageBeRoutedToDataSource = (message) => {
92
+ const type = message.type;
93
+ return datasourceMessages.includes(type);
94
+ };
95
+ var isDataSourceConfigMessage = (message) => ["config", "aggregate", "columns", "filter", "groupBy", "sort"].includes(
96
+ message.type
97
+ );
98
+ var isSessionTableActionMessage = (messageBody) => messageBody.type === "VIEW_PORT_MENU_RESP" && messageBody.action !== null && isSessionTable(messageBody.action.table);
99
+ var isSessionTable = (table) => {
100
+ if (table !== null && typeof table === "object" && "table" in table && "module" in table) {
101
+ return table.table.startsWith("session");
102
+ }
103
+ return false;
104
+ };
105
+
106
+ // src/server-proxy/messages.ts
107
+ var GET_TABLE_META = "GET_TABLE_META";
108
+
109
+ // src/inlined-worker.js
110
+ var workerSourceCode = `
111
+ var __accessCheck = (obj, member, msg) => {
112
+ if (!member.has(obj))
113
+ throw TypeError("Cannot " + msg);
114
+ };
115
+ var __privateGet = (obj, member, getter) => {
116
+ __accessCheck(obj, member, "read from private field");
117
+ return getter ? getter.call(obj) : member.get(obj);
118
+ };
119
+ var __privateAdd = (obj, member, value) => {
120
+ if (member.has(obj))
121
+ throw TypeError("Cannot add the same private member more than once");
122
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
123
+ };
124
+ var __privateSet = (obj, member, value, setter) => {
125
+ __accessCheck(obj, member, "write to private field");
126
+ setter ? setter.call(obj, value) : member.set(obj, value);
127
+ return value;
128
+ };
129
+
130
+ // ../vuu-utils/src/array-utils.ts
131
+ function partition(array, test, pass = [], fail = []) {
132
+ for (let i = 0, len = array.length; i < len; i++) {
133
+ (test(array[i], i) ? pass : fail).push(array[i]);
134
+ }
135
+ return [pass, fail];
136
+ }
137
+
138
+ // ../vuu-utils/src/column-utils.ts
139
+ var metadataKeys = {
140
+ IDX: 0,
141
+ RENDER_IDX: 1,
142
+ IS_LEAF: 2,
143
+ IS_EXPANDED: 3,
144
+ DEPTH: 4,
145
+ COUNT: 5,
146
+ KEY: 6,
147
+ SELECTED: 7,
148
+ count: 8,
149
+ // TODO following only used in datamodel
150
+ PARENT_IDX: "parent_idx",
151
+ IDX_POINTER: "idx_pointer",
152
+ FILTER_COUNT: "filter_count",
153
+ NEXT_FILTER_IDX: "next_filter_idx"
154
+ };
155
+ var { DEPTH, IS_LEAF } = metadataKeys;
156
+
157
+ // ../vuu-utils/src/cookie-utils.ts
158
+ var getCookieValue = (name) => {
159
+ var _a, _b;
160
+ if (((_a = globalThis.document) == null ? void 0 : _a.cookie) !== void 0) {
161
+ return (_b = globalThis.document.cookie.split("; ").find((row) => row.startsWith(\`\${name}=\`))) == null ? void 0 : _b.split("=")[1];
162
+ }
163
+ };
164
+
165
+ // ../vuu-utils/src/range-utils.ts
166
+ function getFullRange({ from, to }, bufferSize = 0, rowCount = Number.MAX_SAFE_INTEGER) {
167
+ if (bufferSize === 0) {
168
+ if (rowCount < from) {
169
+ return { from: 0, to: 0 };
170
+ } else {
171
+ return { from, to: Math.min(to, rowCount) };
172
+ }
173
+ } else if (from === 0) {
174
+ return { from, to: Math.min(to + bufferSize, rowCount) };
175
+ } else {
176
+ const rangeSize = to - from;
177
+ const buff = Math.round(bufferSize / 2);
178
+ const shortfallBefore = from - buff < 0;
179
+ const shortFallAfter = rowCount - (to + buff) < 0;
180
+ if (shortfallBefore && shortFallAfter) {
181
+ return { from: 0, to: rowCount };
182
+ } else if (shortfallBefore) {
183
+ return { from: 0, to: rangeSize + bufferSize };
184
+ } else if (shortFallAfter) {
185
+ return {
186
+ from: Math.max(0, rowCount - (rangeSize + bufferSize)),
187
+ to: rowCount
188
+ };
189
+ } else {
190
+ return { from: from - buff, to: to + buff };
191
+ }
192
+ }
193
+ }
194
+ var withinRange = (value, { from, to }) => value >= from && value < to;
195
+ var WindowRange = class _WindowRange {
196
+ constructor(from, to) {
197
+ this.from = from;
198
+ this.to = to;
199
+ }
200
+ isWithin(index) {
201
+ return withinRange(index, this);
202
+ }
203
+ //find the overlap of this range and a new one
204
+ overlap(from, to) {
205
+ return from >= this.to || to < this.from ? [0, 0] : [Math.max(from, this.from), Math.min(to, this.to)];
206
+ }
207
+ copy() {
208
+ return new _WindowRange(this.from, this.to);
209
+ }
210
+ };
211
+
212
+ // ../vuu-utils/src/datasource-utils.ts
213
+ var isConnectionStatusMessage = (msg) => msg.type === "connection-status";
214
+ var isConnectionQualityMetrics = (msg) => msg.type === "connection-metrics";
215
+ var isViewporttMessage = (msg) => "viewport" in msg;
216
+
217
+ // ../vuu-utils/src/logging-utils.ts
218
+ var logLevels = ["error", "warn", "info", "debug"];
219
+ var isValidLogLevel = (value) => typeof value === "string" && logLevels.includes(value);
220
+ var DEFAULT_LOG_LEVEL = "error";
221
+ var NO_OP = () => void 0;
222
+ var DEFAULT_DEBUG_LEVEL = false ? "error" : "info";
223
+ var { loggingLevel = DEFAULT_DEBUG_LEVEL } = getLoggingSettings();
224
+ var logger = (category) => {
225
+ const debugEnabled5 = loggingLevel === "debug";
226
+ const infoEnabled5 = debugEnabled5 || loggingLevel === "info";
227
+ const warnEnabled = infoEnabled5 || loggingLevel === "warn";
228
+ const errorEnabled = warnEnabled || loggingLevel === "error";
229
+ const info5 = infoEnabled5 ? (message) => console.info(\`[\${category}] \${message}\`) : NO_OP;
230
+ const warn4 = warnEnabled ? (message) => console.warn(\`[\${category}] \${message}\`) : NO_OP;
231
+ const debug5 = debugEnabled5 ? (message) => console.debug(\`[\${category}] \${message}\`) : NO_OP;
232
+ const error4 = errorEnabled ? (message) => console.error(\`[\${category}] \${message}\`) : NO_OP;
233
+ if (false) {
234
+ return {
235
+ errorEnabled,
236
+ error: error4
237
+ };
238
+ } else {
239
+ return {
240
+ debugEnabled: debugEnabled5,
241
+ infoEnabled: infoEnabled5,
242
+ warnEnabled,
243
+ errorEnabled,
244
+ info: info5,
245
+ warn: warn4,
246
+ debug: debug5,
247
+ error: error4
248
+ };
249
+ }
250
+ };
251
+ function getLoggingSettings() {
252
+ if (typeof loggingSettings !== "undefined") {
253
+ return loggingSettings;
254
+ } else {
255
+ return {
256
+ loggingLevel: getLoggingLevelFromCookie()
257
+ };
258
+ }
259
+ }
260
+ function getLoggingLevelFromCookie() {
261
+ const value = getCookieValue("vuu-logging-level");
262
+ if (isValidLogLevel(value)) {
263
+ return value;
264
+ } else {
265
+ return DEFAULT_LOG_LEVEL;
266
+ }
267
+ }
268
+
269
+ // ../vuu-utils/src/debug-utils.ts
270
+ var { debug, debugEnabled } = logger("range-monitor");
271
+ var RangeMonitor = class {
272
+ constructor(source) {
273
+ this.source = source;
274
+ this.range = { from: 0, to: 0 };
275
+ this.timestamp = 0;
276
+ }
277
+ isSet() {
278
+ return this.timestamp !== 0;
279
+ }
280
+ set({ from, to }) {
281
+ const { timestamp } = this;
282
+ this.range.from = from;
283
+ this.range.to = to;
284
+ this.timestamp = performance.now();
285
+ if (timestamp) {
286
+ debugEnabled && debug(
287
+ \`<\${this.source}> [\${from}-\${to}], \${(this.timestamp - timestamp).toFixed(0)} ms elapsed\`
288
+ );
289
+ } else {
290
+ return 0;
291
+ }
292
+ }
293
+ };
294
+
295
+ // ../vuu-utils/src/keyset.ts
296
+ var KeySet = class {
297
+ constructor(range) {
298
+ this.keys = /* @__PURE__ */ new Map();
299
+ this.free = [];
300
+ this.nextKeyValue = 0;
301
+ this.reset(range);
302
+ }
303
+ next() {
304
+ if (this.free.length > 0) {
305
+ return this.free.pop();
306
+ } else {
307
+ return this.nextKeyValue++;
308
+ }
309
+ }
310
+ reset({ from, to }) {
311
+ this.keys.forEach((keyValue, rowIndex) => {
312
+ if (rowIndex < from || rowIndex >= to) {
313
+ this.free.push(keyValue);
314
+ this.keys.delete(rowIndex);
315
+ }
316
+ });
317
+ const size = to - from;
318
+ if (this.keys.size + this.free.length > size) {
319
+ this.free.length = Math.max(0, size - this.keys.size);
320
+ }
321
+ for (let rowIndex = from; rowIndex < to; rowIndex++) {
322
+ if (!this.keys.has(rowIndex)) {
323
+ const nextKeyValue = this.next();
324
+ this.keys.set(rowIndex, nextKeyValue);
325
+ }
326
+ }
327
+ if (this.nextKeyValue > this.keys.size) {
328
+ this.nextKeyValue = this.keys.size;
329
+ }
330
+ }
331
+ keyFor(rowIndex) {
332
+ const key = this.keys.get(rowIndex);
333
+ if (key === void 0) {
334
+ console.log(\`key not found
335
+ keys: \${this.toDebugString()}
336
+ free : \${this.free.join(",")}
337
+ \`);
338
+ throw Error(\`KeySet, no key found for rowIndex \${rowIndex}\`);
339
+ }
340
+ return key;
341
+ }
342
+ toDebugString() {
343
+ return Array.from(this.keys.entries()).map((k, v) => \`\${k}=>\${v}\`).join(",");
344
+ }
345
+ };
346
+
347
+ // ../vuu-utils/src/selection-utils.ts
348
+ var { SELECTED } = metadataKeys;
349
+ var RowSelected = {
350
+ False: 0,
351
+ True: 1,
352
+ First: 2,
353
+ Last: 4
354
+ };
355
+ var rangeIncludes = (range, index) => index >= range[0] && index <= range[1];
356
+ var SINGLE_SELECTED_ROW = RowSelected.True + RowSelected.First + RowSelected.Last;
357
+ var FIRST_SELECTED_ROW_OF_BLOCK = RowSelected.True + RowSelected.First;
358
+ var LAST_SELECTED_ROW_OF_BLOCK = RowSelected.True + RowSelected.Last;
359
+ var getSelectionStatus = (selected, itemIndex) => {
360
+ for (const item of selected) {
361
+ if (typeof item === "number") {
362
+ if (item === itemIndex) {
363
+ return SINGLE_SELECTED_ROW;
364
+ }
365
+ } else if (rangeIncludes(item, itemIndex)) {
366
+ if (itemIndex === item[0]) {
367
+ return FIRST_SELECTED_ROW_OF_BLOCK;
368
+ } else if (itemIndex === item[1]) {
369
+ return LAST_SELECTED_ROW_OF_BLOCK;
370
+ } else {
371
+ return RowSelected.True;
372
+ }
373
+ }
374
+ }
375
+ return RowSelected.False;
376
+ };
377
+ var expandSelection = (selected) => {
378
+ if (selected.every((selectedItem) => typeof selectedItem === "number")) {
379
+ return selected;
380
+ }
381
+ const expandedSelected = [];
382
+ for (const selectedItem of selected) {
383
+ if (typeof selectedItem === "number") {
384
+ expandedSelected.push(selectedItem);
385
+ } else {
386
+ for (let i = selectedItem[0]; i <= selectedItem[1]; i++) {
387
+ expandedSelected.push(i);
388
+ }
389
+ }
390
+ }
391
+ return expandedSelected;
392
+ };
393
+
394
+ // src/data-source.ts
395
+ var isSessionTableActionMessage = (messageBody) => messageBody.type === "VIEW_PORT_MENU_RESP" && messageBody.action !== null && isSessionTable(messageBody.action.table);
396
+ var isSessionTable = (table) => {
397
+ if (table !== null && typeof table === "object" && "table" in table && "module" in table) {
398
+ return table.table.startsWith("session");
399
+ }
400
+ return false;
401
+ };
402
+
403
+ // src/message-utils.ts
404
+ var MENU_RPC_TYPES = [
405
+ "VIEW_PORT_MENUS_SELECT_RPC",
406
+ "VIEW_PORT_MENU_TABLE_RPC",
407
+ "VIEW_PORT_MENU_ROW_RPC",
408
+ "VIEW_PORT_MENU_CELL_RPC",
409
+ "VP_EDIT_CELL_RPC",
410
+ "VP_EDIT_ROW_RPC",
411
+ "VP_EDIT_ADD_ROW_RPC",
412
+ "VP_EDIT_DELETE_CELL_RPC",
413
+ "VP_EDIT_DELETE_ROW_RPC",
414
+ "VP_EDIT_SUBMIT_FORM_RPC"
415
+ ];
416
+ var isVuuMenuRpcRequest = (message) => MENU_RPC_TYPES.includes(message["type"]);
417
+ var isVuuRpcRequest = (message) => message["type"] === "VIEW_PORT_RPC_CALL";
418
+ var stripRequestId = ({
419
+ requestId,
420
+ ...rest
421
+ }) => [requestId, rest];
422
+ var getFirstAndLastRows = (rows) => {
423
+ let firstRow = rows.at(0);
424
+ if (firstRow.updateType === "SIZE") {
425
+ if (rows.length === 1) {
426
+ return rows;
427
+ } else {
428
+ firstRow = rows.at(1);
429
+ }
430
+ }
431
+ const lastRow = rows.at(-1);
432
+ return [firstRow, lastRow];
433
+ };
434
+ var groupRowsByViewport = (rows) => {
435
+ const result = {};
436
+ for (const row of rows) {
437
+ const rowsForViewport = result[row.viewPortId] || (result[row.viewPortId] = []);
438
+ rowsForViewport.push(row);
439
+ }
440
+ return result;
441
+ };
442
+ var createSchemaFromTableMetadata = ({
443
+ columns,
444
+ dataTypes,
445
+ key,
446
+ table
447
+ }) => {
448
+ return {
449
+ table,
450
+ columns: columns.map((col, idx) => ({
451
+ name: col,
452
+ serverDataType: dataTypes[idx]
453
+ })),
454
+ key
455
+ };
456
+ };
457
+
458
+ // src/server-proxy/messages.ts
459
+ var CHANGE_VP_SUCCESS = "CHANGE_VP_SUCCESS";
460
+ var CLOSE_TREE_NODE = "CLOSE_TREE_NODE";
461
+ var CLOSE_TREE_SUCCESS = "CLOSE_TREE_SUCCESS";
462
+ var CREATE_VP = "CREATE_VP";
463
+ var DISABLE_VP = "DISABLE_VP";
464
+ var DISABLE_VP_SUCCESS = "DISABLE_VP_SUCCESS";
465
+ var ENABLE_VP = "ENABLE_VP";
466
+ var ENABLE_VP_SUCCESS = "ENABLE_VP_SUCCESS";
467
+ var GET_VP_VISUAL_LINKS = "GET_VP_VISUAL_LINKS";
468
+ var GET_VIEW_PORT_MENUS = "GET_VIEW_PORT_MENUS";
469
+ var HB = "HB";
470
+ var HB_RESP = "HB_RESP";
471
+ var LOGIN = "LOGIN";
472
+ var OPEN_TREE_NODE = "OPEN_TREE_NODE";
473
+ var OPEN_TREE_SUCCESS = "OPEN_TREE_SUCCESS";
474
+ var REMOVE_VP = "REMOVE_VP";
475
+ var SET_SELECTION_SUCCESS = "SET_SELECTION_SUCCESS";
476
+
477
+ // src/server-proxy/rpc-services.ts
478
+ var getRpcServiceModule = (service) => {
479
+ switch (service) {
480
+ case "TypeAheadRpcHandler":
481
+ return "TYPEAHEAD";
482
+ default:
483
+ return "SIMUL";
484
+ }
485
+ };
486
+
487
+ // src/server-proxy/array-backed-moving-window.ts
488
+ var EMPTY_ARRAY = [];
489
+ var log = logger("array-backed-moving-window");
490
+ function dataIsUnchanged(newRow, existingRow) {
491
+ if (!existingRow) {
492
+ return false;
493
+ }
494
+ if (existingRow.data.length !== newRow.data.length) {
495
+ return false;
496
+ }
497
+ if (existingRow.sel !== newRow.sel) {
498
+ return false;
499
+ }
500
+ for (let i = 0; i < existingRow.data.length; i++) {
501
+ if (existingRow.data[i] !== newRow.data[i]) {
502
+ return false;
503
+ }
504
+ }
505
+ return true;
506
+ }
507
+ var _range;
508
+ var ArrayBackedMovingWindow = class {
509
+ // Note, the buffer is already accounted for in the range passed in here
510
+ constructor({ from: clientFrom, to: clientTo }, { from, to }, bufferSize) {
511
+ __privateAdd(this, _range, void 0);
512
+ this.setRowCount = (rowCount) => {
513
+ var _a;
514
+ (_a = log.info) == null ? void 0 : _a.call(log, \`setRowCount \${rowCount}\`);
515
+ if (rowCount < this.internalData.length) {
516
+ this.internalData.length = rowCount;
517
+ }
518
+ if (rowCount < this.rowCount) {
519
+ this.rowsWithinRange = 0;
520
+ const end = Math.min(rowCount, this.clientRange.to);
521
+ for (let i = this.clientRange.from; i < end; i++) {
522
+ const rowIndex = i - __privateGet(this, _range).from;
523
+ if (this.internalData[rowIndex] !== void 0) {
524
+ this.rowsWithinRange += 1;
525
+ }
526
+ }
527
+ }
528
+ this.rowCount = rowCount;
529
+ };
530
+ this.bufferBreakout = (from, to) => {
531
+ const bufferPerimeter = this.bufferSize * 0.25;
532
+ if (__privateGet(this, _range).to - to < bufferPerimeter) {
533
+ return true;
534
+ } else if (__privateGet(this, _range).from > 0 && from - __privateGet(this, _range).from < bufferPerimeter) {
535
+ return true;
536
+ } else {
537
+ return false;
538
+ }
539
+ };
540
+ this.bufferSize = bufferSize;
541
+ this.clientRange = new WindowRange(clientFrom, clientTo);
542
+ __privateSet(this, _range, new WindowRange(from, to));
543
+ this.internalData = new Array(bufferSize);
544
+ this.rowsWithinRange = 0;
545
+ this.rowCount = 0;
546
+ }
547
+ get range() {
548
+ return __privateGet(this, _range);
549
+ }
550
+ // TODO we shpuld probably have a hasAllClientRowsWithinRange
551
+ get hasAllRowsWithinRange() {
552
+ return this.rowsWithinRange === this.clientRange.to - this.clientRange.from || // this.rowsWithinRange === this.range.to - this.range.from ||
553
+ this.rowCount > 0 && this.clientRange.from + this.rowsWithinRange === this.rowCount;
554
+ }
555
+ // Check to see if set of rows is outside the current viewport range, indicating
556
+ // that veiwport is being scrolled quickly and server is not able to keep up.
557
+ outOfRange(firstIndex, lastIndex) {
558
+ const { from, to } = this.range;
559
+ if (lastIndex < from) {
560
+ return true;
561
+ }
562
+ if (firstIndex >= to) {
563
+ return true;
564
+ }
565
+ }
566
+ setAtIndex(row) {
567
+ const { rowIndex: index } = row;
568
+ const internalIndex = index - __privateGet(this, _range).from;
569
+ if (dataIsUnchanged(row, this.internalData[internalIndex])) {
570
+ return false;
571
+ }
572
+ const isWithinClientRange = this.isWithinClientRange(index);
573
+ if (isWithinClientRange || this.isWithinRange(index)) {
574
+ if (!this.internalData[internalIndex] && isWithinClientRange) {
575
+ this.rowsWithinRange += 1;
576
+ }
577
+ this.internalData[internalIndex] = row;
578
+ }
579
+ return isWithinClientRange;
580
+ }
581
+ getAtIndex(index) {
582
+ return __privateGet(this, _range).isWithin(index) && this.internalData[index - __privateGet(this, _range).from] != null ? this.internalData[index - __privateGet(this, _range).from] : void 0;
583
+ }
584
+ isWithinRange(index) {
585
+ return __privateGet(this, _range).isWithin(index);
586
+ }
587
+ isWithinClientRange(index) {
588
+ return this.clientRange.isWithin(index);
589
+ }
590
+ // Returns [false] or [serverDataRequired, clientRows, holdingRows]
591
+ setClientRange(from, to) {
592
+ var _a;
593
+ (_a = log.debug) == null ? void 0 : _a.call(log, \`setClientRange \${from} - \${to}\`);
594
+ const currentFrom = this.clientRange.from;
595
+ const currentTo = Math.min(this.clientRange.to, this.rowCount);
596
+ if (from === currentFrom && to === currentTo) {
597
+ return [
598
+ false,
599
+ EMPTY_ARRAY
600
+ /*, EMPTY_ARRAY*/
601
+ ];
602
+ }
603
+ const originalRange = this.clientRange.copy();
604
+ this.clientRange.from = from;
605
+ this.clientRange.to = to;
606
+ this.rowsWithinRange = 0;
607
+ for (let i = from; i < to; i++) {
608
+ const internalIndex = i - __privateGet(this, _range).from;
609
+ if (this.internalData[internalIndex]) {
610
+ this.rowsWithinRange += 1;
611
+ }
612
+ }
613
+ let clientRows = EMPTY_ARRAY;
614
+ const offset = __privateGet(this, _range).from;
615
+ if (this.hasAllRowsWithinRange) {
616
+ if (to > originalRange.to) {
617
+ const start = Math.max(from, originalRange.to);
618
+ clientRows = this.internalData.slice(start - offset, to - offset);
619
+ } else {
620
+ const end = Math.min(originalRange.from, to);
621
+ clientRows = this.internalData.slice(from - offset, end - offset);
622
+ }
623
+ }
624
+ const serverDataRequired = this.bufferBreakout(from, to);
625
+ return [serverDataRequired, clientRows];
626
+ }
627
+ setRange(from, to) {
628
+ var _a, _b;
629
+ if (from !== __privateGet(this, _range).from || to !== __privateGet(this, _range).to) {
630
+ (_a = log.debug) == null ? void 0 : _a.call(log, \`setRange \${from} - \${to}\`);
631
+ const [overlapFrom, overlapTo] = __privateGet(this, _range).overlap(from, to);
632
+ const newData = new Array(to - from);
633
+ this.rowsWithinRange = 0;
634
+ for (let i = overlapFrom; i < overlapTo; i++) {
635
+ const data = this.getAtIndex(i);
636
+ if (data) {
637
+ const index = i - from;
638
+ newData[index] = data;
639
+ if (this.isWithinClientRange(i)) {
640
+ this.rowsWithinRange += 1;
641
+ }
642
+ }
643
+ }
644
+ this.internalData = newData;
645
+ __privateGet(this, _range).from = from;
646
+ __privateGet(this, _range).to = to;
647
+ } else {
648
+ (_b = log.debug) == null ? void 0 : _b.call(log, \`setRange \${from} - \${to} IGNORED because not changed\`);
649
+ }
650
+ }
651
+ //TODO temp
652
+ get data() {
653
+ return this.internalData;
654
+ }
655
+ getData() {
656
+ var _a;
657
+ const { from, to } = __privateGet(this, _range);
658
+ const { from: clientFrom, to: clientTo } = this.clientRange;
659
+ const startOffset = Math.max(0, clientFrom - from);
660
+ const endOffset = Math.min(
661
+ to - from,
662
+ to,
663
+ clientTo - from,
664
+ (_a = this.rowCount) != null ? _a : to
665
+ );
666
+ return this.internalData.slice(startOffset, endOffset);
667
+ }
668
+ clear() {
669
+ var _a;
670
+ (_a = log.debug) == null ? void 0 : _a.call(log, "clear");
671
+ this.internalData.length = 0;
672
+ this.rowsWithinRange = 0;
673
+ this.setRowCount(0);
674
+ }
675
+ // used only for debugging
676
+ getCurrentDataRange() {
677
+ const rows = this.internalData;
678
+ const len = rows.length;
679
+ let [firstRow] = this.internalData;
680
+ let lastRow = this.internalData[len - 1];
681
+ if (firstRow && lastRow) {
682
+ return [firstRow.rowIndex, lastRow.rowIndex];
683
+ } else {
684
+ for (let i = 0; i < len; i++) {
685
+ if (rows[i] !== void 0) {
686
+ firstRow = rows[i];
687
+ break;
688
+ }
689
+ }
690
+ for (let i = len - 1; i >= 0; i--) {
691
+ if (rows[i] !== void 0) {
692
+ lastRow = rows[i];
693
+ break;
694
+ }
695
+ }
696
+ if (firstRow && lastRow) {
697
+ return [firstRow.rowIndex, lastRow.rowIndex];
698
+ } else {
699
+ return [-1, -1];
700
+ }
701
+ }
702
+ }
703
+ };
704
+ _range = new WeakMap();
705
+
706
+ // src/server-proxy/viewport.ts
707
+ var EMPTY_GROUPBY = [];
708
+ var { debug: debug2, debugEnabled: debugEnabled2, error, info, infoEnabled, warn } = logger("viewport");
709
+ var isLeafUpdate = ({ rowKey, updateType }) => updateType === "U" && !rowKey.startsWith("$root");
710
+ var NO_DATA_UPDATE = [
711
+ void 0,
712
+ void 0
713
+ ];
714
+ var NO_UPDATE_STATUS = {
715
+ count: 0,
716
+ mode: void 0,
717
+ size: 0,
718
+ ts: 0
719
+ };
720
+ var Viewport = class {
721
+ constructor({
722
+ aggregations,
723
+ bufferSize = 50,
724
+ columns,
725
+ filter,
726
+ groupBy = [],
727
+ table,
728
+ range,
729
+ sort,
730
+ title,
731
+ viewport,
732
+ visualLink
733
+ }, postMessageToClient) {
734
+ /** batchMode is irrelevant for Vuu Table, it was introduced to try and improve rendering performance of AgGrid */
735
+ this.batchMode = true;
736
+ this.hasUpdates = false;
737
+ this.pendingUpdates = [];
738
+ this.pendingOperations = /* @__PURE__ */ new Map();
739
+ this.pendingRangeRequests = [];
740
+ this.rowCountChanged = false;
741
+ this.selectedRows = [];
742
+ this.useBatchMode = true;
743
+ this.lastUpdateStatus = NO_UPDATE_STATUS;
744
+ this.updateThrottleTimer = void 0;
745
+ this.rangeMonitor = new RangeMonitor("ViewPort");
746
+ this.disabled = false;
747
+ this.isTree = false;
748
+ // TODO roll disabled/suspended into status
749
+ this.status = "";
750
+ this.suspended = false;
751
+ this.suspendTimer = null;
752
+ // Records SIZE only updates
753
+ this.setLastSizeOnlyUpdateSize = (size) => {
754
+ this.lastUpdateStatus.size = size;
755
+ };
756
+ this.setLastUpdate = (mode) => {
757
+ const { ts: lastTS, mode: lastMode } = this.lastUpdateStatus;
758
+ let elapsedTime = 0;
759
+ if (lastMode === mode) {
760
+ const ts = Date.now();
761
+ this.lastUpdateStatus.count += 1;
762
+ this.lastUpdateStatus.ts = ts;
763
+ elapsedTime = lastTS === 0 ? 0 : ts - lastTS;
764
+ } else {
765
+ this.lastUpdateStatus.count = 1;
766
+ this.lastUpdateStatus.ts = 0;
767
+ elapsedTime = 0;
768
+ }
769
+ this.lastUpdateStatus.mode = mode;
770
+ return elapsedTime;
771
+ };
772
+ this.rangeRequestAlreadyPending = (range) => {
773
+ const { bufferSize } = this;
774
+ const bufferThreshold = bufferSize * 0.25;
775
+ let { from: stillPendingFrom } = range;
776
+ for (const { from, to } of this.pendingRangeRequests) {
777
+ if (stillPendingFrom >= from && stillPendingFrom < to) {
778
+ if (range.to + bufferThreshold <= to) {
779
+ return true;
780
+ } else {
781
+ stillPendingFrom = to;
782
+ }
783
+ }
784
+ }
785
+ return false;
786
+ };
787
+ this.sendThrottledSizeMessage = () => {
788
+ this.updateThrottleTimer = void 0;
789
+ this.lastUpdateStatus.count = 3;
790
+ this.postMessageToClient({
791
+ clientViewportId: this.clientViewportId,
792
+ mode: "size-only",
793
+ size: this.lastUpdateStatus.size,
794
+ type: "viewport-update"
795
+ });
796
+ };
797
+ // If we are receiving multiple SIZE updates but no data, table is loading rows
798
+ // outside of our viewport. We can safely throttle these requests. Doing so will
799
+ // alleviate pressure on UI DataTable.
800
+ this.shouldThrottleMessage = (mode) => {
801
+ const elapsedTime = this.setLastUpdate(mode);
802
+ return mode === "size-only" && elapsedTime > 0 && elapsedTime < 500 && this.lastUpdateStatus.count > 3;
803
+ };
804
+ this.throttleMessage = (mode) => {
805
+ if (this.shouldThrottleMessage(mode)) {
806
+ info == null ? void 0 : info("throttling updates setTimeout to 2000");
807
+ if (this.updateThrottleTimer === void 0) {
808
+ this.updateThrottleTimer = setTimeout(
809
+ this.sendThrottledSizeMessage,
810
+ 2e3
811
+ );
812
+ }
813
+ return true;
814
+ } else if (this.updateThrottleTimer !== void 0) {
815
+ clearTimeout(this.updateThrottleTimer);
816
+ this.updateThrottleTimer = void 0;
817
+ }
818
+ return false;
819
+ };
820
+ this.getNewRowCount = () => {
821
+ if (this.rowCountChanged && this.dataWindow) {
822
+ this.rowCountChanged = false;
823
+ return this.dataWindow.rowCount;
824
+ }
825
+ };
826
+ this.aggregations = aggregations;
827
+ this.bufferSize = bufferSize;
828
+ this.clientRange = range;
829
+ this.clientViewportId = viewport;
830
+ this.columns = columns;
831
+ this.filter = filter;
832
+ this.groupBy = groupBy;
833
+ this.keys = new KeySet(range);
834
+ this.pendingLinkedParent = visualLink;
835
+ this.table = table;
836
+ this.sort = sort;
837
+ this.title = title;
838
+ infoEnabled && (info == null ? void 0 : info(
839
+ \`constructor #\${viewport} \${table.table} bufferSize=\${bufferSize}\`
840
+ ));
841
+ this.dataWindow = new ArrayBackedMovingWindow(
842
+ this.clientRange,
843
+ range,
844
+ this.bufferSize
845
+ );
846
+ this.postMessageToClient = postMessageToClient;
847
+ }
848
+ get hasUpdatesToProcess() {
849
+ if (this.suspended) {
850
+ return false;
851
+ }
852
+ return this.rowCountChanged || this.hasUpdates;
853
+ }
854
+ get size() {
855
+ var _a;
856
+ return (_a = this.dataWindow.rowCount) != null ? _a : 0;
857
+ }
858
+ subscribe() {
859
+ const { filter } = this.filter;
860
+ this.status = this.status === "subscribed" ? "resubscribing" : "subscribing";
861
+ return {
862
+ type: CREATE_VP,
863
+ table: this.table,
864
+ range: getFullRange(this.clientRange, this.bufferSize),
865
+ aggregations: this.aggregations,
866
+ columns: this.columns,
867
+ sort: this.sort,
868
+ groupBy: this.groupBy,
869
+ filterSpec: { filter }
870
+ };
871
+ }
872
+ handleSubscribed({
873
+ viewPortId,
874
+ aggregations,
875
+ columns,
876
+ filterSpec: filter,
877
+ range,
878
+ sort,
879
+ groupBy
880
+ }, tableSchema) {
881
+ this.serverViewportId = viewPortId;
882
+ this.status = "subscribed";
883
+ this.aggregations = aggregations;
884
+ this.columns = columns;
885
+ this.groupBy = groupBy;
886
+ this.isTree = groupBy && groupBy.length > 0;
887
+ this.dataWindow.setRange(range.from, range.to);
888
+ return {
889
+ aggregations,
890
+ type: "subscribed",
891
+ clientViewportId: this.clientViewportId,
892
+ columns,
893
+ filter,
894
+ groupBy,
895
+ range,
896
+ sort,
897
+ tableSchema
898
+ };
899
+ }
900
+ awaitOperation(requestId, msg) {
901
+ this.pendingOperations.set(requestId, msg);
902
+ }
903
+ // Return a message if we need to communicate this to client UI
904
+ completeOperation(requestId, ...params) {
905
+ var _a;
906
+ const { clientViewportId, pendingOperations } = this;
907
+ const pendingOperation = pendingOperations.get(requestId);
908
+ if (!pendingOperation) {
909
+ error(
910
+ \`no matching operation found to complete for requestId \${requestId}\`
911
+ );
912
+ return;
913
+ }
914
+ const { type } = pendingOperation;
915
+ info == null ? void 0 : info(\`completeOperation \${type}\`);
916
+ pendingOperations.delete(requestId);
917
+ if (type === "CHANGE_VP_RANGE") {
918
+ const [from, to] = params;
919
+ (_a = this.dataWindow) == null ? void 0 : _a.setRange(from, to);
920
+ for (let i = this.pendingRangeRequests.length - 1; i >= 0; i--) {
921
+ const pendingRangeRequest = this.pendingRangeRequests[i];
922
+ if (pendingRangeRequest.requestId === requestId) {
923
+ pendingRangeRequest.acked = true;
924
+ break;
925
+ } else {
926
+ warn == null ? void 0 : warn("range requests sent faster than they are being ACKed");
927
+ }
928
+ }
929
+ } else if (type === "config") {
930
+ const { aggregations, columns, filter, groupBy, sort } = pendingOperation.data;
931
+ this.aggregations = aggregations;
932
+ this.columns = columns;
933
+ this.filter = filter;
934
+ this.groupBy = groupBy;
935
+ this.sort = sort;
936
+ if (groupBy.length > 0) {
937
+ this.isTree = true;
938
+ } else if (this.isTree) {
939
+ this.isTree = false;
940
+ }
941
+ debug2 == null ? void 0 : debug2(\`config change confirmed, isTree : \${this.isTree}\`);
942
+ return {
943
+ clientViewportId,
944
+ type,
945
+ config: pendingOperation.data
946
+ };
947
+ } else if (type === "groupBy") {
948
+ this.isTree = pendingOperation.data.length > 0;
949
+ this.groupBy = pendingOperation.data;
950
+ debug2 == null ? void 0 : debug2(\`groupBy change confirmed, isTree : \${this.isTree}\`);
951
+ return {
952
+ clientViewportId,
953
+ type,
954
+ groupBy: pendingOperation.data
955
+ };
956
+ } else if (type === "columns") {
957
+ this.columns = pendingOperation.data;
958
+ return {
959
+ clientViewportId,
960
+ type,
961
+ columns: pendingOperation.data
962
+ };
963
+ } else if (type === "filter") {
964
+ this.filter = pendingOperation.data;
965
+ return {
966
+ clientViewportId,
967
+ type,
968
+ filter: pendingOperation.data
969
+ };
970
+ } else if (type === "aggregate") {
971
+ this.aggregations = pendingOperation.data;
972
+ return {
973
+ clientViewportId,
974
+ type: "aggregate",
975
+ aggregations: this.aggregations
976
+ };
977
+ } else if (type === "sort") {
978
+ this.sort = pendingOperation.data;
979
+ return {
980
+ clientViewportId,
981
+ type,
982
+ sort: this.sort
983
+ };
984
+ } else if (type === "selection") {
985
+ } else if (type === "disable") {
986
+ this.disabled = true;
987
+ return {
988
+ type: "disabled",
989
+ clientViewportId
990
+ };
991
+ } else if (type === "enable") {
992
+ this.disabled = false;
993
+ return {
994
+ type: "enabled",
995
+ clientViewportId
996
+ };
997
+ } else if (type === "CREATE_VISUAL_LINK") {
998
+ const [colName, parentViewportId, parentColName] = params;
999
+ this.linkedParent = {
1000
+ colName,
1001
+ parentViewportId,
1002
+ parentColName
1003
+ };
1004
+ this.pendingLinkedParent = void 0;
1005
+ return {
1006
+ type: "vuu-link-created",
1007
+ clientViewportId,
1008
+ colName,
1009
+ parentViewportId,
1010
+ parentColName
1011
+ };
1012
+ } else if (type === "REMOVE_VISUAL_LINK") {
1013
+ this.linkedParent = void 0;
1014
+ return {
1015
+ type: "vuu-link-removed",
1016
+ clientViewportId
1017
+ };
1018
+ }
1019
+ }
1020
+ // TODO when a range request arrives, consider the viewport to be scrolling
1021
+ // until data arrives and we have the full range.
1022
+ // When not scrolling, any server data is an update
1023
+ // When scrolling, we are in batch mode
1024
+ rangeRequest(requestId, range) {
1025
+ if (debugEnabled2) {
1026
+ this.rangeMonitor.set(range);
1027
+ }
1028
+ const type = "CHANGE_VP_RANGE";
1029
+ if (this.dataWindow) {
1030
+ const [serverDataRequired, clientRows] = this.dataWindow.setClientRange(
1031
+ range.from,
1032
+ range.to
1033
+ );
1034
+ let debounceRequest;
1035
+ const maxRange = this.dataWindow.rowCount || void 0;
1036
+ const serverRequest = serverDataRequired && !this.rangeRequestAlreadyPending(range) ? {
1037
+ type,
1038
+ viewPortId: this.serverViewportId,
1039
+ ...getFullRange(range, this.bufferSize, maxRange)
1040
+ } : null;
1041
+ if (serverRequest) {
1042
+ debugEnabled2 && (debug2 == null ? void 0 : debug2(
1043
+ \`create CHANGE_VP_RANGE: [\${serverRequest.from} - \${serverRequest.to}]\`
1044
+ ));
1045
+ this.awaitOperation(requestId, { type });
1046
+ const pendingRequest = this.pendingRangeRequests.at(-1);
1047
+ if (pendingRequest) {
1048
+ if (pendingRequest.acked) {
1049
+ console.warn("Range Request before previous request is filled");
1050
+ } else {
1051
+ const { from, to } = pendingRequest;
1052
+ if (this.dataWindow.outOfRange(from, to)) {
1053
+ debounceRequest = {
1054
+ clientViewportId: this.clientViewportId,
1055
+ type: "debounce-begin"
1056
+ };
1057
+ } else {
1058
+ warn == null ? void 0 : warn("Range Request before previous request is acked");
1059
+ }
1060
+ }
1061
+ }
1062
+ this.pendingRangeRequests.push({ ...serverRequest, requestId });
1063
+ if (this.useBatchMode) {
1064
+ this.batchMode = true;
1065
+ }
1066
+ } else if (clientRows.length > 0) {
1067
+ this.batchMode = false;
1068
+ }
1069
+ this.keys.reset(this.dataWindow.clientRange);
1070
+ const toClient = this.isTree ? toClientRowTree : toClientRow;
1071
+ if (clientRows.length) {
1072
+ return [
1073
+ serverRequest,
1074
+ clientRows.map((row) => {
1075
+ return toClient(row, this.keys, this.selectedRows);
1076
+ })
1077
+ ];
1078
+ } else if (debounceRequest) {
1079
+ return [serverRequest, void 0, debounceRequest];
1080
+ } else {
1081
+ return [serverRequest];
1082
+ }
1083
+ } else {
1084
+ return [null];
1085
+ }
1086
+ }
1087
+ setLinks(links) {
1088
+ this.links = links;
1089
+ return [
1090
+ {
1091
+ type: "vuu-links",
1092
+ links,
1093
+ clientViewportId: this.clientViewportId
1094
+ },
1095
+ this.pendingLinkedParent
1096
+ ];
1097
+ }
1098
+ setMenu(menu) {
1099
+ return {
1100
+ type: "vuu-menu",
1101
+ menu,
1102
+ clientViewportId: this.clientViewportId
1103
+ };
1104
+ }
1105
+ openTreeNode(requestId, message) {
1106
+ if (this.useBatchMode) {
1107
+ this.batchMode = true;
1108
+ }
1109
+ return {
1110
+ type: OPEN_TREE_NODE,
1111
+ vpId: this.serverViewportId,
1112
+ treeKey: message.key
1113
+ };
1114
+ }
1115
+ closeTreeNode(requestId, message) {
1116
+ if (this.useBatchMode) {
1117
+ this.batchMode = true;
1118
+ }
1119
+ return {
1120
+ type: CLOSE_TREE_NODE,
1121
+ vpId: this.serverViewportId,
1122
+ treeKey: message.key
1123
+ };
1124
+ }
1125
+ createLink(requestId, colName, parentVpId, parentColumnName) {
1126
+ const message = {
1127
+ type: "CREATE_VISUAL_LINK",
1128
+ parentVpId,
1129
+ childVpId: this.serverViewportId,
1130
+ parentColumnName,
1131
+ childColumnName: colName
1132
+ };
1133
+ this.awaitOperation(requestId, message);
1134
+ if (this.useBatchMode) {
1135
+ this.batchMode = true;
1136
+ }
1137
+ return message;
1138
+ }
1139
+ removeLink(requestId) {
1140
+ const message = {
1141
+ type: "REMOVE_VISUAL_LINK",
1142
+ childVpId: this.serverViewportId
1143
+ };
1144
+ this.awaitOperation(requestId, message);
1145
+ return message;
1146
+ }
1147
+ suspend() {
1148
+ this.suspended = true;
1149
+ info == null ? void 0 : info("suspend");
1150
+ }
1151
+ resume() {
1152
+ this.suspended = false;
1153
+ if (debugEnabled2) {
1154
+ debug2 == null ? void 0 : debug2(\`resume: \${this.currentData()}\`);
1155
+ }
1156
+ return [this.size, this.currentData()];
1157
+ }
1158
+ currentData() {
1159
+ const out = [];
1160
+ if (this.dataWindow) {
1161
+ const records = this.dataWindow.getData();
1162
+ const { keys } = this;
1163
+ const toClient = this.isTree ? toClientRowTree : toClientRow;
1164
+ for (const row of records) {
1165
+ if (row) {
1166
+ out.push(toClient(row, keys, this.selectedRows));
1167
+ }
1168
+ }
1169
+ }
1170
+ return out;
1171
+ }
1172
+ enable(requestId) {
1173
+ this.awaitOperation(requestId, { type: "enable" });
1174
+ info == null ? void 0 : info(\`enable: \${this.serverViewportId}\`);
1175
+ return {
1176
+ type: ENABLE_VP,
1177
+ viewPortId: this.serverViewportId
1178
+ };
1179
+ }
1180
+ disable(requestId) {
1181
+ this.awaitOperation(requestId, { type: "disable" });
1182
+ info == null ? void 0 : info(\`disable: \${this.serverViewportId}\`);
1183
+ this.suspended = false;
1184
+ return {
1185
+ type: DISABLE_VP,
1186
+ viewPortId: this.serverViewportId
1187
+ };
1188
+ }
1189
+ columnRequest(requestId, columns) {
1190
+ this.awaitOperation(requestId, {
1191
+ type: "columns",
1192
+ data: columns
1193
+ });
1194
+ debug2 == null ? void 0 : debug2(\`columnRequest: \${columns}\`);
1195
+ return this.createRequest({ columns });
1196
+ }
1197
+ filterRequest(requestId, dataSourceFilter) {
1198
+ this.awaitOperation(requestId, {
1199
+ type: "filter",
1200
+ data: dataSourceFilter
1201
+ });
1202
+ if (this.useBatchMode) {
1203
+ this.batchMode = true;
1204
+ }
1205
+ const { filter } = dataSourceFilter;
1206
+ info == null ? void 0 : info(\`filterRequest: \${filter}\`);
1207
+ return this.createRequest({ filterSpec: { filter } });
1208
+ }
1209
+ setConfig(requestId, config) {
1210
+ this.awaitOperation(requestId, { type: "config", data: config });
1211
+ const { filter, ...remainingConfig } = config;
1212
+ if (this.useBatchMode) {
1213
+ this.batchMode = true;
1214
+ }
1215
+ debugEnabled2 ? debug2 == null ? void 0 : debug2(\`setConfig \${JSON.stringify(config)}\`) : info == null ? void 0 : info(\`setConfig\`);
1216
+ return this.createRequest(
1217
+ {
1218
+ ...remainingConfig,
1219
+ filterSpec: typeof (filter == null ? void 0 : filter.filter) === "string" ? {
1220
+ filter: filter.filter
1221
+ } : {
1222
+ filter: ""
1223
+ }
1224
+ },
1225
+ true
1226
+ );
1227
+ }
1228
+ aggregateRequest(requestId, aggregations) {
1229
+ this.awaitOperation(requestId, { type: "aggregate", data: aggregations });
1230
+ info == null ? void 0 : info(\`aggregateRequest: \${aggregations}\`);
1231
+ return this.createRequest({ aggregations });
1232
+ }
1233
+ sortRequest(requestId, sort) {
1234
+ this.awaitOperation(requestId, { type: "sort", data: sort });
1235
+ info == null ? void 0 : info(\`sortRequest: \${JSON.stringify(sort.sortDefs)}\`);
1236
+ return this.createRequest({ sort });
1237
+ }
1238
+ groupByRequest(requestId, groupBy = EMPTY_GROUPBY) {
1239
+ var _a;
1240
+ this.awaitOperation(requestId, { type: "groupBy", data: groupBy });
1241
+ if (this.useBatchMode) {
1242
+ this.batchMode = true;
1243
+ }
1244
+ if (!this.isTree) {
1245
+ (_a = this.dataWindow) == null ? void 0 : _a.clear();
1246
+ }
1247
+ return this.createRequest({ groupBy });
1248
+ }
1249
+ selectRequest(requestId, selected) {
1250
+ this.selectedRows = selected;
1251
+ this.awaitOperation(requestId, { type: "selection", data: selected });
1252
+ info == null ? void 0 : info(\`selectRequest: \${selected}\`);
1253
+ return {
1254
+ type: "SET_SELECTION",
1255
+ vpId: this.serverViewportId,
1256
+ selection: expandSelection(selected)
1257
+ };
1258
+ }
1259
+ removePendingRangeRequest(firstIndex, lastIndex) {
1260
+ for (let i = this.pendingRangeRequests.length - 1; i >= 0; i--) {
1261
+ const { from, to } = this.pendingRangeRequests[i];
1262
+ let isLast = true;
1263
+ if (firstIndex >= from && firstIndex < to || lastIndex > from && lastIndex < to) {
1264
+ if (!isLast) {
1265
+ console.warn(
1266
+ "removePendingRangeRequest TABLE_ROWS are not for latest request"
1267
+ );
1268
+ }
1269
+ this.pendingRangeRequests.splice(i, 1);
1270
+ break;
1271
+ } else {
1272
+ isLast = false;
1273
+ }
1274
+ }
1275
+ }
1276
+ updateRows(rows) {
1277
+ var _a, _b, _c;
1278
+ const [firstRow, lastRow] = getFirstAndLastRows(rows);
1279
+ if (firstRow && lastRow) {
1280
+ this.removePendingRangeRequest(firstRow.rowIndex, lastRow.rowIndex);
1281
+ }
1282
+ if (rows.length === 1) {
1283
+ if (firstRow.vpSize === 0 && this.disabled) {
1284
+ debug2 == null ? void 0 : debug2(
1285
+ \`ignore a SIZE=0 message on disabled viewport (\${rows.length} rows)\`
1286
+ );
1287
+ return;
1288
+ } else if (firstRow.updateType === "SIZE") {
1289
+ this.setLastSizeOnlyUpdateSize(firstRow.vpSize);
1290
+ }
1291
+ }
1292
+ for (const row of rows) {
1293
+ if (this.isTree && isLeafUpdate(row)) {
1294
+ continue;
1295
+ } else {
1296
+ if (row.updateType === "SIZE" || ((_a = this.dataWindow) == null ? void 0 : _a.rowCount) !== row.vpSize) {
1297
+ (_b = this.dataWindow) == null ? void 0 : _b.setRowCount(row.vpSize);
1298
+ this.rowCountChanged = true;
1299
+ }
1300
+ if (row.updateType === "U") {
1301
+ if ((_c = this.dataWindow) == null ? void 0 : _c.setAtIndex(row)) {
1302
+ this.hasUpdates = true;
1303
+ if (!this.batchMode) {
1304
+ this.pendingUpdates.push(row);
1305
+ }
1306
+ }
1307
+ }
1308
+ }
1309
+ }
1310
+ }
1311
+ // This is called only after new data has been received from server - data
1312
+ // returned direcly from buffer does not use this.
1313
+ getClientRows() {
1314
+ let out = void 0;
1315
+ let mode = "size-only";
1316
+ if (!this.hasUpdates && !this.rowCountChanged) {
1317
+ return NO_DATA_UPDATE;
1318
+ }
1319
+ if (this.hasUpdates) {
1320
+ const { keys, selectedRows } = this;
1321
+ const toClient = this.isTree ? toClientRowTree : toClientRow;
1322
+ if (this.updateThrottleTimer) {
1323
+ self.clearTimeout(this.updateThrottleTimer);
1324
+ this.updateThrottleTimer = void 0;
1325
+ }
1326
+ if (this.pendingUpdates.length > 0) {
1327
+ out = [];
1328
+ mode = "update";
1329
+ for (const row of this.pendingUpdates) {
1330
+ out.push(toClient(row, keys, selectedRows));
1331
+ }
1332
+ this.pendingUpdates.length = 0;
1333
+ } else {
1334
+ const records = this.dataWindow.getData();
1335
+ if (this.dataWindow.hasAllRowsWithinRange) {
1336
+ out = [];
1337
+ mode = "batch";
1338
+ for (const row of records) {
1339
+ out.push(toClient(row, keys, selectedRows));
1340
+ }
1341
+ this.batchMode = false;
1342
+ }
1343
+ }
1344
+ this.hasUpdates = false;
1345
+ }
1346
+ if (this.throttleMessage(mode)) {
1347
+ return NO_DATA_UPDATE;
1348
+ } else {
1349
+ return [out, mode];
1350
+ }
1351
+ }
1352
+ createRequest(params, overWrite = false) {
1353
+ if (overWrite) {
1354
+ return {
1355
+ type: "CHANGE_VP",
1356
+ viewPortId: this.serverViewportId,
1357
+ ...params
1358
+ };
1359
+ } else {
1360
+ return {
1361
+ type: "CHANGE_VP",
1362
+ viewPortId: this.serverViewportId,
1363
+ aggregations: this.aggregations,
1364
+ columns: this.columns,
1365
+ sort: this.sort,
1366
+ groupBy: this.groupBy,
1367
+ filterSpec: {
1368
+ filter: this.filter.filter
1369
+ },
1370
+ ...params
1371
+ };
1372
+ }
1373
+ }
1374
+ };
1375
+ var toClientRow = ({ rowIndex, rowKey, sel: isSelected, data }, keys, selectedRows) => {
1376
+ return [
1377
+ rowIndex,
1378
+ keys.keyFor(rowIndex),
1379
+ true,
1380
+ false,
1381
+ 0,
1382
+ 0,
1383
+ rowKey,
1384
+ isSelected ? getSelectionStatus(selectedRows, rowIndex) : 0
1385
+ ].concat(data);
1386
+ };
1387
+ var toClientRowTree = ({ rowIndex, rowKey, sel: isSelected, data }, keys, selectedRows) => {
1388
+ const [depth, isExpanded, , isLeaf, , count, ...rest] = data;
1389
+ return [
1390
+ rowIndex,
1391
+ keys.keyFor(rowIndex),
1392
+ isLeaf,
1393
+ isExpanded,
1394
+ depth,
1395
+ count,
1396
+ rowKey,
1397
+ isSelected ? getSelectionStatus(selectedRows, rowIndex) : 0
1398
+ ].concat(rest);
1399
+ };
1400
+
1401
+ // src/server-proxy/server-proxy.ts
1402
+ var _requestId = 1;
1403
+ var { debug: debug3, debugEnabled: debugEnabled3, error: error2, info: info2, infoEnabled: infoEnabled2, warn: warn2 } = logger("server-proxy");
1404
+ var nextRequestId = () => \`\${_requestId++}\`;
1405
+ var DEFAULT_OPTIONS = {};
1406
+ var isActiveViewport = (viewPort) => viewPort.disabled !== true && viewPort.suspended !== true;
1407
+ var NO_ACTION = {
1408
+ type: "NO_ACTION"
1409
+ };
1410
+ var addTitleToLinks = (links, serverViewportId, label) => links.map(
1411
+ (link) => link.parentVpId === serverViewportId ? { ...link, label } : link
1412
+ );
1413
+ function addLabelsToLinks(links, viewports) {
1414
+ return links.map((linkDescriptor) => {
1415
+ const { parentVpId } = linkDescriptor;
1416
+ const viewport = viewports.get(parentVpId);
1417
+ if (viewport) {
1418
+ return {
1419
+ ...linkDescriptor,
1420
+ parentClientVpId: viewport.clientViewportId,
1421
+ label: viewport.title
1422
+ };
1423
+ } else {
1424
+ throw Error("addLabelsToLinks viewport not found");
1425
+ }
1426
+ });
1427
+ }
1428
+ var ServerProxy = class {
1429
+ constructor(connection, callback) {
1430
+ this.authToken = "";
1431
+ this.user = "user";
1432
+ this.pendingRequests = /* @__PURE__ */ new Map();
1433
+ this.queuedRequests = [];
1434
+ this.cachedTableMetaRequests = /* @__PURE__ */ new Map();
1435
+ this.cachedTableSchemas = /* @__PURE__ */ new Map();
1436
+ this.connection = connection;
1437
+ this.postMessageToClient = callback;
1438
+ this.viewports = /* @__PURE__ */ new Map();
1439
+ this.mapClientToServerViewport = /* @__PURE__ */ new Map();
1440
+ }
1441
+ async reconnect() {
1442
+ await this.login(this.authToken);
1443
+ const [activeViewports, inactiveViewports] = partition(
1444
+ Array.from(this.viewports.values()),
1445
+ isActiveViewport
1446
+ );
1447
+ this.viewports.clear();
1448
+ this.mapClientToServerViewport.clear();
1449
+ const reconnectViewports = (viewports) => {
1450
+ viewports.forEach((viewport) => {
1451
+ const { clientViewportId } = viewport;
1452
+ this.viewports.set(clientViewportId, viewport);
1453
+ this.sendMessageToServer(viewport.subscribe(), clientViewportId);
1454
+ });
1455
+ };
1456
+ reconnectViewports(activeViewports);
1457
+ setTimeout(() => {
1458
+ reconnectViewports(inactiveViewports);
1459
+ }, 2e3);
1460
+ }
1461
+ async login(authToken, user = "user") {
1462
+ if (authToken) {
1463
+ this.authToken = authToken;
1464
+ this.user = user;
1465
+ return new Promise((resolve, reject) => {
1466
+ this.sendMessageToServer(
1467
+ { type: LOGIN, token: this.authToken, user },
1468
+ ""
1469
+ );
1470
+ this.pendingLogin = { resolve, reject };
1471
+ });
1472
+ } else if (this.authToken === "") {
1473
+ error2("login, cannot login until auth token has been obtained");
1474
+ }
1475
+ }
1476
+ subscribe(message) {
1477
+ if (!this.mapClientToServerViewport.has(message.viewport)) {
1478
+ const pendingTableSchema = this.getTableMeta(message.table);
1479
+ const viewport = new Viewport(message, this.postMessageToClient);
1480
+ this.viewports.set(message.viewport, viewport);
1481
+ const pendingSubscription = this.awaitResponseToMessage(
1482
+ viewport.subscribe(),
1483
+ message.viewport
1484
+ );
1485
+ const awaitPendingReponses = Promise.all([
1486
+ pendingSubscription,
1487
+ pendingTableSchema
1488
+ ]);
1489
+ awaitPendingReponses.then(([subscribeResponse, tableSchema]) => {
1490
+ const { viewPortId: serverViewportId } = subscribeResponse;
1491
+ const { status: previousViewportStatus } = viewport;
1492
+ if (message.viewport !== serverViewportId) {
1493
+ this.viewports.delete(message.viewport);
1494
+ this.viewports.set(serverViewportId, viewport);
1495
+ }
1496
+ this.mapClientToServerViewport.set(message.viewport, serverViewportId);
1497
+ const clientResponse = viewport.handleSubscribed(
1498
+ subscribeResponse,
1499
+ tableSchema
1500
+ );
1501
+ if (clientResponse) {
1502
+ this.postMessageToClient(clientResponse);
1503
+ if (debugEnabled3) {
1504
+ debug3(
1505
+ \`post DataSourceSubscribedMessage to client: \${JSON.stringify(
1506
+ clientResponse
1507
+ )}\`
1508
+ );
1509
+ }
1510
+ }
1511
+ if (viewport.disabled) {
1512
+ this.disableViewport(viewport);
1513
+ }
1514
+ if (this.queuedRequests.length > 0) {
1515
+ this.processQueuedRequests();
1516
+ }
1517
+ if (previousViewportStatus === "subscribing" && // A session table will never have Visual Links, nor Context Menus
1518
+ !isSessionTable(viewport.table)) {
1519
+ this.sendMessageToServer({
1520
+ type: GET_VP_VISUAL_LINKS,
1521
+ vpId: serverViewportId
1522
+ });
1523
+ this.sendMessageToServer({
1524
+ type: GET_VIEW_PORT_MENUS,
1525
+ vpId: serverViewportId
1526
+ });
1527
+ Array.from(this.viewports.entries()).filter(
1528
+ ([id, { disabled }]) => id !== serverViewportId && !disabled
1529
+ ).forEach(([vpId]) => {
1530
+ this.sendMessageToServer({
1531
+ type: GET_VP_VISUAL_LINKS,
1532
+ vpId
1533
+ });
1534
+ });
1535
+ }
1536
+ });
1537
+ } else {
1538
+ error2(\`spurious subscribe call \${message.viewport}\`);
1539
+ }
1540
+ }
1541
+ processQueuedRequests() {
1542
+ const messageTypesProcessed = {};
1543
+ while (this.queuedRequests.length) {
1544
+ const queuedRequest = this.queuedRequests.pop();
1545
+ if (queuedRequest) {
1546
+ const { clientViewportId, message, requestId } = queuedRequest;
1547
+ if (message.type === "CHANGE_VP_RANGE") {
1548
+ if (messageTypesProcessed.CHANGE_VP_RANGE) {
1549
+ continue;
1550
+ }
1551
+ messageTypesProcessed.CHANGE_VP_RANGE = true;
1552
+ const serverViewportId = this.mapClientToServerViewport.get(clientViewportId);
1553
+ if (serverViewportId) {
1554
+ this.sendMessageToServer(
1555
+ {
1556
+ ...message,
1557
+ viewPortId: serverViewportId
1558
+ },
1559
+ requestId
1560
+ );
1561
+ }
1562
+ }
1563
+ }
1564
+ }
1565
+ }
1566
+ unsubscribe(clientViewportId) {
1567
+ const serverViewportId = this.mapClientToServerViewport.get(clientViewportId);
1568
+ if (serverViewportId) {
1569
+ info2 == null ? void 0 : info2(
1570
+ \`Unsubscribe Message (Client to Server):
1571
+ \${serverViewportId}\`
1572
+ );
1573
+ this.sendMessageToServer({
1574
+ type: REMOVE_VP,
1575
+ viewPortId: serverViewportId
1576
+ });
1577
+ } else {
1578
+ error2(
1579
+ \`failed to unsubscribe client viewport \${clientViewportId}, viewport not found\`
1580
+ );
1581
+ }
1582
+ }
1583
+ getViewportForClient(clientViewportId, throws = true) {
1584
+ const serverViewportId = this.mapClientToServerViewport.get(clientViewportId);
1585
+ if (serverViewportId) {
1586
+ const viewport = this.viewports.get(serverViewportId);
1587
+ if (viewport) {
1588
+ return viewport;
1589
+ } else if (throws) {
1590
+ throw Error(
1591
+ \`Viewport not found for client viewport \${clientViewportId}\`
1592
+ );
1593
+ } else {
1594
+ return null;
1595
+ }
1596
+ } else if (this.viewports.has(clientViewportId)) {
1597
+ return this.viewports.get(clientViewportId);
1598
+ } else if (throws) {
1599
+ throw Error(
1600
+ \`Viewport server id not found for client viewport \${clientViewportId}\`
1601
+ );
1602
+ } else {
1603
+ return null;
1604
+ }
1605
+ }
1606
+ /**********************************************************************/
1607
+ /* Handle messages from client */
1608
+ /**********************************************************************/
1609
+ setViewRange(viewport, message) {
1610
+ const requestId = nextRequestId();
1611
+ const [serverRequest, rows, debounceRequest] = viewport.rangeRequest(
1612
+ requestId,
1613
+ message.range
1614
+ );
1615
+ info2 == null ? void 0 : info2(\`setViewRange \${message.range.from} - \${message.range.to}\`);
1616
+ if (serverRequest) {
1617
+ if (true) {
1618
+ info2 == null ? void 0 : info2(
1619
+ \`CHANGE_VP_RANGE [\${message.range.from}-\${message.range.to}] => [\${serverRequest.from}-\${serverRequest.to}]\`
1620
+ );
1621
+ }
1622
+ const sentToServer = this.sendIfReady(
1623
+ serverRequest,
1624
+ requestId,
1625
+ viewport.status === "subscribed"
1626
+ );
1627
+ if (!sentToServer) {
1628
+ this.queuedRequests.push({
1629
+ clientViewportId: message.viewport,
1630
+ message: serverRequest,
1631
+ requestId
1632
+ });
1633
+ }
1634
+ }
1635
+ if (rows) {
1636
+ info2 == null ? void 0 : info2(\`setViewRange \${rows.length} rows returned from cache\`);
1637
+ this.postMessageToClient({
1638
+ mode: "batch",
1639
+ type: "viewport-update",
1640
+ clientViewportId: viewport.clientViewportId,
1641
+ rows
1642
+ });
1643
+ } else if (debounceRequest) {
1644
+ this.postMessageToClient(debounceRequest);
1645
+ }
1646
+ }
1647
+ setConfig(viewport, message) {
1648
+ const requestId = nextRequestId();
1649
+ const request = viewport.setConfig(requestId, message.config);
1650
+ this.sendIfReady(request, requestId, viewport.status === "subscribed");
1651
+ }
1652
+ aggregate(viewport, message) {
1653
+ const requestId = nextRequestId();
1654
+ const request = viewport.aggregateRequest(requestId, message.aggregations);
1655
+ this.sendIfReady(request, requestId, viewport.status === "subscribed");
1656
+ }
1657
+ sort(viewport, message) {
1658
+ const requestId = nextRequestId();
1659
+ const request = viewport.sortRequest(requestId, message.sort);
1660
+ this.sendIfReady(request, requestId, viewport.status === "subscribed");
1661
+ }
1662
+ groupBy(viewport, message) {
1663
+ const requestId = nextRequestId();
1664
+ const request = viewport.groupByRequest(requestId, message.groupBy);
1665
+ this.sendIfReady(request, requestId, viewport.status === "subscribed");
1666
+ }
1667
+ filter(viewport, message) {
1668
+ const requestId = nextRequestId();
1669
+ const { filter } = message;
1670
+ const request = viewport.filterRequest(requestId, filter);
1671
+ this.sendIfReady(request, requestId, viewport.status === "subscribed");
1672
+ }
1673
+ setColumns(viewport, message) {
1674
+ const requestId = nextRequestId();
1675
+ const { columns } = message;
1676
+ const request = viewport.columnRequest(requestId, columns);
1677
+ this.sendIfReady(request, requestId, viewport.status === "subscribed");
1678
+ }
1679
+ setTitle(viewport, message) {
1680
+ if (viewport) {
1681
+ viewport.title = message.title;
1682
+ this.updateTitleOnVisualLinks(viewport);
1683
+ }
1684
+ }
1685
+ select(viewport, message) {
1686
+ const requestId = nextRequestId();
1687
+ const { selected } = message;
1688
+ const request = viewport.selectRequest(requestId, selected);
1689
+ this.sendIfReady(request, requestId, viewport.status === "subscribed");
1690
+ }
1691
+ disableViewport(viewport) {
1692
+ const requestId = nextRequestId();
1693
+ const request = viewport.disable(requestId);
1694
+ this.sendIfReady(request, requestId, viewport.status === "subscribed");
1695
+ }
1696
+ enableViewport(viewport) {
1697
+ if (viewport.disabled) {
1698
+ const requestId = nextRequestId();
1699
+ const request = viewport.enable(requestId);
1700
+ this.sendIfReady(request, requestId, viewport.status === "subscribed");
1701
+ }
1702
+ }
1703
+ suspendViewport(viewport) {
1704
+ viewport.suspend();
1705
+ viewport.suspendTimer = setTimeout(() => {
1706
+ info2 == null ? void 0 : info2("suspendTimer expired, escalate suspend to disable");
1707
+ this.disableViewport(viewport);
1708
+ }, 3e3);
1709
+ }
1710
+ resumeViewport(viewport) {
1711
+ if (viewport.suspendTimer) {
1712
+ debug3 == null ? void 0 : debug3("clear suspend timer");
1713
+ clearTimeout(viewport.suspendTimer);
1714
+ viewport.suspendTimer = null;
1715
+ }
1716
+ const [size, rows] = viewport.resume();
1717
+ debug3 == null ? void 0 : debug3(\`resumeViewport size \${size}, \${rows.length} rows sent to client\`);
1718
+ this.postMessageToClient({
1719
+ clientViewportId: viewport.clientViewportId,
1720
+ mode: "batch",
1721
+ rows,
1722
+ size,
1723
+ type: "viewport-update"
1724
+ });
1725
+ }
1726
+ openTreeNode(viewport, message) {
1727
+ if (viewport.serverViewportId) {
1728
+ const requestId = nextRequestId();
1729
+ this.sendIfReady(
1730
+ viewport.openTreeNode(requestId, message),
1731
+ requestId,
1732
+ viewport.status === "subscribed"
1733
+ );
1734
+ }
1735
+ }
1736
+ closeTreeNode(viewport, message) {
1737
+ if (viewport.serverViewportId) {
1738
+ const requestId = nextRequestId();
1739
+ this.sendIfReady(
1740
+ viewport.closeTreeNode(requestId, message),
1741
+ requestId,
1742
+ viewport.status === "subscribed"
1743
+ );
1744
+ }
1745
+ }
1746
+ createLink(viewport, message) {
1747
+ const { parentClientVpId, parentColumnName, childColumnName } = message;
1748
+ const requestId = nextRequestId();
1749
+ const parentVpId = this.mapClientToServerViewport.get(parentClientVpId);
1750
+ if (parentVpId) {
1751
+ const request = viewport.createLink(
1752
+ requestId,
1753
+ childColumnName,
1754
+ parentVpId,
1755
+ parentColumnName
1756
+ );
1757
+ this.sendMessageToServer(request, requestId);
1758
+ } else {
1759
+ error2("ServerProxy unable to create link, viewport not found");
1760
+ }
1761
+ }
1762
+ removeLink(viewport) {
1763
+ const requestId = nextRequestId();
1764
+ const request = viewport.removeLink(requestId);
1765
+ this.sendMessageToServer(request, requestId);
1766
+ }
1767
+ updateTitleOnVisualLinks(viewport) {
1768
+ var _a;
1769
+ const { serverViewportId, title } = viewport;
1770
+ for (const vp of this.viewports.values()) {
1771
+ if (vp !== viewport && vp.links && serverViewportId && title) {
1772
+ if ((_a = vp.links) == null ? void 0 : _a.some((link) => link.parentVpId === serverViewportId)) {
1773
+ const [messageToClient] = vp.setLinks(
1774
+ addTitleToLinks(vp.links, serverViewportId, title)
1775
+ );
1776
+ this.postMessageToClient(messageToClient);
1777
+ }
1778
+ }
1779
+ }
1780
+ }
1781
+ removeViewportFromVisualLinks(serverViewportId) {
1782
+ var _a;
1783
+ for (const vp of this.viewports.values()) {
1784
+ if ((_a = vp.links) == null ? void 0 : _a.some(({ parentVpId }) => parentVpId === serverViewportId)) {
1785
+ const [messageToClient] = vp.setLinks(
1786
+ vp.links.filter(({ parentVpId }) => parentVpId !== serverViewportId)
1787
+ );
1788
+ this.postMessageToClient(messageToClient);
1789
+ }
1790
+ }
1791
+ }
1792
+ menuRpcCall(message) {
1793
+ const viewport = this.getViewportForClient(message.vpId, false);
1794
+ if (viewport == null ? void 0 : viewport.serverViewportId) {
1795
+ const [requestId, rpcRequest] = stripRequestId(message);
1796
+ this.sendMessageToServer(
1797
+ {
1798
+ ...rpcRequest,
1799
+ vpId: viewport.serverViewportId
1800
+ },
1801
+ requestId
1802
+ );
1803
+ }
1804
+ }
1805
+ viewportRpcCall(message) {
1806
+ const viewport = this.getViewportForClient(message.vpId, false);
1807
+ if (viewport == null ? void 0 : viewport.serverViewportId) {
1808
+ const [requestId, rpcRequest] = stripRequestId(message);
1809
+ this.sendMessageToServer(
1810
+ {
1811
+ ...rpcRequest,
1812
+ vpId: viewport.serverViewportId,
1813
+ namedParams: {}
1814
+ },
1815
+ requestId
1816
+ );
1817
+ }
1818
+ }
1819
+ rpcCall(message) {
1820
+ const [requestId, rpcRequest] = stripRequestId(message);
1821
+ const module = getRpcServiceModule(rpcRequest.service);
1822
+ this.sendMessageToServer(rpcRequest, requestId, { module });
1823
+ }
1824
+ handleMessageFromClient(message) {
1825
+ var _a;
1826
+ if (isViewporttMessage(message)) {
1827
+ if (message.type === "disable") {
1828
+ const viewport = this.getViewportForClient(message.viewport, false);
1829
+ if (viewport !== null) {
1830
+ return this.disableViewport(viewport);
1831
+ } else {
1832
+ return;
1833
+ }
1834
+ } else {
1835
+ const viewport = this.getViewportForClient(message.viewport);
1836
+ switch (message.type) {
1837
+ case "setViewRange":
1838
+ return this.setViewRange(viewport, message);
1839
+ case "config":
1840
+ return this.setConfig(viewport, message);
1841
+ case "aggregate":
1842
+ return this.aggregate(viewport, message);
1843
+ case "sort":
1844
+ return this.sort(viewport, message);
1845
+ case "groupBy":
1846
+ return this.groupBy(viewport, message);
1847
+ case "filter":
1848
+ return this.filter(viewport, message);
1849
+ case "select":
1850
+ return this.select(viewport, message);
1851
+ case "suspend":
1852
+ return this.suspendViewport(viewport);
1853
+ case "resume":
1854
+ return this.resumeViewport(viewport);
1855
+ case "enable":
1856
+ return this.enableViewport(viewport);
1857
+ case "openTreeNode":
1858
+ return this.openTreeNode(viewport, message);
1859
+ case "closeTreeNode":
1860
+ return this.closeTreeNode(viewport, message);
1861
+ case "createLink":
1862
+ return this.createLink(viewport, message);
1863
+ case "removeLink":
1864
+ return this.removeLink(viewport);
1865
+ case "setColumns":
1866
+ return this.setColumns(viewport, message);
1867
+ case "setTitle":
1868
+ return this.setTitle(viewport, message);
1869
+ default:
1870
+ }
1871
+ }
1872
+ } else if (isVuuRpcRequest(message)) {
1873
+ return this.viewportRpcCall(
1874
+ message
1875
+ );
1876
+ } else if (isVuuMenuRpcRequest(message)) {
1877
+ return this.menuRpcCall(message);
1878
+ } else {
1879
+ const { type, requestId } = message;
1880
+ switch (type) {
1881
+ case "GET_TABLE_LIST": {
1882
+ (_a = this.tableList) != null ? _a : this.tableList = this.awaitResponseToMessage(
1883
+ { type },
1884
+ requestId
1885
+ );
1886
+ this.tableList.then((response) => {
1887
+ this.postMessageToClient({
1888
+ type: "TABLE_LIST_RESP",
1889
+ tables: response.tables,
1890
+ requestId
1891
+ });
1892
+ });
1893
+ return;
1894
+ }
1895
+ case "GET_TABLE_META": {
1896
+ this.getTableMeta(message.table, requestId).then((tableSchema) => {
1897
+ if (tableSchema) {
1898
+ this.postMessageToClient({
1899
+ type: "TABLE_META_RESP",
1900
+ tableSchema,
1901
+ requestId
1902
+ });
1903
+ }
1904
+ });
1905
+ return;
1906
+ }
1907
+ case "RPC_CALL":
1908
+ return this.rpcCall(message);
1909
+ default:
1910
+ }
1911
+ }
1912
+ error2(
1913
+ \`Vuu ServerProxy Unexpected message from client \${JSON.stringify(
1914
+ message
1915
+ )}\`
1916
+ );
1917
+ }
1918
+ getTableMeta(table, requestId = nextRequestId()) {
1919
+ if (isSessionTable(table)) {
1920
+ return Promise.resolve(void 0);
1921
+ }
1922
+ const key = \`\${table.module}:\${table.table}\`;
1923
+ let tableMetaRequest = this.cachedTableMetaRequests.get(key);
1924
+ if (!tableMetaRequest) {
1925
+ tableMetaRequest = this.awaitResponseToMessage(
1926
+ { type: "GET_TABLE_META", table },
1927
+ requestId
1928
+ );
1929
+ this.cachedTableMetaRequests.set(key, tableMetaRequest);
1930
+ }
1931
+ return tableMetaRequest == null ? void 0 : tableMetaRequest.then((response) => this.cacheTableMeta(response));
1932
+ }
1933
+ awaitResponseToMessage(message, requestId = nextRequestId()) {
1934
+ return new Promise((resolve, reject) => {
1935
+ this.sendMessageToServer(message, requestId);
1936
+ this.pendingRequests.set(requestId, { reject, resolve });
1937
+ });
1938
+ }
1939
+ sendIfReady(message, requestId, isReady = true) {
1940
+ if (isReady) {
1941
+ this.sendMessageToServer(message, requestId);
1942
+ }
1943
+ return isReady;
1944
+ }
1945
+ sendMessageToServer(body, requestId = \`\${_requestId++}\`, options = DEFAULT_OPTIONS) {
1946
+ const { module = "CORE" } = options;
1947
+ if (this.authToken) {
1948
+ this.connection.send({
1949
+ requestId,
1950
+ sessionId: this.sessionId,
1951
+ token: this.authToken,
1952
+ user: this.user,
1953
+ module,
1954
+ body
1955
+ });
1956
+ }
1957
+ }
1958
+ handleMessageFromServer(message) {
1959
+ var _a, _b, _c;
1960
+ const { body, requestId, sessionId } = message;
1961
+ const pendingRequest = this.pendingRequests.get(requestId);
1962
+ if (pendingRequest) {
1963
+ const { resolve } = pendingRequest;
1964
+ this.pendingRequests.delete(requestId);
1965
+ resolve(body);
1966
+ return;
1967
+ }
1968
+ const { viewports } = this;
1969
+ switch (body.type) {
1970
+ case HB:
1971
+ this.sendMessageToServer(
1972
+ { type: HB_RESP, ts: +/* @__PURE__ */ new Date() },
1973
+ "NA"
1974
+ );
1975
+ break;
1976
+ case "LOGIN_SUCCESS":
1977
+ if (sessionId) {
1978
+ this.sessionId = sessionId;
1979
+ (_a = this.pendingLogin) == null ? void 0 : _a.resolve(sessionId);
1980
+ this.pendingLogin = void 0;
1981
+ } else {
1982
+ throw Error("LOGIN_SUCCESS did not provide sessionId");
1983
+ }
1984
+ break;
1985
+ case "REMOVE_VP_SUCCESS":
1986
+ {
1987
+ const viewport = viewports.get(body.viewPortId);
1988
+ if (viewport) {
1989
+ this.mapClientToServerViewport.delete(viewport.clientViewportId);
1990
+ viewports.delete(body.viewPortId);
1991
+ this.removeViewportFromVisualLinks(body.viewPortId);
1992
+ }
1993
+ }
1994
+ break;
1995
+ case SET_SELECTION_SUCCESS:
1996
+ {
1997
+ const viewport = this.viewports.get(body.vpId);
1998
+ if (viewport) {
1999
+ viewport.completeOperation(requestId);
2000
+ }
2001
+ }
2002
+ break;
2003
+ case CHANGE_VP_SUCCESS:
2004
+ case DISABLE_VP_SUCCESS:
2005
+ if (viewports.has(body.viewPortId)) {
2006
+ const viewport = this.viewports.get(body.viewPortId);
2007
+ if (viewport) {
2008
+ const response = viewport.completeOperation(requestId);
2009
+ if (response !== void 0) {
2010
+ this.postMessageToClient(response);
2011
+ if (debugEnabled3) {
2012
+ debug3(\`postMessageToClient \${JSON.stringify(response)}\`);
2013
+ }
2014
+ }
2015
+ }
2016
+ }
2017
+ break;
2018
+ case ENABLE_VP_SUCCESS:
2019
+ {
2020
+ const viewport = this.viewports.get(body.viewPortId);
2021
+ if (viewport) {
2022
+ const response = viewport.completeOperation(requestId);
2023
+ if (response) {
2024
+ this.postMessageToClient(response);
2025
+ const [size, rows] = viewport.resume();
2026
+ this.postMessageToClient({
2027
+ clientViewportId: viewport.clientViewportId,
2028
+ mode: "batch",
2029
+ rows,
2030
+ size,
2031
+ type: "viewport-update"
2032
+ });
2033
+ }
2034
+ }
2035
+ }
2036
+ break;
2037
+ case "TABLE_ROW":
2038
+ {
2039
+ const viewportRowMap = groupRowsByViewport(body.rows);
2040
+ if (debugEnabled3) {
2041
+ const [firstRow, secondRow] = body.rows;
2042
+ if (body.rows.length === 0) {
2043
+ debug3("handleMessageFromServer TABLE_ROW 0 rows");
2044
+ } else if ((firstRow == null ? void 0 : firstRow.rowIndex) === -1) {
2045
+ if (body.rows.length === 1) {
2046
+ if (firstRow.updateType === "SIZE") {
2047
+ debug3(
2048
+ \`handleMessageFromServer [\${firstRow.viewPortId}] TABLE_ROW SIZE ONLY \${firstRow.vpSize}\`
2049
+ );
2050
+ } else {
2051
+ debug3(
2052
+ \`handleMessageFromServer [\${firstRow.viewPortId}] TABLE_ROW SIZE \${firstRow.vpSize} rowIdx \${firstRow.rowIndex}\`
2053
+ );
2054
+ }
2055
+ } else {
2056
+ debug3(
2057
+ \`handleMessageFromServer TABLE_ROW \${body.rows.length} rows, SIZE \${firstRow.vpSize}, [\${secondRow == null ? void 0 : secondRow.rowIndex}] - [\${(_b = body.rows[body.rows.length - 1]) == null ? void 0 : _b.rowIndex}]\`
2058
+ );
2059
+ }
2060
+ } else {
2061
+ debug3(
2062
+ \`handleMessageFromServer TABLE_ROW \${body.rows.length} rows [\${firstRow == null ? void 0 : firstRow.rowIndex}] - [\${(_c = body.rows[body.rows.length - 1]) == null ? void 0 : _c.rowIndex}]\`
2063
+ );
2064
+ }
2065
+ }
2066
+ for (const [viewportId, rows] of Object.entries(viewportRowMap)) {
2067
+ const viewport = viewports.get(viewportId);
2068
+ if (viewport) {
2069
+ viewport.updateRows(rows);
2070
+ } else {
2071
+ warn2 == null ? void 0 : warn2(
2072
+ \`TABLE_ROW message received for non registered viewport \${viewportId}\`
2073
+ );
2074
+ }
2075
+ }
2076
+ this.processUpdates();
2077
+ }
2078
+ break;
2079
+ case "CHANGE_VP_RANGE_SUCCESS":
2080
+ {
2081
+ const viewport = this.viewports.get(body.viewPortId);
2082
+ if (viewport) {
2083
+ const { from, to } = body;
2084
+ if (true) {
2085
+ info2 == null ? void 0 : info2(\`CHANGE_VP_RANGE_SUCCESS \${from} - \${to}\`);
2086
+ }
2087
+ viewport.completeOperation(requestId, from, to);
2088
+ }
2089
+ }
2090
+ break;
2091
+ case OPEN_TREE_SUCCESS:
2092
+ case CLOSE_TREE_SUCCESS:
2093
+ break;
2094
+ case "CREATE_VISUAL_LINK_SUCCESS":
2095
+ {
2096
+ const viewport = this.viewports.get(body.childVpId);
2097
+ const parentViewport = this.viewports.get(body.parentVpId);
2098
+ if (viewport && parentViewport) {
2099
+ const { childColumnName, parentColumnName } = body;
2100
+ const response = viewport.completeOperation(
2101
+ requestId,
2102
+ childColumnName,
2103
+ parentViewport.clientViewportId,
2104
+ parentColumnName
2105
+ );
2106
+ if (response) {
2107
+ this.postMessageToClient(response);
2108
+ }
2109
+ }
2110
+ }
2111
+ break;
2112
+ case "REMOVE_VISUAL_LINK_SUCCESS":
2113
+ {
2114
+ const viewport = this.viewports.get(body.childVpId);
2115
+ if (viewport) {
2116
+ const response = viewport.completeOperation(
2117
+ requestId
2118
+ );
2119
+ if (response) {
2120
+ this.postMessageToClient(response);
2121
+ }
2122
+ }
2123
+ }
2124
+ break;
2125
+ case "VP_VISUAL_LINKS_RESP":
2126
+ {
2127
+ const activeLinkDescriptors = this.getActiveLinks(body.links);
2128
+ const viewport = this.viewports.get(body.vpId);
2129
+ if (activeLinkDescriptors.length && viewport) {
2130
+ const linkDescriptorsWithLabels = addLabelsToLinks(
2131
+ activeLinkDescriptors,
2132
+ this.viewports
2133
+ );
2134
+ const [clientMessage, pendingLink] = viewport.setLinks(
2135
+ linkDescriptorsWithLabels
2136
+ );
2137
+ this.postMessageToClient(clientMessage);
2138
+ if (pendingLink) {
2139
+ const { link, parentClientVpId } = pendingLink;
2140
+ const requestId2 = nextRequestId();
2141
+ const serverViewportId = this.mapClientToServerViewport.get(parentClientVpId);
2142
+ if (serverViewportId) {
2143
+ const message2 = viewport.createLink(
2144
+ requestId2,
2145
+ link.fromColumn,
2146
+ serverViewportId,
2147
+ link.toColumn
2148
+ );
2149
+ this.sendMessageToServer(message2, requestId2);
2150
+ }
2151
+ }
2152
+ }
2153
+ }
2154
+ break;
2155
+ case "VIEW_PORT_MENUS_RESP":
2156
+ if (body.menu.name) {
2157
+ const viewport = this.viewports.get(body.vpId);
2158
+ if (viewport) {
2159
+ const clientMessage = viewport.setMenu(body.menu);
2160
+ this.postMessageToClient(clientMessage);
2161
+ }
2162
+ }
2163
+ break;
2164
+ case "VP_EDIT_RPC_RESPONSE":
2165
+ {
2166
+ this.postMessageToClient({
2167
+ action: body.action,
2168
+ requestId,
2169
+ rpcName: body.rpcName,
2170
+ type: "VP_EDIT_RPC_RESPONSE"
2171
+ });
2172
+ }
2173
+ break;
2174
+ case "VP_EDIT_RPC_REJECT":
2175
+ {
2176
+ const viewport = this.viewports.get(body.vpId);
2177
+ if (viewport) {
2178
+ this.postMessageToClient({
2179
+ requestId,
2180
+ type: "VP_EDIT_RPC_REJECT",
2181
+ error: body.error
2182
+ });
2183
+ }
2184
+ }
2185
+ break;
2186
+ case "VIEW_PORT_MENU_REJ": {
2187
+ console.log(\`send menu error back to client\`);
2188
+ const { error: error4, rpcName, vpId } = body;
2189
+ const viewport = this.viewports.get(vpId);
2190
+ if (viewport) {
2191
+ this.postMessageToClient({
2192
+ clientViewportId: viewport.clientViewportId,
2193
+ error: error4,
2194
+ rpcName,
2195
+ type: "VIEW_PORT_MENU_REJ",
2196
+ requestId
2197
+ });
2198
+ }
2199
+ break;
2200
+ }
2201
+ case "VIEW_PORT_MENU_RESP":
2202
+ {
2203
+ if (isSessionTableActionMessage(body)) {
2204
+ const { action, rpcName } = body;
2205
+ this.awaitResponseToMessage({
2206
+ type: "GET_TABLE_META",
2207
+ table: action.table
2208
+ }).then((response) => {
2209
+ const tableSchema = createSchemaFromTableMetadata(
2210
+ response
2211
+ );
2212
+ this.postMessageToClient({
2213
+ rpcName,
2214
+ type: "VIEW_PORT_MENU_RESP",
2215
+ action: {
2216
+ ...action,
2217
+ tableSchema
2218
+ },
2219
+ tableAlreadyOpen: this.isTableOpen(action.table),
2220
+ requestId
2221
+ });
2222
+ });
2223
+ } else {
2224
+ const { action } = body;
2225
+ this.postMessageToClient({
2226
+ type: "VIEW_PORT_MENU_RESP",
2227
+ action: action || NO_ACTION,
2228
+ tableAlreadyOpen: action !== null && this.isTableOpen(action.table),
2229
+ requestId
2230
+ });
2231
+ }
2232
+ }
2233
+ break;
2234
+ case "RPC_RESP":
2235
+ {
2236
+ const { method, result } = body;
2237
+ this.postMessageToClient({
2238
+ type: "RPC_RESP",
2239
+ method,
2240
+ result,
2241
+ requestId
2242
+ });
2243
+ }
2244
+ break;
2245
+ case "VIEW_PORT_RPC_REPONSE":
2246
+ {
2247
+ const { method, action } = body;
2248
+ this.postMessageToClient({
2249
+ type: "VIEW_PORT_RPC_RESPONSE",
2250
+ rpcName: method,
2251
+ action,
2252
+ requestId
2253
+ });
2254
+ }
2255
+ break;
2256
+ case "ERROR":
2257
+ error2(body.msg);
2258
+ break;
2259
+ default:
2260
+ infoEnabled2 && info2(\`handleMessageFromServer \${body["type"]}.\`);
2261
+ }
2262
+ }
2263
+ cacheTableMeta(messageBody) {
2264
+ const { module, table } = messageBody.table;
2265
+ const key = \`\${module}:\${table}\`;
2266
+ let tableSchema = this.cachedTableSchemas.get(key);
2267
+ if (!tableSchema) {
2268
+ tableSchema = createSchemaFromTableMetadata(messageBody);
2269
+ this.cachedTableSchemas.set(key, tableSchema);
2270
+ }
2271
+ return tableSchema;
2272
+ }
2273
+ isTableOpen(table) {
2274
+ if (table) {
2275
+ const tableName = table.table;
2276
+ for (const viewport of this.viewports.values()) {
2277
+ if (!viewport.suspended && viewport.table.table === tableName) {
2278
+ return true;
2279
+ }
2280
+ }
2281
+ }
2282
+ }
2283
+ // Eliminate links to suspended viewports
2284
+ getActiveLinks(linkDescriptors) {
2285
+ return linkDescriptors.filter((linkDescriptor) => {
2286
+ const viewport = this.viewports.get(linkDescriptor.parentVpId);
2287
+ return viewport && !viewport.suspended;
2288
+ });
2289
+ }
2290
+ processUpdates() {
2291
+ this.viewports.forEach((viewport) => {
2292
+ var _a;
2293
+ if (viewport.hasUpdatesToProcess) {
2294
+ const result = viewport.getClientRows();
2295
+ if (result !== NO_DATA_UPDATE) {
2296
+ const [rows, mode] = result;
2297
+ const size = viewport.getNewRowCount();
2298
+ if (size !== void 0 || rows && rows.length > 0) {
2299
+ debugEnabled3 && debug3(
2300
+ \`postMessageToClient #\${viewport.clientViewportId} viewport-update \${mode}, \${(_a = rows == null ? void 0 : rows.length) != null ? _a : "no"} rows, size \${size}\`
2301
+ );
2302
+ if (mode) {
2303
+ this.postMessageToClient({
2304
+ clientViewportId: viewport.clientViewportId,
2305
+ mode,
2306
+ rows,
2307
+ size,
2308
+ type: "viewport-update"
2309
+ });
2310
+ }
2311
+ }
2312
+ }
2313
+ }
2314
+ });
2315
+ }
2316
+ };
2317
+
2318
+ // src/websocket-connection.ts
2319
+ var { debug: debug4, debugEnabled: debugEnabled4, error: error3, info: info3, infoEnabled: infoEnabled3, warn: warn3 } = logger(
2320
+ "websocket-connection"
2321
+ );
2322
+ var WS = "ws";
2323
+ var isWebsocketUrl = (url) => url.startsWith(WS + "://") || url.startsWith(WS + "s://");
2324
+ var connectionAttemptStatus = {};
2325
+ var setWebsocket = Symbol("setWebsocket");
2326
+ var connectionCallback = Symbol("connectionCallback");
2327
+ async function connect(connectionString, protocol, callback, retryLimitDisconnect = 10, retryLimitStartup = 5) {
2328
+ connectionAttemptStatus[connectionString] = {
2329
+ status: "connecting",
2330
+ connect: {
2331
+ allowed: retryLimitStartup,
2332
+ remaining: retryLimitStartup
2333
+ },
2334
+ reconnect: {
2335
+ allowed: retryLimitDisconnect,
2336
+ remaining: retryLimitDisconnect
2337
+ }
2338
+ };
2339
+ return makeConnection(connectionString, protocol, callback);
2340
+ }
2341
+ async function reconnect(connection) {
2342
+ throw Error("connection broken");
2343
+ }
2344
+ async function makeConnection(url, protocol, callback, connection) {
2345
+ const {
2346
+ status: currentStatus,
2347
+ connect: connectStatus,
2348
+ reconnect: reconnectStatus
2349
+ } = connectionAttemptStatus[url];
2350
+ const trackedStatus = currentStatus === "connecting" ? connectStatus : reconnectStatus;
2351
+ try {
2352
+ callback({ type: "connection-status", status: "connecting" });
2353
+ const reconnecting = typeof connection !== "undefined";
2354
+ const ws = await createWebsocket(url, protocol);
2355
+ console.info(
2356
+ "%c\u26A1 %cconnected",
2357
+ "font-size: 24px;color: green;font-weight: bold;",
2358
+ "color:green; font-size: 14px;"
2359
+ );
2360
+ if (connection !== void 0) {
2361
+ connection[setWebsocket](ws);
2362
+ }
2363
+ const websocketConnection = connection != null ? connection : new WebsocketConnection(ws, url, protocol, callback);
2364
+ const status = reconnecting ? "reconnected" : "connection-open-awaiting-session";
2365
+ callback({ type: "connection-status", status });
2366
+ websocketConnection.status = status;
2367
+ trackedStatus.remaining = trackedStatus.allowed;
2368
+ return websocketConnection;
2369
+ } catch (err) {
2370
+ const retry = --trackedStatus.remaining > 0;
2371
+ callback({
2372
+ type: "connection-status",
2373
+ status: "disconnected",
2374
+ reason: "failed to connect",
2375
+ retry
2376
+ });
2377
+ if (retry) {
2378
+ return makeConnectionIn(url, protocol, callback, connection, 2e3);
2379
+ } else {
2380
+ throw Error("Failed to establish connection");
2381
+ }
2382
+ }
2383
+ }
2384
+ var makeConnectionIn = (url, protocol, callback, connection, delay) => new Promise((resolve) => {
2385
+ setTimeout(() => {
2386
+ resolve(makeConnection(url, protocol, callback, connection));
2387
+ }, delay);
2388
+ });
2389
+ var createWebsocket = (connectionString, protocol) => new Promise((resolve, reject) => {
2390
+ const websocketUrl = isWebsocketUrl(connectionString) ? connectionString : \`wss://\${connectionString}\`;
2391
+ if (infoEnabled3 && protocol !== void 0) {
2392
+ info3(\`WebSocket Protocol \${protocol == null ? void 0 : protocol.toString()}\`);
2393
+ }
2394
+ const ws = new WebSocket(websocketUrl, protocol);
2395
+ ws.onopen = () => resolve(ws);
2396
+ ws.onerror = (evt) => reject(evt);
2397
+ });
2398
+ var closeWarn = () => {
2399
+ warn3 == null ? void 0 : warn3(\`Connection cannot be closed, socket not yet opened\`);
2400
+ };
2401
+ var sendWarn = (msg) => {
2402
+ warn3 == null ? void 0 : warn3(\`Message cannot be sent, socket closed \${msg.body.type}\`);
2403
+ };
2404
+ var parseMessage = (message) => {
2405
+ try {
2406
+ return JSON.parse(message);
2407
+ } catch (e) {
2408
+ throw Error(\`Error parsing JSON response from server \${message}\`);
2409
+ }
2410
+ };
2411
+ var WebsocketConnection = class {
2412
+ constructor(ws, url, protocol, callback) {
2413
+ this.close = closeWarn;
2414
+ this.requiresLogin = true;
2415
+ this.send = sendWarn;
2416
+ this.status = "ready";
2417
+ this.messagesCount = 0;
2418
+ this.connectionMetricsInterval = null;
2419
+ this.handleWebsocketMessage = (evt) => {
2420
+ const vuuMessageFromServer = parseMessage(evt.data);
2421
+ this.messagesCount += 1;
2422
+ if (true) {
2423
+ if (debugEnabled4 && vuuMessageFromServer.body.type !== "HB") {
2424
+ debug4 == null ? void 0 : debug4(\`<<< \${vuuMessageFromServer.body.type}\`);
2425
+ }
2426
+ }
2427
+ this[connectionCallback](vuuMessageFromServer);
2428
+ };
2429
+ this.url = url;
2430
+ this.protocol = protocol;
2431
+ this[connectionCallback] = callback;
2432
+ this[setWebsocket](ws);
2433
+ }
2434
+ reconnect() {
2435
+ reconnect(this);
2436
+ }
2437
+ [(connectionCallback, setWebsocket)](ws) {
2438
+ const callback = this[connectionCallback];
2439
+ ws.onmessage = (evt) => {
2440
+ this.status = "connected";
2441
+ ws.onmessage = this.handleWebsocketMessage;
2442
+ this.handleWebsocketMessage(evt);
2443
+ };
2444
+ this.connectionMetricsInterval = setInterval(() => {
2445
+ callback({
2446
+ type: "connection-metrics",
2447
+ messagesLength: this.messagesCount
2448
+ });
2449
+ this.messagesCount = 0;
2450
+ }, 2e3);
2451
+ ws.onerror = () => {
2452
+ error3(\`\u26A1 connection error\`);
2453
+ callback({
2454
+ type: "connection-status",
2455
+ status: "disconnected",
2456
+ reason: "error"
2457
+ });
2458
+ if (this.connectionMetricsInterval) {
2459
+ clearInterval(this.connectionMetricsInterval);
2460
+ this.connectionMetricsInterval = null;
2461
+ }
2462
+ if (this.status === "connection-open-awaiting-session") {
2463
+ error3(
2464
+ \`Websocket connection lost before Vuu session established, check websocket configuration\`
2465
+ );
2466
+ } else if (this.status !== "closed") {
2467
+ reconnect(this);
2468
+ this.send = queue;
2469
+ }
2470
+ };
2471
+ ws.onclose = () => {
2472
+ info3 == null ? void 0 : info3(\`\u26A1 connection close\`);
2473
+ callback({
2474
+ type: "connection-status",
2475
+ status: "disconnected",
2476
+ reason: "close"
2477
+ });
2478
+ if (this.connectionMetricsInterval) {
2479
+ clearInterval(this.connectionMetricsInterval);
2480
+ this.connectionMetricsInterval = null;
2481
+ }
2482
+ if (this.status !== "closed") {
2483
+ reconnect(this);
2484
+ this.send = queue;
2485
+ }
2486
+ };
2487
+ const send = (msg) => {
2488
+ if (true) {
2489
+ if (debugEnabled4 && msg.body.type !== "HB_RESP") {
2490
+ debug4 == null ? void 0 : debug4(\`>>> \${msg.body.type}\`);
2491
+ }
2492
+ }
2493
+ ws.send(JSON.stringify(msg));
2494
+ };
2495
+ const queue = (msg) => {
2496
+ info3 == null ? void 0 : info3(\`TODO queue message until websocket reconnected \${msg.body.type}\`);
2497
+ };
2498
+ this.send = send;
2499
+ this.close = () => {
2500
+ this.status = "closed";
2501
+ ws.close();
2502
+ this.close = closeWarn;
2503
+ this.send = sendWarn;
2504
+ info3 == null ? void 0 : info3("close websocket");
2505
+ };
2506
+ }
2507
+ };
2508
+
2509
+ // src/worker.ts
2510
+ var server;
2511
+ var { info: info4, infoEnabled: infoEnabled4 } = logger("worker");
2512
+ async function connectToServer(url, protocol, token, username, onConnectionStatusChange, retryLimitDisconnect, retryLimitStartup) {
2513
+ const connection = await connect(
2514
+ url,
2515
+ protocol,
2516
+ // if this was called during connect, we would get a ReferenceError, but it will
2517
+ // never be called until subscriptions have been made, so this is safe.
2518
+ //TODO do we need to listen in to the connection messages here so we can lock back in, in the event of a reconnenct ?
2519
+ (msg) => {
2520
+ if (isConnectionQualityMetrics(msg)) {
2521
+ postMessage({ type: "connection-metrics", messages: msg });
2522
+ } else if (isConnectionStatusMessage(msg)) {
2523
+ onConnectionStatusChange(msg);
2524
+ if (msg.status === "reconnected") {
2525
+ server.reconnect();
2526
+ }
2527
+ } else {
2528
+ server.handleMessageFromServer(msg);
2529
+ }
2530
+ },
2531
+ retryLimitDisconnect,
2532
+ retryLimitStartup
2533
+ );
2534
+ server = new ServerProxy(connection, (msg) => sendMessageToClient(msg));
2535
+ if (connection.requiresLogin) {
2536
+ await server.login(token, username);
2537
+ }
2538
+ }
2539
+ function sendMessageToClient(message) {
2540
+ postMessage(message);
2541
+ }
2542
+ var handleMessageFromClient = async ({
2543
+ data: message
2544
+ }) => {
2545
+ switch (message.type) {
2546
+ case "connect":
2547
+ await connectToServer(
2548
+ message.url,
2549
+ message.protocol,
2550
+ message.token,
2551
+ message.username,
2552
+ postMessage,
2553
+ message.retryLimitDisconnect,
2554
+ message.retryLimitStartup
2555
+ );
2556
+ postMessage({ type: "connected" });
2557
+ break;
2558
+ case "subscribe":
2559
+ infoEnabled4 && info4(\`client subscribe: \${JSON.stringify(message)}\`);
2560
+ server.subscribe(message);
2561
+ break;
2562
+ case "unsubscribe":
2563
+ infoEnabled4 && info4(\`client unsubscribe: \${JSON.stringify(message)}\`);
2564
+ server.unsubscribe(message.viewport);
2565
+ break;
2566
+ default:
2567
+ infoEnabled4 && info4(\`client message: \${JSON.stringify(message)}\`);
2568
+ server.handleMessageFromClient(message);
2569
+ }
2570
+ };
2571
+ self.addEventListener("message", handleMessageFromClient);
2572
+ postMessage({ type: "ready" });
2573
+
2574
+ `;
2575
+
2576
+ // src/connection-manager.ts
2577
+ var workerBlob = new Blob([getLoggingConfigForWorker() + workerSourceCode], {
2578
+ type: "text/javascript"
2579
+ });
2580
+ var workerBlobUrl = URL.createObjectURL(workerBlob);
2581
+ var worker;
2582
+ var pendingWorker;
2583
+ var pendingWorkerNoToken = [];
2584
+ var resolveServer;
2585
+ var rejectServer;
2586
+ var serverAPI = new Promise((resolve, reject) => {
2587
+ resolveServer = resolve;
2588
+ rejectServer = reject;
2589
+ });
2590
+ var getServerAPI = () => serverAPI;
2591
+ var viewports = /* @__PURE__ */ new Map();
2592
+ var pendingRequests = /* @__PURE__ */ new Map();
2593
+ var getWorker = async ({
2594
+ handleConnectionStatusChange,
2595
+ protocol,
2596
+ retryLimitDisconnect,
2597
+ retryLimitStartup,
2598
+ token = "",
2599
+ username,
2600
+ url
2601
+ }) => {
2602
+ if (token === "" && pendingWorker === void 0) {
2603
+ return new Promise((resolve) => {
2604
+ pendingWorkerNoToken.push({ resolve });
2605
+ });
2606
+ }
2607
+ return pendingWorker || // we get this far when we receive the first request with auth token
2608
+ (pendingWorker = new Promise((resolve) => {
2609
+ const worker2 = new Worker(workerBlobUrl);
2610
+ const timer = window.setTimeout(() => {
2611
+ console.error("timed out waiting for worker to load");
2612
+ }, 1e3);
2613
+ worker2.onmessage = (msg) => {
2614
+ const { data: message } = msg;
2615
+ if (message.type === "ready") {
2616
+ window.clearTimeout(timer);
2617
+ worker2.postMessage({
2618
+ protocol,
2619
+ retryLimitDisconnect,
2620
+ retryLimitStartup,
2621
+ token,
2622
+ type: "connect",
2623
+ url,
2624
+ username
2625
+ });
2626
+ } else if (message.type === "connected") {
2627
+ worker2.onmessage = handleMessageFromWorker;
2628
+ resolve(worker2);
2629
+ for (const pendingWorkerRequest of pendingWorkerNoToken) {
2630
+ pendingWorkerRequest.resolve(worker2);
2631
+ }
2632
+ pendingWorkerNoToken.length = 0;
2633
+ } else if (isConnectionStatusMessage(message)) {
2634
+ handleConnectionStatusChange({ data: message });
2635
+ } else {
2636
+ console.warn("ConnectionManager: Unexpected message from the worker");
2637
+ }
2638
+ };
2639
+ }));
2640
+ };
2641
+ function handleMessageFromWorker({
2642
+ data: message
2643
+ }) {
2644
+ if (shouldMessageBeRoutedToDataSource(message)) {
2645
+ const viewport = viewports.get(message.clientViewportId);
2646
+ if (viewport) {
2647
+ viewport.postMessageToClientDataSource(message);
2648
+ } else {
2649
+ console.error(
2650
+ `[ConnectionManager] ${message.type} message received, viewport not found`
2651
+ );
2652
+ }
2653
+ } else if (isConnectionStatusMessage(message)) {
2654
+ ConnectionManager.emit("connection-status", message);
2655
+ } else if (isConnectionQualityMetrics(message)) {
2656
+ ConnectionManager.emit("connection-metrics", message);
2657
+ } else {
2658
+ const requestId = message.requestId;
2659
+ if (pendingRequests.has(requestId)) {
2660
+ const { resolve } = pendingRequests.get(requestId);
2661
+ pendingRequests.delete(requestId);
2662
+ const {
2663
+ type: _1,
2664
+ requestId: _2,
2665
+ ...rest
2666
+ } = message;
2667
+ if (messageHasResult(message)) {
2668
+ resolve(message.result);
2669
+ } else if (message.type === "VP_EDIT_RPC_RESPONSE" || message.type === "VP_EDIT_RPC_REJECT") {
2670
+ resolve(message);
2671
+ } else if (isTableSchema(message)) {
2672
+ resolve(message.tableSchema);
2673
+ } else {
2674
+ resolve(rest);
2675
+ }
2676
+ } else {
2677
+ console.warn(
2678
+ "%cConnectionManager Unexpected message from the worker",
2679
+ "color:red;font-weight:bold;"
2680
+ );
2681
+ }
2682
+ }
2683
+ }
2684
+ var asyncRequest = (msg) => {
2685
+ const requestId = uuid();
2686
+ worker.postMessage({
2687
+ requestId,
2688
+ ...msg
2689
+ });
2690
+ return new Promise((resolve, reject) => {
2691
+ pendingRequests.set(requestId, { resolve, reject });
2692
+ });
2693
+ };
2694
+ var connectedServerAPI = {
2695
+ subscribe: (message, callback) => {
2696
+ if (viewports.get(message.viewport)) {
2697
+ throw Error(
2698
+ `ConnectionManager attempting to subscribe with an existing viewport id`
2699
+ );
2700
+ }
2701
+ viewports.set(message.viewport, {
2702
+ status: "subscribing",
2703
+ request: message,
2704
+ postMessageToClientDataSource: callback
2705
+ });
2706
+ worker.postMessage({ type: "subscribe", ...message });
2707
+ },
2708
+ unsubscribe: (viewport) => {
2709
+ worker.postMessage({ type: "unsubscribe", viewport });
2710
+ },
2711
+ send: (message) => {
2712
+ worker.postMessage(message);
2713
+ },
2714
+ destroy: (viewportId) => {
2715
+ if (viewportId && viewports.has(viewportId)) {
2716
+ viewports.delete(viewportId);
2717
+ }
2718
+ },
2719
+ rpcCall: async (message) => asyncRequest(message),
2720
+ getTableList: async () => asyncRequest({ type: "GET_TABLE_LIST" }),
2721
+ getTableSchema: async (table) => asyncRequest({
2722
+ type: GET_TABLE_META,
2723
+ table
2724
+ })
2725
+ };
2726
+ var _ConnectionManager = class extends EventEmitter {
2727
+ // The first request must have the token. We can change this to block others until
2728
+ // the request with token is received.
2729
+ async connect({
2730
+ url,
2731
+ authToken,
2732
+ username,
2733
+ protocol,
2734
+ retryLimitDisconnect,
2735
+ retryLimitStartup
2736
+ }) {
2737
+ worker = await getWorker({
2738
+ protocol,
2739
+ url,
2740
+ token: authToken,
2741
+ username,
2742
+ retryLimitDisconnect,
2743
+ retryLimitStartup,
2744
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2745
+ // @ts-ignore
2746
+ handleConnectionStatusChange: handleMessageFromWorker
2747
+ });
2748
+ return connectedServerAPI;
2749
+ }
2750
+ destroy() {
2751
+ worker.terminate();
2752
+ }
2753
+ };
2754
+ var ConnectionManager = new _ConnectionManager();
2755
+ var connectToServer = async ({
2756
+ url,
2757
+ protocol = void 0,
2758
+ authToken,
2759
+ username,
2760
+ retryLimitDisconnect,
2761
+ retryLimitStartup
2762
+ }) => {
2763
+ try {
2764
+ const serverAPI2 = await ConnectionManager.connect({
2765
+ protocol,
2766
+ url,
2767
+ authToken,
2768
+ username,
2769
+ retryLimitDisconnect,
2770
+ retryLimitStartup
2771
+ });
2772
+ resolveServer(serverAPI2);
2773
+ } catch (err) {
2774
+ console.error("Connection Error", err);
2775
+ rejectServer(err);
2776
+ }
2777
+ };
2778
+ var makeRpcCall = async (rpcRequest) => {
2779
+ try {
2780
+ return (await serverAPI).rpcCall(rpcRequest);
2781
+ } catch (err) {
2782
+ throw Error("Error accessing server api");
2783
+ }
2784
+ };
2785
+
2786
+ // src/constants.ts
2787
+ var _connectionId = 0;
2788
+ var connectionId = {
2789
+ get nextValue() {
2790
+ return _connectionId++;
2791
+ }
2792
+ };
2793
+ var msgType = {
2794
+ connect: "connect",
2795
+ connectionStatus: "connection-status",
2796
+ getFilterData: "GetFilterData",
2797
+ rowData: "rowData",
2798
+ rowSet: "rowset",
2799
+ select: "select",
2800
+ selectAll: "selectAll",
2801
+ selectNone: "selectNone",
2802
+ selected: "selected",
2803
+ snapshot: "snapshot",
2804
+ update: "update",
2805
+ createLink: "createLink",
2806
+ disable: "disable",
2807
+ enable: "enable",
2808
+ suspend: "suspend",
2809
+ resume: "resume",
2810
+ addSubscription: "AddSubscription",
2811
+ closeTreeNode: "closeTreeNode",
2812
+ columnList: "ColumnList",
2813
+ data: "data",
2814
+ openTreeNode: "openTreeNode",
2815
+ aggregate: "aggregate",
2816
+ filter: "filter",
2817
+ filterQuery: "filterQuery",
2818
+ filterData: "filterData",
2819
+ getSearchData: "GetSearchData",
2820
+ groupBy: "groupBy",
2821
+ modifySubscription: "ModifySubscription",
2822
+ searchData: "searchData",
2823
+ setGroupState: "setGroupState",
2824
+ size: "size",
2825
+ sort: "sort",
2826
+ subscribed: "Subscribed",
2827
+ tableList: "TableList",
2828
+ unsubscribe: "TerminateSubscription",
2829
+ viewRangeChanged: "ViewRangeChanged"
2830
+ };
2831
+
2832
+ // src/message-utils.ts
2833
+ var MENU_RPC_TYPES = [
2834
+ "VIEW_PORT_MENUS_SELECT_RPC",
2835
+ "VIEW_PORT_MENU_TABLE_RPC",
2836
+ "VIEW_PORT_MENU_ROW_RPC",
2837
+ "VIEW_PORT_MENU_CELL_RPC",
2838
+ "VP_EDIT_CELL_RPC",
2839
+ "VP_EDIT_ROW_RPC",
2840
+ "VP_EDIT_ADD_ROW_RPC",
2841
+ "VP_EDIT_DELETE_CELL_RPC",
2842
+ "VP_EDIT_DELETE_ROW_RPC",
2843
+ "VP_EDIT_SUBMIT_FORM_RPC"
2844
+ ];
2845
+ var isVuuMenuRpcRequest = (message) => MENU_RPC_TYPES.includes(message["type"]);
2846
+ var isVuuRpcRequest = (message) => message["type"] === "VIEW_PORT_RPC_CALL";
2847
+ var stripRequestId = ({
2848
+ requestId,
2849
+ ...rest
2850
+ }) => [requestId, rest];
2851
+ var getFirstAndLastRows = (rows) => {
2852
+ let firstRow = rows.at(0);
2853
+ if (firstRow.updateType === "SIZE") {
2854
+ if (rows.length === 1) {
2855
+ return rows;
2856
+ } else {
2857
+ firstRow = rows.at(1);
2858
+ }
2859
+ }
2860
+ const lastRow = rows.at(-1);
2861
+ return [firstRow, lastRow];
2862
+ };
2863
+ var groupRowsByViewport = (rows) => {
2864
+ const result = {};
2865
+ for (const row of rows) {
2866
+ const rowsForViewport = result[row.viewPortId] || (result[row.viewPortId] = []);
2867
+ rowsForViewport.push(row);
2868
+ }
2869
+ return result;
2870
+ };
2871
+ var getColumnByName = (schema, name) => {
2872
+ if (name === void 0) {
2873
+ return void 0;
2874
+ } else {
2875
+ const column = schema.columns.find((col) => col.name === name);
2876
+ if (column) {
2877
+ return column;
2878
+ } else {
2879
+ throw Error(
2880
+ `getColumnByName no column '${name}' in schema for ${schema.table.table}`
2881
+ );
2882
+ }
2883
+ }
2884
+ };
2885
+ var createSchemaFromTableMetadata = ({
2886
+ columns,
2887
+ dataTypes,
2888
+ key,
2889
+ table
2890
+ }) => {
2891
+ return {
2892
+ table,
2893
+ columns: columns.map((col, idx) => ({
2894
+ name: col,
2895
+ serverDataType: dataTypes[idx]
2896
+ })),
2897
+ key
2898
+ };
2899
+ };
2900
+
2901
+ // src/vuu-data-source.ts
2902
+ import { parseFilter } from "@vuu-ui/vuu-filter-parser";
2903
+ import {
2904
+ configChanged,
2905
+ debounce,
2906
+ EventEmitter as EventEmitter2,
2907
+ isViewportMenusAction,
2908
+ isVisualLinksAction,
2909
+ itemsOrOrderChanged,
2910
+ logger,
2911
+ metadataKeys,
2912
+ throttle,
2913
+ uuid as uuid2,
2914
+ vanillaConfig,
2915
+ withConfigDefaults
2916
+ } from "@vuu-ui/vuu-utils";
2917
+ var { info } = logger("VuuDataSource");
2918
+ var { KEY } = metadataKeys;
2919
+ var _config, _groupBy, _links, _menu, _optimize, _range, _selectedRowsCount, _size, _status, _title;
2920
+ var VuuDataSource = class extends EventEmitter2 {
2921
+ constructor({
2922
+ bufferSize = 100,
2923
+ aggregations,
2924
+ columns,
2925
+ filter,
2926
+ groupBy,
2927
+ sort,
2928
+ table,
2929
+ title,
2930
+ viewport,
2931
+ visualLink
2932
+ }) {
2933
+ super();
2934
+ this.server = null;
2935
+ __privateAdd(this, _config, vanillaConfig);
2936
+ __privateAdd(this, _groupBy, []);
2937
+ __privateAdd(this, _links, void 0);
2938
+ __privateAdd(this, _menu, void 0);
2939
+ __privateAdd(this, _optimize, "throttle");
2940
+ __privateAdd(this, _range, { from: 0, to: 0 });
2941
+ __privateAdd(this, _selectedRowsCount, 0);
2942
+ __privateAdd(this, _size, 0);
2943
+ __privateAdd(this, _status, "initialising");
2944
+ __privateAdd(this, _title, void 0);
2945
+ this.handleMessageFromServer = (message) => {
2946
+ var _a, _b;
2947
+ if (message.type === "subscribed") {
2948
+ __privateSet(this, _status, "subscribed");
2949
+ if (message.tableSchema) {
2950
+ this.tableSchema = message.tableSchema;
2951
+ }
2952
+ (_a = this.clientCallback) == null ? void 0 : _a.call(this, message);
2953
+ } else if (message.type === "disabled") {
2954
+ __privateSet(this, _status, "disabled");
2955
+ } else if (message.type === "enabled") {
2956
+ __privateSet(this, _status, "enabled");
2957
+ } else if (isDataSourceConfigMessage(message)) {
2958
+ return;
2959
+ } else if (message.type === "debounce-begin") {
2960
+ this.optimize = "debounce";
2961
+ } else {
2962
+ if (message.type === "viewport-update" && message.size !== void 0 && message.size !== __privateGet(this, _size)) {
2963
+ __privateSet(this, _size, message.size);
2964
+ this.emit("resize", message.size);
2965
+ }
2966
+ if (this.configChangePending) {
2967
+ this.setConfigPending();
2968
+ }
2969
+ if (isViewportMenusAction(message)) {
2970
+ __privateSet(this, _menu, message.menu);
2971
+ } else if (isVisualLinksAction(message)) {
2972
+ __privateSet(this, _links, message.links);
2973
+ } else {
2974
+ (_b = this.clientCallback) == null ? void 0 : _b.call(this, message);
2975
+ }
2976
+ if (this.optimize === "debounce") {
2977
+ this.revertDebounce();
2978
+ }
2979
+ }
2980
+ };
2981
+ this.revertDebounce = debounce(() => {
2982
+ this.optimize = "throttle";
2983
+ }, 100);
2984
+ this.rawRangeRequest = (range) => {
2985
+ if (this.viewport && this.server) {
2986
+ this.server.send({
2987
+ viewport: this.viewport,
2988
+ type: "setViewRange",
2989
+ range
2990
+ });
2991
+ }
2992
+ };
2993
+ this.debounceRangeRequest = debounce((range) => {
2994
+ if (this.viewport && this.server) {
2995
+ this.server.send({
2996
+ viewport: this.viewport,
2997
+ type: "setViewRange",
2998
+ range
2999
+ });
3000
+ }
3001
+ }, 50);
3002
+ this.throttleRangeRequest = throttle((range) => {
3003
+ if (this.viewport && this.server) {
3004
+ this.server.send({
3005
+ viewport: this.viewport,
3006
+ type: "setViewRange",
3007
+ range
3008
+ });
3009
+ }
3010
+ }, 80);
3011
+ if (!table)
3012
+ throw Error("RemoteDataSource constructor called without table");
3013
+ this.bufferSize = bufferSize;
3014
+ this.table = table;
3015
+ this.viewport = viewport;
3016
+ __privateSet(this, _config, {
3017
+ ...__privateGet(this, _config),
3018
+ aggregations: aggregations || __privateGet(this, _config).aggregations,
3019
+ columns: columns || __privateGet(this, _config).columns,
3020
+ filter: filter || __privateGet(this, _config).filter,
3021
+ groupBy: groupBy || __privateGet(this, _config).groupBy,
3022
+ sort: sort || __privateGet(this, _config).sort,
3023
+ visualLink: visualLink || __privateGet(this, _config).visualLink
3024
+ });
3025
+ __privateSet(this, _title, title);
3026
+ this.rangeRequest = this.throttleRangeRequest;
3027
+ }
3028
+ async subscribe({
3029
+ viewport = ((_a) => (_a = this.viewport) != null ? _a : this.viewport = uuid2())(),
3030
+ columns,
3031
+ aggregations,
3032
+ range,
3033
+ sort,
3034
+ groupBy,
3035
+ filter
3036
+ }, callback) {
3037
+ var _a2;
3038
+ if (__privateGet(this, _status) === "disabled" || __privateGet(this, _status) === "disabling") {
3039
+ this.enable(callback);
3040
+ return;
3041
+ }
3042
+ this.clientCallback = callback;
3043
+ if (aggregations || columns || filter || groupBy || sort) {
3044
+ __privateSet(this, _config, {
3045
+ ...__privateGet(this, _config),
3046
+ aggregations: aggregations || __privateGet(this, _config).aggregations,
3047
+ columns: columns || __privateGet(this, _config).columns,
3048
+ filter: filter || __privateGet(this, _config).filter,
3049
+ groupBy: groupBy || __privateGet(this, _config).groupBy,
3050
+ sort: sort || __privateGet(this, _config).sort
3051
+ });
3052
+ }
3053
+ if (range) {
3054
+ __privateSet(this, _range, range);
3055
+ }
3056
+ if (__privateGet(this, _status) !== "initialising" && __privateGet(this, _status) !== "unsubscribed") {
3057
+ return;
3058
+ }
3059
+ __privateSet(this, _status, "subscribing");
3060
+ this.viewport = viewport;
3061
+ this.server = await getServerAPI();
3062
+ const { bufferSize } = this;
3063
+ (_a2 = this.server) == null ? void 0 : _a2.subscribe(
3064
+ {
3065
+ ...__privateGet(this, _config),
3066
+ bufferSize,
3067
+ viewport,
3068
+ table: this.table,
3069
+ range: __privateGet(this, _range),
3070
+ title: __privateGet(this, _title)
3071
+ },
3072
+ this.handleMessageFromServer
3073
+ );
3074
+ }
3075
+ unsubscribe() {
3076
+ var _a, _b;
3077
+ console.log(`unsubscribe #${this.viewport}`);
3078
+ info == null ? void 0 : info(`unsubscribe #${this.viewport}`);
3079
+ if (this.viewport) {
3080
+ (_a = this.server) == null ? void 0 : _a.unsubscribe(this.viewport);
3081
+ }
3082
+ (_b = this.server) == null ? void 0 : _b.destroy(this.viewport);
3083
+ this.server = null;
3084
+ this.removeAllListeners();
3085
+ __privateSet(this, _status, "unsubscribed");
3086
+ this.viewport = void 0;
3087
+ this.range = { from: 0, to: 0 };
3088
+ }
3089
+ suspend() {
3090
+ var _a;
3091
+ console.log(`suspend #${this.viewport}, current status ${__privateGet(this, _status)}`);
3092
+ info == null ? void 0 : info(`suspend #${this.viewport}, current status ${__privateGet(this, _status)}`);
3093
+ if (this.viewport) {
3094
+ __privateSet(this, _status, "suspended");
3095
+ (_a = this.server) == null ? void 0 : _a.send({
3096
+ type: "suspend",
3097
+ viewport: this.viewport
3098
+ });
3099
+ }
3100
+ return this;
3101
+ }
3102
+ resume() {
3103
+ var _a;
3104
+ console.log(`resume #${this.viewport}, current status ${__privateGet(this, _status)}`);
3105
+ const isDisabled = __privateGet(this, _status).startsWith("disabl");
3106
+ const isSuspended = __privateGet(this, _status) === "suspended";
3107
+ info == null ? void 0 : info(`resume #${this.viewport}, current status ${__privateGet(this, _status)}`);
3108
+ if (this.viewport) {
3109
+ if (isDisabled) {
3110
+ this.enable();
3111
+ } else if (isSuspended) {
3112
+ (_a = this.server) == null ? void 0 : _a.send({
3113
+ type: "resume",
3114
+ viewport: this.viewport
3115
+ });
3116
+ __privateSet(this, _status, "subscribed");
3117
+ }
3118
+ }
3119
+ return this;
3120
+ }
3121
+ disable() {
3122
+ var _a;
3123
+ info == null ? void 0 : info(`disable #${this.viewport}, current status ${__privateGet(this, _status)}`);
3124
+ if (this.viewport) {
3125
+ __privateSet(this, _status, "disabling");
3126
+ (_a = this.server) == null ? void 0 : _a.send({
3127
+ viewport: this.viewport,
3128
+ type: "disable"
3129
+ });
3130
+ }
3131
+ return this;
3132
+ }
3133
+ enable(callback) {
3134
+ var _a;
3135
+ info == null ? void 0 : info(`enable #${this.viewport}, current status ${__privateGet(this, _status)}`);
3136
+ if (this.viewport && (__privateGet(this, _status) === "disabled" || __privateGet(this, _status) === "disabling")) {
3137
+ __privateSet(this, _status, "enabling");
3138
+ if (callback) {
3139
+ this.clientCallback = callback;
3140
+ }
3141
+ (_a = this.server) == null ? void 0 : _a.send({
3142
+ viewport: this.viewport,
3143
+ type: "enable"
3144
+ });
3145
+ }
3146
+ return this;
3147
+ }
3148
+ select(selected) {
3149
+ var _a;
3150
+ __privateSet(this, _selectedRowsCount, selected.length);
3151
+ if (this.viewport) {
3152
+ (_a = this.server) == null ? void 0 : _a.send({
3153
+ viewport: this.viewport,
3154
+ type: "select",
3155
+ selected
3156
+ });
3157
+ }
3158
+ }
3159
+ openTreeNode(key) {
3160
+ var _a;
3161
+ if (this.viewport) {
3162
+ (_a = this.server) == null ? void 0 : _a.send({
3163
+ viewport: this.viewport,
3164
+ type: "openTreeNode",
3165
+ key
3166
+ });
3167
+ }
3168
+ }
3169
+ closeTreeNode(key) {
3170
+ var _a;
3171
+ if (this.viewport) {
3172
+ (_a = this.server) == null ? void 0 : _a.send({
3173
+ viewport: this.viewport,
3174
+ type: "closeTreeNode",
3175
+ key
3176
+ });
3177
+ }
3178
+ }
3179
+ get links() {
3180
+ return __privateGet(this, _links);
3181
+ }
3182
+ get menu() {
3183
+ return __privateGet(this, _menu);
3184
+ }
3185
+ get status() {
3186
+ return __privateGet(this, _status);
3187
+ }
3188
+ get optimize() {
3189
+ return __privateGet(this, _optimize);
3190
+ }
3191
+ set optimize(optimize) {
3192
+ if (optimize !== __privateGet(this, _optimize)) {
3193
+ __privateSet(this, _optimize, optimize);
3194
+ switch (optimize) {
3195
+ case "none":
3196
+ this.rangeRequest = this.rawRangeRequest;
3197
+ break;
3198
+ case "debounce":
3199
+ this.rangeRequest = this.debounceRangeRequest;
3200
+ break;
3201
+ case "throttle":
3202
+ this.rangeRequest = this.throttleRangeRequest;
3203
+ break;
3204
+ }
3205
+ this.emit("optimize", optimize);
3206
+ }
3207
+ }
3208
+ get selectedRowsCount() {
3209
+ return __privateGet(this, _selectedRowsCount);
3210
+ }
3211
+ get size() {
3212
+ return __privateGet(this, _size);
3213
+ }
3214
+ get range() {
3215
+ return __privateGet(this, _range);
3216
+ }
3217
+ set range(range) {
3218
+ if (range.from !== __privateGet(this, _range).from || range.to !== __privateGet(this, _range).to) {
3219
+ __privateSet(this, _range, range);
3220
+ this.rangeRequest(range);
3221
+ }
3222
+ }
3223
+ get config() {
3224
+ return __privateGet(this, _config);
3225
+ }
3226
+ set config(config) {
3227
+ var _a;
3228
+ if (this.applyConfig(config)) {
3229
+ if (__privateGet(this, _config) && this.viewport && this.server) {
3230
+ if (config) {
3231
+ (_a = this.server) == null ? void 0 : _a.send({
3232
+ viewport: this.viewport,
3233
+ type: "config",
3234
+ config: __privateGet(this, _config)
3235
+ });
3236
+ }
3237
+ }
3238
+ this.emit("config", __privateGet(this, _config));
3239
+ }
3240
+ }
3241
+ applyConfig(config) {
3242
+ var _a;
3243
+ if (configChanged(__privateGet(this, _config), config)) {
3244
+ if (config) {
3245
+ const newConfig = ((_a = config == null ? void 0 : config.filter) == null ? void 0 : _a.filter) && (config == null ? void 0 : config.filter.filterStruct) === void 0 ? {
3246
+ ...config,
3247
+ filter: {
3248
+ filter: config.filter.filter,
3249
+ filterStruct: parseFilter(config.filter.filter)
3250
+ }
3251
+ } : config;
3252
+ __privateSet(this, _config, withConfigDefaults(newConfig));
3253
+ return true;
3254
+ }
3255
+ }
3256
+ }
3257
+ //TODO replace all these individual server calls with calls to setConfig
3258
+ get columns() {
3259
+ return __privateGet(this, _config).columns;
3260
+ }
3261
+ set columns(columns) {
3262
+ __privateSet(this, _config, {
3263
+ ...__privateGet(this, _config),
3264
+ columns
3265
+ });
3266
+ if (this.viewport) {
3267
+ const message = {
3268
+ viewport: this.viewport,
3269
+ type: "setColumns",
3270
+ columns
3271
+ };
3272
+ if (this.server) {
3273
+ this.server.send(message);
3274
+ }
3275
+ }
3276
+ this.emit("config", __privateGet(this, _config));
3277
+ }
3278
+ get aggregations() {
3279
+ return __privateGet(this, _config).aggregations;
3280
+ }
3281
+ set aggregations(aggregations) {
3282
+ var _a;
3283
+ __privateSet(this, _config, {
3284
+ ...__privateGet(this, _config),
3285
+ aggregations
3286
+ });
3287
+ if (this.viewport) {
3288
+ (_a = this.server) == null ? void 0 : _a.send({
3289
+ viewport: this.viewport,
3290
+ type: "aggregate",
3291
+ aggregations
3292
+ });
3293
+ }
3294
+ this.emit("config", __privateGet(this, _config));
3295
+ }
3296
+ get sort() {
3297
+ return __privateGet(this, _config).sort;
3298
+ }
3299
+ set sort(sort) {
3300
+ __privateSet(this, _config, {
3301
+ ...__privateGet(this, _config),
3302
+ sort
3303
+ });
3304
+ if (this.viewport) {
3305
+ const message = {
3306
+ viewport: this.viewport,
3307
+ type: "sort",
3308
+ sort
3309
+ };
3310
+ if (this.server) {
3311
+ this.server.send(message);
3312
+ }
3313
+ }
3314
+ this.emit("config", __privateGet(this, _config));
3315
+ }
3316
+ get filter() {
3317
+ return __privateGet(this, _config).filter;
3318
+ }
3319
+ set filter(filter) {
3320
+ __privateSet(this, _config, {
3321
+ ...__privateGet(this, _config),
3322
+ filter
3323
+ });
3324
+ if (this.viewport) {
3325
+ const message = {
3326
+ viewport: this.viewport,
3327
+ type: "filter",
3328
+ filter
3329
+ };
3330
+ if (this.server) {
3331
+ this.server.send(message);
3332
+ }
3333
+ }
3334
+ this.emit("config", __privateGet(this, _config));
3335
+ }
3336
+ get groupBy() {
3337
+ return __privateGet(this, _config).groupBy;
3338
+ }
3339
+ set groupBy(groupBy) {
3340
+ var _a;
3341
+ if (itemsOrOrderChanged(this.groupBy, groupBy)) {
3342
+ const wasGrouped = __privateGet(this, _groupBy).length > 0;
3343
+ __privateSet(this, _config, {
3344
+ ...__privateGet(this, _config),
3345
+ groupBy
3346
+ });
3347
+ if (this.viewport) {
3348
+ const message = {
3349
+ viewport: this.viewport,
3350
+ type: "groupBy",
3351
+ groupBy: __privateGet(this, _config).groupBy
3352
+ };
3353
+ if (this.server) {
3354
+ this.server.send(message);
3355
+ }
3356
+ }
3357
+ if (!wasGrouped && groupBy.length > 0 && this.viewport) {
3358
+ (_a = this.clientCallback) == null ? void 0 : _a.call(this, {
3359
+ clientViewportId: this.viewport,
3360
+ mode: "batch",
3361
+ type: "viewport-update",
3362
+ size: 0,
3363
+ rows: []
3364
+ });
3365
+ }
3366
+ this.emit("config", __privateGet(this, _config));
3367
+ this.setConfigPending({ groupBy });
3368
+ }
3369
+ }
3370
+ get title() {
3371
+ return __privateGet(this, _title);
3372
+ }
3373
+ set title(title) {
3374
+ var _a;
3375
+ __privateSet(this, _title, title);
3376
+ if (this.viewport && title) {
3377
+ (_a = this.server) == null ? void 0 : _a.send({
3378
+ type: "setTitle",
3379
+ title,
3380
+ viewport: this.viewport
3381
+ });
3382
+ }
3383
+ }
3384
+ get visualLink() {
3385
+ return __privateGet(this, _config).visualLink;
3386
+ }
3387
+ set visualLink(visualLink) {
3388
+ var _a, _b;
3389
+ __privateSet(this, _config, {
3390
+ ...__privateGet(this, _config),
3391
+ visualLink
3392
+ });
3393
+ if (visualLink) {
3394
+ const {
3395
+ parentClientVpId,
3396
+ link: { fromColumn, toColumn }
3397
+ } = visualLink;
3398
+ if (this.viewport) {
3399
+ (_a = this.server) == null ? void 0 : _a.send({
3400
+ viewport: this.viewport,
3401
+ type: "createLink",
3402
+ parentClientVpId,
3403
+ parentColumnName: toColumn,
3404
+ childColumnName: fromColumn
3405
+ });
3406
+ }
3407
+ } else {
3408
+ if (this.viewport) {
3409
+ (_b = this.server) == null ? void 0 : _b.send({
3410
+ type: "removeLink",
3411
+ viewport: this.viewport
3412
+ });
3413
+ }
3414
+ }
3415
+ this.emit("config", __privateGet(this, _config));
3416
+ }
3417
+ setConfigPending(config) {
3418
+ const pendingConfig = this.configChangePending;
3419
+ this.configChangePending = config;
3420
+ if (config !== void 0) {
3421
+ this.emit("config", config, false);
3422
+ } else {
3423
+ this.emit("config", pendingConfig, true);
3424
+ }
3425
+ }
3426
+ async rpcCall(rpcRequest) {
3427
+ var _a;
3428
+ if (this.viewport) {
3429
+ return (_a = this.server) == null ? void 0 : _a.rpcCall({
3430
+ vpId: this.viewport,
3431
+ ...rpcRequest
3432
+ });
3433
+ }
3434
+ }
3435
+ async menuRpcCall(rpcRequest) {
3436
+ var _a;
3437
+ if (this.viewport) {
3438
+ return (_a = this.server) == null ? void 0 : _a.rpcCall({
3439
+ vpId: this.viewport,
3440
+ ...rpcRequest
3441
+ });
3442
+ }
3443
+ }
3444
+ applyEdit(row, columnName, value) {
3445
+ return this.menuRpcCall({
3446
+ rowKey: row[KEY],
3447
+ field: columnName,
3448
+ value,
3449
+ type: "VP_EDIT_CELL_RPC"
3450
+ }).then((response) => {
3451
+ if (response == null ? void 0 : response.error) {
3452
+ return response.error;
3453
+ } else {
3454
+ return true;
3455
+ }
3456
+ });
3457
+ }
3458
+ insertRow(key, data) {
3459
+ return this.menuRpcCall({
3460
+ rowKey: key,
3461
+ data,
3462
+ type: "VP_EDIT_ADD_ROW_RPC"
3463
+ }).then((response) => {
3464
+ if (response == null ? void 0 : response.error) {
3465
+ return response.error;
3466
+ } else {
3467
+ return true;
3468
+ }
3469
+ });
3470
+ }
3471
+ deleteRow(rowKey) {
3472
+ return this.menuRpcCall({
3473
+ rowKey,
3474
+ type: "VP_EDIT_DELETE_ROW_RPC"
3475
+ }).then((response) => {
3476
+ if (response == null ? void 0 : response.error) {
3477
+ return response.error;
3478
+ } else {
3479
+ return true;
3480
+ }
3481
+ });
3482
+ }
3483
+ };
3484
+ _config = new WeakMap();
3485
+ _groupBy = new WeakMap();
3486
+ _links = new WeakMap();
3487
+ _menu = new WeakMap();
3488
+ _optimize = new WeakMap();
3489
+ _range = new WeakMap();
3490
+ _selectedRowsCount = new WeakMap();
3491
+ _size = new WeakMap();
3492
+ _status = new WeakMap();
3493
+ _title = new WeakMap();
3494
+ export {
3495
+ ConnectionManager,
3496
+ VuuDataSource,
3497
+ authenticate,
3498
+ connectToServer,
3499
+ connectionId,
3500
+ createSchemaFromTableMetadata,
3501
+ getColumnByName,
3502
+ getFirstAndLastRows,
3503
+ getServerAPI,
3504
+ groupRowsByViewport,
3505
+ isDataSourceConfigMessage,
3506
+ isSessionTable,
3507
+ isSessionTableActionMessage,
3508
+ isSizeOnly,
3509
+ isVuuMenuRpcRequest,
3510
+ isVuuRpcRequest,
3511
+ makeRpcCall,
3512
+ msgType,
3513
+ shouldMessageBeRoutedToDataSource,
3514
+ stripRequestId,
3515
+ toDataSourceConfig
3516
+ };
3517
+ //# sourceMappingURL=index.js.map