@webda/workflow 0.0.0-stage → 4.0.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +166 -0
  2. package/README.md +54 -2
  3. package/lib/authoring.d.ts +112 -0
  4. package/lib/authoring.d.ts.map +1 -0
  5. package/lib/authoring.js +107 -0
  6. package/lib/authoring.js.map +1 -0
  7. package/lib/expression.d.ts +21 -0
  8. package/lib/expression.d.ts.map +1 -0
  9. package/lib/expression.js +196 -0
  10. package/lib/expression.js.map +1 -0
  11. package/lib/graph.d.ts +291 -0
  12. package/lib/graph.d.ts.map +1 -0
  13. package/lib/graph.js +72 -0
  14. package/lib/graph.js.map +1 -0
  15. package/lib/hooks.d.ts +38 -0
  16. package/lib/hooks.d.ts.map +1 -0
  17. package/lib/hooks.js +23 -0
  18. package/lib/hooks.js.map +1 -0
  19. package/lib/index.d.ts +11 -0
  20. package/lib/index.d.ts.map +1 -0
  21. package/lib/index.js +15 -0
  22. package/lib/index.js.map +1 -0
  23. package/lib/interpreter.d.ts +63 -0
  24. package/lib/interpreter.d.ts.map +1 -0
  25. package/lib/interpreter.js +330 -0
  26. package/lib/interpreter.js.map +1 -0
  27. package/lib/models/workflow.model.d.ts +71 -0
  28. package/lib/models/workflow.model.d.ts.map +1 -0
  29. package/lib/models/workflow.model.js +70 -0
  30. package/lib/models/workflow.model.js.map +1 -0
  31. package/lib/models/workflowinstance.model.d.ts +132 -0
  32. package/lib/models/workflowinstance.model.d.ts.map +1 -0
  33. package/lib/models/workflowinstance.model.js +168 -0
  34. package/lib/models/workflowinstance.model.js.map +1 -0
  35. package/lib/models/workflowsignal.model.d.ts +51 -0
  36. package/lib/models/workflowsignal.model.d.ts.map +1 -0
  37. package/lib/models/workflowsignal.model.js +53 -0
  38. package/lib/models/workflowsignal.model.js.map +1 -0
  39. package/lib/models/workflowtask.model.d.ts +103 -0
  40. package/lib/models/workflowtask.model.d.ts.map +1 -0
  41. package/lib/models/workflowtask.model.js +104 -0
  42. package/lib/models/workflowtask.model.js.map +1 -0
  43. package/lib/workflow.service.d.ts +670 -0
  44. package/lib/workflow.service.d.ts.map +1 -0
  45. package/lib/workflow.service.js +1950 -0
  46. package/lib/workflow.service.js.map +1 -0
  47. package/package.json +68 -3
  48. package/webda.module.json +2670 -0
package/LICENSE ADDED
@@ -0,0 +1,166 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
166
+
package/README.md CHANGED
@@ -1,3 +1,55 @@
1
- # Temporary Holding Version
1
+ # @webda/workflow module
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ This module is part of Webda Application Framework that allows you to quickly develop applications with all modern prerequisites: Security, Extensibility, GraphQL, REST, CloudNative [https://webda.io](https://webda.io)
4
+
5
+ <img src="https://webda.io/img/webda.svg" width="128" />
6
+
7
+ <!-- README_HEADER -->
8
+
9
+ > Durable workflows for Webda: a flow is a sequence of operations with control flow, that survives restarts, retries its tasks, sleeps and runs each step as the user who launched it.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pnpm add @webda/workflow
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```json
20
+ {
21
+ "services": {
22
+ "WorkflowService": {
23
+ "type": "Webda/WorkflowService"
24
+ }
25
+ }
26
+ }
27
+ ```
28
+
29
+ ```ts
30
+ useService<WorkflowService>("WorkflowService").registerFlow({
31
+ id: "Orders.Process",
32
+ version: "",
33
+ params: ["uuid"],
34
+ input: { type: "object", properties: { uuid: { type: "string" } } },
35
+ body: [
36
+ {
37
+ kind: "task",
38
+ id: "process/Orders.Capture",
39
+ operation: "Orders.Capture",
40
+ input: { obj: { uuid: { var: "uuid" } } },
41
+ options: { retries: 3 }
42
+ },
43
+ { kind: "task", id: "process/Workflow.Sleep", operation: "Workflow.Sleep", input: { lit: { duration: "1d" } } },
44
+ { kind: "task", id: "process/Orders.Remind", operation: "Orders.Remind", input: { obj: { uuid: { var: "uuid" } } } }
45
+ ],
46
+ source: "code"
47
+ });
48
+ // The operation Orders.Process launches it and returns { uuid } of the WorkflowInstance
49
+ ```
50
+
51
+ See the [documentation](https://docs.webda.io/pages/Modules/workflow/README) for the graph format, the built-in
52
+ operations, the task options and the engine parameters.
53
+
54
+ Operations run by a workflow should observe `useAbortSignal()` (aborted on timeout, lost lease and stop) to stop
55
+ early. An attempt that keeps running is ignored and the task may run again: operations are assumed to be idempotent.
@@ -0,0 +1,112 @@
1
+ /**
2
+ * The authoring API of `.flow.ts` files
3
+ *
4
+ * A flow is an `async` method of a class extending {@link Workflow}, in a file ending with `.flow.ts`. Its body is
5
+ * never executed: the build compiles it into a workflow graph that {@link WorkflowService} runs. Everything here is
6
+ * a typed stub that throws if it is ever called.
7
+ *
8
+ * Operations are called as `<ServiceClass>.<Method>(input, options?)` and other flows as
9
+ * `<FlowClass>.<Method>(input, options?)`: `@webda/content-mapper` declares those calls in each `.flow.ts` file.
10
+ */
11
+ import type { TaskOptions } from "./graph.js";
12
+ export type { TaskOptions };
13
+ declare global {
14
+ interface DateConstructor {
15
+ /**
16
+ * Current time in milliseconds, recorded by the flow: a retry or a resume reads the recorded value
17
+ *
18
+ * Only available in a `.flow.ts` flow.
19
+ */
20
+ Now(): Promise<number>;
21
+ }
22
+ }
23
+ /**
24
+ * Base class of the flow classes of a `.flow.ts` file: each `async` method is a flow `<Class>.<Method>`
25
+ */
26
+ export declare abstract class Workflow {
27
+ /**
28
+ * Flow classes are never instantiated
29
+ */
30
+ constructor();
31
+ /**
32
+ * Run a body for each item concurrently (a `map` statement)
33
+ * @param _items - the items
34
+ * @param _fn - a single call, or an async block, run for each item
35
+ * @param _options - options
36
+ * @param _options.concurrency - maximum number of items running at once
37
+ * @returns the value of each item, in order
38
+ */
39
+ static Parallel<T, R>(_items: T[], _fn: (item: T) => Promise<R>, _options?: {
40
+ concurrency?: number;
41
+ }): Promise<R[]>;
42
+ /**
43
+ * Start a child flow without waiting for it
44
+ * @param _flow - the child flow, as `OtherFlows.Method`
45
+ * @param _input - its input
46
+ * @returns the uuid of the child instance
47
+ */
48
+ static Start<I>(_flow: (input: I, options?: TaskOptions) => Promise<any>, _input: I): Promise<{
49
+ uuid: string;
50
+ }>;
51
+ /**
52
+ * Call any operation by id, untyped: model operations (`Order.Query`) or operations of other packages
53
+ * @param _operationId - the operation id, a string literal
54
+ * @param _input - its input
55
+ * @param _options - task options
56
+ * @returns the operation result
57
+ */
58
+ static Call<R = any>(_operationId: string, _input?: Record<string, any>, _options?: TaskOptions): Promise<R>;
59
+ }
60
+ /**
61
+ * Wait for a duration (`"1h"`) or until a time (`{ until: timestamp }`)
62
+ * @param _duration - the duration, or the end time
63
+ * @returns when the timer fires
64
+ */
65
+ export declare function Sleep(_duration: string | {
66
+ until: number;
67
+ }): Promise<void>;
68
+ /**
69
+ * Signals
70
+ */
71
+ export declare const Wait: {
72
+ /**
73
+ * Wait for the signal `name` sent with `key` (`Workflow.Signal`): its payload is the result
74
+ * @param _name - the event name
75
+ * @param _options - options
76
+ * @param _options.key - key to match
77
+ * @param _options.timeout - Duration after which the wait throws
78
+ * @param _options.allow - user ids that may send it besides the launcher
79
+ * @returns the signal payload
80
+ */
81
+ ForEvent<T = any>(_name: string, _options: {
82
+ key: string;
83
+ timeout?: string;
84
+ allow?: string[];
85
+ }): Promise<T>;
86
+ };
87
+ /**
88
+ * Random values, recorded by the flow
89
+ */
90
+ export declare const Random: {
91
+ /**
92
+ * A number in [0, 1)
93
+ * @returns the number
94
+ */
95
+ Number(): Promise<number>;
96
+ /**
97
+ * A UUID
98
+ * @returns the uuid
99
+ */
100
+ Uuid(): Promise<string>;
101
+ };
102
+ /**
103
+ * Launch a flow on a schedule, read by the build: every argument must be a literal
104
+ *
105
+ * Several are allowed. The launch runs as the system.
106
+ * @param _cron - cron expression
107
+ * @param _description - description
108
+ * @param _input - the flow input
109
+ * @returns a decorator that changes nothing
110
+ */
111
+ export declare function Cron(_cron: string, _description?: string, _input?: Record<string, any>): <T>(value: T, _context: ClassMethodDecoratorContext<Workflow>) => T;
112
+ //# sourceMappingURL=authoring.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authoring.d.ts","sources":["../src/authoring.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,YAAY,EAAE,WAAW,EAAE,CAAC;AAa5B,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,eAAe;QACvB;;;;WAIG;QACH,GAAG,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;KACxB;CACF;AAED;;GAEG;AACH,8BAAsB,QAAQ;IAC5B;;OAEG;IACH,cAEC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,EAAE;QAAE,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,CAAC,EAAE,CAAC,CAElH;IAED;;;;;OAKG;IACH,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,CAAC,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAE9G;IAED;;;;;;OAMG;IACH,MAAM,CAAC,IAAI,CAAC,CAAC,GAAG,GAAG,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,QAAQ,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC,CAE3G;CACF;AAED;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,SAAS,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAE1E;AAED;;GAEG;AACH,eAAO,MAAM,IAAI;IACf;;;;;;;;OAQG;IACH,QAAQ,CAAC,CAAC,GAAG,GAAG,SAAS,MAAM,YAAY;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,GAAG,OAAO,CAAC,CAAC,CAAC;CAG5G,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,MAAM;IACjB;;;OAGG;IACH,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC;IAGzB;;;OAGG;IACH,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC;CAGxB,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,IAC7E,CAAC,SAAS,CAAC,YAAY,2BAA2B,CAAC,QAAQ,CAAC,KAAG,CAAC,CACzE"}
@@ -0,0 +1,107 @@
1
+ /** Message of every stub. */
2
+ const NOT_EXECUTABLE = "Flows run through WorkflowService";
3
+ /**
4
+ * Throw: a flow body is compiled, never executed
5
+ * @returns never
6
+ */
7
+ function notExecutable() {
8
+ throw new Error(NOT_EXECUTABLE);
9
+ }
10
+ /**
11
+ * Base class of the flow classes of a `.flow.ts` file: each `async` method is a flow `<Class>.<Method>`
12
+ */
13
+ export class Workflow {
14
+ /**
15
+ * Flow classes are never instantiated
16
+ */
17
+ constructor() {
18
+ notExecutable();
19
+ }
20
+ /**
21
+ * Run a body for each item concurrently (a `map` statement)
22
+ * @param _items - the items
23
+ * @param _fn - a single call, or an async block, run for each item
24
+ * @param _options - options
25
+ * @param _options.concurrency - maximum number of items running at once
26
+ * @returns the value of each item, in order
27
+ */
28
+ static Parallel(_items, _fn, _options) {
29
+ return notExecutable();
30
+ }
31
+ /**
32
+ * Start a child flow without waiting for it
33
+ * @param _flow - the child flow, as `OtherFlows.Method`
34
+ * @param _input - its input
35
+ * @returns the uuid of the child instance
36
+ */
37
+ static Start(_flow, _input) {
38
+ return notExecutable();
39
+ }
40
+ /**
41
+ * Call any operation by id, untyped: model operations (`Order.Query`) or operations of other packages
42
+ * @param _operationId - the operation id, a string literal
43
+ * @param _input - its input
44
+ * @param _options - task options
45
+ * @returns the operation result
46
+ */
47
+ static Call(_operationId, _input, _options) {
48
+ return notExecutable();
49
+ }
50
+ }
51
+ /**
52
+ * Wait for a duration (`"1h"`) or until a time (`{ until: timestamp }`)
53
+ * @param _duration - the duration, or the end time
54
+ * @returns when the timer fires
55
+ */
56
+ export function Sleep(_duration) {
57
+ return notExecutable();
58
+ }
59
+ /**
60
+ * Signals
61
+ */
62
+ export const Wait = {
63
+ /**
64
+ * Wait for the signal `name` sent with `key` (`Workflow.Signal`): its payload is the result
65
+ * @param _name - the event name
66
+ * @param _options - options
67
+ * @param _options.key - key to match
68
+ * @param _options.timeout - Duration after which the wait throws
69
+ * @param _options.allow - user ids that may send it besides the launcher
70
+ * @returns the signal payload
71
+ */
72
+ ForEvent(_name, _options) {
73
+ return notExecutable();
74
+ }
75
+ };
76
+ /**
77
+ * Random values, recorded by the flow
78
+ */
79
+ export const Random = {
80
+ /**
81
+ * A number in [0, 1)
82
+ * @returns the number
83
+ */
84
+ Number() {
85
+ return notExecutable();
86
+ },
87
+ /**
88
+ * A UUID
89
+ * @returns the uuid
90
+ */
91
+ Uuid() {
92
+ return notExecutable();
93
+ }
94
+ };
95
+ /**
96
+ * Launch a flow on a schedule, read by the build: every argument must be a literal
97
+ *
98
+ * Several are allowed. The launch runs as the system.
99
+ * @param _cron - cron expression
100
+ * @param _description - description
101
+ * @param _input - the flow input
102
+ * @returns a decorator that changes nothing
103
+ */
104
+ export function Cron(_cron, _description, _input) {
105
+ return (value, _context) => value;
106
+ }
107
+ //# sourceMappingURL=authoring.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authoring.js","sources":["../src/authoring.ts"],"names":[],"mappings":"AAcA,6BAA6B;AAC7B,MAAM,cAAc,GAAG,mCAAmC,CAAC;AAE3D;;;GAGG;AACH,SAAS,aAAa;IACpB,MAAM,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC;AAClC,CAAC;AAaD;;GAEG;AACH,MAAM,OAAgB,QAAQ;IAC5B;;OAEG;IACH;QACE,aAAa,EAAE,CAAC;IAClB,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,QAAQ,CAAO,MAAW,EAAE,GAA4B,EAAE,QAAmC;QAClG,OAAO,aAAa,EAAE,CAAC;IACzB,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,KAAK,CAAI,KAAwD,EAAE,MAAS;QACjF,OAAO,aAAa,EAAE,CAAC;IACzB,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,IAAI,CAAU,YAAoB,EAAE,MAA4B,EAAE,QAAsB;QAC7F,OAAO,aAAa,EAAE,CAAC;IACzB,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,UAAU,KAAK,CAAC,SAAqC;IACzD,OAAO,aAAa,EAAE,CAAC;AACzB,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG;IAClB;;;;;;;;OAQG;IACH,QAAQ,CAAU,KAAa,EAAE,QAA6D;QAC5F,OAAO,aAAa,EAAE,CAAC;IACzB,CAAC;CACF,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB;;;OAGG;IACH,MAAM;QACJ,OAAO,aAAa,EAAE,CAAC;IACzB,CAAC;IACD;;;OAGG;IACH,IAAI;QACF,OAAO,aAAa,EAAE,CAAC;IACzB,CAAC;CACF,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAAC,KAAa,EAAE,YAAqB,EAAE,MAA4B;IACrF,OAAO,CAAI,KAAQ,EAAE,QAA+C,EAAK,EAAE,CAAC,KAAK,CAAC;AACpF,CAAC"}
@@ -0,0 +1,21 @@
1
+ import { type Expr } from "./graph.js";
2
+ /** Maximum length of a string produced by a flow expression */
3
+ export declare const MAX_EXPR_STRING_LENGTH = 1048576;
4
+ /**
5
+ * Evaluate a flow expression
6
+ *
7
+ * Pure: it reads `scope` and never changes it.
8
+ * @param expr - the expression
9
+ * @param scope - the variables
10
+ * @returns the value
11
+ * @throws Error on an invalid expression node
12
+ */
13
+ export declare function evaluate(expr: Expr, scope: Record<string, any>): any;
14
+ /**
15
+ * Validate an expression tree, as received from an untrusted source (a stored workflow)
16
+ * @param expr - the candidate expression
17
+ * @param path - path of this node, `$` for the root
18
+ * @returns the paths of the invalid nodes, empty when the expression is valid
19
+ */
20
+ export declare function validateExpr(expr: unknown, path?: string): string[];
21
+ //# sourceMappingURL=expression.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"expression.d.ts","sources":["../src/expression.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6B,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAElE,+DAA+D;AAC/D,eAAO,MAAM,sBAAsB,UAAY,CAAC;AAkEhD;;;;;;;;GAQG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,GAAG,CAkEpE;AAWD;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,GAAE,MAAY,GAAG,MAAM,EAAE,CA4CxE"}
@@ -0,0 +1,196 @@
1
+ import { BINARY_OPS } from "./graph.js";
2
+ /** Maximum length of a string produced by a flow expression */
3
+ export const MAX_EXPR_STRING_LENGTH = 1_048_576;
4
+ /** Object keys that must never be set on evaluated objects */
5
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
6
+ /**
7
+ * Read a member of a value: own properties only, so an expression never reaches a prototype
8
+ * @param target - the object, array or string
9
+ * @param key - the member name or index
10
+ * @returns the member, undefined when the target is null/undefined or has no such own member
11
+ */
12
+ function member(target, key) {
13
+ if (target === null || target === undefined) {
14
+ return undefined;
15
+ }
16
+ const name = typeof key === "number" ? key : String(key);
17
+ return Object.hasOwn(Object(target), name) ? target[name] : undefined;
18
+ }
19
+ /**
20
+ * Apply a binary operator to evaluated operands (the short-circuit ones are handled by the caller)
21
+ * @param op - the operator
22
+ * @param a - left value
23
+ * @param b - right value
24
+ * @returns the result
25
+ */
26
+ function binary(op, a, b) {
27
+ switch (op) {
28
+ case "==":
29
+ return a == b;
30
+ case "!=":
31
+ return a != b;
32
+ case "===":
33
+ return a === b;
34
+ case "!==":
35
+ return a !== b;
36
+ case "<":
37
+ return a < b;
38
+ case "<=":
39
+ return a <= b;
40
+ case ">":
41
+ return a > b;
42
+ case ">=":
43
+ return a >= b;
44
+ case "+": {
45
+ if (typeof a === "string" || typeof b === "string") {
46
+ const left = String(a);
47
+ const right = String(b);
48
+ if (left.length + right.length > MAX_EXPR_STRING_LENGTH) {
49
+ throw new Error("Expression string length limit exceeded");
50
+ }
51
+ return left + right;
52
+ }
53
+ return a + b;
54
+ }
55
+ case "-":
56
+ return a - b;
57
+ case "*":
58
+ return a * b;
59
+ case "/":
60
+ return a / b;
61
+ case "%":
62
+ return a % b;
63
+ }
64
+ throw new Error(`Invalid expression operator ${op}`);
65
+ }
66
+ /**
67
+ * Evaluate a flow expression
68
+ *
69
+ * Pure: it reads `scope` and never changes it.
70
+ * @param expr - the expression
71
+ * @param scope - the variables
72
+ * @returns the value
73
+ * @throws Error on an invalid expression node
74
+ */
75
+ export function evaluate(expr, scope) {
76
+ const e = expr;
77
+ if (e === null || typeof e !== "object") {
78
+ throw new Error(`Invalid expression ${JSON.stringify(e)}`);
79
+ }
80
+ if ("lit" in e) {
81
+ return e.lit;
82
+ }
83
+ if ("var" in e) {
84
+ return Object.hasOwn(scope, e.var) ? scope[e.var] : undefined;
85
+ }
86
+ if ("get" in e) {
87
+ return member(evaluate(e.get[0], scope), evaluate(e.get[1], scope));
88
+ }
89
+ if ("op" in e) {
90
+ const [left, right] = e.args;
91
+ const a = evaluate(left, scope);
92
+ switch (e.op) {
93
+ case "&&":
94
+ return a ? evaluate(right, scope) : a;
95
+ case "||":
96
+ return a ? a : evaluate(right, scope);
97
+ case "??":
98
+ return a ?? evaluate(right, scope);
99
+ }
100
+ return binary(e.op, a, evaluate(right, scope));
101
+ }
102
+ if ("not" in e) {
103
+ return !evaluate(e.not, scope);
104
+ }
105
+ if ("neg" in e) {
106
+ return -evaluate(e.neg, scope);
107
+ }
108
+ if ("cond" in e) {
109
+ return evaluate(e.cond[0], scope) ? evaluate(e.cond[1], scope) : evaluate(e.cond[2], scope);
110
+ }
111
+ if ("obj" in e) {
112
+ const res = {};
113
+ for (const [key, value] of Object.entries(e.obj)) {
114
+ if (FORBIDDEN_KEYS.has(key)) {
115
+ throw new Error(`Forbidden object key ${key}`);
116
+ }
117
+ Object.defineProperty(res, key, {
118
+ value: evaluate(value, scope),
119
+ enumerable: true,
120
+ configurable: true,
121
+ writable: true
122
+ });
123
+ }
124
+ return res;
125
+ }
126
+ if ("arr" in e) {
127
+ return e.arr.map(item => evaluate(item, scope));
128
+ }
129
+ if ("tpl" in e) {
130
+ let out = "";
131
+ for (const part of e.tpl) {
132
+ const piece = typeof part === "string" ? part : String(evaluate(part, scope));
133
+ if (out.length + piece.length > MAX_EXPR_STRING_LENGTH) {
134
+ throw new Error("Expression string length limit exceeded");
135
+ }
136
+ out += piece;
137
+ }
138
+ return out;
139
+ }
140
+ throw new Error(`Invalid expression ${JSON.stringify(e)}`);
141
+ }
142
+ /**
143
+ * Whether a value is a plain object (not an array, not null)
144
+ * @param value - the value
145
+ * @returns true for an object
146
+ */
147
+ function isObject(value) {
148
+ return value !== null && typeof value === "object" && !Array.isArray(value);
149
+ }
150
+ /**
151
+ * Validate an expression tree, as received from an untrusted source (a stored workflow)
152
+ * @param expr - the candidate expression
153
+ * @param path - path of this node, `$` for the root
154
+ * @returns the paths of the invalid nodes, empty when the expression is valid
155
+ */
156
+ export function validateExpr(expr, path = "$") {
157
+ if (!isObject(expr)) {
158
+ return [path];
159
+ }
160
+ const keys = Object.keys(expr);
161
+ const tuple = (key, length) => Array.isArray(expr[key]) && expr[key].length === length
162
+ ? expr[key].flatMap((item, i) => validateExpr(item, `${path}.${key}[${i}]`))
163
+ : [path];
164
+ if (keys.length === 2 && keys.includes("op") && keys.includes("args")) {
165
+ return BINARY_OPS.includes(expr.op) ? tuple("args", 2) : [path];
166
+ }
167
+ if (keys.length !== 1) {
168
+ return [path];
169
+ }
170
+ const value = expr[keys[0]];
171
+ switch (keys[0]) {
172
+ case "lit":
173
+ return [];
174
+ case "var":
175
+ return typeof value === "string" ? [] : [path];
176
+ case "get":
177
+ return tuple("get", 2);
178
+ case "not":
179
+ case "neg":
180
+ return validateExpr(value, `${path}.${keys[0]}`);
181
+ case "cond":
182
+ return tuple("cond", 3);
183
+ case "obj":
184
+ return isObject(value)
185
+ ? Object.entries(value).flatMap(([k, v]) => FORBIDDEN_KEYS.has(k) ? [`${path}.obj.${k}`] : validateExpr(v, `${path}.obj.${k}`))
186
+ : [path];
187
+ case "arr":
188
+ return Array.isArray(value) ? value.flatMap((v, i) => validateExpr(v, `${path}.arr[${i}]`)) : [path];
189
+ case "tpl":
190
+ return Array.isArray(value)
191
+ ? value.flatMap((v, i) => typeof v === "string" ? [] : isObject(v) ? validateExpr(v, `${path}.tpl[${i}]`) : [`${path}.tpl[${i}]`])
192
+ : [path];
193
+ }
194
+ return [path];
195
+ }
196
+ //# sourceMappingURL=expression.js.map