@temporal-contract/worker 0.0.4 → 0.0.6

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.
package/dist/workflow.mjs CHANGED
@@ -1,3 +1,245 @@
1
- import { c as QueryOutputValidationError, d as UpdateOutputValidationError, f as WorkerError, l as SignalInputValidationError, m as WorkflowOutputValidationError, n as declareWorkflow, p as WorkflowInputValidationError, s as QueryInputValidationError, u as UpdateInputValidationError } from "./handler-B7B5QHez.mjs";
1
+ import { a as ChildWorkflowNotFoundError, c as SignalInputValidationError, d as WorkflowInputValidationError, f as WorkflowOutputValidationError, i as ChildWorkflowError, l as UpdateInputValidationError, n as ActivityInputValidationError, o as QueryInputValidationError, r as ActivityOutputValidationError, s as QueryOutputValidationError, u as UpdateOutputValidationError } from "./errors-BqVTpfcf.mjs";
2
+ import { Future, Result } from "@temporal-contract/boxed";
3
+ import { defineQuery, defineSignal, defineUpdate, executeChild, proxyActivities, setHandler, startChild, workflowInfo } from "@temporalio/workflow";
2
4
 
3
- export { QueryInputValidationError, QueryOutputValidationError, SignalInputValidationError, UpdateInputValidationError, UpdateOutputValidationError, WorkerError, WorkflowInputValidationError, WorkflowOutputValidationError, declareWorkflow };
5
+ //#region src/workflow.ts
6
+ /**
7
+ * Create a typed workflow implementation with automatic validation
8
+ *
9
+ * This wraps a workflow implementation with:
10
+ * - Input/output validation
11
+ * - Typed workflow context with activities
12
+ * - Workflow info access
13
+ *
14
+ * Workflows must be defined in separate files and imported by the Temporal Worker
15
+ * via workflowsPath.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * // workflows/processOrder.ts
20
+ * import { declareWorkflow } from '@temporal-contract/worker';
21
+ * import myContract from '../contract';
22
+ *
23
+ * export const processOrder = declareWorkflow({
24
+ * workflowName: 'processOrder',
25
+ * contract: myContract,
26
+ * implementation: async (context, orderId, customerId) => {
27
+ * // context.activities: typed activities (workflow + global)
28
+ * // context.info: WorkflowInfo
29
+ *
30
+ * const inventory = await context.activities.validateInventory(orderId);
31
+ *
32
+ * if (!inventory.available) {
33
+ * throw new Error('Out of stock');
34
+ * }
35
+ *
36
+ * const payment = await context.activities.chargePayment(customerId, 100);
37
+ *
38
+ * // Global activity
39
+ * await context.activities.sendEmail(
40
+ * customerId,
41
+ * 'Order processed',
42
+ * 'Your order has been processed'
43
+ * );
44
+ *
45
+ * return {
46
+ * orderId,
47
+ * status: payment.success ? 'success' : 'failed',
48
+ * transactionId: payment.transactionId,
49
+ * };
50
+ * },
51
+ * activityOptions: {
52
+ * startToCloseTimeout: '1 minute',
53
+ * },
54
+ * });
55
+ * ```
56
+ *
57
+ * Then in your worker setup:
58
+ * ```ts
59
+ * // worker.ts
60
+ * import { Worker } from '@temporalio/worker';
61
+ * import { activitiesHandler } from './activities';
62
+ *
63
+ * const worker = await Worker.create({
64
+ * workflowsPath: require.resolve('./workflows'), // Imports processOrder
65
+ * activities: activitiesHandler.activities,
66
+ * taskQueue: activitiesHandler.contract.taskQueue,
67
+ * });
68
+ * ```
69
+ */
70
+ function declareWorkflow({ workflowName, contract, implementation, activityOptions }) {
71
+ const definition = contract.workflows[workflowName];
72
+ return async (...args) => {
73
+ const input = args.length === 1 ? args[0] : args;
74
+ const inputResult = await definition.input["~standard"].validate(input);
75
+ if (inputResult.issues) throw new WorkflowInputValidationError(String(workflowName), inputResult.issues);
76
+ const validatedInput = inputResult.value;
77
+ let contextActivities = {};
78
+ if (definition.activities || contract.activities) contextActivities = createValidatedActivities(proxyActivities(activityOptions), definition.activities, contract.activities);
79
+ async function validateChildWorkflowOutput(childDefinition, result$1, childWorkflowName) {
80
+ const outputResult$1 = await childDefinition.output["~standard"].validate(result$1);
81
+ if (outputResult$1.issues) return Result.Error(new ChildWorkflowError(`Child workflow "${childWorkflowName}" output validation failed: ${outputResult$1.issues.map((i) => i.message).join("; ")}`));
82
+ return Result.Ok(outputResult$1.value);
83
+ }
84
+ async function getAndValidateChildWorkflow(childContract, childWorkflowName, args$1) {
85
+ const childDefinition = childContract.workflows[childWorkflowName];
86
+ if (!childDefinition) return Result.Error(new ChildWorkflowNotFoundError(String(childWorkflowName), Object.keys(childContract.workflows)));
87
+ const inputResult$1 = await childDefinition.input["~standard"].validate(args$1);
88
+ if (inputResult$1.issues) return Result.Error(new ChildWorkflowError(`Child workflow "${String(childWorkflowName)}" input validation failed: ${inputResult$1.issues.map((i) => i.message).join("; ")}`));
89
+ const validatedInput$1 = inputResult$1.value;
90
+ return Result.Ok({
91
+ definition: childDefinition,
92
+ validatedInput: validatedInput$1,
93
+ taskQueue: childContract.taskQueue
94
+ });
95
+ }
96
+ function createTypedChildHandle(handle, childDefinition, childWorkflowName) {
97
+ return {
98
+ workflowId: handle.workflowId,
99
+ result: () => {
100
+ return Future.make((resolve) => {
101
+ (async () => {
102
+ try {
103
+ resolve(await validateChildWorkflowOutput(childDefinition, await handle.result(), childWorkflowName));
104
+ } catch (error) {
105
+ resolve(Result.Error(new ChildWorkflowError(`Child workflow execution failed: ${error instanceof Error ? error.message : String(error)}`, error)));
106
+ }
107
+ })();
108
+ });
109
+ }
110
+ };
111
+ }
112
+ function createStartChildWorkflow(childContract, childWorkflowName, options) {
113
+ return Future.make((resolve) => {
114
+ (async () => {
115
+ const validationResult = await getAndValidateChildWorkflow(childContract, childWorkflowName, options.args);
116
+ if (validationResult.isError()) {
117
+ resolve(Result.Error(validationResult.error));
118
+ return;
119
+ }
120
+ const { definition: childDefinition, validatedInput: validatedInput$1, taskQueue } = validationResult.value;
121
+ try {
122
+ const { args: _args, ...temporalOptions } = options;
123
+ const typedHandle = createTypedChildHandle(await startChild(childWorkflowName, {
124
+ ...temporalOptions,
125
+ taskQueue,
126
+ args: [validatedInput$1]
127
+ }), childDefinition, String(childWorkflowName));
128
+ resolve(Result.Ok(typedHandle));
129
+ } catch (error) {
130
+ resolve(Result.Error(new ChildWorkflowError(`Failed to start child workflow: ${error instanceof Error ? error.message : String(error)}`, error)));
131
+ }
132
+ })();
133
+ });
134
+ }
135
+ function createExecuteChildWorkflow(childContract, childWorkflowName, options) {
136
+ return Future.make((resolve) => {
137
+ (async () => {
138
+ const validationResult = await getAndValidateChildWorkflow(childContract, childWorkflowName, options.args);
139
+ if (validationResult.isError()) {
140
+ resolve(Result.Error(validationResult.error));
141
+ return;
142
+ }
143
+ const { definition: childDefinition, validatedInput: validatedInput$1, taskQueue } = validationResult.value;
144
+ try {
145
+ const { args: _args, ...temporalOptions } = options;
146
+ const outputValidationResult = await validateChildWorkflowOutput(childDefinition, await executeChild(childWorkflowName, {
147
+ ...temporalOptions,
148
+ taskQueue,
149
+ args: [validatedInput$1]
150
+ }), String(childWorkflowName));
151
+ if (outputValidationResult.isError()) {
152
+ resolve(Result.Error(outputValidationResult.error));
153
+ return;
154
+ }
155
+ resolve(Result.Ok(outputValidationResult.value));
156
+ } catch (error) {
157
+ resolve(Result.Error(new ChildWorkflowError(`Failed to execute child workflow: ${error instanceof Error ? error.message : String(error)}`, error)));
158
+ }
159
+ })();
160
+ });
161
+ }
162
+ function createDefineSignal(signalName, handler) {
163
+ if (!definition.signals) throw new Error(`Signal "${String(signalName)}" cannot be defined: workflow "${String(workflowName)}" has no signals in its contract`);
164
+ const signalDef = definition.signals[signalName];
165
+ if (!signalDef) throw new Error(`Signal "${String(signalName)}" not found in workflow "${String(workflowName)}" contract`);
166
+ setHandler(defineSignal(signalName), async (...args$1) => {
167
+ const input$1 = args$1.length === 1 ? args$1[0] : args$1;
168
+ const inputResult$1 = await signalDef.input["~standard"].validate(input$1);
169
+ if (inputResult$1.issues) throw new SignalInputValidationError(signalName, inputResult$1.issues);
170
+ await handler(inputResult$1.value);
171
+ });
172
+ }
173
+ function createDefineQuery(queryName, handler) {
174
+ if (!definition.queries) throw new Error(`Query "${String(queryName)}" cannot be defined: workflow "${String(workflowName)}" has no queries in its contract`);
175
+ const queryDef = definition.queries[queryName];
176
+ if (!queryDef) throw new Error(`Query "${String(queryName)}" not found in workflow "${String(workflowName)}" contract`);
177
+ setHandler(defineQuery(queryName), (...args$1) => {
178
+ const input$1 = args$1.length === 1 ? args$1[0] : args$1;
179
+ const inputResult$1 = queryDef.input["~standard"].validate(input$1);
180
+ if (inputResult$1 instanceof Promise) throw new Error(`Query "${String(queryName)}" validation must be synchronous. Use a schema library that supports synchronous validation for queries.`);
181
+ if (inputResult$1.issues) throw new QueryInputValidationError(queryName, inputResult$1.issues);
182
+ const result$1 = handler(inputResult$1.value);
183
+ const outputResult$1 = queryDef.output["~standard"].validate(result$1);
184
+ if (outputResult$1 instanceof Promise) throw new Error(`Query "${String(queryName)}" output validation must be synchronous. Use a schema library that supports synchronous validation for queries.`);
185
+ if (outputResult$1.issues) throw new QueryOutputValidationError(queryName, outputResult$1.issues);
186
+ return outputResult$1.value;
187
+ });
188
+ }
189
+ function createDefineUpdate(updateName, handler) {
190
+ if (!definition.updates) throw new Error(`Update "${String(updateName)}" cannot be defined: workflow "${String(workflowName)}" has no updates in its contract`);
191
+ const updateDef = definition.updates[updateName];
192
+ if (!updateDef) throw new Error(`Update "${String(updateName)}" not found in workflow "${String(workflowName)}" contract`);
193
+ setHandler(defineUpdate(updateName), async (...args$1) => {
194
+ const input$1 = args$1.length === 1 ? args$1[0] : args$1;
195
+ const inputResult$1 = await updateDef.input["~standard"].validate(input$1);
196
+ if (inputResult$1.issues) throw new UpdateInputValidationError(updateName, inputResult$1.issues);
197
+ const result$1 = await handler(inputResult$1.value);
198
+ const outputResult$1 = await updateDef.output["~standard"].validate(result$1);
199
+ if (outputResult$1.issues) throw new UpdateOutputValidationError(updateName, outputResult$1.issues);
200
+ return outputResult$1.value;
201
+ });
202
+ }
203
+ const result = await implementation({
204
+ activities: contextActivities,
205
+ info: workflowInfo(),
206
+ startChildWorkflow: createStartChildWorkflow,
207
+ executeChildWorkflow: createExecuteChildWorkflow,
208
+ defineSignal: createDefineSignal,
209
+ defineQuery: createDefineQuery,
210
+ defineUpdate: createDefineUpdate
211
+ }, validatedInput);
212
+ const outputResult = await definition.output["~standard"].validate(result);
213
+ if (outputResult.issues) throw new WorkflowOutputValidationError(String(workflowName), outputResult.issues);
214
+ return outputResult.value;
215
+ };
216
+ }
217
+ /**
218
+ * Create a validated activities proxy that parses inputs and outputs
219
+ *
220
+ * This wrapper ensures data integrity across the network boundary between
221
+ * workflow and activity execution.
222
+ */
223
+ function createValidatedActivities(rawActivities, workflowActivitiesDefinition, contractActivitiesDefinition) {
224
+ const validatedActivities = {};
225
+ const allActivitiesDefinition = {
226
+ ...contractActivitiesDefinition,
227
+ ...workflowActivitiesDefinition
228
+ };
229
+ for (const [activityName, activityDef] of Object.entries(allActivitiesDefinition)) {
230
+ const rawActivity = rawActivities[activityName];
231
+ if (!rawActivity) throw new Error(`Activity implementation not found for: "${activityName}". Available activities: ${Object.keys(rawActivities).length > 0 ? Object.keys(rawActivities).join(", ") : "none"}`);
232
+ validatedActivities[activityName] = async (input) => {
233
+ const inputResult = await activityDef.input["~standard"].validate(input);
234
+ if (inputResult.issues) throw new ActivityInputValidationError(activityName, inputResult.issues);
235
+ const result = await rawActivity(inputResult.value);
236
+ const outputResult = await activityDef.output["~standard"].validate(result);
237
+ if (outputResult.issues) throw new ActivityOutputValidationError(activityName, outputResult.issues);
238
+ return outputResult.value;
239
+ };
240
+ }
241
+ return validatedActivities;
242
+ }
243
+
244
+ //#endregion
245
+ export { ActivityInputValidationError, ActivityOutputValidationError, ChildWorkflowError, ChildWorkflowNotFoundError, QueryInputValidationError, QueryOutputValidationError, SignalInputValidationError, UpdateInputValidationError, UpdateOutputValidationError, WorkflowInputValidationError, WorkflowOutputValidationError, declareWorkflow };
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@temporal-contract/worker",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
4
4
  "description": "Worker utilities with Result/Future pattern for implementing temporal-contract workflows and activities",
5
5
  "keywords": [
6
- "temporal",
7
- "typescript",
8
6
  "contract",
9
- "worker",
7
+ "future",
10
8
  "result",
11
- "future"
9
+ "temporal",
10
+ "typescript",
11
+ "worker"
12
12
  ],
13
13
  "homepage": "https://github.com/btravers/temporal-contract#readme",
14
14
  "bugs": {
@@ -20,7 +20,7 @@
20
20
  "directory": "packages/worker"
21
21
  },
22
22
  "license": "MIT",
23
- "author": "Benoit TRAVERS <benoit.travers.frgmail.com>",
23
+ "author": "Benoit TRAVERS <benoit.travers.fr@gmail.com>",
24
24
  "type": "module",
25
25
  "exports": {
26
26
  "./activity": {
@@ -33,6 +33,17 @@
33
33
  "default": "./dist/activity.cjs"
34
34
  }
35
35
  },
36
+ "./package.json": "./package.json",
37
+ "./worker": {
38
+ "import": {
39
+ "types": "./dist/worker.d.mts",
40
+ "default": "./dist/worker.mjs"
41
+ },
42
+ "require": {
43
+ "types": "./dist/worker.d.cts",
44
+ "default": "./dist/worker.cjs"
45
+ }
46
+ },
36
47
  "./workflow": {
37
48
  "import": {
38
49
  "types": "./dist/workflow.d.mts",
@@ -42,8 +53,7 @@
42
53
  "types": "./dist/workflow.d.cts",
43
54
  "default": "./dist/workflow.cjs"
44
55
  }
45
- },
46
- "./package.json": "./package.json"
56
+ }
47
57
  },
48
58
  "main": "./dist/index.cjs",
49
59
  "module": "./dist/index.mjs",
@@ -52,28 +62,34 @@
52
62
  "dist"
53
63
  ],
54
64
  "dependencies": {
55
- "@standard-schema/spec": "1.0.0",
56
- "@swan-io/boxed": "3.2.1",
57
- "@temporal-contract/contract": "0.0.4"
65
+ "@standard-schema/spec": "1.1.0",
66
+ "@temporal-contract/boxed": "0.0.6",
67
+ "@temporal-contract/contract": "0.0.6"
58
68
  },
59
69
  "devDependencies": {
60
- "@temporalio/workflow": "1.13.2",
61
- "@types/node": "25.0.1",
62
- "@vitest/coverage-v8": "4.0.15",
63
- "tsdown": "0.17.3",
70
+ "@temporalio/client": "1.14.0",
71
+ "@temporalio/worker": "1.14.0",
72
+ "@temporalio/workflow": "1.14.0",
73
+ "@types/node": "25.0.3",
74
+ "@vitest/coverage-v8": "4.0.16",
75
+ "tsdown": "0.18.1",
64
76
  "typescript": "5.9.3",
65
- "vitest": "4.0.15",
66
- "zod": "4.1.13",
67
- "@temporal-contract/tsconfig": "0.0.4"
77
+ "vitest": "4.0.16",
78
+ "zod": "4.2.1",
79
+ "@temporal-contract/client": "0.0.6",
80
+ "@temporal-contract/testing": "0.0.6",
81
+ "@temporal-contract/tsconfig": "0.0.6"
68
82
  },
69
83
  "peerDependencies": {
70
- "@temporalio/workflow": ">=1.13.0 <2.0.0"
84
+ "@temporalio/worker": "^1",
85
+ "@temporalio/workflow": "^1"
71
86
  },
72
87
  "scripts": {
73
- "build": "tsdown src/activity.ts src/workflow.ts --format cjs,esm --dts --clean",
74
- "dev": "tsdown src/activity.ts src/workflow.ts --format cjs,esm --dts --watch",
75
- "test": "vitest run",
76
- "test:watch": "vitest",
88
+ "build": "tsdown src/activity.ts src/worker.ts src/workflow.ts --format cjs,esm --dts --clean",
89
+ "dev": "tsdown src/activity.ts src/worker.ts src/workflow.ts --format cjs,esm --dts --watch",
90
+ "test": "vitest run --project unit",
91
+ "test:integration": "vitest run --project integration",
92
+ "test:watch": "vitest --project unit",
77
93
  "typecheck": "tsc --noEmit"
78
94
  }
79
95
  }