@protobase/workflows 0.100.2 → 0.100.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,8 @@ import { PinSchemas } from "./pins/pin-sources.js";
8
8
  * app cannot run a type it knows (`unavailable`, by step or trigger type), and the connection `<plugin>:<connection>`
9
9
  * each type that signs in uses (`connections`, by step or trigger type); without it the bindings are not checked.
10
10
  * With `pins`, the types' input and output schemas and the app's records, an argument that reads a value by name is
11
- * checked to take that value's type.
11
+ * checked to take that value's type. `versioned` names the latest version of each step type kept by version, by its id
12
+ * without one, such as `custom:invoice` for `custom:invoice:3`: a Task that names no version is refused naming it.
12
13
  */
13
14
  export type CheckOptions = {
14
15
  resources: readonly string[];
@@ -17,6 +18,7 @@ export type CheckOptions = {
17
18
  unavailable?: Readonly<Record<string, string>>;
18
19
  connections?: Readonly<Record<string, string>>;
19
20
  pins?: PinSchemas;
21
+ versioned?: Readonly<Record<string, string>>;
20
22
  };
21
23
  /**
22
24
  * Why a definition cannot be saved, as it is checked on every save: its size and nesting, its shape against `definitionSchema`, its
@@ -86,6 +86,11 @@ const machineProblems = (machine, scope, options) => {
86
86
  field: "Resource",
87
87
  message: `"${task.type}" cannot run in this app: ${options.unavailable[task.type]}`
88
88
  });
89
+ else if (task && options.versioned && Object.hasOwn(options.versioned, task.type)) problems.push({
90
+ state: where(name),
91
+ field: "Resource",
92
+ message: `"${task.type}" names no version: write ${options.versioned[task.type]}`
93
+ });
89
94
  else if (task && !options.resources.includes(task.type)) problems.push({
90
95
  state: where(name),
91
96
  field: "Resource",
@@ -0,0 +1,12 @@
1
+ //#region src/definition/import/http-connection.d.ts
2
+ /**
3
+ * What an HTTP task's connection sends in this app: a header holding a secret, its whole value, such as `Bearer ...`;
4
+ * null sends nothing in its place.
5
+ */
6
+ export type ConnectionHeader = {
7
+ header: string;
8
+ secret: string;
9
+ } | null;
10
+ /** The header each connection sends, by the connection's ARN, as the import is given them. */
11
+ export type ConnectionHeaders = Record<string, ConnectionHeader>;
12
+ //#endregion
@@ -0,0 +1,84 @@
1
+ import { expressionSource } from "../expressions.js";
2
+ //#region src/definition/import/http-connection.ts
3
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4
+ const secretName = /^[A-Za-z_][A-Za-z0-9_]*$/;
5
+ const literalNames = /* @__PURE__ */ new Set([
6
+ "true",
7
+ "false",
8
+ "null"
9
+ ]);
10
+ const headerName = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
11
+ const asked = (arn) => `names a connection, whose credentials this app does not hold: pass connection_headers { ${JSON.stringify(arn)}: { "header": "Authorization", "secret": "<NAME>" } }, the header its credentials go in and a secret workflows.secrets lists that holds the header's whole value, such as "Bearer ...", or null to send none`;
12
+ /**
13
+ * The ARN of the connection an HTTP task's `Authentication` or `InvocationConfig` names, or the problems that keep it
14
+ * from being read: both or neither given, another field beside `ConnectionArn`, or the ARN as an expression.
15
+ */
16
+ const connectionOf = (args, state) => {
17
+ const given = ["Authentication", "InvocationConfig"].filter((field) => args[field] !== void 0);
18
+ if (given.length === 0) return { problems: [] };
19
+ if (given.length > 1) return { problems: [{
20
+ state,
21
+ field: "Arguments.InvocationConfig",
22
+ message: "is given beside Authentication: an HTTP task names one connection"
23
+ }] };
24
+ const field = given[0];
25
+ const connection = args[field];
26
+ if (!isObject(connection)) return { problems: [{
27
+ state,
28
+ field: `Arguments.${field}`,
29
+ message: "is not { \"ConnectionArn\": \"...\" }"
30
+ }] };
31
+ const problems = Object.keys(connection).filter((key) => key !== "ConnectionArn").map((key) => ({
32
+ state,
33
+ field: `Arguments.${field}.${key}`,
34
+ message: "has no counterpart here: an HTTP task imports with its ConnectionArn alone"
35
+ }));
36
+ const arn = connection.ConnectionArn;
37
+ if (typeof arn !== "string" || expressionSource(arn) !== void 0) problems.push({
38
+ state,
39
+ field: `Arguments.${field}.ConnectionArn`,
40
+ message: "is not an ARN written out, which the import needs to know its header"
41
+ });
42
+ if (problems.length > 0) return { problems };
43
+ return {
44
+ arn,
45
+ field: `Arguments.${field}.ConnectionArn`,
46
+ problems: []
47
+ };
48
+ };
49
+ /** The problem with the header given for a connection, if any. */
50
+ const connectionHeaderProblem = (arn, given, state, field) => {
51
+ if (!Object.hasOwn(given, arn)) return {
52
+ state,
53
+ field,
54
+ message: asked(arn)
55
+ };
56
+ const header = given[arn];
57
+ if (header === null) return;
58
+ if (!isObject(header) || typeof header.header !== "string" || !headerName.test(header.header)) return {
59
+ state,
60
+ field,
61
+ message: `has a connection_headers entry whose header is not a header name: ${asked(arn)}`
62
+ };
63
+ if (typeof header.secret !== "string" || !secretName.test(header.secret) || literalNames.has(header.secret)) return {
64
+ state,
65
+ field,
66
+ message: `has a connection_headers entry whose secret is not a secret's name: ${asked(arn)}`
67
+ };
68
+ };
69
+ /**
70
+ * The request's headers with the connection's header added, taking the place of a header of that name in any case,
71
+ * as a connection's header wins in Step Functions; headers written as an expression are merged when the step runs.
72
+ */
73
+ const withConnectionHeader = (headers, { header, secret }) => {
74
+ const value = `{% $states.context.Secrets.${secret} %}`;
75
+ const source = expressionSource(headers);
76
+ if (source !== void 0) return `{% $merge([{}, $sift((${source}), function($value, $name) { $lowercase($name) != ${JSON.stringify(header.toLowerCase())} }), { ${JSON.stringify(header)}: $states.context.Secrets.${secret} }]) %}`;
77
+ const kept = Object.entries(isObject(headers) ? headers : {}).filter(([name]) => name.toLowerCase() !== header.toLowerCase());
78
+ return {
79
+ ...Object.fromEntries(kept),
80
+ [header]: value
81
+ };
82
+ };
83
+ //#endregion
84
+ export { connectionHeaderProblem, connectionOf, withConnectionHeader };
@@ -0,0 +1,130 @@
1
+ import { fieldPath } from "../problem.js";
2
+ import { expressionSource } from "../expressions.js";
3
+ import { connectionHeaderProblem, connectionOf, withConnectionHeader } from "./http-connection.js";
4
+ import { httpTaskResult, templateWithHttpTaskResult } from "./result-shape.js";
5
+ //#region src/definition/import/http-task.ts
6
+ /** The resource of the Step Functions HTTP task. */
7
+ const httpTaskResource = "arn:aws:states:::http:invoke";
8
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9
+ const argumentNames = {
10
+ ApiEndpoint: "url",
11
+ Method: "method",
12
+ Headers: "headers",
13
+ QueryParameters: "query",
14
+ RequestBody: "body"
15
+ };
16
+ const connectionFields = ["Authentication", "InvocationConfig"];
17
+ const unsentMethods = ["HEAD", "OPTIONS"];
18
+ const unreachedRead = "reads the HTTP task's result as a whole or in a form the import does not rewrite, such as $states . result: read its fields as $states.result.ResponseBody, $states.result.StatusCode, $states.result.StatusText and $states.result.Headers, or the result as $states.result";
19
+ const otherArgument = (key) => key === "Transform" ? "encodes the body as a form, which app:http does not do; send the body as text with a Content-Type header instead" : "is not an argument of the HTTP task this app imports";
20
+ const textRecordProblems = (value, state, field) => {
21
+ if (value === void 0 || expressionSource(value) !== void 0) return [];
22
+ if (!isObject(value)) return [{
23
+ state,
24
+ field,
25
+ message: "is not an object: app:http takes an object of text values"
26
+ }];
27
+ return Object.entries(value).filter(([, item]) => Array.isArray(item) || isObject(item)).map(([name]) => ({
28
+ state,
29
+ field: `${field}.${name}`,
30
+ message: "holds a list or an object: app:http sends one text value per name"
31
+ }));
32
+ };
33
+ const methodProblems = (args, state) => {
34
+ const method = args.Method;
35
+ if (typeof method !== "string" || expressionSource(method) !== void 0) return [];
36
+ const upper = method.toUpperCase();
37
+ if (unsentMethods.includes(upper)) return [{
38
+ state,
39
+ field: "Arguments.Method",
40
+ message: `is ${upper}, which app:http does not send: it sends GET, POST, PUT, PATCH and DELETE`
41
+ }];
42
+ if (upper === "GET" && args.RequestBody !== void 0) return [{
43
+ state,
44
+ field: "Arguments.RequestBody",
45
+ message: "is given with GET, which app:http sends without a body: send it with POST, PUT or PATCH"
46
+ }];
47
+ return [];
48
+ };
49
+ const errorProblem = (name) => {
50
+ if (name.startsWith("States.Http.StatusCode.")) return "is a single status, which app:http does not tell apart: it fails with Http.Status for every status outside 2xx";
51
+ if (name === "States.Http.Socket") return "is the HTTP task's timeout, which app:http does not fail with: it fails with Http.Network when no answer comes, and States.Timeout after the Task's TimeoutSeconds";
52
+ if (name === "States.TaskFailed") return "here matches only an error a step type does not name, never app:http's own: name Http.Status, Http.Network and the others list_workflow_types gives, or States.ALL";
53
+ if (name.startsWith("States.Http.") || name.startsWith("Events.ConnectionResource.")) return "is an error of the HTTP task or its connection, which app:http does not fail with";
54
+ };
55
+ const errorsProblems = (state, where) => ["Retry", "Catch"].flatMap((field) => (Array.isArray(state[field]) ? state[field] : []).flatMap((rule, index) => {
56
+ return (isObject(rule) && Array.isArray(rule.ErrorEquals) ? rule.ErrorEquals : []).flatMap((name, at) => {
57
+ const message = typeof name === "string" ? errorProblem(name) : void 0;
58
+ return message ? [{
59
+ state: where,
60
+ field: `${field}[${index}].ErrorEquals[${at}]`,
61
+ message: `is ${name}, which ${message}`
62
+ }] : [];
63
+ });
64
+ }));
65
+ const httpArguments = (args, header) => {
66
+ const mapped = Object.fromEntries(Object.entries(argumentNames).filter(([from]) => args[from] !== void 0).map(([from, to]) => [to, args[from]]));
67
+ if (args.RequestBody !== void 0) mapped.body_encoding = "json";
68
+ if (header) mapped.headers = withConnectionHeader(mapped.headers, header);
69
+ return mapped;
70
+ };
71
+ /**
72
+ * An HTTP task in JSONata as an app:http step that sends the same request and gives the same result, or the problems
73
+ * that keep it from doing so exactly, each by name: its arguments, method, connection and errors. Its `Output` and
74
+ * `Assign` read the HTTP task's result, `{ StatusCode, StatusText, Headers, ResponseBody }`, and without an `Output` it
75
+ * gives that, so later states read what they read in Step Functions.
76
+ */
77
+ const importHttpTask = (state, where, connections) => {
78
+ const args = state.Arguments;
79
+ if (!isObject(args)) return {
80
+ state,
81
+ problems: [{
82
+ state: where,
83
+ field: "Arguments",
84
+ message: args === void 0 ? "is missing: an HTTP task gives at least its ApiEndpoint and Method" : "is one expression, whose fields the import cannot tell apart: write ApiEndpoint, Method, Headers, QueryParameters and RequestBody each as a field of Arguments"
85
+ }]
86
+ };
87
+ const connection = connectionOf(args, where);
88
+ const problems = [
89
+ ...Object.keys(args).filter((key) => !Object.hasOwn(argumentNames, key) && !connectionFields.includes(key)).map((key) => ({
90
+ state: where,
91
+ field: `Arguments.${key}`,
92
+ message: otherArgument(key)
93
+ })),
94
+ ...methodProblems(args, where),
95
+ ...textRecordProblems(args.Headers, where, "Arguments.Headers"),
96
+ ...textRecordProblems(args.QueryParameters, where, "Arguments.QueryParameters"),
97
+ ...connection.problems,
98
+ ...errorsProblems(state, where)
99
+ ];
100
+ const headerProblem = connection.arn !== void 0 ? connectionHeaderProblem(connection.arn, connections, where, connection.field) : void 0;
101
+ if (headerProblem) problems.push(headerProblem);
102
+ const output = state.Output === void 0 ? {
103
+ value: `{% ${httpTaskResult} %}`,
104
+ unreached: []
105
+ } : templateWithHttpTaskResult(state.Output, ["Output"]);
106
+ const assign = state.Assign === void 0 ? void 0 : templateWithHttpTaskResult(state.Assign, ["Assign"]);
107
+ for (const path of [...output.unreached, ...assign?.unreached ?? []]) problems.push({
108
+ state: where,
109
+ field: fieldPath(path),
110
+ message: unreachedRead
111
+ });
112
+ if (problems.length > 0) return {
113
+ state,
114
+ problems
115
+ };
116
+ const header = connection.arn !== void 0 ? connections[connection.arn] : null;
117
+ const imported = {
118
+ ...state,
119
+ Resource: "app:http",
120
+ Arguments: httpArguments(args, header),
121
+ Output: output.value
122
+ };
123
+ if (assign) imported.Assign = assign.value;
124
+ return {
125
+ state: imported,
126
+ problems: []
127
+ };
128
+ };
129
+ //#endregion
130
+ export { httpTaskResource, importHttpTask };
@@ -0,0 +1,13 @@
1
+ import { Problem } from "../problem.js";
2
+ import { ConnectionHeaders } from "./http-connection.js";
3
+ //#region src/definition/import/import-machine.d.ts
4
+ /**
5
+ * A state machine exported from Step Functions with each of its HTTP tasks, in Maps and Blocks too, as an app:http step
6
+ * (see `importHttpTask`), each connection sending the header `connections` gives for it; every other state as it is.
7
+ * With problems, nothing should be saved: each names the state and field that does not import exactly.
8
+ */
9
+ export declare const importStateMachine: (machine: Record<string, unknown>, connections?: ConnectionHeaders) => {
10
+ stateMachine: Record<string, unknown>;
11
+ problems: Problem[];
12
+ };
13
+ //#endregion
@@ -0,0 +1,58 @@
1
+ import { importHttpTask } from "./http-task.js";
2
+ //#region src/definition/import/import-machine.ts
3
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4
+ const innerFields = [
5
+ "ItemProcessor",
6
+ "Iterator",
7
+ "Processor"
8
+ ];
9
+ const importStates = (states, path, connections) => {
10
+ if (!isObject(states)) return {
11
+ states,
12
+ problems: []
13
+ };
14
+ const problems = [];
15
+ return {
16
+ states: Object.fromEntries(Object.entries(states).map(([name, state]) => {
17
+ if (!isObject(state)) return [name, state];
18
+ let next = state;
19
+ if (state.Type === "Task" && state.Resource === "arn:aws:states:::http:invoke" && state.Parameters === void 0) {
20
+ const result = importHttpTask(state, [...path, name].join("/"), connections);
21
+ problems.push(...result.problems);
22
+ next = result.state;
23
+ }
24
+ for (const field of innerFields) {
25
+ const inner = next[field];
26
+ if (!isObject(inner)) continue;
27
+ const result = importStates(inner.States, [...path, name], connections);
28
+ problems.push(...result.problems);
29
+ next = {
30
+ ...next,
31
+ [field]: {
32
+ ...inner,
33
+ States: result.states
34
+ }
35
+ };
36
+ }
37
+ return [name, next];
38
+ })),
39
+ problems
40
+ };
41
+ };
42
+ /**
43
+ * A state machine exported from Step Functions with each of its HTTP tasks, in Maps and Blocks too, as an app:http step
44
+ * (see `importHttpTask`), each connection sending the header `connections` gives for it; every other state as it is.
45
+ * With problems, nothing should be saved: each names the state and field that does not import exactly.
46
+ */
47
+ const importStateMachine = (machine, connections = {}) => {
48
+ const { states, problems } = importStates(machine.States, [], connections);
49
+ return {
50
+ stateMachine: machine.States === void 0 ? machine : {
51
+ ...machine,
52
+ States: states
53
+ },
54
+ problems
55
+ };
56
+ };
57
+ //#endregion
58
+ export { importStateMachine };
@@ -0,0 +1,113 @@
1
+ import { expressionSource, parse } from "../expressions.js";
2
+ import { expressionReads } from "../reads.js";
3
+ //#region src/definition/import/result-shape.ts
4
+ /**
5
+ * The HTTP task's result, `{ StatusCode, StatusText, Headers, ResponseBody }` with each header's values as a list, as
6
+ * JSONata built from app:http's `{ status, status_text, headers, body }`.
7
+ */
8
+ const httpTaskResult = "({ \"StatusCode\": $states.result.status, \"StatusText\": $states.result.status_text, \"Headers\": $merge([{}, $each($states.result.headers, function($value, $name) { { $name: [$value] } })]), \"ResponseBody\": $states.result.body })";
9
+ const readsPerResult = 4;
10
+ const read = "$states.result";
11
+ const nameCharacter = /[\w$]/;
12
+ const operandEnd = /[\w$)\]}"'`]/;
13
+ const closing = (source, start) => {
14
+ const quote = source[start];
15
+ for (let at = start + 1; at < source.length; at++) if (source[at] === "\\") at++;
16
+ else if (source[at] === quote) return at + 1;
17
+ return source.length;
18
+ };
19
+ const lastSignificant = (text) => text.trimEnd().at(-1) ?? "";
20
+ const replaced = (source) => {
21
+ let rewritten = "";
22
+ let count = 0;
23
+ let at = 0;
24
+ while (at < source.length) {
25
+ const character = source[at];
26
+ const regex = character === "/" && source[at + 1] !== "*" && !operandEnd.test(lastSignificant(rewritten));
27
+ if (character === "\"" || character === "'" || character === "`" || regex) {
28
+ const end = closing(source, at);
29
+ rewritten += source.slice(at, end);
30
+ at = end;
31
+ continue;
32
+ }
33
+ if (source.startsWith("/*", at)) {
34
+ const end = source.indexOf("*/", at + 2);
35
+ const stop = end === -1 ? source.length : end + 2;
36
+ rewritten += source.slice(at, stop);
37
+ at = stop;
38
+ continue;
39
+ }
40
+ if (source.startsWith(read, at) && !nameCharacter.test(source[at + 14] ?? "") && !nameCharacter.test(source[at - 1] ?? "")) {
41
+ rewritten += httpTaskResult;
42
+ count++;
43
+ at += 14;
44
+ continue;
45
+ }
46
+ rewritten += character;
47
+ at++;
48
+ }
49
+ return {
50
+ rewritten,
51
+ count
52
+ };
53
+ };
54
+ const resultReads = (source) => {
55
+ const parsed = parse(source);
56
+ if ("error" in parsed) return;
57
+ const states = expressionReads(parsed.expression).states;
58
+ return {
59
+ count: states.filter((path) => path[0] === "result").length,
60
+ whole: states.some((path) => path.length === 0)
61
+ };
62
+ };
63
+ /**
64
+ * The expression with each read of `$states.result` reading the HTTP task's result, so `$states.result.ResponseBody`
65
+ * reads the body and a variable given the whole result keeps the HTTP task's shape; `undefined` when a read is written
66
+ * in a form the rewrite does not reach, such as `$states . result`, which the syntax tree tells. An expression that does
67
+ * not parse is left as it is, for the check to refuse.
68
+ */
69
+ const withHttpTaskResult = (source) => {
70
+ const before = resultReads(source);
71
+ if (!before) return source;
72
+ const { rewritten, count } = replaced(source);
73
+ const after = resultReads(rewritten);
74
+ if (before.whole || before.count !== count || after?.count !== count * readsPerResult) return;
75
+ return rewritten;
76
+ };
77
+ /**
78
+ * A template, such as an `Output` or an `Assign`, with every expression in it reading the HTTP task's result, and the
79
+ * path of each expression whose reads the rewrite does not reach.
80
+ */
81
+ const templateWithHttpTaskResult = (value, path = []) => {
82
+ const source = expressionSource(value);
83
+ if (source !== void 0) {
84
+ const rewritten = withHttpTaskResult(source);
85
+ return rewritten === void 0 ? {
86
+ value,
87
+ unreached: [path]
88
+ } : {
89
+ value: `{%${rewritten}%}`,
90
+ unreached: []
91
+ };
92
+ }
93
+ if (Array.isArray(value)) {
94
+ const items = value.map((item, index) => templateWithHttpTaskResult(item, [...path, index]));
95
+ return {
96
+ value: items.map((item) => item.value),
97
+ unreached: items.flatMap((item) => item.unreached)
98
+ };
99
+ }
100
+ if (typeof value === "object" && value !== null) {
101
+ const entries = Object.entries(value).map(([key, item]) => [key, templateWithHttpTaskResult(item, [...path, key])]);
102
+ return {
103
+ value: Object.fromEntries(entries.map(([key, item]) => [key, item.value])),
104
+ unreached: entries.flatMap(([, item]) => item.unreached)
105
+ };
106
+ }
107
+ return {
108
+ value,
109
+ unreached: []
110
+ };
111
+ };
112
+ //#endregion
113
+ export { httpTaskResult, templateWithHttpTaskResult, withHttpTaskResult };
@@ -8,8 +8,9 @@ export type RecordSchemas = (resource: string, use: RecordUse) => JsonSchema | u
8
8
  * A type's schema with what its arguments name filled in: `{ "x-record-of": "<argument>" }` is the record of the
9
9
  * resource that argument names, for the `x-record-use` it says (default `read`), and `{ "x-schema-of": "<argument>" }`
10
10
  * is the schema that argument holds, such as an HTTP answer's declared body, and `{ "x-one-or-many-of": "<argument>",
11
- * "anyOf": [<one>, <list>] }` is one or the list as that argument holds an object or a list. An argument that is an
12
- * expression, or a resource the app does not have, leaves the value of any type.
11
+ * "anyOf": [<one>, <list>] }` is one or the list as that argument holds an object or a list. `{ "x-file": true }` is a
12
+ * stored file, with its own title and description. An argument that is an expression, or a resource the app does not
13
+ * have, leaves the value of any type.
13
14
  */
14
15
  export declare const resolveSchema: (schema: JsonSchema, args: Record<string, unknown>, records: RecordSchemas) => JsonSchema;
15
16
  /**
@@ -1,16 +1,22 @@
1
+ import { storedFileSchema } from "../../plugin/stored-file.js";
1
2
  //#region src/definition/pins/resolve-schema.ts
2
3
  const isSchema = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
4
  /**
4
5
  * A type's schema with what its arguments name filled in: `{ "x-record-of": "<argument>" }` is the record of the
5
6
  * resource that argument names, for the `x-record-use` it says (default `read`), and `{ "x-schema-of": "<argument>" }`
6
7
  * is the schema that argument holds, such as an HTTP answer's declared body, and `{ "x-one-or-many-of": "<argument>",
7
- * "anyOf": [<one>, <list>] }` is one or the list as that argument holds an object or a list. An argument that is an
8
- * expression, or a resource the app does not have, leaves the value of any type.
8
+ * "anyOf": [<one>, <list>] }` is one or the list as that argument holds an object or a list. `{ "x-file": true }` is a
9
+ * stored file, with its own title and description. An argument that is an expression, or a resource the app does not
10
+ * have, leaves the value of any type.
9
11
  */
10
12
  const resolveSchema = (schema, args, records) => {
11
13
  const resolve = (node) => {
12
14
  if (Array.isArray(node)) return node.map(resolve);
13
15
  if (!isSchema(node)) return node;
16
+ if (node["x-file"] === true) return {
17
+ ...storedFileSchema,
18
+ ...pick(node, ["title", "description"])
19
+ };
14
20
  const recordOf = node["x-record-of"];
15
21
  if (typeof recordOf === "string") {
16
22
  const resource = args[recordOf];
@@ -34,6 +40,7 @@ const resolveSchema = (schema, args, records) => {
34
40
  return resolve(schema);
35
41
  };
36
42
  const withoutKeys = (node, keys) => Object.fromEntries(Object.entries(node).filter(([key]) => !keys.includes(key)));
43
+ const pick = (node, keys) => Object.fromEntries(Object.entries(node).filter(([key]) => keys.includes(key)));
37
44
  /**
38
45
  * The schema of the value at `path` below a value of `schema`: a property's, or a map's `additionalProperties`; for a
39
46
  * schema of several kinds, any of the branches' schemas for it. Undefined when the schema, or one of its branches,
package/dist/index.d.ts CHANGED
@@ -12,6 +12,8 @@ import { PinKind, PinType, fits, pinType, pinTypeText } from "./definition/pins/
12
12
  import { definitionWarnings } from "./definition/check-warnings.js";
13
13
  import { allStates, blockDefinition, findBlock, innerMachine } from "./definition/inner.js";
14
14
  import { usedConnections } from "./definition/used-connections.js";
15
+ import { ConnectionHeader, ConnectionHeaders } from "./definition/import/http-connection.js";
16
+ import { importStateMachine } from "./definition/import/import-machine.js";
15
17
  import { taskResource, waitSuffix, waitsForToken } from "./definition/task-resource.js";
16
18
  import { assignedNames } from "./definition/expression-fields.js";
17
19
  import { Dependencies, dependsOn, machineDependencies } from "./definition/dataflow/dependencies.js";
@@ -34,4 +36,5 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
34
36
  import { TypeEntry, Unavailable, typeList } from "./plugin/type-list.js";
35
37
  import { ConnectionSupport, connectionUnavailable } from "./plugin/connection-availability.js";
36
38
  import { CatalogEntry, TypeCatalog, typeCatalog } from "./plugin/type-catalog.js";
37
- export { type AnswerRefusal, type BlockCache, type BlockRun, type BlockRunStore, type BlockShare, type BlockState, type CacheCall, type CacheEntry, type CacheIdentity, type CatalogEntry, type Catcher, type CheckOptions, type Checkpoint, type ChoiceRule, type ChoiceState, type ConnectionSupport, type Definition, type DefinitionParts, type Dependencies, type EarlierCheckpoint, type ErrorOutput, type KeptAnswer, type KeyShape, type LoadedPlugin, type LoadedRun, type Machine, type MapState, type Order, type PinKind, type PinSchemas, type PinType, type Problem, type ReadBase, type RecordSchemas, type RecordUse, type Redactor, type Reference, type ReplayedStep, type RerunFrom, type Retrier, type RunChange, type RunStatus, type RunStore, type Runner, type RunnerPort, type SegmentInput, type SegmentQueue, type State, type StateMachine, type StepCacheStore, StepError, type StepLog, type StepRecord, type StepStatus, type StepWiring, type TaskAnswer, type TaskContext, type TaskHandler, type TaskHandlers, type TaskState, type TaskTokenStore, type TraceMode, type TraceSink, type Trigger, type TriggerCheck, type TypeCatalog, type TypeEntry, type Unavailable, type WaitingTask, allStates, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, innerMachine, inputSchema, keptAssigned, limits, loadPlugins, machineDependencies, nestingDepth, orderOf, parseReference, partOfProblem, partsOfDefinition, pinType, pinTypeText, problemText, readText, redacted, referenceSchema, referenceValue, rerunCheckpoint, rerunFrom, rerunProblem, resolveSchema, resultRead, resultSchema, resultState, runSegment, schemaAt, secretRedactor, shortestSecret, stepHandlers, stepStatusSchema, taskResource, taskTokenHash, tokenPattern, triggerChecks, triggerSchema, typeCatalog, typeList, usedConnections, waitSuffix, waitsForToken };
39
+ import { CustomStepManifest, CustomStepVersion, ManifestProblem, customPlugin, customStepEntry, customStepOf, latestCustomSteps, manifestProblems, withCustomSteps } from "./plugin/custom-steps.js";
40
+ export { type AnswerRefusal, type BlockCache, type BlockRun, type BlockRunStore, type BlockShare, type BlockState, type CacheCall, type CacheEntry, type CacheIdentity, type CatalogEntry, type Catcher, type CheckOptions, type Checkpoint, type ChoiceRule, type ChoiceState, type ConnectionHeader, type ConnectionHeaders, type ConnectionSupport, type CustomStepManifest, type CustomStepVersion, type Definition, type DefinitionParts, type Dependencies, type EarlierCheckpoint, type ErrorOutput, type KeptAnswer, type KeyShape, type LoadedPlugin, type LoadedRun, type Machine, type ManifestProblem, type MapState, type Order, type PinKind, type PinSchemas, type PinType, type Problem, type ReadBase, type RecordSchemas, type RecordUse, type Redactor, type Reference, type ReplayedStep, type RerunFrom, type Retrier, type RunChange, type RunStatus, type RunStore, type Runner, type RunnerPort, type SegmentInput, type SegmentQueue, type State, type StateMachine, type StepCacheStore, StepError, type StepLog, type StepRecord, type StepStatus, type StepWiring, type TaskAnswer, type TaskContext, type TaskHandler, type TaskHandlers, type TaskState, type TaskTokenStore, type TraceMode, type TraceSink, type Trigger, type TriggerCheck, type TypeCatalog, type TypeEntry, type Unavailable, type WaitingTask, allStates, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, customPlugin, customStepEntry, customStepOf, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, importStateMachine, innerMachine, inputSchema, keptAssigned, latestCustomSteps, limits, loadPlugins, machineDependencies, manifestProblems, nestingDepth, orderOf, parseReference, partOfProblem, partsOfDefinition, pinType, pinTypeText, problemText, readText, redacted, referenceSchema, referenceValue, rerunCheckpoint, rerunFrom, rerunProblem, resolveSchema, resultRead, resultSchema, resultState, runSegment, schemaAt, secretRedactor, shortestSecret, stepHandlers, stepStatusSchema, taskResource, taskTokenHash, tokenPattern, triggerChecks, triggerSchema, typeCatalog, typeList, usedConnections, waitSuffix, waitsForToken, withCustomSteps };
package/dist/index.js CHANGED
@@ -16,10 +16,12 @@ import { orderOf } from "./definition/types.js";
16
16
  import { checkDefinition } from "./definition/check-definition.js";
17
17
  import { definitionFromParts, partOfProblem, partsOfDefinition } from "./definition/parts.js";
18
18
  import { definitionWarnings } from "./definition/check-warnings.js";
19
+ import { importStateMachine } from "./definition/import/import-machine.js";
19
20
  import { StepError } from "./run/errors.js";
20
21
  import { redacted, secretRedactor, shortestSecret } from "./run/redact.js";
21
22
  import { keptAssigned, rerunCheckpoint, rerunProblem, resultRead } from "./run/rerun.js";
22
23
  import { heldBackLog } from "./run/replay.js";
24
+ import { customPlugin, customStepEntry, customStepOf, latestCustomSteps, manifestProblems, withCustomSteps } from "./plugin/custom-steps.js";
23
25
  import { taskTokenHash, tokenPattern } from "./run/task-token.js";
24
26
  import { rerunFrom } from "./run/rerun-from.js";
25
27
  import { runSegment } from "./run/segment.js";
@@ -30,4 +32,4 @@ import { triggerChecks } from "./plugin/trigger-checks.js";
30
32
  import { typeList } from "./plugin/type-list.js";
31
33
  import { connectionUnavailable } from "./plugin/connection-availability.js";
32
34
  import { typeCatalog } from "./plugin/type-catalog.js";
33
- export { StepError, allStates, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, innerMachine, inputSchema, keptAssigned, limits, loadPlugins, machineDependencies, nestingDepth, orderOf, parseReference, partOfProblem, partsOfDefinition, pinType, pinTypeText, problemText, readText, redacted, referenceSchema, referenceValue, rerunCheckpoint, rerunFrom, rerunProblem, resolveSchema, resultRead, resultSchema, resultState, runSegment, schemaAt, secretRedactor, shortestSecret, stepHandlers, stepStatusSchema, taskResource, taskTokenHash, tokenPattern, triggerChecks, triggerSchema, typeCatalog, typeList, usedConnections, waitSuffix, waitsForToken };
35
+ export { StepError, allStates, assignedNames, blockDefinition, checkDefinition, connectionUnavailable, createRunner, customPlugin, customStepEntry, customStepOf, dataflowDefinitionSchema, definitionFromParts, definitionSchema, definitionWarnings, dependsOn, expressionReferences, expressionSource, findBlock, fits, heldBackLog, importStateMachine, innerMachine, inputSchema, keptAssigned, latestCustomSteps, limits, loadPlugins, machineDependencies, manifestProblems, nestingDepth, orderOf, parseReference, partOfProblem, partsOfDefinition, pinType, pinTypeText, problemText, readText, redacted, referenceSchema, referenceValue, rerunCheckpoint, rerunFrom, rerunProblem, resolveSchema, resultRead, resultSchema, resultState, runSegment, schemaAt, secretRedactor, shortestSecret, stepHandlers, stepStatusSchema, taskResource, taskTokenHash, tokenPattern, triggerChecks, triggerSchema, typeCatalog, typeList, usedConnections, waitSuffix, waitsForToken, withCustomSteps };
package/dist/limits.d.ts CHANGED
@@ -12,7 +12,7 @@ export declare const limits: {
12
12
  readonly taskTimeoutSeconds: 300;
13
13
  readonly defaultTaskTimeoutSeconds: 300;
14
14
  /**
15
- * The longest a Task that waits for an outside result (`.waitForTaskToken`) waits, from its hand-off, and its default:
15
+ * The longest a Task that waits for an outside result (`.waitForTaskToken`) waits, from its try's start, and its default:
16
16
  * 366 days, as a Wait. Its `HeartbeatSeconds` is less.
17
17
  */
18
18
  readonly waitingTaskTimeoutSeconds: number;
package/dist/limits.js CHANGED
@@ -12,7 +12,7 @@ const limits = {
12
12
  taskTimeoutSeconds: 300,
13
13
  defaultTaskTimeoutSeconds: 300,
14
14
  /**
15
- * The longest a Task that waits for an outside result (`.waitForTaskToken`) waits, from its hand-off, and its default:
15
+ * The longest a Task that waits for an outside result (`.waitForTaskToken`) waits, from its try's start, and its default:
16
16
  * 366 days, as a Wait. Its `HeartbeatSeconds` is less.
17
17
  */
18
18
  waitingTaskTimeoutSeconds: 31622400,
@@ -0,0 +1,53 @@
1
+ import { CheckOptions } from "../definition/check-definition.js";
2
+ import { JsonSchema } from "./context.js";
3
+ import { TypeEntry } from "./type-list.js";
4
+ //#region src/plugin/custom-steps.d.ts
5
+ /** The plugin name the app's custom steps take, as `custom:<name>:<version>`; no plugin may take it. */
6
+ export declare const customPlugin = "custom";
7
+ /** One saved version of a custom step, as its type is made from it. */
8
+ export type CustomStepVersion = {
9
+ name: string;
10
+ version: number;
11
+ label: string;
12
+ description: string | null;
13
+ input: JsonSchema;
14
+ output: JsonSchema;
15
+ error_prefix: string;
16
+ errors: Record<string, string>;
17
+ };
18
+ /** A custom step's manifest as a create or an update writes it. */
19
+ export type CustomStepManifest = Partial<Omit<CustomStepVersion, 'version'>> & {
20
+ container?: unknown;
21
+ };
22
+ /** A part of a manifest that cannot be saved: the field, such as `container.dockerfile`, and why. */
23
+ export type ManifestProblem = {
24
+ field: string;
25
+ message: string;
26
+ };
27
+ /**
28
+ * Why a custom step's manifest cannot be saved, each problem naming its field: its name, its container's Dockerfile,
29
+ * files and command, its input and output schemas, its error prefix and its errors. Empty when it can be saved.
30
+ */
31
+ export declare const manifestProblems: (manifest: CustomStepManifest) => ManifestProblem[];
32
+ /**
33
+ * The step type `custom:<name>:<version>` of a saved version: its label and description, its input with `store`, which
34
+ * it requires when its output gives a stored file, its output, and its errors as `<error_prefix>.<Name>`.
35
+ */
36
+ export declare const customStepEntry: (step: CustomStepVersion) => TypeEntry;
37
+ /** The custom step and version a step type's id names, `custom:<name>:<version>`; undefined for any other id. */
38
+ export declare const customStepOf: (id: string) => {
39
+ name: string;
40
+ version: number;
41
+ } | undefined;
42
+ /** The latest version of each custom step among `ids`, by the step's unversioned id, `custom:<name>`. */
43
+ export declare const latestCustomSteps: (ids: readonly string[]) => Record<string, string>;
44
+ /**
45
+ * A tenant's custom step types added to the app's: to a type list (`types`), after the app's own, and to what a
46
+ * definition is checked against (`check`), their arguments and pins included, with `custom:<name>` without a version
47
+ * refused naming the latest.
48
+ */
49
+ export declare const withCustomSteps: (custom: readonly TypeEntry[]) => {
50
+ types: (types: readonly TypeEntry[]) => TypeEntry[];
51
+ check: (check: CheckOptions) => CheckOptions;
52
+ };
53
+ //#endregion
@@ -0,0 +1,256 @@
1
+ import { Ajv } from "ajv";
2
+ //#region src/plugin/custom-steps.ts
3
+ /** The plugin name the app's custom steps take, as `custom:<name>:<version>`; no plugin may take it. */
4
+ const customPlugin = "custom";
5
+ const stepName = /^[a-z][a-z0-9_]*$/;
6
+ const errorName = /^[A-Z][A-Za-z0-9]*$/;
7
+ const dockerfileBytes = 65536;
8
+ const filesBytes = 1048576;
9
+ const containerFields = [
10
+ "dockerfile",
11
+ "files",
12
+ "command"
13
+ ];
14
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15
+ const bytes = (text) => new TextEncoder().encode(text).length;
16
+ const instructions = (dockerfile) => dockerfile.replace(/\\\r?\n/g, " ").split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "" && !line.startsWith("#"));
17
+ const startsFrom = (dockerfile) => /^FROM\s/i.test(instructions(dockerfile).find((line) => !/^ARG\s/i.test(line)) ?? "");
18
+ const dockerfileProblems = (dockerfile) => {
19
+ const field = "container.dockerfile";
20
+ if (typeof dockerfile !== "string" || dockerfile.trim() === "") return [{
21
+ field,
22
+ message: "is missing: give the Dockerfile the step is built from, as text"
23
+ }];
24
+ if (bytes(dockerfile) > dockerfileBytes) return [{
25
+ field,
26
+ message: `is ${bytes(dockerfile)} bytes, more than the ${dockerfileBytes} a Dockerfile may have`
27
+ }];
28
+ return startsFrom(dockerfile) ? [] : [{
29
+ field,
30
+ message: "has no FROM instruction to start with; only ARG lines and comments may come before it"
31
+ }];
32
+ };
33
+ const pathProblem = (path) => {
34
+ if (path === "") return "is an empty path";
35
+ if (path.startsWith("/") || path.startsWith("\\") || /^[A-Za-z]:/.test(path)) return "is an absolute path; give one relative to the build folder";
36
+ if (path.split(/[/\\]/).includes("..")) return "has a \"..\" segment; a file stays inside the build folder";
37
+ };
38
+ const filesProblems = (files) => {
39
+ if (!isObject(files)) return [{
40
+ field: "container.files",
41
+ message: "is an object of relative paths to their text, such as { \"main.py\": \"...\" }, or {} for none"
42
+ }];
43
+ const problems = [];
44
+ let total = 0;
45
+ for (const [path, text] of Object.entries(files)) {
46
+ const problem = pathProblem(path);
47
+ if (problem) problems.push({
48
+ field: "container.files",
49
+ message: `"${path}" ${problem}`
50
+ });
51
+ if (typeof text !== "string") problems.push({
52
+ field: "container.files",
53
+ message: `"${path}" is not text`
54
+ });
55
+ else total += bytes(text);
56
+ }
57
+ if (total > filesBytes) problems.push({
58
+ field: "container.files",
59
+ message: `hold ${total} bytes together, more than the ${filesBytes} a step's files may have`
60
+ });
61
+ return problems;
62
+ };
63
+ const commandProblems = (command) => {
64
+ if (command === void 0) return [];
65
+ return Array.isArray(command) && command.length > 0 && command.every((part) => typeof part === "string" && part !== "") ? [] : [{
66
+ field: "container.command",
67
+ message: "is a list of non-empty texts, such as [\"python\", \"main.py\"], or left out for the image's own"
68
+ }];
69
+ };
70
+ const containerProblems = (container) => {
71
+ if (!isObject(container)) return [{
72
+ field: "container",
73
+ message: "is an object of the step's dockerfile, files and command"
74
+ }];
75
+ return [
76
+ ...Object.keys(container).filter((key) => !containerFields.includes(key)).map((key) => ({
77
+ field: `container.${key}`,
78
+ message: "is not a container field; a container takes dockerfile, files and command"
79
+ })),
80
+ ...dockerfileProblems(container.dockerfile),
81
+ ...filesProblems(container.files),
82
+ ...commandProblems(container.command)
83
+ ];
84
+ };
85
+ const fileMarks = (node, path = []) => {
86
+ if (Array.isArray(node)) return node.flatMap((each, index) => fileMarks(each, [...path, String(index)]));
87
+ if (!isObject(node)) return [];
88
+ return Object.entries(node).flatMap(([key, value]) => [...key === "x-file" ? [{
89
+ path,
90
+ value
91
+ }] : [], ...fileMarks(value, [...path, key])]);
92
+ };
93
+ const schemaProblems = (field, schema) => {
94
+ if (!isObject(schema) || schema.type !== "object") return [{
95
+ field,
96
+ message: "is the JSON Schema of an object, with \"type\": \"object\""
97
+ }];
98
+ const problems = [];
99
+ try {
100
+ new Ajv({ strict: false }).compile(schema);
101
+ } catch (error) {
102
+ problems.push({
103
+ field,
104
+ message: `is no JSON Schema that compiles: ${error instanceof Error ? error.message : String(error)}`
105
+ });
106
+ }
107
+ for (const mark of fileMarks(schema)) if (mark.value !== true) problems.push({
108
+ field: [
109
+ field,
110
+ ...mark.path,
111
+ "x-file"
112
+ ].join("."),
113
+ message: "is true for a stored file, or left out"
114
+ });
115
+ if (field === "input" && isObject(schema.properties) && Object.hasOwn(schema.properties, "store")) problems.push({
116
+ field: "input.properties.store",
117
+ message: "is the argument Protobase gives every custom step, where it stores the files it gives; name yours otherwise"
118
+ });
119
+ return problems;
120
+ };
121
+ const errorsProblems = (errors) => {
122
+ if (!isObject(errors)) return [{
123
+ field: "errors",
124
+ message: "is an object of error names to what each means, such as { \"Refused\": \"the service refused the invoice\" }"
125
+ }];
126
+ return Object.entries(errors).flatMap(([name, text]) => [...errorName.test(name) ? [] : [{
127
+ field: "errors",
128
+ message: `"${name}" is not an error name; start with a capital, then letters and digits`
129
+ }], ...typeof text === "string" ? [] : [{
130
+ field: "errors",
131
+ message: `${name} is not text; say what the error means`
132
+ }]]);
133
+ };
134
+ /**
135
+ * Why a custom step's manifest cannot be saved, each problem naming its field: its name, its container's Dockerfile,
136
+ * files and command, its input and output schemas, its error prefix and its errors. Empty when it can be saved.
137
+ */
138
+ const manifestProblems = (manifest) => {
139
+ const { name, error_prefix: prefix } = manifest;
140
+ return [
141
+ ...typeof name === "string" && stepName.test(name) && name.length <= 64 ? [] : [{
142
+ field: "name",
143
+ message: "is a lowercase letter, then lowercase letters, digits and \"_\", at most 64"
144
+ }],
145
+ ...containerProblems(manifest.container),
146
+ ...schemaProblems("input", manifest.input),
147
+ ...schemaProblems("output", manifest.output),
148
+ ...typeof prefix === "string" && errorName.test(prefix) && prefix !== "States" ? [] : [{
149
+ field: "error_prefix",
150
+ message: "is a capital, then letters and digits, other than States, such as Invoice"
151
+ }],
152
+ ...errorsProblems(manifest.errors)
153
+ ];
154
+ };
155
+ const storeArgument = {
156
+ type: "object",
157
+ required: ["configuration"],
158
+ description: "where the step stores the files it gives: a storage configuration and, when given, a path in it",
159
+ properties: {
160
+ configuration: {
161
+ type: "string",
162
+ description: "the name of a storage configuration, such as \"archive\""
163
+ },
164
+ path: {
165
+ type: "string",
166
+ description: "where in it; default a path of this step in this run"
167
+ }
168
+ }
169
+ };
170
+ const givesFile = (schema) => fileMarks(schema).some((mark) => mark.value === true);
171
+ /**
172
+ * The step type `custom:<name>:<version>` of a saved version: its label and description, its input with `store`, which
173
+ * it requires when its output gives a stored file, its output, and its errors as `<error_prefix>.<Name>`.
174
+ */
175
+ const customStepEntry = (step) => {
176
+ const required = Array.isArray(step.input.required) ? step.input.required : [];
177
+ const properties = isObject(step.input.properties) ? step.input.properties : {};
178
+ const errors = Object.entries(step.errors);
179
+ return {
180
+ id: `${customPlugin}:${step.name}:${step.version}`,
181
+ kind: "step",
182
+ plugin: customPlugin,
183
+ label: step.label,
184
+ description: step.description ?? "",
185
+ input: {
186
+ ...step.input,
187
+ properties: {
188
+ ...properties,
189
+ store: storeArgument
190
+ },
191
+ ...givesFile(step.output) && { required: [...required, "store"] }
192
+ },
193
+ output: step.output,
194
+ ...errors.length > 0 && { errors: Object.fromEntries(errors.map(([name, text]) => [`${step.error_prefix}.${name}`, text])) },
195
+ writes: true,
196
+ available: true
197
+ };
198
+ };
199
+ const requiredInputs = (input) => Array.isArray(input.required) ? input.required : [];
200
+ const customId = /^custom:([a-z][a-z0-9_]*):([1-9][0-9]*)$/;
201
+ /** The custom step and version a step type's id names, `custom:<name>:<version>`; undefined for any other id. */
202
+ const customStepOf = (id) => {
203
+ const found = customId.exec(id);
204
+ return found ? {
205
+ name: found[1],
206
+ version: Number(found[2])
207
+ } : void 0;
208
+ };
209
+ /** The latest version of each custom step among `ids`, by the step's unversioned id, `custom:<name>`. */
210
+ const latestCustomSteps = (ids) => {
211
+ const latest = /* @__PURE__ */ new Map();
212
+ for (const id of ids) {
213
+ const step = customStepOf(id);
214
+ if (step && step.version > (latest.get(step.name)?.version ?? 0)) latest.set(step.name, {
215
+ id,
216
+ version: step.version
217
+ });
218
+ }
219
+ return Object.fromEntries([...latest].map(([name, found]) => [`${customPlugin}:${name}`, found.id]));
220
+ };
221
+ /**
222
+ * A tenant's custom step types added to the app's: to a type list (`types`), after the app's own, and to what a
223
+ * definition is checked against (`check`), their arguments and pins included, with `custom:<name>` without a version
224
+ * refused naming the latest.
225
+ */
226
+ const withCustomSteps = (custom) => ({
227
+ types: (types) => [...types, ...custom],
228
+ check: (check) => {
229
+ if (custom.length === 0) return check;
230
+ return {
231
+ ...check,
232
+ resources: [...check.resources, ...custom.map((type) => type.id)],
233
+ required: {
234
+ ...check.required,
235
+ ...Object.fromEntries(custom.map((type) => [type.id, requiredInputs(type.input)]))
236
+ },
237
+ versioned: {
238
+ ...check.versioned,
239
+ ...latestCustomSteps(custom.map((type) => type.id))
240
+ },
241
+ ...check.pins && { pins: {
242
+ ...check.pins,
243
+ inputs: {
244
+ ...check.pins.inputs,
245
+ ...Object.fromEntries(custom.map((type) => [type.id, type.input]))
246
+ },
247
+ outputs: {
248
+ ...check.pins.outputs,
249
+ ...Object.fromEntries(custom.flatMap((type) => type.output ? [[type.id, type.output]] : []))
250
+ }
251
+ } }
252
+ };
253
+ }
254
+ });
255
+ //#endregion
256
+ export { customPlugin, customStepEntry, customStepOf, latestCustomSteps, manifestProblems, withCustomSteps };
@@ -5,7 +5,7 @@ import { ConnectionError } from "./connection-error.js";
5
5
  import { definePlugin, pluginApi } from "./define-plugin.js";
6
6
  import { AddressRefusedError, ResponseTooLargeError, fetchMaxBytes } from "./fetch-errors.js";
7
7
  import { isFileValue } from "./file-value.js";
8
- import { isStoredFile } from "./stored-file.js";
8
+ import { isStoredFile, storedFileSchema } from "./stored-file.js";
9
9
  import { valueProblems } from "./value-check.js";
10
10
  import { webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties } from "./webhook-input.js";
11
- export { AddressRefusedError, type ConnectionDeclaration, ConnectionError, type FileValue, type JsonSchema, type OAuthEndpoints, type Plugin, type PluginConnection, type PluginFetch, type PluginFetchInit, type PluginFiles, type PluginMail, type PluginMailMessage, type PluginRecords, type PluginServices, type PluginStorage, type PollEvery, type PollingTrigger, type ReadyTrigger, ResponseTooLargeError, type StepContext, StepError, type StepType, type StorageTarget, type StoredFile, type TriggerContext, type TriggerItem, type TriggerType, type WebhookEvent, type WebhookItem, type WebhookTrigger, definePlugin, fetchMaxBytes, isFileValue, isStoredFile, pluginApi, valueProblems, webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties };
11
+ export { AddressRefusedError, type ConnectionDeclaration, ConnectionError, type FileValue, type JsonSchema, type OAuthEndpoints, type Plugin, type PluginConnection, type PluginFetch, type PluginFetchInit, type PluginFiles, type PluginMail, type PluginMailMessage, type PluginRecords, type PluginServices, type PluginStorage, type PollEvery, type PollingTrigger, type ReadyTrigger, ResponseTooLargeError, type StepContext, StepError, type StepType, type StorageTarget, type StoredFile, type TriggerContext, type TriggerItem, type TriggerType, type WebhookEvent, type WebhookItem, type WebhookTrigger, definePlugin, fetchMaxBytes, isFileValue, isStoredFile, pluginApi, storedFileSchema, valueProblems, webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties };
@@ -1,9 +1,9 @@
1
+ import { isStoredFile, storedFileSchema } from "./stored-file.js";
1
2
  import { StepError } from "../run/errors.js";
2
3
  import { definePlugin, pluginApi } from "./define-plugin.js";
3
4
  import { ConnectionError } from "./connection-error.js";
4
5
  import { AddressRefusedError, ResponseTooLargeError, fetchMaxBytes } from "./fetch-errors.js";
5
6
  import { isFileValue } from "./file-value.js";
6
- import { isStoredFile } from "./stored-file.js";
7
7
  import { valueProblems } from "./value-check.js";
8
8
  import { webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties } from "./webhook-input.js";
9
- export { AddressRefusedError, ConnectionError, ResponseTooLargeError, StepError, definePlugin, fetchMaxBytes, isFileValue, isStoredFile, pluginApi, valueProblems, webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties };
9
+ export { AddressRefusedError, ConnectionError, ResponseTooLargeError, StepError, definePlugin, fetchMaxBytes, isFileValue, isStoredFile, pluginApi, storedFileSchema, valueProblems, webhookBodyCeiling, webhookBodyDefault, webhookInputCheck, webhookInputProperties };
@@ -5,6 +5,9 @@ export type LoadedPlugin = {
5
5
  plugin: Plugin;
6
6
  source: string;
7
7
  };
8
- /** The plugins an app runs, each checked as definePlugin checks it, refusing two of one name, which would give two types one id. */
8
+ /**
9
+ * The plugins an app runs, each checked as definePlugin checks it, refusing two of one name, which would give two types
10
+ * one id, and one named `custom`, the name of the app's custom steps.
11
+ */
9
12
  export declare const loadPlugins: (loaded: readonly LoadedPlugin[]) => Plugin[];
10
13
  //#endregion
@@ -1,3 +1,4 @@
1
+ import { customPlugin } from "./custom-steps.js";
1
2
  import { checkPlugin } from "./define-plugin.js";
2
3
  //#region src/plugin/load-plugins.ts
3
4
  const record = (value) => value === void 0 || typeof value === "object" && value !== null;
@@ -6,12 +7,16 @@ const isPlugin = (value) => {
6
7
  const plugin = value;
7
8
  return typeof plugin.name === "string" && typeof plugin.label === "string" && record(plugin.steps) && record(plugin.triggers) && record(plugin.connections);
8
9
  };
9
- /** The plugins an app runs, each checked as definePlugin checks it, refusing two of one name, which would give two types one id. */
10
+ /**
11
+ * The plugins an app runs, each checked as definePlugin checks it, refusing two of one name, which would give two types
12
+ * one id, and one named `custom`, the name of the app's custom steps.
13
+ */
10
14
  const loadPlugins = (loaded) => {
11
15
  const seen = /* @__PURE__ */ new Map();
12
16
  for (const { plugin, source } of loaded) {
13
17
  if (!isPlugin(plugin)) throw new Error(`${source} does not export a workflow plugin as its default; export default definePlugin({ ... })`);
14
18
  checkPlugin(plugin, `Workflow plugin "${plugin.name}" of ${source}`);
19
+ if (plugin.name === "custom") throw new Error(`Workflow plugin "${customPlugin}" of ${source}: "${customPlugin}" is kept for the app's custom steps, whose types are ${customPlugin}:<name>:<version>; give the plugin another name`);
15
20
  const first = seen.get(plugin.name);
16
21
  if (first !== void 0) throw new Error(`Two workflow plugins are named "${plugin.name}": ${first} and ${source}`);
17
22
  seen.set(plugin.name, source);
@@ -1,5 +1,31 @@
1
1
  import { StoredFile } from "./context.js";
2
2
  //#region src/plugin/stored-file.d.ts
3
+ /** A stored file as JSON Schema, as the storage steps give and take it, and as `{ "x-file": true }` stands for. */
4
+ export declare const storedFileSchema: {
5
+ type: string;
6
+ required: string[];
7
+ description: string;
8
+ properties: {
9
+ configuration: {
10
+ type: string;
11
+ };
12
+ node: {
13
+ type: string;
14
+ };
15
+ path: {
16
+ type: string;
17
+ };
18
+ name: {
19
+ type: string;
20
+ };
21
+ type: {
22
+ type: string;
23
+ };
24
+ size: {
25
+ type: string;
26
+ };
27
+ };
28
+ };
3
29
  /** Whether a value has a stored file's shape: its configuration, path, name, type and size, and a text node if any. */
4
30
  export declare const isStoredFile: (value: unknown) => value is StoredFile;
5
31
  //#endregion
@@ -1,4 +1,24 @@
1
1
  //#region src/plugin/stored-file.ts
2
+ /** A stored file as JSON Schema, as the storage steps give and take it, and as `{ "x-file": true }` stands for. */
3
+ const storedFileSchema = {
4
+ type: "object",
5
+ required: [
6
+ "configuration",
7
+ "path",
8
+ "name",
9
+ "type",
10
+ "size"
11
+ ],
12
+ description: "a stored file, { configuration, node?, path, name, type, size }, as a storage step or the http step gave it",
13
+ properties: {
14
+ configuration: { type: "string" },
15
+ node: { type: "string" },
16
+ path: { type: "string" },
17
+ name: { type: "string" },
18
+ type: { type: "string" },
19
+ size: { type: "integer" }
20
+ }
21
+ };
2
22
  /** Whether a value has a stored file's shape: its configuration, path, name, type and size, and a text node if any. */
3
23
  const isStoredFile = (value) => {
4
24
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
@@ -6,4 +26,4 @@ const isStoredFile = (value) => {
6
26
  return typeof configuration === "string" && typeof path === "string" && typeof name === "string" && typeof type === "string" && typeof size === "number" && (node === void 0 || typeof node === "string");
7
27
  };
8
28
  //#endregion
9
- export { isStoredFile };
29
+ export { isStoredFile, storedFileSchema };
package/dist/run/task.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { limits } from "../limits.js";
2
2
  import { StepError, SupersededError } from "./errors.js";
3
+ import "../plugin/custom-steps.js";
3
4
  //#region src/run/task.ts
4
5
  const aborted = (signal) => new Promise((_, reject) => {
5
6
  if (signal.aborted) return reject(signal.reason);
@@ -8,10 +9,12 @@ const aborted = (signal) => new Promise((_, reject) => {
8
9
  /**
9
10
  * Runs a Task's step type with its arguments, within its `TimeoutSeconds`: its result, or a `StepError` naming why it
10
11
  * failed (`States.Timeout` when the time ran out, `States.TaskFailed` for an error of no name of its own). When the
11
- * worker stops, the abort is thrown as it is, so the step is not saved and runs again in the next segment.
12
+ * worker stops, the abort is thrown as it is, so the step is not saved and runs again in the next segment. A custom
13
+ * step, which the save takes, fails as one that does not run yet.
12
14
  */
13
15
  const runTask = async (context, state, args, idempotencyKey, logs) => {
14
16
  const handler = context.tasks[state.Resource];
17
+ if (!handler && state.Resource.startsWith(`custom:`)) throw new StepError("States.Runtime", "Custom steps do not run yet");
15
18
  if (!handler) throw new StepError("States.Runtime", `"${state.Resource}" is not a step type of this app`);
16
19
  const timeout = AbortSignal.timeout((state.TimeoutSeconds ?? limits.defaultTaskTimeoutSeconds) * 1e3);
17
20
  const signal = AbortSignal.any([context.signal, timeout]);
@@ -41,7 +41,7 @@ const overdue = (task, at, timeoutSeconds = Math.round((task.deadline.getTime()
41
41
  * One try of a Task that waits for an outside result (`<type>.waitForTaskToken`). The first segment to reach it gives
42
42
  * the try a token, runs the step type on Arguments that read it as `$states.context.Task.Token`, and marks the token
43
43
  * handed off, so a segment after a restart only waits and never hands the work off again. The run then waits, holding
44
- * no segment, until an answer wakes it, its `TimeoutSeconds` pass (`States.Timeout`, from the hand-off's start) or a
44
+ * no segment, until an answer wakes it, its `TimeoutSeconds` pass (`States.Timeout`, from the try's start) or a
45
45
  * heartbeat is overdue (`States.HeartbeatTimeout`). The answer is the Task's result, which `Output` and `Assign` read as
46
46
  * `$states.result`, or its failure, under the error the answer names. The token is blanked out of all the run keeps.
47
47
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/workflows",
3
- "version": "0.100.2",
3
+ "version": "0.100.4",
4
4
  "description": "Workflows as state machines with JSONata expressions: their check, a runner that saves only what a run needs to go on and traces every step, and the plugin interface for trigger and step types.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {