@kinotic-ai/core 5.0.0-beta.3 → 5.0.0-beta.31

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/dist/index.cjs CHANGED
@@ -19,13 +19,15 @@ var __toESM = (mod, isNodeMode, target) => {
19
19
  return cached;
20
20
  }
21
21
  target = mod != null ? __create(__getProtoOf(mod)) : {};
22
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
- for (let key of __getOwnPropNames(mod))
24
- if (!__hasOwnProp.call(to, key))
25
- __defProp(to, key, {
26
- get: __accessProp.bind(mod, key),
27
- enumerable: true
28
- });
22
+ const to = isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
+ if (mod && typeof mod === "object" || typeof mod === "function") {
24
+ for (let key of __getOwnPropNames(mod))
25
+ if (!__hasOwnProp.call(to, key))
26
+ __defProp(to, key, {
27
+ get: __accessProp.bind(mod, key),
28
+ enumerable: true
29
+ });
30
+ }
29
31
  if (canCache)
30
32
  cache.set(mod, to);
31
33
  return to;
@@ -64,48 +66,55 @@ var __export = (target, all) => {
64
66
  // packages/core/src/index.ts
65
67
  var exports_src = {};
66
68
  __export(exports_src, {
67
- validateZone: () => validateZone,
68
- validateLabel: () => validateLabel,
69
- receivesContext: () => receivesContext,
70
- isAdvertised: () => isAdvertised,
71
- createCRI: () => createCRI,
72
- buildServerUrl: () => buildServerUrl,
73
- buildBrokerUrl: () => buildBrokerUrl,
74
- Zone: () => Zone,
75
- Version: () => Version,
76
- TextEventFactory: () => TextEventFactory,
77
- Sort: () => Sort,
78
- SessionKeepAliveMode: () => SessionKeepAliveMode,
79
- SessionCredentialsResolver: () => SessionCredentialsResolver,
80
- ServiceRegistry: () => ServiceRegistry,
81
- ServerInfo: () => ServerInfo,
82
- Scope: () => Scope,
83
- Publish: () => Publish,
84
- ParticipantConstants: () => ParticipantConstants,
85
- Pageable: () => Pageable,
86
- Order: () => Order,
87
- OffsetPageable: () => OffsetPageable,
88
- NullHandling: () => NullHandling,
89
- KinoticSingleton: () => KinoticSingleton,
90
- Kinotic: () => Kinotic,
91
- JsonEventFactory: () => JsonEventFactory,
92
- FunctionalIterablePage: () => FunctionalIterablePage,
93
- EventConstants: () => EventConstants,
94
- EventBus: () => EventBus,
95
- Event: () => Event,
96
- EnvCredentialsResolver: () => EnvCredentialsResolver,
97
- Direction: () => Direction,
98
- DefaultCRI: () => DefaultCRI,
99
- DataSourceUtils: () => DataSourceUtils,
100
- CursorPageable: () => CursorPageable,
101
- CrudServiceProxyFactory: () => CrudServiceProxyFactory,
102
- CrudServiceProxy: () => CrudServiceProxy,
103
- Context: () => Context,
104
- ConnectedInfo: () => ConnectedInfo,
105
- ChainedCredentialsResolver: () => ChainedCredentialsResolver,
106
- BearerCredentialsResolver: () => BearerCredentialsResolver,
69
+ AbstractIterablePage: () => AbstractIterablePage,
70
+ AuthorizationException: () => AuthorizationException,
107
71
  BasicCredentialsResolver: () => BasicCredentialsResolver,
108
- AbstractIterablePage: () => AbstractIterablePage
72
+ BearerCredentialsResolver: () => BearerCredentialsResolver,
73
+ ChainedCredentialsResolver: () => ChainedCredentialsResolver,
74
+ ConnectedInfo: () => ConnectedInfo,
75
+ Context: () => Context,
76
+ CrudServiceProxy: () => CrudServiceProxy,
77
+ CrudServiceProxyFactory: () => CrudServiceProxyFactory,
78
+ CursorPageable: () => CursorPageable,
79
+ DataSourceUtils: () => DataSourceUtils,
80
+ DefaultCRI: () => DefaultCRI,
81
+ Direction: () => Direction,
82
+ EnvCredentialsResolver: () => EnvCredentialsResolver,
83
+ Event: () => Event,
84
+ EventBus: () => EventBus,
85
+ EventConstants: () => EventConstants,
86
+ FunctionalIterablePage: () => FunctionalIterablePage,
87
+ JsonEventFactory: () => JsonEventFactory,
88
+ Kinotic: () => Kinotic,
89
+ KinoticSingleton: () => KinoticSingleton,
90
+ NullHandling: () => NullHandling,
91
+ OffsetPageable: () => OffsetPageable,
92
+ Order: () => Order,
93
+ Pageable: () => Pageable,
94
+ ParticipantConstants: () => ParticipantConstants,
95
+ Publish: () => Publish,
96
+ RpcError: () => RpcError,
97
+ Scope: () => Scope,
98
+ ScopeOptional: () => ScopeOptional,
99
+ ServerInfo: () => ServerInfo,
100
+ ServiceIdentifier: () => ServiceIdentifier,
101
+ ServiceRegistry: () => ServiceRegistry,
102
+ SessionCredentialsResolver: () => SessionCredentialsResolver,
103
+ SessionEndType: () => SessionEndType,
104
+ SessionKeepAliveMode: () => SessionKeepAliveMode,
105
+ Sort: () => Sort,
106
+ TextEventFactory: () => TextEventFactory,
107
+ Version: () => Version,
108
+ Zone: () => Zone,
109
+ buildBrokerUrl: () => buildBrokerUrl,
110
+ buildServerUrl: () => buildServerUrl,
111
+ createCRI: () => createCRI,
112
+ declareServiceDefinitions: () => declareServiceDefinitions,
113
+ isAdvertised: () => isAdvertised,
114
+ receivesContext: () => receivesContext,
115
+ scopeOptionalMethodNames: () => scopeOptionalMethodNames,
116
+ validateLabel: () => validateLabel,
117
+ validateZone: () => validateZone
109
118
  });
110
119
  module.exports = __toCommonJS(exports_src);
111
120
 
@@ -116,103 +125,205 @@ class ServerInfo {
116
125
  useSSL;
117
126
  }
118
127
  function buildServerUrl(server, scheme) {
119
- return scheme + (server.useSSL ? "s" : "") + "://" + server.host + (server.port ? ":" + server.port : "");
128
+ const host = server.host.includes(":") && !server.host.startsWith("[") ? "[" + server.host + "]" : server.host;
129
+ return scheme + (server.useSSL ? "s" : "") + "://" + host + (server.port ? ":" + server.port : "");
120
130
  }
121
131
  function buildBrokerUrl(server) {
122
- return buildServerUrl(server, "ws") + "/v1";
132
+ return buildServerUrl(server, "ws") + "/api/v1";
123
133
  }
124
134
  var SessionKeepAliveMode;
125
- ((SessionKeepAliveMode2) => {
126
- SessionKeepAliveMode2["NONE"] = "NONE";
127
- SessionKeepAliveMode2["ACTIVITY"] = "ACTIVITY";
128
- SessionKeepAliveMode2["CONNECTION"] = "CONNECTION";
135
+ ((SessionKeepAliveMode) => {
136
+ SessionKeepAliveMode["NONE"] = "NONE";
137
+ SessionKeepAliveMode["ACTIVITY"] = "ACTIVITY";
138
+ SessionKeepAliveMode["CONNECTION"] = "CONNECTION";
129
139
  })(SessionKeepAliveMode ||= {});
130
140
  // packages/core/src/api/event/IEventBus.ts
131
141
  var EventConstants;
132
- ((EventConstants2) => {
133
- EventConstants2["CONTENT_TYPE_HEADER"] = "content-type";
134
- EventConstants2["CONTENT_LENGTH_HEADER"] = "content-length";
135
- EventConstants2["REPLY_TO_HEADER"] = "reply-to";
136
- EventConstants2["CONNECTED_INFO_HEADER"] = "connected-info";
137
- EventConstants2["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
138
- EventConstants2["CORRELATION_ID_HEADER"] = "__correlation-id";
139
- EventConstants2["ORIGIN_CRI_HEADER"] = "__origin-cri";
140
- EventConstants2["ERROR_HEADER"] = "error";
141
- EventConstants2["COMPLETE_HEADER"] = "complete";
142
- EventConstants2["CONTROL_HEADER"] = "control";
143
- EventConstants2["CONTROL_VALUE_COMPLETE"] = "complete";
144
- EventConstants2["CONTROL_VALUE_CANCEL"] = "cancel";
145
- EventConstants2["CONTROL_VALUE_SUSPEND"] = "suspend";
146
- EventConstants2["CONTROL_VALUE_RESUME"] = "resume";
147
- EventConstants2["SERVICE_DESTINATION_PREFIX"] = "srv://";
148
- EventConstants2["SERVICE_DESTINATION_SCHEME"] = "srv";
149
- EventConstants2["STREAM_DESTINATION_PREFIX"] = "stream://";
150
- EventConstants2["STREAM_DESTINATION_SCHEME"] = "stream";
151
- EventConstants2["REPLY_DESTINATION_PREFIX"] = "reply://";
152
- EventConstants2["REPLY_DESTINATION_SCHEME"] = "reply";
153
- EventConstants2["CONTENT_JSON"] = "application/json";
154
- EventConstants2["CONTENT_TEXT"] = "text/plain";
155
- EventConstants2["CONTENT_OCTET_STREAM"] = "application/octet-stream";
156
- EventConstants2["TRACEPARENT_HEADER"] = "traceparent";
157
- EventConstants2["TRACESTATE_HEADER"] = "tracestate";
142
+ ((EventConstants) => {
143
+ EventConstants["CONTENT_TYPE_HEADER"] = "content-type";
144
+ EventConstants["CONTENT_LENGTH_HEADER"] = "content-length";
145
+ EventConstants["REPLY_TO_HEADER"] = "reply-to";
146
+ EventConstants["SENDER_HEADER"] = "sender";
147
+ EventConstants["CONNECTED_INFO_HEADER"] = "connected-info";
148
+ EventConstants["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
149
+ EventConstants["CORRELATION_ID_HEADER"] = "__correlation-id";
150
+ EventConstants["ORIGIN_CRI_HEADER"] = "__origin-cri";
151
+ EventConstants["ERROR_HEADER"] = "error";
152
+ EventConstants["COMPLETE_HEADER"] = "complete";
153
+ EventConstants["CONTROL_HEADER"] = "control";
154
+ EventConstants["CONTROL_VALUE_COMPLETE"] = "complete";
155
+ EventConstants["CONTROL_VALUE_CANCEL"] = "cancel";
156
+ EventConstants["CONTROL_VALUE_SUSPEND"] = "suspend";
157
+ EventConstants["CONTROL_VALUE_RESUME"] = "resume";
158
+ EventConstants["SERVICE_DESTINATION_PREFIX"] = "srv://";
159
+ EventConstants["SERVICE_DESTINATION_SCHEME"] = "srv";
160
+ EventConstants["STREAM_DESTINATION_PREFIX"] = "stream://";
161
+ EventConstants["STREAM_DESTINATION_SCHEME"] = "stream";
162
+ EventConstants["REPLY_DESTINATION_PREFIX"] = "reply://";
163
+ EventConstants["REPLY_DESTINATION_SCHEME"] = "reply";
164
+ EventConstants["CONTENT_JSON"] = "application/json";
165
+ EventConstants["CONTENT_TEXT"] = "text/plain";
166
+ EventConstants["CONTENT_OCTET_STREAM"] = "application/octet-stream";
167
+ EventConstants["TRACEPARENT_HEADER"] = "traceparent";
168
+ EventConstants["TRACESTATE_HEADER"] = "tracestate";
158
169
  })(EventConstants ||= {});
159
170
 
171
+ // packages/core/src/internal/api/Logger.ts
172
+ var import_debug = __toESM(require("debug"), 1);
173
+ function createDebugLogger(namespace) {
174
+ const debugLogger = import_debug.default(namespace);
175
+ return {
176
+ trace: (...args) => debugLogger("TRACE", ...args),
177
+ debug: (...args) => debugLogger("DEBUG", ...args),
178
+ info: (...args) => debugLogger("INFO", ...args),
179
+ warn: (...args) => debugLogger("WARN", ...args),
180
+ error: (...args) => debugLogger("ERROR", ...args)
181
+ };
182
+ }
183
+
160
184
  // packages/core/src/internal/api/StompConnectionManager.ts
161
185
  var import_rx_stomp = require("@stomp/rx-stomp");
162
186
  var import_stompjs = require("@stomp/stompjs");
163
- var import_debug = __toESM(require("debug"));
187
+ var import_debug2 = __toESM(require("debug"), 1);
164
188
  var import_rxjs = require("rxjs");
189
+ var import_operators = require("rxjs/operators");
165
190
  var import_uuid = require("uuid");
191
+
192
+ // packages/core/src/internal/api/SessionRoutes.ts
166
193
  var SESSION_CHECK_PATH = "/api/auth/me";
194
+ var LOGOUT_PATH = "/api/auth/logout";
195
+ async function holdsLogin(server, signal) {
196
+ const response = await fetch(buildServerUrl(server, "http") + SESSION_CHECK_PATH, { credentials: "include", signal });
197
+ return response.status !== 401;
198
+ }
199
+ async function endLogin(server, signal) {
200
+ await fetch(buildServerUrl(server, "http") + LOGOUT_PATH, { method: "POST", credentials: "include", signal });
201
+ }
167
202
 
203
+ // packages/core/src/internal/api/StompActivation.ts
204
+ class StompActivation {
205
+ _ended = false;
206
+ wake = null;
207
+ preparedSocket = null;
208
+ attempt = null;
209
+ failPending = null;
210
+ abortController = new AbortController;
211
+ subscriptions = [];
212
+ get ended() {
213
+ return this._ended;
214
+ }
215
+ get signal() {
216
+ return this.abortController.signal;
217
+ }
218
+ end() {
219
+ this._ended = true;
220
+ this.wake?.();
221
+ this.wake = null;
222
+ this.abortController.abort();
223
+ }
224
+ delay(ms) {
225
+ return new Promise((resolve) => {
226
+ const timer = setTimeout(() => {
227
+ this.wake = null;
228
+ resolve();
229
+ }, ms);
230
+ this.wake = () => {
231
+ clearTimeout(timer);
232
+ resolve();
233
+ };
234
+ });
235
+ }
236
+ own(subscription) {
237
+ this.subscriptions.push(subscription);
238
+ }
239
+ pending(fail) {
240
+ this.failPending = fail;
241
+ }
242
+ established() {
243
+ this.failPending = null;
244
+ }
245
+ failIfPending(reason) {
246
+ const fail = this.failPending;
247
+ this.failPending = null;
248
+ fail?.(reason);
249
+ }
250
+ unsubscribeAll() {
251
+ for (const subscription of this.subscriptions) {
252
+ subscription.unsubscribe();
253
+ }
254
+ this.subscriptions.length = 0;
255
+ }
256
+ }
257
+
258
+ // packages/core/src/internal/api/StompConnectionManager.ts
168
259
  class StompConnectionManager {
169
260
  lastWebsocketError = null;
170
261
  maxConnectionAttemptsReached = false;
171
- replyToCriChangedHandler = null;
172
- rxStomp = null;
262
+ connectionEndedHandler = null;
263
+ rxStomp = new import_rx_stomp.RxStomp;
264
+ activation = null;
265
+ teardown = null;
173
266
  INITIAL_RECONNECT_DELAY = 2000;
174
267
  JITTER_MAX = 5000;
175
268
  MAX_RECONNECT_DELAY = 120000;
269
+ CONNECTION_TIMEOUT = 1e4;
176
270
  connectionAttempts = 0;
177
- debugLogger = import_debug.default("kinoitc:stomp");
178
- fatalErrorsSubject = new import_rxjs.Subject;
179
- _fatalErrors = this.fatalErrorsSubject.asObservable();
271
+ debugLogger = import_debug2.default("kinotic:stomp");
272
+ connectionEstablishedSubject = new import_rxjs.Subject;
273
+ connectionAttemptFailedSubject = new import_rxjs.Subject;
180
274
  initialConnectionSuccessful = false;
181
- serverHeadersSubscription = null;
182
- stompErrorsSubscription = null;
183
- uuidv4 = import_uuid.v4();
275
+ rxStompHasConnected = false;
184
276
  _replyToCri = null;
185
277
  get replyToCri() {
186
278
  return this._replyToCri;
187
279
  }
188
280
  get active() {
189
- return !!this.rxStomp;
281
+ return this.activation !== null;
190
282
  }
191
283
  get connected() {
192
- return this.rxStomp != null && this.rxStomp.connected();
284
+ return this.activation !== null && this.rxStomp.connected();
193
285
  }
194
- get fatalErrors() {
195
- return this._fatalErrors;
286
+ get connectionEstablished() {
287
+ return this.connectionEstablishedSubject.asObservable();
288
+ }
289
+ get connectionAttemptFailed() {
290
+ return this.connectionAttemptFailedSubject.asObservable();
196
291
  }
197
292
  async activate(options) {
198
293
  if (!options?.server?.host) {
199
294
  throw new Error("No host provided");
200
295
  }
201
- if (this.rxStomp) {
296
+ if (this.activation) {
297
+ throw new Error("Stomp connection already active");
298
+ }
299
+ await this.teardown;
300
+ if (this.activation) {
202
301
  throw new Error("Stomp connection already active");
203
302
  }
204
303
  const server = options.server;
205
304
  const credentialsResolver = options.credentials;
305
+ const activation = new StompActivation;
306
+ this.activation = activation;
206
307
  let headerAuth = false;
207
- if (!options.webSocketFactory) {
208
- if (!credentialsResolver) {
209
- throw new Error("No credentials supplied and no default resolution applied");
308
+ try {
309
+ if (!options.webSocketFactory) {
310
+ if (!credentialsResolver) {
311
+ throw new Error("No credentials supplied and no default resolution applied");
312
+ }
313
+ const resolved = await credentialsResolver.resolve(server);
314
+ if (resolved === null) {
315
+ throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
316
+ }
317
+ headerAuth = resolved.authHeaders != null;
210
318
  }
211
- const resolved = await credentialsResolver.resolve(server);
212
- if (resolved === null) {
213
- throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
319
+ if (activation.ended) {
320
+ throw new Error("Deactivated before the connection was established");
214
321
  }
215
- headerAuth = resolved.authHeaders != null;
322
+ } catch (e) {
323
+ if (this.activation === activation) {
324
+ this.activation = null;
325
+ }
326
+ throw e;
216
327
  }
217
328
  return new Promise((resolve, reject) => {
218
329
  this.connectionAttempts = 0;
@@ -220,63 +331,29 @@ class StompConnectionManager {
220
331
  this.lastWebsocketError = null;
221
332
  this.maxConnectionAttemptsReached = false;
222
333
  const url = buildBrokerUrl(server);
223
- this.rxStomp = new import_rx_stomp.RxStomp;
224
- let preparedSocket = null;
225
- const userWebSocketFactory = options.webSocketFactory;
226
- const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
334
+ const usesPreparedSocket = options.webSocketFactory != null || headerAuth;
335
+ const takePreparedSocket = () => {
336
+ const socket = activation.preparedSocket;
337
+ activation.preparedSocket = null;
338
+ return socket;
339
+ };
227
340
  const stompConfig = {
228
341
  brokerURL: url,
229
342
  connectHeaders: {
230
343
  ["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: options.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */
231
344
  },
232
- heartbeatIncoming: 120000,
345
+ heartbeatIncoming: 30000,
233
346
  heartbeatOutgoing: 30000,
347
+ connectionTimeout: this.CONNECTION_TIMEOUT,
234
348
  reconnectDelay: this.INITIAL_RECONNECT_DELAY,
235
349
  maxReconnectDelay: this.MAX_RECONNECT_DELAY,
236
350
  reconnectTimeMode: import_stompjs.ReconnectionTimeMode.EXPONENTIAL,
237
- webSocketFactory: usesPreparedSocket ? () => preparedSocket : undefined,
238
- beforeConnect: async () => {
239
- if (!usesPreparedSocket) {
240
- const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
241
- try {
242
- const res = await fetch(sessionCheckUrl, { credentials: "include" });
243
- if (res.status === 401) {
244
- await this.signalFatal(new Error("Authentication required"));
245
- return;
246
- }
247
- } catch {}
248
- }
249
- if (options?.maxConnectionAttempts) {
250
- this.connectionAttempts++;
251
- if (this.connectionAttempts > options.maxConnectionAttempts) {
252
- this.maxConnectionAttemptsReached = true;
253
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
254
- return;
255
- } else {
256
- await this.connectionJitterDelay();
257
- }
258
- } else {
259
- await this.connectionJitterDelay();
260
- }
261
- if (userWebSocketFactory) {
262
- try {
263
- preparedSocket = await userWebSocketFactory();
264
- } catch (e) {
265
- await this.signalFatal(new Error("WebSocket factory failed", { cause: e }));
266
- }
267
- } else if (headerAuth) {
268
- try {
269
- const resolved = await credentialsResolver.resolve(server);
270
- if (resolved?.authHeaders == null) {
271
- await this.signalFatal(new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
272
- } else {
273
- const WS = WebSocket;
274
- preparedSocket = new WS(url, { headers: resolved.authHeaders });
275
- }
276
- } catch (e) {
277
- await this.signalFatal(new Error("Credential resolution failed", { cause: e }));
278
- }
279
- }
351
+ webSocketFactory: usesPreparedSocket ? takePreparedSocket : undefined,
352
+ beforeConnect: () => {
353
+ const attempt = this.prepareAttempt(activation, options, server, headerAuth);
354
+ const settled = () => new Promise((resolve) => setTimeout(resolve, 0));
355
+ activation.attempt = attempt.then(settled, settled);
356
+ return attempt;
280
357
  }
281
358
  };
282
359
  if (this.debugLogger.enabled) {
@@ -285,93 +362,205 @@ class StompConnectionManager {
285
362
  };
286
363
  }
287
364
  this.rxStomp.configure(stompConfig);
288
- this.rxStomp.webSocketErrors$.subscribe(async (value) => {
365
+ activation.own(this.rxStomp.webSocketErrors$.subscribe((value) => {
289
366
  this.lastWebsocketError = value;
290
- if (options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
291
- this.maxConnectionAttemptsReached = true;
292
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
293
- }
294
- });
295
- this.stompErrorsSubscription = this.rxStomp.stompErrors$.subscribe(async (frame) => {
367
+ }));
368
+ activation.own(this.rxStomp.stompErrors$.subscribe((frame) => {
296
369
  const stompError = new Error(frame.headers["message"], { cause: frame });
297
- await this.signalFatal(new Error("STOMP connection error", { cause: stompError }));
298
- });
299
- const connectedSubscription = this.rxStomp.connected$.subscribe(() => {
300
- connectedSubscription.unsubscribe();
301
- initialFailureSubscription.unsubscribe();
302
- if (!this.initialConnectionSuccessful) {
303
- this.initialConnectionSuccessful = true;
304
- }
305
- });
306
- const initialFailureSubscription = this.fatalErrorsSubject.subscribe((err) => {
307
- connectedSubscription.unsubscribe();
308
- initialFailureSubscription.unsubscribe();
309
- reject(err.message);
310
- });
311
- this.serverHeadersSubscription = this.rxStomp.serverHeaders$.subscribe(async (value) => {
370
+ this.failConnection(activation, new Error("STOMP connection error", { cause: stompError }));
371
+ }));
372
+ activation.own(this.rxStomp.connected$.subscribe(() => {
373
+ activation.established();
374
+ this.initialConnectionSuccessful = true;
375
+ this.connectionAttempts = 0;
376
+ }));
377
+ activation.pending(reject);
378
+ activation.own(this.rxStomp.serverHeaders$.pipe(import_operators.skip(this.rxStompHasConnected ? 1 : 0)).subscribe((value) => {
379
+ this.rxStompHasConnected = true;
312
380
  const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
313
381
  if (connectedInfoJson == null) {
314
382
  if (!this.initialConnectionSuccessful) {
315
- await this.deactivate();
316
- reject("Server did not return proper data for successful login");
383
+ this.failConnection(activation, new Error("Server did not return proper data for successful login"));
317
384
  }
318
385
  return;
319
386
  }
320
387
  const connectedInfo = JSON.parse(connectedInfoJson);
321
388
  if (connectedInfo.replyToId == null) {
322
389
  if (!this.initialConnectionSuccessful) {
323
- await this.deactivate();
324
- reject("Server did not return a replyToId for successful login");
390
+ this.failConnection(activation, new Error("Server did not return a replyToId for successful login"));
325
391
  }
326
392
  return;
327
393
  }
328
- const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + this.uuidv4 + "@kinoitc.js.EventBus/replyHandler";
394
+ const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + import_uuid.v4() + "@kinotic.js.EventBus/replyHandler";
395
+ this._replyToCri = newReplyToCri;
329
396
  if (!this.initialConnectionSuccessful) {
330
- this._replyToCri = newReplyToCri;
331
397
  resolve(connectedInfo);
332
- } else if (this._replyToCri !== newReplyToCri) {
333
- this._replyToCri = newReplyToCri;
334
- this.replyToCriChangedHandler?.(newReplyToCri);
335
398
  }
336
- });
399
+ this.connectionEstablishedSubject.next(connectedInfo);
400
+ }));
401
+ let previousState = this.rxStomp.connectionState$.getValue();
402
+ activation.own(this.rxStomp.connectionState$.subscribe((state) => {
403
+ if (state === import_rx_stomp.RxStompState.CLOSED && this.activation === activation) {
404
+ if (previousState === import_rx_stomp.RxStompState.OPEN) {
405
+ this.connectionEndedHandler?.(null);
406
+ } else if (previousState === import_rx_stomp.RxStompState.CONNECTING) {
407
+ if (options.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
408
+ this.maxConnectionAttemptsReached = true;
409
+ this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
410
+ } else {
411
+ this.connectionAttemptFailedSubject.next();
412
+ }
413
+ }
414
+ }
415
+ previousState = state;
416
+ }));
337
417
  this.rxStomp.activate();
338
418
  });
339
419
  }
340
- async deactivate(force) {
341
- const rxStomp = this.rxStomp;
342
- if (rxStomp) {
343
- await rxStomp.deactivate({ force });
344
- if (this.rxStomp === rxStomp) {
345
- this.serverHeadersSubscription?.unsubscribe();
346
- this.serverHeadersSubscription = null;
347
- this.stompErrorsSubscription?.unsubscribe();
348
- this.stompErrorsSubscription = null;
349
- this.rxStomp = null;
350
- this._replyToCri = null;
420
+ async prepareAttempt(activation, options, server, headerAuth) {
421
+ const credentialsResolver = options.credentials;
422
+ const userWebSocketFactory = options.webSocketFactory;
423
+ const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
424
+ const url = buildBrokerUrl(server);
425
+ if (!usesPreparedSocket) {
426
+ try {
427
+ const signedIn = await holdsLogin(server, AbortSignal.any([activation.signal, AbortSignal.timeout(this.CONNECTION_TIMEOUT)]));
428
+ if (!signedIn) {
429
+ this.failConnection(activation, new Error("Authentication required"));
430
+ return;
431
+ }
432
+ } catch (e) {
433
+ this.debugLogger("Session check of %s failed: %O", server.host, e);
434
+ }
435
+ }
436
+ if (options?.maxConnectionAttempts) {
437
+ this.connectionAttempts++;
438
+ }
439
+ await this.connectionJitterDelay(activation);
440
+ if (activation.ended) {
441
+ return;
442
+ }
443
+ if (userWebSocketFactory) {
444
+ try {
445
+ activation.preparedSocket = await userWebSocketFactory();
446
+ } catch (e) {
447
+ this.failConnection(activation, new Error("WebSocket factory failed", { cause: e }));
448
+ }
449
+ } else if (headerAuth) {
450
+ try {
451
+ const resolved = await credentialsResolver.resolve(server);
452
+ if (resolved?.authHeaders == null) {
453
+ this.failConnection(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
454
+ } else {
455
+ const WS = WebSocket;
456
+ const socket = new WS(url, { headers: resolved.authHeaders });
457
+ this.endOnRejectedUpgrade(activation, socket);
458
+ activation.preparedSocket = socket;
459
+ }
460
+ } catch (e) {
461
+ this.failConnection(activation, new Error("Credential resolution failed", { cause: e }));
351
462
  }
352
463
  }
353
- return;
464
+ if (activation.ended && activation.preparedSocket) {
465
+ activation.preparedSocket.close();
466
+ activation.preparedSocket = null;
467
+ }
468
+ }
469
+ endOnRejectedUpgrade(activation, socket) {
470
+ const emitter = socket;
471
+ if (typeof emitter.on === "function") {
472
+ emitter.on("unexpected-response", (_request, response) => {
473
+ const status = response.statusCode ?? 0;
474
+ if (status >= 400 && status < 500) {
475
+ this.failConnection(activation, new Error("Connection rejected with status " + status));
476
+ }
477
+ socket.close();
478
+ });
479
+ }
480
+ }
481
+ deactivate(force, reason = null) {
482
+ const activation = this.activation;
483
+ let ret;
484
+ if (activation) {
485
+ this.activation = null;
486
+ activation.end();
487
+ const wasOpen = this.rxStomp.connected();
488
+ this._replyToCri = null;
489
+ activation.failIfPending(reason ?? new Error("Deactivated before the connection was established"));
490
+ activation.preparedSocket?.close();
491
+ activation.preparedSocket = null;
492
+ const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
493
+ activation.unsubscribeAll();
494
+ this.teardown = null;
495
+ });
496
+ this.teardown = teardown;
497
+ if (wasOpen || reason !== null) {
498
+ this.connectionEndedHandler?.(reason);
499
+ }
500
+ ret = teardown;
501
+ } else {
502
+ ret = this.teardown ?? Promise.resolve();
503
+ }
504
+ return ret;
354
505
  }
355
- async connectionJitterDelay() {
506
+ async connectionJitterDelay(activation) {
356
507
  if (this.initialConnectionSuccessful) {
357
508
  const randomJitter = Math.random() * this.JITTER_MAX;
358
509
  this.debugLogger(`Adding ${randomJitter}ms of jitter delay`);
359
- return new Promise((resolve) => setTimeout(resolve, randomJitter));
510
+ await activation.delay(randomJitter);
360
511
  }
361
512
  }
362
- async signalFatal(err) {
363
- this.debugLogger("Fatal error, deactivating connection: %O", err);
364
- await this.deactivate();
365
- this.fatalErrorsSubject.next(err);
513
+ failConnection(activation, err) {
514
+ if (!activation.ended) {
515
+ this.debugLogger("Connection failed, ending it: %O", err);
516
+ this.deactivate(undefined, err).catch((e) => this.debugLogger("Closing the failed connection failed: %O", e));
517
+ }
366
518
  }
367
519
  }
368
520
 
369
521
  // packages/core/src/api/event/EventBus.ts
370
522
  var import_api = require("@opentelemetry/api");
371
523
  var import_rxjs2 = require("rxjs");
372
- var import_operators = require("rxjs/operators");
524
+ var import_operators2 = require("rxjs/operators");
373
525
  var import_typescript_optional = require("typescript-optional");
374
526
  var import_uuid2 = require("uuid");
527
+
528
+ // packages/core/src/api/event/RpcError.ts
529
+ class RpcError extends Error {
530
+ exceptionName;
531
+ exceptionClass;
532
+ constructor(message, exceptionName, exceptionClass) {
533
+ super(message);
534
+ this.name = "RpcError";
535
+ this.exceptionName = exceptionName;
536
+ this.exceptionClass = exceptionClass;
537
+ }
538
+ static fromEvent(reply) {
539
+ const message = reply.getHeader("error" /* ERROR_HEADER */) ?? "";
540
+ let ret;
541
+ const detail = describedException(reply);
542
+ if (detail !== undefined) {
543
+ ret = new RpcError(detail.errorMessage ?? message, detail.exceptionName ?? "", detail.exceptionClass ?? "");
544
+ } else {
545
+ ret = new RpcError(message, "", "");
546
+ }
547
+ return ret;
548
+ }
549
+ }
550
+ function describedException(reply) {
551
+ let ret = undefined;
552
+ if (reply.data.isPresent() && reply.getHeader("content-type" /* CONTENT_TYPE_HEADER */)?.startsWith("application/json")) {
553
+ try {
554
+ const parsed = JSON.parse(reply.getDataString());
555
+ if (parsed !== null && typeof parsed === "object") {
556
+ ret = parsed;
557
+ }
558
+ } catch {}
559
+ }
560
+ return ret;
561
+ }
562
+
563
+ // packages/core/src/api/event/EventBus.ts
375
564
  class Event {
376
565
  cri;
377
566
  headers;
@@ -410,24 +599,34 @@ class Event {
410
599
 
411
600
  class EventBus {
412
601
  serverInfo = null;
602
+ log = createDebugLogger("kinotic:EventBus");
413
603
  stompConnectionManager = new StompConnectionManager;
414
604
  connectionLifecycle = Promise.resolve();
415
- replyToCri = null;
605
+ disconnectRequests = 0;
416
606
  requestRepliesObservable = null;
417
607
  requestRepliesSubject = null;
418
608
  requestRepliesSubscription = null;
419
609
  activeCorrelationIds = new Set;
420
610
  recentlyReaped = new Set;
611
+ connectionEndedSubject = new import_rxjs2.Subject;
421
612
  static REAP_DEBOUNCE_MS = 5000;
422
613
  constructor() {
423
- this.stompConnectionManager.fatalErrors.subscribe(() => this.cleanup());
424
- this.stompConnectionManager.replyToCriChangedHandler = (replyToCri) => {
425
- this.replyToCri = replyToCri;
426
- this.resetRequestReplies("Reply destination changed");
614
+ this.stompConnectionManager.connectionEndedHandler = (reason) => {
615
+ this.resetRequestReplies("Connection lost");
616
+ if (!this.stompConnectionManager.active) {
617
+ this.serverInfo = null;
618
+ }
619
+ this.connectionEndedSubject.next(reason);
427
620
  };
428
621
  }
429
- get fatalErrors() {
430
- return this.stompConnectionManager.fatalErrors;
622
+ get connectionEnded() {
623
+ return this.connectionEndedSubject.asObservable();
624
+ }
625
+ get connectionEstablished() {
626
+ return this.stompConnectionManager.connectionEstablished;
627
+ }
628
+ get connectionAttemptFailed() {
629
+ return this.stompConnectionManager.connectionAttemptFailed;
431
630
  }
432
631
  isConnectionActive() {
433
632
  return this.stompConnectionManager.active;
@@ -436,12 +635,14 @@ class EventBus {
436
635
  return this.stompConnectionManager.connected;
437
636
  }
438
637
  connect(options) {
638
+ const disconnectsWhenQueued = this.disconnectRequests;
439
639
  return this.serializeLifecycle(async () => {
640
+ if (this.disconnectRequests !== disconnectsWhenQueued) {
641
+ throw new Error("Disconnected before the connection was started");
642
+ }
440
643
  if (!this.stompConnectionManager.active) {
441
- this.cleanup();
442
644
  const connectedInfo = await this.stompConnectionManager.activate(options);
443
645
  this.serverInfo = { ...options.server };
444
- this.replyToCri = this.stompConnectionManager.replyToCri;
445
646
  return connectedInfo;
446
647
  } else {
447
648
  throw new Error("Event Bus connection already active");
@@ -449,9 +650,12 @@ class EventBus {
449
650
  });
450
651
  }
451
652
  disconnect(force) {
653
+ this.disconnectRequests++;
654
+ const deactivated = this.stompConnectionManager.deactivate(force);
452
655
  return this.serializeLifecycle(async () => {
656
+ await deactivated;
453
657
  await this.stompConnectionManager.deactivate(force);
454
- this.cleanup();
658
+ this.serverInfo = null;
455
659
  });
456
660
  }
457
661
  serializeLifecycle(operation) {
@@ -460,7 +664,7 @@ class EventBus {
460
664
  return result;
461
665
  }
462
666
  send(event) {
463
- if (this.stompConnectionManager.rxStomp) {
667
+ if (this.stompConnectionManager.connected) {
464
668
  const headers = {};
465
669
  for (const [key, value] of event.headers.entries()) {
466
670
  headers[key] = value;
@@ -476,7 +680,8 @@ class EventBus {
476
680
  this.stompConnectionManager.rxStomp.publish({
477
681
  destination: event.cri,
478
682
  headers,
479
- binaryBody: event.data.orUndefined()
683
+ binaryBody: event.data.orUndefined(),
684
+ retryIfDisconnected: false
480
685
  });
481
686
  } else {
482
687
  throw this.createSendUnavailableError();
@@ -486,58 +691,65 @@ class EventBus {
486
691
  return import_rxjs2.firstValueFrom(this.requestStream(event, false));
487
692
  }
488
693
  requestStream(event, sendControlEvents = true) {
489
- if (this.stompConnectionManager?.rxStomp) {
490
- return new import_rxjs2.Observable((subscriber) => {
491
- if (this.requestRepliesObservable == null) {
492
- this.requestRepliesSubject = new import_rxjs2.Subject;
493
- this.requestRepliesObservable = this._observe(this.replyToCri).pipe(import_operators.tap((value) => this.cancelIfUnexpected(value)), import_operators.multicast(this.requestRepliesSubject));
494
- this.requestRepliesSubscription = this.requestRepliesObservable.connect();
495
- }
496
- let serverSignaledCompletion = false;
497
- const correlationId = import_uuid2.v4();
498
- this.activeCorrelationIds.add(correlationId);
499
- const defaultMessagesSubscription = this.requestRepliesObservable.pipe(import_operators.filter((value) => {
500
- return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
501
- })).subscribe({
502
- next(value) {
503
- if (value.hasHeader("control" /* CONTROL_HEADER */)) {
504
- if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
505
- serverSignaledCompletion = true;
506
- subscriber.complete();
507
- } else {
508
- throw new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported");
509
- }
510
- } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
694
+ return new import_rxjs2.Observable((subscriber) => {
695
+ const replyToCri = this.stompConnectionManager.replyToCri;
696
+ if (!this.stompConnectionManager.connected || replyToCri == null) {
697
+ subscriber.error(this.createSendUnavailableError());
698
+ return;
699
+ }
700
+ if (this.requestRepliesObservable == null) {
701
+ this.requestRepliesSubject = new import_rxjs2.Subject;
702
+ this.requestRepliesObservable = this._observe(replyToCri).pipe(import_operators2.tap((value) => this.cancelIfUnexpected(value)), import_operators2.multicast(this.requestRepliesSubject));
703
+ this.requestRepliesSubscription = this.requestRepliesObservable.connect();
704
+ }
705
+ let serverSignaledCompletion = false;
706
+ let replyDestinationReset = false;
707
+ const correlationId = import_uuid2.v4();
708
+ this.activeCorrelationIds.add(correlationId);
709
+ subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
710
+ const defaultMessagesSubscription = this.requestRepliesObservable.pipe(import_operators2.filter((value) => {
711
+ return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
712
+ })).subscribe({
713
+ next(value) {
714
+ if (value.hasHeader("control" /* CONTROL_HEADER */)) {
715
+ if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
511
716
  serverSignaledCompletion = true;
512
- subscriber.error(new Error(value.getHeader("error" /* ERROR_HEADER */)));
717
+ if (value.data.isPresent() || !sendControlEvents) {
718
+ subscriber.next(value);
719
+ }
720
+ subscriber.complete();
513
721
  } else {
514
- subscriber.next(value);
722
+ subscriber.error(new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported"));
515
723
  }
516
- },
517
- error(err) {
518
- subscriber.error(err);
519
- },
520
- complete() {
521
- subscriber.complete();
724
+ } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
725
+ serverSignaledCompletion = true;
726
+ subscriber.error(RpcError.fromEvent(value));
727
+ } else {
728
+ subscriber.next(value);
522
729
  }
523
- });
524
- subscriber.add(defaultMessagesSubscription);
525
- event.setHeader("reply-to" /* REPLY_TO_HEADER */, this.replyToCri);
526
- event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
527
- this.send(event);
528
- return () => {
529
- this.activeCorrelationIds.delete(correlationId);
530
- if (sendControlEvents && !serverSignaledCompletion) {
531
- const controlEvent = new Event(event.cri);
532
- controlEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
533
- controlEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
534
- this.send(controlEvent);
730
+ },
731
+ error(err) {
732
+ replyDestinationReset = true;
733
+ subscriber.error(err);
734
+ },
735
+ complete() {
736
+ subscriber.complete();
737
+ }
738
+ });
739
+ subscriber.add(defaultMessagesSubscription);
740
+ event.setHeader("reply-to" /* REPLY_TO_HEADER */, replyToCri);
741
+ event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
742
+ this.send(event);
743
+ subscriber.add(() => {
744
+ if (sendControlEvents && !serverSignaledCompletion && !replyDestinationReset) {
745
+ try {
746
+ this.sendCancel(event.cri, correlationId);
747
+ } catch (e) {
748
+ this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
535
749
  }
536
- };
750
+ }
537
751
  });
538
- } else {
539
- return import_rxjs2.throwError(() => this.createSendUnavailableError());
540
- }
752
+ });
541
753
  }
542
754
  listen(_serverInfo) {
543
755
  return Promise.reject("Not implemented");
@@ -545,10 +757,6 @@ class EventBus {
545
757
  observe(cri) {
546
758
  return this._observe(cri);
547
759
  }
548
- cleanup() {
549
- this.resetRequestReplies("Connection disconnected");
550
- this.serverInfo = null;
551
- }
552
760
  cancelIfUnexpected(value) {
553
761
  const correlationId = value.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
554
762
  if (correlationId === undefined || this.activeCorrelationIds.has(correlationId)) {
@@ -559,13 +767,19 @@ class EventBus {
559
767
  return;
560
768
  }
561
769
  try {
562
- const cancelEvent = new Event(originCri);
563
- cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
564
- cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
565
- this.send(cancelEvent);
770
+ this.sendCancel(originCri, correlationId);
566
771
  this.recentlyReaped.add(correlationId);
567
772
  setTimeout(() => this.recentlyReaped.delete(correlationId), EventBus.REAP_DEBOUNCE_MS);
568
- } catch {}
773
+ } catch (e) {
774
+ this.log.warn(`Could not cancel orphaned stream ${correlationId} on ${originCri}`, e);
775
+ }
776
+ }
777
+ sendCancel(cri, correlationId) {
778
+ const cancelEvent = new Event(cri);
779
+ cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
780
+ cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
781
+ cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.stompConnectionManager.replyToCri);
782
+ this.send(cancelEvent);
569
783
  }
570
784
  resetRequestReplies(reason) {
571
785
  if (this.requestRepliesSubject != null) {
@@ -580,29 +794,29 @@ class EventBus {
580
794
  }
581
795
  }
582
796
  createSendUnavailableError() {
583
- let ret = "You must call connect on the event bus before sending any request";
797
+ let ret;
584
798
  if (this.stompConnectionManager.maxConnectionAttemptsReached) {
585
799
  ret = "Max connection attempts reached event bus is not available";
800
+ } else if (this.stompConnectionManager.active) {
801
+ ret = "The event bus is not connected to the server";
802
+ } else {
803
+ ret = "You must call connect on the event bus before sending any request";
586
804
  }
587
805
  return new Error(ret);
588
806
  }
589
807
  _observe(cri) {
590
- if (this.stompConnectionManager?.rxStomp) {
591
- return this.stompConnectionManager.rxStomp.watch(cri).pipe(import_operators.map((message) => {
592
- const headers = new Map;
593
- let destination = "";
594
- for (const prop of Object.keys(message.headers)) {
595
- if (prop === "destination") {
596
- destination = message.headers[prop];
597
- } else {
598
- headers.set(prop, message.headers[prop]);
599
- }
808
+ return this.stompConnectionManager.rxStomp.watch(cri).pipe(import_operators2.map((message) => {
809
+ const headers = new Map;
810
+ let destination = "";
811
+ for (const prop of Object.keys(message.headers)) {
812
+ if (prop === "destination") {
813
+ destination = message.headers[prop];
814
+ } else {
815
+ headers.set(prop, message.headers[prop]);
600
816
  }
601
- return new Event(destination, headers, message.binaryBody);
602
- }));
603
- } else {
604
- throw this.createSendUnavailableError();
605
- }
817
+ }
818
+ return new Event(destination, headers, message.binaryBody.length > 0 ? message.binaryBody : undefined);
819
+ }));
606
820
  }
607
821
  }
608
822
 
@@ -680,7 +894,8 @@ class SessionCredentialsResolver {
680
894
 
681
895
  // packages/core/src/internal/api/Util.ts
682
896
  var DEFAULT_PORT = 58503;
683
- var DEFAULT_HOST = "api.kinotic.com";
897
+ var DEFAULT_HOST = "api.kinotic.ai";
898
+ var LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "::1", "[::1]"];
684
899
 
685
900
  class Util {
686
901
  static createReplyEvent(incomingHeaders, headers, body) {
@@ -711,7 +926,6 @@ class Util {
711
926
  const location = typeof window !== "undefined" ? window.location : undefined;
712
927
  let host = server.host ?? env?.KINOTIC_SERVER_HOST;
713
928
  const hostFromLocation = host == null && location != null;
714
- const hostDefaulted = host == null && location == null;
715
929
  if (host == null) {
716
930
  host = location?.hostname ?? DEFAULT_HOST;
717
931
  }
@@ -722,7 +936,7 @@ class Util {
722
936
  } else if (hostFromLocation) {
723
937
  useSSL = location.protocol === "https:";
724
938
  } else {
725
- useSSL = hostDefaulted;
939
+ useSSL = !LOOPBACK_HOSTS.includes(host.toLowerCase());
726
940
  }
727
941
  }
728
942
  let port = server.port;
@@ -744,8 +958,119 @@ class Util {
744
958
  }
745
959
  }
746
960
 
961
+ // packages/core/src/internal/api/Session.ts
962
+ var import_debug3 = __toESM(require("debug"), 1);
963
+ var import_rxjs3 = require("rxjs");
964
+
965
+ // packages/core/src/api/security/SessionEndType.ts
966
+ var SessionEndType;
967
+ ((SessionEndType) => {
968
+ SessionEndType["SIGNED_OUT"] = "SIGNED_OUT";
969
+ SessionEndType["CONNECTION_LOST"] = "CONNECTION_LOST";
970
+ })(SessionEndType ||= {});
971
+
972
+ // packages/core/src/internal/api/Session.ts
973
+ var SESSION_REQUEST_TIMEOUT_MS = 5000;
974
+
975
+ class Session {
976
+ kinotic;
977
+ _connectedInfo = null;
978
+ server = null;
979
+ inFlight = Promise.resolve();
980
+ requests = 0;
981
+ subscriptions = new import_rxjs3.Subscription;
982
+ endedSubject = new import_rxjs3.Subject;
983
+ debugLogger = import_debug3.default("kinotic:session");
984
+ constructor(kinotic) {
985
+ this.kinotic = kinotic;
986
+ this.observe(kinotic.eventBus);
987
+ }
988
+ get connectedInfo() {
989
+ return this._connectedInfo;
990
+ }
991
+ get ended() {
992
+ return this.endedSubject.asObservable();
993
+ }
994
+ release() {
995
+ this._connectedInfo = null;
996
+ }
997
+ observe(eventBus) {
998
+ this.subscriptions.unsubscribe();
999
+ this.subscriptions = new import_rxjs3.Subscription;
1000
+ this.subscriptions.add(eventBus.connectionEstablished.subscribe((connectedInfo) => {
1001
+ if (this._connectedInfo !== null) {
1002
+ this._connectedInfo = connectedInfo;
1003
+ }
1004
+ }));
1005
+ this.subscriptions.add(eventBus.connectionEnded.subscribe((reason) => {
1006
+ if (this._connectedInfo !== null && !this.kinotic.eventBus.isConnectionActive()) {
1007
+ this._connectedInfo = null;
1008
+ if (reason !== null) {
1009
+ this.classifyEnd(reason);
1010
+ }
1011
+ }
1012
+ }));
1013
+ }
1014
+ resume(options) {
1015
+ this.requests++;
1016
+ return this.serialize(async () => {
1017
+ this._connectedInfo = null;
1018
+ try {
1019
+ await this.kinotic.disconnect();
1020
+ } catch (e) {
1021
+ this.debugLogger("Closing the previous connection failed: %O", e);
1022
+ }
1023
+ const resolved = Util.resolveConnectOptions(options);
1024
+ this.server = resolved.server;
1025
+ let ret;
1026
+ try {
1027
+ ret = await this.kinotic.connect(resolved);
1028
+ } catch (e) {
1029
+ await this.kinotic.disconnect().catch((error) => this.debugLogger("Closing the failed connection failed: %O", error));
1030
+ throw e;
1031
+ }
1032
+ this._connectedInfo = ret;
1033
+ return ret;
1034
+ });
1035
+ }
1036
+ logout() {
1037
+ this.requests++;
1038
+ return this.serialize(async () => {
1039
+ this._connectedInfo = null;
1040
+ const server = this.kinotic.eventBus.serverInfo ?? this.server ?? Util.resolveConnectOptions().server;
1041
+ try {
1042
+ await endLogin(server, AbortSignal.timeout(SESSION_REQUEST_TIMEOUT_MS));
1043
+ } catch (e) {
1044
+ this.debugLogger("The logout request failed: %O", e);
1045
+ }
1046
+ try {
1047
+ await this.kinotic.disconnect();
1048
+ } catch (e) {
1049
+ this.debugLogger("Closing the connection failed: %O", e);
1050
+ }
1051
+ });
1052
+ }
1053
+ async classifyEnd(cause) {
1054
+ const requestsAtEnd = this.requests;
1055
+ let signedOut = false;
1056
+ try {
1057
+ signedOut = !await holdsLogin(this.server, AbortSignal.timeout(SESSION_REQUEST_TIMEOUT_MS));
1058
+ } catch (e) {
1059
+ this.debugLogger("The session check failed: %O", e);
1060
+ }
1061
+ if (this.requests === requestsAtEnd) {
1062
+ this.endedSubject.next({ type: signedOut ? "SIGNED_OUT" /* SIGNED_OUT */ : "CONNECTION_LOST" /* CONNECTION_LOST */, cause });
1063
+ }
1064
+ }
1065
+ serialize(operation) {
1066
+ const result = this.inFlight.then(operation);
1067
+ this.inFlight = result.catch(() => {});
1068
+ return result;
1069
+ }
1070
+ }
1071
+
747
1072
  // packages/core/src/api/ServiceRegistry.ts
748
- var import_debug3 = __toESM(require("debug"));
1073
+ var import_debug4 = __toESM(require("debug"), 1);
749
1074
 
750
1075
  // packages/core/src/api/event/DefaultCRI.ts
751
1076
  var ZONE_DELIMITER = "~";
@@ -933,22 +1258,14 @@ class JsonArgumentResolver {
933
1258
  // packages/core/src/internal/api/ReturnValueConverter.ts
934
1259
  class BasicReturnValueConverter {
935
1260
  convert(incomingMetadata, returnValue) {
936
- return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(JSON.stringify(returnValue)));
1261
+ const json = returnValue === undefined ? "null" : JSON.stringify(returnValue);
1262
+ return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(json));
937
1263
  }
938
1264
  }
939
1265
 
940
- // packages/core/src/internal/api/Logger.ts
941
- var import_debug2 = __toESM(require("debug"));
942
- function createDebugLogger(namespace) {
943
- const debugLogger = import_debug2.default(namespace);
944
- return {
945
- trace: (...args) => debugLogger("TRACE", ...args),
946
- debug: (...args) => debugLogger("DEBUG", ...args),
947
- info: (...args) => debugLogger("INFO", ...args),
948
- warn: (...args) => debugLogger("WARN", ...args),
949
- error: (...args) => debugLogger("ERROR", ...args)
950
- };
951
- }
1266
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1267
+ var import_rxjs4 = require("rxjs");
1268
+ var import_operators3 = require("rxjs/operators");
952
1269
 
953
1270
  // packages/core/src/api/ServiceIdentifier.ts
954
1271
  class ServiceIdentifier {
@@ -985,6 +1302,9 @@ class ServiceIdentifier {
985
1302
  }
986
1303
  return this._cri;
987
1304
  }
1305
+ unscopedCri() {
1306
+ return createCRI("srv" /* SERVICE_DESTINATION_SCHEME */, null, this.qualifiedName(), null, this.version || null);
1307
+ }
988
1308
  }
989
1309
 
990
1310
  // packages/core/src/api/ZoneUtil.ts
@@ -1004,6 +1324,7 @@ function validateLabel(label) {
1004
1324
 
1005
1325
  // packages/core/src/api/KinoticDecorators.ts
1006
1326
  var scopeFunctions = new WeakSet;
1327
+ var scopeOptionalFunctions = new WeakSet;
1007
1328
  var versionRegistry = new WeakMap;
1008
1329
  var zonesRegistry = new WeakMap;
1009
1330
  var advertisedRegistry = new WeakMap;
@@ -1041,6 +1362,23 @@ function resolveScope(instance) {
1041
1362
  function Scope(value, _context) {
1042
1363
  scopeFunctions.add(value);
1043
1364
  }
1365
+ function ScopeOptional(value, _context) {
1366
+ scopeOptionalFunctions.add(value);
1367
+ }
1368
+ function scopeOptionalMethodNames(instance) {
1369
+ const ret = new Set;
1370
+ let proto = Object.getPrototypeOf(instance);
1371
+ while (proto && proto !== Object.prototype) {
1372
+ for (const key of Object.getOwnPropertyNames(proto)) {
1373
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1374
+ if (typeof descriptor?.value === "function" && scopeOptionalFunctions.has(descriptor.value)) {
1375
+ ret.add(key);
1376
+ }
1377
+ }
1378
+ proto = Object.getPrototypeOf(proto);
1379
+ }
1380
+ return ret;
1381
+ }
1044
1382
  function Version(version) {
1045
1383
  if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?$/.test(version)) {
1046
1384
  throw new Error(`Invalid semantic version: ${version}. Must follow X.Y.Z[-optional] format.`);
@@ -1103,6 +1441,94 @@ function Publish(namespace, name, advertise = false) {
1103
1441
  };
1104
1442
  }
1105
1443
 
1444
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1445
+ var import_api2 = __toESM(require("@opentelemetry/api"), 1);
1446
+ // packages/core/package.json
1447
+ var package_default = {
1448
+ name: "@kinotic-ai/core",
1449
+ version: "5.0.0-beta.31",
1450
+ type: "module",
1451
+ files: [
1452
+ "dist"
1453
+ ],
1454
+ module: "./dist/index.js",
1455
+ main: "./dist/index.cjs",
1456
+ types: "./dist/index.d.ts",
1457
+ exports: {
1458
+ ".": {
1459
+ import: {
1460
+ types: "./dist/index.d.ts",
1461
+ default: "./dist/index.js"
1462
+ },
1463
+ require: {
1464
+ types: "./dist/index.d.cts",
1465
+ default: "./dist/index.cjs"
1466
+ }
1467
+ },
1468
+ "./node": {
1469
+ import: {
1470
+ types: "./dist/node/index.d.ts",
1471
+ default: "./dist/node/index.js"
1472
+ },
1473
+ require: {
1474
+ types: "./dist/node/index.d.cts",
1475
+ default: "./dist/node/index.cjs"
1476
+ }
1477
+ },
1478
+ "./package.json": "./package.json"
1479
+ },
1480
+ homepage: "https://github.com/kinotic-ai/kinotic",
1481
+ repository: {
1482
+ type: "git",
1483
+ url: "git+https://github.com/kinotic-ai/kinotic.git",
1484
+ directory: "kinotic-js/workspace/packages/core"
1485
+ },
1486
+ license: "Apache-2.0",
1487
+ publishConfig: {
1488
+ access: "public"
1489
+ },
1490
+ scripts: {
1491
+ "type-check": "tsc --noEmit",
1492
+ test: "vitest run",
1493
+ coverage: "vitest run --coverage",
1494
+ "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1495
+ },
1496
+ devDependencies: {
1497
+ "@opentelemetry/exporter-trace-otlp-grpc": "^0.221.0",
1498
+ "@opentelemetry/resources": "^2.10.0",
1499
+ "@opentelemetry/sdk-metrics": "^2.10.0",
1500
+ "@opentelemetry/sdk-node": "^0.221.0",
1501
+ "@opentelemetry/sdk-trace-node": "^2.10.0",
1502
+ "@types/debug": "^4.1.13",
1503
+ "@types/node": "^25.6.0",
1504
+ "@types/ws": "^8.18.0",
1505
+ "@vitest/coverage-v8": "^4.1.4",
1506
+ "@vitest/runner": "^4.1.4",
1507
+ "@vitest/ui": "^4.1.4",
1508
+ allure: "^3.19.1",
1509
+ "allure-vitest": "^3.13.0",
1510
+ dotenv: "^17.4.1",
1511
+ "properties-file": "^4.0.0",
1512
+ testcontainers: "^11.14.0",
1513
+ tslib: "^2.8.1",
1514
+ typescript: "^6.0.2",
1515
+ vitest: "^4.1.4"
1516
+ },
1517
+ dependencies: {
1518
+ "@kinotic-ai/idl": "workspace:^",
1519
+ "@opentelemetry/api": "^1.9.1",
1520
+ "@opentelemetry/semantic-conventions": "^1.40.0",
1521
+ "@stomp/rx-stomp": "^2.4.0",
1522
+ "@stomp/stompjs": "^7.3.0",
1523
+ debug: "^4.4.3",
1524
+ "p-tap": "^4.0.0",
1525
+ rxjs: "^7.8.2",
1526
+ "typescript-optional": "3.0.0-alpha.3",
1527
+ uuid: "^13.0.0",
1528
+ ws: "^8.21.0"
1529
+ }
1530
+ };
1531
+
1106
1532
  // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1107
1533
  class ServiceInvocationSupervisor {
1108
1534
  log;
@@ -1114,7 +1540,13 @@ class ServiceInvocationSupervisor {
1114
1540
  serviceIdentifier;
1115
1541
  serviceInstance;
1116
1542
  methodSubscription = null;
1543
+ unscopedSubscription = null;
1544
+ activeStreams = new Map;
1545
+ connectionEndedSubscription = null;
1546
+ connectionGeneration = 0;
1117
1547
  methodMap;
1548
+ scopeOptionalMethods;
1549
+ tracer;
1118
1550
  constructor(serviceIdentifier, serviceInstance, eventBusService, interceptorProvider, options = {}) {
1119
1551
  if (!serviceIdentifier)
1120
1552
  throw new Error("ServiceIdentifier must not be null");
@@ -1128,10 +1560,12 @@ class ServiceInvocationSupervisor {
1128
1560
  this.serviceInstance = serviceInstance;
1129
1561
  this._eventBus = eventBusService;
1130
1562
  this.interceptorProvider = interceptorProvider;
1131
- this.log = options.logger || createDebugLogger("kinoitc:ServiceInvocationSupervisor");
1563
+ this.log = options.logger || createDebugLogger("kinotic:ServiceInvocationSupervisor");
1132
1564
  this.argumentResolver = options.argumentResolver || new JsonArgumentResolver;
1133
1565
  this.returnValueConverter = options.returnValueConverter || new BasicReturnValueConverter;
1134
1566
  this.methodMap = this.buildMethodMap(serviceInstance);
1567
+ this.scopeOptionalMethods = scopeOptionalMethodNames(serviceInstance);
1568
+ this.tracer = import_api2.default.trace.getTracer(package_default.name, package_default.version);
1135
1569
  }
1136
1570
  isActive() {
1137
1571
  return this.active;
@@ -1151,7 +1585,22 @@ class ServiceInvocationSupervisor {
1151
1585
  }
1152
1586
  this.active = true;
1153
1587
  const criBase = this.serviceIdentifier.cri().baseResource();
1154
- this.methodSubscription = this._eventBus.observe(criBase).subscribe({
1588
+ this.methodSubscription = this.subscribeAt(criBase);
1589
+ this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1590
+ if (this.serviceIdentifier.scope && this.scopeOptionalMethods.size > 0) {
1591
+ const unscopedBase = this.serviceIdentifier.unscopedCri().baseResource();
1592
+ this.unscopedSubscription = this.subscribeAt(unscopedBase);
1593
+ this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
1594
+ }
1595
+ this.connectionEndedSubscription = this._eventBus.connectionEnded.subscribe(() => {
1596
+ this.connectionGeneration++;
1597
+ for (const stream of this.activeStreams.values()) {
1598
+ stream.subscription.unsubscribe();
1599
+ }
1600
+ });
1601
+ }
1602
+ subscribeAt(criBase) {
1603
+ return this._eventBus.observe(criBase).subscribe({
1155
1604
  next: async (event) => {
1156
1605
  await this.processEvent(event);
1157
1606
  },
@@ -1164,7 +1613,6 @@ class ServiceInvocationSupervisor {
1164
1613
  this.active = false;
1165
1614
  }
1166
1615
  });
1167
- this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1168
1616
  }
1169
1617
  stop() {
1170
1618
  if (!this.active) {
@@ -1173,6 +1621,15 @@ class ServiceInvocationSupervisor {
1173
1621
  this.active = false;
1174
1622
  this.methodSubscription?.unsubscribe();
1175
1623
  this.methodSubscription = null;
1624
+ this.unscopedSubscription?.unsubscribe();
1625
+ this.unscopedSubscription = null;
1626
+ this.connectionEndedSubscription?.unsubscribe();
1627
+ this.connectionEndedSubscription = null;
1628
+ const serviceName = this.serviceIdentifier.qualifiedName();
1629
+ for (const stream of this.activeStreams.values()) {
1630
+ this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
1631
+ stream.subscription.unsubscribe();
1632
+ }
1176
1633
  this.log.info("ServiceInvocationSupervisor stopped");
1177
1634
  }
1178
1635
  buildMethodMap(serviceInstance) {
@@ -1212,10 +1669,19 @@ class ServiceInvocationSupervisor {
1212
1669
  if (!correlationId) {
1213
1670
  throw new Error("Streaming control plane messages require a CORRELATION_ID_HEADER");
1214
1671
  }
1215
- this.log.trace(`Processing control event for correlationId: ${correlationId}`);
1672
+ const control = event.getHeader("control" /* CONTROL_HEADER */);
1673
+ this.log.trace(`Processing control event ${control} for correlationId: ${correlationId}`);
1674
+ const stream = this.activeStreams.get(correlationId);
1675
+ if (stream) {
1676
+ stream.subscription.unsubscribe();
1677
+ if (control !== "cancel" /* CONTROL_VALUE_CANCEL */) {
1678
+ throw new Error(`Unknown control header value ${control}`);
1679
+ }
1680
+ }
1216
1681
  }
1217
1682
  async processInvocationRequest(event) {
1218
- const path = createCRI(event.cri).path();
1683
+ const incomingCri = createCRI(event.cri);
1684
+ const path = incomingCri.path();
1219
1685
  if (!path) {
1220
1686
  throw new Error("The methodId must not be blank");
1221
1687
  }
@@ -1223,49 +1689,175 @@ class ServiceInvocationSupervisor {
1223
1689
  if (!handlerMethod) {
1224
1690
  throw new Error(`No method resolved for methodId ${path}`);
1225
1691
  }
1692
+ if (this.serviceIdentifier.scope && !incomingCri.hasScope() && !this.scopeOptionalMethods.has(path)) {
1693
+ throw new Error(`Method ${path} of ${this.serviceIdentifier.qualifiedName()} requires a scoped invocation naming the service instance`);
1694
+ }
1226
1695
  const methodName = path;
1227
- const args = this.argumentResolver.resolveArguments(event);
1228
- const injectContext = receivesContext(this.serviceInstance, methodName);
1229
- let context2 = {};
1230
- const interceptor = this.interceptorProvider();
1231
- if (interceptor) {
1696
+ const span = this.startInvocationSpan(event, methodName);
1697
+ const generation = this.connectionGeneration;
1698
+ try {
1699
+ const args = this.argumentResolver.resolveArguments(event);
1700
+ const injectContext = receivesContext(this.serviceInstance, methodName);
1701
+ let serviceContext = {};
1702
+ const sender = event.getHeader("sender" /* SENDER_HEADER */);
1703
+ if (sender) {
1704
+ serviceContext.participant = JSON.parse(sender);
1705
+ }
1706
+ const interceptor = this.interceptorProvider();
1707
+ if (interceptor) {
1708
+ try {
1709
+ serviceContext = await interceptor.intercept(event, serviceContext);
1710
+ } catch (e) {
1711
+ this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1712
+ if (this.replyOwed(generation)) {
1713
+ this.handleException(event, new Error("Internal server error"));
1714
+ }
1715
+ this.failSpan(span, e);
1716
+ return;
1717
+ }
1718
+ }
1719
+ if (injectContext) {
1720
+ args.push(serviceContext);
1721
+ }
1722
+ const expectedArgsCount = handlerMethod.length;
1723
+ if (args.length !== expectedArgsCount) {
1724
+ throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1725
+ }
1726
+ let result;
1232
1727
  try {
1233
- context2 = await interceptor.intercept(event, context2);
1728
+ result = import_api2.context.with(import_api2.trace.setSpan(import_api2.context.active(), span), () => handlerMethod(...args));
1729
+ if (result instanceof Promise) {
1730
+ result.then((resolved) => this.processMethodInvocationResult(event, resolved, span, generation), (error) => this.failInvocation(event, error, span, generation)).catch((e) => {
1731
+ this.failInvocation(event, e, span, generation);
1732
+ });
1733
+ } else {
1734
+ this.processMethodInvocationResult(event, result, span, generation);
1735
+ }
1234
1736
  } catch (e) {
1235
- this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1236
- this.handleException(event, new Error("Internal server error"));
1237
- return;
1737
+ this.failInvocation(event, e, span, generation);
1738
+ }
1739
+ } catch (e) {
1740
+ this.failSpan(span, e);
1741
+ throw e;
1742
+ }
1743
+ }
1744
+ startInvocationSpan(event, methodName) {
1745
+ const carrier = {};
1746
+ for (const [key, value] of event.headers.entries()) {
1747
+ carrier[key] = value;
1748
+ }
1749
+ const serviceName = this.serviceIdentifier.qualifiedName();
1750
+ return this.tracer.startSpan(`${this.serviceIdentifier.name}/${methodName}`, {
1751
+ kind: import_api2.SpanKind.SERVER,
1752
+ attributes: {
1753
+ "rpc.system": "kinotic",
1754
+ "rpc.service": serviceName,
1755
+ "rpc.method": methodName
1238
1756
  }
1757
+ }, import_api2.propagation.extract(import_api2.context.active(), carrier));
1758
+ }
1759
+ failSpan(span, error) {
1760
+ span.recordException(error);
1761
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1762
+ span.end();
1763
+ }
1764
+ replyOwed(generation) {
1765
+ return generation === this.connectionGeneration;
1766
+ }
1767
+ failInvocation(event, error, span, generation) {
1768
+ if (this.replyOwed(generation)) {
1769
+ this.handleException(event, error);
1770
+ }
1771
+ this.failSpan(span, error);
1772
+ }
1773
+ processMethodInvocationResult(event, result, span, generation) {
1774
+ if (!this.replyOwed(generation)) {
1775
+ span.end();
1776
+ } else if (import_rxjs4.isObservable(result)) {
1777
+ this.streamResult(event, result, span);
1778
+ } else {
1779
+ const reply = this.returnValueConverter.convert(event.headers, result);
1780
+ reply.setHeader("control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */);
1781
+ this.sendReply(reply);
1782
+ span.end();
1783
+ }
1784
+ }
1785
+ streamResult(event, stream, span) {
1786
+ const correlationId = event.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
1787
+ if (!correlationId) {
1788
+ throw new Error("Streaming results require a CORRELATION_ID_HEADER to be set");
1789
+ }
1790
+ if (this.activeStreams.has(correlationId)) {
1791
+ const error = new Error(`stream ${correlationId} already active`);
1792
+ this.handleException(event, error);
1793
+ this.failSpan(span, error);
1794
+ return;
1239
1795
  }
1240
- if (injectContext) {
1241
- args.push(context2);
1796
+ let subscription = null;
1797
+ let failed = false;
1798
+ subscription = stream.pipe(import_operators3.finalize(() => {
1799
+ if (this.activeStreams.get(correlationId)?.subscription === subscription) {
1800
+ this.activeStreams.delete(correlationId);
1801
+ }
1802
+ span.end();
1803
+ })).subscribe({
1804
+ next: (value) => {
1805
+ if (failed) {
1806
+ return;
1807
+ }
1808
+ try {
1809
+ const reply = this.returnValueConverter.convert(event.headers, value);
1810
+ reply.setHeader("__origin-cri" /* ORIGIN_CRI_HEADER */, event.cri);
1811
+ this.sendReply(reply);
1812
+ } catch (e) {
1813
+ failed = true;
1814
+ this.handleException(event, e);
1815
+ span.recordException(e);
1816
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1817
+ subscription?.unsubscribe();
1818
+ }
1819
+ },
1820
+ error: (error) => {
1821
+ if (failed) {
1822
+ return;
1823
+ }
1824
+ this.handleException(event, error);
1825
+ span.recordException(error);
1826
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1827
+ },
1828
+ complete: () => {
1829
+ if (failed) {
1830
+ return;
1831
+ }
1832
+ this.sendReply(Util.createReplyEvent(event.headers, new Map([["control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */]])));
1833
+ }
1834
+ });
1835
+ if (failed) {
1836
+ subscription.unsubscribe();
1242
1837
  }
1243
- const expectedArgsCount = handlerMethod.length;
1244
- if (args.length !== expectedArgsCount) {
1245
- throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1838
+ if (!subscription.closed) {
1839
+ this.activeStreams.set(correlationId, { request: event, subscription });
1246
1840
  }
1247
- let result;
1841
+ }
1842
+ sendReply(event) {
1248
1843
  try {
1249
- result = handlerMethod(...args);
1250
- if (result instanceof Promise) {
1251
- result.then((resolved) => this.processMethodInvocationResult(event, resolved), (error) => this.handleException(event, error));
1252
- } else {
1253
- this.processMethodInvocationResult(event, result);
1254
- }
1844
+ this._eventBus.send(event);
1255
1845
  } catch (e) {
1256
- this.handleException(event, e);
1846
+ this.log.warn(`Could not send reply to ${event.cri}`, e);
1257
1847
  }
1258
1848
  }
1259
- processMethodInvocationResult(event, result) {
1260
- const outgoingEvent = this.returnValueConverter.convert(event.headers, result);
1261
- this._eventBus.send(outgoingEvent);
1262
- }
1263
1849
  handleException(event, error) {
1264
- const errorEvent = Util.createReplyEvent(event.headers, new Map([
1265
- ["error" /* ERROR_HEADER */, error.message || "Unknown error"],
1266
- ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1267
- ]), new TextEncoder().encode(JSON.stringify({ message: error.message })));
1268
- this._eventBus.send(errorEvent);
1850
+ try {
1851
+ const errorMessage = error?.message || "Unknown error";
1852
+ const exceptionName = error instanceof Error ? error.constructor.name : "Error";
1853
+ const errorEvent = Util.createReplyEvent(event.headers, new Map([
1854
+ ["error" /* ERROR_HEADER */, errorMessage],
1855
+ ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1856
+ ]), new TextEncoder().encode(JSON.stringify({ exceptionName, exceptionClass: exceptionName, errorMessage })));
1857
+ this.sendReply(errorEvent);
1858
+ } catch (e) {
1859
+ this.log.warn(`Could not build the error reply for ${event.cri}`, e);
1860
+ }
1269
1861
  }
1270
1862
  validateReplyTo(event) {
1271
1863
  const replyTo = event.getHeader("reply-to" /* REPLY_TO_HEADER */);
@@ -1286,97 +1878,9 @@ class ServiceInvocationSupervisor {
1286
1878
  }
1287
1879
 
1288
1880
  // packages/core/src/api/ServiceRegistry.ts
1289
- var import_api2 = __toESM(require("@opentelemetry/api"));
1881
+ var import_api3 = __toESM(require("@opentelemetry/api"), 1);
1290
1882
  var import_semantic_conventions = require("@opentelemetry/semantic-conventions");
1291
- var import_operators2 = require("rxjs/operators");
1292
- // packages/core/package.json
1293
- var package_default = {
1294
- name: "@kinotic-ai/core",
1295
- version: "5.0.0-beta.3",
1296
- type: "module",
1297
- files: [
1298
- "dist"
1299
- ],
1300
- module: "./dist/index.js",
1301
- main: "./dist/index.cjs",
1302
- types: "./dist/index.d.ts",
1303
- exports: {
1304
- ".": {
1305
- import: {
1306
- types: "./dist/index.d.ts",
1307
- default: "./dist/index.js"
1308
- },
1309
- require: {
1310
- types: "./dist/index.d.cts",
1311
- default: "./dist/index.cjs"
1312
- }
1313
- },
1314
- "./node": {
1315
- import: {
1316
- types: "./dist/node/index.d.ts",
1317
- default: "./dist/node/index.js"
1318
- },
1319
- require: {
1320
- types: "./dist/node/index.d.cts",
1321
- default: "./dist/node/index.cjs"
1322
- }
1323
- },
1324
- "./package.json": "./package.json"
1325
- },
1326
- homepage: "https://github.com/kinotic-ai/kinotic",
1327
- license: "Elastic License 2.0",
1328
- publishConfig: {
1329
- access: "public"
1330
- },
1331
- scripts: {
1332
- "type-check": "tsc --noEmit",
1333
- test: "vitest run",
1334
- coverage: "vitest run --coverage",
1335
- "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1336
- },
1337
- devDependencies: {
1338
- "@opentelemetry/exporter-trace-otlp-grpc": "^0.214.0",
1339
- "@opentelemetry/resources": "^2.6.1",
1340
- "@opentelemetry/sdk-metrics": "^2.6.1",
1341
- "@opentelemetry/sdk-node": "^0.214.0",
1342
- "@opentelemetry/sdk-trace-node": "^2.6.1",
1343
- "@types/node": "^25.6.0",
1344
- "@types/uuid": "^11.0.0",
1345
- "@types/ws": "^8.18.0",
1346
- "@vitest/coverage-v8": "^4.1.4",
1347
- "@vitest/runner": "^4.1.4",
1348
- "@vitest/ui": "^4.1.4",
1349
- allure: "^3.4.1",
1350
- "allure-vitest": "^3.7.1",
1351
- dotenv: "^17.4.1",
1352
- "properties-file": "^4.0.0",
1353
- testcontainers: "^11.14.0",
1354
- tslib: "^2.8.1",
1355
- typescript: "^6.0.2",
1356
- vitest: "^4.1.4",
1357
- ws: "^8.20.0"
1358
- },
1359
- dependencies: {
1360
- "@opentelemetry/api": "^1.9.1",
1361
- "@opentelemetry/semantic-conventions": "^1.40.0",
1362
- "@stomp/rx-stomp": "^2.4.0",
1363
- "@stomp/stompjs": "^7.3.0",
1364
- "@types/debug": "^4.1.13",
1365
- debug: "^4.4.3",
1366
- "p-tap": "^4.0.0",
1367
- rxjs: "^7.8.2",
1368
- "typescript-optional": "3.0.0-alpha.3",
1369
- uuid: "^13.0.0",
1370
- ws: "^8.18.0"
1371
- },
1372
- peerDependenciesMeta: {
1373
- typescript: {
1374
- optional: true
1375
- }
1376
- }
1377
- };
1378
-
1379
- // packages/core/src/api/ServiceRegistry.ts
1883
+ var import_operators4 = require("rxjs/operators");
1380
1884
  class JsonEventFactory {
1381
1885
  create(cri, args) {
1382
1886
  const event = new Event(cri);
@@ -1410,12 +1914,61 @@ class TextEventFactory {
1410
1914
  return event;
1411
1915
  }
1412
1916
  }
1917
+ var APPLICATION_SERVICE_DIRECTORY = "app-api~org.kinotic.app.api.services.ApplicationServiceDirectory";
1918
+ var APPLICATION_ZONE = /^app\.[^.]+\.([^.]+)(\.|$)/;
1919
+ var declaredDefinitions = new Map;
1920
+ function declareServiceDefinitions(definitions) {
1921
+ for (const definition of definitions) {
1922
+ declaredDefinitions.set(qualifiedNameOf(definition.namespace, definition.name), definition);
1923
+ }
1924
+ }
1925
+ function qualifiedNameOf(namespace, name) {
1926
+ return namespace ? `${namespace}.${name}` : name;
1927
+ }
1928
+ function servedFunctions(serviceInstance) {
1929
+ const ret = new Set;
1930
+ let proto = Object.getPrototypeOf(serviceInstance);
1931
+ while (proto && proto !== Object.prototype) {
1932
+ for (const key of Object.getOwnPropertyNames(proto)) {
1933
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1934
+ if (typeof descriptor?.value === "function" && key !== "constructor") {
1935
+ ret.add(key);
1936
+ }
1937
+ }
1938
+ proto = Object.getPrototypeOf(proto);
1939
+ }
1940
+ return [...ret].sort();
1941
+ }
1942
+ function directoryEntryOf(serviceInstance, serviceIdentifier) {
1943
+ let ret = null;
1944
+ const application = serviceIdentifier.zone ? APPLICATION_ZONE.exec(serviceIdentifier.zone) : null;
1945
+ if (application) {
1946
+ const qualifiedName = qualifiedNameOf(serviceIdentifier.namespace, serviceIdentifier.name);
1947
+ const definition = declaredDefinitions.get(qualifiedName);
1948
+ if (definition) {
1949
+ const declared = definition.functions.map((f) => f.name).sort();
1950
+ const served = servedFunctions(serviceInstance);
1951
+ if (declared.join() !== served.join()) {
1952
+ throw new Error(`${qualifiedName} serves the functions [${served}] but its definition declares [${declared}];` + " run kinotic sync and import the generated ServiceDefinitions module");
1953
+ }
1954
+ ret = {
1955
+ applicationId: application[1],
1956
+ zone: serviceIdentifier.zone,
1957
+ version: serviceIdentifier.version ?? null,
1958
+ advertised: isAdvertised(serviceInstance),
1959
+ serviceDefinition: definition
1960
+ };
1961
+ }
1962
+ }
1963
+ return ret;
1964
+ }
1413
1965
 
1414
1966
  class ServiceRegistry {
1415
1967
  _eventBus;
1416
1968
  supervisors = new Map;
1969
+ entries = new Map;
1417
1970
  contextInterceptor = null;
1418
- debugLogger = import_debug3.default("kinoitc:serviceRegistry");
1971
+ debugLogger = import_debug4.default("kinotic:serviceRegistry");
1419
1972
  constructor(eventBus) {
1420
1973
  this._eventBus = eventBus;
1421
1974
  }
@@ -1435,9 +1988,16 @@ class ServiceRegistry {
1435
1988
  const criString = serviceIdentifier.cri().raw();
1436
1989
  if (!this.supervisors.has(criString)) {
1437
1990
  this.debugLogger(`Registering service for CRI: ${criString}`);
1991
+ const entry = directoryEntryOf(service, serviceIdentifier);
1438
1992
  const supervisor = new ServiceInvocationSupervisor(serviceIdentifier, service, this.eventBus, () => this.contextInterceptor);
1439
1993
  this.supervisors.set(criString, supervisor);
1440
1994
  supervisor.start();
1995
+ if (entry) {
1996
+ this.entries.set(criString, entry);
1997
+ if (this.eventBus.isConnected()) {
1998
+ this.registerEntry(entry).catch((error) => this.debugLogger(`Failed to register ${criString} in the directory`, error));
1999
+ }
2000
+ }
1441
2001
  }
1442
2002
  }
1443
2003
  unRegister(serviceIdentifier) {
@@ -1447,8 +2007,18 @@ class ServiceRegistry {
1447
2007
  this.debugLogger(`Unregistering service for CRI: ${criString}`);
1448
2008
  supervisor.stop();
1449
2009
  this.supervisors.delete(criString);
2010
+ this.entries.delete(criString);
2011
+ }
2012
+ }
2013
+ async registerEntries() {
2014
+ for (const entry of this.entries.values()) {
2015
+ await this.registerEntry(entry);
1450
2016
  }
1451
2017
  }
2018
+ async registerEntry(entry) {
2019
+ this.debugLogger(`Registering ${entry.zone}~${qualifiedNameOf(entry.serviceDefinition.namespace, entry.serviceDefinition.name)} in the directory`);
2020
+ await this.serviceProxy(APPLICATION_SERVICE_DIRECTORY).invoke("register", [entry]);
2021
+ }
1452
2022
  registerContextInterceptor(interceptor) {
1453
2023
  this.contextInterceptor = interceptor;
1454
2024
  }
@@ -1465,24 +2035,24 @@ class ServiceProxy {
1465
2035
  }
1466
2036
  this.serviceIdentifier = serviceIdentifier;
1467
2037
  this.serviceRegistry = serviceRegistry;
1468
- this.tracer = import_api2.default.trace.getTracer("kinoitc.client", package_default.version);
2038
+ this.tracer = import_api3.default.trace.getTracer(package_default.name, package_default.version);
1469
2039
  }
1470
2040
  invoke(methodIdentifier, args, scope, eventFactory) {
1471
2041
  return this.tracer.startActiveSpan(`${this.serviceIdentifier}/${methodIdentifier}`, {
1472
- kind: import_api2.SpanKind.CLIENT
2042
+ kind: import_api3.SpanKind.CLIENT
1473
2043
  }, async (span) => {
1474
2044
  if (scope) {
1475
- span.setAttribute("kinoitc.scope", scope);
2045
+ span.setAttribute("kinotic.scope", scope);
1476
2046
  }
1477
- span.setAttribute("rpc.system", "kinoitc");
2047
+ span.setAttribute("rpc.system", "kinotic");
1478
2048
  span.setAttribute("rpc.service", this.serviceIdentifier);
1479
2049
  span.setAttribute("rpc.method", methodIdentifier);
1480
- return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(import_operators2.first()).toPromise().then(async (value) => {
2050
+ return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(import_operators4.first()).toPromise().then(async (value) => {
1481
2051
  span.end();
1482
2052
  return value;
1483
2053
  }, async (ex) => {
1484
2054
  span.recordException(ex);
1485
- span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
2055
+ span.setStatus({ code: import_api3.SpanStatusCode.ERROR });
1486
2056
  span.end();
1487
2057
  throw ex;
1488
2058
  });
@@ -1498,13 +2068,13 @@ class ServiceProxy {
1498
2068
  eventFactoryToUse = eventFactory;
1499
2069
  }
1500
2070
  let eventBusToUse = this.serviceRegistry.eventBus;
1501
- const span = import_api2.default.trace.getActiveSpan();
2071
+ const span = import_api3.default.trace.getActiveSpan();
1502
2072
  if (span) {
1503
2073
  span.setAttribute(import_semantic_conventions.ATTR_SERVER_ADDRESS, eventBusToUse.serverInfo?.host || "unknown");
1504
2074
  span.setAttribute(import_semantic_conventions.ATTR_SERVER_PORT, eventBusToUse.serverInfo?.port || "unknown");
1505
2075
  }
1506
2076
  let event = eventFactoryToUse.create(cri, args);
1507
- return eventBusToUse.requestStream(event, sendControlEvents).pipe(import_operators2.map((value) => {
2077
+ return eventBusToUse.requestStream(event, sendControlEvents).pipe(import_operators4.map((value) => {
1508
2078
  const contentType = value.getHeader("content-type" /* CONTENT_TYPE_HEADER */);
1509
2079
  if (contentType !== undefined) {
1510
2080
  if (contentType === "application/json" /* CONTENT_JSON */) {
@@ -1527,11 +2097,16 @@ class ServiceProxy {
1527
2097
  class KinoticSingleton {
1528
2098
  _eventBus;
1529
2099
  serviceRegistry;
2100
+ _session;
1530
2101
  zonePrefix = null;
1531
2102
  defaultZone = null;
1532
2103
  constructor() {
1533
2104
  this._eventBus = new EventBus;
1534
2105
  this.serviceRegistry = new ServiceRegistry(this._eventBus);
2106
+ this._session = new Session(this);
2107
+ }
2108
+ get session() {
2109
+ return this._session;
1535
2110
  }
1536
2111
  get eventBus() {
1537
2112
  return this._eventBus;
@@ -1539,11 +2114,15 @@ class KinoticSingleton {
1539
2114
  set eventBus(eventBus) {
1540
2115
  this._eventBus = eventBus;
1541
2116
  this.serviceRegistry.eventBus = eventBus;
2117
+ this._session.observe(eventBus);
1542
2118
  }
1543
- connect(options) {
1544
- return this._eventBus.connect(Util.resolveConnectOptions(options));
2119
+ async connect(options) {
2120
+ const ret = await this._eventBus.connect(Util.resolveConnectOptions(options));
2121
+ await this.serviceRegistry.registerEntries();
2122
+ return ret;
1545
2123
  }
1546
2124
  disconnect(force) {
2125
+ this._session.release();
1547
2126
  return this._eventBus.disconnect(force);
1548
2127
  }
1549
2128
  serviceProxy(serviceIdentifier) {
@@ -1662,6 +2241,9 @@ class CrudServiceProxy {
1662
2241
  deleteById(id) {
1663
2242
  return this.serviceProxy.invoke("deleteById", [id]);
1664
2243
  }
2244
+ deleteByIdSync(id) {
2245
+ return this.serviceProxy.invoke("deleteByIdSync", [id]);
2246
+ }
1665
2247
  async findAll(pageable) {
1666
2248
  const page = await this.findAllSinglePage(pageable);
1667
2249
  return new FindAllIterablePage(pageable, page, this);
@@ -1752,15 +2334,15 @@ class CursorPageable extends Pageable {
1752
2334
  }
1753
2335
  // packages/core/src/api/crud/Sort.ts
1754
2336
  var Direction;
1755
- ((Direction2) => {
1756
- Direction2["ASC"] = "ASC";
1757
- Direction2["DESC"] = "DESC";
2337
+ ((Direction) => {
2338
+ Direction["ASC"] = "ASC";
2339
+ Direction["DESC"] = "DESC";
1758
2340
  })(Direction ||= {});
1759
2341
  var NullHandling;
1760
- ((NullHandling2) => {
1761
- NullHandling2["NATIVE"] = "NATIVE";
1762
- NullHandling2["NULLS_FIRST"] = "NULLS_FIRST";
1763
- NullHandling2["NULLS_LAST"] = "NULLS_LAST";
2342
+ ((NullHandling) => {
2343
+ NullHandling["NATIVE"] = "NATIVE";
2344
+ NullHandling["NULLS_FIRST"] = "NULLS_FIRST";
2345
+ NullHandling["NULLS_LAST"] = "NULLS_LAST";
1764
2346
  })(NullHandling ||= {});
1765
2347
 
1766
2348
  class Order {
@@ -1784,6 +2366,13 @@ class Order {
1784
2366
  class Sort {
1785
2367
  orders = [];
1786
2368
  }
2369
+ // packages/core/src/api/security/AuthorizationException.ts
2370
+ class AuthorizationException extends Error {
2371
+ constructor(message = "Access denied") {
2372
+ super(message);
2373
+ this.name = "AuthorizationException";
2374
+ }
2375
+ }
1787
2376
  // packages/core/src/api/security/ConnectedInfo.ts
1788
2377
  class ConnectedInfo {
1789
2378
  replyToId;