@weave-js/core 0.15.3 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/index.mjs +0 -0
  2. package/lib/broker/context.js +4 -11
  3. package/lib/broker/defaultOptions.js +3 -2
  4. package/lib/broker/index.js +80 -26
  5. package/lib/broker/public.d.ts +2 -1
  6. package/lib/buildRuntime.js +30 -13
  7. package/lib/cache/adapters/index.js +14 -0
  8. package/lib/cache/lock.js +17 -0
  9. package/lib/errorHandler.js +27 -2
  10. package/lib/errors.js +11 -1
  11. package/lib/helper/defineAction.js +22 -7
  12. package/lib/helper/defineBrokerOptions.js +26 -8
  13. package/lib/helper/defineService.js +29 -5
  14. package/lib/index.js +69 -19
  15. package/lib/logger/format/asHumanReadable.js +4 -4
  16. package/lib/metrics/common.js +1 -1
  17. package/lib/metrics/exporter/base.js +2 -2
  18. package/lib/metrics/exporter/event.js +15 -13
  19. package/lib/metrics/exporter/index.js +1 -1
  20. package/lib/metrics/index.js +28 -0
  21. package/lib/middlewares/bulkhead/index.js +3 -3
  22. package/lib/middlewares/cache/index.js +6 -5
  23. package/lib/middlewares/context-tracker/index.js +12 -5
  24. package/lib/middlewares/index.js +18 -0
  25. package/lib/middlewares/tracing/tags.js +2 -2
  26. package/lib/middlewares/validator/index.js +2 -2
  27. package/lib/registry/actionEndpoint.js +5 -5
  28. package/lib/registry/collections/actionCollection.js +2 -2
  29. package/lib/registry/collections/endpointCollection.js +5 -5
  30. package/lib/registry/collections/eventCollection.js +5 -5
  31. package/lib/registry/collections/nodeCollection.js +2 -2
  32. package/lib/registry/collections/serviceCollection.js +2 -2
  33. package/lib/registry/node.js +1 -1
  34. package/lib/registry/registry.js +24 -15
  35. package/lib/registry/service/parseAction.js +11 -2
  36. package/lib/registry/service/parseEvent.js +2 -1
  37. package/lib/registry/service/service.js +29 -8
  38. package/lib/registry/serviceItem.js +2 -2
  39. package/lib/runtime/initActionInvoker.js +5 -1
  40. package/lib/runtime/initCache.js +4 -0
  41. package/lib/runtime/initContextFactory.js +6 -15
  42. package/lib/runtime/initEventbus.js +25 -4
  43. package/lib/runtime/initLogger.js +30 -10
  44. package/lib/runtime/initMetrics.js +18 -8
  45. package/lib/runtime/initRegistry.js +1 -1
  46. package/lib/runtime/initServiceManager.js +4 -0
  47. package/lib/runtime/initTracing.js +5 -1
  48. package/lib/runtime/initTransport.js +1 -1
  49. package/lib/runtime/initUuidFactory.js +1 -5
  50. package/lib/runtime/initValidator.js +1 -6
  51. package/lib/tracing/collectors/base.js +21 -3
  52. package/lib/tracing/collectors/event.js +10 -0
  53. package/lib/tracing/collectors/index.js +34 -1
  54. package/lib/transport/adapters/adapterBase.js +14 -4
  55. package/lib/transport/adapters/fromURI.js +31 -23
  56. package/lib/transport/createTransport.js +30 -13
  57. package/lib/transport/messageHandlers.js +3 -3
  58. package/lib/utils/index.js +17 -1
  59. package/lib/utils/options.js +70 -2
  60. package/lib/utils/restoreError.js +25 -0
  61. package/lib/utils/wrap-handler.js +22 -0
  62. package/package.json +2 -1
  63. package/types/index.d.ts +958 -0
  64. /package/lib/{types.js → types.__js} +0 -0
@@ -0,0 +1,958 @@
1
+ import { Stream, Writable } from 'stream';
2
+ import { EventEmitter } from 'events';
3
+
4
+ // ===== UTILITY TYPES =====
5
+
6
+ /**
7
+ * Log level type definition
8
+ */
9
+ export type LogLevel = 'verbose' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
10
+
11
+ /**
12
+ * Service action visibility levels
13
+ */
14
+ export type ServiceActionVisibility = 'published' | 'public' | 'protected' | 'private';
15
+
16
+ /**
17
+ * Type mapping for parameter validation
18
+ */
19
+ export interface TypeMap {
20
+ string: string;
21
+ number: number;
22
+ boolean: boolean;
23
+ email: string;
24
+ object: object;
25
+ array: any[];
26
+ date: Date;
27
+ uuid: string;
28
+ url: string;
29
+ any: any;
30
+ }
31
+
32
+ /**
33
+ * Utility type to convert parameter schemas to actual types
34
+ */
35
+ export type ParamsToType<TParams extends Record<string, { type: keyof TypeMap }>> = {
36
+ [K in keyof TParams]: TypeMap[TParams[K]['type']];
37
+ };
38
+
39
+ // ===== CORE INTERFACES =====
40
+
41
+ /**
42
+ * Unique identifier for spans in tracing
43
+ */
44
+ export interface Span {
45
+ id: string;
46
+ sampled: boolean;
47
+ parentId?: string;
48
+ traceId?: string;
49
+ operationName?: string;
50
+ startTime?: number;
51
+ finishTime?: number;
52
+ tags?: Record<string, any>;
53
+ logs?: Array<{ timestamp: number; fields: Record<string, any> }>;
54
+ }
55
+
56
+ /**
57
+ * Context metadata object
58
+ */
59
+ export interface ContextMetaObject {
60
+ user?: any;
61
+ headers?: Record<string, any>;
62
+ timeout?: number;
63
+ retryCount?: number;
64
+ requestId?: string;
65
+ [key: string]: any;
66
+ }
67
+
68
+ /**
69
+ * Action options for service calls
70
+ */
71
+ export interface ActionOptions {
72
+ context?: Context;
73
+ parentContext?: Context;
74
+ meta?: ContextMetaObject;
75
+ stream?: Stream;
76
+ timeout?: number;
77
+ retryCount?: number;
78
+ custom?: Record<string, any>;
79
+ requestId?: string;
80
+ parentSpan?: Span;
81
+ nodeId?: string;
82
+ }
83
+
84
+ /**
85
+ * Event options for event broadcasting
86
+ */
87
+ export interface EventOptions {
88
+ groups?: string[];
89
+ nodeId?: string;
90
+ broadcast?: boolean;
91
+ }
92
+
93
+ /**
94
+ * Request context passed to actions and events
95
+ */
96
+ export interface Context<T = any> {
97
+ id?: string;
98
+ requestId?: string;
99
+ nodeId: string;
100
+ callerNodeId?: string;
101
+ parentContext?: Context;
102
+ parentId?: string;
103
+ endpoint?: Endpoint;
104
+ data: T;
105
+ meta: ContextMetaObject;
106
+ level: number;
107
+ retryCount?: number;
108
+ tracing: boolean;
109
+ span: Span;
110
+ isCachedResult?: boolean;
111
+ eventType?: string;
112
+ eventName?: string;
113
+ eventGroups?: string[];
114
+ options: ActionOptions;
115
+ duration: number;
116
+ stopTime: number;
117
+ metrics?: any;
118
+
119
+ // Methods
120
+ setData(data: any): void;
121
+ call<TParams = any, TResult = any>(actionName: string, params?: TParams, options?: ActionOptions): Promise<TResult>;
122
+ emit(eventName: string, payload?: any, options?: EventOptions): Promise<void>;
123
+ broadcast(eventName: string, payload?: any, options?: EventOptions): Promise<void>;
124
+ startSpan(name?: string, parentSpan?: Span): Span;
125
+ finishSpan(span?: Span): void;
126
+ copy(): Context<T>;
127
+ setStream(stream: Stream): void;
128
+ setEndpoint(endpoint: Endpoint): void;
129
+ }
130
+
131
+ // ===== LOGGER INTERFACES =====
132
+
133
+ /**
134
+ * Logger instance interface
135
+ */
136
+ export interface Logger {
137
+ fatal(message: string | object, ...args: any[]): void;
138
+ error(message: string | object, ...args: any[]): void;
139
+ warn(message: string | object, ...args: any[]): void;
140
+ info(message: string | object, ...args: any[]): void;
141
+ debug(message: string | object, ...args: any[]): void;
142
+ verbose(message: string | object, ...args: any[]): void;
143
+
144
+ // Utility methods
145
+ child(bindings: object): Logger;
146
+ level: string;
147
+ }
148
+
149
+ /**
150
+ * Logger configuration options
151
+ */
152
+ export interface LoggerOptions {
153
+ enabled?: boolean;
154
+ level?: LogLevel;
155
+ messageKey?: string;
156
+ customLevels?: Record<string, number>;
157
+ base?: Record<string, any>;
158
+ destination?: Writable;
159
+ colors?: boolean;
160
+ formatter?: 'json' | 'human' | ((data: any) => string);
161
+ }
162
+
163
+ /**
164
+ * Logger factory bindings
165
+ */
166
+ export interface LoggerFactoryBindings {
167
+ nodeId: string;
168
+ moduleName: string;
169
+ [key: string]: any;
170
+ }
171
+
172
+ /**
173
+ * Logger factory function type
174
+ */
175
+ export type LoggerFactoryFunction = (bindings: LoggerFactoryBindings, level?: LogLevel) => Logger;
176
+
177
+ // ===== SERVICE INTERFACES =====
178
+
179
+ /**
180
+ * Service settings interface
181
+ */
182
+ export interface ServiceSettings {
183
+ [key: string]: any;
184
+ }
185
+
186
+ /**
187
+ * Service action parameter schema
188
+ */
189
+ export interface ServiceActionParamSchema<T extends keyof TypeMap = keyof TypeMap> {
190
+ type: T;
191
+ optional?: boolean;
192
+ default?: TypeMap[T];
193
+ min?: number;
194
+ max?: number;
195
+ length?: number;
196
+ pattern?: string | RegExp;
197
+ enum?: TypeMap[T][];
198
+ custom?: (value: any, errors: any[]) => boolean;
199
+ [key: string]: any;
200
+ }
201
+
202
+ /**
203
+ * Service action schema definition
204
+ */
205
+ export interface ServiceActionSchema<TParams extends Record<string, ServiceActionParamSchema> = any> {
206
+ params?: TParams;
207
+ visibility?: ServiceActionVisibility;
208
+ cache?: boolean | object;
209
+ timeout?: number;
210
+ retries?: number;
211
+ bulkhead?: object;
212
+ circuitBreaker?: object;
213
+ tracing?: boolean | object;
214
+ metrics?: boolean | object;
215
+ handler: (this: Service, context: Context<ParamsToType<TParams>>) => Promise<any> | any;
216
+ [key: string]: any;
217
+ }
218
+
219
+ /**
220
+ * Service action handler function
221
+ */
222
+ export type ServiceActionHandler = (this: Service, context: Context) => Promise<any> | any;
223
+
224
+ /**
225
+ * Service event definition
226
+ */
227
+ export interface ServiceEvent {
228
+ group?: string;
229
+ handler: (this: Service, context: Context) => Promise<any> | any;
230
+ }
231
+
232
+ /**
233
+ * Service method definition
234
+ */
235
+ export type ServiceMethodDefinition = (this: Service, ...args: any[]) => any;
236
+
237
+ /**
238
+ * Service lifecycle hooks
239
+ */
240
+ export interface ServiceHooks {
241
+ before?: {
242
+ [actionName: string]: (context: Context) => Promise<Context> | Context;
243
+ };
244
+ after?: {
245
+ [actionName: string]: (context: Context, response: any) => Promise<any> | any;
246
+ };
247
+ error?: {
248
+ [actionName: string]: (context: Context, error: Error) => Promise<void> | void;
249
+ };
250
+ }
251
+
252
+ /**
253
+ * Service schema definition
254
+ */
255
+ export interface ServiceSchema {
256
+ name: string;
257
+ version?: string | number;
258
+ dependencies?: string[];
259
+ mixins?: ServiceSchema[] | ServiceSchema;
260
+ settings?: ServiceSettings;
261
+ meta?: Record<string, any>;
262
+ hooks?: ServiceHooks;
263
+ actions?: Record<string, ServiceActionSchema | ServiceActionHandler | boolean>;
264
+ events?: Record<string, ServiceEvent | ServiceActionHandler>;
265
+ methods?: Record<string, ServiceMethodDefinition>;
266
+
267
+ // Lifecycle methods
268
+ created?(this: Service): void | Promise<void>;
269
+ started?(this: Service): void | Promise<void>;
270
+ stopped?(this: Service): void | Promise<void>;
271
+ afterSchemasMerged?(this: Service): void | Promise<void>;
272
+ }
273
+
274
+ /**
275
+ * Service instance interface
276
+ */
277
+ export interface Service {
278
+ filename?: string;
279
+ runtime: Runtime;
280
+ broker: Broker;
281
+ log: Logger;
282
+ version?: string | number;
283
+ name: string;
284
+ meta?: object;
285
+ fullyQualifiedName: string;
286
+ schema: ServiceSchema;
287
+ settings: ServiceSettings;
288
+ actions: Record<string, (data: object, options?: ActionOptions) => any>;
289
+ events: Record<string, (context: Context) => any>;
290
+ methods: Record<string, Function>;
291
+
292
+ // Lifecycle methods
293
+ start(): Promise<void>;
294
+ stop(): Promise<void>;
295
+ }
296
+
297
+ // ===== REGISTRY INTERFACES =====
298
+
299
+ /**
300
+ * Node information
301
+ */
302
+ export interface NodeInfo {
303
+ nodeId: string;
304
+ instanceId: string;
305
+ hostname: string;
306
+ ipList: string[];
307
+ port?: number;
308
+ version: string;
309
+ uptime: number;
310
+ cpu?: number;
311
+ memory?: {
312
+ rss: number;
313
+ heapTotal: number;
314
+ heapUsed: number;
315
+ };
316
+ [key: string]: any;
317
+ }
318
+
319
+ /**
320
+ * Node client interface
321
+ */
322
+ export interface NodeClient {
323
+ nodeId: string;
324
+ available: boolean;
325
+ lastHeartbeatTime: number;
326
+ [key: string]: any;
327
+ }
328
+
329
+ /**
330
+ * Service item in registry
331
+ */
332
+ export interface ServiceItem {
333
+ name: string;
334
+ version?: string | number;
335
+ fullName: string;
336
+ nodeId: string;
337
+ actions?: Record<string, any>;
338
+ events?: Record<string, any>;
339
+ settings?: ServiceSettings;
340
+ metadata?: object;
341
+ }
342
+
343
+ /**
344
+ * Node in the registry
345
+ */
346
+ export interface Node {
347
+ id: string;
348
+ info: NodeInfo;
349
+ isLocal: boolean;
350
+ client: NodeClient;
351
+ cpu?: number;
352
+ cpuSequence?: number;
353
+ lastHeartbeatTime: number;
354
+ offlineTime: number;
355
+ isAvailable: boolean;
356
+ wasDisconnectedUnexpectedly: boolean;
357
+ services: ServiceItem[];
358
+ sequence: number;
359
+ events?: string[];
360
+ IPList: string[];
361
+
362
+ // Methods
363
+ update(info: NodeInfo, isLocal?: boolean): boolean;
364
+ updateLocalInfo(isLocal?: boolean): void;
365
+ heartbeat(info: NodeInfo): void;
366
+ disconnected(isLocal?: boolean): void;
367
+ }
368
+
369
+ /**
370
+ * Service action endpoint
371
+ */
372
+ export interface Endpoint {
373
+ node: Node;
374
+ service: ServiceItem;
375
+ action: any;
376
+ isLocal: boolean;
377
+ state: boolean;
378
+ name: string;
379
+
380
+ // Methods
381
+ updateAction(): void;
382
+ isAvailable(): boolean;
383
+ }
384
+
385
+ /**
386
+ * Registry configuration options
387
+ */
388
+ export interface RegistryOptions {
389
+ preferLocalActions?: boolean;
390
+ publishNodeService?: boolean;
391
+ requestTimeout?: number;
392
+ maxCallLevel?: number;
393
+ loadBalancingStrategy?: string | object;
394
+ }
395
+
396
+ /**
397
+ * Registry interface
398
+ */
399
+ export interface Registry {
400
+ runtime?: Runtime;
401
+ log: Logger;
402
+
403
+ // Methods
404
+ init?(): void;
405
+ registerLocalService(serviceItem: ServiceItem): void;
406
+ registerRemoteServices(node: Node, services: ServiceItem[]): void;
407
+ deregisterService(serviceName: string, version?: string | number, nodeId?: string): void;
408
+ deregisterServiceByNodeId(nodeId: string): void;
409
+ hasService(serviceName: string, version?: string | number, nodeId?: string): boolean;
410
+ getNextAvailableActionEndpoint(actionName: string): Endpoint | Error;
411
+ getActionEndpointByNodeId(actionName: string, nodeId: string): Endpoint | undefined;
412
+ getActionEndpoints(actionName: string): Endpoint[];
413
+ getLocalActionEndpoint(actionName: string): Endpoint | undefined;
414
+ getActionList(filterParams?: any): any[];
415
+ }
416
+
417
+ // ===== TRANSPORT INTERFACES =====
418
+
419
+ /**
420
+ * Transport message
421
+ */
422
+ export interface TransportMessage {
423
+ type: string;
424
+ targetNodeId: string;
425
+ payload: object;
426
+ meta?: object;
427
+ }
428
+
429
+ /**
430
+ * Transport message handler
431
+ */
432
+ export type TransportMessageHandler = (type: string, data: object) => void;
433
+
434
+ /**
435
+ * Pending store for tracking requests
436
+ */
437
+ export interface PendingStore {
438
+ [requestId: string]: {
439
+ resolve: (value: any) => void;
440
+ reject: (error: Error) => void;
441
+ timeout?: NodeJS.Timeout;
442
+ };
443
+ }
444
+
445
+ /**
446
+ * Transport configuration options
447
+ */
448
+ export interface TransportOptions {
449
+ adapter?: string | object;
450
+ maxQueueSize?: number;
451
+ heartbeatInterval?: number;
452
+ heartbeatTimeout?: number;
453
+ localNodeUpdateInterval?: number;
454
+ offlineNodeCheckInterval?: number;
455
+ maxOfflineTime?: number;
456
+ maxChunkSize?: number;
457
+ streams?: {
458
+ handleBackpressure?: boolean;
459
+ };
460
+ }
461
+
462
+ /**
463
+ * Transport interface
464
+ */
465
+ export interface Transport {
466
+ broker: Broker;
467
+ log: Logger;
468
+ isConnected: boolean;
469
+ isReady: boolean;
470
+ pending: PendingStore;
471
+ adapterName: string;
472
+
473
+ // Methods
474
+ connect(): Promise<void>;
475
+ disconnect(): Promise<void>;
476
+ setReady(): Promise<void>;
477
+ send(message: TransportMessage): Promise<void>;
478
+ request(context: Context): Promise<any>;
479
+ response(nodeId: string, action: string, params: object, meta: object, error?: Error): Promise<void>;
480
+ createMessage(nodeId: string, action: string, params: object): TransportMessage;
481
+ removePendingRequestsById(id: string): void;
482
+ removePendingRequestsByNodeId(nodeId: string): void;
483
+
484
+ // Transport-specific methods
485
+ sendNodeInfo?(): Promise<void>;
486
+ sendPing?(): Promise<void>;
487
+ discoverNode?(nodeId: string): Promise<void>;
488
+ discoverNodes?(): Promise<void>;
489
+ sendEvent?(): Promise<void>;
490
+ sendBroadcastEvent?(): Promise<void>;
491
+
492
+ statistics?: any;
493
+ }
494
+
495
+ // ===== CACHE INTERFACES =====
496
+
497
+ /**
498
+ * Cache configuration options
499
+ */
500
+ export interface CacheOptions {
501
+ enabled?: boolean;
502
+ adapter?: string | object;
503
+ ttl?: number;
504
+ lock?: {
505
+ enabled?: boolean;
506
+ ttl?: number;
507
+ };
508
+ }
509
+
510
+ /**
511
+ * Cache interface
512
+ */
513
+ export interface Cache {
514
+ name?: string;
515
+ options: CacheOptions;
516
+ log: Logger;
517
+
518
+ // Methods
519
+ init(): void;
520
+ set(key: string, value: any, ttl?: number): Promise<void>;
521
+ get(key: string): Promise<any>;
522
+ remove(key: string): Promise<boolean>;
523
+ clear(): Promise<void>;
524
+ getCachingKey(actionName: string, params: any, meta: any): string;
525
+ createMiddleware(): Middleware;
526
+ stop(): Promise<void>;
527
+ }
528
+
529
+ // ===== METRICS INTERFACES =====
530
+
531
+ /**
532
+ * Metric types
533
+ */
534
+ export type MetricType = 'counter' | 'gauge' | 'histogram' | 'info';
535
+
536
+ /**
537
+ * Base metric interface
538
+ */
539
+ export interface BaseMetric {
540
+ name: string;
541
+ type: MetricType;
542
+ description?: string;
543
+ unit?: string;
544
+ labels?: Record<string, string>;
545
+
546
+ // Methods
547
+ set?(value: number, labels?: Record<string, string>): void;
548
+ increment?(value?: number, labels?: Record<string, string>): void;
549
+ decrement?(value?: number, labels?: Record<string, string>): void;
550
+ observe?(value: number, labels?: Record<string, string>): void;
551
+ reset?(): void;
552
+ }
553
+
554
+ /**
555
+ * Metrics configuration options
556
+ */
557
+ export interface MetricsOptions {
558
+ enabled?: boolean;
559
+ adapters?: Array<string | object>;
560
+ collectCommonMetrics?: boolean;
561
+ collectInterval?: number;
562
+ defaultBuckets?: number[];
563
+ }
564
+
565
+ /**
566
+ * Metrics registry interface
567
+ */
568
+ export interface MetricRegistry {
569
+ options: MetricsOptions;
570
+
571
+ // Methods
572
+ init(): void;
573
+ register(metric: BaseMetric): void;
574
+ unregister(name: string): void;
575
+ get(name: string): BaseMetric | undefined;
576
+ list(): BaseMetric[];
577
+ increment(name: string, value?: number, labels?: Record<string, string>): void;
578
+ decrement(name: string, value?: number, labels?: Record<string, string>): void;
579
+ set(name: string, value: number, labels?: Record<string, string>): void;
580
+ observe(name: string, value: number, labels?: Record<string, string>): void;
581
+ stop(): Promise<void>;
582
+ }
583
+
584
+ // ===== TRACING INTERFACES =====
585
+
586
+ /**
587
+ * Tracing configuration options
588
+ */
589
+ export interface TracingOptions {
590
+ enabled?: boolean;
591
+ samplingRate?: number;
592
+ collectors?: Array<string | object>;
593
+ defaultTags?: Record<string, string>;
594
+ errors?: {
595
+ fields?: string[];
596
+ stackTrace?: boolean;
597
+ };
598
+ }
599
+
600
+ /**
601
+ * Tracer interface
602
+ */
603
+ export interface Tracer {
604
+ options: TracingOptions;
605
+
606
+ // Methods
607
+ init(): void;
608
+ startSpan(name: string, parentSpan?: Span): Span;
609
+ finishSpan(span: Span): void;
610
+ stop(): Promise<void>;
611
+ }
612
+
613
+ // ===== MIDDLEWARE INTERFACES =====
614
+
615
+ /**
616
+ * Middleware handler function
617
+ */
618
+ export type MiddlewareHandler = (context: Context, next: () => Promise<any>) => Promise<any>;
619
+
620
+ /**
621
+ * Middleware definition
622
+ */
623
+ export interface Middleware {
624
+ name?: string;
625
+ handler: MiddlewareHandler;
626
+ priority?: number;
627
+ }
628
+
629
+ /**
630
+ * Bulkhead configuration
631
+ */
632
+ export interface BulkheadOptions {
633
+ enabled?: boolean;
634
+ concurrentCalls?: number;
635
+ maxQueueSize?: number;
636
+ }
637
+
638
+ /**
639
+ * Circuit breaker configuration
640
+ */
641
+ export interface CircuitBreakerOptions {
642
+ enabled?: boolean;
643
+ halfOpenTimeout?: number;
644
+ maxFailures?: number;
645
+ windowTime?: number;
646
+ }
647
+
648
+ /**
649
+ * Retry policy configuration
650
+ */
651
+ export interface RetryPolicyOptions {
652
+ enabled?: boolean;
653
+ delay?: number;
654
+ retries?: number;
655
+ factor?: number;
656
+ maxDelay?: number;
657
+ }
658
+
659
+ /**
660
+ * Context tracking configuration
661
+ */
662
+ export interface ContextTrackingOptions {
663
+ enabled?: boolean;
664
+ shutdownTimeout?: number;
665
+ }
666
+
667
+ /**
668
+ * Validator configuration
669
+ */
670
+ export interface ValidatorOptions {
671
+ strict?: boolean;
672
+ strictMode?: 'remove' | 'error';
673
+ }
674
+
675
+ // ===== CORE INTERFACES =====
676
+
677
+ /**
678
+ * Service manager interface
679
+ */
680
+ export interface ServiceManager {
681
+ services: Map<string, Service>;
682
+
683
+ // Methods
684
+ createService(schema: ServiceSchema): Service;
685
+ registerService(service: Service): void;
686
+ unregisterService(serviceName: string): void;
687
+ startServices(): Promise<void>;
688
+ stopServices(): Promise<void>;
689
+ }
690
+
691
+ /**
692
+ * Context factory interface
693
+ */
694
+ export interface ContextFactory {
695
+ create(endpoint: Endpoint, data: any, options?: ActionOptions): Context;
696
+ createFromService(service: Service, data: any, options?: ActionOptions): Context;
697
+ }
698
+
699
+ /**
700
+ * Event bus interface
701
+ */
702
+ export interface EventBus {
703
+ emit(eventName: string, payload?: any, options?: EventOptions): Promise<void>;
704
+ broadcast(eventName: string, payload: any, options?: EventOptions): Promise<void>;
705
+ broadcastLocal(eventName: string, payload: any, options?: EventOptions): Promise<void>;
706
+ }
707
+
708
+ /**
709
+ * Action invoker interface
710
+ */
711
+ export interface ActionInvoker {
712
+ call<TParams = any, TResult = any>(actionName: string, params?: TParams, options?: ActionOptions): Promise<TResult>;
713
+ multiCall(calls: Array<{ action: string; params?: any; options?: ActionOptions }>): Promise<any[]>;
714
+ }
715
+
716
+ /**
717
+ * Runtime instance state
718
+ */
719
+ export interface RuntimeInstanceState {
720
+ isStarted: boolean;
721
+ instanceId: string;
722
+ }
723
+
724
+ /**
725
+ * Ping result
726
+ */
727
+ export interface PingResult {
728
+ nodeId: string;
729
+ time: number;
730
+ [key: string]: any;
731
+ }
732
+
733
+ /**
734
+ * Runtime interface - core system runtime
735
+ */
736
+ export interface Runtime {
737
+ nodeId: string;
738
+ version: string;
739
+ options: BrokerOptions;
740
+ bus: EventEmitter;
741
+ state: RuntimeInstanceState;
742
+
743
+ // Core components
744
+ actionInvoker: ActionInvoker;
745
+ eventBus?: EventBus;
746
+ broker?: Broker;
747
+ middlewareHandler?: MiddlewareHandler;
748
+ validator?: any;
749
+ services?: ServiceManager;
750
+ contextFactory?: ContextFactory;
751
+ registry: Registry;
752
+ transport?: Transport;
753
+ cache?: Cache;
754
+ metrics?: MetricRegistry;
755
+ tracer?: Tracer;
756
+
757
+ // Utilities
758
+ log: Logger;
759
+ createLogger?: (topic: string, data?: any) => Logger;
760
+ getUUID?: () => string;
761
+ generateUUID: () => string;
762
+
763
+ // Error handling
764
+ handleError: (error: Error) => void;
765
+ fatalError: (message?: string, error?: Error, killProcess?: boolean) => void;
766
+ }
767
+
768
+ /**
769
+ * Main broker configuration options
770
+ */
771
+ export interface BrokerOptions {
772
+ nodeId?: string;
773
+ namespace?: string;
774
+
775
+ // Feature options
776
+ bulkhead?: BulkheadOptions;
777
+ cache?: CacheOptions;
778
+ circuitBreaker?: CircuitBreakerOptions;
779
+ contextTracking?: ContextTrackingOptions;
780
+ metrics?: MetricsOptions;
781
+ registry?: RegistryOptions;
782
+ retryPolicy?: RetryPolicyOptions;
783
+ transport?: TransportOptions;
784
+ tracing?: TracingOptions;
785
+ logger?: LoggerOptions | LoggerFactoryFunction;
786
+
787
+ // Validation
788
+ validateActionParams?: boolean;
789
+ validatorOptions?: ValidatorOptions;
790
+
791
+ // Middleware
792
+ loadInternalMiddlewares?: boolean;
793
+ middlewares?: Middleware[];
794
+
795
+ // Lifecycle hooks
796
+ errorHandler?: (error: Error) => void;
797
+ uuidFactory?: (runtime: Runtime) => string;
798
+ waitForServiceInterval?: number;
799
+ beforeRegisterMiddlewares?: () => string;
800
+
801
+ // Service lifecycle
802
+ created?(this: Broker): void | Promise<void>;
803
+ started?(this: Broker): void | Promise<void>;
804
+ stopped?(this: Broker): void | Promise<void>;
805
+ }
806
+
807
+ /**
808
+ * Main Broker interface - the primary API
809
+ */
810
+ export interface Broker {
811
+ nodeId: string;
812
+ namespace?: string;
813
+ runtime: Runtime;
814
+ bus: EventEmitter;
815
+ version: string;
816
+ options: BrokerOptions;
817
+
818
+ // Core components access
819
+ metrics?: MetricRegistry;
820
+ validator: any;
821
+ contextFactory: ContextFactory;
822
+ registry: Registry;
823
+ cache?: Cache;
824
+ tracer?: Tracer;
825
+ transport?: Transport;
826
+ log: Logger;
827
+
828
+ // Lifecycle methods
829
+ start(): Promise<void>;
830
+ stop(): Promise<void>;
831
+
832
+ // Service management
833
+ createService(schema: ServiceSchema): Service;
834
+ loadService(path: string): Service;
835
+ loadServices(path?: string, pattern?: string): Service[];
836
+
837
+ // Action calls
838
+ call<TParams = any, TResult = any>(actionName: string, params?: TParams, options?: ActionOptions): Promise<TResult>;
839
+ multiCall(calls: Array<{ action: string; params?: any; options?: ActionOptions }>): Promise<any[]>;
840
+
841
+ // Events
842
+ emit(eventName: string, payload?: any, options?: EventOptions): Promise<void>;
843
+ broadcast(eventName: string, payload?: any, options?: EventOptions): Promise<void>;
844
+ broadcastLocal(eventName: string, payload?: any, options?: EventOptions): Promise<void>;
845
+
846
+ // Utilities
847
+ createLogger(topic: string, data?: any): Logger;
848
+ getUUID(): string;
849
+ waitForServices(services: string[] | string, timeout?: number): Promise<void>;
850
+ ping(nodeId: string, timeout?: number): Promise<PingResult>;
851
+ getNextActionEndpoint(actionName: string): Endpoint | Error;
852
+
853
+ // Error handling
854
+ handleError(error: Error): void;
855
+ fatalError(message?: string, error?: Error, killProcess?: boolean): void;
856
+ }
857
+
858
+ // ===== ERROR CLASSES =====
859
+
860
+ /**
861
+ * Base Weave error class
862
+ */
863
+ export class WeaveError extends Error {
864
+ constructor(message: string, code?: string, type?: string, data?: any);
865
+ code?: string;
866
+ type?: string;
867
+ data?: any;
868
+ }
869
+
870
+ export class WeaveMaxCallLevelError extends WeaveError {}
871
+ export class WeaveParameterValidationError extends WeaveError {}
872
+ export class WeaveServiceNotFoundError extends WeaveError {}
873
+ export class WeaveRequestTimeoutError extends WeaveError {}
874
+ export class WeaveRetryableError extends WeaveError {}
875
+ export class WeaveActionNotFoundError extends WeaveError {}
876
+
877
+ // ===== MAIN EXPORTS =====
878
+
879
+ /**
880
+ * Create a new Weave broker instance
881
+ * @param options - Broker configuration options
882
+ * @returns A new Broker instance
883
+ */
884
+ export function createBroker(options?: BrokerOptions): Broker;
885
+
886
+ /**
887
+ * @deprecated Use createBroker instead
888
+ */
889
+ export function Weave(options?: BrokerOptions): Broker;
890
+
891
+ /**
892
+ * Default broker options
893
+ */
894
+ export const defaultOptions: BrokerOptions;
895
+
896
+ /**
897
+ * Weave constants
898
+ */
899
+ export namespace Constants {
900
+ export const INTERNAL_SERVICES: string[];
901
+ export const MIDDLEWARE: {
902
+ BULKHEAD: string;
903
+ CACHE: string;
904
+ CIRCUIT_BREAKER: string;
905
+ CONTEXT_TRACKER: string;
906
+ ERROR_HANDLER: string;
907
+ METRICS: string;
908
+ RETRY: string;
909
+ TIMEOUT: string;
910
+ TRACING: string;
911
+ VALIDATOR: string;
912
+ };
913
+ }
914
+
915
+ /**
916
+ * Available cache adapters
917
+ */
918
+ export namespace Cache {
919
+ export function resolve(adapter: string | object): any;
920
+ }
921
+
922
+ /**
923
+ * Available transport adapters
924
+ */
925
+ export namespace TransportAdapters {
926
+ export function resolve(adapter: string | object): any;
927
+ }
928
+
929
+ /**
930
+ * Available tracing adapters
931
+ */
932
+ export namespace TracingAdapters {
933
+ export function resolve(adapter: string | object): any;
934
+ }
935
+
936
+ /**
937
+ * Helper functions for type-safe service definitions
938
+ */
939
+ export function defineService<T extends ServiceSchema>(schema: T): T;
940
+ export function defineAction<TParams extends Record<string, ServiceActionParamSchema>>(
941
+ action: ServiceActionSchema<TParams>
942
+ ): ServiceActionSchema<TParams>;
943
+ export function defineBrokerOptions<T extends BrokerOptions>(options: T): T;
944
+
945
+ /**
946
+ * Weave errors namespace
947
+ */
948
+ export namespace Errors {
949
+ export {
950
+ WeaveError,
951
+ WeaveMaxCallLevelError,
952
+ WeaveParameterValidationError,
953
+ WeaveServiceNotFoundError,
954
+ WeaveRequestTimeoutError,
955
+ WeaveRetryableError,
956
+ WeaveActionNotFoundError
957
+ };
958
+ }