@diagonal-hq/workflows 0.3.1 → 0.5.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.
@@ -1,4 +1,4 @@
1
1
  export { HostError, WorkflowFailure, fail, validationError } from "../errors.js";
2
2
  export { InputField, InputSchema, v, type ContentDocument, type ContentNode, type ContentOptions, type FileVisibility, type Infer, type InferInput, type InputFieldKind, type InputFieldSpec, type InputShape, type Money, type RecordScope } from "../input.js";
3
3
  export { defineWorkflow, parseWorkflowInput, redirect, respond, validateWorkflowInput, type Identity, type InputErrors, type InputValidator, type RequestContext, type ScriptExecution, type WorkflowContext, type WorkflowDefinition, type WorkflowExecution } from "../workflow.js";
4
- export type { ScriptHostContext, WorkspaceNotificationTypes, WorkspaceResources } from "../index.js";
4
+ export type { ScriptHostContext, WorkspaceFieldCatalog, WorkspaceNotificationTypes, WorkspaceResources } from "../index.js";
@@ -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-7MUIXOH5.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;
@@ -0,0 +1,36 @@
1
+ import { type WorkspaceSystemFields } from "./generated/capabilities.js";
2
+ import type { WorkspaceFieldCatalog } from "./index.js";
3
+ type Fields = Omit<WorkspaceSystemFields, keyof WorkspaceFieldCatalog> & WorkspaceFieldCatalog;
4
+ type Property<T, K extends string> = T extends null | undefined ? never : T extends readonly (infer Item)[] ? K extends `${number}` ? K extends keyof T ? T[K] : Item : unknown : T extends object ? K extends keyof T ? T[K] : unknown : unknown;
5
+ type PathValue<T, P extends string> = P extends `${infer Head}.${infer Tail}` ? PathValue<Property<T, Head>, Tail> : Property<T, P>;
6
+ export type WorkspaceValue<K extends string> = K extends keyof Fields ? Fields[K] : K extends `${infer Key}.${infer Path}` ? Key extends keyof Fields ? PathValue<Fields[Key], Path> : unknown : unknown;
7
+ type DefaultValue<D> = Exclude<D, undefined> | (undefined extends D ? null : never);
8
+ type ReadValue<K extends string, D> = Exclude<WorkspaceValue<K>, null | undefined> | DefaultValue<D>;
9
+ type WriteValue<K extends string> = K extends keyof Fields ? Fields[K] | null : unknown;
10
+ type WrittenValues<V> = {
11
+ [K in keyof V]: K extends string ? WriteValue<K> : unknown;
12
+ };
13
+ export type WorkspaceValues = {
14
+ [K in keyof Fields]: Fields[K] | null;
15
+ } & Record<string, unknown>;
16
+ declare function value<K extends string, D>(input: {
17
+ key: K;
18
+ defaultValue: D;
19
+ }): Promise<ReadValue<K, D>>;
20
+ declare function value<K extends string, D = never>(input: {
21
+ key: K;
22
+ defaultValue?: D;
23
+ }): Promise<ReadValue<K, D | undefined>>;
24
+ export declare const workspace: {
25
+ value: typeof value;
26
+ setValue: <K extends string>(input: {
27
+ key: K;
28
+ value?: WriteValue<NoInfer<K>>;
29
+ }) => Promise<WriteValue<K>>;
30
+ values: (input?: Record<never, never>) => Promise<WorkspaceValues>;
31
+ setValues: <V extends Record<string, unknown> = Record<never, never>>(input: {
32
+ values?: V & WrittenValues<NoInfer<V>>;
33
+ }) => Promise<WrittenValues<V>>;
34
+ loginUrl: (input: import("./index.js").WorkspaceLoginUrlInput) => Promise<import("./index.js").WorkspaceLoginUrlOutput>;
35
+ };
36
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diagonal-hq/workflows",
3
- "version": "0.3.1",
3
+ "version": "0.5.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
- };