@hatchet-dev/typescript-sdk 0.8.0-alpha.3 → 0.8.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.
@@ -16,6 +16,7 @@ exports.WebhookHandler = void 0;
16
16
  const hatchet_error_1 = __importDefault(require("../../util/errors/hatchet-error"));
17
17
  const crypto_1 = require("crypto");
18
18
  const action_listener_1 = require("../dispatcher/action-listener");
19
+ const okMessage = 'The Hatchet webhooks endpoint is up and running!';
19
20
  class WebhookHandler {
20
21
  // eslint-disable-next-line no-useless-constructor
21
22
  constructor(worker, workflows
@@ -35,28 +36,32 @@ class WebhookHandler {
35
36
  * @throws {HatchetError} - If no secret is provided.
36
37
  * @throws {HatchetError} - If no body is provided.
37
38
  */
38
- handle(body, secret, signature) {
39
+ handle(body, signature, secret) {
39
40
  return __awaiter(this, void 0, void 0, function* () {
40
- if (!signature || typeof signature !== 'string') {
41
- throw new hatchet_error_1.default('No signature provided');
42
- }
43
- if (!secret) {
44
- throw new hatchet_error_1.default('No secret provided');
45
- }
46
- if (!body) {
47
- throw new hatchet_error_1.default('No body provided');
48
- }
49
- // verify hmac signature
50
- const actualSignature = (0, crypto_1.createHmac)('sha256', secret).update(body).digest('hex');
51
- if (actualSignature !== signature) {
52
- throw new hatchet_error_1.default(`Invalid signature, expected ${actualSignature}, got ${signature}`);
53
- }
41
+ this.checkSignature(body, signature, secret);
54
42
  const action = action_listener_1.ActionObject.parse(JSON.parse(body));
55
43
  yield this.worker.handleAction(action);
56
44
  });
57
45
  }
58
- getHealthcheckResponse() {
46
+ checkSignature(body, signature, secret) {
47
+ if (!signature || typeof signature !== 'string') {
48
+ throw new hatchet_error_1.default('No signature provided');
49
+ }
50
+ if (!secret) {
51
+ throw new hatchet_error_1.default('No secret provided');
52
+ }
53
+ if (!body) {
54
+ throw new hatchet_error_1.default('No body provided');
55
+ }
56
+ // verify hmac signature
57
+ const actualSignature = (0, crypto_1.createHmac)('sha256', secret).update(body).digest('hex');
58
+ if (actualSignature !== signature) {
59
+ throw new hatchet_error_1.default(`Invalid signature, expected ${actualSignature}, got ${signature}`);
60
+ }
61
+ }
62
+ getHealthcheckResponse(body, signature, secret) {
59
63
  return __awaiter(this, void 0, void 0, function* () {
64
+ this.checkSignature(body, signature, secret);
60
65
  for (const workflow of this.workflows) {
61
66
  yield this.worker.registerWorkflow(workflow);
62
67
  }
@@ -80,16 +85,11 @@ class WebhookHandler {
80
85
  return (req, res) => {
81
86
  if (req.method === 'GET') {
82
87
  res.sendStatus(200);
83
- res.send('OK!');
88
+ res.send(okMessage);
84
89
  return;
85
90
  }
86
- if (req.method !== 'POST') {
87
- res.sendStatus(405);
88
- res.json({ error: 'Method not allowed' });
89
- return;
90
- }
91
- if (req.headers['x-healthcheck']) {
92
- this.getHealthcheckResponse()
91
+ if (req.method === 'PUT') {
92
+ this.getHealthcheckResponse(req.body, req.headers['x-hatchet-signature'], secret)
93
93
  .then((resp) => {
94
94
  res.sendStatus(200);
95
95
  res.json(resp);
@@ -100,6 +100,11 @@ class WebhookHandler {
100
100
  });
101
101
  return;
102
102
  }
103
+ if (req.method !== 'POST') {
104
+ res.sendStatus(405);
105
+ res.json({ error: 'Method not allowed' });
106
+ return;
107
+ }
103
108
  this.handle(req.body, req.headers['x-hatchet-signature'], secret)
104
109
  .then(() => {
105
110
  res.sendStatus(200);
@@ -122,25 +127,25 @@ class WebhookHandler {
122
127
  const handle = () => __awaiter(this, void 0, void 0, function* () {
123
128
  if (req.method === 'GET') {
124
129
  res.writeHead(200, { 'Content-Type': 'application/json' });
125
- res.write('OK!');
130
+ res.write(okMessage);
126
131
  res.end();
127
132
  return;
128
133
  }
129
- if (req.method !== 'POST') {
130
- res.writeHead(405, { 'Content-Type': 'application/json' });
131
- res.write(JSON.stringify({ error: 'Method not allowed' }));
134
+ const body = yield this.getBody(req);
135
+ if (req.method === 'PUT') {
136
+ const resp = yield this.getHealthcheckResponse(body, req.headers['x-hatchet-signature'], secret);
137
+ res.writeHead(200, { 'Content-Type': 'application/json' });
138
+ res.write(JSON.stringify(resp));
132
139
  res.end();
133
140
  return;
134
141
  }
135
- if (req.headers['x-healthcheck']) {
136
- const resp = yield this.getHealthcheckResponse();
137
- res.writeHead(200, { 'Content-Type': 'application/json' });
138
- res.write(JSON.stringify(resp));
142
+ if (req.method !== 'POST') {
143
+ res.writeHead(405, { 'Content-Type': 'application/json' });
144
+ res.write(JSON.stringify({ error: 'Method not allowed' }));
139
145
  res.end();
140
146
  return;
141
147
  }
142
- const body = yield this.getBody(req);
143
- yield this.handle(body, secret, req.headers['x-hatchet-signature']);
148
+ yield this.handle(body, req.headers['x-hatchet-signature'], secret);
144
149
  res.writeHead(200, 'OK');
145
150
  res.end();
146
151
  });
@@ -160,14 +165,19 @@ class WebhookHandler {
160
165
  */
161
166
  nextJSHandler({ secret }) {
162
167
  const ok = () => __awaiter(this, void 0, void 0, function* () {
163
- return new Response('OK!', { status: 200 });
168
+ return new Response(okMessage, { status: 200 });
164
169
  });
165
170
  const f = (req) => __awaiter(this, void 0, void 0, function* () {
166
- if (req.headers.get('x-healthcheck')) {
167
- const resp = yield this.getHealthcheckResponse();
171
+ const sig = req.headers.get('x-hatchet-signature');
172
+ const body = yield req.text();
173
+ if (req.method === 'PUT') {
174
+ const resp = yield this.getHealthcheckResponse(body, sig, secret);
168
175
  return new Response(JSON.stringify(resp), { status: 200 });
169
176
  }
170
- yield this.handle(yield req.text(), secret, req.headers.get('x-hatchet-signature'));
177
+ if (req.method !== 'POST') {
178
+ return new Response('Method not allowed', { status: 405 });
179
+ }
180
+ yield this.handle(body, sig, secret);
171
181
  return new Response('ok', { status: 200 });
172
182
  });
173
183
  return {
@@ -20,7 +20,6 @@ export declare class Worker {
20
20
  maxRuns?: number;
21
21
  logger: Logger;
22
22
  registeredWorkflowPromises: Array<Promise<any>>;
23
- registeredWorkflowIds: string[];
24
23
  constructor(client: HatchetClient, options: {
25
24
  name: string;
26
25
  handleKill?: boolean;
@@ -28,7 +27,7 @@ export declare class Worker {
28
27
  });
29
28
  private registerActions;
30
29
  getHandler(workflows: Workflow[]): WebhookHandler;
31
- registerWebhook(webhook: WebhookWorkerCreateRequest): Promise<import("axios").AxiosResponse<import("../rest/generated/data-contracts").WebhookWorker, any>>;
30
+ registerWebhook(webhook: WebhookWorkerCreateRequest): Promise<import("axios").AxiosResponse<import("../rest/generated/data-contracts").WebhookWorkerCreated, any>>;
32
31
  /**
33
32
  * @deprecated use registerWorkflow instead
34
33
  */
@@ -32,7 +32,6 @@ class Worker {
32
32
  this.futures = {};
33
33
  this.contexts = {};
34
34
  this.registeredWorkflowPromises = [];
35
- this.registeredWorkflowIds = [];
36
35
  this.client = client;
37
36
  this.name = this.client.config.namespace + options.name;
38
37
  this.action_registry = {};
@@ -67,7 +66,7 @@ class Worker {
67
66
  }
68
67
  registerWebhook(webhook) {
69
68
  return __awaiter(this, void 0, void 0, function* () {
70
- return this.client.admin.webhook_create(Object.assign(Object.assign({}, webhook), { workflows: this.registeredWorkflowIds }));
69
+ return this.client.admin.webhook_create(Object.assign({}, webhook));
71
70
  });
72
71
  }
73
72
  /**
@@ -108,7 +107,6 @@ class Worker {
108
107
  ],
109
108
  }
110
109
  : undefined;
111
- this.registeredWorkflowIds.push(workflow.id);
112
110
  const registeredWorkflow = this.client.admin.putWorkflow({
113
111
  name: workflow.id,
114
112
  description: workflow.description,
package/index.d.ts CHANGED
@@ -4,4 +4,5 @@ export * from './step';
4
4
  export * from './clients/worker';
5
5
  export * from './clients/rest';
6
6
  export * from './clients/admin';
7
+ export * from './util/workflow-run-ref';
7
8
  export default Hatchet;
package/index.js CHANGED
@@ -20,4 +20,5 @@ __exportStar(require("./step"), exports);
20
20
  __exportStar(require("./clients/worker"), exports);
21
21
  __exportStar(require("./clients/rest"), exports);
22
22
  __exportStar(require("./clients/admin"), exports);
23
+ __exportStar(require("./util/workflow-run-ref"), exports);
23
24
  exports.default = hatchet_client_1.HatchetClient;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hatchet-dev/typescript-sdk",
3
- "version": "0.8.0-alpha.3",
3
+ "version": "0.8.0-alpha.4",
4
4
  "description": "Background task orchestration & visibility for developers",
5
5
  "types": "dist/index.d.ts",
6
6
  "files": [
@@ -84,7 +84,7 @@
84
84
  "ts-jest": "^29.1.1",
85
85
  "ts-node": "^10.9.2",
86
86
  "ts-proto": "^1.167.0",
87
- "typedoc": "^0.25.7",
87
+ "typedoc": "^0.26.2",
88
88
  "typedoc-plugin-markdown": "^4.0.2",
89
89
  "typescript": "^5.3.3"
90
90
  },
@@ -28,7 +28,19 @@ var __importStar = (this && this.__importStar) || function (mod) {
28
28
  return result;
29
29
  };
30
30
  Object.defineProperty(exports, "__esModule", { value: true });
31
- exports.DispatcherDefinition = exports.ReleaseSlotResponse = exports.ReleaseSlotRequest = exports.RefreshTimeoutResponse = exports.RefreshTimeoutRequest = exports.HeartbeatResponse = exports.HeartbeatRequest = exports.OverridesDataResponse = exports.OverridesData = exports.StepRunResult = exports.WorkflowRunEvent = exports.WorkflowEvent = exports.SubscribeToWorkflowRunsRequest = exports.SubscribeToWorkflowEventsRequest = exports.ActionEventResponse = exports.StepActionEvent = exports.GroupKeyActionEvent = exports.WorkerUnsubscribeResponse = exports.WorkerUnsubscribeRequest = exports.WorkerListenRequest = exports.AssignedAction = exports.WorkerRegisterResponse = exports.WorkerRegisterRequest = exports.workflowRunEventTypeToJSON = exports.workflowRunEventTypeFromJSON = exports.WorkflowRunEventType = exports.resourceEventTypeToJSON = exports.resourceEventTypeFromJSON = exports.ResourceEventType = exports.resourceTypeToJSON = exports.resourceTypeFromJSON = exports.ResourceType = exports.stepActionEventTypeToJSON = exports.stepActionEventTypeFromJSON = exports.StepActionEventType = exports.groupKeyActionEventTypeToJSON = exports.groupKeyActionEventTypeFromJSON = exports.GroupKeyActionEventType = exports.actionTypeToJSON = exports.actionTypeFromJSON = exports.ActionType = exports.protobufPackage = void 0;
31
+ exports.DispatcherDefinition = exports.ReleaseSlotResponse = exports.ReleaseSlotRequest = exports.RefreshTimeoutResponse = exports.RefreshTimeoutRequest = exports.HeartbeatResponse = exports.HeartbeatRequest = exports.OverridesDataResponse = exports.OverridesData = exports.StepRunResult = exports.WorkflowRunEvent = exports.WorkflowEvent = exports.SubscribeToWorkflowRunsRequest = exports.SubscribeToWorkflowEventsRequest = exports.ActionEventResponse = exports.StepActionEvent = exports.GroupKeyActionEvent = exports.WorkerUnsubscribeResponse = exports.WorkerUnsubscribeRequest = exports.WorkerListenRequest = exports.AssignedAction = exports.WorkerRegisterResponse = exports.WorkerRegisterRequest = exports.WorkflowRunEventType = exports.ResourceEventType = exports.ResourceType = exports.StepActionEventType = exports.GroupKeyActionEventType = exports.ActionType = exports.protobufPackage = void 0;
32
+ exports.actionTypeFromJSON = actionTypeFromJSON;
33
+ exports.actionTypeToJSON = actionTypeToJSON;
34
+ exports.groupKeyActionEventTypeFromJSON = groupKeyActionEventTypeFromJSON;
35
+ exports.groupKeyActionEventTypeToJSON = groupKeyActionEventTypeToJSON;
36
+ exports.stepActionEventTypeFromJSON = stepActionEventTypeFromJSON;
37
+ exports.stepActionEventTypeToJSON = stepActionEventTypeToJSON;
38
+ exports.resourceTypeFromJSON = resourceTypeFromJSON;
39
+ exports.resourceTypeToJSON = resourceTypeToJSON;
40
+ exports.resourceEventTypeFromJSON = resourceEventTypeFromJSON;
41
+ exports.resourceEventTypeToJSON = resourceEventTypeToJSON;
42
+ exports.workflowRunEventTypeFromJSON = workflowRunEventTypeFromJSON;
43
+ exports.workflowRunEventTypeToJSON = workflowRunEventTypeToJSON;
32
44
  const _m0 = __importStar(require("protobufjs/minimal"));
33
45
  const timestamp_1 = require("../google/protobuf/timestamp");
34
46
  exports.protobufPackage = '';
@@ -56,7 +68,6 @@ function actionTypeFromJSON(object) {
56
68
  return ActionType.UNRECOGNIZED;
57
69
  }
58
70
  }
59
- exports.actionTypeFromJSON = actionTypeFromJSON;
60
71
  function actionTypeToJSON(object) {
61
72
  switch (object) {
62
73
  case ActionType.START_STEP_RUN:
@@ -70,7 +81,6 @@ function actionTypeToJSON(object) {
70
81
  return 'UNRECOGNIZED';
71
82
  }
72
83
  }
73
- exports.actionTypeToJSON = actionTypeToJSON;
74
84
  var GroupKeyActionEventType;
75
85
  (function (GroupKeyActionEventType) {
76
86
  GroupKeyActionEventType[GroupKeyActionEventType["GROUP_KEY_EVENT_TYPE_UNKNOWN"] = 0] = "GROUP_KEY_EVENT_TYPE_UNKNOWN";
@@ -99,7 +109,6 @@ function groupKeyActionEventTypeFromJSON(object) {
99
109
  return GroupKeyActionEventType.UNRECOGNIZED;
100
110
  }
101
111
  }
102
- exports.groupKeyActionEventTypeFromJSON = groupKeyActionEventTypeFromJSON;
103
112
  function groupKeyActionEventTypeToJSON(object) {
104
113
  switch (object) {
105
114
  case GroupKeyActionEventType.GROUP_KEY_EVENT_TYPE_UNKNOWN:
@@ -115,7 +124,6 @@ function groupKeyActionEventTypeToJSON(object) {
115
124
  return 'UNRECOGNIZED';
116
125
  }
117
126
  }
118
- exports.groupKeyActionEventTypeToJSON = groupKeyActionEventTypeToJSON;
119
127
  var StepActionEventType;
120
128
  (function (StepActionEventType) {
121
129
  StepActionEventType[StepActionEventType["STEP_EVENT_TYPE_UNKNOWN"] = 0] = "STEP_EVENT_TYPE_UNKNOWN";
@@ -144,7 +152,6 @@ function stepActionEventTypeFromJSON(object) {
144
152
  return StepActionEventType.UNRECOGNIZED;
145
153
  }
146
154
  }
147
- exports.stepActionEventTypeFromJSON = stepActionEventTypeFromJSON;
148
155
  function stepActionEventTypeToJSON(object) {
149
156
  switch (object) {
150
157
  case StepActionEventType.STEP_EVENT_TYPE_UNKNOWN:
@@ -160,7 +167,6 @@ function stepActionEventTypeToJSON(object) {
160
167
  return 'UNRECOGNIZED';
161
168
  }
162
169
  }
163
- exports.stepActionEventTypeToJSON = stepActionEventTypeToJSON;
164
170
  var ResourceType;
165
171
  (function (ResourceType) {
166
172
  ResourceType[ResourceType["RESOURCE_TYPE_UNKNOWN"] = 0] = "RESOURCE_TYPE_UNKNOWN";
@@ -185,7 +191,6 @@ function resourceTypeFromJSON(object) {
185
191
  return ResourceType.UNRECOGNIZED;
186
192
  }
187
193
  }
188
- exports.resourceTypeFromJSON = resourceTypeFromJSON;
189
194
  function resourceTypeToJSON(object) {
190
195
  switch (object) {
191
196
  case ResourceType.RESOURCE_TYPE_UNKNOWN:
@@ -199,7 +204,6 @@ function resourceTypeToJSON(object) {
199
204
  return 'UNRECOGNIZED';
200
205
  }
201
206
  }
202
- exports.resourceTypeToJSON = resourceTypeToJSON;
203
207
  var ResourceEventType;
204
208
  (function (ResourceEventType) {
205
209
  ResourceEventType[ResourceEventType["RESOURCE_EVENT_TYPE_UNKNOWN"] = 0] = "RESOURCE_EVENT_TYPE_UNKNOWN";
@@ -240,7 +244,6 @@ function resourceEventTypeFromJSON(object) {
240
244
  return ResourceEventType.UNRECOGNIZED;
241
245
  }
242
246
  }
243
- exports.resourceEventTypeFromJSON = resourceEventTypeFromJSON;
244
247
  function resourceEventTypeToJSON(object) {
245
248
  switch (object) {
246
249
  case ResourceEventType.RESOURCE_EVENT_TYPE_UNKNOWN:
@@ -262,7 +265,6 @@ function resourceEventTypeToJSON(object) {
262
265
  return 'UNRECOGNIZED';
263
266
  }
264
267
  }
265
- exports.resourceEventTypeToJSON = resourceEventTypeToJSON;
266
268
  var WorkflowRunEventType;
267
269
  (function (WorkflowRunEventType) {
268
270
  WorkflowRunEventType[WorkflowRunEventType["WORKFLOW_RUN_EVENT_TYPE_FINISHED"] = 0] = "WORKFLOW_RUN_EVENT_TYPE_FINISHED";
@@ -279,7 +281,6 @@ function workflowRunEventTypeFromJSON(object) {
279
281
  return WorkflowRunEventType.UNRECOGNIZED;
280
282
  }
281
283
  }
282
- exports.workflowRunEventTypeFromJSON = workflowRunEventTypeFromJSON;
283
284
  function workflowRunEventTypeToJSON(object) {
284
285
  switch (object) {
285
286
  case WorkflowRunEventType.WORKFLOW_RUN_EVENT_TYPE_FINISHED:
@@ -289,7 +290,6 @@ function workflowRunEventTypeToJSON(object) {
289
290
  return 'UNRECOGNIZED';
290
291
  }
291
292
  }
292
- exports.workflowRunEventTypeToJSON = workflowRunEventTypeToJSON;
293
293
  function createBaseWorkerRegisterRequest() {
294
294
  return { workerName: '', actions: [], services: [], maxRuns: undefined };
295
295
  }
@@ -28,7 +28,11 @@ var __importStar = (this && this.__importStar) || function (mod) {
28
28
  return result;
29
29
  };
30
30
  Object.defineProperty(exports, "__esModule", { value: true });
31
- exports.WorkflowServiceDefinition = exports.PutRateLimitResponse = exports.PutRateLimitRequest = exports.TriggerWorkflowResponse = exports.TriggerWorkflowRequest = exports.WorkflowTriggerCronRef = exports.WorkflowTriggerEventRef = exports.WorkflowVersion = exports.ScheduleWorkflowRequest = exports.ListWorkflowsRequest = exports.CreateStepRateLimit = exports.CreateWorkflowStepOpts = exports.CreateWorkflowJobOpts = exports.WorkflowConcurrencyOpts = exports.CreateWorkflowVersionOpts = exports.PutWorkflowRequest = exports.rateLimitDurationToJSON = exports.rateLimitDurationFromJSON = exports.RateLimitDuration = exports.concurrencyLimitStrategyToJSON = exports.concurrencyLimitStrategyFromJSON = exports.ConcurrencyLimitStrategy = exports.protobufPackage = void 0;
31
+ exports.WorkflowServiceDefinition = exports.PutRateLimitResponse = exports.PutRateLimitRequest = exports.TriggerWorkflowResponse = exports.TriggerWorkflowRequest = exports.WorkflowTriggerCronRef = exports.WorkflowTriggerEventRef = exports.WorkflowVersion = exports.ScheduleWorkflowRequest = exports.ListWorkflowsRequest = exports.CreateStepRateLimit = exports.CreateWorkflowStepOpts = exports.CreateWorkflowJobOpts = exports.WorkflowConcurrencyOpts = exports.CreateWorkflowVersionOpts = exports.PutWorkflowRequest = exports.RateLimitDuration = exports.ConcurrencyLimitStrategy = exports.protobufPackage = void 0;
32
+ exports.concurrencyLimitStrategyFromJSON = concurrencyLimitStrategyFromJSON;
33
+ exports.concurrencyLimitStrategyToJSON = concurrencyLimitStrategyToJSON;
34
+ exports.rateLimitDurationFromJSON = rateLimitDurationFromJSON;
35
+ exports.rateLimitDurationToJSON = rateLimitDurationToJSON;
32
36
  const _m0 = __importStar(require("protobufjs/minimal"));
33
37
  const timestamp_1 = require("../google/protobuf/timestamp");
34
38
  exports.protobufPackage = '';
@@ -60,7 +64,6 @@ function concurrencyLimitStrategyFromJSON(object) {
60
64
  return ConcurrencyLimitStrategy.UNRECOGNIZED;
61
65
  }
62
66
  }
63
- exports.concurrencyLimitStrategyFromJSON = concurrencyLimitStrategyFromJSON;
64
67
  function concurrencyLimitStrategyToJSON(object) {
65
68
  switch (object) {
66
69
  case ConcurrencyLimitStrategy.CANCEL_IN_PROGRESS:
@@ -76,7 +79,6 @@ function concurrencyLimitStrategyToJSON(object) {
76
79
  return 'UNRECOGNIZED';
77
80
  }
78
81
  }
79
- exports.concurrencyLimitStrategyToJSON = concurrencyLimitStrategyToJSON;
80
82
  var RateLimitDuration;
81
83
  (function (RateLimitDuration) {
82
84
  RateLimitDuration[RateLimitDuration["SECOND"] = 0] = "SECOND";
@@ -117,7 +119,6 @@ function rateLimitDurationFromJSON(object) {
117
119
  return RateLimitDuration.UNRECOGNIZED;
118
120
  }
119
121
  }
120
- exports.rateLimitDurationFromJSON = rateLimitDurationFromJSON;
121
122
  function rateLimitDurationToJSON(object) {
122
123
  switch (object) {
123
124
  case RateLimitDuration.SECOND:
@@ -139,7 +140,6 @@ function rateLimitDurationToJSON(object) {
139
140
  return 'UNRECOGNIZED';
140
141
  }
141
142
  }
142
- exports.rateLimitDurationToJSON = rateLimitDurationToJSON;
143
143
  function createBasePutWorkflowRequest() {
144
144
  return { opts: undefined };
145
145
  }
package/step.d.ts CHANGED
@@ -3,7 +3,7 @@ import { Action } from './clients/dispatcher/action-listener';
3
3
  import { LogLevel } from './clients/event/event-client';
4
4
  import { Logger } from './util/logger';
5
5
  import { HatchetClient } from './clients/hatchet-client';
6
- import { WorkflowRunEvent } from './protoc/dispatcher';
6
+ import WorkflowRunRef from './util/workflow-run-ref';
7
7
  export declare const CreateRateLimitSchema: z.ZodObject<{
8
8
  key: z.ZodString;
9
9
  units: z.ZodNumber;
@@ -48,9 +48,16 @@ export declare const CreateStepSchema: z.ZodObject<{
48
48
  units: number;
49
49
  }[] | undefined;
50
50
  }>;
51
- type JSONPrimitive = string | number | boolean | null | Array<JSONPrimitive>;
51
+ export type JsonObject = {
52
+ [Key in string]: JsonValue;
53
+ } & {
54
+ [Key in string]?: JsonValue | undefined;
55
+ };
56
+ export type JsonArray = JsonValue[] | readonly JsonValue[];
57
+ export type JsonPrimitive = string | number | boolean | null;
58
+ export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
52
59
  export type NextStep = {
53
- [key: string]: NextStep | JSONPrimitive | Array<NextStep>;
60
+ [key: string]: JsonValue;
54
61
  };
55
62
  interface ContextData<T, K> {
56
63
  input: T;
@@ -58,15 +65,6 @@ interface ContextData<T, K> {
58
65
  triggered_by: string;
59
66
  user_data: K;
60
67
  }
61
- declare class ChildWorkflowRef<T> {
62
- workflowRunId: Promise<string>;
63
- parentWorkflowRunId: string;
64
- client: HatchetClient;
65
- constructor(workflowRunId: Promise<string>, parentWorkflowRunId: string, client: HatchetClient);
66
- stream(): Promise<AsyncGenerator<WorkflowRunEvent, void, unknown>>;
67
- result(): Promise<T>;
68
- toJSON(): Promise<string>;
69
- }
70
68
  export declare class Context<T, K = {}> {
71
69
  data: ContextData<T, K>;
72
70
  input: T;
@@ -96,7 +94,7 @@ export declare class Context<T, K = {}> {
96
94
  refreshTimeout(incrementBy: string): Promise<void>;
97
95
  releaseSlot(): Promise<void>;
98
96
  putStream(data: string | Uint8Array): Promise<void>;
99
- spawnWorkflow<P = unknown, Q = unknown>(workflowName: string, input: Q, key?: string): ChildWorkflowRef<P>;
97
+ spawnWorkflow<Q = JsonValue, P = JsonValue>(workflowName: string, input: Q, key?: string): WorkflowRunRef<P>;
100
98
  }
101
99
  export type StepRunFunction<T, K> = (ctx: Context<T, K>) => Promise<NextStep | void> | NextStep | void;
102
100
  export interface CreateStep<T, K> extends z.infer<typeof CreateStepSchema> {
package/step.js CHANGED
@@ -31,13 +31,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
31
31
  step((generator = generator.apply(thisArg, _arguments || [])).next());
32
32
  });
33
33
  };
34
- var __asyncValues = (this && this.__asyncValues) || function (o) {
35
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
36
- var m = o[Symbol.asyncIterator], i;
37
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
38
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
39
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
40
- };
41
34
  var __importDefault = (this && this.__importDefault) || function (mod) {
42
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
43
36
  };
@@ -49,7 +42,6 @@ const z = __importStar(require("zod"));
49
42
  const workflow_1 = require("./workflow");
50
43
  const logger_1 = require("./util/logger");
51
44
  const parse_1 = require("./util/parse");
52
- const dispatcher_1 = require("./protoc/dispatcher");
53
45
  exports.CreateRateLimitSchema = z.object({
54
46
  key: z.string(),
55
47
  units: z.number().min(1),
@@ -61,60 +53,6 @@ exports.CreateStepSchema = z.object({
61
53
  retries: z.number().optional(),
62
54
  rate_limits: z.array(exports.CreateRateLimitSchema).optional(),
63
55
  });
64
- class ChildWorkflowRef {
65
- constructor(workflowRunId, parentWorkflowRunId, client) {
66
- this.workflowRunId = workflowRunId;
67
- this.parentWorkflowRunId = parentWorkflowRunId;
68
- this.client = client;
69
- }
70
- stream() {
71
- return __awaiter(this, void 0, void 0, function* () {
72
- const workflowRunId = yield this.workflowRunId;
73
- const listener = yield this.client.listener.getChildListener(workflowRunId, this.parentWorkflowRunId);
74
- return listener.stream();
75
- });
76
- }
77
- result() {
78
- return __awaiter(this, void 0, void 0, function* () {
79
- const listener = yield this.stream();
80
- return new Promise((resolve, reject) => {
81
- (() => __awaiter(this, void 0, void 0, function* () {
82
- var _a, e_1, _b, _c;
83
- try {
84
- for (var _d = true, _e = __asyncValues(yield listener), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
85
- _c = _f.value;
86
- _d = false;
87
- const event = _c;
88
- if (event.eventType === dispatcher_1.WorkflowRunEventType.WORKFLOW_RUN_EVENT_TYPE_FINISHED) {
89
- if (event.results.some((r) => !!r.error)) {
90
- reject(event.results);
91
- return;
92
- }
93
- const result = event.results.reduce((acc, r) => (Object.assign(Object.assign({}, acc), { [r.stepReadableId]: JSON.parse(r.output || '{}') })), {});
94
- resolve(result);
95
- return;
96
- }
97
- }
98
- }
99
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
100
- finally {
101
- try {
102
- if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
103
- }
104
- finally { if (e_1) throw e_1.error; }
105
- }
106
- }))();
107
- });
108
- });
109
- }
110
- toJSON() {
111
- return __awaiter(this, void 0, void 0, function* () {
112
- return JSON.stringify({
113
- workflowRunId: yield this.workflowRunId,
114
- });
115
- });
116
- }
117
- }
118
56
  class Context {
119
57
  constructor(action, client) {
120
58
  this.controller = new AbortController();
@@ -229,14 +167,19 @@ class Context {
229
167
  spawnWorkflow(workflowName, input, key) {
230
168
  const { workflowRunId, stepRunId } = this.action;
231
169
  const name = this.client.config.namespace + workflowName;
232
- const childWorkflowRunIdPromise = this.client.admin.runWorkflow(name, input, {
233
- parentId: workflowRunId,
234
- parentStepRunId: stepRunId,
235
- childKey: key,
236
- childIndex: this.spawnIndex,
237
- });
238
- this.spawnIndex += 1;
239
- return new ChildWorkflowRef(childWorkflowRunIdPromise, workflowRunId, this.client);
170
+ try {
171
+ const resp = this.client.admin.runWorkflow(name, input, {
172
+ parentId: workflowRunId,
173
+ parentStepRunId: stepRunId,
174
+ childKey: key,
175
+ childIndex: this.spawnIndex,
176
+ });
177
+ this.spawnIndex += 1;
178
+ return resp;
179
+ }
180
+ catch (e) {
181
+ throw new hatchet_error_1.default(e.message);
182
+ }
240
183
  }
241
184
  }
242
185
  exports.Context = Context;
@@ -1,11 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getAddressesFromJWT = exports.getTenantIdFromJWT = void 0;
3
+ exports.getTenantIdFromJWT = getTenantIdFromJWT;
4
+ exports.getAddressesFromJWT = getAddressesFromJWT;
4
5
  function getTenantIdFromJWT(token) {
5
6
  const claims = extractClaimsFromJWT(token);
6
7
  return claims.sub;
7
8
  }
8
- exports.getTenantIdFromJWT = getTenantIdFromJWT;
9
9
  function getAddressesFromJWT(token) {
10
10
  const claims = extractClaimsFromJWT(token);
11
11
  return {
@@ -13,7 +13,6 @@ function getAddressesFromJWT(token) {
13
13
  grpcBroadcastAddress: claims.grpc_broadcast_address,
14
14
  };
15
15
  }
16
- exports.getAddressesFromJWT = getAddressesFromJWT;
17
16
  function extractClaimsFromJWT(token) {
18
17
  const parts = token.split('.');
19
18
  if (parts.length !== 3) {
package/util/parse.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseJSON = void 0;
3
+ exports.parseJSON = parseJSON;
4
4
  function parseJSON(json) {
5
5
  // TODO why is this needed?
6
6
  if (json.startsWith('ey')) {
@@ -22,4 +22,3 @@ function parseJSON(json) {
22
22
  throw new Error(`Could not parse JSON: ${e.message}`);
23
23
  }
24
24
  }
25
- exports.parseJSON = parseJSON;
package/util/retrier.js CHANGED
@@ -12,7 +12,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.retrier = void 0;
15
+ exports.retrier = retrier;
16
16
  const sleep_1 = __importDefault(require("./sleep"));
17
17
  const DEFAULT_RETRY_INTERVAL = 5; // seconds
18
18
  const DEFAULT_RETRY_COUNT = 5;
@@ -33,4 +33,3 @@ function retrier(fn_1, logger_1) {
33
33
  throw lastError;
34
34
  });
35
35
  }
36
- exports.retrier = retrier;
@@ -1,3 +1,2 @@
1
- /// <reference types="node" />
2
1
  import { Worker, WorkerOptions } from 'worker_threads';
3
2
  export declare function runThreaded(scriptPath: string, options: WorkerOptions): Worker;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.runThreaded = void 0;
6
+ exports.runThreaded = runThreaded;
7
7
  const worker_threads_1 = require("worker_threads");
8
8
  const path_1 = __importDefault(require("path"));
9
9
  function runThreaded(scriptPath, options) {
@@ -32,5 +32,4 @@ function runThreaded(scriptPath, options) {
32
32
  : resolvedPath;
33
33
  return new worker_threads_1.Worker(ex, Object.assign(Object.assign({}, options), { eval: isTs ? true : undefined }));
34
34
  }
35
- exports.runThreaded = runThreaded;
36
35
  // execArgv: ? ['--require', 'ts-node/register'] : undefined,
@@ -0,0 +1,17 @@
1
+ import { ListenerClient, StepRunEvent } from '../clients/listener/listener-client';
2
+ type EventualWorkflowRunId = string | Promise<string> | Promise<{
3
+ workflowRunId: string;
4
+ }>;
5
+ export default class WorkflowRunRef<T> {
6
+ workflowRunId: EventualWorkflowRunId;
7
+ parentWorkflowRunId?: string;
8
+ private client;
9
+ constructor(workflowRunId: string | Promise<string> | Promise<{
10
+ workflowRunId: string;
11
+ }>, client: ListenerClient, parentWorkflowRunId?: string);
12
+ getWorkflowRunId(): Promise<string>;
13
+ stream(): Promise<AsyncGenerator<StepRunEvent, void, unknown>>;
14
+ result(): Promise<T>;
15
+ toJSON(): Promise<string>;
16
+ }
17
+ export {};