@kinotic-ai/core 5.0.0-beta.2 → 5.0.0-beta.20

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
@@ -66,9 +66,14 @@ var exports_src = {};
66
66
  __export(exports_src, {
67
67
  validateZone: () => validateZone,
68
68
  validateLabel: () => validateLabel,
69
+ scopeOptionalMethodNames: () => scopeOptionalMethodNames,
69
70
  receivesContext: () => receivesContext,
70
71
  isAdvertised: () => isAdvertised,
72
+ declaresAuthzResource: () => declaresAuthzResource,
73
+ declareServiceDefinitions: () => declareServiceDefinitions,
71
74
  createCRI: () => createCRI,
75
+ buildServerUrl: () => buildServerUrl,
76
+ buildBrokerUrl: () => buildBrokerUrl,
72
77
  Zone: () => Zone,
73
78
  Version: () => Version,
74
79
  TextEventFactory: () => TextEventFactory,
@@ -76,8 +81,11 @@ __export(exports_src, {
76
81
  SessionKeepAliveMode: () => SessionKeepAliveMode,
77
82
  SessionCredentialsResolver: () => SessionCredentialsResolver,
78
83
  ServiceRegistry: () => ServiceRegistry,
84
+ ServiceIdentifier: () => ServiceIdentifier,
79
85
  ServerInfo: () => ServerInfo,
86
+ ScopeOptional: () => ScopeOptional,
80
87
  Scope: () => Scope,
88
+ RpcError: () => RpcError,
81
89
  Publish: () => Publish,
82
90
  ParticipantConstants: () => ParticipantConstants,
83
91
  Pageable: () => Pageable,
@@ -103,6 +111,9 @@ __export(exports_src, {
103
111
  ChainedCredentialsResolver: () => ChainedCredentialsResolver,
104
112
  BearerCredentialsResolver: () => BearerCredentialsResolver,
105
113
  BasicCredentialsResolver: () => BasicCredentialsResolver,
114
+ AuthzResource: () => AuthzResource,
115
+ AuthzCheck: () => AuthzCheck,
116
+ AuthorizationException: () => AuthorizationException,
106
117
  AbstractIterablePage: () => AbstractIterablePage
107
118
  });
108
119
  module.exports = __toCommonJS(exports_src);
@@ -113,6 +124,12 @@ class ServerInfo {
113
124
  port;
114
125
  useSSL;
115
126
  }
127
+ function buildServerUrl(server, scheme) {
128
+ return scheme + (server.useSSL ? "s" : "") + "://" + server.host + (server.port ? ":" + server.port : "");
129
+ }
130
+ function buildBrokerUrl(server) {
131
+ return buildServerUrl(server, "ws") + "/v1";
132
+ }
116
133
  var SessionKeepAliveMode;
117
134
  ((SessionKeepAliveMode2) => {
118
135
  SessionKeepAliveMode2["NONE"] = "NONE";
@@ -125,6 +142,7 @@ var EventConstants;
125
142
  EventConstants2["CONTENT_TYPE_HEADER"] = "content-type";
126
143
  EventConstants2["CONTENT_LENGTH_HEADER"] = "content-length";
127
144
  EventConstants2["REPLY_TO_HEADER"] = "reply-to";
145
+ EventConstants2["SENDER_HEADER"] = "sender";
128
146
  EventConstants2["CONNECTED_INFO_HEADER"] = "connected-info";
129
147
  EventConstants2["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
130
148
  EventConstants2["CORRELATION_ID_HEADER"] = "__correlation-id";
@@ -149,126 +167,172 @@ var EventConstants;
149
167
  EventConstants2["TRACESTATE_HEADER"] = "tracestate";
150
168
  })(EventConstants ||= {});
151
169
 
170
+ // packages/core/src/internal/api/Logger.ts
171
+ var import_debug = __toESM(require("debug"));
172
+ function createDebugLogger(namespace) {
173
+ const debugLogger = import_debug.default(namespace);
174
+ return {
175
+ trace: (...args) => debugLogger("TRACE", ...args),
176
+ debug: (...args) => debugLogger("DEBUG", ...args),
177
+ info: (...args) => debugLogger("INFO", ...args),
178
+ warn: (...args) => debugLogger("WARN", ...args),
179
+ error: (...args) => debugLogger("ERROR", ...args)
180
+ };
181
+ }
182
+
152
183
  // packages/core/src/internal/api/StompConnectionManager.ts
153
184
  var import_rx_stomp = require("@stomp/rx-stomp");
154
185
  var import_stompjs = require("@stomp/stompjs");
155
- var import_debug = __toESM(require("debug"));
186
+ var import_debug2 = __toESM(require("debug"));
156
187
  var import_rxjs = require("rxjs");
188
+ var import_operators = require("rxjs/operators");
157
189
  var import_uuid = require("uuid");
190
+
191
+ // packages/core/src/internal/api/StompActivation.ts
192
+ class StompActivation {
193
+ _ended = false;
194
+ wake = null;
195
+ preparedSocket = null;
196
+ attempt = null;
197
+ failPending = null;
198
+ subscriptions = [];
199
+ get ended() {
200
+ return this._ended;
201
+ }
202
+ end() {
203
+ this._ended = true;
204
+ this.wake?.();
205
+ this.wake = null;
206
+ }
207
+ delay(ms) {
208
+ return new Promise((resolve) => {
209
+ const timer = setTimeout(() => {
210
+ this.wake = null;
211
+ resolve();
212
+ }, ms);
213
+ this.wake = () => {
214
+ clearTimeout(timer);
215
+ resolve();
216
+ };
217
+ });
218
+ }
219
+ own(subscription) {
220
+ this.subscriptions.push(subscription);
221
+ }
222
+ pending(fail) {
223
+ this.failPending = fail;
224
+ }
225
+ established() {
226
+ this.failPending = null;
227
+ }
228
+ failIfPending(reason) {
229
+ const fail = this.failPending;
230
+ this.failPending = null;
231
+ fail?.(reason);
232
+ }
233
+ unsubscribeAll() {
234
+ for (const subscription of this.subscriptions) {
235
+ subscription.unsubscribe();
236
+ }
237
+ this.subscriptions.length = 0;
238
+ }
239
+ }
240
+
241
+ // packages/core/src/internal/api/StompConnectionManager.ts
158
242
  var SESSION_CHECK_PATH = "/api/auth/me";
159
243
 
160
244
  class StompConnectionManager {
161
245
  lastWebsocketError = null;
162
246
  maxConnectionAttemptsReached = false;
163
- replyToCriChangedHandler = null;
164
- rxStomp = null;
247
+ connectionEndedHandler = null;
248
+ rxStomp = new import_rx_stomp.RxStomp;
249
+ activation = null;
250
+ teardown = null;
165
251
  INITIAL_RECONNECT_DELAY = 2000;
166
252
  JITTER_MAX = 5000;
167
253
  MAX_RECONNECT_DELAY = 120000;
168
254
  connectionAttempts = 0;
169
- debugLogger = import_debug.default("kinoitc:stomp");
170
- fatalErrorsSubject = new import_rxjs.Subject;
171
- _fatalErrors = this.fatalErrorsSubject.asObservable();
255
+ debugLogger = import_debug2.default("kinotic:stomp");
256
+ connectionEstablishedSubject = new import_rxjs.Subject;
172
257
  initialConnectionSuccessful = false;
173
- serverHeadersSubscription = null;
174
- stompErrorsSubscription = null;
175
- uuidv4 = import_uuid.v4();
258
+ rxStompHasConnected = false;
176
259
  _replyToCri = null;
177
260
  get replyToCri() {
178
261
  return this._replyToCri;
179
262
  }
180
263
  get active() {
181
- return !!this.rxStomp;
264
+ return this.activation !== null;
182
265
  }
183
266
  get connected() {
184
- return this.rxStomp != null && this.rxStomp.connected();
267
+ return this.activation !== null && this.rxStomp.connected();
185
268
  }
186
- get fatalErrors() {
187
- return this._fatalErrors;
269
+ get connectionEstablished() {
270
+ return this.connectionEstablishedSubject.asObservable();
188
271
  }
189
272
  async activate(options) {
190
- if (!options?.host) {
273
+ if (!options?.server?.host) {
191
274
  throw new Error("No host provided");
192
275
  }
193
- if (this.rxStomp) {
276
+ if (this.activation) {
277
+ throw new Error("Stomp connection already active");
278
+ }
279
+ await this.teardown;
280
+ if (this.activation) {
194
281
  throw new Error("Stomp connection already active");
195
282
  }
196
- const server = { host: options.host, port: options.port, useSSL: options.useSSL };
283
+ const server = options.server;
197
284
  const credentialsResolver = options.credentials;
285
+ const activation = new StompActivation;
286
+ this.activation = activation;
198
287
  let headerAuth = false;
199
- if (!options.webSocketFactory) {
200
- if (!credentialsResolver) {
201
- throw new Error("No credentials supplied and no default resolution applied");
288
+ try {
289
+ if (!options.webSocketFactory) {
290
+ if (!credentialsResolver) {
291
+ throw new Error("No credentials supplied and no default resolution applied");
292
+ }
293
+ const resolved = await credentialsResolver.resolve(server);
294
+ if (resolved === null) {
295
+ throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
296
+ }
297
+ headerAuth = resolved.authHeaders != null;
202
298
  }
203
- const resolved = await credentialsResolver.resolve(server);
204
- if (resolved === null) {
205
- throw new Error("No Kinotic credentials found; consulted: " + credentialsResolver.name);
299
+ if (activation.ended) {
300
+ throw new Error("Deactivated before the connection was established");
301
+ }
302
+ } catch (e) {
303
+ if (this.activation === activation) {
304
+ this.activation = null;
206
305
  }
207
- headerAuth = resolved.authHeaders != null;
306
+ throw e;
208
307
  }
209
308
  return new Promise((resolve, reject) => {
210
309
  this.connectionAttempts = 0;
211
310
  this.initialConnectionSuccessful = false;
212
311
  this.lastWebsocketError = null;
213
312
  this.maxConnectionAttemptsReached = false;
214
- const url = Util.buildBrokerUrl(server);
215
- this.rxStomp = new import_rx_stomp.RxStomp;
216
- let preparedSocket = null;
217
- const userWebSocketFactory = options.webSocketFactory;
218
- const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
313
+ const url = buildBrokerUrl(server);
314
+ const usesPreparedSocket = options.webSocketFactory != null || headerAuth;
315
+ const takePreparedSocket = () => {
316
+ const socket = activation.preparedSocket;
317
+ activation.preparedSocket = null;
318
+ return socket;
319
+ };
219
320
  const stompConfig = {
220
321
  brokerURL: url,
221
322
  connectHeaders: {
222
323
  ["session-keep-alive" /* SESSION_KEEP_ALIVE_HEADER */]: options.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */
223
324
  },
224
- heartbeatIncoming: 120000,
325
+ heartbeatIncoming: 30000,
225
326
  heartbeatOutgoing: 30000,
226
327
  reconnectDelay: this.INITIAL_RECONNECT_DELAY,
227
328
  maxReconnectDelay: this.MAX_RECONNECT_DELAY,
228
329
  reconnectTimeMode: import_stompjs.ReconnectionTimeMode.EXPONENTIAL,
229
- webSocketFactory: usesPreparedSocket ? () => preparedSocket : undefined,
230
- beforeConnect: async () => {
231
- if (!usesPreparedSocket) {
232
- const sessionCheckUrl = "http" + (server.useSSL ? "s" : "") + "://" + server.host + (server.port ? ":" + server.port : "") + SESSION_CHECK_PATH;
233
- try {
234
- const res = await fetch(sessionCheckUrl, { credentials: "include" });
235
- if (res.status === 401) {
236
- await this.signalFatal(new Error("Authentication required"));
237
- return;
238
- }
239
- } catch {}
240
- }
241
- if (options?.maxConnectionAttempts) {
242
- this.connectionAttempts++;
243
- if (this.connectionAttempts > options.maxConnectionAttempts) {
244
- this.maxConnectionAttemptsReached = true;
245
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
246
- return;
247
- } else {
248
- await this.connectionJitterDelay();
249
- }
250
- } else {
251
- await this.connectionJitterDelay();
252
- }
253
- if (userWebSocketFactory) {
254
- try {
255
- preparedSocket = await userWebSocketFactory();
256
- } catch (e) {
257
- await this.signalFatal(new Error("WebSocket factory failed", { cause: e }));
258
- }
259
- } else if (headerAuth) {
260
- try {
261
- const resolved = await credentialsResolver.resolve(server);
262
- if (resolved?.authHeaders == null) {
263
- await this.signalFatal(new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
264
- } else {
265
- const WS = WebSocket;
266
- preparedSocket = new WS(url, { headers: resolved.authHeaders });
267
- }
268
- } catch (e) {
269
- await this.signalFatal(new Error("Credential resolution failed", { cause: e }));
270
- }
271
- }
330
+ webSocketFactory: usesPreparedSocket ? takePreparedSocket : undefined,
331
+ beforeConnect: () => {
332
+ const attempt = this.prepareAttempt(activation, options, server, headerAuth);
333
+ const settled = () => new Promise((resolve2) => setTimeout(resolve2, 0));
334
+ activation.attempt = attempt.then(settled, settled);
335
+ return attempt;
272
336
  }
273
337
  };
274
338
  if (this.debugLogger.enabled) {
@@ -277,93 +341,195 @@ class StompConnectionManager {
277
341
  };
278
342
  }
279
343
  this.rxStomp.configure(stompConfig);
280
- this.rxStomp.webSocketErrors$.subscribe(async (value) => {
344
+ activation.own(this.rxStomp.webSocketErrors$.subscribe(async (value) => {
281
345
  this.lastWebsocketError = value;
282
- if (options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
346
+ if (!activation.ended && options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
283
347
  this.maxConnectionAttemptsReached = true;
284
- await this.signalFatal(new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
348
+ await this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
285
349
  }
286
- });
287
- this.stompErrorsSubscription = this.rxStomp.stompErrors$.subscribe(async (frame) => {
350
+ }));
351
+ activation.own(this.rxStomp.stompErrors$.subscribe(async (frame) => {
288
352
  const stompError = new Error(frame.headers["message"], { cause: frame });
289
- await this.signalFatal(new Error("STOMP connection error", { cause: stompError }));
290
- });
291
- const connectedSubscription = this.rxStomp.connected$.subscribe(() => {
292
- connectedSubscription.unsubscribe();
293
- initialFailureSubscription.unsubscribe();
294
- if (!this.initialConnectionSuccessful) {
295
- this.initialConnectionSuccessful = true;
296
- }
297
- });
298
- const initialFailureSubscription = this.fatalErrorsSubject.subscribe((err) => {
299
- connectedSubscription.unsubscribe();
300
- initialFailureSubscription.unsubscribe();
301
- reject(err.message);
302
- });
303
- this.serverHeadersSubscription = this.rxStomp.serverHeaders$.subscribe(async (value) => {
353
+ await this.failConnection(activation, new Error("STOMP connection error", { cause: stompError }));
354
+ }));
355
+ activation.own(this.rxStomp.connected$.subscribe(() => {
356
+ activation.established();
357
+ this.initialConnectionSuccessful = true;
358
+ this.connectionAttempts = 0;
359
+ }));
360
+ activation.pending(reject);
361
+ activation.own(this.rxStomp.serverHeaders$.pipe(import_operators.skip(this.rxStompHasConnected ? 1 : 0)).subscribe(async (value) => {
362
+ this.rxStompHasConnected = true;
304
363
  const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
305
364
  if (connectedInfoJson == null) {
306
365
  if (!this.initialConnectionSuccessful) {
307
- await this.deactivate();
308
- reject("Server did not return proper data for successful login");
366
+ await this.deactivate(undefined, new Error("Server did not return proper data for successful login"));
309
367
  }
310
368
  return;
311
369
  }
312
370
  const connectedInfo = JSON.parse(connectedInfoJson);
313
371
  if (connectedInfo.replyToId == null) {
314
372
  if (!this.initialConnectionSuccessful) {
315
- await this.deactivate();
316
- reject("Server did not return a replyToId for successful login");
373
+ await this.deactivate(undefined, new Error("Server did not return a replyToId for successful login"));
317
374
  }
318
375
  return;
319
376
  }
320
- const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + this.uuidv4 + "@kinoitc.js.EventBus/replyHandler";
377
+ const newReplyToCri = "reply://" /* REPLY_DESTINATION_PREFIX */ + connectedInfo.replyToId + ":" + import_uuid.v4() + "@kinotic.js.EventBus/replyHandler";
378
+ this._replyToCri = newReplyToCri;
321
379
  if (!this.initialConnectionSuccessful) {
322
- this._replyToCri = newReplyToCri;
323
380
  resolve(connectedInfo);
324
- } else if (this._replyToCri !== newReplyToCri) {
325
- this._replyToCri = newReplyToCri;
326
- this.replyToCriChangedHandler?.(newReplyToCri);
327
381
  }
328
- });
382
+ this.connectionEstablishedSubject.next(connectedInfo);
383
+ }));
384
+ let previousState = this.rxStomp.connectionState$.getValue();
385
+ activation.own(this.rxStomp.connectionState$.subscribe((state) => {
386
+ if (state === import_rx_stomp.RxStompState.CLOSED && previousState === import_rx_stomp.RxStompState.OPEN && this.activation === activation) {
387
+ this.connectionEndedHandler?.(null);
388
+ }
389
+ previousState = state;
390
+ }));
329
391
  this.rxStomp.activate();
330
392
  });
331
393
  }
332
- async deactivate(force) {
333
- const rxStomp = this.rxStomp;
334
- if (rxStomp) {
335
- await rxStomp.deactivate({ force });
336
- if (this.rxStomp === rxStomp) {
337
- this.serverHeadersSubscription?.unsubscribe();
338
- this.serverHeadersSubscription = null;
339
- this.stompErrorsSubscription?.unsubscribe();
340
- this.stompErrorsSubscription = null;
341
- this.rxStomp = null;
342
- this._replyToCri = null;
394
+ async prepareAttempt(activation, options, server, headerAuth) {
395
+ const credentialsResolver = options.credentials;
396
+ const userWebSocketFactory = options.webSocketFactory;
397
+ const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
398
+ const url = buildBrokerUrl(server);
399
+ if (!usesPreparedSocket) {
400
+ const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
401
+ try {
402
+ const res = await fetch(sessionCheckUrl, { credentials: "include" });
403
+ if (res.status === 401) {
404
+ await this.failConnection(activation, new Error("Authentication required"));
405
+ return;
406
+ }
407
+ } catch (e) {
408
+ this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
409
+ }
410
+ }
411
+ if (options?.maxConnectionAttempts) {
412
+ this.connectionAttempts++;
413
+ if (this.connectionAttempts > options.maxConnectionAttempts) {
414
+ this.maxConnectionAttemptsReached = true;
415
+ await this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
416
+ return;
417
+ } else {
418
+ await this.connectionJitterDelay(activation);
419
+ }
420
+ } else {
421
+ await this.connectionJitterDelay(activation);
422
+ }
423
+ if (activation.ended) {
424
+ return;
425
+ }
426
+ if (userWebSocketFactory) {
427
+ try {
428
+ activation.preparedSocket = await userWebSocketFactory();
429
+ } catch (e) {
430
+ await this.failConnection(activation, new Error("WebSocket factory failed", { cause: e }));
431
+ }
432
+ } else if (headerAuth) {
433
+ try {
434
+ const resolved = await credentialsResolver.resolve(server);
435
+ if (resolved?.authHeaders == null) {
436
+ await this.failConnection(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
437
+ } else {
438
+ const WS = WebSocket;
439
+ activation.preparedSocket = new WS(url, { headers: resolved.authHeaders });
440
+ }
441
+ } catch (e) {
442
+ await this.failConnection(activation, new Error("Credential resolution failed", { cause: e }));
443
+ }
444
+ }
445
+ if (activation.ended && activation.preparedSocket) {
446
+ activation.preparedSocket.close();
447
+ activation.preparedSocket = null;
448
+ }
449
+ }
450
+ deactivate(force, reason = null) {
451
+ const activation = this.activation;
452
+ let ret;
453
+ if (activation) {
454
+ this.activation = null;
455
+ activation.end();
456
+ const wasOpen = this.rxStomp.connected();
457
+ this._replyToCri = null;
458
+ activation.failIfPending(reason ?? new Error("Deactivated before the connection was established"));
459
+ activation.preparedSocket?.close();
460
+ activation.preparedSocket = null;
461
+ const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
462
+ activation.unsubscribeAll();
463
+ this.teardown = null;
464
+ });
465
+ this.teardown = teardown;
466
+ if (wasOpen || reason !== null) {
467
+ this.connectionEndedHandler?.(reason);
343
468
  }
469
+ ret = teardown;
470
+ } else {
471
+ ret = this.teardown ?? Promise.resolve();
344
472
  }
345
- return;
473
+ return ret;
346
474
  }
347
- async connectionJitterDelay() {
475
+ async connectionJitterDelay(activation) {
348
476
  if (this.initialConnectionSuccessful) {
349
477
  const randomJitter = Math.random() * this.JITTER_MAX;
350
478
  this.debugLogger(`Adding ${randomJitter}ms of jitter delay`);
351
- return new Promise((resolve) => setTimeout(resolve, randomJitter));
479
+ await activation.delay(randomJitter);
352
480
  }
353
481
  }
354
- async signalFatal(err) {
355
- this.debugLogger("Fatal error, deactivating connection: %O", err);
356
- await this.deactivate();
357
- this.fatalErrorsSubject.next(err);
482
+ async failConnection(activation, err) {
483
+ if (!activation.ended) {
484
+ this.debugLogger("Connection failed, ending it: %O", err);
485
+ await this.deactivate(undefined, err);
486
+ }
358
487
  }
359
488
  }
360
489
 
361
490
  // packages/core/src/api/event/EventBus.ts
362
491
  var import_api = require("@opentelemetry/api");
363
492
  var import_rxjs2 = require("rxjs");
364
- var import_operators = require("rxjs/operators");
493
+ var import_operators2 = require("rxjs/operators");
365
494
  var import_typescript_optional = require("typescript-optional");
366
495
  var import_uuid2 = require("uuid");
496
+
497
+ // packages/core/src/api/event/RpcError.ts
498
+ class RpcError extends Error {
499
+ exceptionName;
500
+ exceptionClass;
501
+ constructor(message, exceptionName, exceptionClass) {
502
+ super(message);
503
+ this.name = "RpcError";
504
+ this.exceptionName = exceptionName;
505
+ this.exceptionClass = exceptionClass;
506
+ }
507
+ static fromEvent(reply) {
508
+ const message = reply.getHeader("error" /* ERROR_HEADER */) ?? "";
509
+ let ret;
510
+ const detail = describedException(reply);
511
+ if (detail !== undefined) {
512
+ ret = new RpcError(detail.errorMessage ?? message, detail.exceptionName ?? "", detail.exceptionClass ?? "");
513
+ } else {
514
+ ret = new RpcError(message, "", "");
515
+ }
516
+ return ret;
517
+ }
518
+ }
519
+ function describedException(reply) {
520
+ let ret = undefined;
521
+ if (reply.data.isPresent() && reply.getHeader("content-type" /* CONTENT_TYPE_HEADER */)?.startsWith("application/json")) {
522
+ try {
523
+ const parsed = JSON.parse(reply.getDataString());
524
+ if (parsed !== null && typeof parsed === "object") {
525
+ ret = parsed;
526
+ }
527
+ } catch {}
528
+ }
529
+ return ret;
530
+ }
531
+
532
+ // packages/core/src/api/event/EventBus.ts
367
533
  class Event {
368
534
  cri;
369
535
  headers;
@@ -402,24 +568,31 @@ class Event {
402
568
 
403
569
  class EventBus {
404
570
  serverInfo = null;
571
+ log = createDebugLogger("kinotic:EventBus");
405
572
  stompConnectionManager = new StompConnectionManager;
406
573
  connectionLifecycle = Promise.resolve();
407
- replyToCri = null;
574
+ disconnectRequests = 0;
408
575
  requestRepliesObservable = null;
409
576
  requestRepliesSubject = null;
410
577
  requestRepliesSubscription = null;
411
578
  activeCorrelationIds = new Set;
412
579
  recentlyReaped = new Set;
580
+ connectionEndedSubject = new import_rxjs2.Subject;
413
581
  static REAP_DEBOUNCE_MS = 5000;
414
582
  constructor() {
415
- this.stompConnectionManager.fatalErrors.subscribe(() => this.cleanup());
416
- this.stompConnectionManager.replyToCriChangedHandler = (replyToCri) => {
417
- this.replyToCri = replyToCri;
418
- this.resetRequestReplies("Reply destination changed");
583
+ this.stompConnectionManager.connectionEndedHandler = (reason) => {
584
+ this.resetRequestReplies("Connection lost");
585
+ if (!this.stompConnectionManager.active) {
586
+ this.serverInfo = null;
587
+ }
588
+ this.connectionEndedSubject.next(reason);
419
589
  };
420
590
  }
421
- get fatalErrors() {
422
- return this.stompConnectionManager.fatalErrors;
591
+ get connectionEnded() {
592
+ return this.connectionEndedSubject.asObservable();
593
+ }
594
+ get connectionEstablished() {
595
+ return this.stompConnectionManager.connectionEstablished;
423
596
  }
424
597
  isConnectionActive() {
425
598
  return this.stompConnectionManager.active;
@@ -428,15 +601,14 @@ class EventBus {
428
601
  return this.stompConnectionManager.connected;
429
602
  }
430
603
  connect(options) {
604
+ const disconnectsWhenQueued = this.disconnectRequests;
431
605
  return this.serializeLifecycle(async () => {
606
+ if (this.disconnectRequests !== disconnectsWhenQueued) {
607
+ throw new Error("Disconnected before the connection was started");
608
+ }
432
609
  if (!this.stompConnectionManager.active) {
433
- this.cleanup();
434
610
  const connectedInfo = await this.stompConnectionManager.activate(options);
435
- this.serverInfo = new ServerInfo;
436
- this.serverInfo.host = options.host;
437
- this.serverInfo.port = options.port;
438
- this.serverInfo.useSSL = options.useSSL;
439
- this.replyToCri = this.stompConnectionManager.replyToCri;
611
+ this.serverInfo = { ...options.server };
440
612
  return connectedInfo;
441
613
  } else {
442
614
  throw new Error("Event Bus connection already active");
@@ -444,9 +616,12 @@ class EventBus {
444
616
  });
445
617
  }
446
618
  disconnect(force) {
619
+ this.disconnectRequests++;
620
+ const deactivated = this.stompConnectionManager.deactivate(force);
447
621
  return this.serializeLifecycle(async () => {
622
+ await deactivated;
448
623
  await this.stompConnectionManager.deactivate(force);
449
- this.cleanup();
624
+ this.serverInfo = null;
450
625
  });
451
626
  }
452
627
  serializeLifecycle(operation) {
@@ -455,7 +630,7 @@ class EventBus {
455
630
  return result;
456
631
  }
457
632
  send(event) {
458
- if (this.stompConnectionManager.rxStomp) {
633
+ if (this.stompConnectionManager.connected) {
459
634
  const headers = {};
460
635
  for (const [key, value] of event.headers.entries()) {
461
636
  headers[key] = value;
@@ -471,7 +646,8 @@ class EventBus {
471
646
  this.stompConnectionManager.rxStomp.publish({
472
647
  destination: event.cri,
473
648
  headers,
474
- binaryBody: event.data.orUndefined()
649
+ binaryBody: event.data.orUndefined(),
650
+ retryIfDisconnected: false
475
651
  });
476
652
  } else {
477
653
  throw this.createSendUnavailableError();
@@ -481,58 +657,65 @@ class EventBus {
481
657
  return import_rxjs2.firstValueFrom(this.requestStream(event, false));
482
658
  }
483
659
  requestStream(event, sendControlEvents = true) {
484
- if (this.stompConnectionManager?.rxStomp) {
485
- return new import_rxjs2.Observable((subscriber) => {
486
- if (this.requestRepliesObservable == null) {
487
- this.requestRepliesSubject = new import_rxjs2.Subject;
488
- this.requestRepliesObservable = this._observe(this.replyToCri).pipe(import_operators.tap((value) => this.cancelIfUnexpected(value)), import_operators.multicast(this.requestRepliesSubject));
489
- this.requestRepliesSubscription = this.requestRepliesObservable.connect();
490
- }
491
- let serverSignaledCompletion = false;
492
- const correlationId = import_uuid2.v4();
493
- this.activeCorrelationIds.add(correlationId);
494
- const defaultMessagesSubscription = this.requestRepliesObservable.pipe(import_operators.filter((value) => {
495
- return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
496
- })).subscribe({
497
- next(value) {
498
- if (value.hasHeader("control" /* CONTROL_HEADER */)) {
499
- if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
500
- serverSignaledCompletion = true;
501
- subscriber.complete();
502
- } else {
503
- throw new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported");
504
- }
505
- } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
660
+ return new import_rxjs2.Observable((subscriber) => {
661
+ const replyToCri = this.stompConnectionManager.replyToCri;
662
+ if (!this.stompConnectionManager.connected || replyToCri == null) {
663
+ subscriber.error(this.createSendUnavailableError());
664
+ return;
665
+ }
666
+ if (this.requestRepliesObservable == null) {
667
+ this.requestRepliesSubject = new import_rxjs2.Subject;
668
+ this.requestRepliesObservable = this._observe(replyToCri).pipe(import_operators2.tap((value) => this.cancelIfUnexpected(value)), import_operators2.multicast(this.requestRepliesSubject));
669
+ this.requestRepliesSubscription = this.requestRepliesObservable.connect();
670
+ }
671
+ let serverSignaledCompletion = false;
672
+ let replyDestinationReset = false;
673
+ const correlationId = import_uuid2.v4();
674
+ this.activeCorrelationIds.add(correlationId);
675
+ subscriber.add(() => this.activeCorrelationIds.delete(correlationId));
676
+ const defaultMessagesSubscription = this.requestRepliesObservable.pipe(import_operators2.filter((value) => {
677
+ return value.headers.get("__correlation-id" /* CORRELATION_ID_HEADER */) === correlationId;
678
+ })).subscribe({
679
+ next(value) {
680
+ if (value.hasHeader("control" /* CONTROL_HEADER */)) {
681
+ if (value.headers.get("control" /* CONTROL_HEADER */) === "complete" /* CONTROL_VALUE_COMPLETE */) {
506
682
  serverSignaledCompletion = true;
507
- subscriber.error(new Error(value.getHeader("error" /* ERROR_HEADER */)));
683
+ if (value.data.isPresent() || !sendControlEvents) {
684
+ subscriber.next(value);
685
+ }
686
+ subscriber.complete();
508
687
  } else {
509
- subscriber.next(value);
688
+ subscriber.error(new Error("Control Header " + value.headers.get("control" /* CONTROL_HEADER */) + " is not supported"));
510
689
  }
511
- },
512
- error(err) {
513
- subscriber.error(err);
514
- },
515
- complete() {
516
- subscriber.complete();
690
+ } else if (value.hasHeader("error" /* ERROR_HEADER */)) {
691
+ serverSignaledCompletion = true;
692
+ subscriber.error(RpcError.fromEvent(value));
693
+ } else {
694
+ subscriber.next(value);
517
695
  }
518
- });
519
- subscriber.add(defaultMessagesSubscription);
520
- event.setHeader("reply-to" /* REPLY_TO_HEADER */, this.replyToCri);
521
- event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
522
- this.send(event);
523
- return () => {
524
- this.activeCorrelationIds.delete(correlationId);
525
- if (sendControlEvents && !serverSignaledCompletion) {
526
- const controlEvent = new Event(event.cri);
527
- controlEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
528
- controlEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
529
- this.send(controlEvent);
696
+ },
697
+ error(err) {
698
+ replyDestinationReset = true;
699
+ subscriber.error(err);
700
+ },
701
+ complete() {
702
+ subscriber.complete();
703
+ }
704
+ });
705
+ subscriber.add(defaultMessagesSubscription);
706
+ event.setHeader("reply-to" /* REPLY_TO_HEADER */, replyToCri);
707
+ event.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
708
+ this.send(event);
709
+ subscriber.add(() => {
710
+ if (sendControlEvents && !serverSignaledCompletion && !replyDestinationReset) {
711
+ try {
712
+ this.sendCancel(event.cri, correlationId);
713
+ } catch (e) {
714
+ this.log.warn(`Could not cancel stream ${correlationId} on ${event.cri}`, e);
530
715
  }
531
- };
716
+ }
532
717
  });
533
- } else {
534
- return import_rxjs2.throwError(() => this.createSendUnavailableError());
535
- }
718
+ });
536
719
  }
537
720
  listen(_serverInfo) {
538
721
  return Promise.reject("Not implemented");
@@ -540,10 +723,6 @@ class EventBus {
540
723
  observe(cri) {
541
724
  return this._observe(cri);
542
725
  }
543
- cleanup() {
544
- this.resetRequestReplies("Connection disconnected");
545
- this.serverInfo = null;
546
- }
547
726
  cancelIfUnexpected(value) {
548
727
  const correlationId = value.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
549
728
  if (correlationId === undefined || this.activeCorrelationIds.has(correlationId)) {
@@ -554,13 +733,19 @@ class EventBus {
554
733
  return;
555
734
  }
556
735
  try {
557
- const cancelEvent = new Event(originCri);
558
- cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
559
- cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
560
- this.send(cancelEvent);
736
+ this.sendCancel(originCri, correlationId);
561
737
  this.recentlyReaped.add(correlationId);
562
738
  setTimeout(() => this.recentlyReaped.delete(correlationId), EventBus.REAP_DEBOUNCE_MS);
563
- } catch {}
739
+ } catch (e) {
740
+ this.log.warn(`Could not cancel orphaned stream ${correlationId} on ${originCri}`, e);
741
+ }
742
+ }
743
+ sendCancel(cri, correlationId) {
744
+ const cancelEvent = new Event(cri);
745
+ cancelEvent.setHeader("control" /* CONTROL_HEADER */, "cancel" /* CONTROL_VALUE_CANCEL */);
746
+ cancelEvent.setHeader("__correlation-id" /* CORRELATION_ID_HEADER */, correlationId);
747
+ cancelEvent.setHeader("reply-to" /* REPLY_TO_HEADER */, this.stompConnectionManager.replyToCri);
748
+ this.send(cancelEvent);
564
749
  }
565
750
  resetRequestReplies(reason) {
566
751
  if (this.requestRepliesSubject != null) {
@@ -575,29 +760,29 @@ class EventBus {
575
760
  }
576
761
  }
577
762
  createSendUnavailableError() {
578
- let ret = "You must call connect on the event bus before sending any request";
763
+ let ret;
579
764
  if (this.stompConnectionManager.maxConnectionAttemptsReached) {
580
765
  ret = "Max connection attempts reached event bus is not available";
766
+ } else if (this.stompConnectionManager.active) {
767
+ ret = "The event bus is not connected to the server";
768
+ } else {
769
+ ret = "You must call connect on the event bus before sending any request";
581
770
  }
582
771
  return new Error(ret);
583
772
  }
584
773
  _observe(cri) {
585
- if (this.stompConnectionManager?.rxStomp) {
586
- return this.stompConnectionManager.rxStomp.watch(cri).pipe(import_operators.map((message) => {
587
- const headers = new Map;
588
- let destination = "";
589
- for (const prop of Object.keys(message.headers)) {
590
- if (prop === "destination") {
591
- destination = message.headers[prop];
592
- } else {
593
- headers.set(prop, message.headers[prop]);
594
- }
774
+ return this.stompConnectionManager.rxStomp.watch(cri).pipe(import_operators2.map((message) => {
775
+ const headers = new Map;
776
+ let destination = "";
777
+ for (const prop of Object.keys(message.headers)) {
778
+ if (prop === "destination") {
779
+ destination = message.headers[prop];
780
+ } else {
781
+ headers.set(prop, message.headers[prop]);
595
782
  }
596
- return new Event(destination, headers, message.binaryBody);
597
- }));
598
- } else {
599
- throw this.createSendUnavailableError();
600
- }
783
+ }
784
+ return new Event(destination, headers, message.binaryBody.length > 0 ? message.binaryBody : undefined);
785
+ }));
601
786
  }
602
787
  }
603
788
 
@@ -620,28 +805,46 @@ class ChainedCredentialsResolver {
620
805
  }
621
806
  }
622
807
 
808
+ // packages/core/src/api/security/BasicCredentialsResolver.ts
809
+ class BasicCredentialsResolver {
810
+ name = "BasicCredentialsResolver";
811
+ credentials;
812
+ constructor(clientId, clientSecret, organizationId, applicationId) {
813
+ const authHeaders = { clientId, clientSecret };
814
+ if (organizationId != null)
815
+ authHeaders.organizationId = organizationId;
816
+ if (applicationId != null)
817
+ authHeaders.applicationId = applicationId;
818
+ this.credentials = { authHeaders, organizationId, applicationId };
819
+ }
820
+ async resolve(_server) {
821
+ return this.credentials;
822
+ }
823
+ }
824
+
825
+ // packages/core/src/api/security/BearerCredentialsResolver.ts
826
+ class BearerCredentialsResolver {
827
+ name = "BearerCredentialsResolver";
828
+ token;
829
+ constructor(token) {
830
+ this.token = token;
831
+ }
832
+ async resolve(_server) {
833
+ const token = typeof this.token === "function" ? await this.token() : this.token;
834
+ return { authHeaders: { Authorization: `Bearer ${token}` } };
835
+ }
836
+ }
837
+
623
838
  // packages/core/src/api/security/EnvCredentialsResolver.ts
624
839
  class EnvCredentialsResolver {
625
840
  name = "EnvCredentialsResolver";
626
- async resolve(_server) {
841
+ async resolve(server) {
627
842
  const env = typeof process !== "undefined" ? process.env : undefined;
628
843
  let ret = null;
629
844
  if (env?.KINOTIC_CLIENT_ID && env?.KINOTIC_CLIENT_SECRET) {
630
- const authHeaders = {
631
- clientId: env.KINOTIC_CLIENT_ID,
632
- clientSecret: env.KINOTIC_CLIENT_SECRET
633
- };
634
- if (env.KINOTIC_ORGANIZATION_ID)
635
- authHeaders.organizationId = env.KINOTIC_ORGANIZATION_ID;
636
- if (env.KINOTIC_APPLICATION_ID)
637
- authHeaders.applicationId = env.KINOTIC_APPLICATION_ID;
638
- ret = {
639
- authHeaders,
640
- organizationId: env.KINOTIC_ORGANIZATION_ID,
641
- applicationId: env.KINOTIC_APPLICATION_ID
642
- };
845
+ ret = await new BasicCredentialsResolver(env.KINOTIC_CLIENT_ID, env.KINOTIC_CLIENT_SECRET, env.KINOTIC_ORGANIZATION_ID || undefined, env.KINOTIC_APPLICATION_ID || undefined).resolve(server);
643
846
  } else if (env?.KINOTIC_TOKEN) {
644
- ret = { authHeaders: { Authorization: `Bearer ${env.KINOTIC_TOKEN}` } };
847
+ ret = await new BearerCredentialsResolver(env.KINOTIC_TOKEN).resolve(server);
645
848
  }
646
849
  return ret;
647
850
  }
@@ -657,7 +860,7 @@ class SessionCredentialsResolver {
657
860
 
658
861
  // packages/core/src/internal/api/Util.ts
659
862
  var DEFAULT_PORT = 58503;
660
- var DEFAULT_HOST = "api.kinotic.com";
863
+ var DEFAULT_HOST = "api.kinotic.ai";
661
864
 
662
865
  class Util {
663
866
  static createReplyEvent(incomingHeaders, headers, body) {
@@ -681,20 +884,18 @@ class Util {
681
884
  }
682
885
  return new Event(replyCRI, newHeaders, body || undefined);
683
886
  }
684
- static buildBrokerUrl(serverInfo) {
685
- return "ws" + (serverInfo.useSSL ? "s" : "") + "://" + serverInfo.host + (serverInfo.port ? ":" + serverInfo.port : "") + "/v1";
686
- }
687
887
  static resolveConnectOptions(options) {
688
888
  const opts = options ?? {};
889
+ const server = opts.server ?? {};
689
890
  const env = typeof process !== "undefined" ? process.env : undefined;
690
891
  const location = typeof window !== "undefined" ? window.location : undefined;
691
- let host = opts.host ?? env?.KINOTIC_SERVER_HOST;
892
+ let host = server.host ?? env?.KINOTIC_SERVER_HOST;
692
893
  const hostFromLocation = host == null && location != null;
693
894
  const hostDefaulted = host == null && location == null;
694
895
  if (host == null) {
695
896
  host = location?.hostname ?? DEFAULT_HOST;
696
897
  }
697
- let useSSL = opts.useSSL;
898
+ let useSSL = server.useSSL;
698
899
  if (useSSL == null) {
699
900
  if (env?.KINOTIC_SERVER_USE_SSL != null) {
700
901
  useSSL = env.KINOTIC_SERVER_USE_SSL === "true";
@@ -704,7 +905,7 @@ class Util {
704
905
  useSSL = hostDefaulted;
705
906
  }
706
907
  }
707
- let port = opts.port;
908
+ let port = server.port;
708
909
  if (port === undefined) {
709
910
  if (env?.KINOTIC_SERVER_PORT != null) {
710
911
  port = Number(env.KINOTIC_SERVER_PORT);
@@ -716,9 +917,7 @@ class Util {
716
917
  }
717
918
  return {
718
919
  ...opts,
719
- host,
720
- port,
721
- useSSL,
920
+ server: { host, port, useSSL },
722
921
  sessionKeepAlive: opts.sessionKeepAlive ?? "ACTIVITY" /* ACTIVITY */,
723
922
  credentials: opts.credentials ?? new ChainedCredentialsResolver(new EnvCredentialsResolver, new SessionCredentialsResolver)
724
923
  };
@@ -914,22 +1113,14 @@ class JsonArgumentResolver {
914
1113
  // packages/core/src/internal/api/ReturnValueConverter.ts
915
1114
  class BasicReturnValueConverter {
916
1115
  convert(incomingMetadata, returnValue) {
917
- return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(JSON.stringify(returnValue)));
1116
+ const json = returnValue === undefined ? "null" : JSON.stringify(returnValue);
1117
+ return Util.createReplyEvent(incomingMetadata, new Map([["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]]), new TextEncoder().encode(json));
918
1118
  }
919
1119
  }
920
1120
 
921
- // packages/core/src/internal/api/Logger.ts
922
- var import_debug2 = __toESM(require("debug"));
923
- function createDebugLogger(namespace) {
924
- const debugLogger = import_debug2.default(namespace);
925
- return {
926
- trace: (...args) => debugLogger("TRACE", ...args),
927
- debug: (...args) => debugLogger("DEBUG", ...args),
928
- info: (...args) => debugLogger("INFO", ...args),
929
- warn: (...args) => debugLogger("WARN", ...args),
930
- error: (...args) => debugLogger("ERROR", ...args)
931
- };
932
- }
1121
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1122
+ var import_rxjs3 = require("rxjs");
1123
+ var import_operators3 = require("rxjs/operators");
933
1124
 
934
1125
  // packages/core/src/api/ServiceIdentifier.ts
935
1126
  class ServiceIdentifier {
@@ -966,6 +1157,9 @@ class ServiceIdentifier {
966
1157
  }
967
1158
  return this._cri;
968
1159
  }
1160
+ unscopedCri() {
1161
+ return createCRI("srv" /* SERVICE_DESTINATION_SCHEME */, null, this.qualifiedName(), null, this.version || null);
1162
+ }
969
1163
  }
970
1164
 
971
1165
  // packages/core/src/api/ZoneUtil.ts
@@ -985,10 +1179,12 @@ function validateLabel(label) {
985
1179
 
986
1180
  // packages/core/src/api/KinoticDecorators.ts
987
1181
  var scopeFunctions = new WeakSet;
1182
+ var scopeOptionalFunctions = new WeakSet;
988
1183
  var versionRegistry = new WeakMap;
989
1184
  var zonesRegistry = new WeakMap;
990
1185
  var advertisedRegistry = new WeakMap;
991
1186
  var contextMarkedFunctions = new WeakSet;
1187
+ var authzResourceClasses = new WeakSet;
992
1188
  function findInConstructorChain(registry, constructor) {
993
1189
  let current = constructor;
994
1190
  while (current) {
@@ -1022,6 +1218,23 @@ function resolveScope(instance) {
1022
1218
  function Scope(value, _context) {
1023
1219
  scopeFunctions.add(value);
1024
1220
  }
1221
+ function ScopeOptional(value, _context) {
1222
+ scopeOptionalFunctions.add(value);
1223
+ }
1224
+ function scopeOptionalMethodNames(instance) {
1225
+ const ret = new Set;
1226
+ let proto = Object.getPrototypeOf(instance);
1227
+ while (proto && proto !== Object.prototype) {
1228
+ for (const key of Object.getOwnPropertyNames(proto)) {
1229
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1230
+ if (typeof descriptor?.value === "function" && scopeOptionalFunctions.has(descriptor.value)) {
1231
+ ret.add(key);
1232
+ }
1233
+ }
1234
+ proto = Object.getPrototypeOf(proto);
1235
+ }
1236
+ return ret;
1237
+ }
1025
1238
  function Version(version) {
1026
1239
  if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?$/.test(version)) {
1027
1240
  throw new Error(`Invalid semantic version: ${version}. Must follow X.Y.Z[-optional] format.`);
@@ -1062,6 +1275,23 @@ function resolveEffectiveZone(constructor) {
1062
1275
  }
1063
1276
  return effectiveZone;
1064
1277
  }
1278
+ function AuthzResource(declaration) {
1279
+ return function(value, _context) {
1280
+ authzResourceClasses.add(value);
1281
+ };
1282
+ }
1283
+ function AuthzCheck(declaration) {
1284
+ return function(_value, _context) {};
1285
+ }
1286
+ function declaresAuthzResource(serviceInstance) {
1287
+ let ret = false;
1288
+ let current = serviceInstance.constructor;
1289
+ while (current && !ret) {
1290
+ ret = authzResourceClasses.has(current);
1291
+ current = Object.getPrototypeOf(current);
1292
+ }
1293
+ return ret;
1294
+ }
1065
1295
  function Publish(namespace, name, advertise = false) {
1066
1296
  return function(value, _context) {
1067
1297
  advertisedRegistry.set(value, advertise);
@@ -1084,6 +1314,94 @@ function Publish(namespace, name, advertise = false) {
1084
1314
  };
1085
1315
  }
1086
1316
 
1317
+ // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1318
+ var import_api2 = __toESM(require("@opentelemetry/api"));
1319
+ // packages/core/package.json
1320
+ var package_default = {
1321
+ name: "@kinotic-ai/core",
1322
+ version: "5.0.0-beta.20",
1323
+ type: "module",
1324
+ files: [
1325
+ "dist"
1326
+ ],
1327
+ module: "./dist/index.js",
1328
+ main: "./dist/index.cjs",
1329
+ types: "./dist/index.d.ts",
1330
+ exports: {
1331
+ ".": {
1332
+ import: {
1333
+ types: "./dist/index.d.ts",
1334
+ default: "./dist/index.js"
1335
+ },
1336
+ require: {
1337
+ types: "./dist/index.d.cts",
1338
+ default: "./dist/index.cjs"
1339
+ }
1340
+ },
1341
+ "./node": {
1342
+ import: {
1343
+ types: "./dist/node/index.d.ts",
1344
+ default: "./dist/node/index.js"
1345
+ },
1346
+ require: {
1347
+ types: "./dist/node/index.d.cts",
1348
+ default: "./dist/node/index.cjs"
1349
+ }
1350
+ },
1351
+ "./package.json": "./package.json"
1352
+ },
1353
+ homepage: "https://github.com/kinotic-ai/kinotic",
1354
+ repository: {
1355
+ type: "git",
1356
+ url: "git+https://github.com/kinotic-ai/kinotic.git",
1357
+ directory: "kinotic-js/workspace/packages/core"
1358
+ },
1359
+ license: "Elastic License 2.0",
1360
+ publishConfig: {
1361
+ access: "public"
1362
+ },
1363
+ scripts: {
1364
+ "type-check": "tsc --noEmit",
1365
+ test: "vitest run",
1366
+ coverage: "vitest run --coverage",
1367
+ "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1368
+ },
1369
+ devDependencies: {
1370
+ "@opentelemetry/exporter-trace-otlp-grpc": "^0.221.0",
1371
+ "@opentelemetry/resources": "^2.10.0",
1372
+ "@opentelemetry/sdk-metrics": "^2.10.0",
1373
+ "@opentelemetry/sdk-node": "^0.221.0",
1374
+ "@opentelemetry/sdk-trace-node": "^2.10.0",
1375
+ "@types/debug": "^4.1.13",
1376
+ "@types/node": "^25.6.0",
1377
+ "@types/ws": "^8.18.0",
1378
+ "@vitest/coverage-v8": "^4.1.4",
1379
+ "@vitest/runner": "^4.1.4",
1380
+ "@vitest/ui": "^4.1.4",
1381
+ allure: "^3.19.1",
1382
+ "allure-vitest": "^3.13.0",
1383
+ dotenv: "^17.4.1",
1384
+ "properties-file": "^4.0.0",
1385
+ testcontainers: "^11.14.0",
1386
+ tslib: "^2.8.1",
1387
+ typescript: "^6.0.2",
1388
+ vitest: "^4.1.4"
1389
+ },
1390
+ dependencies: {
1391
+ "@kinotic-ai/idl": "workspace:*",
1392
+ "@opentelemetry/api": "^1.9.1",
1393
+ "@opentelemetry/semantic-conventions": "^1.40.0",
1394
+ "@stomp/rx-stomp": "^2.4.0",
1395
+ "@stomp/stompjs": "^7.3.0",
1396
+ debug: "^4.4.3",
1397
+ "p-tap": "^4.0.0",
1398
+ rxjs: "^7.8.2",
1399
+ "typescript-optional": "3.0.0-alpha.3",
1400
+ uuid: "^13.0.0",
1401
+ ws: "^8.21.0"
1402
+ }
1403
+ };
1404
+
1087
1405
  // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1088
1406
  class ServiceInvocationSupervisor {
1089
1407
  log;
@@ -1095,7 +1413,13 @@ class ServiceInvocationSupervisor {
1095
1413
  serviceIdentifier;
1096
1414
  serviceInstance;
1097
1415
  methodSubscription = null;
1416
+ unscopedSubscription = null;
1417
+ activeStreams = new Map;
1418
+ connectionEndedSubscription = null;
1419
+ connectionGeneration = 0;
1098
1420
  methodMap;
1421
+ scopeOptionalMethods;
1422
+ tracer;
1099
1423
  constructor(serviceIdentifier, serviceInstance, eventBusService, interceptorProvider, options = {}) {
1100
1424
  if (!serviceIdentifier)
1101
1425
  throw new Error("ServiceIdentifier must not be null");
@@ -1109,10 +1433,12 @@ class ServiceInvocationSupervisor {
1109
1433
  this.serviceInstance = serviceInstance;
1110
1434
  this._eventBus = eventBusService;
1111
1435
  this.interceptorProvider = interceptorProvider;
1112
- this.log = options.logger || createDebugLogger("kinoitc:ServiceInvocationSupervisor");
1436
+ this.log = options.logger || createDebugLogger("kinotic:ServiceInvocationSupervisor");
1113
1437
  this.argumentResolver = options.argumentResolver || new JsonArgumentResolver;
1114
1438
  this.returnValueConverter = options.returnValueConverter || new BasicReturnValueConverter;
1115
1439
  this.methodMap = this.buildMethodMap(serviceInstance);
1440
+ this.scopeOptionalMethods = scopeOptionalMethodNames(serviceInstance);
1441
+ this.tracer = import_api2.default.trace.getTracer(package_default.name, package_default.version);
1116
1442
  }
1117
1443
  isActive() {
1118
1444
  return this.active;
@@ -1132,7 +1458,22 @@ class ServiceInvocationSupervisor {
1132
1458
  }
1133
1459
  this.active = true;
1134
1460
  const criBase = this.serviceIdentifier.cri().baseResource();
1135
- this.methodSubscription = this._eventBus.observe(criBase).subscribe({
1461
+ this.methodSubscription = this.subscribeAt(criBase);
1462
+ this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1463
+ if (this.serviceIdentifier.scope && this.scopeOptionalMethods.size > 0) {
1464
+ const unscopedBase = this.serviceIdentifier.unscopedCri().baseResource();
1465
+ this.unscopedSubscription = this.subscribeAt(unscopedBase);
1466
+ this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
1467
+ }
1468
+ this.connectionEndedSubscription = this._eventBus.connectionEnded.subscribe(() => {
1469
+ this.connectionGeneration++;
1470
+ for (const stream of this.activeStreams.values()) {
1471
+ stream.subscription.unsubscribe();
1472
+ }
1473
+ });
1474
+ }
1475
+ subscribeAt(criBase) {
1476
+ return this._eventBus.observe(criBase).subscribe({
1136
1477
  next: async (event) => {
1137
1478
  await this.processEvent(event);
1138
1479
  },
@@ -1145,7 +1486,6 @@ class ServiceInvocationSupervisor {
1145
1486
  this.active = false;
1146
1487
  }
1147
1488
  });
1148
- this.log.info(`ServiceInvocationSupervisor started for ${criBase}`);
1149
1489
  }
1150
1490
  stop() {
1151
1491
  if (!this.active) {
@@ -1154,6 +1494,15 @@ class ServiceInvocationSupervisor {
1154
1494
  this.active = false;
1155
1495
  this.methodSubscription?.unsubscribe();
1156
1496
  this.methodSubscription = null;
1497
+ this.unscopedSubscription?.unsubscribe();
1498
+ this.unscopedSubscription = null;
1499
+ this.connectionEndedSubscription?.unsubscribe();
1500
+ this.connectionEndedSubscription = null;
1501
+ const serviceName = this.serviceIdentifier.qualifiedName();
1502
+ for (const stream of this.activeStreams.values()) {
1503
+ this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
1504
+ stream.subscription.unsubscribe();
1505
+ }
1157
1506
  this.log.info("ServiceInvocationSupervisor stopped");
1158
1507
  }
1159
1508
  buildMethodMap(serviceInstance) {
@@ -1193,10 +1542,19 @@ class ServiceInvocationSupervisor {
1193
1542
  if (!correlationId) {
1194
1543
  throw new Error("Streaming control plane messages require a CORRELATION_ID_HEADER");
1195
1544
  }
1196
- this.log.trace(`Processing control event for correlationId: ${correlationId}`);
1545
+ const control = event.getHeader("control" /* CONTROL_HEADER */);
1546
+ this.log.trace(`Processing control event ${control} for correlationId: ${correlationId}`);
1547
+ const stream = this.activeStreams.get(correlationId);
1548
+ if (stream) {
1549
+ stream.subscription.unsubscribe();
1550
+ if (control !== "cancel" /* CONTROL_VALUE_CANCEL */) {
1551
+ throw new Error(`Unknown control header value ${control}`);
1552
+ }
1553
+ }
1197
1554
  }
1198
1555
  async processInvocationRequest(event) {
1199
- const path = createCRI(event.cri).path();
1556
+ const incomingCri = createCRI(event.cri);
1557
+ const path = incomingCri.path();
1200
1558
  if (!path) {
1201
1559
  throw new Error("The methodId must not be blank");
1202
1560
  }
@@ -1204,49 +1562,167 @@ class ServiceInvocationSupervisor {
1204
1562
  if (!handlerMethod) {
1205
1563
  throw new Error(`No method resolved for methodId ${path}`);
1206
1564
  }
1565
+ if (this.serviceIdentifier.scope && !incomingCri.hasScope() && !this.scopeOptionalMethods.has(path)) {
1566
+ throw new Error(`Method ${path} of ${this.serviceIdentifier.qualifiedName()} requires a scoped invocation naming the service instance`);
1567
+ }
1207
1568
  const methodName = path;
1208
- const args = this.argumentResolver.resolveArguments(event);
1209
- const injectContext = receivesContext(this.serviceInstance, methodName);
1210
- let context2 = {};
1211
- const interceptor = this.interceptorProvider();
1212
- if (interceptor) {
1569
+ const span = this.startInvocationSpan(event, methodName);
1570
+ const generation = this.connectionGeneration;
1571
+ try {
1572
+ const args = this.argumentResolver.resolveArguments(event);
1573
+ const injectContext = receivesContext(this.serviceInstance, methodName);
1574
+ let serviceContext = {};
1575
+ const sender = event.getHeader("sender" /* SENDER_HEADER */);
1576
+ if (sender) {
1577
+ serviceContext.participant = JSON.parse(sender);
1578
+ }
1579
+ const interceptor = this.interceptorProvider();
1580
+ if (interceptor) {
1581
+ try {
1582
+ serviceContext = await interceptor.intercept(event, serviceContext);
1583
+ } catch (e) {
1584
+ this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1585
+ if (this.replyOwed(generation)) {
1586
+ this.handleException(event, new Error("Internal server error"));
1587
+ }
1588
+ this.failSpan(span, e);
1589
+ return;
1590
+ }
1591
+ }
1592
+ if (injectContext) {
1593
+ args.push(serviceContext);
1594
+ }
1595
+ const expectedArgsCount = handlerMethod.length;
1596
+ if (args.length !== expectedArgsCount) {
1597
+ throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1598
+ }
1599
+ let result;
1213
1600
  try {
1214
- context2 = await interceptor.intercept(event, context2);
1601
+ result = import_api2.context.with(import_api2.trace.setSpan(import_api2.context.active(), span), () => handlerMethod(...args));
1602
+ if (result instanceof Promise) {
1603
+ result.then((resolved) => this.processMethodInvocationResult(event, resolved, span, generation), (error) => this.failInvocation(event, error, span, generation)).catch((e) => {
1604
+ this.failInvocation(event, e, span, generation);
1605
+ });
1606
+ } else {
1607
+ this.processMethodInvocationResult(event, result, span, generation);
1608
+ }
1215
1609
  } catch (e) {
1216
- this.log.error(`Interceptor failed to create context for event: ${JSON.stringify(event)}`, e);
1217
- this.handleException(event, new Error("Internal server error"));
1218
- return;
1610
+ this.failInvocation(event, e, span, generation);
1219
1611
  }
1612
+ } catch (e) {
1613
+ this.failSpan(span, e);
1614
+ throw e;
1615
+ }
1616
+ }
1617
+ startInvocationSpan(event, methodName) {
1618
+ const carrier = {};
1619
+ for (const [key, value] of event.headers.entries()) {
1620
+ carrier[key] = value;
1621
+ }
1622
+ const serviceName = this.serviceIdentifier.qualifiedName();
1623
+ return this.tracer.startSpan(`${this.serviceIdentifier.name}/${methodName}`, {
1624
+ kind: import_api2.SpanKind.SERVER,
1625
+ attributes: {
1626
+ "rpc.system": "kinotic",
1627
+ "rpc.service": serviceName,
1628
+ "rpc.method": methodName
1629
+ }
1630
+ }, import_api2.propagation.extract(import_api2.context.active(), carrier));
1631
+ }
1632
+ failSpan(span, error) {
1633
+ span.recordException(error);
1634
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1635
+ span.end();
1636
+ }
1637
+ replyOwed(generation) {
1638
+ return generation === this.connectionGeneration;
1639
+ }
1640
+ failInvocation(event, error, span, generation) {
1641
+ if (this.replyOwed(generation)) {
1642
+ this.handleException(event, error);
1643
+ }
1644
+ this.failSpan(span, error);
1645
+ }
1646
+ processMethodInvocationResult(event, result, span, generation) {
1647
+ if (!this.replyOwed(generation)) {
1648
+ span.end();
1649
+ } else if (import_rxjs3.isObservable(result)) {
1650
+ this.streamResult(event, result, span);
1651
+ } else {
1652
+ const reply = this.returnValueConverter.convert(event.headers, result);
1653
+ reply.setHeader("control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */);
1654
+ this.sendReply(reply);
1655
+ span.end();
1220
1656
  }
1221
- if (injectContext) {
1222
- args.push(context2);
1657
+ }
1658
+ streamResult(event, stream, span) {
1659
+ const correlationId = event.getHeader("__correlation-id" /* CORRELATION_ID_HEADER */);
1660
+ if (!correlationId) {
1661
+ throw new Error("Streaming results require a CORRELATION_ID_HEADER to be set");
1662
+ }
1663
+ let subscription = null;
1664
+ let failed = false;
1665
+ subscription = stream.pipe(import_operators3.finalize(() => {
1666
+ this.activeStreams.delete(correlationId);
1667
+ span.end();
1668
+ })).subscribe({
1669
+ next: (value) => {
1670
+ if (failed) {
1671
+ return;
1672
+ }
1673
+ try {
1674
+ const reply = this.returnValueConverter.convert(event.headers, value);
1675
+ reply.setHeader("__origin-cri" /* ORIGIN_CRI_HEADER */, event.cri);
1676
+ this.sendReply(reply);
1677
+ } catch (e) {
1678
+ failed = true;
1679
+ this.handleException(event, e);
1680
+ span.recordException(e);
1681
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1682
+ subscription?.unsubscribe();
1683
+ }
1684
+ },
1685
+ error: (error) => {
1686
+ if (failed) {
1687
+ return;
1688
+ }
1689
+ this.handleException(event, error);
1690
+ span.recordException(error);
1691
+ span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1692
+ },
1693
+ complete: () => {
1694
+ if (failed) {
1695
+ return;
1696
+ }
1697
+ this.sendReply(Util.createReplyEvent(event.headers, new Map([["control" /* CONTROL_HEADER */, "complete" /* CONTROL_VALUE_COMPLETE */]])));
1698
+ }
1699
+ });
1700
+ if (failed) {
1701
+ subscription.unsubscribe();
1223
1702
  }
1224
- const expectedArgsCount = handlerMethod.length;
1225
- if (args.length !== expectedArgsCount) {
1226
- throw new Error(`Argument count mismatch for method ${path}: expected ${expectedArgsCount}, got ${args.length}`);
1703
+ if (!subscription.closed) {
1704
+ this.activeStreams.set(correlationId, { request: event, subscription });
1227
1705
  }
1228
- let result;
1706
+ }
1707
+ sendReply(event) {
1229
1708
  try {
1230
- result = handlerMethod(...args);
1231
- if (result instanceof Promise) {
1232
- result.then((resolved) => this.processMethodInvocationResult(event, resolved), (error) => this.handleException(event, error));
1233
- } else {
1234
- this.processMethodInvocationResult(event, result);
1235
- }
1709
+ this._eventBus.send(event);
1236
1710
  } catch (e) {
1237
- this.handleException(event, e);
1711
+ this.log.warn(`Could not send reply to ${event.cri}`, e);
1238
1712
  }
1239
1713
  }
1240
- processMethodInvocationResult(event, result) {
1241
- const outgoingEvent = this.returnValueConverter.convert(event.headers, result);
1242
- this._eventBus.send(outgoingEvent);
1243
- }
1244
1714
  handleException(event, error) {
1245
- const errorEvent = Util.createReplyEvent(event.headers, new Map([
1246
- ["error" /* ERROR_HEADER */, error.message || "Unknown error"],
1247
- ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1248
- ]), new TextEncoder().encode(JSON.stringify({ message: error.message })));
1249
- this._eventBus.send(errorEvent);
1715
+ try {
1716
+ const errorMessage = error?.message || "Unknown error";
1717
+ const exceptionName = error instanceof Error ? error.constructor.name : "Error";
1718
+ const errorEvent = Util.createReplyEvent(event.headers, new Map([
1719
+ ["error" /* ERROR_HEADER */, errorMessage],
1720
+ ["content-type" /* CONTENT_TYPE_HEADER */, "application/json"]
1721
+ ]), new TextEncoder().encode(JSON.stringify({ exceptionName, exceptionClass: exceptionName, errorMessage })));
1722
+ this.sendReply(errorEvent);
1723
+ } catch (e) {
1724
+ this.log.warn(`Could not build the error reply for ${event.cri}`, e);
1725
+ }
1250
1726
  }
1251
1727
  validateReplyTo(event) {
1252
1728
  const replyTo = event.getHeader("reply-to" /* REPLY_TO_HEADER */);
@@ -1267,97 +1743,9 @@ class ServiceInvocationSupervisor {
1267
1743
  }
1268
1744
 
1269
1745
  // packages/core/src/api/ServiceRegistry.ts
1270
- var import_api2 = __toESM(require("@opentelemetry/api"));
1746
+ var import_api3 = __toESM(require("@opentelemetry/api"));
1271
1747
  var import_semantic_conventions = require("@opentelemetry/semantic-conventions");
1272
- var import_operators2 = require("rxjs/operators");
1273
- // packages/core/package.json
1274
- var package_default = {
1275
- name: "@kinotic-ai/core",
1276
- version: "5.0.0-beta.2",
1277
- type: "module",
1278
- files: [
1279
- "dist"
1280
- ],
1281
- module: "./dist/index.js",
1282
- main: "./dist/index.cjs",
1283
- types: "./dist/index.d.ts",
1284
- exports: {
1285
- ".": {
1286
- import: {
1287
- types: "./dist/index.d.ts",
1288
- default: "./dist/index.js"
1289
- },
1290
- require: {
1291
- types: "./dist/index.d.cts",
1292
- default: "./dist/index.cjs"
1293
- }
1294
- },
1295
- "./node": {
1296
- import: {
1297
- types: "./dist/node/index.d.ts",
1298
- default: "./dist/node/index.js"
1299
- },
1300
- require: {
1301
- types: "./dist/node/index.d.cts",
1302
- default: "./dist/node/index.cjs"
1303
- }
1304
- },
1305
- "./package.json": "./package.json"
1306
- },
1307
- homepage: "https://github.com/kinotic-ai/kinotic",
1308
- license: "Elastic License 2.0",
1309
- publishConfig: {
1310
- access: "public"
1311
- },
1312
- scripts: {
1313
- "type-check": "tsc --noEmit",
1314
- test: "vitest run",
1315
- coverage: "vitest run --coverage",
1316
- "ui-test": "vitest --ui --coverage.enabled=true --mode development"
1317
- },
1318
- devDependencies: {
1319
- "@opentelemetry/exporter-trace-otlp-grpc": "^0.214.0",
1320
- "@opentelemetry/resources": "^2.6.1",
1321
- "@opentelemetry/sdk-metrics": "^2.6.1",
1322
- "@opentelemetry/sdk-node": "^0.214.0",
1323
- "@opentelemetry/sdk-trace-node": "^2.6.1",
1324
- "@types/node": "^25.6.0",
1325
- "@types/uuid": "^11.0.0",
1326
- "@types/ws": "^8.18.0",
1327
- "@vitest/coverage-v8": "^4.1.4",
1328
- "@vitest/runner": "^4.1.4",
1329
- "@vitest/ui": "^4.1.4",
1330
- allure: "^3.4.1",
1331
- "allure-vitest": "^3.7.1",
1332
- dotenv: "^17.4.1",
1333
- "properties-file": "^4.0.0",
1334
- testcontainers: "^11.14.0",
1335
- tslib: "^2.8.1",
1336
- typescript: "^6.0.2",
1337
- vitest: "^4.1.4",
1338
- ws: "^8.20.0"
1339
- },
1340
- dependencies: {
1341
- "@opentelemetry/api": "^1.9.1",
1342
- "@opentelemetry/semantic-conventions": "^1.40.0",
1343
- "@stomp/rx-stomp": "^2.4.0",
1344
- "@stomp/stompjs": "^7.3.0",
1345
- "@types/debug": "^4.1.13",
1346
- debug: "^4.4.3",
1347
- "p-tap": "^4.0.0",
1348
- rxjs: "^7.8.2",
1349
- "typescript-optional": "3.0.0-alpha.3",
1350
- uuid: "^13.0.0",
1351
- ws: "^8.18.0"
1352
- },
1353
- peerDependenciesMeta: {
1354
- typescript: {
1355
- optional: true
1356
- }
1357
- }
1358
- };
1359
-
1360
- // packages/core/src/api/ServiceRegistry.ts
1748
+ var import_operators4 = require("rxjs/operators");
1361
1749
  class JsonEventFactory {
1362
1750
  create(cri, args) {
1363
1751
  const event = new Event(cri);
@@ -1391,12 +1779,63 @@ class TextEventFactory {
1391
1779
  return event;
1392
1780
  }
1393
1781
  }
1782
+ var SERVICE_DIRECTORY_SERVICE = "app-api~org.kinotic.app.api.services.ServiceDirectoryService";
1783
+ var APPLICATION_ZONE = /^app\.[^.]+\.([^.]+)(\.|$)/;
1784
+ var declaredDefinitions = new Map;
1785
+ function declareServiceDefinitions(definitions) {
1786
+ for (const definition of definitions) {
1787
+ declaredDefinitions.set(qualifiedNameOf(definition.namespace, definition.name), definition);
1788
+ }
1789
+ }
1790
+ function qualifiedNameOf(namespace, name) {
1791
+ return namespace ? `${namespace}.${name}` : name;
1792
+ }
1793
+ function servedFunctions(serviceInstance) {
1794
+ const ret = new Set;
1795
+ let proto = Object.getPrototypeOf(serviceInstance);
1796
+ while (proto && proto !== Object.prototype) {
1797
+ for (const key of Object.getOwnPropertyNames(proto)) {
1798
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1799
+ if (typeof descriptor?.value === "function" && key !== "constructor") {
1800
+ ret.add(key);
1801
+ }
1802
+ }
1803
+ proto = Object.getPrototypeOf(proto);
1804
+ }
1805
+ return [...ret].sort();
1806
+ }
1807
+ function directoryEntryOf(serviceInstance, serviceIdentifier) {
1808
+ let ret = null;
1809
+ const application = serviceIdentifier.zone ? APPLICATION_ZONE.exec(serviceIdentifier.zone) : null;
1810
+ if (application) {
1811
+ const qualifiedName = qualifiedNameOf(serviceIdentifier.namespace, serviceIdentifier.name);
1812
+ const definition = declaredDefinitions.get(qualifiedName);
1813
+ if (definition) {
1814
+ const declared = definition.functions.map((f) => f.name).sort();
1815
+ const served = servedFunctions(serviceInstance);
1816
+ if (declared.join() !== served.join()) {
1817
+ throw new Error(`${qualifiedName} serves the functions [${served}] but its definition declares [${declared}];` + " run kinotic sync and import the generated ServiceDefinitions module");
1818
+ }
1819
+ ret = {
1820
+ applicationId: application[1],
1821
+ zone: serviceIdentifier.zone,
1822
+ version: serviceIdentifier.version ?? null,
1823
+ advertised: isAdvertised(serviceInstance),
1824
+ serviceDefinition: definition
1825
+ };
1826
+ } else if (declaresAuthzResource(serviceInstance)) {
1827
+ throw new Error(`${qualifiedName} declares a resource but the project declares no definition for it;` + " run kinotic sync and import the generated ServiceDefinitions module");
1828
+ }
1829
+ }
1830
+ return ret;
1831
+ }
1394
1832
 
1395
1833
  class ServiceRegistry {
1396
1834
  _eventBus;
1397
1835
  supervisors = new Map;
1836
+ entries = new Map;
1398
1837
  contextInterceptor = null;
1399
- debugLogger = import_debug3.default("kinoitc:serviceRegistry");
1838
+ debugLogger = import_debug3.default("kinotic:serviceRegistry");
1400
1839
  constructor(eventBus) {
1401
1840
  this._eventBus = eventBus;
1402
1841
  }
@@ -1416,9 +1855,16 @@ class ServiceRegistry {
1416
1855
  const criString = serviceIdentifier.cri().raw();
1417
1856
  if (!this.supervisors.has(criString)) {
1418
1857
  this.debugLogger(`Registering service for CRI: ${criString}`);
1858
+ const entry = directoryEntryOf(service, serviceIdentifier);
1419
1859
  const supervisor = new ServiceInvocationSupervisor(serviceIdentifier, service, this.eventBus, () => this.contextInterceptor);
1420
1860
  this.supervisors.set(criString, supervisor);
1421
1861
  supervisor.start();
1862
+ if (entry) {
1863
+ this.entries.set(criString, entry);
1864
+ if (this.eventBus.isConnected()) {
1865
+ this.registerEntry(entry).catch((error) => this.debugLogger(`Failed to register ${criString} in the directory`, error));
1866
+ }
1867
+ }
1422
1868
  }
1423
1869
  }
1424
1870
  unRegister(serviceIdentifier) {
@@ -1428,8 +1874,18 @@ class ServiceRegistry {
1428
1874
  this.debugLogger(`Unregistering service for CRI: ${criString}`);
1429
1875
  supervisor.stop();
1430
1876
  this.supervisors.delete(criString);
1877
+ this.entries.delete(criString);
1431
1878
  }
1432
1879
  }
1880
+ async registerEntries() {
1881
+ for (const entry of this.entries.values()) {
1882
+ await this.registerEntry(entry);
1883
+ }
1884
+ }
1885
+ async registerEntry(entry) {
1886
+ this.debugLogger(`Registering ${entry.zone}~${qualifiedNameOf(entry.serviceDefinition.namespace, entry.serviceDefinition.name)} in the directory`);
1887
+ await this.serviceProxy(SERVICE_DIRECTORY_SERVICE).invoke("register", [entry]);
1888
+ }
1433
1889
  registerContextInterceptor(interceptor) {
1434
1890
  this.contextInterceptor = interceptor;
1435
1891
  }
@@ -1446,24 +1902,24 @@ class ServiceProxy {
1446
1902
  }
1447
1903
  this.serviceIdentifier = serviceIdentifier;
1448
1904
  this.serviceRegistry = serviceRegistry;
1449
- this.tracer = import_api2.default.trace.getTracer("kinoitc.client", package_default.version);
1905
+ this.tracer = import_api3.default.trace.getTracer(package_default.name, package_default.version);
1450
1906
  }
1451
1907
  invoke(methodIdentifier, args, scope, eventFactory) {
1452
1908
  return this.tracer.startActiveSpan(`${this.serviceIdentifier}/${methodIdentifier}`, {
1453
- kind: import_api2.SpanKind.CLIENT
1909
+ kind: import_api3.SpanKind.CLIENT
1454
1910
  }, async (span) => {
1455
1911
  if (scope) {
1456
- span.setAttribute("kinoitc.scope", scope);
1912
+ span.setAttribute("kinotic.scope", scope);
1457
1913
  }
1458
- span.setAttribute("rpc.system", "kinoitc");
1914
+ span.setAttribute("rpc.system", "kinotic");
1459
1915
  span.setAttribute("rpc.service", this.serviceIdentifier);
1460
1916
  span.setAttribute("rpc.method", methodIdentifier);
1461
- return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(import_operators2.first()).toPromise().then(async (value) => {
1917
+ return this.__invokeStream(false, methodIdentifier, args, scope, eventFactory).pipe(import_operators4.first()).toPromise().then(async (value) => {
1462
1918
  span.end();
1463
1919
  return value;
1464
1920
  }, async (ex) => {
1465
1921
  span.recordException(ex);
1466
- span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
1922
+ span.setStatus({ code: import_api3.SpanStatusCode.ERROR });
1467
1923
  span.end();
1468
1924
  throw ex;
1469
1925
  });
@@ -1479,13 +1935,13 @@ class ServiceProxy {
1479
1935
  eventFactoryToUse = eventFactory;
1480
1936
  }
1481
1937
  let eventBusToUse = this.serviceRegistry.eventBus;
1482
- const span = import_api2.default.trace.getActiveSpan();
1938
+ const span = import_api3.default.trace.getActiveSpan();
1483
1939
  if (span) {
1484
1940
  span.setAttribute(import_semantic_conventions.ATTR_SERVER_ADDRESS, eventBusToUse.serverInfo?.host || "unknown");
1485
1941
  span.setAttribute(import_semantic_conventions.ATTR_SERVER_PORT, eventBusToUse.serverInfo?.port || "unknown");
1486
1942
  }
1487
1943
  let event = eventFactoryToUse.create(cri, args);
1488
- return eventBusToUse.requestStream(event, sendControlEvents).pipe(import_operators2.map((value) => {
1944
+ return eventBusToUse.requestStream(event, sendControlEvents).pipe(import_operators4.map((value) => {
1489
1945
  const contentType = value.getHeader("content-type" /* CONTENT_TYPE_HEADER */);
1490
1946
  if (contentType !== undefined) {
1491
1947
  if (contentType === "application/json" /* CONTENT_JSON */) {
@@ -1521,8 +1977,10 @@ class KinoticSingleton {
1521
1977
  this._eventBus = eventBus;
1522
1978
  this.serviceRegistry.eventBus = eventBus;
1523
1979
  }
1524
- connect(options) {
1525
- return this._eventBus.connect(Util.resolveConnectOptions(options));
1980
+ async connect(options) {
1981
+ const ret = await this._eventBus.connect(Util.resolveConnectOptions(options));
1982
+ await this.serviceRegistry.registerEntries();
1983
+ return ret;
1526
1984
  }
1527
1985
  disconnect(force) {
1528
1986
  return this._eventBus.disconnect(force);
@@ -1643,6 +2101,9 @@ class CrudServiceProxy {
1643
2101
  deleteById(id) {
1644
2102
  return this.serviceProxy.invoke("deleteById", [id]);
1645
2103
  }
2104
+ deleteByIdSync(id) {
2105
+ return this.serviceProxy.invoke("deleteByIdSync", [id]);
2106
+ }
1646
2107
  async findAll(pageable) {
1647
2108
  const page = await this.findAllSinglePage(pageable);
1648
2109
  return new FindAllIterablePage(pageable, page, this);
@@ -1765,32 +2226,11 @@ class Order {
1765
2226
  class Sort {
1766
2227
  orders = [];
1767
2228
  }
1768
- // packages/core/src/api/security/BasicCredentialsResolver.ts
1769
- class BasicCredentialsResolver {
1770
- name = "BasicCredentialsResolver";
1771
- credentials;
1772
- constructor(clientId, clientSecret, organizationId, applicationId) {
1773
- const authHeaders = { clientId, clientSecret };
1774
- if (organizationId != null)
1775
- authHeaders.organizationId = organizationId;
1776
- if (applicationId != null)
1777
- authHeaders.applicationId = applicationId;
1778
- this.credentials = { authHeaders, organizationId, applicationId };
1779
- }
1780
- async resolve(_server) {
1781
- return this.credentials;
1782
- }
1783
- }
1784
- // packages/core/src/api/security/BearerCredentialsResolver.ts
1785
- class BearerCredentialsResolver {
1786
- name = "BearerCredentialsResolver";
1787
- token;
1788
- constructor(token) {
1789
- this.token = token;
1790
- }
1791
- async resolve(_server) {
1792
- const token = typeof this.token === "function" ? await this.token() : this.token;
1793
- return { authHeaders: { Authorization: `Bearer ${token}` } };
2229
+ // packages/core/src/api/security/AuthorizationException.ts
2230
+ class AuthorizationException extends Error {
2231
+ constructor(message = "Access denied") {
2232
+ super(message);
2233
+ this.name = "AuthorizationException";
1794
2234
  }
1795
2235
  }
1796
2236
  // packages/core/src/api/security/ConnectedInfo.ts