@diagonal-hq/workflows 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,18 +4,45 @@ This package is the authoring API of Diagonal managed workflows. A workflow modu
4
4
 
5
5
  ## Entry points
6
6
 
7
- | Entry point | Used by | Exports |
8
- | ---------------------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
9
- | `@diagonal-hq/workflows` | Workflows | `defineWorkflow`, `respond`, `redirect`, `fail`, `validationError`, the input schema builder `v`, `transaction`, `data`, `mail`, `notification`, `sms`, and the generated capability wrappers |
10
- | `@diagonal-hq/workflows/test` | E2E setup and assert scripts | Every capability wrapper except the test profile's deny list (`auth`), `transaction`, and the root helpers that call no host capability |
11
- | `@diagonal-hq/workflows/migration` | Data migration scripts | Every capability wrapper except the migration profile's deny list (outbound calls, messages, payments, `auth`, and `workflow.run`), `transaction`, and the root helpers that call no host capability |
12
- | `@diagonal-hq/workflows/testing` | Local workflow tests in Node | `MockTransport`, `runWorkflow`, and `fake` |
13
- | `@diagonal-hq/workflows/http` | Local runs against a real workspace | `HttpTransport` |
7
+ | Entry point | Used by | Exports |
8
+ | -------------------------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
9
+ | `@diagonal-hq/workflows` | Workflows | `defineWorkflow`, `respond`, `redirect`, `fail`, `validationError`, the input schema builder `v`, `transaction`, `data`, `mail`, `notification`, `sms`, and the generated capability wrappers |
10
+ | `@diagonal-hq/workflows/test` | E2E setup and assert scripts | Every capability wrapper except the test profile's deny list (`auth`), `transaction`, and the root helpers that call no host capability |
11
+ | `@diagonal-hq/workflows/testing` | Local workflow tests in Node | `MockTransport`, `runWorkflow`, and `fake` |
12
+ | `@diagonal-hq/workflows/http` | Local runs against a real workspace | `HttpTransport` |
14
13
 
15
- A profile entry point (`/test` or `/migration`) exports every capability except its profile's deny list. `ScriptProfile` in the platform owns the deny lists, and `generated/capabilities.json` publishes the allowed names under `profiles`. The workflow script compiler reports a reference to a denied capability, and the script host refuses the call. Neither entry point exports `invoke` or `setTransport`, because the compiler cannot check a capability name that a script builds at run time.
14
+ The `/test` profile entry point exports every capability except its profile's deny list. `ScriptProfile` in the platform owns the deny lists, and `generated/capabilities.json` publishes the allowed names under `profiles`. The workflow script compiler reports a reference to a denied capability, and the script host refuses the call. The entry point exports neither `invoke` nor `setTransport`, because the compiler cannot check a capability name that a script builds at run time.
16
15
 
17
16
  Only `/testing` imports Node built-in modules (`node:async_hooks` and `node:crypto`). The other entry points need no Node API.
18
17
 
18
+ ## Write a data migration
19
+
20
+ File-based workspace migrations use the ordinary workflow SDK. Export a default `defineWorkflow(config, handler)` from `@diagonal/workflow`. The config is a static object literal with `name` and `trigger: { type: 'manual' }`. Every migration runs as system, and the build ignores a `runAs` that the file sets. Use `data.each`, `data.update`, and other ordinary capabilities in the handler to perform the work directly.
21
+
22
+ ```ts
23
+ import { Resources } from '@app/generated/resources';
24
+ import { data, defineWorkflow } from '@diagonal/workflow';
25
+
26
+ export default defineWorkflow(
27
+ {
28
+ name: 'Backfill post slug',
29
+ trigger: { type: 'manual' },
30
+ runAs: 'system'
31
+ },
32
+ async () => {
33
+ for await (const post of data.each({ resource: Resources.Posts.slug })) {
34
+ // ...
35
+ }
36
+ }
37
+ );
38
+ ```
39
+
40
+ A migration with `export const config` or `title` still builds, with a warning.
41
+
42
+ Create a file with `diagonal make:migration <name>`, or `npm run migration -- <name>` in a workspace template. It creates `migrations/YYYYMMDDHHmmss_name.ts`. Deployment activation queues all new filenames independently as ordinary asynchronous workflows. They can run concurrently. The timestamp sorts filenames for listing and history and does not enforce execution order. Put dependent operations in one script. The platform records the filename for the workspace environment in Postgres before launch. It records every terminal outcome and never launches that filename again. Manual and nested workflow calls cannot run migration files. Inspect the existing workflow execution status for a failure, then add a new migration file to correct it.
43
+
44
+ Migrations run after schema activation. Existing schema safety guards still apply. Deploy a new field as optional, fill it in a migration, then make it required in a later release. A failed migration can leave completed writes in place, so account for those writes in the correction.
45
+
19
46
  ## Run a workflow in a test
20
47
 
21
48
  ```ts
@@ -29,6 +56,17 @@ const output = await runWorkflow(welcomeMember, {}, { transport });
29
56
 
30
57
  `runWorkflow` sends each capability call to the transport of its own run. Overlapping and nested runs do not share transports. A call with no mock handler fails with `capability_denied`.
31
58
 
59
+ Imported from this package, `runWorkflow` runs the handler in Node. A deployed script runs in QuickJS, so the two engines can give different results. In a file-based workspace, the build and `diagonal check` run each `workflows/<name>.test.ts` and `migrations/<name>.test.ts` with a `runWorkflow` that runs the compiled code of the workflow file in QuickJS, with the production SDK runtime and limits. The test code itself still runs in Node. That `runWorkflow` has these differences:
60
+
61
+ - It always runs the `validate` option of the workflow config, as a deployed run does. It runs a `validateInput` export only when the test passes that export as the `validateInput` option. Another validator, or a `validateInput` option for a workflow with a `validate` option, is refused.
62
+ - Inputs, context, mock replies, and the result cross the engine boundary as JSON. A handler that returns `undefined` gives `null`, and a `Date` becomes a string.
63
+ - A `WorkflowFailure` or `HostError` from the script is rethrown as that class. A mock that throws another error reaches the script as a `HostError` with the code `internal_error`.
64
+ - A workflow that the test defines itself has no compiled code, so it runs in Node.
65
+
66
+ ### QuickJS limits
67
+
68
+ The QuickJS build has no `Intl` and no locale data. `toLocaleDateString`, `toLocaleTimeString`, `toLocaleString`, and `localeCompare` ignore their locale and options arguments. For example, `new Date('2026-11-03T12:00:00Z').toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })` gives `November 3, 2026` in Node and `11/03/2026` in QuickJS. Use the host helpers `date.format`, `time.format`, and `money.format`, which format with ICU on the host.
69
+
32
70
  ## Source in the platform repository
33
71
 
34
72
  `src/` is the same SDK source that the workflow script compiler embeds and that the QuickJS runtime bundles. Existing workspace modules import it as `@diagonal/workflow`. `php artisan workflows:script-sdk:build` regenerates `generated/capabilities.json`, `src/generated/capabilities.ts`, and `src/generated/profiles/*.ts`. Do not hand-edit them.
@@ -189,18 +189,27 @@ async function validateWorkflowInput(validator, input, ctx) {
189
189
  validationError(errors);
190
190
  }
191
191
  }
192
- function defineWorkflow(inputOrHandler, maybeHandler) {
193
- if (typeof inputOrHandler === "function") {
194
- return { $diagonal: "workflow", run: async (input, ctx) => inputOrHandler(input, ctx) };
192
+ function defineWorkflow(first, maybeHandler) {
193
+ if (typeof first === "function") {
194
+ return { $diagonal: "workflow", run: async (input, ctx) => first(input, ctx) };
195
195
  }
196
- const spec = inputOrHandler.$spec;
196
+ const schema = first instanceof InputSchema ? first : first.input;
197
+ const validate = first instanceof InputSchema ? void 0 : first.validate;
197
198
  const handler = maybeHandler;
198
199
  if (handler === void 0) {
199
- throw new TypeError("defineWorkflow(input, handler) needs a handler after the input schema.");
200
+ throw new TypeError(
201
+ schema === first ? "defineWorkflow(input, handler) needs a handler after the input schema." : "defineWorkflow(config, handler) needs a handler after the config."
202
+ );
203
+ }
204
+ if (validate !== void 0 && typeof validate !== "function") {
205
+ throw new TypeError(
206
+ "The validate option of defineWorkflow(config, handler) must be a function."
207
+ );
200
208
  }
201
209
  return {
202
210
  $diagonal: "workflow",
203
- input: spec,
211
+ ...schema === void 0 ? {} : { input: schema.$spec },
212
+ ...validate === void 0 ? {} : { validate },
204
213
  run: async (input, ctx) => handler(input, ctx)
205
214
  };
206
215
  }
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  invoke
3
- } from "./chunk-RWZW4V74.js";
3
+ } from "./chunk-EU2ME5WR.js";
4
4
  import {
5
5
  HostError
6
6
  } from "./chunk-OF5QITP7.js";
@@ -27,7 +27,7 @@ async function transaction(fn) {
27
27
  }
28
28
 
29
29
  // packages/workflows/src/generated/capabilities.ts
30
- var SDK_VERSION = 57;
30
+ var SDK_VERSION = 62;
31
31
  var ai = {
32
32
  /** Ask a decisions model typed questions about some content and get labelled answers with their probabilities */
33
33
  decide: (input) => invoke("ai.decide", input),
@@ -375,6 +375,10 @@ var data2 = {
375
375
  create: (input) => invoke("data.create", input),
376
376
  find: (input) => invoke("data.find", input),
377
377
  update: (input) => invoke("data.update", input),
378
+ /**
379
+ * One page of the records that the search matches: 50 records by default, and at most 100 with
380
+ * `pageSize`. To read every match, use `data.each`, which requests the pages for you.
381
+ */
378
382
  search: (input) => invoke("data.search", input),
379
383
  each,
380
384
  delete: (input) => invoke("data.delete", input),
@@ -382,6 +386,7 @@ var data2 = {
382
386
  count: (input) => invoke("data.count", input),
383
387
  findOrCreate: (input) => invoke("data.find-or-create", input),
384
388
  updateOrCreate: (input) => invoke("data.update-or-create", input),
389
+ /** Create all of `records` in one call. The call has no limit on the number of records. */
385
390
  createMany: (input) => invoke("data.create-many", input),
386
391
  deleteMany: (input) => invoke("data.delete-many", input)
387
392
  };
package/dist/data.d.ts CHANGED
@@ -45,7 +45,8 @@ type EachInput<R> = Omit<DataSearchInput, 'resource' | 'page' | 'pageSize' | 'pa
45
45
  maxRecords?: number;
46
46
  };
47
47
  /**
48
- * Visit every record that the search matches, one record at a time, with cursor paging. The
48
+ * Visit every record that the search matches, one record at a time. Use it in place of a loop
49
+ * over `data.search` pages: it calls `data.search` with cursor paging and pages of 100 records. The
49
50
  * query is copied when `each` is called, so a change to the input object during the walk does
50
51
  * not change the pages.
51
52
  *
@@ -73,6 +74,10 @@ export declare const data: {
73
74
  }) => Promise<{
74
75
  id: string;
75
76
  } & Record<string, unknown>>;
77
+ /**
78
+ * One page of the records that the search matches: 50 records by default, and at most 100 with
79
+ * `pageSize`. To read every match, use `data.each`, which requests the pages for you.
80
+ */
76
81
  search: <R extends ResourceKey>(input: Omit<DataSearchInput, "resource"> & {
77
82
  resource: R;
78
83
  }) => Promise<SearchOutput<R>>;
@@ -100,6 +105,7 @@ export declare const data: {
100
105
  }) => Promise<{
101
106
  id: string;
102
107
  } & Record<string, unknown>>;
108
+ /** Create all of `records` in one call. The call has no limit on the number of records. */
103
109
  createMany: <R extends ResourceKey>(input: Omit<DataCreateManyInput, "resource" | "records"> & {
104
110
  resource: R;
105
111
  records: Array<InputOf<R>>;
@@ -1,6 +1,6 @@
1
1
  import type { ResourceKeyWith } from "../data.js";
2
2
  import type { ContentDocument } from "../input.js";
3
- export declare const SDK_VERSION = 57;
3
+ export declare const SDK_VERSION = 62;
4
4
  export interface AiDecideInput {
5
5
  state: unknown;
6
6
  questions: Array<{
@@ -75,6 +75,12 @@ export interface ChartDistributionInput {
75
75
  categoryField: string;
76
76
  valueField?: string | null;
77
77
  filters?: unknown;
78
+ /**
79
+ * Maximum number of categories to show.
80
+ * From 1 to 50.
81
+ * @minimum 1
82
+ * @maximum 50
83
+ */
78
84
  limit?: number | null;
79
85
  }
80
86
  export type ChartDistributionOutput = Array<{
@@ -101,6 +107,12 @@ export interface ChartLeaderboardInput {
101
107
  valueField?: string | null;
102
108
  metricName: string;
103
109
  filters?: unknown;
110
+ /**
111
+ * Number of top entries to return.
112
+ * From 1 to 100.
113
+ * @minimum 1
114
+ * @maximum 100
115
+ */
104
116
  limit: number;
105
117
  }
106
118
  export type ChartLeaderboardOutput = Array<{
@@ -120,6 +132,12 @@ export interface ChartTimeSeriesInput {
120
132
  [key: string]: unknown;
121
133
  }>;
122
134
  filters?: unknown;
135
+ /**
136
+ * Maximum number of time periods to return.
137
+ * From 1 to 1000.
138
+ * @minimum 1
139
+ * @maximum 1000
140
+ */
123
141
  limit?: number | null;
124
142
  }
125
143
  export type ChartTimeSeriesOutput = Array<Record<string, unknown>>;
@@ -139,6 +157,12 @@ export interface DataAggregateMetricsInput {
139
157
  direction?: "asc" | "desc";
140
158
  [key: string]: unknown;
141
159
  }>;
160
+ /**
161
+ * Maximum number of groups to return.
162
+ * From 1 to 1000.
163
+ * @minimum 1
164
+ * @maximum 1000
165
+ */
142
166
  limit?: number | null;
143
167
  }
144
168
  export type DataAggregateMetricsOutput = Array<Record<string, unknown>>;
@@ -153,7 +177,18 @@ export interface DataCountInput {
153
177
  }>;
154
178
  relations?: Array<string>;
155
179
  recordScope?: "active" | "archived" | "activeOrArchived" | null;
180
+ /**
181
+ * The page number.
182
+ * At least 1.
183
+ * @minimum 1
184
+ */
156
185
  page?: number | null;
186
+ /**
187
+ * The number of records per page.
188
+ * From 1 to 100.
189
+ * @minimum 1
190
+ * @maximum 100
191
+ */
157
192
  pageSize?: number | null;
158
193
  }
159
194
  export type DataCountOutput = number;
@@ -253,7 +288,18 @@ export interface DataSearchInput {
253
288
  }>;
254
289
  relations?: Array<string>;
255
290
  recordScope?: "active" | "archived" | "activeOrArchived" | null;
291
+ /**
292
+ * The page number.
293
+ * At least 1.
294
+ * @minimum 1
295
+ */
256
296
  page?: number | null;
297
+ /**
298
+ * The number of records per page.
299
+ * From 1 to 100.
300
+ * @minimum 1
301
+ * @maximum 100
302
+ */
257
303
  pageSize?: number | null;
258
304
  paging?: "cursor" | "page" | null;
259
305
  after?: string | null;
@@ -273,6 +319,12 @@ export interface DataSemanticSearchInput {
273
319
  resource: string;
274
320
  query: string;
275
321
  filters?: unknown;
322
+ /**
323
+ * The maximum number of records to return.
324
+ * From 1 to 100.
325
+ * @minimum 1
326
+ * @maximum 100
327
+ */
276
328
  topK?: number | null;
277
329
  recordScope?: "active" | "archived" | "activeOrArchived" | null;
278
330
  }
@@ -292,7 +344,18 @@ export interface DataSumInput {
292
344
  }>;
293
345
  relations?: Array<string>;
294
346
  recordScope?: "active" | "archived" | "activeOrArchived" | null;
347
+ /**
348
+ * The page number.
349
+ * At least 1.
350
+ * @minimum 1
351
+ */
295
352
  page?: number | null;
353
+ /**
354
+ * The number of records per page.
355
+ * From 1 to 100.
356
+ * @minimum 1
357
+ * @maximum 100
358
+ */
296
359
  pageSize?: number | null;
297
360
  field: string;
298
361
  }
@@ -476,6 +539,12 @@ export interface MailSearchInput {
476
539
  statuses?: Array<"bounced" | "deferred" | "delivered" | "dropped" | "failed" | "sending" | "sent" | "spam_reported" | "suppressed"> | null;
477
540
  dateFrom?: string | null;
478
541
  dateBefore?: string | null;
542
+ /**
543
+ * Maximum number of emails to return, newest first. Total still counts every match.
544
+ * From 1 to 100.
545
+ * @minimum 1
546
+ * @maximum 100
547
+ */
479
548
  limit?: number | null;
480
549
  }
481
550
  export type MailSearchOutput = {
package/dist/index.js CHANGED
@@ -37,7 +37,7 @@ import {
37
37
  web,
38
38
  workflow,
39
39
  workspace
40
- } from "./chunks/chunk-KXVTSLCN.js";
40
+ } from "./chunks/chunk-QLQ4NOFV.js";
41
41
  import {
42
42
  InputField,
43
43
  InputSchema,
@@ -49,7 +49,7 @@ import {
49
49
  setTransport,
50
50
  v,
51
51
  validateWorkflowInput
52
- } from "./chunks/chunk-RWZW4V74.js";
52
+ } from "./chunks/chunk-EU2ME5WR.js";
53
53
  import {
54
54
  HostError,
55
55
  WorkflowFailure,
@@ -6,9 +6,10 @@ type Declared = [keyof WorkspaceNotificationTypes] extends [never] ? false : tru
6
6
  export type NotificationTypeKey = Declared extends true ? Entry extends {
7
7
  id: infer I;
8
8
  } ? I : never : string;
9
- type EntryFor<T> = Extract<Entry, {
10
- id: T;
11
- }>;
9
+ type MatchingEntry<E, T> = E extends {
10
+ id: infer I;
11
+ } ? (T extends I ? E : never) : never;
12
+ type EntryFor<T> = MatchingEntry<Entry, T>;
12
13
  /**
13
14
  * The template ids of one notification type under `Channel`: every template, or only the
14
15
  * templates with email or SMS on. Any string while the workspace declares no types.
@@ -1,4 +1,3 @@
1
- import "../chunks/chunk-CSWWU6TP.js";
2
1
  import {
3
2
  ai,
4
3
  calendar,
@@ -36,7 +35,7 @@ import {
36
35
  web,
37
36
  workflow,
38
37
  workspace
39
- } from "../chunks/chunk-KXVTSLCN.js";
38
+ } from "../chunks/chunk-QLQ4NOFV.js";
40
39
  import {
41
40
  InputField,
42
41
  InputSchema,
@@ -46,7 +45,7 @@ import {
46
45
  respond,
47
46
  v,
48
47
  validateWorkflowInput
49
- } from "../chunks/chunk-RWZW4V74.js";
48
+ } from "../chunks/chunk-EU2ME5WR.js";
50
49
  import {
51
50
  HostError,
52
51
  WorkflowFailure,
@@ -0,0 +1,6 @@
1
+ import type { WorkflowContext } from "../workflow.js";
2
+ export type LocalContextOptions = Omit<Partial<WorkflowContext>, 'execution'> & {
3
+ execution?: Partial<WorkflowContext['execution']>;
4
+ };
5
+ /** The context of a local run: the supplied values over local defaults, with a fresh execution ID. */
6
+ export declare function localWorkflowContext(supplied: LocalContextOptions | undefined): WorkflowContext;
@@ -1,5 +1,6 @@
1
1
  import { type HostTransport } from "../transport.js";
2
- import { type InputValidator, type WorkflowContext, type WorkflowDefinition } from "../workflow.js";
2
+ import { type InputValidator, type WorkflowDefinition } from "../workflow.js";
3
+ import { type LocalContextOptions } from "./context.js";
3
4
  export declare class MockTransport implements HostTransport {
4
5
  private readonly handlers;
5
6
  readonly calls: Array<{
@@ -11,10 +12,12 @@ export declare class MockTransport implements HostTransport {
11
12
  }
12
13
  export declare function runWorkflow<I, O>(workflow: WorkflowDefinition<I, O>, input: I, options?: {
13
14
  transport?: HostTransport;
14
- context?: Omit<Partial<WorkflowContext>, 'execution'> & {
15
- execution?: Partial<WorkflowContext['execution']>;
16
- };
17
- /** The module's `validateInput` export; it runs before the handler, as in the sandbox. */
15
+ context?: LocalContextOptions;
16
+ /**
17
+ * The module's `validateInput` export; it runs before the handler, as in the sandbox. The
18
+ * `validate` option of the workflow config always runs, so a workflow with one takes no
19
+ * `validateInput`.
20
+ */
18
21
  validateInput?: InputValidator<I>;
19
22
  }): Promise<O>;
20
23
  export declare const fake: {
@@ -2,14 +2,13 @@ import {
2
2
  parseWorkflowInput,
3
3
  setTransport,
4
4
  validateWorkflowInput
5
- } from "../chunks/chunk-RWZW4V74.js";
5
+ } from "../chunks/chunk-EU2ME5WR.js";
6
6
  import {
7
7
  HostError
8
8
  } from "../chunks/chunk-OF5QITP7.js";
9
9
 
10
10
  // packages/workflows/src/testing/index.ts
11
11
  import { AsyncLocalStorage } from "node:async_hooks";
12
- import { randomUUID } from "node:crypto";
13
12
 
14
13
  // packages/workflows/src/serial-transaction-transport.ts
15
14
  var PromiseConstructor = Promise;
@@ -91,6 +90,33 @@ var SerialTransactionTransport = class {
91
90
  }
92
91
  };
93
92
 
93
+ // packages/workflows/src/testing/context.ts
94
+ import { randomUUID } from "node:crypto";
95
+ var defaultContext = {
96
+ user: null,
97
+ callingUser: null,
98
+ trigger: {},
99
+ request: null,
100
+ workspace: { id: "local", timezone: "UTC" },
101
+ now: (/* @__PURE__ */ new Date(0)).toISOString()
102
+ };
103
+ function localWorkflowContext(supplied) {
104
+ const suppliedExecution = supplied?.execution;
105
+ const workflowId = suppliedExecution && "workflowId" in suppliedExecution && typeof suppliedExecution.workflowId === "string" ? suppliedExecution.workflowId : "local";
106
+ const execution = {
107
+ id: randomUUID(),
108
+ kind: "workflow",
109
+ workflowId,
110
+ owner: { type: "workflow", id: workflowId }
111
+ };
112
+ const context = {
113
+ ...defaultContext,
114
+ ...supplied,
115
+ execution: { ...execution, ...suppliedExecution }
116
+ };
117
+ return context;
118
+ }
119
+
94
120
  // packages/workflows/src/testing/index.ts
95
121
  var MockTransport = class {
96
122
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -108,14 +134,6 @@ var MockTransport = class {
108
134
  return handler(input);
109
135
  }
110
136
  };
111
- var defaultContext = {
112
- user: null,
113
- callingUser: null,
114
- trigger: {},
115
- request: null,
116
- workspace: { id: "local", timezone: "UTC" },
117
- now: (/* @__PURE__ */ new Date(0)).toISOString()
118
- };
119
137
  var runTransports = new AsyncLocalStorage();
120
138
  var activeRuns = 0;
121
139
  var runTransport = {
@@ -131,26 +149,20 @@ var runTransport = {
131
149
  };
132
150
  async function runWorkflow(workflow, input, options = {}) {
133
151
  const transport = options.transport ?? new MockTransport({});
134
- const suppliedExecution = options.context?.execution;
135
- const workflowId = suppliedExecution && "workflowId" in suppliedExecution && typeof suppliedExecution.workflowId === "string" ? suppliedExecution.workflowId : "local";
136
- const execution = {
137
- id: randomUUID(),
138
- kind: "workflow",
139
- workflowId,
140
- owner: { type: "workflow", id: workflowId }
141
- };
142
- const context = {
143
- ...defaultContext,
144
- ...options.context,
145
- execution: { ...execution, ...suppliedExecution }
146
- };
152
+ const context = localWorkflowContext(options.context);
147
153
  activeRuns++;
148
154
  setTransport(runTransport);
149
155
  try {
150
156
  return await runTransports.run(new SerialTransactionTransport(transport), async () => {
151
157
  const parsed = parseWorkflowInput(workflow, input);
152
- if (options.validateInput) {
153
- await validateWorkflowInput(options.validateInput, parsed, context);
158
+ if (workflow.validate !== void 0 && options.validateInput !== void 0) {
159
+ throw new TypeError(
160
+ "The workflow has a validate option, which always runs. Remove the validateInput option."
161
+ );
162
+ }
163
+ const validator = workflow.validate ?? options.validateInput;
164
+ if (validator !== void 0) {
165
+ await validateWorkflowInput(validator, parsed, context);
154
166
  }
155
167
  return await workflow.run(parsed, context);
156
168
  });
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The options of `defineWorkflow(config, handler)` other than `input` and `validate`. The build
3
+ * reads them as static data, checks them, and removes them from the compiled script, so the
4
+ * compiler sees only `input` and `validate`. `@diagonal-hq/cli` replaces this declaration with its
5
+ * `WorkflowConfig`, so the editor checks each option.
6
+ */
7
+ export type WorkflowConfig = Record<never, never>;
@@ -1,6 +1,7 @@
1
1
  import type { ResourceKeyWith } from "./data.js";
2
2
  import type { ScriptHostContext } from "./index.js";
3
- import { type InferInput, type InputFieldSpec, type InputSchema, type InputShape } from "./input.js";
3
+ import { InputSchema, type InferInput, type InputFieldSpec, type InputShape } from "./input.js";
4
+ import type { WorkflowConfig } from "./workflow-config.js";
4
5
  export interface Identity {
5
6
  id: string;
6
7
  /** The identity's resource has the Authenticatable capability. */
@@ -47,6 +48,11 @@ export interface WorkflowDefinition<I, O> {
47
48
  readonly $diagonal: 'workflow';
48
49
  /** The declared input schema, when the workflow has one. */
49
50
  readonly input?: InputFieldSpec;
51
+ /**
52
+ * The `validate` option of the config, which runs before the handler with the same input. A
53
+ * method, like `run`, so a definition stays assignable to a narrower input type.
54
+ */
55
+ validate?(input: I, ctx: WorkflowContext): ReturnType<InputValidator<I>>;
50
56
  /** Runs the handler with input that {@link parseWorkflowInput} already converted. */
51
57
  run(input: I, ctx: WorkflowContext): Promise<O>;
52
58
  }
@@ -61,19 +67,30 @@ export declare function parseWorkflowInput<I>(workflow: WorkflowDefinition<I, un
61
67
  */
62
68
  export type InputErrors<I> = Partial<Record<keyof I & string, string | string[]>> & Record<string, string | string[] | undefined>;
63
69
  /**
64
- * The `validateInput` export a script may define beside its workflow. It runs before the handler
65
- * with the same input and context; when it reports any error, the run ends with a 422 and those
66
- * errors, and the handler does not run.
70
+ * The `validate` option of a workflow config, or the `validateInput` export a script may define
71
+ * beside its workflow. It runs before the handler with the same input and context; when it
72
+ * reports any error, the run ends with a 422 and those errors, and the handler does not run.
67
73
  */
68
74
  export type InputValidator<I> = (input: I, ctx: WorkflowContext) => InputErrors<I> | void | Promise<InputErrors<I> | void>;
69
75
  /** Runs a script's input validator and ends the run with a validation error when it reports one. */
70
76
  export declare function validateWorkflowInput<I>(validator: InputValidator<I>, input: I, ctx: WorkflowContext): Promise<void>;
71
77
  type Handler<I, O> = (input: I, ctx: WorkflowContext) => Promise<O> | O;
72
78
  /**
73
- * Declares a workflow. With an input schema first, the platform validates every run's input
74
- * against it before the script starts, and the handler's `input` type comes from the schema.
79
+ * Declares a workflow. A file-based workflow passes its config first, as `definePage` does. The
80
+ * build reads the config as static data. With an `input` schema in the config, or a schema first,
81
+ * the platform validates every run's input against it before the script starts, and the handler's
82
+ * `input` type comes from the schema. A `validate` function in the config runs after that check
83
+ * and before the handler, with the same input type.
75
84
  */
85
+ export declare function defineWorkflow<S extends InputShape, O = unknown>(config: WorkflowConfig & {
86
+ readonly input: InputSchema<S>;
87
+ readonly validate?: InputValidator<InferInput<S>>;
88
+ }, handler: Handler<InferInput<S>, O>): WorkflowDefinition<InferInput<S>, O>;
76
89
  export declare function defineWorkflow<S extends InputShape, O = unknown>(input: InputSchema<S>, handler: Handler<InferInput<S>, O>): WorkflowDefinition<InferInput<S>, O>;
90
+ export declare function defineWorkflow<I = Record<string, unknown>, O = unknown>(config: WorkflowConfig & {
91
+ readonly input?: undefined;
92
+ readonly validate?: InputValidator<I>;
93
+ }, handler: Handler<I, O>): WorkflowDefinition<I, O>;
77
94
  export declare function defineWorkflow<I = Record<string, unknown>, O = unknown>(handler: Handler<I, O>): WorkflowDefinition<I, O>;
78
95
  export type ResponseOutput = {
79
96
  $response_status: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diagonal-hq/workflows",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "The authoring API of Diagonal managed workflows, their capabilities, and the workflow test helpers.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
@@ -19,10 +19,6 @@
19
19
  "types": "./dist/profiles/test.d.ts",
20
20
  "default": "./dist/profiles/test.js"
21
21
  },
22
- "./migration": {
23
- "types": "./dist/profiles/migration.d.ts",
24
- "default": "./dist/profiles/migration.js"
25
- },
26
22
  "./testing": {
27
23
  "types": "./dist/testing/index.d.ts",
28
24
  "default": "./dist/testing/index.js"
File without changes
@@ -1,155 +0,0 @@
1
- import { data as rootData } from "../../data.js";
2
- import { calendar as rootCalendar, callback as rootCallback, chart as rootChart, date as rootDate, file as rootFile, guard as rootGuard, lifecycle as rootLifecycle, mail as rootMail, markdown as rootMarkdown, mediaLibrary as rootMediaLibrary, money as rootMoney, notification as rootNotification, number as rootNumber, package as rootPackage, page as rootPage, payables as rootPayables, payment as rootPayment, phone as rootPhone, scheduling as rootScheduling, schema as rootSchema, security as rootSecurity, subscriptions as rootSubscriptions, text as rootText, time as rootTime, timezone as rootTimezone, tiptap as rootTiptap, user as rootUser, workflow as rootWorkflow, workspace as rootWorkspace } from "../capabilities.js";
3
- export declare const calendar: {
4
- generateLink: typeof rootCalendar.generateLink;
5
- searchEvents: typeof rootCalendar.searchEvents;
6
- };
7
- export declare const callback: {
8
- get: typeof rootCallback.get;
9
- remove: typeof rootCallback.remove;
10
- set: typeof rootCallback.set;
11
- };
12
- export declare const chart: {
13
- distribution: typeof rootChart.distribution;
14
- kpi: typeof rootChart.kpi;
15
- leaderboard: typeof rootChart.leaderboard;
16
- timeSeries: typeof rootChart.timeSeries;
17
- };
18
- export declare const data: {
19
- aggregateMetrics: typeof rootData.aggregateMetrics;
20
- count: typeof rootData.count;
21
- create: typeof rootData.create;
22
- createMany: typeof rootData.createMany;
23
- delete: typeof rootData.delete;
24
- deleteMany: typeof rootData.deleteMany;
25
- find: typeof rootData.find;
26
- findOrCreate: typeof rootData.findOrCreate;
27
- relation: {
28
- attach: typeof rootData.relation.attach;
29
- attachMany: typeof rootData.relation.attachMany;
30
- detach: typeof rootData.relation.detach;
31
- detachMany: typeof rootData.relation.detachMany;
32
- sync: typeof rootData.relation.sync;
33
- };
34
- restore: typeof rootData.restore;
35
- search: typeof rootData.search;
36
- semanticSearch: typeof rootData.semanticSearch;
37
- sum: typeof rootData.sum;
38
- update: typeof rootData.update;
39
- updateOrCreate: typeof rootData.updateOrCreate;
40
- validate: typeof rootData.validate;
41
- };
42
- export declare const date: {
43
- add: typeof rootDate.add;
44
- diff: typeof rootDate.diff;
45
- endOf: typeof rootDate.endOf;
46
- format: typeof rootDate.format;
47
- startOf: typeof rootDate.startOf;
48
- subtract: typeof rootDate.subtract;
49
- };
50
- export declare const file: {
51
- changeVisibility: typeof rootFile.changeVisibility;
52
- createMediaLibraryItem: typeof rootFile.createMediaLibraryItem;
53
- createQrCode: typeof rootFile.createQrCode;
54
- };
55
- export declare const guard: {
56
- validate: typeof rootGuard.validate;
57
- };
58
- export declare const lifecycle: {
59
- output: typeof rootLifecycle.output;
60
- };
61
- export declare const mail: {
62
- search: typeof rootMail.search;
63
- };
64
- export declare const markdown: {
65
- fromContent: typeof rootMarkdown.fromContent;
66
- toContent: typeof rootMarkdown.toContent;
67
- };
68
- export declare const mediaLibrary: {
69
- createFolder: typeof rootMediaLibrary.createFolder;
70
- deleteItem: typeof rootMediaLibrary.deleteItem;
71
- moveItems: typeof rootMediaLibrary.moveItems;
72
- updateItem: typeof rootMediaLibrary.updateItem;
73
- };
74
- export declare const money: {
75
- format: typeof rootMoney.format;
76
- };
77
- export declare const notification: {
78
- setConsent: typeof rootNotification.setConsent;
79
- };
80
- export declare const number: {
81
- format: typeof rootNumber.format;
82
- };
83
- declare const package_: {
84
- installInput: typeof rootPackage.installInput;
85
- };
86
- export { package_ as package };
87
- export declare const page: {
88
- url: typeof rootPage.url;
89
- };
90
- export declare const payables: {
91
- void: typeof rootPayables.void;
92
- writeOff: typeof rootPayables.writeOff;
93
- };
94
- export declare const payment: {
95
- createManual: typeof rootPayment.createManual;
96
- };
97
- export declare const phone: {
98
- format: typeof rootPhone.format;
99
- };
100
- export declare const scheduling: {
101
- bookSlot: typeof rootScheduling.bookSlot;
102
- findSlots: typeof rootScheduling.findSlots;
103
- };
104
- export declare const schema: {
105
- toJsonSchema: typeof rootSchema.toJsonSchema;
106
- };
107
- export declare const security: {
108
- randomPassword: typeof rootSecurity.randomPassword;
109
- };
110
- export declare const subscriptions: {
111
- activate: typeof rootSubscriptions.activate;
112
- cancel: typeof rootSubscriptions.cancel;
113
- changeItems: typeof rootSubscriptions.changeItems;
114
- create: typeof rootSubscriptions.create;
115
- generateInvoice: typeof rootSubscriptions.generateInvoice;
116
- pause: typeof rootSubscriptions.pause;
117
- preview: typeof rootSubscriptions.preview;
118
- previewChange: typeof rootSubscriptions.previewChange;
119
- resume: typeof rootSubscriptions.resume;
120
- setUpcomingItems: typeof rootSubscriptions.setUpcomingItems;
121
- };
122
- export declare const text: {
123
- generate: typeof rootText.generate;
124
- hash: typeof rootText.hash;
125
- randomUuid: typeof rootText.randomUuid;
126
- toContent: typeof rootText.toContent;
127
- };
128
- export declare const time: {
129
- add: typeof rootTime.add;
130
- diff: typeof rootTime.diff;
131
- endOf: typeof rootTime.endOf;
132
- format: typeof rootTime.format;
133
- startOf: typeof rootTime.startOf;
134
- subtract: typeof rootTime.subtract;
135
- };
136
- export declare const timezone: {
137
- format: typeof rootTimezone.format;
138
- interpret: typeof rootTimezone.interpret;
139
- };
140
- export declare const tiptap: {
141
- parse: typeof rootTiptap.parse;
142
- };
143
- export declare const user: {
144
- authorize: typeof rootUser.authorize;
145
- };
146
- export declare const workflow: {
147
- url: typeof rootWorkflow.url;
148
- };
149
- export declare const workspace: {
150
- loginUrl: typeof rootWorkspace.loginUrl;
151
- setValue: typeof rootWorkspace.setValue;
152
- setValues: typeof rootWorkspace.setValues;
153
- value: typeof rootWorkspace.value;
154
- values: typeof rootWorkspace.values;
155
- };
@@ -1,9 +0,0 @@
1
- import "../console.js";
2
- import { data as rootData } from "../data.js";
3
- import { data as migrationData } from "../generated/profiles/migration.js";
4
- export * from "./shared.js";
5
- export * from "../generated/profiles/migration.js";
6
- export { transaction } from "../transaction.js";
7
- export declare const data: typeof migrationData & {
8
- each: typeof rootData.each;
9
- };
@@ -1,255 +0,0 @@
1
- import "../chunks/chunk-CSWWU6TP.js";
2
- import {
3
- calendar,
4
- callback,
5
- chart,
6
- data,
7
- date,
8
- file,
9
- guard,
10
- lifecycle,
11
- mail,
12
- markdown,
13
- mediaLibrary,
14
- money,
15
- notification,
16
- number,
17
- package_,
18
- page,
19
- payables,
20
- payment,
21
- phone,
22
- scheduling,
23
- schema,
24
- security,
25
- subscriptions,
26
- text,
27
- time,
28
- timezone,
29
- tiptap,
30
- transaction,
31
- user,
32
- workflow,
33
- workspace
34
- } from "../chunks/chunk-KXVTSLCN.js";
35
- import {
36
- InputField,
37
- InputSchema,
38
- defineWorkflow,
39
- parseWorkflowInput,
40
- redirect,
41
- respond,
42
- v,
43
- validateWorkflowInput
44
- } from "../chunks/chunk-RWZW4V74.js";
45
- import {
46
- HostError,
47
- WorkflowFailure,
48
- fail,
49
- validationError
50
- } from "../chunks/chunk-OF5QITP7.js";
51
-
52
- // packages/workflows/src/generated/profiles/migration.ts
53
- var calendar2 = {
54
- generateLink: calendar.generateLink,
55
- searchEvents: calendar.searchEvents
56
- };
57
- var callback2 = {
58
- get: callback.get,
59
- remove: callback.remove,
60
- set: callback.set
61
- };
62
- var chart2 = {
63
- distribution: chart.distribution,
64
- kpi: chart.kpi,
65
- leaderboard: chart.leaderboard,
66
- timeSeries: chart.timeSeries
67
- };
68
- var data2 = {
69
- aggregateMetrics: data.aggregateMetrics,
70
- count: data.count,
71
- create: data.create,
72
- createMany: data.createMany,
73
- delete: data.delete,
74
- deleteMany: data.deleteMany,
75
- find: data.find,
76
- findOrCreate: data.findOrCreate,
77
- relation: {
78
- attach: data.relation.attach,
79
- attachMany: data.relation.attachMany,
80
- detach: data.relation.detach,
81
- detachMany: data.relation.detachMany,
82
- sync: data.relation.sync
83
- },
84
- restore: data.restore,
85
- search: data.search,
86
- semanticSearch: data.semanticSearch,
87
- sum: data.sum,
88
- update: data.update,
89
- updateOrCreate: data.updateOrCreate,
90
- validate: data.validate
91
- };
92
- var date2 = {
93
- add: date.add,
94
- diff: date.diff,
95
- endOf: date.endOf,
96
- format: date.format,
97
- startOf: date.startOf,
98
- subtract: date.subtract
99
- };
100
- var file2 = {
101
- changeVisibility: file.changeVisibility,
102
- createMediaLibraryItem: file.createMediaLibraryItem,
103
- createQrCode: file.createQrCode
104
- };
105
- var guard2 = {
106
- validate: guard.validate
107
- };
108
- var lifecycle2 = {
109
- output: lifecycle.output
110
- };
111
- var mail2 = {
112
- search: mail.search
113
- };
114
- var markdown2 = {
115
- fromContent: markdown.fromContent,
116
- toContent: markdown.toContent
117
- };
118
- var mediaLibrary2 = {
119
- createFolder: mediaLibrary.createFolder,
120
- deleteItem: mediaLibrary.deleteItem,
121
- moveItems: mediaLibrary.moveItems,
122
- updateItem: mediaLibrary.updateItem
123
- };
124
- var money2 = {
125
- format: money.format
126
- };
127
- var notification2 = {
128
- setConsent: notification.setConsent
129
- };
130
- var number2 = {
131
- format: number.format
132
- };
133
- var package_2 = {
134
- installInput: package_.installInput
135
- };
136
- var page2 = {
137
- url: page.url
138
- };
139
- var payables2 = {
140
- void: payables.void,
141
- writeOff: payables.writeOff
142
- };
143
- var payment2 = {
144
- createManual: payment.createManual
145
- };
146
- var phone2 = {
147
- format: phone.format
148
- };
149
- var scheduling2 = {
150
- bookSlot: scheduling.bookSlot,
151
- findSlots: scheduling.findSlots
152
- };
153
- var schema2 = {
154
- toJsonSchema: schema.toJsonSchema
155
- };
156
- var security2 = {
157
- randomPassword: security.randomPassword
158
- };
159
- var subscriptions2 = {
160
- activate: subscriptions.activate,
161
- cancel: subscriptions.cancel,
162
- changeItems: subscriptions.changeItems,
163
- create: subscriptions.create,
164
- generateInvoice: subscriptions.generateInvoice,
165
- pause: subscriptions.pause,
166
- preview: subscriptions.preview,
167
- previewChange: subscriptions.previewChange,
168
- resume: subscriptions.resume,
169
- setUpcomingItems: subscriptions.setUpcomingItems
170
- };
171
- var text2 = {
172
- generate: text.generate,
173
- hash: text.hash,
174
- randomUuid: text.randomUuid,
175
- toContent: text.toContent
176
- };
177
- var time2 = {
178
- add: time.add,
179
- diff: time.diff,
180
- endOf: time.endOf,
181
- format: time.format,
182
- startOf: time.startOf,
183
- subtract: time.subtract
184
- };
185
- var timezone2 = {
186
- format: timezone.format,
187
- interpret: timezone.interpret
188
- };
189
- var tiptap2 = {
190
- parse: tiptap.parse
191
- };
192
- var user2 = {
193
- authorize: user.authorize
194
- };
195
- var workflow2 = {
196
- url: workflow.url
197
- };
198
- var workspace2 = {
199
- loginUrl: workspace.loginUrl,
200
- setValue: workspace.setValue,
201
- setValues: workspace.setValues,
202
- value: workspace.value,
203
- values: workspace.values
204
- };
205
-
206
- // packages/workflows/src/profiles/migration.ts
207
- var data3 = {
208
- ...data2,
209
- each: data.each
210
- };
211
- export {
212
- HostError,
213
- InputField,
214
- InputSchema,
215
- WorkflowFailure,
216
- calendar2 as calendar,
217
- callback2 as callback,
218
- chart2 as chart,
219
- data3 as data,
220
- date2 as date,
221
- defineWorkflow,
222
- fail,
223
- file2 as file,
224
- guard2 as guard,
225
- lifecycle2 as lifecycle,
226
- mail2 as mail,
227
- markdown2 as markdown,
228
- mediaLibrary2 as mediaLibrary,
229
- money2 as money,
230
- notification2 as notification,
231
- number2 as number,
232
- package_2 as package,
233
- page2 as page,
234
- parseWorkflowInput,
235
- payables2 as payables,
236
- payment2 as payment,
237
- phone2 as phone,
238
- redirect,
239
- respond,
240
- scheduling2 as scheduling,
241
- schema2 as schema,
242
- security2 as security,
243
- subscriptions2 as subscriptions,
244
- text2 as text,
245
- time2 as time,
246
- timezone2 as timezone,
247
- tiptap2 as tiptap,
248
- transaction,
249
- user2 as user,
250
- v,
251
- validateWorkflowInput,
252
- validationError,
253
- workflow2 as workflow,
254
- workspace2 as workspace
255
- };