@magek/core 0.0.1

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 (195) hide show
  1. package/dist/authorizer.d.ts +7 -0
  2. package/dist/authorizer.js +35 -0
  3. package/dist/command-dispatcher.d.ts +8 -0
  4. package/dist/command-dispatcher.js +55 -0
  5. package/dist/core-concepts/data-migration/entities/data-migration-entity.d.ts +12 -0
  6. package/dist/core-concepts/data-migration/entities/data-migration-entity.js +37 -0
  7. package/dist/core-concepts/data-migration/events/data-migration-finished.d.ts +7 -0
  8. package/dist/core-concepts/data-migration/events/data-migration-finished.js +13 -0
  9. package/dist/core-concepts/data-migration/events/data-migration-started.d.ts +7 -0
  10. package/dist/core-concepts/data-migration/events/data-migration-started.js +13 -0
  11. package/dist/core-concepts/data-migration/events/entity-migrated.d.ts +9 -0
  12. package/dist/core-concepts/data-migration/events/entity-migrated.js +15 -0
  13. package/dist/core-concepts/touch-entity/events/entity-touched.d.ts +7 -0
  14. package/dist/core-concepts/touch-entity/events/entity-touched.js +13 -0
  15. package/dist/data-migrations.d.ts +8 -0
  16. package/dist/data-migrations.js +73 -0
  17. package/dist/decorators/command.d.ts +19 -0
  18. package/dist/decorators/command.js +47 -0
  19. package/dist/decorators/data-migration.d.ts +9 -0
  20. package/dist/decorators/data-migration.js +25 -0
  21. package/dist/decorators/entity.d.ts +32 -0
  22. package/dist/decorators/entity.js +100 -0
  23. package/dist/decorators/event-handler.d.ts +3 -0
  24. package/dist/decorators/event-handler.js +18 -0
  25. package/dist/decorators/event.d.ts +8 -0
  26. package/dist/decorators/event.js +22 -0
  27. package/dist/decorators/field-metadata-reader.d.ts +6 -0
  28. package/dist/decorators/field-metadata-reader.js +221 -0
  29. package/dist/decorators/global-error-handler.d.ts +2 -0
  30. package/dist/decorators/global-error-handler.js +15 -0
  31. package/dist/decorators/global-event-handler.d.ts +3 -0
  32. package/dist/decorators/global-event-handler.js +9 -0
  33. package/dist/decorators/health-sensor.d.ts +14 -0
  34. package/dist/decorators/health-sensor.js +38 -0
  35. package/dist/decorators/index.d.ts +16 -0
  36. package/dist/decorators/index.js +19 -0
  37. package/dist/decorators/metadata.d.ts +13 -0
  38. package/dist/decorators/metadata.js +55 -0
  39. package/dist/decorators/non-exposed.d.ts +2 -0
  40. package/dist/decorators/non-exposed.js +24 -0
  41. package/dist/decorators/notification.d.ts +35 -0
  42. package/dist/decorators/notification.js +94 -0
  43. package/dist/decorators/projects.d.ts +32 -0
  44. package/dist/decorators/projects.js +87 -0
  45. package/dist/decorators/query.d.ts +2 -0
  46. package/dist/decorators/query.js +25 -0
  47. package/dist/decorators/read-model.d.ts +39 -0
  48. package/dist/decorators/read-model.js +129 -0
  49. package/dist/decorators/role.d.ts +6 -0
  50. package/dist/decorators/role.js +15 -0
  51. package/dist/decorators/scheduled-command.d.ts +9 -0
  52. package/dist/decorators/scheduled-command.js +25 -0
  53. package/dist/decorators/schema-migration.d.ts +36 -0
  54. package/dist/decorators/schema-migration.js +146 -0
  55. package/dist/decorators/sequenced-by.d.ts +28 -0
  56. package/dist/decorators/sequenced-by.js +79 -0
  57. package/dist/decorators/stage3-utils.d.ts +6 -0
  58. package/dist/decorators/stage3-utils.js +25 -0
  59. package/dist/delete-event-dispatcher.d.ts +4 -0
  60. package/dist/delete-event-dispatcher.js +23 -0
  61. package/dist/event-dispatcher.d.ts +9 -0
  62. package/dist/event-dispatcher.js +37 -0
  63. package/dist/event-processor.d.ts +15 -0
  64. package/dist/event-processor.js +125 -0
  65. package/dist/event-search.d.ts +2 -0
  66. package/dist/event-search.js +26 -0
  67. package/dist/event-stream-consumer.d.ts +7 -0
  68. package/dist/event-stream-consumer.js +36 -0
  69. package/dist/event-stream-producer.d.ts +7 -0
  70. package/dist/event-stream-producer.js +30 -0
  71. package/dist/events-reader.d.ts +11 -0
  72. package/dist/events-reader.js +63 -0
  73. package/dist/global-error-dispatcher.d.ts +16 -0
  74. package/dist/global-error-dispatcher.js +109 -0
  75. package/dist/graphql-dispatcher.d.ts +16 -0
  76. package/dist/graphql-dispatcher.js +195 -0
  77. package/dist/importer.d.ts +14 -0
  78. package/dist/importer.js +49 -0
  79. package/dist/index.d.ts +60 -0
  80. package/dist/index.js +100 -0
  81. package/dist/injectable/index.d.ts +21 -0
  82. package/dist/injectable/index.js +2 -0
  83. package/dist/instrumentation/decorator/trace.d.ts +13 -0
  84. package/dist/instrumentation/decorator/trace.js +116 -0
  85. package/dist/instrumentation/index.d.ts +2 -0
  86. package/dist/instrumentation/index.js +5 -0
  87. package/dist/instrumentation/trace-notifier.d.ts +3 -0
  88. package/dist/instrumentation/trace-notifier.js +26 -0
  89. package/dist/magek.d.ts +42 -0
  90. package/dist/magek.js +158 -0
  91. package/dist/query-dispatcher.d.ts +8 -0
  92. package/dist/query-dispatcher.js +47 -0
  93. package/dist/read-model-schema-migrator.d.ts +14 -0
  94. package/dist/read-model-schema-migrator.js +80 -0
  95. package/dist/read-models-reader.d.ts +31 -0
  96. package/dist/read-models-reader.js +196 -0
  97. package/dist/register-handler.d.ts +11 -0
  98. package/dist/register-handler.js +95 -0
  99. package/dist/rocket-dispatcher.d.ts +6 -0
  100. package/dist/rocket-dispatcher.js +21 -0
  101. package/dist/scheduled-command-dispatcher.d.ts +12 -0
  102. package/dist/scheduled-command-dispatcher.js +54 -0
  103. package/dist/schema-migrator.d.ts +12 -0
  104. package/dist/schema-migrator.js +71 -0
  105. package/dist/sensor/health/health-indicators/database-events-health-indicator.d.ts +5 -0
  106. package/dist/sensor/health/health-indicators/database-events-health-indicator.js +26 -0
  107. package/dist/sensor/health/health-indicators/database-health-indicator.d.ts +5 -0
  108. package/dist/sensor/health/health-indicators/database-health-indicator.js +29 -0
  109. package/dist/sensor/health/health-indicators/database-read-models-health-indicator.d.ts +5 -0
  110. package/dist/sensor/health/health-indicators/database-read-models-health-indicator.js +26 -0
  111. package/dist/sensor/health/health-indicators/default-health-indicators.d.ts +5 -0
  112. package/dist/sensor/health/health-indicators/default-health-indicators.js +39 -0
  113. package/dist/sensor/health/health-indicators/function-health-indicator.d.ts +5 -0
  114. package/dist/sensor/health/health-indicators/function-health-indicator.js +30 -0
  115. package/dist/sensor/health/health-indicators/health-indicator.d.ts +5 -0
  116. package/dist/sensor/health/health-indicators/health-indicator.js +30 -0
  117. package/dist/sensor/health/health-indicators/index.d.ts +3 -0
  118. package/dist/sensor/health/health-indicators/index.js +6 -0
  119. package/dist/sensor/health/health-indicators/os-info.d.ts +14 -0
  120. package/dist/sensor/health/health-indicators/os-info.js +38 -0
  121. package/dist/sensor/health/health-indicators/rockets-health-indicator.d.ts +5 -0
  122. package/dist/sensor/health/health-indicators/rockets-health-indicator.js +57 -0
  123. package/dist/sensor/health/health-indicators/version.d.ts +2 -0
  124. package/dist/sensor/health/health-indicators/version.js +24 -0
  125. package/dist/sensor/health/health-service.d.ts +22 -0
  126. package/dist/sensor/health/health-service.js +117 -0
  127. package/dist/sensor/health/health-utils.d.ts +7 -0
  128. package/dist/sensor/health/health-utils.js +53 -0
  129. package/dist/sensor/health/index.d.ts +3 -0
  130. package/dist/sensor/health/index.js +6 -0
  131. package/dist/sensor/index.d.ts +1 -0
  132. package/dist/sensor/index.js +4 -0
  133. package/dist/services/event-store.d.ts +27 -0
  134. package/dist/services/event-store.js +260 -0
  135. package/dist/services/filter-helpers.d.ts +3 -0
  136. package/dist/services/filter-helpers.js +19 -0
  137. package/dist/services/graphql/common.d.ts +26 -0
  138. package/dist/services/graphql/common.js +53 -0
  139. package/dist/services/graphql/graphql-generator.d.ts +46 -0
  140. package/dist/services/graphql/graphql-generator.js +269 -0
  141. package/dist/services/graphql/graphql-mutation-generator.d.ts +12 -0
  142. package/dist/services/graphql/graphql-mutation-generator.js +25 -0
  143. package/dist/services/graphql/graphql-query-generator.d.ts +22 -0
  144. package/dist/services/graphql/graphql-query-generator.js +39 -0
  145. package/dist/services/graphql/graphql-subcriptions-generator.d.ts +17 -0
  146. package/dist/services/graphql/graphql-subcriptions-generator.js +60 -0
  147. package/dist/services/graphql/graphql-type-informer.d.ts +23 -0
  148. package/dist/services/graphql/graphql-type-informer.js +160 -0
  149. package/dist/services/graphql/query-generators/graphql-query-by-keys-generator.d.ts +14 -0
  150. package/dist/services/graphql/query-generators/graphql-query-by-keys-generator.js +48 -0
  151. package/dist/services/graphql/query-generators/graphql-query-events-generator.d.ts +11 -0
  152. package/dist/services/graphql/query-generators/graphql-query-events-generator.js +68 -0
  153. package/dist/services/graphql/query-generators/graphql-query-filters-generator.d.ts +14 -0
  154. package/dist/services/graphql/query-generators/graphql-query-filters-generator.js +31 -0
  155. package/dist/services/graphql/query-generators/graphql-query-generator.d.ts +12 -0
  156. package/dist/services/graphql/query-generators/graphql-query-generator.js +17 -0
  157. package/dist/services/graphql/query-generators/graphql-query-listed-generator.d.ts +16 -0
  158. package/dist/services/graphql/query-generators/graphql-query-listed-generator.js +65 -0
  159. package/dist/services/graphql/query-helpers/graphql-handled-fields-generator.d.ts +15 -0
  160. package/dist/services/graphql/query-helpers/graphql-handled-fields-generator.js +65 -0
  161. package/dist/services/graphql/query-helpers/graphql-query-filter-arguments-builder.d.ts +13 -0
  162. package/dist/services/graphql/query-helpers/graphql-query-filter-arguments-builder.js +169 -0
  163. package/dist/services/graphql/query-helpers/graphql-query-filter-fields-builder.d.ts +11 -0
  164. package/dist/services/graphql/query-helpers/graphql-query-filter-fields-builder.js +28 -0
  165. package/dist/services/graphql/query-helpers/graphql-query-sort-builder.d.ts +12 -0
  166. package/dist/services/graphql/query-helpers/graphql-query-sort-builder.js +61 -0
  167. package/dist/services/graphql/websocket-protocol/graphql-websocket-protocol.d.ts +20 -0
  168. package/dist/services/graphql/websocket-protocol/graphql-websocket-protocol.js +127 -0
  169. package/dist/services/pub-sub/noop-read-model-pub-sub.d.ts +5 -0
  170. package/dist/services/pub-sub/noop-read-model-pub-sub.js +10 -0
  171. package/dist/services/pub-sub/read-model-pub-sub.d.ts +9 -0
  172. package/dist/services/pub-sub/read-model-pub-sub.js +112 -0
  173. package/dist/services/raw-events-parser.d.ts +5 -0
  174. package/dist/services/raw-events-parser.js +44 -0
  175. package/dist/services/read-model-searcher.d.ts +2 -0
  176. package/dist/services/read-model-searcher.js +11 -0
  177. package/dist/services/read-model-store.d.ts +41 -0
  178. package/dist/services/read-model-store.js +295 -0
  179. package/dist/services/token-verifiers/index.d.ts +4 -0
  180. package/dist/services/token-verifiers/index.js +7 -0
  181. package/dist/services/token-verifiers/jwks-uri-token-verifier.d.ts +21 -0
  182. package/dist/services/token-verifiers/jwks-uri-token-verifier.js +23 -0
  183. package/dist/services/token-verifiers/public-key-token-verifier.d.ts +13 -0
  184. package/dist/services/token-verifiers/public-key-token-verifier.js +19 -0
  185. package/dist/services/token-verifiers/role-based-token-verifier.d.ts +8 -0
  186. package/dist/services/token-verifiers/role-based-token-verifier.js +35 -0
  187. package/dist/services/token-verifiers/utilities.d.ts +31 -0
  188. package/dist/services/token-verifiers/utilities.js +70 -0
  189. package/dist/subscribers-notifier.d.ts +14 -0
  190. package/dist/subscribers-notifier.js +109 -0
  191. package/dist/token-verifier.d.ts +11 -0
  192. package/dist/token-verifier.js +46 -0
  193. package/dist/touch-entity-handler.d.ts +4 -0
  194. package/dist/touch-entity-handler.js +16 -0
  195. package/package.json +71 -0
@@ -0,0 +1,195 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MagekGraphQLDispatcher = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const common_1 = require("@magek/common");
6
+ const graphql_1 = require("graphql");
7
+ const graphql = require("graphql");
8
+ const graphql_generator_1 = require("./services/graphql/graphql-generator");
9
+ const read_models_reader_1 = require("./read-models-reader");
10
+ const noop_read_model_pub_sub_1 = require("./services/pub-sub/noop-read-model-pub-sub");
11
+ const graphql_websocket_protocol_1 = require("./services/graphql/websocket-protocol/graphql-websocket-protocol");
12
+ const token_verifier_1 = require("./token-verifier");
13
+ const instrumentation_1 = require("./instrumentation");
14
+ class MagekGraphQLDispatcher {
15
+ constructor(config) {
16
+ this.config = config;
17
+ this.readModelDispatcher = new read_models_reader_1.MagekReadModelsReader(config);
18
+ this.graphQLSchema = graphql_generator_1.GraphQLGenerator.generateSchema(config);
19
+ this.tokenVerifier = new token_verifier_1.MagekTokenVerifier(config);
20
+ this.websocketHandler = new graphql_websocket_protocol_1.GraphQLWebsocketHandler(config, {
21
+ onStartOperation: this.runGraphQLOperation.bind(this),
22
+ onStopOperation: this.readModelDispatcher.unsubscribe.bind(this.readModelDispatcher),
23
+ onTerminate: this.handleDisconnect.bind(this),
24
+ }, this.tokenVerifier);
25
+ }
26
+ async dispatch(request) {
27
+ const logger = (0, common_1.getLogger)(this.config, 'MagekGraphQLDispatcher#dispatch');
28
+ const envelopeOrError = await this.config.provider.graphQL.rawToEnvelope(this.config, request);
29
+ logger.debug('Received the following GraphQL envelope: ', envelopeOrError);
30
+ switch (envelopeOrError.eventType) {
31
+ case 'CONNECT':
32
+ return this.config.provider.graphQL.handleResult(null, common_1.graphQLWebsocketSubprotocolHeaders);
33
+ case 'MESSAGE':
34
+ const responseHeaders = { ...this.config.defaultResponseHeaders };
35
+ const result = await this.handleMessage(envelopeOrError, responseHeaders);
36
+ return this.config.provider.graphQL.handleResult(result, responseHeaders);
37
+ case 'DISCONNECT':
38
+ return this.config.provider.graphQL.handleResult(await this.handleDisconnect(envelopeOrError.connectionID));
39
+ default:
40
+ return this.config.provider.graphQL.handleResult({
41
+ errors: [new Error(`Unknown message type ${envelopeOrError.eventType}`)],
42
+ });
43
+ }
44
+ }
45
+ async verifyTokenFromEnvelope(envelope) {
46
+ const logger = (0, common_1.getLogger)(this.config, 'MagekGraphQLDispatcher#verifyTokenFromEnvelop');
47
+ if (envelope.token) {
48
+ try {
49
+ logger.debug(`Decoding current user from auth token: ${envelope.token}`);
50
+ envelope.currentUser = await this.tokenVerifier.verify(envelope.token);
51
+ }
52
+ catch (e) {
53
+ envelope = {
54
+ ...envelope,
55
+ error: e,
56
+ };
57
+ logger.debug('Unable to decode auth token');
58
+ }
59
+ }
60
+ return envelope;
61
+ }
62
+ async handleMessage(envelope, responseHeaders) {
63
+ const logger = (0, common_1.getLogger)(this.config, 'MagekGraphQLDispatcher#handleMessage');
64
+ logger.debug('Starting GraphQL operation:', envelope);
65
+ const envelopeOrError = await this.verifyTokenFromEnvelope(envelope);
66
+ if (cameThroughSocket(envelopeOrError)) {
67
+ return this.websocketHandler.handle(envelopeOrError);
68
+ }
69
+ return this.runGraphQLOperation(envelopeOrError, responseHeaders);
70
+ }
71
+ async runGraphQLOperation(envelope, responseHeaders = {}) {
72
+ const logger = (0, common_1.getLogger)(this.config, 'MagekGraphQLDispatcher#runGraphQLOperation');
73
+ try {
74
+ if ('error' in envelope) {
75
+ throw envelope.error;
76
+ }
77
+ if (!envelope.value) {
78
+ throw new common_1.InvalidParameterError('Received an empty GraphQL body');
79
+ }
80
+ const operation = envelope.value;
81
+ if (!operation.query) {
82
+ throw new common_1.InvalidParameterError('Received an empty GraphQL query');
83
+ }
84
+ const queryDocument = graphql.parse(operation.query);
85
+ const errors = graphql.validate(this.graphQLSchema, queryDocument);
86
+ if (errors.length > 0) {
87
+ throw errors;
88
+ }
89
+ const operationData = graphql.getOperationAST(queryDocument, operation.operationName);
90
+ const isIntrospectionQuery = operation.operationName === 'IntrospectionQuery' || operation.query.includes('__schema');
91
+ if (isIntrospectionQuery && !this.config.enableGraphQLIntrospection) {
92
+ throw new common_1.InvalidProtocolError('Instrospection queries are disabled. Check the configuration if you want to enable them.');
93
+ }
94
+ if (!operationData) {
95
+ throw new common_1.InvalidParameterError('Could not extract GraphQL operation. ' +
96
+ 'Be sure to either send only one query, mutation, or subscription, or, in case you send several operations, ' +
97
+ 'include the "operationName" field');
98
+ }
99
+ const resolverContext = {
100
+ connectionID: envelope.connectionID,
101
+ responseHeaders: responseHeaders,
102
+ requestID: envelope.requestID,
103
+ user: envelope.currentUser,
104
+ operation: {
105
+ ...operation,
106
+ },
107
+ pubSub: new noop_read_model_pub_sub_1.NoopReadModelPubSub(),
108
+ storeSubscriptions: true,
109
+ context: envelope.context,
110
+ };
111
+ switch (operationData.operation) {
112
+ case graphql_1.OperationTypeNode.QUERY:
113
+ case graphql_1.OperationTypeNode.MUTATION:
114
+ return await this.handleQueryOrMutation(queryDocument, resolverContext);
115
+ case graphql_1.OperationTypeNode.SUBSCRIPTION:
116
+ return await this.handleSubscription(queryDocument, resolverContext);
117
+ }
118
+ }
119
+ catch (e) {
120
+ const error = e;
121
+ logger.error(e);
122
+ const errors = Array.isArray(e) ? e.map(toGraphQLErrorWithExtensions) : [toGraphQLErrorWithExtensions(error)];
123
+ return { errors };
124
+ }
125
+ }
126
+ async handleQueryOrMutation(queryDocument, resolverContext) {
127
+ var _a;
128
+ const logger = (0, common_1.getLogger)(this.config, 'MagekGraphQLDispatcher#handleQueryOrMutation');
129
+ const result = await graphql.execute({
130
+ schema: this.graphQLSchema,
131
+ document: queryDocument,
132
+ contextValue: resolverContext,
133
+ variableValues: resolverContext.operation.variables,
134
+ operationName: resolverContext.operation.operationName,
135
+ });
136
+ result.errors = (_a = result.errors) === null || _a === void 0 ? void 0 : _a.map(toGraphQLErrorWithExtensions);
137
+ logger.debug('GraphQL result: ', result);
138
+ return result;
139
+ }
140
+ async handleSubscription(queryDocument, resolverContext) {
141
+ const logger = (0, common_1.getLogger)(this.config, 'MagekGraphQLDispatcher#handleSubscription');
142
+ if (!cameThroughSocket(resolverContext)) {
143
+ throw new common_1.InvalidProtocolError('This API and protocol does not support "subscription" operations, only "query" and "mutation". Use the socket API for "subscription"');
144
+ }
145
+ const result = await graphql.subscribe({
146
+ schema: this.graphQLSchema,
147
+ document: queryDocument,
148
+ contextValue: resolverContext,
149
+ variableValues: resolverContext.operation.variables,
150
+ operationName: resolverContext.operation.operationName,
151
+ });
152
+ logger.debug('GraphQL subscription finished');
153
+ return result;
154
+ }
155
+ async handleDisconnect(connectionID) {
156
+ const logger = (0, common_1.getLogger)(this.config, 'MagekGraphQLDispatcher#handleDisconnect');
157
+ if (!connectionID) {
158
+ // This should be impossible, but just in case
159
+ logger.info("Received a DISCONNECT message but field 'connectionID' is missing. Doing nothing");
160
+ return;
161
+ }
162
+ logger.debug('Deleting all subscriptions and connection data');
163
+ await this.config.sessionStore.deleteConnection(this.config, connectionID);
164
+ await this.readModelDispatcher.unsubscribeAll(connectionID);
165
+ }
166
+ }
167
+ exports.MagekGraphQLDispatcher = MagekGraphQLDispatcher;
168
+ tslib_1.__decorate([
169
+ (0, instrumentation_1.Trace)(common_1.TraceActionTypes.GRAPHQL_DISPATCH),
170
+ tslib_1.__metadata("design:type", Function),
171
+ tslib_1.__metadata("design:paramtypes", [Object]),
172
+ tslib_1.__metadata("design:returntype", Promise)
173
+ ], MagekGraphQLDispatcher.prototype, "dispatch", null);
174
+ tslib_1.__decorate([
175
+ (0, instrumentation_1.Trace)(common_1.TraceActionTypes.GRAPHQL_RUN_OPERATION),
176
+ tslib_1.__metadata("design:type", Function),
177
+ tslib_1.__metadata("design:paramtypes", [Object, Object]),
178
+ tslib_1.__metadata("design:returntype", Promise)
179
+ ], MagekGraphQLDispatcher.prototype, "runGraphQLOperation", null);
180
+ function cameThroughSocket(withConnectionID) {
181
+ return withConnectionID.connectionID != undefined;
182
+ }
183
+ function toGraphQLErrorWithExtensions(e) {
184
+ if (e instanceof graphql_1.GraphQLError) {
185
+ const originalError = e.originalError;
186
+ return new graphql_1.GraphQLError(e.message, e.nodes, e.source, e.positions, e.path, originalError, {
187
+ code: originalError === null || originalError === void 0 ? void 0 : originalError.code,
188
+ data: originalError === null || originalError === void 0 ? void 0 : originalError.data,
189
+ });
190
+ }
191
+ return new graphql_1.GraphQLError(e.message, undefined, undefined, undefined, undefined, e, {
192
+ code: e.code,
193
+ data: e.data,
194
+ });
195
+ }
@@ -0,0 +1,14 @@
1
+ export declare class Importer {
2
+ static importUserProjectFiles(codeRootPath: string): void;
3
+ private static importWithoutExtension;
4
+ private static getImportFiles;
5
+ private static walkDir;
6
+ /**
7
+ * Returns true if the file is a JavaScript file.
8
+ */
9
+ private static isJavaScriptFile;
10
+ private static isNotIndexJs;
11
+ private static removeDevExtension;
12
+ private static listDirectory;
13
+ private static isDirectory;
14
+ }
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Importer = void 0;
4
+ const fs = require("fs");
5
+ const path = require("path");
6
+ class Importer {
7
+ static importUserProjectFiles(codeRootPath) {
8
+ Importer.getImportFiles(codeRootPath).forEach(Importer.importWithoutExtension);
9
+ }
10
+ static importWithoutExtension(file) {
11
+ require(Importer.removeDevExtension(file));
12
+ }
13
+ static getImportFiles(codeRootPath) {
14
+ return Importer.walkDir(codeRootPath).filter(Importer.isJavaScriptFile).filter(Importer.isNotIndexJs);
15
+ }
16
+ static walkDir(dir) {
17
+ const files = [];
18
+ Importer.listDirectory(dir).forEach((file) => {
19
+ const fileName = path.join(dir, file);
20
+ if (Importer.isDirectory(fileName)) {
21
+ const filesInDirectory = Importer.walkDir(fileName);
22
+ files.push(...filesInDirectory);
23
+ }
24
+ else {
25
+ files.push(fileName);
26
+ }
27
+ });
28
+ return files;
29
+ }
30
+ /**
31
+ * Returns true if the file is a JavaScript file.
32
+ */
33
+ static isJavaScriptFile(file) {
34
+ return file.match(/.*\.js$/) != null;
35
+ }
36
+ static isNotIndexJs(file) {
37
+ return file.match(/index.js$/) == null;
38
+ }
39
+ static removeDevExtension(file) {
40
+ return path.join(file.replace(/(\.d)?(\.ts|\.js)/, ''));
41
+ }
42
+ static listDirectory(dir) {
43
+ return fs.readdirSync(dir);
44
+ }
45
+ static isDirectory(fileName) {
46
+ return fs.statSync(fileName).isDirectory();
47
+ }
48
+ }
49
+ exports.Importer = Importer;
@@ -0,0 +1,60 @@
1
+ export { Magek } from './magek';
2
+ export { RegisterHandler } from './register-handler';
3
+ export * from './decorators';
4
+ export { MagekDataMigrations } from './data-migrations';
5
+ export { MagekDataMigrationFinished } from './core-concepts/data-migration/events/data-migration-finished';
6
+ export { MagekDataMigrationEntity } from './core-concepts/data-migration/entities/data-migration-entity';
7
+ export { MagekTouchEntityHandler } from './touch-entity-handler';
8
+ export * from './services/token-verifiers';
9
+ export * from './instrumentation/index';
10
+ export * from './decorators/health-sensor';
11
+ export * as Injectable from './injectable';
12
+ /**
13
+ * Pushes a page of events to be processed by the event dispatcher.
14
+ *
15
+ * @param rawEvents A provider-specific representation of the events to be processed
16
+ * @returns A promise that resolves when the events are processed
17
+ */
18
+ export declare function eventDispatcher(rawEvents: unknown): Promise<void>;
19
+ /**
20
+ * Serves a GraphQL request. GraphQL resolvers can send response objects back to the client.
21
+ *
22
+ * @param rawRequest A provider-specific representation of the GraphQL request.
23
+ * @returns A promise that resolves to the GraphQL response.
24
+ */
25
+ export declare function graphQLDispatcher(rawRequest: unknown): Promise<unknown>;
26
+ /**
27
+ * Triggers pending scheduled commands. This function is meant to be called by a scheduler.
28
+ *
29
+ * @param rawRequest A provider-specific representation of the request to trigger scheduled commands
30
+ * @returns A promise that resolves when the scheduled commands are triggered
31
+ */
32
+ export declare function triggerScheduledCommands(rawRequest: unknown): Promise<void>;
33
+ /**
34
+ * Notifies subscribers of a new update on a read model
35
+ *
36
+ * @param rawRequest A provider-specific representation of the request to notify subscribers.
37
+ * @returns A promise that resolves when the subscribers are notified
38
+ */
39
+ export declare function notifySubscribers(rawRequest: unknown): Promise<void>;
40
+ /**
41
+ * Consumes events from the event stream and dispatches them to the event handlers
42
+ *
43
+ * @param rawEvent A provider-specific representation of the event to be processed
44
+ * @returns A promise that resolves when the event is processed
45
+ */
46
+ export declare function consumeEventStream(rawEvent: unknown): Promise<unknown>;
47
+ /**
48
+ * Produces events to the event stream
49
+ *
50
+ * @param rawEvent A provider-specific representation of the event to be produced
51
+ * @returns A promise that resolves when the event is produced
52
+ */
53
+ export declare function produceEventStream(rawEvent: unknown): Promise<unknown>;
54
+ /**
55
+ * Returns the health of the application
56
+ *
57
+ * @param request A provider-specific representation of the request to check the health
58
+ * @returns A promise that resolves to the health of the application
59
+ */
60
+ export declare function health(request: unknown): Promise<unknown>;
package/dist/index.js ADDED
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Injectable = exports.MagekTouchEntityHandler = exports.MagekDataMigrationEntity = exports.MagekDataMigrationFinished = exports.MagekDataMigrations = exports.RegisterHandler = exports.Magek = void 0;
4
+ exports.eventDispatcher = eventDispatcher;
5
+ exports.graphQLDispatcher = graphQLDispatcher;
6
+ exports.triggerScheduledCommands = triggerScheduledCommands;
7
+ exports.notifySubscribers = notifySubscribers;
8
+ exports.consumeEventStream = consumeEventStream;
9
+ exports.produceEventStream = produceEventStream;
10
+ exports.health = health;
11
+ const tslib_1 = require("tslib");
12
+ const magek_1 = require("./magek");
13
+ const event_dispatcher_1 = require("./event-dispatcher");
14
+ const graphql_dispatcher_1 = require("./graphql-dispatcher");
15
+ const scheduled_command_dispatcher_1 = require("./scheduled-command-dispatcher");
16
+ const subscribers_notifier_1 = require("./subscribers-notifier");
17
+ const event_stream_consumer_1 = require("./event-stream-consumer");
18
+ const event_stream_producer_1 = require("./event-stream-producer");
19
+ const sensor_1 = require("./sensor");
20
+ // Exports
21
+ var magek_2 = require("./magek");
22
+ Object.defineProperty(exports, "Magek", { enumerable: true, get: function () { return magek_2.Magek; } });
23
+ var register_handler_1 = require("./register-handler");
24
+ Object.defineProperty(exports, "RegisterHandler", { enumerable: true, get: function () { return register_handler_1.RegisterHandler; } });
25
+ tslib_1.__exportStar(require("./decorators"), exports);
26
+ var data_migrations_1 = require("./data-migrations");
27
+ Object.defineProperty(exports, "MagekDataMigrations", { enumerable: true, get: function () { return data_migrations_1.MagekDataMigrations; } });
28
+ var data_migration_finished_1 = require("./core-concepts/data-migration/events/data-migration-finished");
29
+ Object.defineProperty(exports, "MagekDataMigrationFinished", { enumerable: true, get: function () { return data_migration_finished_1.MagekDataMigrationFinished; } });
30
+ var data_migration_entity_1 = require("./core-concepts/data-migration/entities/data-migration-entity");
31
+ Object.defineProperty(exports, "MagekDataMigrationEntity", { enumerable: true, get: function () { return data_migration_entity_1.MagekDataMigrationEntity; } });
32
+ var touch_entity_handler_1 = require("./touch-entity-handler");
33
+ Object.defineProperty(exports, "MagekTouchEntityHandler", { enumerable: true, get: function () { return touch_entity_handler_1.MagekTouchEntityHandler; } });
34
+ tslib_1.__exportStar(require("./services/token-verifiers"), exports);
35
+ tslib_1.__exportStar(require("./instrumentation/index"), exports);
36
+ tslib_1.__exportStar(require("./decorators/health-sensor"), exports);
37
+ exports.Injectable = require("./injectable");
38
+ /**
39
+ * Pushes a page of events to be processed by the event dispatcher.
40
+ *
41
+ * @param rawEvents A provider-specific representation of the events to be processed
42
+ * @returns A promise that resolves when the events are processed
43
+ */
44
+ async function eventDispatcher(rawEvents) {
45
+ return event_dispatcher_1.MagekEventDispatcher.dispatch(rawEvents, magek_1.Magek.config);
46
+ }
47
+ /**
48
+ * Serves a GraphQL request. GraphQL resolvers can send response objects back to the client.
49
+ *
50
+ * @param rawRequest A provider-specific representation of the GraphQL request.
51
+ * @returns A promise that resolves to the GraphQL response.
52
+ */
53
+ async function graphQLDispatcher(rawRequest) {
54
+ return new graphql_dispatcher_1.MagekGraphQLDispatcher(magek_1.Magek.config).dispatch(rawRequest);
55
+ }
56
+ /**
57
+ * Triggers pending scheduled commands. This function is meant to be called by a scheduler.
58
+ *
59
+ * @param rawRequest A provider-specific representation of the request to trigger scheduled commands
60
+ * @returns A promise that resolves when the scheduled commands are triggered
61
+ */
62
+ async function triggerScheduledCommands(rawRequest) {
63
+ return new scheduled_command_dispatcher_1.MagekScheduledCommandDispatcher(magek_1.Magek.config).dispatch(rawRequest);
64
+ }
65
+ /**
66
+ * Notifies subscribers of a new update on a read model
67
+ *
68
+ * @param rawRequest A provider-specific representation of the request to notify subscribers.
69
+ * @returns A promise that resolves when the subscribers are notified
70
+ */
71
+ async function notifySubscribers(rawRequest) {
72
+ return new subscribers_notifier_1.MagekSubscribersNotifier(magek_1.Magek.config).dispatch(rawRequest);
73
+ }
74
+ /**
75
+ * Consumes events from the event stream and dispatches them to the event handlers
76
+ *
77
+ * @param rawEvent A provider-specific representation of the event to be processed
78
+ * @returns A promise that resolves when the event is processed
79
+ */
80
+ async function consumeEventStream(rawEvent) {
81
+ return event_stream_consumer_1.MagekEventStreamConsumer.consume(rawEvent, magek_1.Magek.config);
82
+ }
83
+ /**
84
+ * Produces events to the event stream
85
+ *
86
+ * @param rawEvent A provider-specific representation of the event to be produced
87
+ * @returns A promise that resolves when the event is produced
88
+ */
89
+ async function produceEventStream(rawEvent) {
90
+ return event_stream_producer_1.MagekEventStreamProducer.produce(rawEvent, magek_1.Magek.config);
91
+ }
92
+ /**
93
+ * Returns the health of the application
94
+ *
95
+ * @param request A provider-specific representation of the request to check the health
96
+ * @returns A promise that resolves to the health of the application
97
+ */
98
+ async function health(request) {
99
+ return new sensor_1.MagekHealthService(magek_1.Magek.config).health(request);
100
+ }
@@ -0,0 +1,21 @@
1
+ import type { Command as OclifCommand, Config } from '@oclif/core';
2
+ /**
3
+ * Type for a concrete oclif Command class (non-abstract).
4
+ * This represents a class constructor that creates Command instances.
5
+ */
6
+ export type ConcreteCommand = new (argv: string[], config: Config) => OclifCommand;
7
+ /**
8
+ * Injectable interface for registering custom CLI commands with Magek.
9
+ * Commands should be oclif Command classes (concrete implementations, not abstract).
10
+ */
11
+ export interface Injectable {
12
+ /**
13
+ * Map of command names to oclif Command classes.
14
+ * The command name will be used as the subcommand name.
15
+ */
16
+ commands: Record<string, ConcreteCommand>;
17
+ }
18
+ /**
19
+ * Type for an oclif Command class.
20
+ */
21
+ export type Command = ConcreteCommand;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Stage 3 method decorator context
3
+ */
4
+ interface Stage3MethodContext {
5
+ kind: 'method';
6
+ name: string | symbol;
7
+ static: boolean;
8
+ private: boolean;
9
+ metadata: Record<string | symbol, unknown>;
10
+ addInitializer?: (initializer: () => void) => void;
11
+ }
12
+ export declare function Trace(actionType?: string, description?: string): (targetOrMethod: unknown, memberOrContext: string | Stage3MethodContext, descriptor?: TypedPropertyDescriptor<(...params: any[]) => Promise<any>>) => any;
13
+ export {};
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Trace = Trace;
4
+ const common_1 = require("@magek/common");
5
+ const trace_notifier_1 = require("../trace-notifier");
6
+ const magek_1 = require("../../magek");
7
+ /**
8
+ * Type guard for Stage 3 method context
9
+ */
10
+ function isStage3MethodContext(arg) {
11
+ return (arg !== null &&
12
+ typeof arg === 'object' &&
13
+ 'kind' in arg &&
14
+ arg.kind === 'method' &&
15
+ 'name' in arg);
16
+ }
17
+ function Trace(actionType = common_1.TraceActionTypes.CUSTOM, description) {
18
+ // Return type is 'any' to support both legacy (returns PropertyDescriptor) and Stage 3 (returns Function) decorators
19
+ return (targetOrMethod, memberOrContext, descriptor) => {
20
+ // Detect Stage 3 decorator
21
+ if (isStage3MethodContext(memberOrContext)) {
22
+ // Stage 3: targetOrMethod is the actual method function
23
+ const originalMethod = targetOrMethod;
24
+ const methodName = String(memberOrContext.name);
25
+ // Return a new function that wraps the original
26
+ return async function (...args) {
27
+ const config = magek_1.Magek.config;
28
+ const tracerConfigured = (0, trace_notifier_1.isTraceEnabled)(actionType, config);
29
+ if (!tracerConfigured) {
30
+ return await originalMethod.apply(this, args);
31
+ }
32
+ const parameters = buildParametersStage3(this, methodName, args, description, config);
33
+ const startTime = new Date().getTime();
34
+ await (0, trace_notifier_1.notifyTrace)(common_1.TraceTypes.START, actionType, parameters, config);
35
+ try {
36
+ return await originalMethod.apply(this, args);
37
+ }
38
+ finally {
39
+ parameters.elapsedInvocationMillis = new Date().getTime() - startTime;
40
+ await (0, trace_notifier_1.notifyTrace)(common_1.TraceTypes.END, actionType, parameters, config);
41
+ }
42
+ };
43
+ }
44
+ // Legacy decorator
45
+ const target = targetOrMethod;
46
+ const member = memberOrContext;
47
+ // Handle case where descriptor is undefined (can happen with certain TypeScript/ESM configurations)
48
+ if (!descriptor) {
49
+ return;
50
+ }
51
+ const originalMethod = descriptor.value;
52
+ if (!originalMethod) {
53
+ return descriptor;
54
+ }
55
+ descriptor.value = async function (...args) {
56
+ const config = magek_1.Magek.config;
57
+ const tracerConfigured = (0, trace_notifier_1.isTraceEnabled)(actionType, config);
58
+ if (!tracerConfigured) {
59
+ return await originalMethod.apply(this, args);
60
+ }
61
+ const parameters = buildParameters(target, member, args, description, descriptor, config);
62
+ const startTime = new Date().getTime();
63
+ await (0, trace_notifier_1.notifyTrace)(common_1.TraceTypes.START, actionType, parameters, config);
64
+ try {
65
+ return await originalMethod.apply(this, args);
66
+ }
67
+ finally {
68
+ parameters.elapsedInvocationMillis = new Date().getTime() - startTime;
69
+ await (0, trace_notifier_1.notifyTrace)(common_1.TraceTypes.END, actionType, parameters, config);
70
+ }
71
+ };
72
+ return descriptor;
73
+ };
74
+ }
75
+ function buildParameters(target, member, args, description, descriptor, config) {
76
+ let internal = undefined;
77
+ if (config && config.traceConfiguration.includeInternal) {
78
+ internal = {
79
+ target: target,
80
+ descriptor: descriptor,
81
+ };
82
+ }
83
+ const parameters = {
84
+ className: getClassName(target),
85
+ methodName: member,
86
+ args: args,
87
+ description: description,
88
+ traceId: common_1.UUID.generate(),
89
+ internal: internal,
90
+ };
91
+ return parameters;
92
+ }
93
+ function buildParametersStage3(instance, methodName, args, description, config) {
94
+ let internal = undefined;
95
+ if (config && config.traceConfiguration.includeInternal) {
96
+ internal = {
97
+ target: instance,
98
+ descriptor: {}, // Stage 3 decorators don't have access to property descriptors
99
+ };
100
+ }
101
+ const parameters = {
102
+ className: getClassName(instance),
103
+ methodName: methodName,
104
+ args: args,
105
+ description: description,
106
+ traceId: common_1.UUID.generate(),
107
+ internal: internal,
108
+ };
109
+ return parameters;
110
+ }
111
+ // Get class name for instances and static methods
112
+ function getClassName(target) {
113
+ var _a, _b, _c, _d, _e;
114
+ // @ts-ignore
115
+ return (_e = (_c = (_b = (_a = target === null || target === void 0 ? void 0 : target.prototype) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) !== null && _c !== void 0 ? _c : (_d = target === null || target === void 0 ? void 0 : target.constructor) === null || _d === void 0 ? void 0 : _d.name) !== null && _e !== void 0 ? _e : '';
116
+ }
@@ -0,0 +1,2 @@
1
+ export * from './trace-notifier';
2
+ export * from './decorator/trace';
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./trace-notifier"), exports);
5
+ tslib_1.__exportStar(require("./decorator/trace"), exports);
@@ -0,0 +1,3 @@
1
+ import { MagekConfig, TraceInfo, TraceTypes } from '@magek/common';
2
+ export declare function notifyTrace(type: TraceTypes, actionType: string, parameters: TraceInfo, config: MagekConfig): Promise<void>;
3
+ export declare function isTraceEnabled(actionType: string, config: MagekConfig): boolean;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.notifyTrace = notifyTrace;
4
+ exports.isTraceEnabled = isTraceEnabled;
5
+ const common_1 = require("@magek/common");
6
+ async function notifyTrace(type, actionType, parameters, config) {
7
+ const handler = type === common_1.TraceTypes.START ? config.traceConfiguration.onStart : config.traceConfiguration.onEnd;
8
+ return handler.call(handler, config, actionType, parameters);
9
+ }
10
+ function isTraceEnabled(actionType, config) {
11
+ if (!config) {
12
+ return false;
13
+ }
14
+ const invocations = config.traceConfiguration;
15
+ if (!invocations) {
16
+ return false;
17
+ }
18
+ const enableNotificationsInvocations = invocations.enableTraceNotification;
19
+ if (!enableNotificationsInvocations) {
20
+ return false;
21
+ }
22
+ if (Array.isArray(enableNotificationsInvocations) && !enableNotificationsInvocations.includes(actionType)) {
23
+ return false;
24
+ }
25
+ return true;
26
+ }
@@ -0,0 +1,42 @@
1
+ import { MagekConfig, Class, EntityInterface, EventDeleteParameters, EventSearchParameters, EventSearchResponse, PaginatedEntitiesIdsResult, ReadModelInterface, Searcher, UUID } from '@magek/common';
2
+ /**
3
+ * Main class to interact with Magek and configure it.
4
+ * Sensible defaults are used whenever possible:
5
+ * - `appName`: `new-magek-app`
6
+ *
7
+ */
8
+ export declare class Magek {
9
+ static readonly configuredEnvironments: Set<string>;
10
+ static readonly config: MagekConfig;
11
+ static configureCurrentEnv(configurator: (config: MagekConfig) => void): void;
12
+ /**
13
+ * Allows to configure the Magek project.
14
+ *
15
+ * @param environment The name of the environment you want to configure
16
+ * @param configurator A function that receives the configuration object to set the values
17
+ */
18
+ static configure(environment: string, configurator: (config: MagekConfig) => void): void;
19
+ /**
20
+ * Initializes the Magek project
21
+ */
22
+ static start(codeRootPath: string): void;
23
+ private static runInjectableCommands;
24
+ /**
25
+ * This function returns a "Searcher" configured to search instances of the read model class passed as param.
26
+ * For more information, check the Searcher class.
27
+ * @param readModelClass The class of the read model you what to run searches for
28
+ */
29
+ static readModel<TReadModel extends ReadModelInterface>(readModelClass: Class<TReadModel>): Searcher<TReadModel>;
30
+ static events(request: EventSearchParameters): Promise<Array<EventSearchResponse>>;
31
+ static entitiesIDs(entityTypeName: string, limit: number, afterCursor?: Record<string, string>): Promise<PaginatedEntitiesIdsResult>;
32
+ static deleteEvent(parameters: EventDeleteParameters): Promise<boolean>;
33
+ /**
34
+ * Fetches the last known version of an entity
35
+ * @param entityClass Name of the entity class
36
+ * @param entityID
37
+ */
38
+ static entity<TEntity extends EntityInterface>(entityClass: Class<TEntity>, entityID: UUID): Promise<TEntity | undefined>;
39
+ private static configureMagekConcepts;
40
+ private static configureDataMigrations;
41
+ private static configureTouchEntities;
42
+ }