@camunda8/sdk 8.4.0 → 8.5.0-alpha.4

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 (215) hide show
  1. package/.eslintrc.json +31 -0
  2. package/CHANGELOG.md +32 -21
  3. package/CODE_OF_CONDUCT.md +73 -0
  4. package/CONTRIBUTING.md +116 -0
  5. package/LICENSE +3 -3
  6. package/README.md +228 -34
  7. package/dist/admin/index.d.ts +2 -0
  8. package/dist/admin/index.js +30 -0
  9. package/dist/admin/index.js.map +1 -0
  10. package/dist/admin/lib/AdminApiClient.d.ts +121 -0
  11. package/dist/admin/lib/AdminApiClient.js +254 -0
  12. package/dist/admin/lib/AdminApiClient.js.map +1 -0
  13. package/dist/admin/lib/AdminDto.d.ts +98 -0
  14. package/dist/admin/lib/AdminDto.js +3 -0
  15. package/dist/admin/lib/AdminDto.js.map +1 -0
  16. package/dist/c8/index.d.ts +42 -0
  17. package/dist/c8/index.js +92 -0
  18. package/dist/c8/index.js.map +1 -0
  19. package/dist/index.d.ts +15 -14
  20. package/dist/index.js +14 -16
  21. package/dist/index.js.map +1 -1
  22. package/dist/lib/CertificateAuthority.d.ts +2 -0
  23. package/dist/lib/CertificateAuthority.js +15 -0
  24. package/dist/lib/CertificateAuthority.js.map +1 -0
  25. package/dist/lib/ClientConstructor.d.ts +6 -0
  26. package/dist/lib/ClientConstructor.js +3 -0
  27. package/dist/lib/ClientConstructor.js.map +1 -0
  28. package/dist/lib/Configuration.d.ts +113 -0
  29. package/dist/lib/Configuration.js +367 -0
  30. package/dist/lib/Configuration.js.map +1 -0
  31. package/dist/lib/ConstructOAuthProvider.d.ts +3 -0
  32. package/dist/lib/ConstructOAuthProvider.js +14 -0
  33. package/dist/lib/ConstructOAuthProvider.js.map +1 -0
  34. package/dist/lib/CreateUserAgentString.d.ts +2 -0
  35. package/dist/lib/CreateUserAgentString.js +11 -0
  36. package/dist/lib/CreateUserAgentString.js.map +1 -0
  37. package/dist/lib/Delay.d.ts +1 -0
  38. package/dist/lib/Delay.js +6 -0
  39. package/dist/lib/Delay.js.map +1 -0
  40. package/dist/lib/EnvironmentSetup.d.ts +11 -0
  41. package/dist/lib/EnvironmentSetup.js +35 -0
  42. package/dist/lib/EnvironmentSetup.js.map +1 -0
  43. package/dist/lib/GetPackageVersion.d.ts +1 -0
  44. package/dist/lib/GetPackageVersion.js +32 -0
  45. package/dist/lib/GetPackageVersion.js.map +1 -0
  46. package/dist/lib/LosslessJsonParser.d.ts +103 -0
  47. package/dist/lib/LosslessJsonParser.js +252 -0
  48. package/dist/lib/LosslessJsonParser.js.map +1 -0
  49. package/dist/lib/RequireConfiguration.d.ts +2 -0
  50. package/dist/lib/RequireConfiguration.js +11 -0
  51. package/dist/lib/RequireConfiguration.js.map +1 -0
  52. package/dist/lib/SuppressZeebeLogging.d.ts +2 -0
  53. package/dist/lib/SuppressZeebeLogging.js +14 -0
  54. package/dist/lib/SuppressZeebeLogging.js.map +1 -0
  55. package/dist/lib/ValueOrDefault.d.ts +1 -0
  56. package/dist/lib/ValueOrDefault.js +8 -0
  57. package/dist/lib/ValueOrDefault.js.map +1 -0
  58. package/dist/lib/index.d.ts +12 -0
  59. package/dist/lib/index.js +32 -0
  60. package/dist/lib/index.js.map +1 -0
  61. package/dist/modeler/index.d.ts +2 -0
  62. package/dist/modeler/index.js +30 -0
  63. package/dist/modeler/index.js.map +1 -0
  64. package/dist/modeler/lib/ModelerAPIClient.d.ts +210 -0
  65. package/dist/modeler/lib/ModelerAPIClient.js +417 -0
  66. package/dist/modeler/lib/ModelerAPIClient.js.map +1 -0
  67. package/dist/modeler/lib/ModelerDto.d.ts +187 -0
  68. package/dist/modeler/lib/ModelerDto.js +3 -0
  69. package/dist/modeler/lib/ModelerDto.js.map +1 -0
  70. package/dist/oauth/index.d.ts +15 -0
  71. package/dist/oauth/index.js +8 -0
  72. package/dist/oauth/index.js.map +1 -0
  73. package/dist/oauth/lib/IOAuthProvider.d.ts +4 -0
  74. package/dist/oauth/lib/IOAuthProvider.js +3 -0
  75. package/dist/oauth/lib/IOAuthProvider.js.map +1 -0
  76. package/dist/oauth/lib/NullAuthProvider.d.ts +5 -0
  77. package/dist/oauth/lib/NullAuthProvider.js +16 -0
  78. package/dist/oauth/lib/NullAuthProvider.js.map +1 -0
  79. package/dist/oauth/lib/OAuthProvider.d.ts +44 -0
  80. package/dist/oauth/lib/OAuthProvider.js +316 -0
  81. package/dist/oauth/lib/OAuthProvider.js.map +1 -0
  82. package/dist/operate/index.d.ts +2 -0
  83. package/dist/operate/index.js +30 -0
  84. package/dist/operate/index.js.map +1 -0
  85. package/dist/operate/lib/OperateApiClient.d.ts +204 -0
  86. package/dist/operate/lib/OperateApiClient.js +440 -0
  87. package/dist/operate/lib/OperateApiClient.js.map +1 -0
  88. package/dist/operate/lib/OperateDto.d.ts +126 -0
  89. package/dist/operate/lib/OperateDto.js +125 -0
  90. package/dist/operate/lib/OperateDto.js.map +1 -0
  91. package/dist/operate/lib/TestableOperateApiClient.d.ts +7 -0
  92. package/dist/operate/lib/TestableOperateApiClient.js +15 -0
  93. package/dist/operate/lib/TestableOperateApiClient.js.map +1 -0
  94. package/dist/operate/lib/parseSearchResults.d.ts +4 -0
  95. package/dist/operate/lib/parseSearchResults.js +26 -0
  96. package/dist/operate/lib/parseSearchResults.js.map +1 -0
  97. package/dist/optimize/index.d.ts +2 -0
  98. package/dist/optimize/index.js +30 -0
  99. package/dist/optimize/index.js.map +1 -0
  100. package/dist/optimize/lib/APIObjects.d.ts +191 -0
  101. package/dist/optimize/lib/APIObjects.js +3 -0
  102. package/dist/optimize/lib/APIObjects.js.map +1 -0
  103. package/dist/optimize/lib/OptimizeApiClient.d.ts +269 -0
  104. package/dist/optimize/lib/OptimizeApiClient.js +410 -0
  105. package/dist/optimize/lib/OptimizeApiClient.js.map +1 -0
  106. package/dist/optimize/lib/ReportResults.d.ts +23 -0
  107. package/dist/optimize/lib/ReportResults.js +28 -0
  108. package/dist/optimize/lib/ReportResults.js.map +1 -0
  109. package/dist/proto/zeebe.proto +996 -0
  110. package/dist/tasklist/index.d.ts +2 -0
  111. package/dist/tasklist/index.js +30 -0
  112. package/dist/tasklist/index.js.map +1 -0
  113. package/dist/tasklist/lib/TasklistApiClient.d.ts +104 -0
  114. package/dist/tasklist/lib/TasklistApiClient.js +233 -0
  115. package/dist/tasklist/lib/TasklistApiClient.js.map +1 -0
  116. package/dist/tasklist/lib/TasklistDto.d.ts +147 -0
  117. package/dist/tasklist/lib/TasklistDto.js +26 -0
  118. package/dist/tasklist/lib/TasklistDto.js.map +1 -0
  119. package/dist/tasklist/lib/utils.d.ts +15 -0
  120. package/dist/tasklist/lib/utils.js +25 -0
  121. package/dist/tasklist/lib/utils.js.map +1 -0
  122. package/dist/zeebe/index.d.ts +21 -0
  123. package/dist/zeebe/index.js +53 -0
  124. package/dist/zeebe/index.js.map +1 -0
  125. package/dist/zeebe/lib/BpmnParser.d.ts +38 -0
  126. package/dist/zeebe/lib/BpmnParser.js +274 -0
  127. package/dist/zeebe/lib/BpmnParser.js.map +1 -0
  128. package/dist/zeebe/lib/ConnectionFactory.d.ts +25 -0
  129. package/dist/zeebe/lib/ConnectionFactory.js +43 -0
  130. package/dist/zeebe/lib/ConnectionFactory.js.map +1 -0
  131. package/dist/zeebe/lib/ConnectionStatusEvent.d.ts +6 -0
  132. package/dist/zeebe/lib/ConnectionStatusEvent.js +10 -0
  133. package/dist/zeebe/lib/ConnectionStatusEvent.js.map +1 -0
  134. package/dist/zeebe/lib/GetPackageVersion.d.ts +1 -0
  135. package/dist/zeebe/lib/GetPackageVersion.js +32 -0
  136. package/dist/zeebe/lib/GetPackageVersion.js.map +1 -0
  137. package/dist/zeebe/lib/GrpcClient.d.ts +75 -0
  138. package/dist/zeebe/lib/GrpcClient.js +467 -0
  139. package/dist/zeebe/lib/GrpcClient.js.map +1 -0
  140. package/dist/zeebe/lib/GrpcError.d.ts +19 -0
  141. package/dist/zeebe/lib/GrpcError.js +23 -0
  142. package/dist/zeebe/lib/GrpcError.js.map +1 -0
  143. package/dist/zeebe/lib/GrpcMiddleware.d.ts +21 -0
  144. package/dist/zeebe/lib/GrpcMiddleware.js +78 -0
  145. package/dist/zeebe/lib/GrpcMiddleware.js.map +1 -0
  146. package/dist/zeebe/lib/MockStdOut.d.ts +7 -0
  147. package/dist/zeebe/lib/MockStdOut.js +19 -0
  148. package/dist/zeebe/lib/MockStdOut.js.map +1 -0
  149. package/dist/zeebe/lib/Queue.d.ts +8 -0
  150. package/dist/zeebe/lib/Queue.js +15 -0
  151. package/dist/zeebe/lib/Queue.js.map +1 -0
  152. package/dist/zeebe/lib/SimpleLogger.d.ts +8 -0
  153. package/dist/zeebe/lib/SimpleLogger.js +47 -0
  154. package/dist/zeebe/lib/SimpleLogger.js.map +1 -0
  155. package/dist/zeebe/lib/StatefulLogInterceptor.d.ts +29 -0
  156. package/dist/zeebe/lib/StatefulLogInterceptor.js +81 -0
  157. package/dist/zeebe/lib/StatefulLogInterceptor.js.map +1 -0
  158. package/dist/zeebe/lib/TypedEmitter.d.ts +16 -0
  159. package/dist/zeebe/lib/TypedEmitter.js +24 -0
  160. package/dist/zeebe/lib/TypedEmitter.js.map +1 -0
  161. package/dist/zeebe/lib/ZBJsonLogger.d.ts +5 -0
  162. package/dist/zeebe/lib/ZBJsonLogger.js +12 -0
  163. package/dist/zeebe/lib/ZBJsonLogger.js.map +1 -0
  164. package/dist/zeebe/lib/ZBLogger.d.ts +20 -0
  165. package/dist/zeebe/lib/ZBLogger.js +134 -0
  166. package/dist/zeebe/lib/ZBLogger.js.map +1 -0
  167. package/dist/zeebe/lib/ZBWorkerBase.d.ts +78 -0
  168. package/dist/zeebe/lib/ZBWorkerBase.js +417 -0
  169. package/dist/zeebe/lib/ZBWorkerBase.js.map +1 -0
  170. package/dist/zeebe/lib/cancelProcesses.d.ts +1 -0
  171. package/dist/zeebe/lib/cancelProcesses.js +40 -0
  172. package/dist/zeebe/lib/cancelProcesses.js.map +1 -0
  173. package/dist/zeebe/lib/createUniqueTaskType.d.ts +0 -0
  174. package/dist/zeebe/lib/createUniqueTaskType.js +65 -0
  175. package/dist/zeebe/lib/createUniqueTaskType.js.map +1 -0
  176. package/dist/zeebe/lib/index.d.ts +2 -0
  177. package/dist/zeebe/lib/index.js +19 -0
  178. package/dist/zeebe/lib/index.js.map +1 -0
  179. package/dist/zeebe/lib/interfaces-1.0.d.ts +303 -0
  180. package/dist/zeebe/lib/interfaces-1.0.js +5 -0
  181. package/dist/zeebe/lib/interfaces-1.0.js.map +1 -0
  182. package/dist/zeebe/lib/interfaces-grpc-1.0.d.ts +679 -0
  183. package/dist/zeebe/lib/interfaces-grpc-1.0.js +22 -0
  184. package/dist/zeebe/lib/interfaces-grpc-1.0.js.map +1 -0
  185. package/dist/zeebe/lib/interfaces-published-contract.d.ts +67 -0
  186. package/dist/zeebe/lib/interfaces-published-contract.js +3 -0
  187. package/dist/zeebe/lib/interfaces-published-contract.js.map +1 -0
  188. package/dist/zeebe/lib/stringifyVariables.d.ts +18 -0
  189. package/dist/zeebe/lib/stringifyVariables.js +28 -0
  190. package/dist/zeebe/lib/stringifyVariables.js.map +1 -0
  191. package/dist/zeebe/lib/utils.d.ts +7 -0
  192. package/dist/zeebe/lib/utils.js +48 -0
  193. package/dist/zeebe/lib/utils.js.map +1 -0
  194. package/dist/zeebe/types.d.ts +3 -0
  195. package/dist/zeebe/types.js +20 -0
  196. package/dist/zeebe/types.js.map +1 -0
  197. package/dist/zeebe/zb/ZBWorker.d.ts +7 -0
  198. package/dist/zeebe/zb/ZBWorker.js +73 -0
  199. package/dist/zeebe/zb/ZBWorker.js.map +1 -0
  200. package/dist/zeebe/zb/ZeebeGrpcClient.d.ts +587 -0
  201. package/dist/zeebe/zb/ZeebeGrpcClient.js +1021 -0
  202. package/dist/zeebe/zb/ZeebeGrpcClient.js.map +1 -0
  203. package/package.json +130 -30
  204. package/renovate.json +9 -0
  205. package/.github/workflows/build-docs.yml +0 -39
  206. package/.github/workflows/tag-and-publish.yml +0 -48
  207. package/.prettierignore +0 -2
  208. package/img/video.png +0 -0
  209. package/jest.config.js +0 -5
  210. package/src/__tests__/exports.spec.ts +0 -7
  211. package/src/index.ts +0 -17
  212. package/tsconfig.build.json +0 -8
  213. package/tsconfig.json +0 -10
  214. package/tsconfig.tsbuildinfo +0 -1
  215. package/typedoc.json +0 -10
@@ -0,0 +1,1021 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.ZeebeGrpcClient = void 0;
30
+ const fs_1 = require("fs");
31
+ const path = __importStar(require("path"));
32
+ const chalk_1 = __importDefault(require("chalk"));
33
+ const debug_1 = __importDefault(require("debug"));
34
+ const lib_1 = require("lib");
35
+ const promise_retry_1 = __importDefault(require("promise-retry"));
36
+ const typed_duration_1 = require("typed-duration");
37
+ const uuid_1 = require("uuid");
38
+ const lib_2 = require("../lib");
39
+ const ConnectionFactory_1 = require("../lib/ConnectionFactory");
40
+ const ConnectionStatusEvent_1 = require("../lib/ConnectionStatusEvent");
41
+ const GrpcError_1 = require("../lib/GrpcError");
42
+ const SimpleLogger_1 = require("../lib/SimpleLogger");
43
+ const TypedEmitter_1 = require("../lib/TypedEmitter");
44
+ const ZBJsonLogger_1 = require("../lib/ZBJsonLogger");
45
+ const utils_1 = require("../lib/utils");
46
+ const ZBWorker_1 = require("./ZBWorker");
47
+ const debug = (0, debug_1.default)('camunda:zeebeclient');
48
+ const idColors = [
49
+ chalk_1.default.yellow,
50
+ chalk_1.default.green,
51
+ chalk_1.default.cyan,
52
+ chalk_1.default.magenta,
53
+ chalk_1.default.blue,
54
+ ];
55
+ /**
56
+ * @description A client for interacting with a Zeebe broker. With the connection credentials set in the environment, you can use a "zero-conf" constructor with no arguments.
57
+ * @example
58
+ * ```
59
+ * const zbc = new ZeebeGrpcClient()
60
+ * zbc.topology().then(info =>
61
+ * console.log(JSON.stringify(info, null, 2))
62
+ * )
63
+ * ```
64
+ */
65
+ class ZeebeGrpcClient extends TypedEmitter_1.TypedEmitter {
66
+ constructor(options) {
67
+ super();
68
+ this.connected = undefined;
69
+ this.readied = false;
70
+ this.closing = false;
71
+ this.workerCount = 0;
72
+ this.workers = [];
73
+ const config = lib_1.CamundaEnvironmentConfigurator.mergeConfigWithEnvironment(options?.config ?? {});
74
+ this.config = config;
75
+ this.options = {};
76
+ this.options.longPoll = typed_duration_1.Duration.seconds.of(config.zeebeGrpcSettings.ZEEBE_GRPC_WORKER_LONGPOLL_SECONDS);
77
+ this.options.pollInterval = typed_duration_1.Duration.milliseconds.of(config.zeebeGrpcSettings.ZEEBE_GRPC_WORKER_POLL_INTERVAL_MS);
78
+ this.retry = config.zeebeGrpcSettings.ZEEBE_GRPC_CLIENT_RETRY;
79
+ this.options.retry = this.retry;
80
+ this.loglevel = config.zeebeGrpcSettings.ZEEBE_CLIENT_LOG_LEVEL;
81
+ this.options.loglevel = this.loglevel;
82
+ const logTypeFromEnvironment = () => ({
83
+ JSON: ZBJsonLogger_1.ZBJsonLogger,
84
+ SIMPLE: SimpleLogger_1.ZBSimpleLogger,
85
+ })[config.zeebeGrpcSettings.ZEEBE_CLIENT_LOG_TYPE ?? 'NONE'];
86
+ this.stdout = logTypeFromEnvironment() ?? SimpleLogger_1.ZBSimpleLogger;
87
+ this.options.tenantId = config.CAMUNDA_TENANT_ID;
88
+ this.tenantId = this.options.tenantId;
89
+ this.gatewayAddress = (0, lib_1.RequireConfiguration)(config.ZEEBE_ADDRESS, 'ZEEBE_ADDRESS');
90
+ this.useTLS = config.CAMUNDA_SECURE_CONNECTION;
91
+ const certChainPath = config.CAMUNDA_CUSTOM_CERT_CHAIN_PATH;
92
+ const rootCertsPath = config.CAMUNDA_CUSTOM_ROOT_CERT_PATH;
93
+ const privateKeyPath = config.CAMUNDA_CUSTOM_PRIVATE_KEY_PATH;
94
+ const customSSL = {
95
+ certChain: certChainPath ? (0, fs_1.readFileSync)(certChainPath) : undefined,
96
+ privateKey: privateKeyPath ? (0, fs_1.readFileSync)(privateKeyPath) : undefined,
97
+ rootCerts: rootCertsPath ? (0, fs_1.readFileSync)(rootCertsPath) : undefined,
98
+ };
99
+ this.customSSL = customSSL;
100
+ this.options.customSSL = customSSL;
101
+ this.connectionTolerance = typed_duration_1.Duration.milliseconds.of(config.zeebeGrpcSettings.ZEEBE_GRPC_CLIENT_CONNECTION_TOLERANCE_MS);
102
+ this.onConnectionError = this.options.onConnectionError;
103
+ this.onReady = this.options.onReady;
104
+ this.oAuthProvider =
105
+ options?.oAuthProvider ?? (0, lib_1.constructOAuthProvider)(config);
106
+ const { grpcClient, log } = this.constructGrpcClient({
107
+ grpcConfig: {
108
+ namespace: this.options.logNamespace || 'ZBClient',
109
+ },
110
+ logConfig: {
111
+ _tag: 'ZBCLIENT',
112
+ loglevel: this.loglevel,
113
+ longPoll: typed_duration_1.Duration.milliseconds.from(this.options.longPoll),
114
+ namespace: this.options.logNamespace || 'ZBClient',
115
+ pollInterval: typed_duration_1.Duration.milliseconds.from(this.options.pollInterval),
116
+ stdout: this.stdout,
117
+ },
118
+ });
119
+ grpcClient.on(ConnectionStatusEvent_1.ConnectionStatusEvent.connectionError, (err) => {
120
+ if (this.connected !== false) {
121
+ this.onConnectionError?.(err);
122
+ this.emit(ConnectionStatusEvent_1.ConnectionStatusEvent.connectionError);
123
+ }
124
+ this.connected = false;
125
+ this.readied = false;
126
+ });
127
+ grpcClient.on(ConnectionStatusEvent_1.ConnectionStatusEvent.ready, () => {
128
+ if (!this.readied) {
129
+ this.onReady?.();
130
+ this.emit(ConnectionStatusEvent_1.ConnectionStatusEvent.ready);
131
+ }
132
+ this.connected = true;
133
+ this.readied = true;
134
+ });
135
+ this.grpc = grpcClient;
136
+ this.logger = log;
137
+ this.maxRetries = config.zeebeGrpcSettings.ZEEBE_GRPC_CLIENT_MAX_RETRIES;
138
+ this.maxRetryTimeout = typed_duration_1.Duration.seconds.of(config.zeebeGrpcSettings.ZEEBE_GRPC_CLIENT_MAX_RETRY_TIMEOUT_SECONDS);
139
+ // Send command to broker to eagerly fail / prove connection.
140
+ // This is useful for, for example: the Node-Red client, which wants to
141
+ // display the connection status.
142
+ const eagerConnection = config.zeebeGrpcSettings.ZEEBE_GRPC_CLIENT_EAGER_CONNECT;
143
+ if (eagerConnection ?? false) {
144
+ this.topology()
145
+ .then((res) => {
146
+ this.logger.logDirect(chalk_1.default.blueBright('Zeebe cluster topology:'));
147
+ this.logger.logDirect(res.brokers);
148
+ })
149
+ .catch((e) => {
150
+ // Swallow exception to avoid throwing if retries are off
151
+ if (e.thisWillNeverHappenYo) {
152
+ this.emit(ConnectionStatusEvent_1.ConnectionStatusEvent.unknown);
153
+ }
154
+ });
155
+ }
156
+ }
157
+ /**
158
+ * @description activateJobs allows you to manually activate jobs, effectively building a worker; rather than using the ZBWorker class.
159
+ * @example
160
+ * ```
161
+ * const zbc = new ZeebeGrpcClient()
162
+ * zbc.activateJobs({
163
+ * maxJobsToActivate: 5,
164
+ * requestTimeout: 6000,
165
+ * timeout: 5 * 60 * 1000,
166
+ * type: 'process-payment',
167
+ * worker: 'my-worker-uuid'
168
+ * }).then(jobs =>
169
+ * jobs.forEach(job =>
170
+ * // business logic
171
+ * zbc.completeJob({
172
+ * jobKey: job.key,
173
+ * variables: {}
174
+ * ))
175
+ * )
176
+ * })
177
+ * ```
178
+ */
179
+ activateJobs(request) {
180
+ const { inputVariableDto, customHeadersDto, ...req } = request;
181
+ const inputVariableDtoToUse = inputVariableDto ??
182
+ lib_1.LosslessDto;
183
+ const customHeadersDtoToUse = customHeadersDto ??
184
+ lib_1.LosslessDto;
185
+ // eslint-disable-next-line no-async-promise-executor
186
+ return new Promise(async (resolve, reject) => {
187
+ try {
188
+ const stream = await this.grpc.activateJobsStream(req);
189
+ stream.on('data', (res) => {
190
+ const jobs = res.jobs.map((job) => (0, lib_2.parseVariablesAndCustomHeadersToJSON)(job, inputVariableDtoToUse, customHeadersDtoToUse));
191
+ resolve(jobs);
192
+ });
193
+ }
194
+ catch (e) {
195
+ reject(e);
196
+ }
197
+ });
198
+ }
199
+ /**
200
+ *
201
+ * @description Broadcast a Signal
202
+ * @example
203
+ * ```
204
+ * const zbc = new ZeebeGrpcClient()
205
+ *
206
+ * zbc.broadcastSignal({
207
+ * signalName: 'my-signal',
208
+ * variables: { reasonCode: 3 }
209
+ * })
210
+ */
211
+ async broadcastSignal(req) {
212
+ const request = {
213
+ signalName: req.signalName,
214
+ variables: JSON.stringify(req.variables ?? {}),
215
+ tenantId: req.tenantId ?? this.tenantId,
216
+ };
217
+ return this.executeOperation('broadcastSignal', () => this.grpc.broadcastSignalSync(request));
218
+ }
219
+ /**
220
+ *
221
+ * @description Cancel a process instance by process instance key.
222
+ * @example
223
+ * ```
224
+ * const zbc = new ZeebeGrpcClient()
225
+ *
226
+ * zbc.cancelProcessInstance(processInstanceId)
227
+ * .catch(
228
+ * (e: any) => console.log(`Error cancelling instance: ${e.message}`)
229
+ * )
230
+ * ```
231
+ */
232
+ async cancelProcessInstance(processInstanceKey) {
233
+ utils_1.Utils.validateNumber(processInstanceKey, 'processInstanceKey');
234
+ return this.executeOperation('cancelProcessInstance', () => this.grpc.cancelProcessInstanceSync({
235
+ processInstanceKey,
236
+ }));
237
+ }
238
+ /**
239
+ *
240
+ * @description Create a worker that polls the gateway for jobs and executes a job handler when units of work are available.
241
+ * @example
242
+ * ```
243
+ * const zbc = new ZB.ZeebeGrpcClient()
244
+ *
245
+ * const zbWorker = zbc.createWorker({
246
+ * taskType: 'demo-service',
247
+ * taskHandler: myTaskHandler,
248
+ * })
249
+ *
250
+ * // A job handler must return one of job.complete, job.fail, job.error, or job.forward
251
+ * // Note: unhandled exceptions in the job handler cause the library to call job.fail
252
+ * async function myTaskHandler(job) {
253
+ * zbWorker.log('Task variables', job.variables)
254
+ *
255
+ * // Task worker business logic goes here
256
+ * const updateToBrokerVariables = {
257
+ * updatedProperty: 'newValue',
258
+ * }
259
+ *
260
+ * const res = await callExternalSystem(job.variables)
261
+ *
262
+ * if (res.code === 'SUCCESS') {
263
+ * return job.complete({
264
+ * ...updateToBrokerVariables,
265
+ * ...res.values
266
+ * })
267
+ * }
268
+ * if (res.code === 'BUSINESS_ERROR') {
269
+ * return job.error({
270
+ * code: res.errorCode,
271
+ * message: res.message
272
+ * })
273
+ * }
274
+ * if (res.code === 'ERROR') {
275
+ * return job.fail({
276
+ * errorMessage: res.message,
277
+ * retryBackOff: 2000
278
+ * })
279
+ * }
280
+ * }
281
+ * ```
282
+ */
283
+ createWorker(config) {
284
+ debug(`Creating worker for task type ${config.taskType}`);
285
+ if (this.closing) {
286
+ throw new Error('Client is closing. No worker creation allowed!');
287
+ }
288
+ const idColor = idColors[this.workerCount++ % idColors.length];
289
+ // Merge parent client options with worker override
290
+ const options = {
291
+ ...this.options,
292
+ onConnectionError: undefined, // Do not inherit client handler
293
+ onReady: undefined, // Do not inherit client handler
294
+ ...config,
295
+ };
296
+ // Give worker its own gRPC connection
297
+ const { grpcClient: workerGRPCClient, log } = this.constructGrpcClient({
298
+ grpcConfig: {
299
+ namespace: 'ZBWorker',
300
+ tasktype: config.taskType,
301
+ },
302
+ logConfig: {
303
+ _tag: 'ZBWORKER',
304
+ colorise: true,
305
+ id: config.id,
306
+ loglevel: options.loglevel,
307
+ namespace: ['ZBWorker', options.logNamespace].join(' ').trim(),
308
+ pollInterval: options.longPoll,
309
+ stdout: options.stdout,
310
+ taskType: config.taskType,
311
+ },
312
+ });
313
+ const worker = new ZBWorker_1.ZBWorker({
314
+ grpcClient: workerGRPCClient,
315
+ id: config.id || null,
316
+ idColor,
317
+ log,
318
+ options: { ...this.options, ...options },
319
+ taskHandler: config.taskHandler,
320
+ taskType: config.taskType,
321
+ zbClient: this,
322
+ });
323
+ this.workers.push(worker);
324
+ return worker;
325
+ }
326
+ /**
327
+ * @description Gracefully shut down all workers, draining existing tasks, and return when it is safe to exit.
328
+ *
329
+ * @example
330
+ * ```
331
+ * const zbc = new ZeebeGrpcClient()
332
+ *
333
+ * zbc.createWorker({
334
+ * taskType:
335
+ * })
336
+ *
337
+ * setTimeout(async () => {
338
+ * await zbc.close()
339
+ * console.log('All work completed.')
340
+ * }),
341
+ * 5 * 60 * 1000 // 5 mins
342
+ * )
343
+ * ```
344
+ */
345
+ async close(timeout) {
346
+ this.closePromise =
347
+ this.closePromise ||
348
+ new Promise((resolve) => {
349
+ // Prevent the creation of more workers
350
+ this.closing = true;
351
+ Promise.all(this.workers.map((w) => w.close(timeout)))
352
+ .then(() => this.grpc.close(timeout))
353
+ .then(() => {
354
+ this.emit(ConnectionStatusEvent_1.ConnectionStatusEvent.close);
355
+ this.grpc.removeAllListeners();
356
+ this.removeAllListeners();
357
+ resolve(null);
358
+ });
359
+ });
360
+ return this.closePromise;
361
+ }
362
+ /**
363
+ *
364
+ * @description Explicitly complete a job. The method is useful for manually constructing a worker.
365
+ * @example
366
+ * ```
367
+ * const zbc = new ZeebeGrpcClient()
368
+ * zbc.activateJobs({
369
+ * maxJobsToActivate: 5,
370
+ * requestTimeout: 6000,
371
+ * timeout: 5 * 60 * 1000,
372
+ * type: 'process-payment',
373
+ * worker: 'my-worker-uuid'
374
+ * }).then(jobs =>
375
+ * jobs.forEach(job =>
376
+ * // business logic
377
+ * zbc.completeJob({
378
+ * jobKey: job.key,
379
+ * variables: {}
380
+ * ))
381
+ * )
382
+ * })
383
+ * ```
384
+ */
385
+ completeJob(completeJobRequest) {
386
+ const withStringifiedVariables = (0, lib_2.stringifyVariables)(completeJobRequest);
387
+ this.logger.logDebug(withStringifiedVariables);
388
+ return this.executeOperation('completeJob', () => this.grpc.completeJobSync(withStringifiedVariables).catch((e) => {
389
+ if (e.code === GrpcError_1.GrpcError.NOT_FOUND) {
390
+ e.details +=
391
+ '. The process may have been cancelled, the job cancelled by an interrupting event, or the job already completed.' +
392
+ ' For more detail, see: https://forum.zeebe.io/t/command-rejected-with-code-complete/908/17';
393
+ }
394
+ throw e;
395
+ }));
396
+ }
397
+ // tslint:disable: no-object-literal-type-assertion
398
+ /**
399
+ *
400
+ * @description Create a new process instance. Asynchronously returns a process instance id.
401
+ * @example
402
+ * ```
403
+ * const zbc = new ZeebeGrpcClient()
404
+ *
405
+ * zbc.createProcessInstance({
406
+ * bpmnProcessId: 'onboarding-process',
407
+ * variables: {
408
+ * customerId: 'uuid-3455'
409
+ * },
410
+ * version: 5 // optional, will use latest by default
411
+ * }).then(res => console.log(JSON.stringify(res, null, 2)))
412
+ *
413
+ * zbc.createProcessInstance({
414
+ * bpmnProcessId: 'SkipFirstTask',
415
+ * variables: { id: random },
416
+ * startInstructions: [{elementId: 'second_service_task'}]
417
+ * }).then(res => (id = res.processInstanceKey))
418
+ * ```
419
+ */
420
+ createProcessInstance(config) {
421
+ const request = {
422
+ bpmnProcessId: config.bpmnProcessId,
423
+ variables: config.variables,
424
+ version: config.version || -1,
425
+ startInstructions: config.startInstructions || [],
426
+ };
427
+ const createProcessInstanceRequest = (0, lib_2.stringifyVariables)({
428
+ ...request,
429
+ startInstructions: request.startInstructions,
430
+ tenantId: config.tenantId ?? this.tenantId,
431
+ });
432
+ return this.executeOperation('createProcessInstance', () => this.grpc.createProcessInstanceSync(createProcessInstanceRequest));
433
+ }
434
+ /**
435
+ *
436
+ * @description Create a process instance, and return a Promise that returns the outcome of the process.
437
+ * @example
438
+ * ```
439
+ * const zbc = new ZeebeGrpcClient()
440
+ *
441
+ * zbc.createProcessInstanceWithResult({
442
+ * bpmnProcessId: 'order-process',
443
+ * variables: {
444
+ * customerId: 123,
445
+ * invoiceId: 567
446
+ * }
447
+ * })
448
+ * .then(console.log)
449
+ * ```
450
+ */
451
+ createProcessInstanceWithResult(config) {
452
+ const request = {
453
+ bpmnProcessId: config.bpmnProcessId,
454
+ fetchVariables: config.fetchVariables,
455
+ requestTimeout: config.requestTimeout || 0,
456
+ variables: config.variables,
457
+ version: config.version || -1,
458
+ tenantId: config.tenantId ?? this.tenantId,
459
+ };
460
+ const createProcessInstanceRequest = (0, lib_2.stringifyVariables)({
461
+ bpmnProcessId: request.bpmnProcessId,
462
+ variables: request.variables,
463
+ version: request.version,
464
+ tenantId: request.tenantId ?? this.tenantId,
465
+ });
466
+ return this.executeOperation('createProcessInstanceWithResult', () => this.grpc.createProcessInstanceWithResultSync({
467
+ fetchVariables: request.fetchVariables,
468
+ request: createProcessInstanceRequest,
469
+ requestTimeout: request.requestTimeout,
470
+ })).then((res) => (0, lib_2.parseVariables)(res));
471
+ }
472
+ /**
473
+ * Delete a resource.
474
+ * @param resourceId - The key of the resource that should be deleted. This can either be the key of a process definition, the key of a decision requirements definition or the key of a form.
475
+ * @returns
476
+ */
477
+ deleteResource({ resourceKey, }) {
478
+ return this.executeOperation('deleteResourceSync', () => this.grpc.deleteResourceSync({ resourceKey }));
479
+ }
480
+ async deployResource(resource) {
481
+ const isProcess = (maybeProcess // eslint-disable-line @typescript-eslint/no-explicit-any
482
+ ) => !!maybeProcess.process;
483
+ const isProcessFilename = (maybeProcessFilename // eslint-disable-line @typescript-eslint/no-explicit-any
484
+ ) => !!maybeProcessFilename.processFilename;
485
+ const isDecision = (maybeDecision // eslint-disable-line @typescript-eslint/no-explicit-any
486
+ ) => !!maybeDecision.decision;
487
+ const isDecisionFilename = (maybeDecisionFilename // eslint-disable-line @typescript-eslint/no-explicit-any
488
+ ) => !!maybeDecisionFilename.decisionFilename;
489
+ // default fall-through
490
+ /* const isForm = ( maybeForm: any ): maybeForm is { form: Buffer; name: string } =>
491
+ !!maybeForm.form
492
+ */
493
+ const isFormFilename = (maybeFormFilename // eslint-disable-line @typescript-eslint/no-explicit-any
494
+ ) => !!maybeFormFilename.formFilename;
495
+ if (isProcessFilename(resource)) {
496
+ const filename = resource.processFilename;
497
+ const process = (0, fs_1.readFileSync)(filename);
498
+ return this.executeOperation('deployResource', () => this.grpc.deployResourceSync({
499
+ resources: [
500
+ {
501
+ name: filename,
502
+ content: process,
503
+ },
504
+ ],
505
+ tenantId: resource.tenantId ?? this.tenantId,
506
+ }));
507
+ }
508
+ else if (isProcess(resource)) {
509
+ return this.executeOperation('deployResource', () => this.grpc.deployResourceSync({
510
+ resources: [
511
+ {
512
+ name: resource.name,
513
+ content: resource.process,
514
+ },
515
+ ],
516
+ tenantId: resource.tenantId ?? this.tenantId,
517
+ }));
518
+ }
519
+ else if (isDecisionFilename(resource)) {
520
+ const filename = resource.decisionFilename;
521
+ const decision = (0, fs_1.readFileSync)(filename);
522
+ return this.executeOperation('deployResource', () => this.grpc.deployResourceSync({
523
+ resources: [
524
+ {
525
+ name: filename,
526
+ content: decision,
527
+ },
528
+ ],
529
+ tenantId: resource.tenantId ?? this.tenantId,
530
+ }));
531
+ }
532
+ else if (isDecision(resource)) {
533
+ return this.executeOperation('deployResource', () => this.grpc.deployResourceSync({
534
+ resources: [
535
+ {
536
+ name: resource.name,
537
+ content: resource.decision,
538
+ },
539
+ ],
540
+ tenantId: resource.tenantId ?? this.tenantId,
541
+ }));
542
+ }
543
+ else if (isFormFilename(resource)) {
544
+ const filename = resource.formFilename;
545
+ const form = (0, fs_1.readFileSync)(filename);
546
+ return this.executeOperation('deployResource', () => this.grpc.deployResourceSync({
547
+ resources: [
548
+ {
549
+ name: filename,
550
+ content: form,
551
+ },
552
+ ],
553
+ tenantId: resource.tenantId ?? this.tenantId,
554
+ }));
555
+ } /* if (isForm(resource)) */
556
+ else {
557
+ // default fall-through
558
+ return this.executeOperation('deployResource', () => this.grpc.deployResourceSync({
559
+ resources: [
560
+ {
561
+ name: resource.name,
562
+ content: resource.form,
563
+ },
564
+ ],
565
+ tenantId: resource.tenantId ?? this.tenantId,
566
+ }));
567
+ }
568
+ }
569
+ /**
570
+ *
571
+ * @description Evaluates a decision. The decision to evaluate can be specified either by using its unique key (as returned by DeployResource), or using the decision ID. When using the decision ID, the latest deployed version of the decision is used.
572
+ * @example
573
+ * ```
574
+ * const zbc = new ZeebeGrpcClient()
575
+ * zbc.evaluateDecision({
576
+ * decisionId: 'my-decision',
577
+ * variables: { season: "Fall" }
578
+ * }).then(res => console.log(JSON.stringify(res, null, 2)))
579
+ */
580
+ evaluateDecision(evaluateDecisionRequest) {
581
+ // the gRPC API call needs a JSON string, but we accept a JSON object, so we transform it here
582
+ const variables = (0, lib_1.losslessStringify)(evaluateDecisionRequest.variables);
583
+ return this.executeOperation('evaluateDecision', () => this.grpc.evaluateDecisionSync({
584
+ ...evaluateDecisionRequest,
585
+ variables,
586
+ tenantId: evaluateDecisionRequest.tenantId ?? this.tenantId,
587
+ }));
588
+ }
589
+ /**
590
+ *
591
+ * @description Fail a job. This is useful if you are using the decoupled completion pattern or building your own worker.
592
+ * For the retry count, the current count is available in the job metadata.
593
+ *
594
+ * @example
595
+ * ```
596
+ * const zbc = new ZeebeGrpcClient()
597
+ * zbc.failJob( {
598
+ * jobKey: '345424343451',
599
+ * retries: 3,
600
+ * errorMessage: 'Could not get a response from the order invoicing API',
601
+ * retryBackOff: 30 * 1000 // optional, otherwise available for reactivation immediately
602
+ * })
603
+ * ```
604
+ */
605
+ failJob(failJobRequest) {
606
+ return this.executeOperation('failJob', () => this.grpc.failJobSync(failJobRequest));
607
+ }
608
+ /**
609
+ * @description Return an array of task types contained in a BPMN file or array of BPMN files. This can be useful, for example, to do
610
+ * @example
611
+ * ```
612
+ * const zbc = new ZeebeGrpcClient()
613
+ * zbc.getServiceTypesFromBpmn(['bpmn/onboarding.bpmn', 'bpmn/process-sale.bpmn'])
614
+ * .then(tasktypes => console.log('The task types are:', tasktypes))
615
+ *
616
+ * ```
617
+ */
618
+ getServiceTypesFromBpmn(files) {
619
+ const fileArray = typeof files === 'string' ? [files] : files;
620
+ return lib_2.BpmnParser.getTaskTypes(lib_2.BpmnParser.parseBpmn(fileArray));
621
+ }
622
+ /**
623
+ *
624
+ * @description Modify a running process instance. This allows you to move the execution tokens, and change the variables. Added in 8.1.
625
+ * See the [gRPC protocol documentation](https://docs.camunda.io/docs/apis-clients/grpc/#modifyprocessinstance-rpc).
626
+ * @example
627
+ * ```
628
+ * zbc.createProcessInstance('SkipFirstTask', {}).then(res =>
629
+ * zbc.modifyProcessInstance({
630
+ * processInstanceKey: res.processInstanceKey,
631
+ * activateInstructions: [{
632
+ * elementId: 'second_service_task',
633
+ * ancestorElementInstanceKey: "-1",
634
+ * variableInstructions: [{
635
+ * scopeId: '',
636
+ * variables: { second: 1}
637
+ * }]
638
+ * }]
639
+ * })
640
+ * )
641
+ * ```
642
+ */
643
+ modifyProcessInstance(modifyProcessInstanceRequest) {
644
+ return this.executeOperation('modifyProcessInstance', () => {
645
+ // We accept JSONDoc for the variableInstructions, but the actual gRPC call needs stringified JSON, so transform it with a mutation
646
+ const req = utils_1.Utils.deepClone(modifyProcessInstanceRequest);
647
+ req?.activateInstructions?.forEach((a) => a.variableInstructions.forEach((v) => (v.variables = (0, lib_1.losslessStringify)(v.variables))));
648
+ return this.grpc.modifyProcessInstanceSync({
649
+ ...req,
650
+ });
651
+ });
652
+ }
653
+ /**
654
+ *
655
+ * @since 8.5.0
656
+ */
657
+ migrateProcessInstance(migrateProcessInstanceRequest) {
658
+ return this.executeOperation('migrateProcessInstance', () => this.grpc.migrateProcessInstanceSync(migrateProcessInstanceRequest));
659
+ }
660
+ /**
661
+ * @description Publish a message to the broker for correlation with a workflow instance. See [this tutorial](https://docs.camunda.io/docs/guides/message-correlation/) for a detailed description of message correlation.
662
+ * @example
663
+ * ```
664
+ * const zbc = new ZeebeGrpcClient()
665
+ *
666
+ * zbc.publishMessage({
667
+ * // Should match the "Message Name" in a BPMN Message Catch
668
+ * name: 'order_status',
669
+ * correlationKey: 'uuid-124-532-5432',
670
+ * variables: {
671
+ * event: 'PROCESSED'
672
+ * }
673
+ * })
674
+ * ```
675
+ */
676
+ publishMessage(publishMessageRequest) {
677
+ return this.executeOperation('publishMessage', () => this.grpc.publishMessageSync((0, lib_2.stringifyVariables)({
678
+ ...publishMessageRequest,
679
+ variables: publishMessageRequest.variables,
680
+ tenantId: publishMessageRequest.tenantId ?? this.tenantId,
681
+ })));
682
+ }
683
+ /**
684
+ * @description Publish a message to the broker for correlation with a workflow message start event.
685
+ * For a message targeting a start event, the correlation key is not needed to target a specific running process instance.
686
+ * However, the hash of the correlationKey is used to determine the partition where this workflow will start.
687
+ * So we assign a random uuid to balance workflow instances created via start message across partitions.
688
+ *
689
+ * We make the correlationKey optional, because the caller can specify a correlationKey + messageId
690
+ * to guarantee an idempotent message.
691
+ *
692
+ * Multiple messages with the same correlationKey + messageId combination will only start a workflow once.
693
+ * See: https://github.com/zeebe-io/zeebe/issues/1012 and https://github.com/zeebe-io/zeebe/issues/1022
694
+ * @example
695
+ * ```
696
+ * const zbc = new ZeebeGrpcClient()
697
+ * zbc.publishStartMessage({
698
+ * name: 'Start_New_Onboarding_Flow',
699
+ * variables: {
700
+ * customerId: 'uuid-348-234-8908'
701
+ * }
702
+ * })
703
+ *
704
+ * // To do the same in an idempotent fashion - note: only idempotent during the lifetime of the created instance.
705
+ * zbc.publishStartMessage({
706
+ * name: 'Start_New_Onboarding_Flow',
707
+ * messageId: 'uuid-348-234-8908', // use customerId to make process idempotent per customer
708
+ * variables: {
709
+ * customerId: 'uuid-348-234-8908'
710
+ * }
711
+ * })
712
+ * ```
713
+ */
714
+ publishStartMessage(publishStartMessageRequest) {
715
+ /**
716
+ * The hash of the correlationKey is used to determine the partition where this workflow will start.
717
+ * So we assign a random uuid to balance workflow instances created via start message across partitions.
718
+ *
719
+ * We make the correlationKey optional, because the caller can specify a correlationKey + messageId
720
+ * to guarantee an idempotent message.
721
+ *
722
+ * Multiple messages with the same correlationKey + messageId combination will only start a workflow once.
723
+ * See: https://github.com/zeebe-io/zeebe/issues/1012 and https://github.com/zeebe-io/zeebe/issues/1022
724
+ */
725
+ const publishMessageRequest = {
726
+ correlationKey: (0, uuid_1.v4)(),
727
+ ...publishStartMessageRequest,
728
+ tenantId: publishStartMessageRequest.tenantId ?? this.tenantId,
729
+ };
730
+ return this.executeOperation('publishStartMessage', () => this.grpc.publishMessageSync((0, lib_2.stringifyVariables)({
731
+ ...publishMessageRequest,
732
+ variables: publishMessageRequest.variables || {},
733
+ })));
734
+ }
735
+ /**
736
+ *
737
+ * @description Resolve an incident by incident key.
738
+ * @example
739
+ * ```
740
+ * type JSONObject = {[key: string]: string | number | boolean | JSONObject}
741
+ *
742
+ * const zbc = new ZeebeGrpcClient()
743
+ *
744
+ * async updateAndResolveIncident({
745
+ * processInstanceId,
746
+ * incidentKey,
747
+ * variables
748
+ * } : {
749
+ * processInstanceId: string,
750
+ * incidentKey: string,
751
+ * variables: JSONObject
752
+ * }) {
753
+ * await zbc.setVariables({
754
+ * elementInstanceKey: processInstanceId,
755
+ * variables
756
+ * })
757
+ * await zbc.updateRetries()
758
+ * zbc.resolveIncident({
759
+ * incidentKey
760
+ * })
761
+ * zbc.resolveIncident(incidentKey)
762
+ * }
763
+ *
764
+ * ```
765
+ */
766
+ resolveIncident(resolveIncidentRequest) {
767
+ return this.executeOperation('resolveIncident', () => this.grpc.resolveIncidentSync(resolveIncidentRequest));
768
+ }
769
+ /**
770
+ *
771
+ * @description Directly modify the variables is a process instance. This can be used with `resolveIncident` to update the process and resolve an incident.
772
+ * @example
773
+ * ```
774
+ * type JSONObject = {[key: string]: string | number | boolean | JSONObject}
775
+ *
776
+ * const zbc = new ZeebeGrpcClient()
777
+ *
778
+ * async function updateAndResolveIncident({
779
+ * incidentKey,
780
+ * processInstanceKey,
781
+ * jobKey,
782
+ * variableUpdate
783
+ * } : {
784
+ * incidentKey: string
785
+ * processInstanceKey: string
786
+ * jobKey: string
787
+ * variableUpdate: JSONObject
788
+ * }) {
789
+ * await zbc.setVariables({
790
+ * elementInstanceKey: processInstanceKey,
791
+ * variables: variableUpdate
792
+ * })
793
+ * await zbc.updateJobRetries({
794
+ * jobKey,
795
+ * retries: 1
796
+ * })
797
+ * return zbc.resolveIncident({
798
+ * incidentKey
799
+ * })
800
+ * }
801
+ * ```
802
+ */
803
+ setVariables(request) {
804
+ /*
805
+ We allow developers to interact with variables as a native JS object, but the Zeebe server needs it as a JSON document
806
+ So we stringify it here.
807
+ */
808
+ const variables = typeof request.variables === 'object'
809
+ ? (0, lib_1.losslessStringify)(request.variables)
810
+ : request.variables;
811
+ return this.executeOperation('setVariables', () => this.grpc.setVariablesSync({ ...request, variables }));
812
+ }
813
+ /**
814
+ *
815
+ * @description Fail a job by throwing a business error (i.e. non-technical) that occurs while processing a job.
816
+ * The error is handled in the workflow by an error catch event.
817
+ * If there is no error catch event with the specified `errorCode` then an incident will be raised instead.
818
+ * This method is useful when building a worker, for example for the decoupled completion pattern.
819
+ * @example
820
+ * ```
821
+ * type JSONObject = {[key: string]: string | number | boolean | JSONObject}
822
+ *
823
+ * interface errorResult {
824
+ * resultType: 'ERROR' as 'ERROR'
825
+ * errorCode: string
826
+ * errorMessage: string
827
+ * }
828
+ *
829
+ * interface successResult {
830
+ * resultType: 'SUCCESS' as 'SUCCESS'
831
+ * variableUpdate: JSONObject
832
+ * }
833
+ *
834
+ * type Result = errorResult | successResult
835
+ *
836
+ * const zbc = new ZeebeGrpcClient()
837
+ *
838
+ *
839
+ * // This could be a listener on a return queue from an external system
840
+ * async function handleJob(jobKey: string, result: Result) {
841
+ * if (resultType === 'ERROR') {
842
+ * const { errorMessage, errorCode } = result
843
+ * zbc.throwError({
844
+ * jobKey,
845
+ * errorCode,
846
+ * errorMessage
847
+ * })
848
+ * } else {
849
+ * zbc.completeJob({
850
+ * jobKey,
851
+ * variables: result.variableUpdate
852
+ * })
853
+ * }
854
+ * }
855
+ * ```
856
+ */
857
+ throwError(throwErrorRequest) {
858
+ const req = (0, lib_2.stringifyVariables)({
859
+ ...throwErrorRequest,
860
+ variables: throwErrorRequest.variables ?? {},
861
+ });
862
+ return this.executeOperation('throwError', () => this.grpc.throwErrorSync(req));
863
+ }
864
+ /**
865
+ * @description Return the broker cluster topology.
866
+ * @example
867
+ * ```
868
+ * const zbc = new ZeebeGrpcClient()
869
+ *
870
+ * zbc.topology().then(res => console.res(JSON.stringify(res, null, 2)))
871
+ * ```
872
+ */
873
+ topology() {
874
+ return this.executeOperation('topology', this.grpc.topologySync);
875
+ }
876
+ /**
877
+ *
878
+ * @description Update the number of retries for a Job. This is useful if a job has zero remaining retries and fails, raising an incident.
879
+ * @example
880
+ * ```
881
+ * type JSONObject = {[key: string]: string | number | boolean | JSONObject}
882
+ *
883
+ * const zbc = new ZeebeGrpcClient()
884
+ *
885
+ * async function updateAndResolveIncident({
886
+ * incidentKey,
887
+ * processInstanceKey,
888
+ * jobKey,
889
+ * variableUpdate
890
+ * } : {
891
+ * incidentKey: string
892
+ * processInstanceKey: string
893
+ * jobKey: string
894
+ * variableUpdate: JSONObject
895
+ * }) {
896
+ * await zbc.setVariables({
897
+ * elementInstanceKey: processInstanceKey,
898
+ * variables: variableUpdate
899
+ * })
900
+ * await zbc.updateJobRetries({
901
+ * jobKey,
902
+ * retries: 1
903
+ * })
904
+ * return zbc.resolveIncident({
905
+ * incidentKey
906
+ * })
907
+ * }
908
+ * ```
909
+ */
910
+ updateJobRetries(updateJobRetriesRequest) {
911
+ return this.executeOperation('updateJobRetries', () => this.grpc.updateJobRetriesSync(updateJobRetriesRequest));
912
+ }
913
+ constructGrpcClient({ grpcConfig, logConfig, }) {
914
+ const { grpcClient, log } = ConnectionFactory_1.ConnectionFactory.getGrpcClient({
915
+ grpcConfig: {
916
+ config: this.config,
917
+ connectionTolerance: typed_duration_1.Duration.milliseconds.from(this.connectionTolerance),
918
+ customSSL: this.customSSL,
919
+ host: this.gatewayAddress,
920
+ loglevel: this.loglevel,
921
+ namespace: grpcConfig.namespace,
922
+ oAuth: this.oAuthProvider,
923
+ options: {
924
+ longPoll: this.options.longPoll
925
+ ? typed_duration_1.Duration.milliseconds.from(this.options.longPoll)
926
+ : undefined,
927
+ },
928
+ packageName: 'gateway_protocol',
929
+ protoPath: path.join(__dirname, '../../proto/zeebe.proto'),
930
+ service: 'Gateway',
931
+ stdout: this.stdout,
932
+ tasktype: grpcConfig.tasktype,
933
+ useTLS: this.useTLS,
934
+ },
935
+ logConfig,
936
+ });
937
+ if (grpcConfig.onConnectionError) {
938
+ grpcClient.on(ConnectionStatusEvent_1.ConnectionStatusEvent.connectionError, grpcConfig.onConnectionError);
939
+ }
940
+ if (grpcConfig.onReady) {
941
+ grpcClient.on(ConnectionStatusEvent_1.ConnectionStatusEvent.ready, grpcConfig.onReady);
942
+ }
943
+ return { grpcClient: grpcClient, log };
944
+ }
945
+ /**
946
+ * If this.retry is set true, the operation will be wrapped in an configurable retry on exceptions
947
+ * of gRPC error code 14 - Transient Network Failure.
948
+ * See: https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
949
+ * If this.retry is false, it will be executed with no retry, and the application should handle the exception.
950
+ * @param operation A gRPC command operation
951
+ */
952
+ async executeOperation(operationName, operation, retries) {
953
+ return this.retry
954
+ ? this.retryOnFailure(operationName, operation, retries)
955
+ : operation();
956
+ }
957
+ _onConnectionError(err) {
958
+ if (!this.connected) {
959
+ return;
960
+ }
961
+ this.connected = false;
962
+ // const debounce =
963
+ // this.lastConnectionError &&
964
+ // new Date().valueOf() - this.lastConnectionError.valueOf() >
965
+ // this.connectionTolerance / 2
966
+ // if (!debounce) {
967
+ this.onConnectionError?.(err);
968
+ this.emit(ConnectionStatusEvent_1.ConnectionStatusEvent.connectionError);
969
+ // }
970
+ // this.lastConnectionError = new Date()
971
+ }
972
+ /**
973
+ * This function takes a gRPC operation that returns a Promise as a function, and invokes it.
974
+ * If the operation throws gRPC error 14, this function will continue to try it until it succeeds
975
+ * or retries are exhausted.
976
+ * @param operation A gRPC command operation that may fail if the broker is not available
977
+ */
978
+ async retryOnFailure(operationName, operation, retries = this.maxRetries) {
979
+ let connectionErrorCount = 0;
980
+ return (0, promise_retry_1.default)((retry, n) => {
981
+ if (this.closing || this.grpc.channelClosed) {
982
+ /**
983
+ * Should we reject instead? The idea here is that calling ZBClient.close() will allow the application to cleanly shut down.
984
+ * If we reject here, any pending calls will throw errors. This is probably not what the user is expecting to see.
985
+ */
986
+ return Promise.resolve(null);
987
+ }
988
+ if (n > 1) {
989
+ this.logger.logError(`[${operationName}]: Attempt ${n} (max: ${this.maxRetries}).`);
990
+ }
991
+ return operation().catch((err) => {
992
+ // This could be DNS resolution, or the gRPC gateway is not reachable yet, or Backpressure
993
+ const isNetworkError = (err.message.indexOf('14') === 0 ||
994
+ err.message.indexOf('Stream removed') !== -1) &&
995
+ !err.message.includes('partition'); // Error 14 can be host unavailable (network) or partition unavailable (not network)
996
+ const isBackpressure = err.message.indexOf('8') === 0 || err.code === 8;
997
+ if (isNetworkError) {
998
+ if (connectionErrorCount < 0) {
999
+ this._onConnectionError(err);
1000
+ }
1001
+ connectionErrorCount++;
1002
+ }
1003
+ if (isNetworkError || isBackpressure) {
1004
+ this.logger.logError(`[${operationName}]: ${err.message}`);
1005
+ retry(err);
1006
+ }
1007
+ // The gRPC channel will be closed if close has been called
1008
+ if (this.grpc.channelClosed) {
1009
+ return Promise.resolve(null);
1010
+ }
1011
+ throw err;
1012
+ });
1013
+ }, {
1014
+ forever: retries === -1,
1015
+ maxTimeout: typed_duration_1.Duration.milliseconds.from(this.maxRetryTimeout),
1016
+ retries: retries === -1 ? undefined : retries,
1017
+ });
1018
+ }
1019
+ }
1020
+ exports.ZeebeGrpcClient = ZeebeGrpcClient;
1021
+ //# sourceMappingURL=ZeebeGrpcClient.js.map