@vuu-ui/vuu-data-remote 0.0.26

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.
Files changed (55) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +19 -0
  3. package/cjs/authenticate.js +28 -0
  4. package/cjs/authenticate.js.map +1 -0
  5. package/cjs/connection-manager.js +228 -0
  6. package/cjs/connection-manager.js.map +1 -0
  7. package/cjs/constants.js +50 -0
  8. package/cjs/constants.js.map +1 -0
  9. package/cjs/data-source.js +58 -0
  10. package/cjs/data-source.js.map +1 -0
  11. package/cjs/index.js +32 -0
  12. package/cjs/index.js.map +1 -0
  13. package/cjs/inlined-worker.js +14 -0
  14. package/cjs/inlined-worker.js.map +1 -0
  15. package/cjs/message-utils.js +63 -0
  16. package/cjs/message-utils.js.map +1 -0
  17. package/cjs/server-proxy/messages.js +6 -0
  18. package/cjs/server-proxy/messages.js.map +1 -0
  19. package/cjs/vuu-data-source.js +574 -0
  20. package/cjs/vuu-data-source.js.map +1 -0
  21. package/esm/authenticate.js +26 -0
  22. package/esm/authenticate.js.map +1 -0
  23. package/esm/connection-manager.js +223 -0
  24. package/esm/connection-manager.js.map +1 -0
  25. package/esm/constants.js +47 -0
  26. package/esm/constants.js.map +1 -0
  27. package/esm/data-source.js +51 -0
  28. package/esm/data-source.js.map +1 -0
  29. package/esm/index.js +7 -0
  30. package/esm/index.js.map +1 -0
  31. package/esm/inlined-worker.js +12 -0
  32. package/esm/inlined-worker.js.map +1 -0
  33. package/esm/message-utils.js +56 -0
  34. package/esm/message-utils.js.map +1 -0
  35. package/esm/server-proxy/messages.js +4 -0
  36. package/esm/server-proxy/messages.js.map +1 -0
  37. package/esm/vuu-data-source.js +572 -0
  38. package/esm/vuu-data-source.js.map +1 -0
  39. package/package.json +33 -0
  40. package/types/authenticate.d.ts +1 -0
  41. package/types/connection-manager.d.ts +52 -0
  42. package/types/connectionTypes.d.ts +5 -0
  43. package/types/constants.d.ts +41 -0
  44. package/types/data-source.d.ts +8 -0
  45. package/types/index.d.ts +7 -0
  46. package/types/inlined-worker.d.ts +1 -0
  47. package/types/message-utils.d.ts +14 -0
  48. package/types/server-proxy/array-backed-moving-window.d.ts +28 -0
  49. package/types/server-proxy/messages.d.ts +38 -0
  50. package/types/server-proxy/rpc-services.d.ts +2 -0
  51. package/types/server-proxy/server-proxy.d.ts +62 -0
  52. package/types/server-proxy/viewport.d.ts +141 -0
  53. package/types/vuu-data-source.d.ts +63 -0
  54. package/types/websocket-connection.d.ts +24 -0
  55. package/types/worker.d.ts +1 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2015 UBS
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,19 @@
1
+ # vuu-data
2
+
3
+ This package allows a web application to consume data from a [VUU](https://https://vuu.finos.org/docs/introduction/intro/) server instance.
4
+
5
+ ## RPC calls
6
+
7
+ There are two flavours of RPC call, 'direct' RPC calls and 'menu' RPC calls.
8
+
9
+ This package supports both, direct RPC calls are made via the ConnectionManager - the useRpcService hook can be used from a React component. Menu RPC calls always pertain to a specific viewport and are made via the DataSource.
10
+
11
+ Currently there are two direct Rpc requests, both provided by the TYPEAHEAD module , the two methods are:
12
+
13
+ - getUniqueFieldValues
14
+ - getUniqueFieldValuesStartingWith
15
+
16
+ There are two menu Rpc requests, provided by the CORE module. The rpcNames are
17
+
18
+ - ADD_ROWS_TO_ORDERS
19
+ - SET_SPEED_MED | SET_SPEED_SLOW | SET_SPEED_FAST
@@ -0,0 +1,28 @@
1
+ 'use strict';
2
+
3
+ const defaultAuthUrl = "api/authn";
4
+ const authenticate = async (username, password, authUrl = defaultAuthUrl) => fetch(authUrl, {
5
+ method: "POST",
6
+ credentials: "include",
7
+ headers: {
8
+ "Content-Type": "application/json",
9
+ "access-control-allow-origin": location.host
10
+ },
11
+ body: JSON.stringify({ username, password })
12
+ }).then((response) => {
13
+ if (response.ok) {
14
+ const authToken = response.headers.get("vuu-auth-token");
15
+ if (typeof authToken === "string" && authToken.length > 0) {
16
+ return authToken;
17
+ } else {
18
+ throw Error(`Authentication failed auth token not returned by server`);
19
+ }
20
+ } else {
21
+ throw Error(
22
+ `Authentication failed ${response.status} ${response.statusText}`
23
+ );
24
+ }
25
+ });
26
+
27
+ exports.authenticate = authenticate;
28
+ //# sourceMappingURL=authenticate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authenticate.js","sources":["../src/authenticate.ts"],"sourcesContent":["const defaultAuthUrl = \"api/authn\";\n\nexport const authenticate = async (\n username: string,\n password: string,\n authUrl = defaultAuthUrl\n): Promise<string | void> =>\n fetch(authUrl, {\n method: \"POST\",\n credentials: \"include\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"access-control-allow-origin\": location.host,\n },\n body: JSON.stringify({ username, password }),\n }).then((response) => {\n if (response.ok) {\n const authToken = response.headers.get(\"vuu-auth-token\");\n if (typeof authToken === \"string\" && authToken.length > 0) {\n return authToken;\n } else {\n throw Error(`Authentication failed auth token not returned by server`);\n }\n } else {\n throw Error(\n `Authentication failed ${response.status} ${response.statusText}`\n );\n }\n });\n"],"names":[],"mappings":";;AAAA,MAAM,cAAiB,GAAA,WAAA,CAAA;AAEhB,MAAM,eAAe,OAC1B,QAAA,EACA,UACA,OAAU,GAAA,cAAA,KAEV,MAAM,OAAS,EAAA;AAAA,EACb,MAAQ,EAAA,MAAA;AAAA,EACR,WAAa,EAAA,SAAA;AAAA,EACb,OAAS,EAAA;AAAA,IACP,cAAgB,EAAA,kBAAA;AAAA,IAChB,+BAA+B,QAAS,CAAA,IAAA;AAAA,GAC1C;AAAA,EACA,MAAM,IAAK,CAAA,SAAA,CAAU,EAAE,QAAA,EAAU,UAAU,CAAA;AAC7C,CAAC,CAAA,CAAE,IAAK,CAAA,CAAC,QAAa,KAAA;AACpB,EAAA,IAAI,SAAS,EAAI,EAAA;AACf,IAAA,MAAM,SAAY,GAAA,QAAA,CAAS,OAAQ,CAAA,GAAA,CAAI,gBAAgB,CAAA,CAAA;AACvD,IAAA,IAAI,OAAO,SAAA,KAAc,QAAY,IAAA,SAAA,CAAU,SAAS,CAAG,EAAA;AACzD,MAAO,OAAA,SAAA,CAAA;AAAA,KACF,MAAA;AACL,MAAA,MAAM,MAAM,CAAyD,uDAAA,CAAA,CAAA,CAAA;AAAA,KACvE;AAAA,GACK,MAAA;AACL,IAAM,MAAA,KAAA;AAAA,MACJ,CAAyB,sBAAA,EAAA,QAAA,CAAS,MAAM,CAAA,CAAA,EAAI,SAAS,UAAU,CAAA,CAAA;AAAA,KACjE,CAAA;AAAA,GACF;AACF,CAAC;;;;"}
@@ -0,0 +1,228 @@
1
+ 'use strict';
2
+
3
+ var vuuUtils = require('@vuu-ui/vuu-utils');
4
+ var dataSource = require('./data-source.js');
5
+ var messages = require('./server-proxy/messages.js');
6
+ var inlinedWorker = require('./inlined-worker.js');
7
+
8
+ const workerBlob = new Blob([vuuUtils.getLoggingConfigForWorker() + inlinedWorker.workerSourceCode], {
9
+ type: "text/javascript"
10
+ });
11
+ const workerBlobUrl = URL.createObjectURL(workerBlob);
12
+ let worker;
13
+ let pendingWorker;
14
+ const pendingWorkerNoToken = [];
15
+ let resolveServer;
16
+ let rejectServer;
17
+ const serverAPI = new Promise((resolve, reject) => {
18
+ resolveServer = resolve;
19
+ rejectServer = reject;
20
+ });
21
+ const getServerAPI = () => serverAPI;
22
+ const viewports = /* @__PURE__ */ new Map();
23
+ const pendingRequests = /* @__PURE__ */ new Map();
24
+ const getWorker = async ({
25
+ handleConnectionStatusChange,
26
+ protocol,
27
+ retryLimitDisconnect,
28
+ retryLimitStartup,
29
+ token = "",
30
+ username,
31
+ url
32
+ }) => {
33
+ if (token === "" && pendingWorker === void 0) {
34
+ return new Promise((resolve, reject) => {
35
+ pendingWorkerNoToken.push({ resolve, reject });
36
+ });
37
+ }
38
+ return pendingWorker || // we get this far when we receive the first request with auth token
39
+ (pendingWorker = new Promise((resolve, reject) => {
40
+ const worker2 = new Worker(workerBlobUrl);
41
+ const timer = window.setTimeout(() => {
42
+ reject(Error("timed out waiting for worker to load"));
43
+ }, 1e3);
44
+ worker2.onmessage = (msg) => {
45
+ const { data: message } = msg;
46
+ if (message.type === "ready") {
47
+ window.clearTimeout(timer);
48
+ worker2.postMessage({
49
+ protocol,
50
+ retryLimitDisconnect,
51
+ retryLimitStartup,
52
+ token,
53
+ type: "connect",
54
+ url,
55
+ username
56
+ });
57
+ } else if (message.type === "connected") {
58
+ worker2.onmessage = handleMessageFromWorker;
59
+ resolve(worker2);
60
+ for (const pendingWorkerRequest of pendingWorkerNoToken) {
61
+ pendingWorkerRequest.resolve(worker2);
62
+ }
63
+ pendingWorkerNoToken.length = 0;
64
+ } else if (vuuUtils.isConnectionStatusMessage(message)) {
65
+ handleConnectionStatusChange({ data: message });
66
+ } else if (message.type === "connection-failed") {
67
+ reject(message.reason);
68
+ for (const pendingWorkerRequest of pendingWorkerNoToken) {
69
+ pendingWorkerRequest.reject(message.reason);
70
+ }
71
+ pendingWorkerNoToken.length = 0;
72
+ } else {
73
+ console.warn("ConnectionManager: Unexpected message from the worker");
74
+ }
75
+ };
76
+ }));
77
+ };
78
+ function handleMessageFromWorker({
79
+ data: message
80
+ }) {
81
+ if (dataSource.shouldMessageBeRoutedToDataSource(message)) {
82
+ const viewport = viewports.get(message.clientViewportId);
83
+ if (viewport) {
84
+ viewport.postMessageToClientDataSource(message);
85
+ } else {
86
+ console.error(
87
+ `[ConnectionManager] ${message.type} message received, viewport not found`
88
+ );
89
+ }
90
+ } else if (vuuUtils.isConnectionStatusMessage(message)) {
91
+ ConnectionManager.emit("connection-status", message);
92
+ } else if (vuuUtils.isConnectionQualityMetrics(message)) {
93
+ ConnectionManager.emit("connection-metrics", message);
94
+ } else {
95
+ const requestId = message.requestId;
96
+ if (pendingRequests.has(requestId)) {
97
+ const { resolve } = pendingRequests.get(requestId);
98
+ pendingRequests.delete(requestId);
99
+ const {
100
+ type: _1,
101
+ requestId: _2,
102
+ ...rest
103
+ } = message;
104
+ if (vuuUtils.messageHasResult(message)) {
105
+ resolve(message.result);
106
+ } else if (message.type === "VP_EDIT_RPC_RESPONSE" || message.type === "VP_EDIT_RPC_REJECT") {
107
+ resolve(message);
108
+ } else if (vuuUtils.isTableSchema(message)) {
109
+ resolve(message.tableSchema);
110
+ } else {
111
+ resolve(rest);
112
+ }
113
+ } else {
114
+ console.warn(
115
+ "%cConnectionManager Unexpected message from the worker",
116
+ "color:red;font-weight:bold;"
117
+ );
118
+ }
119
+ }
120
+ }
121
+ const asyncRequest = (msg) => {
122
+ const requestId = vuuUtils.uuid();
123
+ worker.postMessage({
124
+ requestId,
125
+ ...msg
126
+ });
127
+ return new Promise((resolve, reject) => {
128
+ pendingRequests.set(requestId, { resolve, reject });
129
+ });
130
+ };
131
+ const connectedServerAPI = {
132
+ subscribe: (message, callback) => {
133
+ if (viewports.get(message.viewport)) {
134
+ throw Error(
135
+ `ConnectionManager attempting to subscribe with an existing viewport id`
136
+ );
137
+ }
138
+ viewports.set(message.viewport, {
139
+ status: "subscribing",
140
+ request: message,
141
+ postMessageToClientDataSource: callback
142
+ });
143
+ worker.postMessage({ type: "subscribe", ...message });
144
+ },
145
+ unsubscribe: (viewport) => {
146
+ worker.postMessage({ type: "unsubscribe", viewport });
147
+ },
148
+ send: (message) => {
149
+ worker.postMessage(message);
150
+ },
151
+ destroy: (viewportId) => {
152
+ if (viewportId && viewports.has(viewportId)) {
153
+ viewports.delete(viewportId);
154
+ }
155
+ },
156
+ rpcCall: async (message) => asyncRequest(message),
157
+ getTableList: async () => asyncRequest({ type: "GET_TABLE_LIST" }),
158
+ getTableSchema: async (table) => asyncRequest({
159
+ type: messages.GET_TABLE_META,
160
+ table
161
+ })
162
+ };
163
+ class _ConnectionManager extends vuuUtils.EventEmitter {
164
+ // The first request must have the token. We can change this to block others until
165
+ // the request with token is received.
166
+ async connect({
167
+ url,
168
+ authToken,
169
+ username,
170
+ protocol,
171
+ retryLimitDisconnect,
172
+ retryLimitStartup
173
+ }) {
174
+ worker = await getWorker({
175
+ protocol,
176
+ url,
177
+ token: authToken,
178
+ username,
179
+ retryLimitDisconnect,
180
+ retryLimitStartup,
181
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
182
+ // @ts-ignore
183
+ handleConnectionStatusChange: handleMessageFromWorker
184
+ });
185
+ return connectedServerAPI;
186
+ }
187
+ destroy() {
188
+ worker.terminate();
189
+ }
190
+ }
191
+ const ConnectionManager = new _ConnectionManager();
192
+ const connectToServer = async ({
193
+ url,
194
+ protocol = void 0,
195
+ authToken,
196
+ username,
197
+ retryLimitDisconnect,
198
+ retryLimitStartup
199
+ }) => {
200
+ try {
201
+ const serverAPI2 = await ConnectionManager.connect({
202
+ protocol,
203
+ url,
204
+ authToken,
205
+ username,
206
+ retryLimitDisconnect,
207
+ retryLimitStartup
208
+ });
209
+ resolveServer(serverAPI2);
210
+ return "connected";
211
+ } catch (err) {
212
+ rejectServer(err);
213
+ return "rejected";
214
+ }
215
+ };
216
+ const makeRpcCall = async (rpcRequest) => {
217
+ try {
218
+ return (await serverAPI).rpcCall(rpcRequest);
219
+ } catch (err) {
220
+ throw Error("Error accessing server api");
221
+ }
222
+ };
223
+
224
+ exports.ConnectionManager = ConnectionManager;
225
+ exports.connectToServer = connectToServer;
226
+ exports.getServerAPI = getServerAPI;
227
+ exports.makeRpcCall = makeRpcCall;
228
+ //# sourceMappingURL=connection-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection-manager.js","sources":["../src/connection-manager.ts"],"sourcesContent":["import {\n ConnectionStatusMessage,\n DataSourceCallbackMessage,\n ServerProxySubscribeMessage,\n TableSchema,\n VuuUIMessageIn,\n VuuUIMessageInRPC,\n VuuUIMessageInTableList,\n VuuUIMessageInTableMeta,\n VuuUIMessageOut,\n WebSocketProtocol,\n} from \"@vuu-ui/vuu-data-types\";\nimport {\n ClientToServerMenuRPC,\n ClientToServerTableList,\n ClientToServerTableMeta,\n ClientToServerViewportRpcCall,\n VuuRpcRequest,\n VuuTable,\n VuuTableList,\n} from \"@vuu-ui/vuu-protocol-types\";\nimport {\n EventEmitter,\n getLoggingConfigForWorker,\n isConnectionQualityMetrics,\n isConnectionStatusMessage,\n isTableSchema,\n messageHasResult,\n uuid,\n} from \"@vuu-ui/vuu-utils\";\nimport { shouldMessageBeRoutedToDataSource as messageShouldBeRoutedToDataSource } from \"./data-source\";\nimport * as Message from \"./server-proxy/messages\";\n\n// Note: inlined-worker is a generated file, it must be built\nimport { ConnectionQualityMetrics } from \"@vuu-ui/vuu-data-types\";\nimport { workerSourceCode } from \"./inlined-worker\";\n\nconst workerBlob = new Blob([getLoggingConfigForWorker() + workerSourceCode], {\n type: \"text/javascript\",\n});\nconst workerBlobUrl = URL.createObjectURL(workerBlob);\n\ntype WorkerResolver = {\n reject: (message: string | PromiseLike<string>) => void;\n resolve: (value: Worker | PromiseLike<Worker>) => void;\n};\n\nlet worker: Worker;\nlet pendingWorker: Promise<Worker>;\nconst pendingWorkerNoToken: WorkerResolver[] = [];\n\nlet resolveServer: (server: ServerAPI) => void;\nlet rejectServer: (err: unknown) => void;\n\nconst serverAPI = new Promise<ServerAPI>((resolve, reject) => {\n resolveServer = resolve;\n rejectServer = reject;\n});\n\n/**\n * returns a promise for serverApi. This will be resolved when the\n * connectToServer call succeeds. If client never calls connectToServer\n * serverAPI will never be resolved.\n */\nexport const getServerAPI = () => serverAPI;\n\nexport type PostMessageToClientCallback = (\n msg: DataSourceCallbackMessage\n) => void;\n\nconst viewports = new Map<\n string,\n {\n postMessageToClientDataSource: PostMessageToClientCallback;\n request: ServerProxySubscribeMessage;\n status: \"subscribing\";\n }\n>();\nconst pendingRequests = new Map();\n\ntype WorkerOptions = {\n protocol: WebSocketProtocol;\n retryLimitDisconnect?: number;\n retryLimitStartup?: number;\n url: string;\n token?: string;\n username: string | undefined;\n handleConnectionStatusChange: (msg: {\n data: ConnectionStatusMessage;\n }) => void;\n};\n\n// We do not resolve the worker until we have a connection, but we will get\n// connection status messages before that, so we forward them to caller\n// while they wait for worker.\nconst getWorker = async ({\n handleConnectionStatusChange,\n protocol,\n retryLimitDisconnect,\n retryLimitStartup,\n token = \"\",\n username,\n url,\n}: WorkerOptions) => {\n if (token === \"\" && pendingWorker === undefined) {\n return new Promise<Worker>((resolve, reject) => {\n pendingWorkerNoToken.push({ resolve, reject });\n });\n }\n //FIXME If we have a pending request already and a new request arrives with a DIFFERENT\n // token, this would cause us to ignore the new request and ultimately resolve it with\n // the original request.\n return (\n pendingWorker ||\n // we get this far when we receive the first request with auth token\n (pendingWorker = new Promise((resolve, reject) => {\n const worker = new Worker(workerBlobUrl);\n\n const timer: number | null = window.setTimeout(() => {\n reject(Error(\"timed out waiting for worker to load\"));\n }, 1000);\n\n // This is the inial message handler only, it processes messages whilst we are\n // establishing a connection. When we resolve the worker, a runtime message\n // handler will replace this (see below)\n worker.onmessage = (msg: MessageEvent<VuuUIMessageIn>) => {\n const { data: message } = msg;\n if (message.type === \"ready\") {\n window.clearTimeout(timer);\n worker.postMessage({\n protocol,\n retryLimitDisconnect,\n retryLimitStartup,\n token,\n type: \"connect\",\n url,\n username,\n });\n } else if (message.type === \"connected\") {\n worker.onmessage = handleMessageFromWorker;\n resolve(worker);\n for (const pendingWorkerRequest of pendingWorkerNoToken) {\n pendingWorkerRequest.resolve(worker);\n }\n pendingWorkerNoToken.length = 0;\n } else if (isConnectionStatusMessage(message)) {\n handleConnectionStatusChange({ data: message });\n } else if (message.type === \"connection-failed\") {\n reject(message.reason);\n for (const pendingWorkerRequest of pendingWorkerNoToken) {\n pendingWorkerRequest.reject(message.reason);\n }\n pendingWorkerNoToken.length = 0;\n } else {\n console.warn(\"ConnectionManager: Unexpected message from the worker\");\n }\n };\n // TODO handle error\n }))\n );\n};\n\nfunction handleMessageFromWorker({\n data: message,\n}: MessageEvent<VuuUIMessageIn | DataSourceCallbackMessage>) {\n if (messageShouldBeRoutedToDataSource(message)) {\n const viewport = 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 (isConnectionStatusMessage(message)) {\n ConnectionManager.emit(\"connection-status\", message);\n } else if (isConnectionQualityMetrics(message)) {\n ConnectionManager.emit(\"connection-metrics\", message);\n } else {\n const requestId = (message as VuuUIMessageInRPC).requestId;\n if (pendingRequests.has(requestId)) {\n const { resolve } = pendingRequests.get(requestId);\n pendingRequests.delete(requestId);\n const {\n type: _1,\n requestId: _2,\n ...rest\n } = message as\n | VuuUIMessageInRPC\n | VuuUIMessageInTableList\n | VuuUIMessageInTableMeta;\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 (isTableSchema(message)) {\n resolve(message.tableSchema);\n } else {\n resolve(rest);\n }\n } else {\n console.warn(\n \"%cConnectionManager Unexpected message from the worker\",\n \"color:red;font-weight:bold;\"\n );\n }\n }\n}\n\nconst asyncRequest = <T = unknown>(\n msg:\n | VuuRpcRequest\n | ClientToServerMenuRPC\n | ClientToServerTableList\n | ClientToServerTableMeta\n | ClientToServerViewportRpcCall\n): Promise<T> => {\n const requestId = uuid();\n worker.postMessage({\n requestId,\n ...msg,\n });\n return new Promise((resolve, reject) => {\n pendingRequests.set(requestId, { resolve, reject });\n });\n};\n\nexport interface ServerAPI {\n destroy: (viewportId?: string) => void;\n getTableSchema: (table: VuuTable) => Promise<TableSchema>;\n getTableList: () => Promise<VuuTableList>;\n rpcCall: <T = unknown>(\n msg: VuuRpcRequest | ClientToServerMenuRPC | ClientToServerViewportRpcCall\n ) => Promise<T>;\n send: (message: VuuUIMessageOut) => void;\n subscribe: (\n message: ServerProxySubscribeMessage,\n callback: PostMessageToClientCallback\n ) => void;\n unsubscribe: (viewport: string) => void;\n}\n\nconst connectedServerAPI: ServerAPI = {\n subscribe: (message, callback) => {\n if (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 viewports.set(message.viewport, {\n status: \"subscribing\",\n request: message,\n postMessageToClientDataSource: callback,\n });\n worker.postMessage({ type: \"subscribe\", ...message });\n },\n\n unsubscribe: (viewport) => {\n worker.postMessage({ type: \"unsubscribe\", viewport });\n },\n\n send: (message) => {\n worker.postMessage(message);\n },\n\n destroy: (viewportId?: string) => {\n if (viewportId && viewports.has(viewportId)) {\n viewports.delete(viewportId);\n }\n },\n\n rpcCall: async <T = unknown>(\n message:\n | VuuRpcRequest\n | ClientToServerMenuRPC\n | ClientToServerViewportRpcCall\n ) => asyncRequest<T>(message),\n\n getTableList: async () =>\n asyncRequest<VuuTableList>({ type: \"GET_TABLE_LIST\" }),\n\n getTableSchema: async (table) =>\n asyncRequest<TableSchema>({\n type: Message.GET_TABLE_META,\n table,\n }),\n};\n\nexport type ConnectionEvents = {\n \"connection-status\": (message: ConnectionStatusMessage) => void;\n \"connection-metrics\": (message: ConnectionQualityMetrics) => void;\n};\n\nexport type ConnectOptions = {\n url: string;\n authToken?: string;\n username?: string;\n protocol?: WebSocketProtocol;\n /** Max number of reconnect attempts in the event of unsuccessful websocket connection at startup */\n retryLimitStartup?: number;\n /** Max number of reconnect attempts in the event of a disconnected websocket connection */\n retryLimitDisconnect?: number;\n};\n\nclass _ConnectionManager extends EventEmitter<ConnectionEvents> {\n // The first request must have the token. We can change this to block others until\n // the request with token is received.\n async connect({\n url,\n authToken,\n username,\n protocol,\n retryLimitDisconnect,\n retryLimitStartup,\n }: ConnectOptions): Promise<ServerAPI> {\n // By passing handleMessageFromWorker here, we can get connection status\n //messages while we wait for worker to resolve.\n worker = await getWorker({\n protocol,\n url,\n token: authToken,\n username,\n retryLimitDisconnect,\n retryLimitStartup,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n handleConnectionStatusChange: handleMessageFromWorker,\n });\n return connectedServerAPI;\n }\n\n destroy() {\n worker.terminate();\n }\n}\n\nexport const ConnectionManager = new _ConnectionManager();\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 */\nexport const connectToServer = async ({\n url,\n protocol = undefined,\n authToken,\n username,\n retryLimitDisconnect,\n retryLimitStartup,\n}: ConnectOptions): Promise<\"connected\" | \"rejected\"> => {\n try {\n const serverAPI = await ConnectionManager.connect({\n protocol,\n url,\n authToken,\n username,\n retryLimitDisconnect,\n retryLimitStartup,\n });\n resolveServer(serverAPI);\n return \"connected\";\n } catch (err: unknown) {\n rejectServer(err);\n return \"rejected\";\n }\n};\n\nexport const makeRpcCall = async <T = unknown>(rpcRequest: VuuRpcRequest) => {\n try {\n return (await serverAPI).rpcCall<T>(rpcRequest);\n } catch (err) {\n throw Error(\"Error accessing server api\");\n }\n};\n"],"names":["getLoggingConfigForWorker","workerSourceCode","worker","isConnectionStatusMessage","messageShouldBeRoutedToDataSource","isConnectionQualityMetrics","messageHasResult","isTableSchema","uuid","Message.GET_TABLE_META","EventEmitter","serverAPI"],"mappings":";;;;;;;AAqCA,MAAM,aAAa,IAAI,IAAA,CAAK,CAACA,kCAA0B,EAAA,GAAIC,8BAAgB,CAAG,EAAA;AAAA,EAC5E,IAAM,EAAA,iBAAA;AACR,CAAC,CAAA,CAAA;AACD,MAAM,aAAA,GAAgB,GAAI,CAAA,eAAA,CAAgB,UAAU,CAAA,CAAA;AAOpD,IAAI,MAAA,CAAA;AACJ,IAAI,aAAA,CAAA;AACJ,MAAM,uBAAyC,EAAC,CAAA;AAEhD,IAAI,aAAA,CAAA;AACJ,IAAI,YAAA,CAAA;AAEJ,MAAM,SAAY,GAAA,IAAI,OAAmB,CAAA,CAAC,SAAS,MAAW,KAAA;AAC5D,EAAgB,aAAA,GAAA,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AA,EACA,oBAAA;AAAA,EACA,iBAAA;AACF,CAAyD,KAAA;AACvD,EAAI,IAAA;AACF,IAAMC,MAAAA,UAAAA,GAAY,MAAM,iBAAA,CAAkB,OAAQ,CAAA;AAAA,MAChD,QAAA;AAAA,MACA,GAAA;AAAA,MACA,SAAA;AAAA,MACA,QAAA;AAAA,MACA,oBAAA;AAAA,MACA,iBAAA;AAAA,KACD,CAAA,CAAA;AACD,IAAA,aAAA,CAAcA,UAAS,CAAA,CAAA;AACvB,IAAO,OAAA,WAAA,CAAA;AAAA,WACA,GAAc,EAAA;AACrB,IAAA,YAAA,CAAa,GAAG,CAAA,CAAA;AAChB,IAAO,OAAA,UAAA,CAAA;AAAA,GACT;AACF,EAAA;AAEa,MAAA,WAAA,GAAc,OAAoB,UAA8B,KAAA;AAC3E,EAAI,IAAA;AACF,IAAQ,OAAA,CAAA,MAAM,SAAW,EAAA,OAAA,CAAW,UAAU,CAAA,CAAA;AAAA,WACvC,GAAK,EAAA;AACZ,IAAA,MAAM,MAAM,4BAA4B,CAAA,CAAA;AAAA,GAC1C;AACF;;;;;;;"}
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ let _connectionId = 0;
4
+ const connectionId = {
5
+ get nextValue() {
6
+ return _connectionId++;
7
+ }
8
+ };
9
+ const msgType = {
10
+ connect: "connect",
11
+ connectionStatus: "connection-status",
12
+ getFilterData: "GetFilterData",
13
+ rowData: "rowData",
14
+ rowSet: "rowset",
15
+ select: "select",
16
+ selectAll: "selectAll",
17
+ selectNone: "selectNone",
18
+ selected: "selected",
19
+ snapshot: "snapshot",
20
+ update: "update",
21
+ createLink: "createLink",
22
+ disable: "disable",
23
+ enable: "enable",
24
+ suspend: "suspend",
25
+ resume: "resume",
26
+ addSubscription: "AddSubscription",
27
+ closeTreeNode: "closeTreeNode",
28
+ columnList: "ColumnList",
29
+ data: "data",
30
+ openTreeNode: "openTreeNode",
31
+ aggregate: "aggregate",
32
+ filter: "filter",
33
+ filterQuery: "filterQuery",
34
+ filterData: "filterData",
35
+ getSearchData: "GetSearchData",
36
+ groupBy: "groupBy",
37
+ modifySubscription: "ModifySubscription",
38
+ searchData: "searchData",
39
+ setGroupState: "setGroupState",
40
+ size: "size",
41
+ sort: "sort",
42
+ subscribed: "Subscribed",
43
+ tableList: "TableList",
44
+ unsubscribe: "TerminateSubscription",
45
+ viewRangeChanged: "ViewRangeChanged"
46
+ };
47
+
48
+ exports.connectionId = connectionId;
49
+ exports.msgType = msgType;
50
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.js","sources":["../src/constants.ts"],"sourcesContent":["let _connectionId = 0;\n\nexport const connectionId = {\n get nextValue() {\n return _connectionId++;\n },\n};\n\nexport const msgType = {\n connect: \"connect\",\n connectionStatus: \"connection-status\",\n getFilterData: \"GetFilterData\",\n rowData: \"rowData\",\n rowSet: \"rowset\",\n select: \"select\",\n selectAll: \"selectAll\",\n selectNone: \"selectNone\",\n selected: \"selected\",\n snapshot: \"snapshot\",\n update: \"update\",\n createLink: \"createLink\",\n disable: \"disable\",\n enable: \"enable\",\n suspend: \"suspend\",\n resume: \"resume\",\n\n addSubscription: \"AddSubscription\",\n closeTreeNode: \"closeTreeNode\",\n columnList: \"ColumnList\",\n data: \"data\",\n openTreeNode: \"openTreeNode\",\n aggregate: \"aggregate\",\n filter: \"filter\",\n filterQuery: \"filterQuery\",\n filterData: \"filterData\",\n getSearchData: \"GetSearchData\",\n groupBy: \"groupBy\",\n modifySubscription: \"ModifySubscription\",\n searchData: \"searchData\",\n setGroupState: \"setGroupState\",\n size: \"size\",\n sort: \"sort\",\n subscribed: \"Subscribed\",\n tableList: \"TableList\",\n unsubscribe: \"TerminateSubscription\",\n viewRangeChanged: \"ViewRangeChanged\",\n};\n"],"names":[],"mappings":";;AAAA,IAAI,aAAgB,GAAA,CAAA,CAAA;AAEb,MAAM,YAAe,GAAA;AAAA,EAC1B,IAAI,SAAY,GAAA;AACd,IAAO,OAAA,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-only";
4
+ const toDataSourceConfig = (message) => {
5
+ switch (message.type) {
6
+ case "aggregate":
7
+ return { aggregations: message.aggregations };
8
+ case "columns":
9
+ return { columns: message.columns };
10
+ case "filter":
11
+ return { filter: message.filter };
12
+ case "groupBy":
13
+ return { groupBy: message.groupBy };
14
+ case "sort":
15
+ return { sort: message.sort };
16
+ case "config":
17
+ return message.config;
18
+ }
19
+ };
20
+ const datasourceMessages = [
21
+ "config",
22
+ "aggregate",
23
+ "viewport-update",
24
+ "columns",
25
+ "debounce-begin",
26
+ "disabled",
27
+ "enabled",
28
+ "filter",
29
+ "groupBy",
30
+ "vuu-link-created",
31
+ "vuu-link-removed",
32
+ "vuu-links",
33
+ "vuu-menu",
34
+ "sort",
35
+ "subscribed"
36
+ ];
37
+ const shouldMessageBeRoutedToDataSource = (message) => {
38
+ const type = message.type;
39
+ return datasourceMessages.includes(type);
40
+ };
41
+ const isDataSourceConfigMessage = (message) => ["config", "aggregate", "columns", "filter", "groupBy", "sort"].includes(
42
+ message.type
43
+ );
44
+ const isSessionTableActionMessage = (messageBody) => messageBody.type === "VIEW_PORT_MENU_RESP" && messageBody.action !== null && isSessionTable(messageBody.action.table);
45
+ const isSessionTable = (table) => {
46
+ if (table !== null && typeof table === "object" && "table" in table && "module" in table) {
47
+ return table.table.startsWith("session");
48
+ }
49
+ return false;
50
+ };
51
+
52
+ exports.isDataSourceConfigMessage = isDataSourceConfigMessage;
53
+ exports.isSessionTable = isSessionTable;
54
+ exports.isSessionTableActionMessage = isSessionTableActionMessage;
55
+ exports.isSizeOnly = isSizeOnly;
56
+ exports.shouldMessageBeRoutedToDataSource = shouldMessageBeRoutedToDataSource;
57
+ exports.toDataSourceConfig = toDataSourceConfig;
58
+ //# sourceMappingURL=data-source.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data-source.js","sources":["../src/data-source.ts"],"sourcesContent":["import {\n DataSourceCallbackMessage,\n DataSourceConfig,\n DataSourceConfigMessage,\n DataSourceDataSizeMessage,\n} from \"@vuu-ui/vuu-data-types\";\nimport {\n ServerToClientBody,\n ServerToClientMenuSessionTableAction,\n VuuTable,\n} from \"@vuu-ui/vuu-protocol-types\";\n\nexport const isSizeOnly = (\n message: DataSourceCallbackMessage\n): message is DataSourceDataSizeMessage =>\n message.type === \"viewport-update\" && message.mode === \"size-only\";\n\nexport const toDataSourceConfig = (\n message: DataSourceConfigMessage\n): DataSourceConfig => {\n switch (message.type) {\n case \"aggregate\":\n return { aggregations: message.aggregations };\n case \"columns\":\n return { columns: message.columns };\n case \"filter\":\n return { filter: message.filter };\n case \"groupBy\":\n return { groupBy: message.groupBy };\n case \"sort\":\n return { sort: message.sort };\n case \"config\":\n return message.config;\n }\n};\n\nconst datasourceMessages = [\n \"config\",\n \"aggregate\",\n \"viewport-update\",\n \"columns\",\n \"debounce-begin\",\n \"disabled\",\n \"enabled\",\n \"filter\",\n \"groupBy\",\n \"vuu-link-created\",\n \"vuu-link-removed\",\n \"vuu-links\",\n \"vuu-menu\",\n \"sort\",\n \"subscribed\",\n];\n\nexport const shouldMessageBeRoutedToDataSource = (\n message: unknown\n): message is DataSourceCallbackMessage => {\n const type = (message as DataSourceCallbackMessage).type;\n return datasourceMessages.includes(type);\n};\n\nexport const isDataSourceConfigMessage = (\n message: DataSourceCallbackMessage\n): message is DataSourceConfigMessage =>\n [\"config\", \"aggregate\", \"columns\", \"filter\", \"groupBy\", \"sort\"].includes(\n message.type\n );\n\nexport const isSessionTableActionMessage = (\n messageBody: ServerToClientBody\n): messageBody is ServerToClientMenuSessionTableAction =>\n messageBody.type === \"VIEW_PORT_MENU_RESP\" &&\n messageBody.action !== null &&\n isSessionTable(messageBody.action.table);\n\nexport const isSessionTable = (table?: unknown) => {\n if (\n table !== null &&\n typeof table === \"object\" &&\n \"table\" in table &&\n \"module\" in table\n ) {\n return (table as VuuTable).table.startsWith(\"session\");\n }\n return false;\n};\n"],"names":[],"mappings":";;AAYO,MAAM,aAAa,CACxB,OAAA,KAEA,QAAQ,IA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