@bett3r-dev/pv3-types 1.0.0 → 1.4.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 (137) hide show
  1. package/CHANGELOG.md +305 -0
  2. package/build/adminPlugin.d.ts +24 -0
  3. package/build/adminPlugin.d.ts.map +1 -0
  4. package/build/{eventsourcing/utils.js → adminPlugin.js} +1 -1
  5. package/build/adminPlugin.js.map +1 -0
  6. package/build/aggregateSchema.d.ts +94 -0
  7. package/build/aggregateSchema.d.ts.map +1 -0
  8. package/build/aggregateSchema.js +287 -0
  9. package/build/aggregateSchema.js.map +1 -0
  10. package/build/authentication.d.ts +179 -78
  11. package/build/authentication.d.ts.map +1 -1
  12. package/build/authentication.js +62 -19
  13. package/build/authentication.js.map +1 -1
  14. package/build/cache.d.ts +50 -4
  15. package/build/cache.d.ts.map +1 -1
  16. package/build/clusterAdministration.d.ts +712 -225
  17. package/build/clusterAdministration.d.ts.map +1 -1
  18. package/build/clusterAdministration.js +175 -52
  19. package/build/clusterAdministration.js.map +1 -1
  20. package/build/configuration.d.ts +26 -5
  21. package/build/configuration.d.ts.map +1 -1
  22. package/build/database.d.ts +240 -56
  23. package/build/database.d.ts.map +1 -1
  24. package/build/database.js +102 -20
  25. package/build/database.js.map +1 -1
  26. package/build/endpoints.d.ts +141 -41
  27. package/build/endpoints.d.ts.map +1 -1
  28. package/build/endpoints.js +50 -26
  29. package/build/endpoints.js.map +1 -1
  30. package/build/errors.d.ts +166 -0
  31. package/build/errors.d.ts.map +1 -0
  32. package/build/errors.js +276 -0
  33. package/build/errors.js.map +1 -0
  34. package/build/evenstore.d.ts +47 -7
  35. package/build/evenstore.d.ts.map +1 -1
  36. package/build/eventsourcing/aggregateBuilder.d.ts +17 -8
  37. package/build/eventsourcing/aggregateBuilder.d.ts.map +1 -1
  38. package/build/eventsourcing/commandBuilder.d.ts +20 -13
  39. package/build/eventsourcing/commandBuilder.d.ts.map +1 -1
  40. package/build/eventsourcing/commandHandlers.d.ts +155 -33
  41. package/build/eventsourcing/commandHandlers.d.ts.map +1 -1
  42. package/build/eventsourcing/commandHandlers.js +62 -14
  43. package/build/eventsourcing/commandHandlers.js.map +1 -1
  44. package/build/eventsourcing/eventHandlers.d.ts +173 -44
  45. package/build/eventsourcing/eventHandlers.d.ts.map +1 -1
  46. package/build/eventsourcing/eventHandlers.js +29 -21
  47. package/build/eventsourcing/eventHandlers.js.map +1 -1
  48. package/build/eventsourcing/eventHandlersBuilder.d.ts +18 -12
  49. package/build/eventsourcing/eventHandlersBuilder.d.ts.map +1 -1
  50. package/build/eventsourcing/eventHandlersBuilder.js.map +1 -1
  51. package/build/eventsourcing/eventsourcing.types.d.ts +322 -0
  52. package/build/eventsourcing/eventsourcing.types.d.ts.map +1 -0
  53. package/build/eventsourcing/eventsourcing.types.js +26 -0
  54. package/build/eventsourcing/eventsourcing.types.js.map +1 -0
  55. package/build/eventsourcing/externalSystemBuilder.d.ts +8 -7
  56. package/build/eventsourcing/externalSystemBuilder.d.ts.map +1 -1
  57. package/build/eventsourcing/index.d.ts +2 -378
  58. package/build/eventsourcing/index.d.ts.map +1 -1
  59. package/build/eventsourcing/index.js +2 -23
  60. package/build/eventsourcing/index.js.map +1 -1
  61. package/build/eventsourcing/invariants.d.ts +34 -10
  62. package/build/eventsourcing/invariants.d.ts.map +1 -1
  63. package/build/eventsourcing/shapeChangeForSubscriber.d.ts +33 -0
  64. package/build/eventsourcing/shapeChangeForSubscriber.d.ts.map +1 -0
  65. package/build/eventsourcing/shapeChangeForSubscriber.js +47 -0
  66. package/build/eventsourcing/shapeChangeForSubscriber.js.map +1 -0
  67. package/build/index.d.ts +6 -1
  68. package/build/index.d.ts.map +1 -1
  69. package/build/index.js +6 -1
  70. package/build/index.js.map +1 -1
  71. package/build/infrastructure.d.ts +9 -1
  72. package/build/infrastructure.d.ts.map +1 -1
  73. package/build/infrastructure.js +33 -1
  74. package/build/infrastructure.js.map +1 -1
  75. package/build/livenessWatchdog.d.ts +28 -0
  76. package/build/livenessWatchdog.d.ts.map +1 -0
  77. package/build/livenessWatchdog.js +43 -0
  78. package/build/livenessWatchdog.js.map +1 -0
  79. package/build/logger.d.ts +8 -9
  80. package/build/logger.d.ts.map +1 -1
  81. package/build/logger.js +18 -6
  82. package/build/logger.js.map +1 -1
  83. package/build/outboxManager.d.ts +858 -14
  84. package/build/outboxManager.d.ts.map +1 -1
  85. package/build/outboxManager.js +173 -15
  86. package/build/outboxManager.js.map +1 -1
  87. package/build/permissions.d.ts +47 -0
  88. package/build/permissions.d.ts.map +1 -0
  89. package/build/permissions.js +3 -0
  90. package/build/permissions.js.map +1 -0
  91. package/build/ports.d.ts +10 -10
  92. package/build/ports.d.ts.map +1 -1
  93. package/build/routesAuth.d.ts +17 -25
  94. package/build/routesAuth.d.ts.map +1 -1
  95. package/build/routesAuth.js +4 -14
  96. package/build/routesAuth.js.map +1 -1
  97. package/build/typedEventEmitter.d.ts +7 -13
  98. package/build/typedEventEmitter.d.ts.map +1 -1
  99. package/build/typedEventEmitter.js +2 -2
  100. package/build/typedEventEmitter.js.map +1 -1
  101. package/build/userSession.d.ts +8 -0
  102. package/build/userSession.d.ts.map +1 -0
  103. package/build/userSession.js +3 -0
  104. package/build/userSession.js.map +1 -0
  105. package/package.json +22 -7
  106. package/build/eventsourcing/utils.d.ts +0 -4
  107. package/build/eventsourcing/utils.d.ts.map +0 -1
  108. package/build/eventsourcing/utils.js.map +0 -1
  109. package/build/validation.d.ts +0 -64
  110. package/build/validation.d.ts.map +0 -1
  111. package/build/validation.js +0 -57
  112. package/build/validation.js.map +0 -1
  113. package/src/authentication.ts +0 -273
  114. package/src/cache.ts +0 -109
  115. package/src/clusterAdministration.ts +0 -216
  116. package/src/configuration.ts +0 -71
  117. package/src/database.ts +0 -157
  118. package/src/endpoints.ts +0 -198
  119. package/src/evenstore.ts +0 -27
  120. package/src/eventsourcing/aggregateBuilder.ts +0 -11
  121. package/src/eventsourcing/commandBuilder.ts +0 -64
  122. package/src/eventsourcing/commandHandlers.ts +0 -137
  123. package/src/eventsourcing/eventHandlers.ts +0 -118
  124. package/src/eventsourcing/eventHandlersBuilder.ts +0 -42
  125. package/src/eventsourcing/externalSystemBuilder.ts +0 -20
  126. package/src/eventsourcing/index.ts +0 -111
  127. package/src/eventsourcing/invariants.ts +0 -27
  128. package/src/eventsourcing/utils.ts +0 -4
  129. package/src/index.ts +0 -15
  130. package/src/infrastructure.ts +0 -41
  131. package/src/logger.ts +0 -45
  132. package/src/outboxManager.ts +0 -36
  133. package/src/ports.ts +0 -42
  134. package/src/routesAuth.ts +0 -58
  135. package/src/typedEventEmitter.ts +0 -73
  136. package/src/validation.ts +0 -89
  137. package/tsconfig.json +0 -15
@@ -1,64 +0,0 @@
1
- //*******************************************
2
- // Command Builder
3
- //*******************************************
4
-
5
- import { BaseSchema } from '@bett3r-dev/jsonschema-definer';
6
- import { Command, CommandCommitFunction, CommandErrorHandlerFunction, CommandFormatFunction, CommandHandlerFunction, CommandLoadFunction, EventFactory, InvariantType } from '.';
7
-
8
- export type CommandBuilderFromSchemaType<Model, EVENTS extends Record<string, EventFactory>, EVENT extends keyof EVENTS, CommandPayload> = {
9
- /**
10
- * Loads the streams from the aggregate. If the Command Handler is an Aggregate the fuction will be ignored.
11
- * Default Implementation:
12
- * ```ts
13
- * loadAggregateState(state.commandHandler, (state.streams || []), options)
14
- * .then(u.ensureArray)
15
- * .then((aggregateState) => ({...state, aggregateState} as CommandHandlerState));
16
- * ```
17
- */
18
- withLoadFunction: ( loadFunction: CommandLoadFunction<Model, CommandPayload> ) => CommandBuilderFromSchemaType<Model, EVENTS, EVENT, CommandPayload>
19
- /**
20
- * Commits the new event/events to the store
21
- * DefaultImplementation:
22
- * ```ts
23
- * const defaultCommit = (state: CommandHandlerState) =>
24
- * commitCommands(state);
25
- * ```
26
- */
27
- withCommitFunction: ( commitFunction: CommandCommitFunction<Model, CommandPayload> ) => CommandBuilderFromSchemaType<Model, EVENTS, EVENT, CommandPayload>
28
- withResultFormatFunction: ( resultFormatFunction: CommandFormatFunction<Model, CommandPayload> ) => CommandBuilderFromSchemaType<Model, EVENTS, EVENT, CommandPayload>
29
- withInvariant: ( invariant: InvariantType<Model, CommandPayload> | (( state: Model, data: CommandPayload ) => Promise<void> )) => CommandBuilderFromSchemaType<Model, EVENTS, EVENT, CommandPayload>,
30
- produces: <EVENT extends keyof EVENTS>( events: EVENT[]) => {
31
- withHandler: <USER, StateModel = Model>( handler: CommandHandlerFunction<StateModel, CommandPayload, EVENTS, EVENT, USER> ) => {
32
- build: () => Command<EVENTS, EVENT, Model, CommandPayload>,
33
- withErrorHandler: ( errorHandler: CommandErrorHandlerFunction<CommandPayload> ) => {
34
- build: () => Command<EVENTS, EVENT, Model, CommandPayload>
35
- }
36
- },
37
- withErrorHandler: ( errorHandler: CommandErrorHandlerFunction<CommandPayload> ) => {
38
- build: () => Command<EVENTS, EVENT, Model, CommandPayload>
39
- },
40
- build: () => Command<EVENTS, EVENT, Model, CommandPayload>
41
- }
42
- }
43
-
44
- export type CommandBuilderInstance<Model, EVENTS extends Record<string, EventFactory>, EVENT extends keyof EVENTS, CommandPayload> = {
45
- withDescription: ( description: string ) => CommandBuilderInstance<Model, EVENTS, EVENT, CommandPayload>
46
- /** Specify where to find the id of the aggregate when the command has no Id in the Params of the request
47
- *
48
- * suppose a structure of
49
- * ```ts
50
- * {
51
- * ISC: 'QWERASDFZXCV',
52
- * marketing: { promoId: '1q2w3e'}
53
- * products: [{id: 1}, {id:2}]
54
- * }
55
- * ```
56
- * Some examples are: `ISC`, `warehouse.id`.
57
- * In the case of an array use a Dollar sign `$`.
58
- * `products.$.id`
59
- */
60
- withDataPropertyId: ( dataPath: string ) => CommandBuilderInstance<Model, EVENTS, EVENT, CommandPayload>
61
- withSchema: <CommandPayload>( schema: BaseSchema<CommandPayload> ) => CommandBuilderFromSchemaType<Model, EVENTS, EVENT, CommandPayload>,
62
- }
63
-
64
- export type CommandBuilderType<Model = any, EVENTS extends Record<string, EventFactory>=any, EVENT extends keyof EVENTS=any, CommandPayload=any> = ( init?: Omit<Command<EVENTS, EVENT, CommandPayload, Model>, 'handler' | 'events' | 'schema'> ) => CommandBuilderInstance<Model, EVENTS, EVENT, CommandPayload>
@@ -1,137 +0,0 @@
1
- import S, { BaseSchema } from '@bett3r-dev/jsonschema-definer';
2
- import { Builder, CommittedEvent, EventFactory, EventMetadata, GetMessageType, ReadStreamOptions } from '.';
3
- import { AppErrorInstance, AppErrorType } from '../validation';
4
- import { DatabasePort } from '../database';
5
- import { EndpointActionParams, EndpointActionParamsContext } from '../endpoints';
6
-
7
- export type CommandHandlerState<Events = Record<string, EventFactory>, Payload=any, Model = any, USER=any> = {
8
- commandHandler: Aggregate | System,
9
- command: Command,
10
- stream: string,
11
- data: Payload,
12
- query: {id?: string},
13
- params: Record<string, any>,
14
- context: Partial<EndpointActionParamsContext<USER>>
15
- events: Events[keyof Events][],
16
- state: Model,
17
- committedEvents?: Array<CommittedEvent>,
18
- metadata?: EventMetadata
19
- expectedVersion?: number
20
- }
21
-
22
- export type CommandExecutionResponse<Model = unknown> = {
23
- state?: Model,
24
- events: CommittedEvent[]
25
- }
26
-
27
- export type ExecuteCommandFunction = <SYSTEM extends System, COMMAND extends keyof SYSTEM['commands']>( commandHandler:SYSTEM, commandName: COMMAND ) => ( params: Partial<EndpointActionParams> ) => Promise<unknown>;
28
- export type CommandLoadFunction<Model=any, Payload=any> = ( state: CommandHandlerState<Model,Payload>, options?: ReadStreamOptions, initialState?: Model ) => Promise<CommandHandlerState<Model, Payload>>
29
- export type CommandCommitFunction<Model=any, Payload=any> = ( state: CommandHandlerState<Model,Payload> ) => Promise<CommandHandlerState<Model, Payload>>
30
- export type CommandFormatFunction<Model=any, Payload=any> = ( handlerState: CommandHandlerState<Model, Payload> ) => Promise<CommandExecutionResponse<Model>>
31
-
32
- export type CommandHandlerFunction<Model=any, CommandPayload=unknown, Events extends Record<string, EventFactory<EVENT>>=any, EVENT extends keyof Events=any, USER = any> = ( state: Model extends undefined ? null : Model, data: CommandPayload, aggregateState: CommandHandlerState<Events, CommandPayload, any, USER> ) => Promise<EventFactory<EVENT, GetMessageType<Events[EVENT]>>[]> | EventFactory<EVENT, GetMessageType<Events[EVENT]>>[]
33
-
34
- export type CommandErrorHandlerFunction<CommandPayload=unknown> = ( error: AppErrorInstance, data: CommandPayload ) => Promise<any>
35
-
36
- export type Command<EVENTS extends Record<string, EventFactory<EVENT>>=any, EVENT extends keyof EVENTS=any, SystemModel=any, CommandPayload=any> = {
37
- schema: BaseSchema<CommandPayload>
38
- handler: CommandHandlerFunction<SystemModel, CommandPayload, EVENTS, EVENT>
39
- onErrorHandler?: CommandErrorHandlerFunction<CommandPayload>,
40
- dataPropertyId?: string,
41
- name?: string,
42
- actors?: string[]
43
- description?: string
44
- multipartProperties?: string[],
45
- events?: EVENT[],
46
- invariants?: InvariantType[]
47
- load?: CommandLoadFunction,
48
- commit?: CommandCommitFunction,
49
- format?: CommandFormatFunction
50
- }
51
-
52
- export type InvariantType<Model=any, Payload=any> = {
53
- events?: string[],
54
- rejects: AppErrorType[],
55
- beforeLoad?: ( state: CommandHandlerState<any, Payload, Model> ) => Promise<CommandHandlerState<any, Payload, Model>>
56
- check: ( commandHandlerState: CommandHandlerState<any, Payload, Model> ) => Promise<CommandHandlerState<any, Payload, Model> | void> | void | CommandHandlerState<any, Payload, Model>
57
- }
58
-
59
- //*******************************************
60
- // Systems
61
- //*******************************************
62
-
63
- export const SystemGetQuerySchema = S.shape({
64
- stream: S.string(),
65
- names: S.array().items( S.string()).optional(),
66
- from: S.number().optional(),
67
- limit: S.number().optional(),
68
- backward: S.boolean().optional(),
69
- after: S.string().format( 'date-time' ).optional(),
70
- before: S.string().format( 'date-time' ).optional(),
71
- });
72
- export type SystemGetQueryType = typeof SystemGetQuerySchema.type;
73
- export const SystemEndpointParamsSchema = S.shape({
74
- id: S.string().description( 'id for the aggregate' )
75
- });
76
- export const CommandEndpointQuerySchema = S.shape({
77
- expectedVersion: S.string().optional(),
78
- causationId: S.string().optional(),
79
- correlationId: S.string().optional(),
80
- });
81
-
82
- export type OnValidationErrorFunctionType = Function;
83
-
84
- export type System<Commands extends Record<string, Command | Builder<Command>>=any, EVENTS extends Record<string, EventFactory>=any> = {
85
- name: string,
86
- events: EVENTS,
87
- isStreamable?: boolean,
88
- isAggregate?: boolean,
89
- isEventsourced?: boolean,
90
- commands: Commands,
91
- templateCommand: Command
92
- }
93
-
94
- //*******************************************
95
- // Aggregates
96
- //*******************************************
97
-
98
- export type AggregateReducedState<Model = any> = {state: Model, lastEvent?: Partial<Pick<CommittedEvent, 'id'|'version'>>}
99
-
100
- export type EventReducers<EVENTS extends Record<string, EventFactory>=any, Model=any> = {
101
- [Name in keyof EVENTS]: ( state: Model, data: GetMessageType<EVENTS[Name]>, metadata: EventMetadata ) => Partial<Model>
102
- }
103
-
104
- export type Aggregate<Commands extends Record<string, Command | Builder<Command>>=any, EVENTS extends Record<string, EventFactory>=any, Model=any> = System<Commands, EVENTS> & {
105
- schema: BaseSchema<Model>
106
- outboxDatabase?: DatabasePort,
107
- outboxCollection?: string,
108
- initialValue: () => Partial<Model> | null | undefined,
109
- eventReducers: EventReducers<EVENTS, Model>
110
- }
111
-
112
- //*******************************************
113
- // Command Handlers
114
- //*******************************************
115
-
116
- export type EventSourcingCommandHandlers = {
117
- loadStream: (
118
- stream: string,
119
- options?: ReadStreamOptions
120
- ) => Promise<CommittedEvent[] | undefined>;
121
- loadAggregateState: (
122
- system: System,
123
- stream?: string,
124
- options?: ReadStreamOptions
125
- ) => Promise<Record<string, any> | null>;
126
- executeCommand: ExecuteCommandFunction;
127
- registerCommandHandlerGetEndpoints: (
128
- aggregateOrSystem: Aggregate | System,
129
- name?: string
130
- ) => string[];
131
- registerCommandHandlerPostEndpoints: (
132
- aggregateOrSystem: ( Aggregate | System ) & {
133
- events: Record<string, EventFactory>;
134
- },
135
- name?: string
136
- ) => Record<string, string>;
137
- };
@@ -1,118 +0,0 @@
1
- import S, { ObjectSchema } from '@bett3r-dev/jsonschema-definer';
2
- import { AppErrorInstance } from '../validation';
3
- import { Collection, CollectionQueryParams, DatabaseChange, DatabasePort, Document } from '../database';
4
- import { EndpointActionParams, RequestObject, ResponseObject } from '../endpoints';
5
- import { CommittedEvent, EventFactory, GetMessageType } from '../eventsourcing';
6
- import { LoggerType } from '../logger';
7
- import { System } from './commandHandlers';
8
- import { TypedEventEmitter } from '../typedEventEmitter';
9
-
10
- const SortStringSchema = S.string().pattern( /^(\w+),?(asc|desc)?$/ );
11
- const FilterStringSchema = S
12
- .string()
13
- .pattern( /^([\w\d._]+),(eq|neq|lt|gt|lte|gte|in|nin|contains|notContains|some|every|exists|notExists),(.+?)$/ );
14
-
15
- export const ReadModelDefaultParamsSchema = S.shape({
16
- id: S.string().optional()
17
- });
18
-
19
- export const ReadModelDefaultQuerySchema = S.shape({
20
- access_token: S.string().optional(),
21
- apikey: S.string().optional(),
22
- limit: S.string().optional(),
23
- after: S.string().optional(),
24
- sort: S.oneOf( SortStringSchema, S.array().items( SortStringSchema )).optional(),
25
- select: S.array().items( S.string()).optional(),
26
- //TODO: scape , for when the value has commas.
27
- filter: S
28
- .oneOf( FilterStringSchema, S.array().items( FilterStringSchema ))
29
- .optional()
30
- });
31
-
32
- export type ReadModelDefaultQuery = typeof ReadModelDefaultQuerySchema.type
33
-
34
- export type ReadModelDefaultParams = typeof ReadModelDefaultParamsSchema.type;
35
-
36
-
37
- export const defaultParamsSchemas = {
38
- params: ReadModelDefaultParamsSchema
39
- };
40
-
41
- export const defaultQuerySchemas = {
42
- query: ReadModelDefaultQuerySchema
43
- };
44
-
45
- export type EventHandler<EVENTS extends Record<string, EventFactory>=any> = {
46
- name: string;
47
- events: EVENTS;
48
- concurrency?: number;
49
- errorHandlers?: {
50
- [Name in keyof EVENTS]?: HandlerExecutionErrorType<CommittedEvent<GetMessageType<EVENTS[Name]>>>
51
- },
52
- }
53
-
54
- export type PolicyResponse = {name: string, id?: string, data?: any};
55
- export type HandlerExecutionErrorType<EVENT extends CommittedEvent = CommittedEvent> = ( error: AppErrorInstance, event: EVENT ) => Promise<unknown>;
56
-
57
- //*******************************************
58
- // Policies
59
- //*******************************************
60
-
61
- export type Policy<CommandHandler extends System=any, Events extends Record<string, EventFactory>=any> = EventHandler<Events> & {
62
- commandHandler?: CommandHandler,
63
- eventHandlers: {
64
- [Name in keyof Events]: ( event: CommittedEvent<GetMessageType<Events[Name]>> ) => Promise<PolicyResponse | void>
65
- }
66
- }
67
-
68
- //*******************************************
69
- // Readmodels
70
- //*******************************************
71
-
72
- export type QueryParamsTranslator<Model extends Document, Params, Query> = ( schema: ObjectSchema<Model>, params: Pick<EndpointActionParams<any, Query, Params>, 'params' | 'query'> ) => CollectionQueryParams<Model>;
73
-
74
- export type QueryHandler<MODEL extends Document=any,PARAMS=any,QUERY=any> = ( repository: Collection<MODEL>, params: CollectionQueryParams<MODEL> & {params: EndpointActionParams<any, QUERY, PARAMS>}) => Promise<MODEL | MODEL[]>;
75
-
76
- export type QueryTransformer<MODEL extends Document=any,PARAMS=any,QUERY=any> = ( projectionParams: CollectionQueryParams<MODEL>, params: EndpointActionParams<any, QUERY, PARAMS> ) => Promise<CollectionQueryParams<MODEL>> | CollectionQueryParams<MODEL>;
77
-
78
- export type ReadModelSubscriptionCloseEmitterEvents = {close: string};
79
-
80
- export type ReadmodelSubscriptionManagerType<Model extends Document = any> = {
81
- type: string,
82
- startSubscription: ( projectionParams: CollectionQueryParams<Model>, req: RequestObject, res: ResponseObject ) => string | void;
83
- notifySubscriptions: ( logger: LoggerType, collection: string ) => <T extends Document>( change: DatabaseChange<T>, subscriptionId?: string ) => void;
84
- readModelSubscriptionCloseEmitter: TypedEventEmitter<ReadModelSubscriptionCloseEmitterEvents>
85
- send: ( logger:LoggerType, id: string, change:DatabaseChange,collection: string, res: ResponseObject, data: string ) => void;
86
- };
87
-
88
- export type Query<MODEL extends Document=any, PARAMS extends Record<string, any>=any, QUERY extends Record<string, any>=any> = {
89
- route?: string;
90
- protocol?: 'http',
91
- description?: string;
92
- schemas?: {
93
- query?: ObjectSchema<QUERY>
94
- params?: ObjectSchema<PARAMS>
95
- };
96
- translator?: QueryParamsTranslator<MODEL, PARAMS, QUERY>;
97
- subscriptions?: ReadmodelSubscriptionManagerType[];
98
- transformers?: QueryTransformer<MODEL,PARAMS, QUERY>[],
99
- queryHandler?: QueryHandler<MODEL, PARAMS, QUERY>;
100
- };
101
-
102
- export type EventProjectors<EVENTS extends Record<string, EventFactory>=any> = {
103
- [Name in keyof EVENTS]: ( event: CommittedEvent<GetMessageType<EVENTS[Name]>> ) => Promise<any>
104
- };
105
-
106
- export type ReadModel<Model extends Document =any, EVENTS extends Record<string, EventFactory>=any> = EventHandler<EVENTS> & {
107
- isReadModel: true;
108
- schema: ObjectSchema<Model>;
109
- queries: Query<Model>[];
110
- eventProjectors?:EventProjectors<EVENTS>;
111
- database?: DatabasePort;
112
- collection?:string
113
- }
114
-
115
- export type ReadmodelChange<Model extends Document> = {
116
- type: 'insert' | 'update' | 'delete',
117
- data: Model
118
- }
@@ -1,42 +0,0 @@
1
- import { ObjectSchema } from '@bett3r-dev/jsonschema-definer';
2
- import { A, O } from 'ts-toolbelt';
3
- import { Builder, CommittedEvent, EventFactory, EventHandler, EventMetadata, EventProjectors, GetBuilderType, GetMessageType, Message, Policy, PolicyResponse, Query, ReadModel, System } from '.';
4
- import { AppErrorInstance, DatabasePort, Document } from '..';
5
-
6
- export type GetCommandType<SYSTEM extends System | EventHandler, Name extends A.Key> = SYSTEM extends System
7
- ? O.Path<SYSTEM, ['commands', Name]> extends ( Builder<infer T extends Object> ) ? O.Path<T, ['schema', 'type']> : O.Path<SYSTEM, ['commands', Name, 'schema', 'type']>
8
- : O.Path<SYSTEM, ['commandHandler','commands', Name]> extends ( Builder<infer T extends Object> ) ? O.Path<T, ['schema', 'type']> : O.Path<SYSTEM, ['commandHandler','commands', Name, 'schema', 'type']>
9
-
10
- export type CommandInstance<Payload=any> = Message<Payload> & {
11
- name: string;
12
- id?: string;
13
- metadata?: EventMetadata
14
- }
15
-
16
- export const createCommand = <Handler extends System | EventHandler> ( handler: Handler )=> <COMMAND extends keyof ( Handler extends System ? Handler['commands'] : O.Path<GetBuilderType<Handler>,['commandHandler','commands']> )>( command: COMMAND, id?: string, data?: GetCommandType<Handler, COMMAND>, metadata?: EventMetadata ): CommandInstance => {
17
- return {
18
- name: command as string,
19
- ...( id ? { id } : {}),
20
- ...( data ? { data } : {}),
21
- ...( metadata ? { metadata } : {})
22
- };
23
- };
24
-
25
- export type EventHandlerBuilderType<EVENTS extends Record<string, EventFactory>, T extends Policy | ReadModel> = Builder<EventHandler<EVENTS>> & {
26
- eventHandler: EventHandler<EVENTS>,
27
- withErrorHandlers: ( errorHandlers: {
28
- [Name in keyof EVENTS]?: ( error: AppErrorInstance, event: CommittedEvent<GetMessageType<EVENTS[Name]>> ) => Promise<unknown>
29
- }) => { build: () => T extends Policy ? Policy<T['commandHandler'], EVENTS> : T extends ReadModel ? ReadModel<T['schema'] extends ObjectSchema<infer MODEL extends Document> ? MODEL: Document, EVENTS> : any},
30
- };
31
-
32
- export type PolicyBuilderType<CommandHandler extends System, EVENTS extends Record<string, EventFactory>> = Builder<Policy<CommandHandler, EVENTS>> & EventHandlerBuilderType<EVENTS, Policy<CommandHandler, EVENTS>> & {
33
- withEventHandlers: ( handlers: ( params: {createCommand: ReturnType<typeof createCommand<CommandHandler>>}) => {
34
- [Name in keyof EVENTS]: ( event: CommittedEvent<GetMessageType<EVENTS[Name]>> ) => Promise<PolicyResponse|void>
35
- }) => Pick<PolicyBuilderType<CommandHandler, EVENTS>, 'build' | 'withErrorHandlers'>,
36
- }
37
-
38
- export type ReadmodelBuilderType<Model extends Document, EVENTS extends Record<string, EventFactory>> = Builder<ReadModel<Model, EVENTS>> & EventHandlerBuilderType<EVENTS, ReadModel<Model, EVENTS>> & {
39
- withDatabase: ( database: DatabasePort, collection?:string ) => ReadmodelBuilderType<Model, EVENTS>
40
- withProjector: ( eventProjectors?: ( params: {database: DatabasePort, collection:string}) => EventProjectors<EVENTS> ) => ReadmodelBuilderType<Model, EVENTS>
41
- withQuery: <PARAMS extends Record<string, any>, QUERY extends Record<string, any>>( query?: Query<Model, PARAMS, QUERY> ) => ReadmodelBuilderType<Model, EVENTS>
42
- }
@@ -1,20 +0,0 @@
1
- import { Builder, Command, CommandBuilderType, EventFactory, System } from '.';
2
- import { CreateEventType } from './utils';
3
-
4
- export type ExternalSystemBuilderType<Model, EVENTS extends Record<string, EventFactory>> = {
5
-
6
- withCommandTemplate: ( command: Command ) => ExternalSystemBuilderType<Model, EVENTS>
7
-
8
-
9
- /**
10
- * This is the last function that builds the aggregate, the last function you'll call
11
- */
12
- withCommands: <
13
- EVENT extends keyof EVENTS,
14
- Commands extends Record<string, Command<EVENTS, EVENT, Model> | Builder<Command<EVENTS, EVENT, Model>>>
15
- > ( commands: ( params: {
16
- commandBuilder: CommandBuilderType<Model, EVENTS>,
17
- createEvent: CreateEventType<System< any, EVENTS >>,
18
- }) => Commands ) => System<Commands, EVENTS>
19
- system: System<any, EVENTS>
20
- }
@@ -1,111 +0,0 @@
1
- import S, { BaseSchema, ObjectSchema } from '@bett3r-dev/jsonschema-definer';
2
- import { CollectionFilter, Document } from '../database';
3
- import { ResponseObject } from '../endpoints';
4
- import { PortEmitter } from '../ports';
5
- import { EventSourcingCommandHandlers, ExecuteCommandFunction, System } from './commandHandlers';
6
- import { EventHandler } from './eventHandlers';
7
-
8
- export * from './commandHandlers';
9
- export * from './eventHandlers';
10
- export * from './invariants';
11
- export * from './aggregateBuilder';
12
- export * from './commandBuilder';
13
- export * from './eventHandlersBuilder';
14
- export * from './externalSystemBuilder';
15
-
16
- export type Message<Payload, Name = string> = {
17
- name?: Name,
18
- data?: Payload,
19
- description?: string
20
- }
21
-
22
- export type MessageSchema<Payload> = {
23
- schema?: BaseSchema<Payload> | BaseSchema<Payload, false> | ObjectSchema | BaseSchema | null
24
- }
25
-
26
- export type EventInstance<Payload=any, Name=any> = Message<Payload, Name> & MessageSchema<Payload>
27
-
28
- export const Event = <Payload>( eventInstance: EventInstance<Payload> ): EventInstance<Payload> => eventInstance;
29
-
30
- export type EventFactory<Name=any, EventPayload = any> = () => EventInstance<EventPayload, Name>
31
-
32
- export const EventMetadataSchema = S.shape({
33
- causationId: S.string().optional(),
34
- correlationId: S.string().optional(),
35
- user: S.any().optional()
36
- });
37
-
38
- export type EventMetadata = typeof EventMetadataSchema.type;
39
-
40
- export type EventToCommit<Payload = any> = {
41
- name: string,
42
- data?: Payload,
43
- stream: string
44
- metadata: EventMetadata
45
- };
46
-
47
- export type CommittedEvent<Payload = any> = EventToCommit<Payload> & {
48
- id: number
49
- timestamp: string
50
- version: number
51
- }
52
-
53
- const ensureArray = ( maybeArray: any ) => Array.isArray( maybeArray ) ? maybeArray : [maybeArray];
54
-
55
- export const CommittedEventSchema = <T>( payloadSchema: BaseSchema<T>, names?: string | string[]) => S.shape({
56
- id: S.number(),
57
- name: ( names ? S.string().enum( ...ensureArray( names )) : S.string()),
58
- timestamp: S.string().format( 'date-time' ),
59
- data: payloadSchema,
60
- version: S.number(),
61
- stream: S.string(),
62
- metadata: EventMetadataSchema,
63
- });
64
-
65
- export type GetMessageType<Payload> = Payload extends (()=> EventInstance<infer T> ) ? T : unknown
66
-
67
- export type Builder<T = any> = {
68
- build:() => T
69
- }
70
-
71
- export type GetBuilderType<T> = T extends ( Builder<infer InnerT> ) ? InnerT : T
72
-
73
- //*******************************************
74
- // Readmodels
75
- //*******************************************
76
- // export type GetEventType<SYSTEM extends System, Name extends A.Key> = GetMessageType<O.Path<SYSTEM, ['events', Name]>>
77
-
78
- // export type GetErrorDataType<Payload> = Payload extends (()=> AppErrorType<infer T>) ? T : unknown
79
- // export type CreateErrorType<ERRORS extends Record<string, AppErrorFactory>> = (errors: ERRORS)=> <ERROR extends keyof ERRORS>(error: ERROR, params: Pick<AppErrorInstance<GetErrorDataType<ERRORS[ERROR]>>, 'details' | 'description'> ) => AppErrorInstance<GetErrorDataType<ERRORS[ERROR]>>;
80
-
81
- export type ReadModelSubscription<Model extends Document = any> = {
82
- id: string;
83
- res: ResponseObject;
84
- filter: CollectionFilter<Model>[];
85
- };
86
-
87
-
88
- export type ReadStreamOptions = {
89
- stream?: string,
90
- direction?: 'forwards' | 'backwards',
91
- from?: number,
92
- fromVersion?: number,
93
- limit?: number,
94
- events?: string[],
95
- before?: string,
96
- after?: string,
97
- }
98
-
99
- export type ReadMultipleStreamOptions = Omit<ReadStreamOptions, 'stream'> & {
100
- streams: string[],
101
- }
102
-
103
- export type EventSourcingType = Pick<EventSourcingCommandHandlers, 'executeCommand' | 'loadAggregateState' | 'loadStream'> & {
104
- routeEventHandler: ( eventHandler: EventHandler | Builder<EventHandler> ) => void,
105
- routeCommandHandler: ( commandHandler: System ) => void,
106
-
107
- handleEvent: ( eventHandler: EventHandler, executeCommand: ExecuteCommandFunction ) => ( event: CommittedEvent ) => Promise<any>,
108
- logEventsourcingRoutes: () => void
109
- }
110
-
111
- export type EventSourcingPort = PortEmitter & EventSourcingType;
@@ -1,27 +0,0 @@
1
- import { DatabaseOps, ErrorTypes, LoggerType } from '..';
2
-
3
- export type InvariantParams = {
4
- errorName?: string;
5
- errorType?: ErrorTypes
6
- logger?: LoggerType;
7
- };
8
-
9
- export type ReadmodelInvariantComparisonOR = {
10
- OR: ReadmodelInvariantComparison[]
11
- }
12
-
13
- export type ReadmodelInvariantComparisonAND = {
14
- AND: ReadmodelInvariantComparison[]
15
- }
16
-
17
- export type ReadmodelInvariantComparisonInstance = {
18
- path: string;
19
- readmodelPath: string;
20
- op: DatabaseOps;
21
- };
22
-
23
- export type ReadmodelInvariantComparison = Partial<
24
- & ReadmodelInvariantComparisonOR
25
- & ReadmodelInvariantComparisonAND
26
- & ReadmodelInvariantComparisonInstance
27
- >
@@ -1,4 +0,0 @@
1
- import { CommittedEvent, EventFactory, EventHandler, GetMessageType, System } from '.';
2
- import { O } from 'ts-toolbelt';
3
-
4
- export type CreateEventType<Handler extends System | EventHandler> = <EVENT extends keyof O.Path<Handler, ['events']>>( event: EVENT, data?: GetMessageType<Handler['events'][EVENT]>, committedEvent?: Partial<Omit<CommittedEvent, 'data' | 'name'>> ) => EventFactory<EVENT, GetMessageType<Handler['events'][EVENT]>>;
package/src/index.ts DELETED
@@ -1,15 +0,0 @@
1
- export * from './authentication';
2
- export * from './cache';
3
- export * from './clusterAdministration';
4
- export * from './configuration';
5
- export * from './database';
6
- export * from './endpoints';
7
- export * from './evenstore';
8
- export * from './eventsourcing';
9
- export * from './infrastructure';
10
- export * from './logger';
11
- export * from './outboxManager';
12
- export * from './ports';
13
- export * from './routesAuth';
14
- export * from './typedEventEmitter';
15
- export * from './validation';
@@ -1,41 +0,0 @@
1
- import S from '@bett3r-dev/jsonschema-definer';
2
- import { OpenAPIV3_1 } from 'openapi-types';
3
- import { StructureServiceType } from './clusterAdministration';
4
- import { AdapterBase } from './ports';
5
-
6
- export const InfrastructureConfigSchema = S.shape({
7
- infrastructureLeaderRandomBackoff: S.number().default( 1000 ).optional()
8
- });
9
- export type InfrastructureConfigType = typeof InfrastructureConfigSchema.type;
10
-
11
- export type EnvironmentServiceType = {
12
- openApi: OpenAPIV3_1.Document,
13
- service: string,
14
- openApiEndpoint?: string,
15
- instances: {host: string, timeRunning: number}[],
16
- port: number,
17
- }
18
-
19
- export type InfrastructureServiceType = Omit<StructureServiceType, 'hosts'> & {
20
- instances: {host: string, timeRunning: number}[],
21
- service: string,
22
- }
23
- export type InfrastructureThisServiceType = InfrastructureServiceType & {
24
- leadershipRank: number;
25
- host: string;
26
- }
27
-
28
- export type InfrastructureAdapterType = AdapterBase & {
29
- getServices: () => Promise<EnvironmentServiceType[]>;
30
- // addService: (baseService: string, modules: string[]) => Promise<void>;
31
- // removeService: (service: string) => Promise<void>;
32
- scaleService: ( service: string, replicasCount: number ) => Promise<void>;
33
- listenForInfrastructureChanges: ( callback: ( event: 'destroy' | 'create', service: EnvironmentServiceType ) => void ) => void;
34
- reloadLoadBalancer: () => Promise<void>;
35
- };
36
-
37
- export type InfrastructurePortType = InfrastructureAdapterType & {
38
- getServicesOpenApiDocumentation: () => Record<string, OpenAPIV3_1.Document>;
39
- getThisServiceInfo: () => InfrastructureThisServiceType;
40
- start: InfrastructureAdapterType['start'];
41
- }
package/src/logger.ts DELETED
@@ -1,45 +0,0 @@
1
- import S from '@bett3r-dev/jsonschema-definer';
2
- import { AdapterBase } from './ports';
3
-
4
- export const LoggerConfigSchema = S.shape({
5
- logLevel: S.string().enum( 'silly', 'debug', 'log', 'info', 'warn', 'error' ).optional(),
6
- modulesWhitelist: S.array().items( S.string()).optional(),
7
- modulesBlacklist: S.array().items( S.string()).optional()
8
- }).optional();
9
- export type LoggerConfig = typeof LoggerConfigSchema.type;
10
-
11
- export type LogLevels = 'silly'| 'debug'| 'log'| 'info'| 'warn'| 'error';
12
-
13
- export const LogLevelMap = {
14
- error: 0,
15
- warn: 1,
16
- info: 2,
17
- log: 3,
18
- debug: 4,
19
- silly: 5,
20
- };
21
- export const LevelLogMap: Record<number, LogLevels> = {
22
- 0: 'error',
23
- 1: 'warn',
24
- 2: 'info',
25
- 3: 'log',
26
- 4: 'debug',
27
- 5: 'silly',
28
- };
29
-
30
- export type LoggerAdapter = AdapterBase & {
31
- log: ( originalArgs: any[], level: LogLevels , module: string ) => void
32
- }
33
-
34
- export type LoggerPort = {
35
- createLoggerInstance: ( module: string ) => LoggerType
36
- }
37
-
38
- export type LoggerType = {
39
- silly: ( ...args: any[])=>void
40
- debug: ( ...args: any[])=>void
41
- log: ( ...args: any[])=>void
42
- info: ( ...args: any[])=>void
43
- warn: ( ...args: any[])=>void
44
- error: ( ...args: any[])=>void
45
- }
@@ -1,36 +0,0 @@
1
- import S from '@bett3r-dev/jsonschema-definer';
2
- import { InfrastructureConfigSchema } from '@bett3r-dev/pv3-types';
3
- import { CommittedEvent } from '@bett3r-dev/pv3-types';
4
- import { ClusterStructureConfigSchema } from '@bett3r-dev/pv3-types';
5
-
6
- export const UdpConfigSchema = S.shape({
7
- port: S.number().default( 16706 ).optional(),
8
- multicastAddress: S.string().default( '224.0.1.50' ).optional(),
9
- ttl: S.number().optional()
10
- });
11
- export type UdpConfigType = typeof UdpConfigSchema.type;
12
-
13
-
14
- export const AdminServicesConfigSchema = S.shape({
15
- udp: UdpConfigSchema.optional().default({}),
16
- structure: ClusterStructureConfigSchema.optional().default({}),
17
- infrastructure: InfrastructureConfigSchema.optional().default({}),
18
- metricsInterval: S.number().optional().default( 1000 )
19
- });
20
- export type AdminServicesConfigType = typeof AdminServicesConfigSchema.type;
21
-
22
- export type OutboxManagerType = {
23
- start: ( activateDiscoveredSubscriptions?: boolean ) => Promise<void>,
24
- stop: () => Promise<void>
25
- }
26
-
27
- export type TcpEventMessageRequest = {
28
- endpoint: string,
29
- event: CommittedEvent
30
- }
31
- export type TcpEventMessageResponse = {
32
- id: number,
33
- status: number,
34
- error?: string
35
- }
36
-