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