@vuu-ui/vuu-data-remote 0.8.94 → 0.8.95
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/ConnectionManager.js +0 -7
- package/cjs/ConnectionManager.js.map +1 -1
- package/cjs/WebSocketConnection.js.map +1 -1
- package/cjs/index.js +2 -0
- package/cjs/index.js.map +1 -1
- package/cjs/inlined-worker.js +15 -6
- package/cjs/inlined-worker.js.map +1 -1
- package/cjs/rest-data/moving-window.js +66 -0
- package/cjs/rest-data/moving-window.js.map +1 -0
- package/cjs/rest-data/rest-data-source.js +195 -0
- package/cjs/rest-data/rest-data-source.js.map +1 -0
- package/cjs/rest-data/rest-utils.js +52 -0
- package/cjs/rest-data/rest-utils.js.map +1 -0
- package/cjs/vuu-data-source.js +11 -1
- package/cjs/vuu-data-source.js.map +1 -1
- package/esm/ConnectionManager.js +0 -7
- package/esm/ConnectionManager.js.map +1 -1
- package/esm/WebSocketConnection.js.map +1 -1
- package/esm/index.js +1 -0
- package/esm/index.js.map +1 -1
- package/esm/inlined-worker.js +15 -6
- package/esm/inlined-worker.js.map +1 -1
- package/esm/rest-data/moving-window.js +64 -0
- package/esm/rest-data/moving-window.js.map +1 -0
- package/esm/rest-data/rest-data-source.js +193 -0
- package/esm/rest-data/rest-data-source.js.map +1 -0
- package/esm/rest-data/rest-utils.js +49 -0
- package/esm/rest-data/rest-utils.js.map +1 -0
- package/esm/vuu-data-source.js +12 -2
- package/esm/vuu-data-source.js.map +1 -1
- package/package.json +7 -7
- package/types/ConnectionManager.d.ts +0 -2
- package/types/WebSocketConnection.d.ts +7 -7
- package/types/index.d.ts +1 -0
- package/types/inlined-worker.d.ts +1 -1
- package/types/rest-data/moving-window.d.ts +14 -0
- package/types/rest-data/rest-data-source.d.ts +48 -0
- package/types/rest-data/rest-utils.d.ts +11 -0
- package/types/server-proxy/viewport.d.ts +1 -5
- package/types/vuu-data-source.d.ts +6 -4
package/cjs/ConnectionManager.js
CHANGED
|
@@ -153,13 +153,6 @@ const _ConnectionManager = class _ConnectionManager extends vuuUtils.EventEmitte
|
|
|
153
153
|
destroy() {
|
|
154
154
|
__privateGet(this, _worker).terminate();
|
|
155
155
|
}
|
|
156
|
-
async makeRpcCall(rpcRequest) {
|
|
157
|
-
try {
|
|
158
|
-
return this.asyncRequest(rpcRequest);
|
|
159
|
-
} catch (err) {
|
|
160
|
-
throw Error("Error accessing server api");
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
156
|
};
|
|
164
157
|
_connectionState = new WeakMap();
|
|
165
158
|
_instance = new WeakMap();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ConnectionManager.js","sources":["../src/ConnectionManager.ts"],"sourcesContent":["import {\n ConnectOptions,\n DataSourceCallbackMessage,\n ServerAPI,\n ServerProxySubscribeMessage,\n TableSchema,\n VuuUIMessageIn,\n} from \"@vuu-ui/vuu-data-types\";\nimport {\n VuuCreateVisualLink,\n VuuRemoveVisualLink,\n VuuRpcMenuRequest,\n VuuRpcServiceRequest,\n VuuRpcViewportRequest,\n VuuTableList,\n VuuTableListRequest,\n VuuTableMetaRequest,\n} from \"@vuu-ui/vuu-protocol-types\";\nimport {\n DeferredPromise,\n EventEmitter,\n isConnectionQualityMetrics,\n isRequestResponse,\n isTableSchemaMessage,\n messageHasResult,\n uuid,\n} from \"@vuu-ui/vuu-utils\";\nimport {\n WebSocketConnectionEvents,\n WebSocketConnectionState,\n isWebSocketConnectionMessage,\n} from \"./WebSocketConnection\";\nimport { DedicatedWorker } from \"./DedicatedWorker\";\nimport { shouldMessageBeRoutedToDataSource } from \"./data-source\";\n\nimport { ConnectionQualityMetrics } from \"@vuu-ui/vuu-data-types\";\n\nexport type PostMessageToClientCallback = (\n msg: DataSourceCallbackMessage,\n) => void;\n\nexport type ConnectionEvents = WebSocketConnectionEvents & {\n \"connection-metrics\": (message: ConnectionQualityMetrics) => void;\n};\n\ntype RegisteredViewport = {\n postMessageToClientDataSource: PostMessageToClientCallback;\n request: ServerProxySubscribeMessage;\n status: \"subscribing\";\n};\n\nclass ConnectionManager extends EventEmitter<ConnectionEvents> {\n #connectionState: WebSocketConnectionState = {\n connectionPhase: \"connecting\",\n connectionStatus: \"closed\",\n retryAttemptsTotal: -1,\n retryAttemptsRemaining: -1,\n secondsToNextRetry: -1,\n };\n static #instance: ConnectionManager;\n #deferredServerAPI = new DeferredPromise<ServerAPI>();\n #pendingRequests = new Map();\n #viewports = new Map<string, RegisteredViewport>();\n // #worker?: Worker;\n #worker: DedicatedWorker;\n\n private constructor() {\n super();\n this.#worker = new DedicatedWorker(this.handleMessageFromWorker);\n }\n\n public static get instance(): ConnectionManager {\n if (!ConnectionManager.#instance) {\n ConnectionManager.#instance = new ConnectionManager();\n }\n return ConnectionManager.#instance;\n }\n\n /**\n * Open a connection to the VuuServer. This method opens the websocket connection\n * and logs in. It can be called from whichever client code has access to the auth\n * token (eg. the login page, or just a hardcoded login script in a sample).\n * This will unblock any DataSources which may have already tried to subscribe to data,\n * but lacked access to the auth token.\n *\n * @param serverUrl\n * @param token\n */\n async connect(options: ConnectOptions) {\n const result = await this.#worker.connect(options);\n if (result === \"connected\") {\n this.#deferredServerAPI.resolve(this.connectedServerAPI);\n }\n return result;\n }\n\n private handleMessageFromWorker = (\n message: VuuUIMessageIn | DataSourceCallbackMessage,\n ) => {\n if (shouldMessageBeRoutedToDataSource(message)) {\n const viewport = this.#viewports.get(message.clientViewportId);\n if (viewport) {\n viewport.postMessageToClientDataSource(message);\n } else {\n console.error(\n `[ConnectionManager] ${message.type} message received, viewport not found`,\n );\n }\n } else if (isWebSocketConnectionMessage(message)) {\n this.#connectionState = message;\n this.emit(\"connection-status\", message);\n } else if (isConnectionQualityMetrics(message)) {\n this.emit(\"connection-metrics\", message);\n } else if (isRequestResponse(message)) {\n const { requestId } = message;\n if (this.#pendingRequests.has(requestId)) {\n const { resolve } = this.#pendingRequests.get(requestId);\n this.#pendingRequests.delete(requestId);\n const { requestId: _, ...messageWithoutRequestId } = message;\n\n if (messageHasResult(message)) {\n resolve(message.result);\n } else if (\n message.type === \"VP_EDIT_RPC_RESPONSE\" ||\n message.type === \"VP_EDIT_RPC_REJECT\"\n ) {\n resolve(message);\n } else if (isTableSchemaMessage(message)) {\n resolve(message.tableSchema);\n } else {\n resolve(messageWithoutRequestId);\n }\n } else {\n console.warn(\n \"%cConnectionManager Unexpected message from the worker\",\n \"color:red;font-weight:bold;\",\n );\n }\n }\n };\n\n get connectionStatus() {\n return this.#connectionState.connectionStatus;\n }\n\n get serverAPI() {\n return this.#deferredServerAPI.promise;\n }\n\n private connectedServerAPI: ServerAPI = {\n subscribe: (message, callback) => {\n if (this.#viewports.get(message.viewport)) {\n throw Error(\n `ConnectionManager attempting to subscribe with an existing viewport id`,\n );\n }\n // TODO we never use this status\n this.#viewports.set(message.viewport, {\n status: \"subscribing\",\n request: message,\n postMessageToClientDataSource: callback,\n });\n this.#worker.send({ type: \"subscribe\", ...message });\n },\n\n unsubscribe: (viewport) => {\n this.#worker.send({ type: \"unsubscribe\", viewport });\n },\n\n send: (message) => {\n this.#worker.send(message);\n },\n\n destroy: (viewportId?: string) => {\n if (viewportId && this.#viewports.has(viewportId)) {\n this.#viewports.delete(viewportId);\n }\n },\n\n rpcCall: async <T = unknown>(\n message:\n | VuuRpcServiceRequest\n | VuuRpcMenuRequest\n | VuuRpcViewportRequest\n | VuuCreateVisualLink\n | VuuRemoveVisualLink,\n ) => this.asyncRequest<T>(message),\n\n getTableList: async () =>\n this.asyncRequest<VuuTableList>({ type: \"GET_TABLE_LIST\" }),\n\n getTableSchema: async (table) =>\n this.asyncRequest<TableSchema>({\n type: \"GET_TABLE_META\",\n table,\n }),\n };\n\n private asyncRequest = <T = unknown>(\n msg:\n | VuuRpcServiceRequest\n | VuuRpcMenuRequest\n | VuuTableListRequest\n | VuuTableMetaRequest\n | VuuRpcViewportRequest\n | VuuCreateVisualLink\n | VuuRemoveVisualLink,\n ): Promise<T> => {\n const requestId = uuid();\n this.#worker.send({\n requestId,\n ...msg,\n });\n return new Promise((resolve, reject) => {\n this.#pendingRequests.set(requestId, { resolve, reject });\n });\n };\n\n async disconnect() {\n try {\n // should we await this ?\n this.#worker.send({ type: \"disconnect\" });\n // how do we disable the serverAPI\n return \"disconnected\";\n } catch (err: unknown) {\n return \"rejected\";\n }\n }\n\n destroy() {\n this.#worker.terminate();\n }\n\n async makeRpcCall<T = unknown>(rpcRequest: VuuRpcServiceRequest) {\n try {\n return this.asyncRequest<T>(rpcRequest);\n } catch (err) {\n throw Error(\"Error accessing server api\");\n }\n }\n}\n\nexport default ConnectionManager.instance;\n"],"names":["EventEmitter","DeferredPromise","shouldMessageBeRoutedToDataSource","isWebSocketConnectionMessage","isConnectionQualityMetrics","isRequestResponse","messageHasResult","isTableSchemaMessage","uuid","DedicatedWorker"],"mappings":";;;;;;;;;;;;;;;;;AAAA,IAAA,gBAAA,EAAA,SAAA,EAAA,kBAAA,EAAA,gBAAA,EAAA,UAAA,EAAA,OAAA,CAAA;AAmDA,MAAM,kBAAA,GAAN,MAAM,kBAAA,SAA0BA,qBAA+B,CAAA;AAAA,EAerD,WAAc,GAAA;AACpB,IAAM,KAAA,EAAA,CAAA;AAfR,IAA6C,YAAA,CAAA,IAAA,EAAA,gBAAA,EAAA;AAAA,MAC3C,eAAiB,EAAA,YAAA;AAAA,MACjB,gBAAkB,EAAA,QAAA;AAAA,MAClB,kBAAoB,EAAA,CAAA,CAAA;AAAA,MACpB,sBAAwB,EAAA,CAAA,CAAA;AAAA,MACxB,kBAAoB,EAAA,CAAA,CAAA;AAAA,KACtB,CAAA,CAAA;AAEA,IAAA,YAAA,CAAA,IAAA,EAAA,kBAAA,EAAqB,IAAIC,wBAA2B,EAAA,CAAA,CAAA;AACpD,IAAA,YAAA,CAAA,IAAA,EAAA,gBAAA,sBAAuB,GAAI,EAAA,CAAA,CAAA;AAC3B,IAAA,YAAA,CAAA,IAAA,EAAA,UAAA,sBAAiB,GAAgC,EAAA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A,CAAA;AAAA,aACA,GAAc,EAAA;AACrB,MAAO,OAAA,UAAA,CAAA;AAAA,KACT;AAAA,GACF;AAAA,EAEA,OAAU,GAAA;AACR,IAAA,YAAA,CAAA,IAAA,EAAK,SAAQ,SAAU,EAAA,CAAA;AAAA,GACzB;AAAA,EAEA,MAAM,YAAyB,UAAkC,EAAA;AAC/D,IAAI,IAAA;AACF,MAAO,OAAA,IAAA,CAAK,aAAgB,UAAU,CAAA,CAAA;AAAA,aAC/B,GAAK,EAAA;AACZ,MAAA,MAAM,MAAM,4BAA4B,CAAA,CAAA;AAAA,KAC1C;AAAA,GACF;AACF,CAAA,CAAA;AA5LE,gBAAA,GAAA,IAAA,OAAA,EAAA,CAAA;AAOO,SAAA,GAAA,IAAA,OAAA,EAAA,CAAA;AACP,kBAAA,GAAA,IAAA,OAAA,EAAA,CAAA;AACA,gBAAA,GAAA,IAAA,OAAA,EAAA,CAAA;AACA,UAAA,GAAA,IAAA,OAAA,EAAA,CAAA;AAEA,OAAA,GAAA,IAAA,OAAA,EAAA,CAAA;AALA,YAAA,CARI,kBAQG,EAAA,SAAA,CAAA,CAAA;AART,IAAM,iBAAN,GAAA,kBAAA,CAAA;AA+LA,0BAAe,iBAAkB,CAAA,QAAA;;;;"}
|
|
1
|
+
{"version":3,"file":"ConnectionManager.js","sources":["../src/ConnectionManager.ts"],"sourcesContent":["import {\n ConnectOptions,\n DataSourceCallbackMessage,\n ServerAPI,\n ServerProxySubscribeMessage,\n TableSchema,\n VuuUIMessageIn,\n} from \"@vuu-ui/vuu-data-types\";\nimport {\n VuuCreateVisualLink,\n VuuRemoveVisualLink,\n VuuRpcMenuRequest,\n VuuRpcServiceRequest,\n VuuRpcViewportRequest,\n VuuTableList,\n VuuTableListRequest,\n VuuTableMetaRequest,\n} from \"@vuu-ui/vuu-protocol-types\";\nimport {\n DeferredPromise,\n EventEmitter,\n isConnectionQualityMetrics,\n isRequestResponse,\n isTableSchemaMessage,\n messageHasResult,\n uuid,\n} from \"@vuu-ui/vuu-utils\";\nimport {\n WebSocketConnectionEvents,\n WebSocketConnectionState,\n isWebSocketConnectionMessage,\n} from \"./WebSocketConnection\";\nimport { DedicatedWorker } from \"./DedicatedWorker\";\nimport { shouldMessageBeRoutedToDataSource } from \"./data-source\";\n\nimport { ConnectionQualityMetrics } from \"@vuu-ui/vuu-data-types\";\n\nexport type PostMessageToClientCallback = (\n msg: DataSourceCallbackMessage,\n) => void;\n\nexport type ConnectionEvents = WebSocketConnectionEvents & {\n \"connection-metrics\": (message: ConnectionQualityMetrics) => void;\n};\n\ntype RegisteredViewport = {\n postMessageToClientDataSource: PostMessageToClientCallback;\n request: ServerProxySubscribeMessage;\n status: \"subscribing\";\n};\n\nclass ConnectionManager extends EventEmitter<ConnectionEvents> {\n #connectionState: WebSocketConnectionState = {\n connectionPhase: \"connecting\",\n connectionStatus: \"closed\",\n retryAttemptsTotal: -1,\n retryAttemptsRemaining: -1,\n secondsToNextRetry: -1,\n };\n static #instance: ConnectionManager;\n #deferredServerAPI = new DeferredPromise<ServerAPI>();\n #pendingRequests = new Map();\n #viewports = new Map<string, RegisteredViewport>();\n // #worker?: Worker;\n #worker: DedicatedWorker;\n\n private constructor() {\n super();\n this.#worker = new DedicatedWorker(this.handleMessageFromWorker);\n }\n\n public static get instance(): ConnectionManager {\n if (!ConnectionManager.#instance) {\n ConnectionManager.#instance = new ConnectionManager();\n }\n return ConnectionManager.#instance;\n }\n\n /**\n * Open a connection to the VuuServer. This method opens the websocket connection\n * and logs in. It can be called from whichever client code has access to the auth\n * token (eg. the login page, or just a hardcoded login script in a sample).\n * This will unblock any DataSources which may have already tried to subscribe to data,\n * but lacked access to the auth token.\n *\n * @param serverUrl\n * @param token\n */\n async connect(options: ConnectOptions) {\n const result = await this.#worker.connect(options);\n if (result === \"connected\") {\n this.#deferredServerAPI.resolve(this.connectedServerAPI);\n }\n return result;\n }\n\n private handleMessageFromWorker = (\n message: VuuUIMessageIn | DataSourceCallbackMessage,\n ) => {\n if (shouldMessageBeRoutedToDataSource(message)) {\n const viewport = this.#viewports.get(message.clientViewportId);\n if (viewport) {\n viewport.postMessageToClientDataSource(message);\n } else {\n console.error(\n `[ConnectionManager] ${message.type} message received, viewport not found`,\n );\n }\n } else if (isWebSocketConnectionMessage(message)) {\n this.#connectionState = message;\n this.emit(\"connection-status\", message);\n } else if (isConnectionQualityMetrics(message)) {\n this.emit(\"connection-metrics\", message);\n } else if (isRequestResponse(message)) {\n const { requestId } = message;\n if (this.#pendingRequests.has(requestId)) {\n const { resolve } = this.#pendingRequests.get(requestId);\n this.#pendingRequests.delete(requestId);\n const { requestId: _, ...messageWithoutRequestId } = message;\n\n if (messageHasResult(message)) {\n resolve(message.result);\n } else if (\n message.type === \"VP_EDIT_RPC_RESPONSE\" ||\n message.type === \"VP_EDIT_RPC_REJECT\"\n ) {\n resolve(message);\n } else if (isTableSchemaMessage(message)) {\n resolve(message.tableSchema);\n } else {\n resolve(messageWithoutRequestId);\n }\n } else {\n console.warn(\n \"%cConnectionManager Unexpected message from the worker\",\n \"color:red;font-weight:bold;\",\n );\n }\n }\n };\n\n get connectionStatus() {\n return this.#connectionState.connectionStatus;\n }\n\n get serverAPI() {\n return this.#deferredServerAPI.promise;\n }\n\n private connectedServerAPI: ServerAPI = {\n subscribe: (message, callback) => {\n if (this.#viewports.get(message.viewport)) {\n throw Error(\n `ConnectionManager attempting to subscribe with an existing viewport id`,\n );\n }\n // TODO we never use this status\n this.#viewports.set(message.viewport, {\n status: \"subscribing\",\n request: message,\n postMessageToClientDataSource: callback,\n });\n this.#worker.send({ type: \"subscribe\", ...message });\n },\n\n unsubscribe: (viewport) => {\n this.#worker.send({ type: \"unsubscribe\", viewport });\n },\n\n send: (message) => {\n this.#worker.send(message);\n },\n\n destroy: (viewportId?: string) => {\n if (viewportId && this.#viewports.has(viewportId)) {\n this.#viewports.delete(viewportId);\n }\n },\n\n rpcCall: async <T = unknown>(\n message:\n | VuuRpcServiceRequest\n | VuuRpcMenuRequest\n | VuuRpcViewportRequest\n | VuuCreateVisualLink\n | VuuRemoveVisualLink,\n ) => this.asyncRequest<T>(message),\n\n getTableList: async () =>\n this.asyncRequest<VuuTableList>({ type: \"GET_TABLE_LIST\" }),\n\n getTableSchema: async (table) =>\n this.asyncRequest<TableSchema>({\n type: \"GET_TABLE_META\",\n table,\n }),\n };\n\n private asyncRequest = <T = unknown>(\n msg:\n | VuuRpcServiceRequest\n | VuuRpcMenuRequest\n | VuuTableListRequest\n | VuuTableMetaRequest\n | VuuRpcViewportRequest\n | VuuCreateVisualLink\n | VuuRemoveVisualLink,\n ): Promise<T> => {\n const requestId = uuid();\n this.#worker.send({\n requestId,\n ...msg,\n });\n return new Promise((resolve, reject) => {\n this.#pendingRequests.set(requestId, { resolve, reject });\n });\n };\n\n async disconnect() {\n try {\n // should we await this ?\n this.#worker.send({ type: \"disconnect\" });\n // how do we disable the serverAPI\n return \"disconnected\";\n } catch (err: unknown) {\n return \"rejected\";\n }\n }\n\n destroy() {\n this.#worker.terminate();\n }\n}\n\nexport default ConnectionManager.instance;\n"],"names":["EventEmitter","DeferredPromise","shouldMessageBeRoutedToDataSource","isWebSocketConnectionMessage","isConnectionQualityMetrics","isRequestResponse","messageHasResult","isTableSchemaMessage","uuid","DedicatedWorker"],"mappings":";;;;;;;;;;;;;;;;;AAAA,IAAA,gBAAA,EAAA,SAAA,EAAA,kBAAA,EAAA,gBAAA,EAAA,UAAA,EAAA,OAAA,CAAA;AAmDA,MAAM,kBAAA,GAAN,MAAM,kBAAA,SAA0BA,qBAA+B,CAAA;AAAA,EAerD,WAAc,GAAA;AACpB,IAAM,KAAA,EAAA,CAAA;AAfR,IAA6C,YAAA,CAAA,IAAA,EAAA,gBAAA,EAAA;AAAA,MAC3C,eAAiB,EAAA,YAAA;AAAA,MACjB,gBAAkB,EAAA,QAAA;AAAA,MAClB,kBAAoB,EAAA,CAAA,CAAA;AAAA,MACpB,sBAAwB,EAAA,CAAA,CAAA;AAAA,MACxB,kBAAoB,EA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A,IAAI,SAAY,GAAA;AACd,IAAA,OAAO,mBAAK,kBAAmB,CAAA,CAAA,OAAA,CAAA;AAAA,GACjC;AAAA,EAuEA,MAAM,UAAa,GAAA;AACjB,IAAI,IAAA;AAEF,MAAA,YAAA,CAAA,IAAA,EAAK,OAAQ,CAAA,CAAA,IAAA,CAAK,EAAE,IAAA,EAAM,cAAc,CAAA,CAAA;AAExC,MAAO,OAAA,cAAA,CAAA;AAAA,aACA,GAAc,EAAA;AACrB,MAAO,OAAA,UAAA,CAAA;AAAA,KACT;AAAA,GACF;AAAA,EAEA,OAAU,GAAA;AACR,IAAA,YAAA,CAAA,IAAA,EAAK,SAAQ,SAAU,EAAA,CAAA;AAAA,GACzB;AACF,CAAA,CAAA;AApLE,gBAAA,GAAA,IAAA,OAAA,EAAA,CAAA;AAOO,SAAA,GAAA,IAAA,OAAA,EAAA,CAAA;AACP,kBAAA,GAAA,IAAA,OAAA,EAAA,CAAA;AACA,gBAAA,GAAA,IAAA,OAAA,EAAA,CAAA;AACA,UAAA,GAAA,IAAA,OAAA,EAAA,CAAA;AAEA,OAAA,GAAA,IAAA,OAAA,EAAA,CAAA;AALA,YAAA,CARI,kBAQG,EAAA,SAAA,CAAA,CAAA;AART,IAAM,iBAAN,GAAA,kBAAA,CAAA;AAuLA,0BAAe,iBAAkB,CAAA,QAAA;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WebSocketConnection.js","sources":["../src/WebSocketConnection.ts"],"sourcesContent":["import { WebSocketProtocol } from \"@vuu-ui/vuu-data-types\";\nimport { VuuClientMessage, VuuServerMessage } from \"@vuu-ui/vuu-protocol-types\";\nimport { DeferredPromise, EventEmitter } from \"@vuu-ui/vuu-utils\";\n\nexport type ConnectingStatus = \"connecting\" | \"reconnecting\";\nexport type RetryStatus = ConnectingStatus | \"disconnected\";\nexport type ConnectedStatus = \"connected\" | \"reconnected\";\nexport type ConnectionStatus =\n | RetryStatus\n | ConnectedStatus\n | \"closed\"\n | \"connection-open-awaiting-session\"\n | \"failed\"\n | \"inactive\";\n\ntype ReconnectAttempts = {\n retryAttemptsTotal: number;\n retryAttemptsRemaining: number;\n secondsToNextRetry: number;\n};\n\nexport interface WebSocketConnectionState extends ReconnectAttempts {\n connectionPhase: ConnectingStatus;\n connectionStatus: ConnectionStatus;\n}\n\nexport const isWebSocketConnectionMessage = (\n msg: object | WebSocketConnectionState,\n): msg is WebSocketConnectionState => {\n if (\"connectionStatus\" in msg) {\n return [\n \"connecting\",\n \"connected\",\n \"connection-open-awaiting-session\",\n \"reconnecting\",\n \"reconnected\",\n \"disconnected\",\n \"closed\",\n \"failed\",\n ].includes(msg.connectionStatus);\n } else {\n return false;\n }\n};\n\nexport type VuuServerMessageCallback = (msg: VuuServerMessage) => void;\n\nexport type RetryLimits = {\n connect: number;\n reconnect: number;\n};\n\nexport type WebSocketConnectionConfig = {\n url: string;\n protocols: WebSocketProtocol;\n callback: VuuServerMessageCallback;\n connectionTimeout?: number;\n retryLimits?: RetryLimits;\n};\n\nconst DEFAULT_RETRY_LIMITS: RetryLimits = {\n connect: 5,\n reconnect: 8,\n};\n\nconst DEFAULT_CONNECTION_TIMEOUT = 10000;\n\nconst ConnectingEndState: Record<ConnectingStatus, ConnectedStatus> = {\n connecting: \"connected\",\n reconnecting: \"reconnected\",\n} as const;\n\nconst parseWebSocketMessage = (message: string): VuuServerMessage => {\n try {\n return JSON.parse(message) as VuuServerMessage;\n } catch (e) {\n throw Error(`Error parsing JSON response from server ${message}`);\n }\n};\n\nexport type WebSocketConnectionCloseReason = \"failure\" | \"shutdown\";\nexport type WebSocketConnectionEvents = {\n closed: (reason: WebSocketConnectionCloseReason) => void;\n connected: () => void;\n \"connection-status\": (message: WebSocketConnectionState) => void;\n reconnected: () => void;\n};\n\nexport class WebSocketConnection extends EventEmitter<WebSocketConnectionEvents> {\n #callback;\n /**\n We are not confirmedOpen until we receive the first message from the\n server. If we get an unexpected close event before that, we consider\n the reconnect attempts as still within the connection phase, not true\n reconnection. This can happen e.g. when connecting to remote host via\n a proxy.\n */\n #confirmedOpen = false;\n #connectionState: WebSocketConnectionState;\n #connectionTimeout;\n #deferredConnection?: DeferredPromise;\n #protocols;\n #reconnectAttempts: ReconnectAttempts;\n #requiresLogin = true;\n #url;\n #ws?: WebSocket;\n\n constructor({\n callback,\n connectionTimeout = DEFAULT_CONNECTION_TIMEOUT,\n protocols,\n retryLimits = DEFAULT_RETRY_LIMITS,\n url,\n }: WebSocketConnectionConfig) {\n super();\n\n this.#callback = callback;\n this.#connectionTimeout = connectionTimeout;\n this.#url = url;\n this.#protocols = protocols;\n\n this.#reconnectAttempts = {\n retryAttemptsTotal: retryLimits.reconnect,\n retryAttemptsRemaining: retryLimits.reconnect,\n secondsToNextRetry: 1,\n };\n\n /**\n * Initial retryAttempts are for the 'connecting' phase. These will\n * be replaced with 'reconnecting' phase retry attempts only once\n * initial connection succeeds.\n */\n this.#connectionState = {\n connectionPhase: \"connecting\",\n connectionStatus: \"closed\",\n retryAttemptsTotal: retryLimits.connect,\n retryAttemptsRemaining: retryLimits.connect,\n secondsToNextRetry: 1,\n };\n }\n\n get connectionTimeout() {\n return this.#connectionTimeout;\n }\n\n get protocols() {\n return this.#protocols;\n }\n\n get requiresLogin() {\n return this.#requiresLogin;\n }\n\n get isClosed() {\n return this.status === \"closed\";\n }\n get isDisconnected() {\n return this.status === \"disconnected\";\n }\n\n get isConnecting() {\n return this.#connectionState.connectionPhase === \"connecting\";\n }\n\n get status() {\n return this.#connectionState.connectionStatus;\n }\n\n private set status(connectionStatus: ConnectionStatus) {\n this.#connectionState = {\n ...this.#connectionState,\n connectionStatus,\n };\n this.emit(\"connection-status\", this.#connectionState);\n }\n\n get connectionState() {\n return this.#connectionState;\n }\n\n private get hasConnectionAttemptsRemaining() {\n return this.#connectionState.retryAttemptsRemaining > 0;\n }\n\n private get confirmedOpen() {\n return this.#confirmedOpen;\n }\n\n /**\n * We are 'confirmedOpen' when we see the first message transmitted\n * from the server. This ensures that even if we have one or more\n * proxies in our route to the endPoint, all connections have been\n * opened successfully.\n * First time in here (on our initial successful connection) we switch\n * from 'connect' phase to 'reconnect' phase. We may have different\n * retry configurations for these two phases.\n */\n private set confirmedOpen(confirmedOpen: boolean) {\n this.#confirmedOpen = confirmedOpen;\n\n if (confirmedOpen && this.isConnecting) {\n this.#connectionState = {\n ...this.#connectionState,\n connectionPhase: \"reconnecting\",\n ...this.#reconnectAttempts,\n };\n } else if (confirmedOpen) {\n // we have successfully reconnected after a failure.\n // Reset the retry attempts, ready for next failure\n // Note: this retry is shared with 'disconnected' status\n this.#connectionState = {\n ...this.#connectionState,\n ...this.#reconnectAttempts,\n };\n }\n }\n\n get url() {\n return this.#url;\n }\n\n async connect(clientCall = true) {\n const state = this.#connectionState;\n if (this.isConnecting && this.#deferredConnection === undefined) {\n // We block on the first connecting call, this will be the\n // initial connect call from app. Any other calls will be\n // reconnect attempts. The initial connecting call returns a promise.\n // This promise is resolved either on that initial call or on a\n // subsequent successful retry attempt within nthat same initial\n // connecting phase.\n this.#deferredConnection = new DeferredPromise();\n }\n const { connectionTimeout, protocols, url } = this;\n this.status = state.connectionPhase;\n const timer = setTimeout(() => {\n throw Error(\n `Failed to open WebSocket connection to ${url}, timed out after ${connectionTimeout}ms`,\n );\n }, connectionTimeout);\n\n const ws = (this.#ws = new WebSocket(url, protocols));\n\n ws.onopen = () => {\n const connectedStatus = ConnectingEndState[state.connectionPhase];\n this.status = connectedStatus;\n clearTimeout(timer);\n if (this.#deferredConnection) {\n this.#deferredConnection.resolve(undefined);\n this.#deferredConnection = undefined;\n }\n if (this.isConnecting) {\n this.emit(\"connected\");\n } else {\n this.emit(\"reconnected\");\n }\n };\n ws.onerror = () => {\n clearTimeout(timer);\n };\n\n ws.onclose = () => {\n if (!this.isClosed) {\n this.confirmedOpen = false;\n this.status = \"disconnected\";\n if (this.hasConnectionAttemptsRemaining) {\n this.reconnect();\n } else {\n this.close(\"failure\");\n }\n }\n };\n\n ws.onmessage = (evt) => {\n if (!this.confirmedOpen) {\n // Now that we are confirmedOpen any subsequent close events\n // will be treated as part of a reconnection phase.\n this.confirmedOpen = true;\n }\n this.receive(evt);\n };\n\n if (clientCall) {\n return this.#deferredConnection?.promise;\n }\n }\n\n private reconnect() {\n const { retryAttemptsRemaining, secondsToNextRetry } =\n this.#connectionState;\n setTimeout(() => {\n this.#connectionState = {\n ...this.#connectionState,\n retryAttemptsRemaining: retryAttemptsRemaining - 1,\n secondsToNextRetry: secondsToNextRetry * 2,\n };\n this.connect(false);\n }, secondsToNextRetry * 1000);\n }\n\n private receive = (evt: MessageEvent) => {\n const vuuMessageFromServer = parseWebSocketMessage(evt.data);\n this.#callback(vuuMessageFromServer);\n };\n\n send = (msg: VuuClientMessage) => {\n this.#ws?.send(JSON.stringify(msg));\n };\n\n close(reason: WebSocketConnectionCloseReason = \"shutdown\") {\n this.status = \"closed\";\n if (reason === \"failure\") {\n if (this.#deferredConnection) {\n this.#deferredConnection.reject(Error(\"connection failed\"));\n this.#deferredConnection = undefined;\n }\n } else {\n this.#ws?.close();\n }\n this.emit(\"closed\", reason);\n this.#ws = undefined;\n }\n}\n"],"names":[],"mappings":";;;;AA0Ba,MAAA,4BAAA,GAA+B,CAC1C,GACoC,KAAA;AACpC,EAAA,IAAI,sBAAsB,GAAK,EAAA;AAC7B,IAAO,OAAA;AAAA,MACL,YAAA;AAAA,MACA,WAAA;AAAA,MACA,kCAAA;AAAA,MACA,cAAA;AAAA,MACA,aAAA;AAAA,MACA,cAAA;AAAA,MACA,QAAA;AAAA,MACA,QAAA;AAAA,KACF,CAAE,QAAS,CAAA,GAAA,CAAI,gBAAgB,CAAA,CAAA;AAAA,GAC1B,MAAA;AACL,IAAO,OAAA,KAAA,CAAA;AAAA,GACT;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"WebSocketConnection.js","sources":["../src/WebSocketConnection.ts"],"sourcesContent":["import { WebSocketProtocol } from \"@vuu-ui/vuu-data-types\";\nimport { VuuClientMessage, VuuServerMessage } from \"@vuu-ui/vuu-protocol-types\";\nimport { DeferredPromise, EventEmitter } from \"@vuu-ui/vuu-utils\";\n\nexport type ConnectingStatus = \"connecting\" | \"reconnecting\";\nexport type ConnectedStatus = \"connected\" | \"reconnected\";\nexport type ConnectionStatus =\n | ConnectedStatus\n | \"closed\"\n | \"connection-open-awaiting-session\"\n | \"disconnected\"\n | \"failed\"\n | \"inactive\";\n\ntype InternalConnectionStatus = ConnectionStatus | ConnectingStatus;\n\ntype ReconnectAttempts = {\n retryAttemptsTotal: number;\n retryAttemptsRemaining: number;\n secondsToNextRetry: number;\n};\n\nexport interface WebSocketConnectionState<\n T extends InternalConnectionStatus = ConnectionStatus,\n> extends ReconnectAttempts {\n connectionPhase: ConnectingStatus;\n connectionStatus: T;\n}\n\nconst isNotConnecting = (\n connectionState: WebSocketConnectionState<InternalConnectionStatus>,\n): connectionState is WebSocketConnectionState<ConnectionStatus> =>\n connectionState.connectionStatus !== \"connecting\" &&\n connectionState.connectionStatus !== \"reconnecting\";\n\nexport const isWebSocketConnectionMessage = (\n msg: object | WebSocketConnectionState,\n): msg is WebSocketConnectionState => {\n if (\"connectionStatus\" in msg) {\n return [\n \"connecting\",\n \"connected\",\n \"connection-open-awaiting-session\",\n \"reconnecting\",\n \"reconnected\",\n \"disconnected\",\n \"closed\",\n \"failed\",\n ].includes(msg.connectionStatus);\n } else {\n return false;\n }\n};\n\nexport type VuuServerMessageCallback = (msg: VuuServerMessage) => void;\n\nexport type RetryLimits = {\n connect: number;\n reconnect: number;\n};\n\nexport type WebSocketConnectionConfig = {\n url: string;\n protocols: WebSocketProtocol;\n callback: VuuServerMessageCallback;\n connectionTimeout?: number;\n retryLimits?: RetryLimits;\n};\n\nconst DEFAULT_RETRY_LIMITS: RetryLimits = {\n connect: 5,\n reconnect: 8,\n};\n\nconst DEFAULT_CONNECTION_TIMEOUT = 10000;\n\nconst ConnectingEndState: Record<ConnectingStatus, ConnectedStatus> = {\n connecting: \"connected\",\n reconnecting: \"reconnected\",\n} as const;\n\nconst parseWebSocketMessage = (message: string): VuuServerMessage => {\n try {\n return JSON.parse(message) as VuuServerMessage;\n } catch (e) {\n throw Error(`Error parsing JSON response from server ${message}`);\n }\n};\n\nexport type WebSocketConnectionCloseReason = \"failure\" | \"shutdown\";\nexport type WebSocketConnectionEvents = {\n closed: (reason: WebSocketConnectionCloseReason) => void;\n connected: () => void;\n \"connection-status\": (message: WebSocketConnectionState) => void;\n reconnected: () => void;\n};\n\nexport class WebSocketConnection extends EventEmitter<WebSocketConnectionEvents> {\n #callback;\n /**\n We are not confirmedOpen until we receive the first message from the\n server. If we get an unexpected close event before that, we consider\n the reconnect attempts as still within the connection phase, not true\n reconnection. This can happen e.g. when connecting to remote host via\n a proxy.\n */\n #confirmedOpen = false;\n #connectionState: WebSocketConnectionState<InternalConnectionStatus>;\n #connectionTimeout;\n #deferredConnection?: DeferredPromise;\n #protocols;\n #reconnectAttempts: ReconnectAttempts;\n #requiresLogin = true;\n #url;\n #ws?: WebSocket;\n\n constructor({\n callback,\n connectionTimeout = DEFAULT_CONNECTION_TIMEOUT,\n protocols,\n retryLimits = DEFAULT_RETRY_LIMITS,\n url,\n }: WebSocketConnectionConfig) {\n super();\n\n this.#callback = callback;\n this.#connectionTimeout = connectionTimeout;\n this.#url = url;\n this.#protocols = protocols;\n\n this.#reconnectAttempts = {\n retryAttemptsTotal: retryLimits.reconnect,\n retryAttemptsRemaining: retryLimits.reconnect,\n secondsToNextRetry: 1,\n };\n\n /**\n * Initial retryAttempts are for the 'connecting' phase. These will\n * be replaced with 'reconnecting' phase retry attempts only once\n * initial connection succeeds.\n */\n this.#connectionState = {\n connectionPhase: \"connecting\",\n connectionStatus: \"closed\",\n retryAttemptsTotal: retryLimits.connect,\n retryAttemptsRemaining: retryLimits.connect,\n secondsToNextRetry: 1,\n };\n }\n\n get connectionTimeout() {\n return this.#connectionTimeout;\n }\n\n get protocols() {\n return this.#protocols;\n }\n\n get requiresLogin() {\n return this.#requiresLogin;\n }\n\n get isClosed() {\n return this.status === \"closed\";\n }\n get isDisconnected() {\n return this.status === \"disconnected\";\n }\n\n get isConnecting() {\n return this.#connectionState.connectionPhase === \"connecting\";\n }\n\n get status() {\n return this.#connectionState.connectionStatus;\n }\n\n private set status(connectionStatus: InternalConnectionStatus) {\n this.#connectionState = {\n ...this.#connectionState,\n connectionStatus,\n };\n // we don't publish the connecting states. They have little meaning for clients\n // and are will generally be very short-lived.\n if (isNotConnecting(this.#connectionState)) {\n this.emit(\"connection-status\", this.#connectionState);\n }\n }\n\n get connectionState() {\n return this.#connectionState;\n }\n\n private get hasConnectionAttemptsRemaining() {\n return this.#connectionState.retryAttemptsRemaining > 0;\n }\n\n private get confirmedOpen() {\n return this.#confirmedOpen;\n }\n\n /**\n * We are 'confirmedOpen' when we see the first message transmitted\n * from the server. This ensures that even if we have one or more\n * proxies in our route to the endPoint, all connections have been\n * opened successfully.\n * First time in here (on our initial successful connection) we switch\n * from 'connect' phase to 'reconnect' phase. We may have different\n * retry configurations for these two phases.\n */\n private set confirmedOpen(confirmedOpen: boolean) {\n this.#confirmedOpen = confirmedOpen;\n\n if (confirmedOpen && this.isConnecting) {\n this.#connectionState = {\n ...this.#connectionState,\n connectionPhase: \"reconnecting\",\n ...this.#reconnectAttempts,\n };\n } else if (confirmedOpen) {\n // we have successfully reconnected after a failure.\n // Reset the retry attempts, ready for next failure\n // Note: this retry is shared with 'disconnected' status\n this.#connectionState = {\n ...this.#connectionState,\n ...this.#reconnectAttempts,\n };\n }\n }\n\n get url() {\n return this.#url;\n }\n\n async connect(clientCall = true) {\n const state = this.#connectionState;\n if (this.isConnecting && this.#deferredConnection === undefined) {\n // We block on the first connecting call, this will be the\n // initial connect call from app. Any other calls will be\n // reconnect attempts. The initial connecting call returns a promise.\n // This promise is resolved either on that initial call or on a\n // subsequent successful retry attempt within nthat same initial\n // connecting phase.\n this.#deferredConnection = new DeferredPromise();\n }\n const { connectionTimeout, protocols, url } = this;\n this.status = state.connectionPhase;\n const timer = setTimeout(() => {\n throw Error(\n `Failed to open WebSocket connection to ${url}, timed out after ${connectionTimeout}ms`,\n );\n }, connectionTimeout);\n\n const ws = (this.#ws = new WebSocket(url, protocols));\n\n ws.onopen = () => {\n const connectedStatus = ConnectingEndState[state.connectionPhase];\n this.status = connectedStatus;\n clearTimeout(timer);\n if (this.#deferredConnection) {\n this.#deferredConnection.resolve(undefined);\n this.#deferredConnection = undefined;\n }\n if (this.isConnecting) {\n this.emit(\"connected\");\n } else {\n this.emit(\"reconnected\");\n }\n console.log(\"connected\");\n };\n ws.onerror = () => {\n clearTimeout(timer);\n };\n\n ws.onclose = () => {\n if (!this.isClosed) {\n this.confirmedOpen = false;\n this.status = \"disconnected\";\n if (this.hasConnectionAttemptsRemaining) {\n this.reconnect();\n } else {\n this.close(\"failure\");\n }\n }\n };\n\n ws.onmessage = (evt) => {\n if (!this.confirmedOpen) {\n // Now that we are confirmedOpen any subsequent close events\n // will be treated as part of a reconnection phase.\n this.confirmedOpen = true;\n }\n this.receive(evt);\n };\n\n if (clientCall) {\n return this.#deferredConnection?.promise;\n }\n }\n\n private reconnect() {\n const { retryAttemptsRemaining, secondsToNextRetry } =\n this.#connectionState;\n setTimeout(() => {\n this.#connectionState = {\n ...this.#connectionState,\n retryAttemptsRemaining: retryAttemptsRemaining - 1,\n secondsToNextRetry: secondsToNextRetry * 2,\n };\n this.connect(false);\n }, secondsToNextRetry * 1000);\n }\n\n private receive = (evt: MessageEvent) => {\n const vuuMessageFromServer = parseWebSocketMessage(evt.data);\n this.#callback(vuuMessageFromServer);\n };\n\n send = (msg: VuuClientMessage) => {\n this.#ws?.send(JSON.stringify(msg));\n };\n\n close(reason: WebSocketConnectionCloseReason = \"shutdown\") {\n this.status = \"closed\";\n if (reason === \"failure\") {\n if (this.#deferredConnection) {\n this.#deferredConnection.reject(Error(\"connection failed\"));\n this.#deferredConnection = undefined;\n }\n } else {\n this.#ws?.close();\n }\n this.emit(\"closed\", reason);\n this.#ws = undefined;\n }\n}\n"],"names":[],"mappings":";;;;AAmCa,MAAA,4BAAA,GAA+B,CAC1C,GACoC,KAAA;AACpC,EAAA,IAAI,sBAAsB,GAAK,EAAA;AAC7B,IAAO,OAAA;AAAA,MACL,YAAA;AAAA,MACA,WAAA;AAAA,MACA,kCAAA;AAAA,MACA,cAAA;AAAA,MACA,aAAA;AAAA,MACA,cAAA;AAAA,MACA,QAAA;AAAA,MACA,QAAA;AAAA,KACF,CAAE,QAAS,CAAA,GAAA,CAAI,gBAAgB,CAAA,CAAA;AAAA,GAC1B,MAAA;AACL,IAAO,OAAA,KAAA,CAAA;AAAA,GACT;AACF;;;;"}
|
package/cjs/index.js
CHANGED
|
@@ -5,6 +5,7 @@ var ConnectionManager = require('./ConnectionManager.js');
|
|
|
5
5
|
var constants = require('./constants.js');
|
|
6
6
|
var dataSource = require('./data-source.js');
|
|
7
7
|
var messageUtils = require('./message-utils.js');
|
|
8
|
+
var restDataSource = require('./rest-data/rest-data-source.js');
|
|
8
9
|
var vuuDataSource = require('./vuu-data-source.js');
|
|
9
10
|
|
|
10
11
|
|
|
@@ -22,5 +23,6 @@ exports.getFirstAndLastRows = messageUtils.getFirstAndLastRows;
|
|
|
22
23
|
exports.groupRowsByViewport = messageUtils.groupRowsByViewport;
|
|
23
24
|
exports.isVuuRpcRequest = messageUtils.isVuuRpcRequest;
|
|
24
25
|
exports.stripRequestId = messageUtils.stripRequestId;
|
|
26
|
+
exports.RestDataSource = restDataSource.RestDataSource;
|
|
25
27
|
exports.VuuDataSource = vuuDataSource.VuuDataSource;
|
|
26
28
|
//# sourceMappingURL=index.js.map
|
package/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/cjs/inlined-worker.js
CHANGED
|
@@ -765,7 +765,7 @@ var NO_UPDATE_STATUS = {
|
|
|
765
765
|
size: 0,
|
|
766
766
|
ts: 0
|
|
767
767
|
};
|
|
768
|
-
var _status;
|
|
768
|
+
var _status, _clientRange;
|
|
769
769
|
var Viewport = class {
|
|
770
770
|
constructor({
|
|
771
771
|
aggregations,
|
|
@@ -788,8 +788,9 @@ var Viewport = class {
|
|
|
788
788
|
/**
|
|
789
789
|
* clientRange is always the range requested by the client. We should assume
|
|
790
790
|
* these are the rows visible to the user
|
|
791
|
+
* TODO what is clientRange needed for ?
|
|
791
792
|
*/
|
|
792
|
-
|
|
793
|
+
__privateAdd(this, _clientRange);
|
|
793
794
|
__publicField(this, "columns");
|
|
794
795
|
__publicField(this, "dataWindow");
|
|
795
796
|
__publicField(this, "filter");
|
|
@@ -895,7 +896,7 @@ var Viewport = class {
|
|
|
895
896
|
});
|
|
896
897
|
this.aggregations = aggregations;
|
|
897
898
|
this.bufferSize = bufferSize;
|
|
898
|
-
this
|
|
899
|
+
__privateSet(this, _clientRange, range);
|
|
899
900
|
this.clientViewportId = viewport;
|
|
900
901
|
this.columns = columns;
|
|
901
902
|
this.filter = filter;
|
|
@@ -909,7 +910,7 @@ var Viewport = class {
|
|
|
909
910
|
\`constructor #\${viewport} \${table.table} bufferSize=\${bufferSize}\`
|
|
910
911
|
));
|
|
911
912
|
this.dataWindow = new ArrayBackedMovingWindow(
|
|
912
|
-
this
|
|
913
|
+
__privateGet(this, _clientRange),
|
|
913
914
|
range,
|
|
914
915
|
this.bufferSize
|
|
915
916
|
);
|
|
@@ -925,6 +926,9 @@ var Viewport = class {
|
|
|
925
926
|
var _a;
|
|
926
927
|
return (_a = this.dataWindow.rowCount) != null ? _a : 0;
|
|
927
928
|
}
|
|
929
|
+
get clientRange() {
|
|
930
|
+
return __privateGet(this, _clientRange);
|
|
931
|
+
}
|
|
928
932
|
get status() {
|
|
929
933
|
return __privateGet(this, _status);
|
|
930
934
|
}
|
|
@@ -937,7 +941,7 @@ var Viewport = class {
|
|
|
937
941
|
return {
|
|
938
942
|
type: CREATE_VP,
|
|
939
943
|
table: this.table,
|
|
940
|
-
range: getFullRange(this
|
|
944
|
+
range: getFullRange(__privateGet(this, _clientRange), this.bufferSize),
|
|
941
945
|
aggregations: this.aggregations,
|
|
942
946
|
columns: this.columns,
|
|
943
947
|
sort: this.sort,
|
|
@@ -1445,6 +1449,7 @@ var Viewport = class {
|
|
|
1445
1449
|
}
|
|
1446
1450
|
};
|
|
1447
1451
|
_status = new WeakMap();
|
|
1452
|
+
_clientRange = new WeakMap();
|
|
1448
1453
|
var toClientRow = ({ rowIndex, rowKey, sel: isSelected, data }, keys, selectedRows) => {
|
|
1449
1454
|
return [
|
|
1450
1455
|
rowIndex,
|
|
@@ -2411,6 +2416,7 @@ var ServerProxy = class {
|
|
|
2411
2416
|
};
|
|
2412
2417
|
|
|
2413
2418
|
// src/WebSocketConnection.ts
|
|
2419
|
+
var isNotConnecting = (connectionState) => connectionState.connectionStatus !== "connecting" && connectionState.connectionStatus !== "reconnecting";
|
|
2414
2420
|
var isWebSocketConnectionMessage = (msg) => {
|
|
2415
2421
|
if ("connectionStatus" in msg) {
|
|
2416
2422
|
return [
|
|
@@ -2521,7 +2527,9 @@ var WebSocketConnection = class extends EventEmitter {
|
|
|
2521
2527
|
...__privateGet(this, _connectionState),
|
|
2522
2528
|
connectionStatus
|
|
2523
2529
|
});
|
|
2524
|
-
|
|
2530
|
+
if (isNotConnecting(__privateGet(this, _connectionState))) {
|
|
2531
|
+
this.emit("connection-status", __privateGet(this, _connectionState));
|
|
2532
|
+
}
|
|
2525
2533
|
}
|
|
2526
2534
|
get connectionState() {
|
|
2527
2535
|
return __privateGet(this, _connectionState);
|
|
@@ -2586,6 +2594,7 @@ var WebSocketConnection = class extends EventEmitter {
|
|
|
2586
2594
|
} else {
|
|
2587
2595
|
this.emit("reconnected");
|
|
2588
2596
|
}
|
|
2597
|
+
console.log("connected");
|
|
2589
2598
|
};
|
|
2590
2599
|
ws2.onerror = () => {
|
|
2591
2600
|
clearTimeout(timer);
|