aparavi-client 1.0.2

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 (169) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +523 -0
  3. package/dist/aparavi-client-typescript-1.0.0.tgz +0 -0
  4. package/dist/aparavi-client-typescript-1.0.1.tgz +0 -0
  5. package/dist/cjs/client.js +1002 -0
  6. package/dist/cjs/client.js.map +1 -0
  7. package/dist/cjs/constants.js +37 -0
  8. package/dist/cjs/constants.js.map +1 -0
  9. package/dist/cjs/core/DAPBase.js +313 -0
  10. package/dist/cjs/core/DAPBase.js.map +1 -0
  11. package/dist/cjs/core/DAPClient.js +173 -0
  12. package/dist/cjs/core/DAPClient.js.map +1 -0
  13. package/dist/cjs/core/TransportBase.js +131 -0
  14. package/dist/cjs/core/TransportBase.js.map +1 -0
  15. package/dist/cjs/core/TransportWebSocket.js +492 -0
  16. package/dist/cjs/core/TransportWebSocket.js.map +1 -0
  17. package/dist/cjs/exceptions/index.js +109 -0
  18. package/dist/cjs/exceptions/index.js.map +1 -0
  19. package/dist/cjs/index.js +56 -0
  20. package/dist/cjs/index.js.map +1 -0
  21. package/dist/cjs/package.json +3 -0
  22. package/dist/cjs/schema/Doc.js +79 -0
  23. package/dist/cjs/schema/Doc.js.map +1 -0
  24. package/dist/cjs/schema/DocFilter.js +133 -0
  25. package/dist/cjs/schema/DocFilter.js.map +1 -0
  26. package/dist/cjs/schema/DocGroup.js +235 -0
  27. package/dist/cjs/schema/DocGroup.js.map +1 -0
  28. package/dist/cjs/schema/DocMetadata.js +57 -0
  29. package/dist/cjs/schema/DocMetadata.js.map +1 -0
  30. package/dist/cjs/schema/Question.js +414 -0
  31. package/dist/cjs/schema/Question.js.map +1 -0
  32. package/dist/cjs/schema/index.js +50 -0
  33. package/dist/cjs/schema/index.js.map +1 -0
  34. package/dist/cjs/types/client.js +26 -0
  35. package/dist/cjs/types/client.js.map +1 -0
  36. package/dist/cjs/types/data.js +26 -0
  37. package/dist/cjs/types/data.js.map +1 -0
  38. package/dist/cjs/types/events.js +119 -0
  39. package/dist/cjs/types/events.js.map +1 -0
  40. package/dist/cjs/types/index.js +50 -0
  41. package/dist/cjs/types/index.js.map +1 -0
  42. package/dist/cjs/types/pipeline.js +26 -0
  43. package/dist/cjs/types/pipeline.js.map +1 -0
  44. package/dist/cjs/types/task.js +115 -0
  45. package/dist/cjs/types/task.js.map +1 -0
  46. package/dist/cli/cli/aparavi.js +1401 -0
  47. package/dist/cli/cli/aparavi.js.map +1 -0
  48. package/dist/cli/src/client.js +1002 -0
  49. package/dist/cli/src/client.js.map +1 -0
  50. package/dist/cli/src/constants.js +37 -0
  51. package/dist/cli/src/constants.js.map +1 -0
  52. package/dist/cli/src/core/DAPBase.js +313 -0
  53. package/dist/cli/src/core/DAPBase.js.map +1 -0
  54. package/dist/cli/src/core/DAPClient.js +173 -0
  55. package/dist/cli/src/core/DAPClient.js.map +1 -0
  56. package/dist/cli/src/core/TransportBase.js +131 -0
  57. package/dist/cli/src/core/TransportBase.js.map +1 -0
  58. package/dist/cli/src/core/TransportWebSocket.js +492 -0
  59. package/dist/cli/src/core/TransportWebSocket.js.map +1 -0
  60. package/dist/cli/src/exceptions/index.js +109 -0
  61. package/dist/cli/src/exceptions/index.js.map +1 -0
  62. package/dist/cli/src/index.js +56 -0
  63. package/dist/cli/src/index.js.map +1 -0
  64. package/dist/cli/src/schema/Doc.js +79 -0
  65. package/dist/cli/src/schema/Doc.js.map +1 -0
  66. package/dist/cli/src/schema/DocFilter.js +133 -0
  67. package/dist/cli/src/schema/DocFilter.js.map +1 -0
  68. package/dist/cli/src/schema/DocGroup.js +235 -0
  69. package/dist/cli/src/schema/DocGroup.js.map +1 -0
  70. package/dist/cli/src/schema/DocMetadata.js +57 -0
  71. package/dist/cli/src/schema/DocMetadata.js.map +1 -0
  72. package/dist/cli/src/schema/Question.js +414 -0
  73. package/dist/cli/src/schema/Question.js.map +1 -0
  74. package/dist/cli/src/schema/index.js +50 -0
  75. package/dist/cli/src/schema/index.js.map +1 -0
  76. package/dist/cli/src/types/client.js +26 -0
  77. package/dist/cli/src/types/client.js.map +1 -0
  78. package/dist/cli/src/types/data.js +26 -0
  79. package/dist/cli/src/types/data.js.map +1 -0
  80. package/dist/cli/src/types/events.js +119 -0
  81. package/dist/cli/src/types/events.js.map +1 -0
  82. package/dist/cli/src/types/index.js +50 -0
  83. package/dist/cli/src/types/index.js.map +1 -0
  84. package/dist/cli/src/types/pipeline.js +26 -0
  85. package/dist/cli/src/types/pipeline.js.map +1 -0
  86. package/dist/cli/src/types/task.js +115 -0
  87. package/dist/cli/src/types/task.js.map +1 -0
  88. package/dist/esm/client.js +997 -0
  89. package/dist/esm/client.js.map +1 -0
  90. package/dist/esm/constants.js +34 -0
  91. package/dist/esm/constants.js.map +1 -0
  92. package/dist/esm/core/DAPBase.js +309 -0
  93. package/dist/esm/core/DAPBase.js.map +1 -0
  94. package/dist/esm/core/DAPClient.js +169 -0
  95. package/dist/esm/core/DAPClient.js.map +1 -0
  96. package/dist/esm/core/TransportBase.js +127 -0
  97. package/dist/esm/core/TransportBase.js.map +1 -0
  98. package/dist/esm/core/TransportWebSocket.js +488 -0
  99. package/dist/esm/core/TransportWebSocket.js.map +1 -0
  100. package/dist/esm/exceptions/index.js +100 -0
  101. package/dist/esm/exceptions/index.js.map +1 -0
  102. package/dist/esm/index.js +40 -0
  103. package/dist/esm/index.js.map +1 -0
  104. package/dist/esm/package.json +3 -0
  105. package/dist/esm/schema/Doc.js +75 -0
  106. package/dist/esm/schema/Doc.js.map +1 -0
  107. package/dist/esm/schema/DocFilter.js +129 -0
  108. package/dist/esm/schema/DocFilter.js.map +1 -0
  109. package/dist/esm/schema/DocGroup.js +231 -0
  110. package/dist/esm/schema/DocGroup.js.map +1 -0
  111. package/dist/esm/schema/DocMetadata.js +53 -0
  112. package/dist/esm/schema/DocMetadata.js.map +1 -0
  113. package/dist/esm/schema/Question.js +409 -0
  114. package/dist/esm/schema/Question.js.map +1 -0
  115. package/dist/esm/schema/index.js +34 -0
  116. package/dist/esm/schema/index.js.map +1 -0
  117. package/dist/esm/types/client.js +25 -0
  118. package/dist/esm/types/client.js.map +1 -0
  119. package/dist/esm/types/data.js +25 -0
  120. package/dist/esm/types/data.js.map +1 -0
  121. package/dist/esm/types/events.js +116 -0
  122. package/dist/esm/types/events.js.map +1 -0
  123. package/dist/esm/types/index.js +34 -0
  124. package/dist/esm/types/index.js.map +1 -0
  125. package/dist/esm/types/pipeline.js +25 -0
  126. package/dist/esm/types/pipeline.js.map +1 -0
  127. package/dist/esm/types/task.js +112 -0
  128. package/dist/esm/types/task.js.map +1 -0
  129. package/dist/types/client.d.ts +395 -0
  130. package/dist/types/client.d.ts.map +1 -0
  131. package/dist/types/constants.d.ts +34 -0
  132. package/dist/types/constants.d.ts.map +1 -0
  133. package/dist/types/core/DAPBase.d.ts +140 -0
  134. package/dist/types/core/DAPBase.d.ts.map +1 -0
  135. package/dist/types/core/DAPClient.d.ts +83 -0
  136. package/dist/types/core/DAPClient.d.ts.map +1 -0
  137. package/dist/types/core/TransportBase.d.ts +94 -0
  138. package/dist/types/core/TransportBase.d.ts.map +1 -0
  139. package/dist/types/core/TransportWebSocket.d.ts +78 -0
  140. package/dist/types/core/TransportWebSocket.d.ts.map +1 -0
  141. package/dist/types/exceptions/index.d.ts +81 -0
  142. package/dist/types/exceptions/index.d.ts.map +1 -0
  143. package/dist/types/index.d.ts +36 -0
  144. package/dist/types/index.d.ts.map +1 -0
  145. package/dist/types/schema/Doc.d.ts +69 -0
  146. package/dist/types/schema/Doc.d.ts.map +1 -0
  147. package/dist/types/schema/DocFilter.d.ts +101 -0
  148. package/dist/types/schema/DocFilter.d.ts.map +1 -0
  149. package/dist/types/schema/DocGroup.d.ts +113 -0
  150. package/dist/types/schema/DocGroup.d.ts.map +1 -0
  151. package/dist/types/schema/DocMetadata.d.ts +61 -0
  152. package/dist/types/schema/DocMetadata.d.ts.map +1 -0
  153. package/dist/types/schema/Question.d.ts +163 -0
  154. package/dist/types/schema/Question.d.ts.map +1 -0
  155. package/dist/types/schema/index.d.ts +34 -0
  156. package/dist/types/schema/index.d.ts.map +1 -0
  157. package/dist/types/types/client.d.ts +140 -0
  158. package/dist/types/types/client.d.ts.map +1 -0
  159. package/dist/types/types/data.d.ts +95 -0
  160. package/dist/types/types/data.d.ts.map +1 -0
  161. package/dist/types/types/events.d.ts +246 -0
  162. package/dist/types/types/events.d.ts.map +1 -0
  163. package/dist/types/types/index.d.ts +34 -0
  164. package/dist/types/types/index.d.ts.map +1 -0
  165. package/dist/types/types/pipeline.d.ts +61 -0
  166. package/dist/types/types/pipeline.d.ts.map +1 -0
  167. package/dist/types/types/task.d.ts +265 -0
  168. package/dist/types/types/task.d.ts.map +1 -0
  169. package/package.json +75 -0
@@ -0,0 +1,997 @@
1
+ /**
2
+ * MIT License
3
+ *
4
+ * Copyright (c) 2024 Aparavi Development Team
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+ import { TransportWebSocket } from './core/TransportWebSocket';
25
+ import { DAPClient } from './core/DAPClient';
26
+ import { CONST_DEFAULT_SERVICE } from './constants';
27
+ // Global counter for generating unique client IDs
28
+ let clientId = 0;
29
+ /**
30
+ * Streaming data pipe for sending large datasets to Aparavi pipelines.
31
+ *
32
+ * DataPipe provides a stream-like interface for uploading data to an Aparavi
33
+ * pipeline. It handles the low-level protocol details of opening, writing to,
34
+ * and closing data pipes on the server.
35
+ *
36
+ * Usage pattern:
37
+ * 1. Create pipe using client.pipe()
38
+ * 2. Call open() to establish the pipe
39
+ * 3. Call write() multiple times with data chunks
40
+ * 4. Call close() to finalize and get results
41
+ *
42
+ * @example
43
+ * ```typescript
44
+ * const pipe = await client.pipe(token, { filename: 'data.json' }, 'application/json');
45
+ * await pipe.open();
46
+ * await pipe.write(new TextEncoder().encode('{"data": "value"}'));
47
+ * const result = await pipe.close();
48
+ * ```
49
+ */
50
+ export class DataPipe {
51
+ /**
52
+ * Creates a new DataPipe instance.
53
+ *
54
+ * @param client - The AparaviClient instance managing this pipe
55
+ * @param token - Task token for the pipeline receiving the data
56
+ * @param objinfo - Metadata about the object being sent (e.g., filename, size)
57
+ * @param mimeType - MIME type of the data being sent (default: 'application/octet-stream')
58
+ * @param provider - Optional provider name for the data source
59
+ */
60
+ constructor(client, token, objinfo = {}, mimeType = 'application/octet-stream', provider) {
61
+ this._opened = false;
62
+ this._closed = false;
63
+ this._client = client;
64
+ this._token = token;
65
+ this._objinfo = objinfo;
66
+ this._mimeType = mimeType;
67
+ this._provider = provider;
68
+ }
69
+ /**
70
+ * Check if the pipe is currently open for writing.
71
+ *
72
+ * @returns true if the pipe has been opened and not yet closed
73
+ */
74
+ get isOpened() {
75
+ return this._opened;
76
+ }
77
+ /**
78
+ * Get the unique ID assigned to this pipe by the server.
79
+ *
80
+ * This ID is assigned when the pipe is opened and is used for subsequent
81
+ * write operations. It remains undefined until open() is called successfully.
82
+ *
83
+ * @returns The server-assigned pipe ID, or undefined if not yet opened
84
+ */
85
+ get pipeId() {
86
+ return this._pipeId;
87
+ }
88
+ /**
89
+ * Open the pipe for data transmission.
90
+ *
91
+ * Establishes a data pipe on the server for streaming data to the pipeline.
92
+ * Must be called before any write() operations. The server will assign a
93
+ * unique pipe ID that is used for subsequent operations.
94
+ *
95
+ * @returns This DataPipe instance (for method chaining)
96
+ * @throws Error if the pipe is already opened or if the pipeline is not running
97
+ */
98
+ async open() {
99
+ if (this._opened) {
100
+ throw new Error('Pipe already opened');
101
+ }
102
+ const request = this._client.buildRequest('apaext_process', {
103
+ arguments: {
104
+ subcommand: 'open',
105
+ object: this._objinfo,
106
+ mimeType: this._mimeType,
107
+ provider: this._provider,
108
+ },
109
+ token: this._token,
110
+ });
111
+ const response = await this._client.request(request);
112
+ if (this._client.didFail(response)) {
113
+ throw new Error(response.message || 'Your pipeline is not currently running.');
114
+ }
115
+ this._pipeId = response.body?.pipe_id;
116
+ this._opened = true;
117
+ return this;
118
+ }
119
+ /**
120
+ * Write data to the pipe.
121
+ *
122
+ * Sends a chunk of data through the pipe to the server pipeline. Can be called
123
+ * multiple times to stream large datasets. The pipe must be opened first.
124
+ *
125
+ * @param buffer - Data to write, must be a Uint8Array
126
+ * @throws Error if the pipe is not opened, buffer is invalid, or write fails
127
+ */
128
+ async write(buffer) {
129
+ if (!this._opened) {
130
+ throw new Error('Pipe not opened');
131
+ }
132
+ if (!(buffer instanceof Uint8Array)) {
133
+ throw new Error('Buffer must be Uint8Array');
134
+ }
135
+ const request = this._client.buildRequest('apaext_process', {
136
+ arguments: {
137
+ subcommand: 'write',
138
+ pipe_id: this._pipeId,
139
+ data: buffer,
140
+ },
141
+ token: this._token,
142
+ });
143
+ const response = await this._client.request(request);
144
+ if (this._client.didFail(response)) {
145
+ throw new Error(response.message || 'Failed to write to pipe');
146
+ }
147
+ }
148
+ /**
149
+ * Close the pipe and get the processing results.
150
+ *
151
+ * Finalizes the data stream and signals the server that no more data will be sent.
152
+ * The server processes any buffered data and returns the final result. After closing,
153
+ * the pipe cannot be reopened or written to again.
154
+ *
155
+ * @returns The processing result from the server, or undefined if already closed
156
+ * @throws Error if closing the pipe fails
157
+ */
158
+ async close() {
159
+ if (!this._opened || this._closed) {
160
+ return;
161
+ }
162
+ try {
163
+ const request = this._client.buildRequest('apaext_process', {
164
+ arguments: {
165
+ subcommand: 'close',
166
+ pipe_id: this._pipeId,
167
+ },
168
+ token: this._token,
169
+ });
170
+ const response = await this._client.request(request);
171
+ if (this._client.didFail(response)) {
172
+ throw new Error(response.message || 'Failed to close pipe');
173
+ }
174
+ return response.body;
175
+ }
176
+ finally {
177
+ this._closed = true;
178
+ }
179
+ }
180
+ }
181
+ /**
182
+ * Main Aparavi client for connecting to Aparavi servers and services.
183
+ *
184
+ * This client provides a comprehensive API for interacting with Aparavi services,
185
+ * including connection management, pipeline execution, data operations, AI chat,
186
+ * event handling, and server connectivity testing.
187
+ *
188
+ * Key features:
189
+ * - Single shared WebSocket connection for all operations
190
+ * - Connection management (connect/disconnect) with optional persistence
191
+ * - Automatic reconnection when persist mode is enabled
192
+ * - Pipeline execution (use, terminate, getTaskStatus)
193
+ * - Data operations (send, sendFiles, pipe)
194
+ * - AI chat functionality (chat)
195
+ * - Event handling (setEvents, event callbacks)
196
+ * - Server connectivity testing (ping)
197
+ * - Full TypeScript type safety
198
+ */
199
+ export class AparaviClient extends DAPClient {
200
+ /**
201
+ * Creates a new AparaviClient instance.
202
+ *
203
+ * Configuration priority (highest to lowest):
204
+ * 1. Values passed in config parameter (auth, uri)
205
+ * 2. Values from env parameter (if provided)
206
+ * 3. Values from .env file (Node.js only)
207
+ * 4. Default values
208
+ *
209
+ * @param config - Configuration options for the client
210
+ * @param config.auth - API key for authentication (required)
211
+ * @param config.uri - Server URI (default: CONST_DEFAULT_SERVICE)
212
+ * @param config.env - Environment variables dictionary for configuration and substitution
213
+ * @param config.onEvent - Callback for server events
214
+ * @param config.onConnected - Callback when connection is established
215
+ * @param config.onDisconnected - Callback when connection is lost
216
+ * @param config.persist - Enable automatic reconnection
217
+ * @param config.reconnectDelay - Delay between reconnection attempts in ms
218
+ * @param config.module - Optional module name for client identification
219
+ *
220
+ * @throws Error if auth is not provided via config, env, or .env file
221
+ *
222
+ * @example
223
+ * ```typescript
224
+ * // Using explicit auth and URI
225
+ * const client = new AparaviClient({
226
+ * auth: 'your-api-key',
227
+ * uri: 'wss://your-server.com',
228
+ * persist: true,
229
+ * onEvent: (event) => console.log('Event:', event)
230
+ * });
231
+ *
232
+ * // Using custom env dictionary
233
+ * const client = new AparaviClient({
234
+ * env: {
235
+ * APARAVI_APIKEY: 'your-api-key',
236
+ * APARAVI_URI: 'wss://your-server.com',
237
+ * APARAVI_PROJECT_ID: 'my-project'
238
+ * }
239
+ * });
240
+ * ```
241
+ */
242
+ constructor(config = {}) {
243
+ // Check if we're in Node.js or browser environment
244
+ const isBrowser = typeof window !== 'undefined';
245
+ // Build environment variables dictionary
246
+ // Priority: provided env > .env file
247
+ let clientEnv = {};
248
+ if (config.env) {
249
+ // Use provided env dictionary
250
+ clientEnv = { ...config.env };
251
+ }
252
+ else {
253
+ // Load from .env file only (Node.js only)
254
+ if (!isBrowser) {
255
+ try {
256
+ const fs = require('fs');
257
+ const path = require('path');
258
+ const envPath = path.join(process.cwd(), '.env');
259
+ if (fs.existsSync(envPath)) {
260
+ const content = fs.readFileSync(envPath, 'utf-8');
261
+ // Parse each line
262
+ for (const line of content.split('\n')) {
263
+ const trimmed = line.trim();
264
+ // Skip comments and empty lines
265
+ if (!trimmed || trimmed.startsWith('#')) {
266
+ continue;
267
+ }
268
+ // Parse KEY=VALUE format
269
+ const match = trimmed.match(/^([^=]+)=(.*)$/);
270
+ if (match) {
271
+ const key = match[1].trim();
272
+ let value = match[2].trim();
273
+ // Remove quotes if present
274
+ if ((value.startsWith('"') && value.endsWith('"')) ||
275
+ (value.startsWith("'") && value.endsWith("'"))) {
276
+ value = value.slice(1, -1);
277
+ }
278
+ clientEnv[key] = value;
279
+ }
280
+ }
281
+ }
282
+ }
283
+ catch {
284
+ // File doesn't exist or can't be read - that's okay
285
+ }
286
+ }
287
+ }
288
+ const { auth = config.auth || clientEnv.APARAVI_APIKEY, uri = config.uri || clientEnv.APARAVI_URI || CONST_DEFAULT_SERVICE, onEvent, onConnected, onDisconnected, persist, reconnectDelay, module, } = config;
289
+ if (!auth) {
290
+ throw new Error("Authentication key is required. Provide 'auth' parameter, 'env' parameter, or set 'APARAVI_APIKEY' in .env file.");
291
+ }
292
+ // Convert HTTP/HTTPS URI to WS/WSS for WebSocket connections
293
+ const wsUri = AparaviClient._convertToWebSocketUri(uri);
294
+ const fullUri = `${wsUri}/task/service`;
295
+ // Create unique client identifier
296
+ const clientName = module || `CLIENT-${clientId++}`;
297
+ // Set up WebSocket transport for server communication
298
+ const transport = new TransportWebSocket(fullUri, auth);
299
+ // Initialize the DAPClient
300
+ super(clientName, transport, config);
301
+ this._dapAttempted = false;
302
+ this._nextChatId = 1;
303
+ // Persistence properties for automatic reconnection
304
+ this._persist = false;
305
+ this._reconnectDelay = 1000; // Default delay in milliseconds
306
+ this._manualDisconnect = false;
307
+ // Store connection details and environment
308
+ this._uri = fullUri;
309
+ this._apikey = auth;
310
+ this._env = clientEnv;
311
+ // Set up callbacks if provided
312
+ if (onEvent)
313
+ this._callerOnEvent = onEvent;
314
+ if (onConnected)
315
+ this._callerOnConnected = onConnected;
316
+ if (onDisconnected)
317
+ this._callerOnDisconnected = onDisconnected;
318
+ // Set up persistence options
319
+ this._persist = persist ?? false;
320
+ this._reconnectDelay = reconnectDelay ?? 1000;
321
+ }
322
+ /**
323
+ * Convert HTTP/HTTPS URI to WebSocket URI
324
+ */
325
+ static _convertToWebSocketUri(uri) {
326
+ try {
327
+ const url = new URL(uri);
328
+ const wsScheme = url.protocol === 'https:' ? 'wss:' : 'ws:';
329
+ return `${wsScheme}//${url.host}`;
330
+ }
331
+ catch {
332
+ return uri;
333
+ }
334
+ }
335
+ /**
336
+ * Clear any pending reconnection timeout
337
+ */
338
+ _clearReconnectTimeout() {
339
+ if (this._reconnectTimeout) {
340
+ clearTimeout(this._reconnectTimeout);
341
+ this._reconnectTimeout = undefined;
342
+ }
343
+ }
344
+ /**
345
+ * Schedule a reconnection attempt after the configured delay
346
+ */
347
+ _scheduleReconnect() {
348
+ this._clearReconnectTimeout();
349
+ this.debugMessage(`Scheduling reconnection in ${this._reconnectDelay}ms`);
350
+ this._reconnectTimeout = setTimeout(async () => {
351
+ if (this._persist && !this._manualDisconnect) {
352
+ this.debugMessage('Attempting to reconnect...');
353
+ try {
354
+ await super.connect();
355
+ }
356
+ catch (error) {
357
+ this.debugMessage(`Reconnection failed: ${error}`);
358
+ // Will schedule another attempt via onDisconnected
359
+ }
360
+ }
361
+ }, this._reconnectDelay);
362
+ }
363
+ // ============================================================================
364
+ // CONNECTION METHODS
365
+ // ============================================================================
366
+ /**
367
+ * Check if the client is currently connected to the Aparavi server.
368
+ */
369
+ isConnected() {
370
+ return this._transport?.isConnected() || false;
371
+ }
372
+ /**
373
+ * Connect to the Aparavi server.
374
+ *
375
+ * Must be called before executing pipelines or other operations.
376
+ * In persist mode, enables automatic reconnection on disconnect.
377
+ */
378
+ async connect() {
379
+ this._manualDisconnect = false;
380
+ // If we are already connected, disconnect first
381
+ if (this.isConnected()) {
382
+ await this.disconnect();
383
+ }
384
+ // Call the DAP client function
385
+ await super.connect();
386
+ }
387
+ /**
388
+ * Disconnect from the Aparavi server and stop automatic reconnection.
389
+ *
390
+ * Should be called when finished with the client to clean up resources.
391
+ */
392
+ async disconnect() {
393
+ this._manualDisconnect = true;
394
+ this._clearReconnectTimeout();
395
+ // Call the DAP client function
396
+ await super.disconnect();
397
+ }
398
+ /**
399
+ * Send a request to the Aparavi server.
400
+ */
401
+ async request(request) {
402
+ // Delegate to parent class for actual request processing
403
+ return super.request(request);
404
+ }
405
+ // ============================================================================
406
+ // PING METHODS
407
+ // ============================================================================
408
+ /**
409
+ * Test connectivity to the Aparavi server.
410
+ *
411
+ * Sends a lightweight ping request to the server to verify it's responding
412
+ * and reachable. This is useful for connectivity testing, health checks,
413
+ * and measuring response times.
414
+ */
415
+ async ping(token) {
416
+ // Build ping request
417
+ const request = this.buildRequest('apaext_ping', { token });
418
+ // Send to server and wait for response
419
+ const response = await this.request(request);
420
+ // Check if ping failed
421
+ if (this.didFail(response)) {
422
+ const errorMsg = response.message || 'Ping failed';
423
+ throw new Error(`Ping failed: ${errorMsg}`);
424
+ }
425
+ }
426
+ // ============================================================================
427
+ // EXECUTION METHODS
428
+ // ============================================================================
429
+ /**
430
+ * Substitute environment variables in a string.
431
+ * Replaces ${APARAVI_*} patterns with values from client's env dictionary.
432
+ * If variable is not found, leaves it unchanged.
433
+ */
434
+ substituteEnvVars(value) {
435
+ // Match ${APARAVI_*} patterns
436
+ return value.replace(/\$\{(APARAVI_[^}]+)\}/g, (match, varName) => {
437
+ // Check if variable exists in client's env
438
+ if (varName in this._env) {
439
+ return String(this._env[varName]);
440
+ }
441
+ // If not found, leave as is
442
+ return match;
443
+ });
444
+ }
445
+ /**
446
+ * Recursively process an object/array to substitute environment variables.
447
+ * Only processes string values, leaving other types unchanged.
448
+ */
449
+ processEnvSubstitution(obj) {
450
+ if (typeof obj === 'string') {
451
+ // If it's a string, perform substitution
452
+ return this.substituteEnvVars(obj);
453
+ }
454
+ else if (Array.isArray(obj)) {
455
+ // If it's an array, process each element
456
+ return obj.map(item => this.processEnvSubstitution(item));
457
+ }
458
+ else if (obj !== null && typeof obj === 'object') {
459
+ // If it's an object, process each property
460
+ const result = {};
461
+ for (const [key, value] of Object.entries(obj)) {
462
+ result[key] = this.processEnvSubstitution(value);
463
+ }
464
+ return result;
465
+ }
466
+ // For other types (number, boolean, null), return as is
467
+ return obj;
468
+ }
469
+ /**
470
+ * Start an Aparavi pipeline for processing data.
471
+ *
472
+ * This method loads and executes a pipeline configuration. It automatically performs
473
+ * environment variable substitution on the pipeline config, replacing ${APARAVI_*}
474
+ * placeholders with values from the .env file.
475
+ *
476
+ * @param options - Pipeline execution options
477
+ * @param options.token - Custom token for the pipeline (auto-generated if not provided)
478
+ * @param options.filepath - Path to JSON file containing pipeline configuration
479
+ * @param options.pipeline - Pipeline configuration object (alternative to filepath)
480
+ * @param options.source - Override pipeline source
481
+ * @param options.threads - Number of threads for execution (default: 1)
482
+ * @param options.useExisting - Use existing pipeline instance
483
+ * @param options.args - Command line arguments to pass to pipeline
484
+ *
485
+ * @returns Promise resolving to an object containing the task token and other metadata
486
+ * @throws Error if neither pipeline nor filepath is provided
487
+ *
488
+ * @example
489
+ * ```typescript
490
+ * // Using pipeline file
491
+ * const result = await client.use({ filepath: './pipeline.json' });
492
+ *
493
+ * // Using pipeline object
494
+ * const result = await client.use({
495
+ * pipeline: { components: [...], source: 'local', project_id: '123' }
496
+ * });
497
+ *
498
+ * // With environment variable substitution
499
+ * // Pipeline config: { "endpoint": "${APARAVI_URI}/api" }
500
+ * // Will be replaced with actual APARAVI_URI value from .env
501
+ * ```
502
+ */
503
+ async use(options = {}) {
504
+ const { token, filepath, pipeline, source, threads, useExisting, args } = options;
505
+ // Validate required parameters
506
+ if (!pipeline && !filepath) {
507
+ throw new Error('Pipeline configuration or file path is required and must be specified');
508
+ }
509
+ let pipelineConfig;
510
+ // Load pipeline configuration from file if needed
511
+ if (!pipeline && filepath) {
512
+ // Check if we're in Node.js environment
513
+ if (typeof window !== 'undefined') {
514
+ throw new Error('File loading not available in browser environment. Please provide pipeline object directly.');
515
+ }
516
+ // Load file in Node.js
517
+ const fs = require('fs');
518
+ const fileContent = fs.readFileSync(filepath, 'utf-8');
519
+ pipelineConfig = JSON.parse(fileContent);
520
+ }
521
+ else {
522
+ pipelineConfig = pipeline;
523
+ }
524
+ // Create a deep copy of the pipeline config to avoid modifying the original
525
+ let processedConfig = JSON.parse(JSON.stringify(pipelineConfig));
526
+ // Perform environment variable substitution on the pipeline configuration
527
+ processedConfig = this.processEnvSubstitution(processedConfig);
528
+ // Override source if specified (after substitution)
529
+ if (source !== undefined) {
530
+ processedConfig.pipeline.source = source;
531
+ }
532
+ // Build execution request with all parameters
533
+ const arguments_ = {
534
+ pipeline: processedConfig,
535
+ args: args || [],
536
+ };
537
+ // Add optional parameters if specified
538
+ if (token !== undefined) {
539
+ arguments_.token = token;
540
+ }
541
+ if (threads !== undefined) {
542
+ arguments_.threads = threads;
543
+ }
544
+ if (useExisting !== undefined) {
545
+ arguments_.useExisting = useExisting;
546
+ }
547
+ // Send execution request to server
548
+ const request = this.buildRequest('execute', { arguments: arguments_ });
549
+ const response = await this.request(request);
550
+ // Check for execution errors
551
+ if (this.didFail(response)) {
552
+ const errorMsg = response.message || 'Unknown execution error';
553
+ this.debugMessage(`Pipeline execution failed: ${errorMsg}`);
554
+ throw new Error(errorMsg);
555
+ }
556
+ // Extract and validate response
557
+ const responseBody = response.body || {};
558
+ const taskToken = responseBody.token;
559
+ if (!taskToken) {
560
+ throw new Error('Server did not return a task token in successful response');
561
+ }
562
+ this.debugMessage(`Pipeline execution started successfully, task token: ${taskToken}`);
563
+ // Type assertion to ensure token is present
564
+ return responseBody;
565
+ }
566
+ /**
567
+ * Terminate a running pipeline.
568
+ */
569
+ async terminate(token) {
570
+ // Send termination request
571
+ const request = this.buildRequest('terminate', { token });
572
+ const response = await this.request(request);
573
+ // Check for termination errors
574
+ if (this.didFail(response)) {
575
+ const errorMsg = response.message || 'Unknown termination error';
576
+ this.debugMessage(`Pipeline termination failed: ${errorMsg}`);
577
+ throw new Error(errorMsg);
578
+ }
579
+ }
580
+ /**
581
+ * Get the current status of a running pipeline.
582
+ */
583
+ async getTaskStatus(token) {
584
+ // Send status request
585
+ const request = this.buildRequest('apaext_get_task_status', { token });
586
+ const response = await this.request(request);
587
+ // Check for status retrieval errors
588
+ if (this.didFail(response)) {
589
+ const errorMsg = response.message || 'Unknown status retrieval error';
590
+ this.debugMessage(`Pipeline status retrieval failed: ${errorMsg}`);
591
+ throw new Error(errorMsg);
592
+ }
593
+ // Return status information
594
+ return response.body || {};
595
+ }
596
+ // ============================================================================
597
+ // DATA METHODS
598
+ // ============================================================================
599
+ /**
600
+ * Create a data pipe for streaming operations.
601
+ */
602
+ async pipe(token, objinfo = {}, mimeType, provider) {
603
+ return new DataPipe(this, token, objinfo, mimeType, provider);
604
+ }
605
+ /**
606
+ * Send data to a running pipeline.
607
+ */
608
+ async send(token, data, objinfo = {}, mimetype) {
609
+ // Convert string to bytes if needed
610
+ let buffer;
611
+ if (typeof data === 'string') {
612
+ buffer = new TextEncoder().encode(data);
613
+ }
614
+ else if (data instanceof Uint8Array) {
615
+ buffer = data;
616
+ }
617
+ else {
618
+ throw new Error('data must be either a string or Uint8Array');
619
+ }
620
+ // Create and use a temporary pipe for the data
621
+ const pipe = await this.pipe(token, objinfo, mimetype);
622
+ try {
623
+ await pipe.open();
624
+ await pipe.write(buffer);
625
+ return await pipe.close();
626
+ }
627
+ catch (error) {
628
+ // Clean up pipe on any error
629
+ if (pipe.isOpened) {
630
+ try {
631
+ await pipe.close();
632
+ }
633
+ catch {
634
+ // Ignore cleanup errors
635
+ }
636
+ }
637
+ throw error;
638
+ }
639
+ }
640
+ /**
641
+ * Upload multiple files to a pipeline with progress tracking and parallel execution.
642
+ *
643
+ * This method efficiently uploads files in parallel with configurable concurrency control.
644
+ * Each file is streamed through a data pipe, and progress events are emitted through the
645
+ * event system for all subscribers. The order of results matches the input file order.
646
+ *
647
+ * Progress events are sent through the event system as 'apaevt_status_upload' events
648
+ * (matching Python client behavior) rather than through a callback parameter.
649
+ *
650
+ * @param files - Array of file objects with optional metadata and MIME types
651
+ * @param token - Pipeline task token to receive the uploads
652
+ * @param maxConcurrent - Maximum number of concurrent uploads (default: 5)
653
+ *
654
+ * @returns Promise resolving to array of UPLOAD_RESULT objects in the same order as input
655
+ *
656
+ * @example
657
+ * ```typescript
658
+ * // Subscribe to upload events
659
+ * client.on('apaevt_status_upload', (event) => {
660
+ * console.log(`${event.body.filepath}: ${event.body.bytes_sent}/${event.body.file_size}`);
661
+ * });
662
+ *
663
+ * // Upload files
664
+ * const results = await client.sendFiles(
665
+ * [
666
+ * { file: fileObject1 },
667
+ * { file: fileObject2, mimetype: 'application/json' },
668
+ * { file: fileObject3, objinfo: { custom: 'metadata' } }
669
+ * ],
670
+ * 'task-token',
671
+ * 10 // Upload max 10 files concurrently
672
+ * );
673
+ * ```
674
+ */
675
+ async sendFiles(files, token, maxConcurrent = 5) {
676
+ const results = new Array(files.length);
677
+ /**
678
+ * Helper function to send upload events through the event system.
679
+ * This matches the Python implementation where events are emitted
680
+ * through the event system rather than callbacks.
681
+ */
682
+ const sendUploadEvent = (body) => {
683
+ const eventMessage = {
684
+ event: 'apaevt_status_upload',
685
+ body: body,
686
+ seq: 0,
687
+ type: 'event'
688
+ };
689
+ // Emit event through your event system
690
+ // Replace this with your actual event emission method
691
+ this.onEvent(eventMessage);
692
+ };
693
+ /**
694
+ * Upload a single file
695
+ */
696
+ const uploadFile = async (fileData, index) => {
697
+ const { file, objinfo = {}, mimetype } = fileData;
698
+ const startTime = Date.now();
699
+ let bytesUploaded = 0;
700
+ let pipe = null;
701
+ let error;
702
+ let result;
703
+ // Prepare objinfo with file metadata
704
+ const fullObjinfo = {
705
+ name: file.name,
706
+ size: file.size,
707
+ ...objinfo,
708
+ };
709
+ const finalMimetype = mimetype || file.type || 'application/octet-stream';
710
+ try {
711
+ const fileSize = file.size;
712
+ // Create and open pipe
713
+ pipe = await this.pipe(token, fullObjinfo, finalMimetype);
714
+ // Open the pipe
715
+ await pipe.open();
716
+ // Send upload start event (action: 'open')
717
+ sendUploadEvent({
718
+ action: 'open',
719
+ filepath: file.name,
720
+ bytes_sent: 0,
721
+ file_size: fileSize,
722
+ upload_time: 0,
723
+ });
724
+ // Upload file in chunks
725
+ const reader = file.stream().getReader();
726
+ try {
727
+ while (true) {
728
+ const { done, value } = await reader.read();
729
+ if (done)
730
+ break;
731
+ // Write chunk
732
+ await pipe.write(value);
733
+ bytesUploaded += value.length;
734
+ // Send progress event for every chunk (action: 'write')
735
+ sendUploadEvent({
736
+ action: 'write',
737
+ filepath: file.name,
738
+ bytes_sent: bytesUploaded,
739
+ file_size: fileSize,
740
+ upload_time: (Date.now() - startTime) / 1000,
741
+ });
742
+ }
743
+ }
744
+ finally {
745
+ reader.releaseLock();
746
+ }
747
+ // Send close event (action: 'close')
748
+ sendUploadEvent({
749
+ action: 'close',
750
+ filepath: file.name,
751
+ bytes_sent: bytesUploaded,
752
+ file_size: fileSize,
753
+ upload_time: (Date.now() - startTime) / 1000,
754
+ });
755
+ // Close pipe and get result
756
+ result = await pipe.close();
757
+ }
758
+ catch (err) {
759
+ error = err instanceof Error ? err.message : String(err);
760
+ }
761
+ // Create final result
762
+ const uploadTime = (Date.now() - startTime) / 1000;
763
+ const finalResult = {
764
+ action: error ? 'error' : 'complete',
765
+ filepath: file.name,
766
+ bytes_sent: bytesUploaded,
767
+ file_size: file.size,
768
+ upload_time: uploadTime,
769
+ result,
770
+ error,
771
+ };
772
+ // Send final result event (action: 'complete' or 'error')
773
+ sendUploadEvent(finalResult);
774
+ // Store result at the correct index
775
+ results[index] = finalResult;
776
+ };
777
+ // Execute uploads with concurrency limit
778
+ const executing = new Set();
779
+ for (let i = 0; i < files.length; i++) {
780
+ const uploadPromise = uploadFile(files[i], i).then(() => {
781
+ // Remove this promise from the executing set when done
782
+ executing.delete(uploadPromise);
783
+ }).catch(() => {
784
+ // Remove this promise from the executing set even on error
785
+ executing.delete(uploadPromise);
786
+ });
787
+ executing.add(uploadPromise);
788
+ // If we've reached max concurrency, wait for one to complete
789
+ if (executing.size >= maxConcurrent) {
790
+ await Promise.race(executing);
791
+ }
792
+ }
793
+ // Wait for all remaining uploads to complete
794
+ await Promise.all(Array.from(executing));
795
+ return results;
796
+ }
797
+ // ============================================================================
798
+ // CHAT METHODS
799
+ // ============================================================================
800
+ /**
801
+ * Ask a question to Aparavi's AI and get an intelligent response.
802
+ */
803
+ async chat(options) {
804
+ const { token, question } = options;
805
+ try {
806
+ // Validate that we have a question to ask
807
+ if (!question) {
808
+ throw new Error('Question cannot be empty');
809
+ }
810
+ // Create unique identifier for this chat operation
811
+ const objinfo = { name: `Question ${this._nextChatId}` };
812
+ this._nextChatId += 1;
813
+ // Create pipe instance
814
+ const pipe = new DataPipe(this, token, objinfo, 'application/aparavi-question', 'chat');
815
+ try {
816
+ // Open the communication channel to the AI
817
+ await pipe.open();
818
+ // Send the question as JSON data to the AI system
819
+ const questionJson = JSON.stringify(question.toDict());
820
+ const questionBytes = new TextEncoder().encode(questionJson);
821
+ await pipe.write(questionBytes);
822
+ // Close the pipe and get the AI's response
823
+ const result = await pipe.close();
824
+ // Check it
825
+ if (!result) {
826
+ throw new Error('No response received from AI');
827
+ }
828
+ // Return success response in standard format
829
+ return result;
830
+ }
831
+ finally {
832
+ // Ensure the pipe is properly closed even if errors occur
833
+ if (pipe.isOpened) {
834
+ try {
835
+ await pipe.close();
836
+ }
837
+ catch {
838
+ // Ignore errors during cleanup
839
+ }
840
+ }
841
+ }
842
+ }
843
+ catch (error) {
844
+ // Return error response in standard format
845
+ throw new Error(error instanceof Error ? error.message : String(error));
846
+ }
847
+ }
848
+ // ============================================================================
849
+ // EVENT METHODS
850
+ // ============================================================================
851
+ /**
852
+ * Send events to debugging interface if available (for development).
853
+ */
854
+ _sendVSCodeEvent(eventType, body) {
855
+ // Set up debugging integration on first use
856
+ if (!this._dapAttempted) {
857
+ this._dapAttempted = true;
858
+ try {
859
+ // In browser environment, check for debugging tools
860
+ if (typeof window !== 'undefined' && window.__APARAVI_DEBUG__) {
861
+ this._dapSend = window.__APARAVI_DEBUG__.sendEvent;
862
+ }
863
+ }
864
+ catch {
865
+ // Not in debugging environment - no problem
866
+ }
867
+ }
868
+ // Send event to debugger if available
869
+ if (this._dapSend) {
870
+ const customEvent = {
871
+ type: 'event',
872
+ event: eventType,
873
+ body: body,
874
+ };
875
+ this._dapSend(customEvent);
876
+ }
877
+ }
878
+ /**
879
+ * Handle incoming events from the Aparavi server.
880
+ */
881
+ async onEvent(message) {
882
+ // Extract event information
883
+ const eventType = message.event || 'unknown';
884
+ const eventBody = message.body || {};
885
+ const seqNum = message.seq || 0;
886
+ // Forward to debugging interface if available
887
+ this._sendVSCodeEvent(eventType, eventBody);
888
+ // Call user-provided event handler if available
889
+ if (this._callerOnEvent) {
890
+ try {
891
+ await this._callerOnEvent(message);
892
+ }
893
+ catch (error) {
894
+ // Log errors but don't let user code break the connection
895
+ this.debugMessage(`Error in user onEvent handler for ${eventType} (seq ${seqNum}): ${error}`);
896
+ }
897
+ }
898
+ }
899
+ /**
900
+ * Handle connected events from the Aparavi server.
901
+ */
902
+ async onConnected(connectionInfo) {
903
+ this._manualDisconnect = false;
904
+ this._clearReconnectTimeout();
905
+ // Call user-provided event handler if available
906
+ if (this._callerOnConnected) {
907
+ try {
908
+ await this._callerOnConnected(connectionInfo);
909
+ }
910
+ catch (error) {
911
+ // Log errors but don't let user code break the connection
912
+ this.debugMessage(`Error in user onConnected handler for ${connectionInfo}: ${error}`);
913
+ }
914
+ }
915
+ }
916
+ /**
917
+ * Handle disconnected events from the Aparavi server.
918
+ */
919
+ async onDisconnected(reason, hasError) {
920
+ // Call user-provided event handler if available
921
+ if (this._callerOnDisconnected) {
922
+ try {
923
+ await this._callerOnDisconnected(reason, hasError);
924
+ }
925
+ catch (error) {
926
+ // Log errors but don't let user code break the connection
927
+ this.debugMessage(`Error in user onDisconnected handler for ${reason}: ${error}`);
928
+ }
929
+ }
930
+ // Schedule reconnection if persist is enabled and not a manual disconnect
931
+ if (this._persist && !this._manualDisconnect) {
932
+ this._scheduleReconnect();
933
+ }
934
+ }
935
+ /**
936
+ * Subscribe to specific types of events from the server.
937
+ */
938
+ async setEvents(token, eventTypes) {
939
+ // Build event subscription request
940
+ const request = this.buildRequest('apaext_monitor', {
941
+ arguments: { types: eventTypes },
942
+ token,
943
+ });
944
+ // Send to server
945
+ const response = await this.request(request);
946
+ // Check for errors
947
+ if (this.didFail(response)) {
948
+ const errorMsg = response.message || 'Event subscription failed';
949
+ throw new Error(errorMsg);
950
+ }
951
+ }
952
+ // ============================================================================
953
+ // CONTEXT MANAGER SUPPORT - Python-style async context manager
954
+ // ============================================================================
955
+ /**
956
+ * Async disposal support for 'await using' pattern.
957
+ * Equivalent to Python's __aexit__
958
+ */
959
+ async [Symbol.asyncDispose]() {
960
+ await this.disconnect();
961
+ }
962
+ /**
963
+ * Static factory method for automatic connection management.
964
+ * Equivalent to Python's async with pattern
965
+ */
966
+ static async withConnection(config, callback) {
967
+ const client = new AparaviClient(config);
968
+ try {
969
+ await client.connect();
970
+ return await callback(client);
971
+ }
972
+ finally {
973
+ await client.disconnect();
974
+ }
975
+ }
976
+ // ============================================================================
977
+ // ADDITIONAL CONVENIENCE METHODS
978
+ // ============================================================================
979
+ /**
980
+ * Get connection information (TypeScript-specific convenience)
981
+ */
982
+ getConnectionInfo() {
983
+ return {
984
+ connected: this.isConnected(),
985
+ transport: 'WebSocket',
986
+ uri: this._uri,
987
+ };
988
+ }
989
+ /**
990
+ * Get API key (for debugging/validation)
991
+ */
992
+ getApiKey() {
993
+ return this._apikey;
994
+ }
995
+ }
996
+ export { AparaviClient as default };
997
+ //# sourceMappingURL=client.js.map