@parcha/agentrun-dsl 0.1.0-beta.23 → 0.1.0-beta.231
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +2 -0
- package/README.md +22 -17
- package/dist/author-references.d.ts +8 -0
- package/dist/author-references.js +8 -0
- package/dist/author.d.ts +0 -2
- package/dist/author.js +15 -8
- package/dist/authoring.js +4 -3
- package/dist/cli.js +13 -12
- package/dist/code-exec.d.ts +19 -0
- package/dist/code-exec.js +54 -5
- package/dist/decision-provider.d.ts +166 -0
- package/dist/decision-provider.js +238 -0
- package/dist/decision-receipts.d.ts +64 -3
- package/dist/decision-receipts.js +50 -8
- package/dist/dry-run.d.ts +31 -1
- package/dist/dry-run.js +122 -16
- package/dist/edit.d.ts +149 -0
- package/dist/edit.js +1422 -0
- package/dist/evidence.d.ts +19 -0
- package/dist/evidence.js +63 -0
- package/dist/graph.d.ts +17 -0
- package/dist/graph.js +71 -6
- package/dist/index.d.ts +18 -12
- package/dist/index.js +17 -10
- package/dist/inspection.d.ts +5 -0
- package/dist/inspection.js +14 -1
- package/dist/pattern-screen.d.ts +14 -0
- package/dist/pattern-screen.js +451 -0
- package/dist/pointer-warning.d.ts +14 -0
- package/dist/pointer-warning.js +22 -0
- package/dist/predicates.d.ts +32 -2
- package/dist/predicates.js +66 -6
- package/dist/record.d.ts +4 -0
- package/dist/record.js +6 -0
- package/dist/recovery/binding.js +2 -1
- package/dist/recovery/call-key.d.ts +0 -4
- package/dist/recovery/call-key.js +0 -7
- package/dist/recovery/driver.d.ts +43 -20
- package/dist/recovery/driver.js +144 -48
- package/dist/recovery/frozen-snapshot.d.ts +33 -3
- package/dist/recovery/frozen-snapshot.js +28 -12
- package/dist/recovery/handoff-receipts.d.ts +0 -35
- package/dist/recovery/handoff-receipts.js +2 -44
- package/dist/recovery/index.d.ts +4 -8
- package/dist/recovery/index.js +4 -7
- package/dist/recovery/item-state.d.ts +2 -1
- package/dist/recovery/item-state.js +7 -13
- package/dist/recovery/with-recovery.d.ts +9 -3
- package/dist/recovery/with-recovery.js +72 -15
- package/dist/submit-envelope.d.ts +9 -0
- package/dist/submit-envelope.js +44 -0
- package/dist/system-one.d.ts +21 -2
- package/dist/system-one.js +96 -18
- package/dist/testing/decision-provider.d.ts +32 -0
- package/dist/testing/decision-provider.js +183 -0
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.js +2 -0
- package/dist/vocabulary.d.ts +16 -3
- package/dist/vocabulary.js +23 -8
- package/dist/workflow-shape.js +4 -2
- package/dist/workflow.d.ts +145 -19
- package/dist/workflow.js +795 -236
- package/dist/zod-json-contract.js +6 -8
- package/package.json +16 -4
- package/schema/workflow.schema.json +352 -1
- package/skills/author/SKILL.md +4 -1
- package/skills/author/references/jev-decisions.md +50 -5
- package/skills/author/references/language.md +16 -11
- package/dist/recovery/effect-failure.d.ts +0 -34
- package/dist/recovery/effect-failure.js +0 -62
- package/dist/recovery/handoff-block.d.ts +0 -36
- package/dist/recovery/handoff-block.js +0 -148
- package/dist/recovery/handoff-digest.d.ts +0 -58
- package/dist/recovery/handoff-digest.js +0 -195
- package/dist/recovery/handoff-files.d.ts +0 -54
- package/dist/recovery/handoff-files.js +0 -162
- package/dist/recovery/handoff-redact.d.ts +0 -12
- package/dist/recovery/handoff-redact.js +0 -44
- package/dist/recovery/handoff.d.ts +0 -44
- package/dist/recovery/handoff.js +0 -46
package/dist/edit.js
ADDED
|
@@ -0,0 +1,1422 @@
|
|
|
1
|
+
// Edits to a workflow document, each a pure function from one document to the next, so a visual editor, a CLI and a
|
|
2
|
+
// server can share them and the JSON stays the source of truth. A node is named by its JSON Pointer, the path
|
|
3
|
+
// `workflowGraph` gives it. This module imports only the graph and the vocabulary, which import nothing, so a browser
|
|
4
|
+
// bundles it.
|
|
5
|
+
//
|
|
6
|
+
// Every operation takes the document and returns `{ doc, moved, added, removed, changed }`. It never mutates its input,
|
|
7
|
+
// and a subtree it did not touch is shared with the input, so it keeps its bytes. `moved` maps each node whose path
|
|
8
|
+
// changed, in the input's document order; `added` and `removed` list the nodes that exist only after or only before;
|
|
9
|
+
// `changed` lists the nodes whose own fields changed (their `changeCheck` in `workflowGraph`).
|
|
10
|
+
//
|
|
11
|
+
// An operation that would break the document's structure throws one `EditError` and writes nothing. That covers a
|
|
12
|
+
// placement the schema forbids, a node of no known kind, a missing required field, and a container left without its
|
|
13
|
+
// children. Each error carries a code from `EDIT_ERROR_CODES` and the path it is about, in the input's coordinates
|
|
14
|
+
// where the node existed there. An edit to a document that is already broken is allowed, as long as it adds no new
|
|
15
|
+
// break.
|
|
16
|
+
//
|
|
17
|
+
// The checks here are structural. Whether a reference is produced upstream, a field is well typed or a placeholder
|
|
18
|
+
// is filled in is the validator's call: it draws its issues on nodes at these same paths.
|
|
19
|
+
//
|
|
20
|
+
// Choices made where the semantics are the product's to decide; each takes the conservative option:
|
|
21
|
+
// - insert into a slot that holds one node (a map's or a loop's body, a route branch, a child workflow's root, the
|
|
22
|
+
// document's root) makes a chain of the two: index 0 puts the new node first, 1 puts it last. An empty slot takes the
|
|
23
|
+
// node itself.
|
|
24
|
+
// - remove never collapses a chain of one step into that step, and never removes the last step, a parallel's
|
|
25
|
+
// second-to-last branch, a route's second-to-last branch or a body.
|
|
26
|
+
// - move counts `index` in the document as given: the drop point a canvas shows between two steps.
|
|
27
|
+
// - duplicate puts the copy right after the node, in a chain if the node sits alone in its slot. Every node of the
|
|
28
|
+
// copy gets a fresh label. Every key the copy writes (`as`, `failedAs`, or the label of an agent, decide, extract or
|
|
29
|
+
// code node with no `as`) gets a fresh name, off every name its scope uses (a copied child workflow's own input keys
|
|
30
|
+
// included), and the copy's own references to those keys follow them, a copied route's branches and a copied
|
|
31
|
+
// verifier's state included (both read the node's own `as`). Code is copied as it is, so a copied code node writes
|
|
32
|
+
// the same record keys as its source: duplicating a code branch of a parallel gives two branches that write one key,
|
|
33
|
+
// which the run refuses. A copied code node with no `as` writes a result other than a record under its fresh label,
|
|
34
|
+
// and the copy's reads of the old label follow that label; when its code returns a record that names the old label,
|
|
35
|
+
// those reads find nothing. So duplicate returns `mentions` as rename does: the code and shell sources of the copy
|
|
36
|
+
// that mention a key the copy was given a fresh name for (or one of its `<key>$...` keys) by its old name.
|
|
37
|
+
// - wrap takes one node, or consecutive steps or branches of one container, and fills the new container's fields
|
|
38
|
+
// with placeholders the validator flags:
|
|
39
|
+
// - map: `itemsPath: ""` and a fresh `as`;
|
|
40
|
+
// - loop: `until: { predicate: "" }` and `maxIters: 1`;
|
|
41
|
+
// - route: by value, with `valuePath: ""`, the wrapped nodes in branch `match`, and a no-op branch `skip` that
|
|
42
|
+
// `otherwise` names.
|
|
43
|
+
// A parallel takes at least two nodes, one per branch.
|
|
44
|
+
// - unwrap puts a container's children where it was: a chain's steps or a parallel's branches spliced into the
|
|
45
|
+
// enclosing chain, or the body of a map or a loop. A route needs the name of the branch to keep, and its other
|
|
46
|
+
// branches go. A child workflow is never unwrapped, since it runs on its own state, and neither is a map whose body
|
|
47
|
+
// reads `item` or `item_index`, nor a route whose kept branch reads the route's `as`. A nested map's body (the body
|
|
48
|
+
// itself a map included) and a pick's or sift's `describe` read their own `item`, not the outer map's; the rest of
|
|
49
|
+
// `describe` reads the state like any field.
|
|
50
|
+
// - removeBranch keeps a branch that `otherwise` or `unsure` names. renameBranch carries `otherwise` and `unsure`, but
|
|
51
|
+
// not a value elsewhere that compares against the old name.
|
|
52
|
+
// - setField writes exactly the field it names, as given. It refuses the kind, a child slot (use the tree
|
|
53
|
+
// operations), a field the node's kind or route form does not have, and the removal of a required field. Setting a
|
|
54
|
+
// label this way carries nothing; rename does.
|
|
55
|
+
// - rename changes a node's label. When that label is the key the node writes (an agent, decide, extract or code node
|
|
56
|
+
// with no `as`; a code node writes there when its code returns something other than a record), every reference in
|
|
57
|
+
// scope follows it: the `{placeholders}` in state maps, call args, input, env and
|
|
58
|
+
// produces, a child workflow's input, `escalate.summary`, and pick and sift `describe` (all but its own `item`),
|
|
59
|
+
// plus the state paths in itemsPath, valuePath, resultPath, requires and predicates (`path`, `key`, quote_missing's
|
|
60
|
+
// `pages`, under `not` too), and the workflow's `output.path`.
|
|
61
|
+
// - In scope means the nodes that run after the write and see it: later steps of the enclosing chains, and the
|
|
62
|
+
// whole body of an enclosing loop (a later pass reads what an earlier one wrote) with its `until`. Scope ends at
|
|
63
|
+
// the nearest enclosing map (whose `resultPath` reads the item's state) or child workflow (whose `output.path`
|
|
64
|
+
// reads it). A sibling branch of a parallel or a route does not see the write.
|
|
65
|
+
// - Instructions are literal and never rewritten. Code is never rewritten either: the code and shell sources in
|
|
66
|
+
// scope that mention the old key (or one of its `<key>$...` keys) are listed in `mentions`, for the caller to
|
|
67
|
+
// show. So is a renamed code node's own code when it names the old key: a record it returns with that key still
|
|
68
|
+
// writes the old name. The validator does not see a read inside code, so that list is the only warning.
|
|
69
|
+
// - rename refuses a name another node's label or key holds in its workflow, or that a reference (as `<name>$...`
|
|
70
|
+
// too), an input or a code source in scope already uses. A label in another workflow (a sibling child's) is free. It also refuses to rename a key another node in scope or the input also writes, since it
|
|
71
|
+
// can't tell whose readers are whose.
|
|
72
|
+
// - renameKey renames the key a node writes: its `as` when it has one (any kind, a map's and a decision node's
|
|
73
|
+
// included), else its label when that is the key, where it gives the document rename gives; with
|
|
74
|
+
// `{ field: "failedAs" }`, a map's `failedAs`. The references in scope follow it as they follow rename,
|
|
75
|
+
// `<key>$answers` and `<key>$verify` included, and so do the reads a node makes of its own `as`: a route's branches
|
|
76
|
+
// (the route writes its choice before they run) and a verifier's state. It takes a name of letters, digits and "_",
|
|
77
|
+
// refuses names and keys as rename does (all but the node's own label, which its key may take), and refuses a node
|
|
78
|
+
// that writes no such key: a chain, parallel, loop, escalate, report or artifact, or a node with no `failedAs` when
|
|
79
|
+
// that is the field.
|
|
80
|
+
// - No edit gives a label, an `as`, a `failedAs` or a route branch a name `Object.prototype` has (`constructor`,
|
|
81
|
+
// `toString`, `__proto__` and the rest) or `prototype`: rename, renameKey, renameBranch and setField refuse one, and
|
|
82
|
+
// insert and addBranch refuse a node with one anywhere inside it. A read of such a key that nothing wrote would find
|
|
83
|
+
// the prototype's value. An edit to a field's current value stays no change.
|
|
84
|
+
// - setBranchCriteria writes a judged route branch's criteria; a route by value matches its branches by name and takes
|
|
85
|
+
// none.
|
|
86
|
+
// - setSchema writes or removes a schema of the document, or of a child workflow (named by its workflow node's path).
|
|
87
|
+
// It refuses to remove a schema something names (schemaUsers lists them: the workflow's `input.schemaId` and
|
|
88
|
+
// `output.schemaId`, a node's `out` and `verify.out`, and a `$ref` to `#/definitions/<id>` in another schema), and it
|
|
89
|
+
// never renames one.
|
|
90
|
+
// - namesInScope runs rename's scope rules backwards: a node may read its workflow's input keys, a map body's `item`
|
|
91
|
+
// and `item_index`, and every key whose readers include it, with that key's `<key>$answers` and `<key>$verify`. A
|
|
92
|
+
// map's `resultPath`, a loop's `until`, a `verify` (the node's own `as` and `submission`), a pick's or sift's
|
|
93
|
+
// `describe` (its own `item`) and a child's `output.path` see more than the node's other fields, so namesInScope
|
|
94
|
+
// takes the field. It cannot list a key only a code node's returned record writes, nor the keys of an
|
|
95
|
+
// input whose schema lists no properties; the validator does not flag a read of either.
|
|
96
|
+
// - placeholderNode makes the smallest node of a kind that holds no nodes: wrap makes containers of nodes that exist.
|
|
97
|
+
import { workflowGraph } from "./graph.js";
|
|
98
|
+
import { DECISION_NODE_FIELDS, HOST_NODE_FIELDS, IGNORED_NODE_FIELDS, isPrototypeName, NODE_FIELDS, WORKFLOW_NODE_KINDS } from "./vocabulary.js";
|
|
99
|
+
/** Every code an EditError carries. */
|
|
100
|
+
export const EDIT_ERROR_CODES = [
|
|
101
|
+
/** The document is not an object. */
|
|
102
|
+
"DOCUMENT_INVALID",
|
|
103
|
+
/** No node sits at the path. */
|
|
104
|
+
"PATH_NOT_FOUND",
|
|
105
|
+
/** The parent has no such slot, or the node is not a container the operation works on. */
|
|
106
|
+
"SLOT_INVALID",
|
|
107
|
+
/** The index is not a whole number within the slot. */
|
|
108
|
+
"INDEX_OUT_OF_RANGE",
|
|
109
|
+
/** The node is not a node of a known kind with its required fields and only its own fields. */
|
|
110
|
+
"NODE_INVALID",
|
|
111
|
+
/** setField, rename or renameKey named a field the node may not have written that way, or that it lacks. */
|
|
112
|
+
"FIELD_INVALID",
|
|
113
|
+
/** The name is empty, holds a "$", is no state key where the name is one, or is a name an object's prototype has. */
|
|
114
|
+
"NAME_INVALID",
|
|
115
|
+
/** Another node's label or key already holds the name, or a reference, input or code source uses it. */
|
|
116
|
+
"NAME_TAKEN",
|
|
117
|
+
/** Another node or the input writes the key being renamed. */
|
|
118
|
+
"NAME_SHARED",
|
|
119
|
+
/** No branch has that name or index. */
|
|
120
|
+
"BRANCH_NOT_FOUND",
|
|
121
|
+
/** A branch already has that name. */
|
|
122
|
+
"BRANCH_TAKEN",
|
|
123
|
+
/** `otherwise` or `unsure` names the branch. */
|
|
124
|
+
"BRANCH_IN_USE",
|
|
125
|
+
/** The move puts a node inside itself. */
|
|
126
|
+
"MOVE_INTO_SELF",
|
|
127
|
+
/** The nodes to wrap are none, repeated, not consecutive siblings, too few for the container, or the kind is no container. */
|
|
128
|
+
"WRAP_INVALID",
|
|
129
|
+
/** The node is not a container that can be unwrapped there. */
|
|
130
|
+
"UNWRAP_INVALID",
|
|
131
|
+
/** The result would break a rule of the document's structure. */
|
|
132
|
+
"STRUCTURE_INVALID",
|
|
133
|
+
/** The workflow has no schema with that id. */
|
|
134
|
+
"SCHEMA_NOT_FOUND",
|
|
135
|
+
/** A field or another schema still names the schema being removed. */
|
|
136
|
+
"SCHEMA_IN_USE",
|
|
137
|
+
/** The schema is not a JSON object. */
|
|
138
|
+
"SCHEMA_INVALID",
|
|
139
|
+
];
|
|
140
|
+
/** The one error the operations throw. `path` is the node it is about, in the input document where that node existed
|
|
141
|
+
* there; `related` names other nodes the error is about: the one holding a taken name, the other writers of a key. */
|
|
142
|
+
export class EditError extends Error {
|
|
143
|
+
code;
|
|
144
|
+
path;
|
|
145
|
+
related;
|
|
146
|
+
constructor(code, path, message, related = []) {
|
|
147
|
+
super(message);
|
|
148
|
+
this.name = "EditError";
|
|
149
|
+
this.code = code;
|
|
150
|
+
this.path = path;
|
|
151
|
+
this.related = related;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
// ---- the vocabulary, as the edits read it ---------------------------------------------------------------------------
|
|
155
|
+
const KINDS = new Set(WORKFLOW_NODE_KINDS);
|
|
156
|
+
/** The fields of each kind that hold its children, which only the tree operations write. */
|
|
157
|
+
const SLOT_FIELDS = { chain: ["steps"], parallel: ["branches"], map: ["body"], loop: ["body"], route: ["branches"], workflow: ["workflow"] };
|
|
158
|
+
/** Fields only one form of route has: a route Jev chooses, or a route by value. */
|
|
159
|
+
const JUDGED_ROUTE_ONLY = ["state", "instructions", "unsure", ...DECISION_NODE_FIELDS];
|
|
160
|
+
const BY_VALUE_ROUTE_ONLY = ["valuePath", "otherwise"];
|
|
161
|
+
/** The schema's required fields of each kind, and of each form of route. */
|
|
162
|
+
const REQUIRED = {
|
|
163
|
+
chain: ["node", "steps"],
|
|
164
|
+
code: ["node", "label", "code"],
|
|
165
|
+
agent: ["node", "label", "instructions", "out"],
|
|
166
|
+
decide: ["node", "label", "instructions", "out"],
|
|
167
|
+
extract: ["node", "label", "instructions", "out"],
|
|
168
|
+
report: ["node", "label", "instructions"],
|
|
169
|
+
artifact: ["node", "label", "type"],
|
|
170
|
+
map: ["node", "label", "itemsPath", "body", "as"],
|
|
171
|
+
parallel: ["node", "label", "branches"],
|
|
172
|
+
loop: ["node", "label", "body", "until", "maxIters"],
|
|
173
|
+
escalate: ["node", "label", "when", "kind", "stage", "summary"],
|
|
174
|
+
call: ["node", "label", "via", "as", "deadline_s"],
|
|
175
|
+
workflow: ["node", "label", "workflow", "input", "out", "as"],
|
|
176
|
+
judge: ["node", "label", "state", "out", "as"],
|
|
177
|
+
pick: ["node", "label", "itemsPath", "describe", "instructions", "as"],
|
|
178
|
+
sift: ["node", "label", "itemsPath", "out", "as"],
|
|
179
|
+
route: ["node", "label", "state", "instructions", "branches"],
|
|
180
|
+
"route by value": ["node", "label", "valuePath", "branches"],
|
|
181
|
+
};
|
|
182
|
+
/** A judged route takes at most this many branches (System One's choice limit). */
|
|
183
|
+
const MAX_ROUTE_BRANCHES = 240;
|
|
184
|
+
/** The nesting depth `workflowGraph` walks. */
|
|
185
|
+
const MAX_DEPTH = 128;
|
|
186
|
+
/** State keys the engine gives a node, which no rename or fresh name may take. */
|
|
187
|
+
const RESERVED_KEYS = new Set(["item", "item_index", "report_markdown", "artifact", "state", "submission", "$host"]);
|
|
188
|
+
/** The placeholder a required field takes in a new node: a value insert accepts and the validator flags until someone
|
|
189
|
+
* fills it in (an empty text, an empty state map, a predicate with no name, a deadline of 0 seconds), or, for a loop's
|
|
190
|
+
* `maxIters`, the smallest bound. placeholderNode and wrap fill fields from it. */
|
|
191
|
+
export const FIELD_PLACEHOLDERS = Object.freeze({
|
|
192
|
+
instructions: "", code: "", out: "", type: "", itemsPath: "", describe: "", kind: "", stage: "", summary: "", via: "",
|
|
193
|
+
valuePath: "", state: Object.freeze({}), when: Object.freeze({ predicate: "" }), until: Object.freeze({ predicate: "" }),
|
|
194
|
+
deadline_s: 0, maxIters: 1,
|
|
195
|
+
});
|
|
196
|
+
/** A copy of a field's placeholder, to write into a document. */
|
|
197
|
+
const placeholder = (field) => structuredClone(FIELD_PLACEHOLDERS[field]);
|
|
198
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
199
|
+
const isNode = (value) => isObject(value) && typeof value.node === "string";
|
|
200
|
+
const isByValue = (node) => node.node === "route" && node.valuePath !== undefined;
|
|
201
|
+
/** The fields the node's kind (and its route form) accepts, `node` and the child slots included. */
|
|
202
|
+
const fieldsOf = (node) => {
|
|
203
|
+
const kind = String(node.node);
|
|
204
|
+
if (!KINDS.has(kind))
|
|
205
|
+
return [];
|
|
206
|
+
const own = [...NODE_FIELDS[kind], ...HOST_NODE_FIELDS];
|
|
207
|
+
if (kind !== "route")
|
|
208
|
+
return own;
|
|
209
|
+
const other = isByValue(node) ? JUDGED_ROUTE_ONLY : BY_VALUE_ROUTE_ONLY;
|
|
210
|
+
return own.filter((field) => !other.includes(field));
|
|
211
|
+
};
|
|
212
|
+
/** The fields setField writes on this node: its kind's (and its route form's) own fields, without `node` and the child
|
|
213
|
+
* slots. A property panel lists these. */
|
|
214
|
+
export function editableFields(node) {
|
|
215
|
+
if (!isObject(node))
|
|
216
|
+
return [];
|
|
217
|
+
const slots = SLOT_FIELDS[String(node.node)] ?? [];
|
|
218
|
+
return fieldsOf(node).filter((field) => field !== "node" && !slots.includes(field));
|
|
219
|
+
}
|
|
220
|
+
/** The fields the schema requires of this node's kind (and its route form), `node` included. */
|
|
221
|
+
export function requiredFields(node) {
|
|
222
|
+
if (!isObject(node) || !KINDS.has(String(node.node)))
|
|
223
|
+
return [];
|
|
224
|
+
return [...REQUIRED[isByValue(node) ? "route by value" : String(node.node)]];
|
|
225
|
+
}
|
|
226
|
+
// ---- pointers and the walk ------------------------------------------------------------------------------------------
|
|
227
|
+
const escape = (part) => part.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
228
|
+
const unescape = (part) => part.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
229
|
+
/** Every node of the document, in the order and at the paths `workflowGraph` gives them. */
|
|
230
|
+
function entriesOf(doc) {
|
|
231
|
+
const out = [];
|
|
232
|
+
const visit = (node, at, depth) => {
|
|
233
|
+
if (!isNode(node) || depth > MAX_DEPTH)
|
|
234
|
+
return;
|
|
235
|
+
out.push({ ...at, node });
|
|
236
|
+
if (depth + 1 > MAX_DEPTH)
|
|
237
|
+
return;
|
|
238
|
+
const { path, keys, scope } = at;
|
|
239
|
+
const child = (value, slot, index, many, tail, inner = scope) => visit(value, { path: `${path}/${many ? `${slot}/${index}` : slot}`, parentPath: path, slot, index, many, keys: [...keys, ...tail], scope: inner }, depth + 1);
|
|
240
|
+
switch (node.node) {
|
|
241
|
+
case "chain":
|
|
242
|
+
if (Array.isArray(node.steps))
|
|
243
|
+
node.steps.forEach((step, index) => child(step, "steps", index, true, ["steps", String(index)]));
|
|
244
|
+
break;
|
|
245
|
+
case "parallel":
|
|
246
|
+
if (Array.isArray(node.branches))
|
|
247
|
+
node.branches.forEach((branch, index) => child(branch, "branches", index, true, ["branches", String(index)]));
|
|
248
|
+
break;
|
|
249
|
+
case "map":
|
|
250
|
+
case "loop":
|
|
251
|
+
child(node.body, "body", 0, false, ["body"]);
|
|
252
|
+
break;
|
|
253
|
+
case "route":
|
|
254
|
+
if (isObject(node.branches))
|
|
255
|
+
for (const [name, branch] of Object.entries(node.branches)) {
|
|
256
|
+
if (isObject(branch))
|
|
257
|
+
child(branch.body, `branches/${escape(name)}/body`, 0, false, ["branches", name, "body"]);
|
|
258
|
+
}
|
|
259
|
+
break;
|
|
260
|
+
case "workflow":
|
|
261
|
+
if (isObject(node.workflow))
|
|
262
|
+
child(node.workflow.root, "workflow/root", 0, false, ["workflow", "root"], path);
|
|
263
|
+
break;
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
visit(doc.root, { path: "/root", parentPath: "", slot: "root", index: 0, many: false, keys: ["root"], scope: "" }, 0);
|
|
267
|
+
return out;
|
|
268
|
+
}
|
|
269
|
+
/** Where the node at `path` sits: its parent's path, the slot it is in, and its index there (0 in a slot that holds one
|
|
270
|
+
* node). Undefined when no node sits there. */
|
|
271
|
+
export function locate(doc, path) {
|
|
272
|
+
if (!isObject(doc))
|
|
273
|
+
return undefined;
|
|
274
|
+
const entry = entriesOf(doc).find((candidate) => candidate.path === path);
|
|
275
|
+
return entry && { parentPath: entry.parentPath, slot: entry.slot, index: entry.index };
|
|
276
|
+
}
|
|
277
|
+
// ---- copy on write ----------------------------------------------------------------------------------------------------
|
|
278
|
+
const DELETE = Symbol("delete");
|
|
279
|
+
/** One operation's copies: each copied object remembers the object it was copied from, so the result can say which
|
|
280
|
+
* node of the input each node of the output is. */
|
|
281
|
+
class Draft {
|
|
282
|
+
from = new WeakMap();
|
|
283
|
+
copy(value) {
|
|
284
|
+
const copied = (Array.isArray(value) ? value.slice() : { ...value });
|
|
285
|
+
this.from.set(copied, this.source(value));
|
|
286
|
+
return copied;
|
|
287
|
+
}
|
|
288
|
+
source(value) {
|
|
289
|
+
let at = value;
|
|
290
|
+
for (let next = this.from.get(at); next !== undefined; next = this.from.get(at))
|
|
291
|
+
at = next;
|
|
292
|
+
return at;
|
|
293
|
+
}
|
|
294
|
+
/** `doc` with the value at `keys` replaced by `fn` of it (a key deleted when `fn` returns DELETE), each object on the
|
|
295
|
+
* way copied and every other value shared. */
|
|
296
|
+
update(doc, keys, fn) {
|
|
297
|
+
const go = (value, i) => {
|
|
298
|
+
if (i === keys.length)
|
|
299
|
+
return fn(value);
|
|
300
|
+
if (!isObject(value) && !Array.isArray(value))
|
|
301
|
+
throw new Error(`edit: no container at ${keys.slice(0, i).join("/")}`);
|
|
302
|
+
const copied = this.copy(value);
|
|
303
|
+
const inner = go(value[keys[i]], i + 1);
|
|
304
|
+
if (inner === DELETE)
|
|
305
|
+
delete copied[keys[i]];
|
|
306
|
+
else
|
|
307
|
+
copied[keys[i]] = inner;
|
|
308
|
+
return copied;
|
|
309
|
+
};
|
|
310
|
+
return go(doc, 0);
|
|
311
|
+
}
|
|
312
|
+
/** `update`, where `fn` revises the node at `keys`: what it returns is that node, edited, not a new one. */
|
|
313
|
+
revise(doc, keys, fn) {
|
|
314
|
+
return this.update(doc, keys, (value) => {
|
|
315
|
+
const next = fn(value);
|
|
316
|
+
if (next !== value && isObject(value))
|
|
317
|
+
this.from.set(next, this.source(value));
|
|
318
|
+
return next;
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/** A JSON value copied, so the document never shares an object with its caller. */
|
|
323
|
+
const clone = (value) => {
|
|
324
|
+
if (Array.isArray(value))
|
|
325
|
+
return value.map(clone);
|
|
326
|
+
if (isObject(value))
|
|
327
|
+
return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, clone(inner)]));
|
|
328
|
+
return value;
|
|
329
|
+
};
|
|
330
|
+
/** How many reports and artifacts sit in the node, as the validator counts them: never inside a child workflow. */
|
|
331
|
+
const terminals = (node) => {
|
|
332
|
+
if (!isNode(node))
|
|
333
|
+
return 0;
|
|
334
|
+
switch (node.node) {
|
|
335
|
+
case "report":
|
|
336
|
+
case "artifact": return 1;
|
|
337
|
+
case "chain": return Array.isArray(node.steps) ? node.steps.reduce((n, step) => n + terminals(step), 0) : 0;
|
|
338
|
+
case "parallel": return Array.isArray(node.branches) ? node.branches.reduce((n, branch) => n + terminals(branch), 0) : 0;
|
|
339
|
+
case "map":
|
|
340
|
+
case "loop": return terminals(node.body);
|
|
341
|
+
case "route": return isObject(node.branches) ? Object.values(node.branches).reduce((n, branch) => n + (isObject(branch) ? terminals(branch.body) : 0), 0) : 0;
|
|
342
|
+
default: return 0;
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
/** The document's structural breaks, in document order and then the document's own. They mirror the validator's rules
|
|
346
|
+
* on where a node may sit and what it must hold: a known kind, only its kind's fields, the schema's required fields,
|
|
347
|
+
* steps, branches and bodies present and enough of them, a report or artifact only as the root chain's last step.
|
|
348
|
+
* The validator's other structural rules (a model node's `out` naming `report_markdown`, the depth bound) and every
|
|
349
|
+
* value's type are its own to check. */
|
|
350
|
+
function problemsOf(doc) {
|
|
351
|
+
const out = [];
|
|
352
|
+
const add = (at, rule, code, message) => { out.push({ at, rule, code, message }); };
|
|
353
|
+
const visit = (value, path, holder, slot, depth) => {
|
|
354
|
+
if (!isNode(value)) {
|
|
355
|
+
add(holder, `slot:${slot}`, "STRUCTURE_INVALID", `${path}: no node here; the ${slot === "root" ? "document" : "slot"} needs one`);
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
if (depth > MAX_DEPTH)
|
|
359
|
+
return;
|
|
360
|
+
const kind = String(value.node);
|
|
361
|
+
if (!KINDS.has(kind)) {
|
|
362
|
+
add(path, "kind", "NODE_INVALID", `${path}: unknown node kind "${kind}"`);
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
const allowed = new Set([...fieldsOf(value), ...(IGNORED_NODE_FIELDS[kind] ?? [])]);
|
|
366
|
+
for (const key of Object.keys(value))
|
|
367
|
+
if (!allowed.has(key))
|
|
368
|
+
add(path, `key:${key}`, "NODE_INVALID", `${path}: a ${isByValue(value) ? "route by value" : kind} node has no field "${key}"`);
|
|
369
|
+
const slots = SLOT_FIELDS[kind] ?? [];
|
|
370
|
+
for (const field of requiredFields(value))
|
|
371
|
+
if (!slots.includes(field) && value[field] === undefined)
|
|
372
|
+
add(path, `required:${field}`, "NODE_INVALID", `${path}: a ${kind} node needs "${field}"`);
|
|
373
|
+
const inside = (rule, where) => add(path, rule, "STRUCTURE_INVALID", `${path}: a report or artifact cannot sit inside ${where}; the workflow renders its terminal once, as the root chain's last step`);
|
|
374
|
+
switch (kind) {
|
|
375
|
+
case "chain":
|
|
376
|
+
if (!Array.isArray(value.steps)) {
|
|
377
|
+
add(path, "slot:steps", "STRUCTURE_INVALID", `${path}: a chain needs steps`);
|
|
378
|
+
break;
|
|
379
|
+
}
|
|
380
|
+
if (!value.steps.length)
|
|
381
|
+
add(path, "chain-empty", "STRUCTURE_INVALID", `${path}: a chain needs at least one step`);
|
|
382
|
+
value.steps.forEach((step, index) => visit(step, `${path}/steps/${index}`, path, "steps", depth + 1));
|
|
383
|
+
break;
|
|
384
|
+
case "parallel":
|
|
385
|
+
if (!Array.isArray(value.branches)) {
|
|
386
|
+
add(path, "slot:branches", "STRUCTURE_INVALID", `${path}: a parallel needs branches`);
|
|
387
|
+
break;
|
|
388
|
+
}
|
|
389
|
+
if (value.branches.length < 2)
|
|
390
|
+
add(path, "parallel-few", "STRUCTURE_INVALID", `${path}: a parallel needs at least two branches`);
|
|
391
|
+
value.branches.forEach((branch, index) => visit(branch, `${path}/branches/${index}`, path, "branches", depth + 1));
|
|
392
|
+
if (terminals(value))
|
|
393
|
+
inside("terminal-inside", "a parallel branch");
|
|
394
|
+
break;
|
|
395
|
+
case "map":
|
|
396
|
+
case "loop":
|
|
397
|
+
visit(value.body, `${path}/body`, path, "body", depth + 1);
|
|
398
|
+
if (terminals(value.body))
|
|
399
|
+
inside("terminal-inside", `a ${kind} body`);
|
|
400
|
+
break;
|
|
401
|
+
case "route": {
|
|
402
|
+
if (!isObject(value.branches)) {
|
|
403
|
+
add(path, "slot:branches", "STRUCTURE_INVALID", `${path}: a route needs branches`);
|
|
404
|
+
break;
|
|
405
|
+
}
|
|
406
|
+
const names = Object.keys(value.branches);
|
|
407
|
+
if (names.length < 2)
|
|
408
|
+
add(path, "route-few", "STRUCTURE_INVALID", `${path}: a route needs at least two branches`);
|
|
409
|
+
if (!isByValue(value) && names.length > MAX_ROUTE_BRANCHES)
|
|
410
|
+
add(path, "route-many", "STRUCTURE_INVALID", `${path}: a route Jev chooses takes at most ${MAX_ROUTE_BRANCHES} branches`);
|
|
411
|
+
for (const name of names) {
|
|
412
|
+
const branch = value.branches[name];
|
|
413
|
+
if (!isObject(branch))
|
|
414
|
+
add(path, "slot:branch", "STRUCTURE_INVALID", `${path}: branch "${name}" needs a body`);
|
|
415
|
+
else
|
|
416
|
+
visit(branch.body, `${path}/branches/${escape(name)}/body`, path, "branch", depth + 1);
|
|
417
|
+
}
|
|
418
|
+
if (terminals(value))
|
|
419
|
+
inside("terminal-inside", "a route branch");
|
|
420
|
+
break;
|
|
421
|
+
}
|
|
422
|
+
case "workflow": {
|
|
423
|
+
const child = value.workflow;
|
|
424
|
+
const root = isObject(child) ? child.root : undefined;
|
|
425
|
+
if (!isNode(root) || (root.node === "chain" && (!Array.isArray(root.steps) || !root.steps.length)))
|
|
426
|
+
add(path, "child-root", "STRUCTURE_INVALID", `${path}: the child workflow needs a root node`);
|
|
427
|
+
if (isNode(root)) {
|
|
428
|
+
visit(root, `${path}/workflow/root`, path, "workflow/root", depth + 1);
|
|
429
|
+
if (terminals(root))
|
|
430
|
+
inside("terminal-inside", "a child workflow; the parent owns the terminal");
|
|
431
|
+
}
|
|
432
|
+
break;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
};
|
|
436
|
+
visit(doc.root, "/root", "", "root", 0);
|
|
437
|
+
const total = terminals(doc.root);
|
|
438
|
+
if (total > 1)
|
|
439
|
+
add("", "terminals", "STRUCTURE_INVALID", "/root: a workflow has at most one terminal node (report or artifact)");
|
|
440
|
+
else if (total === 1) {
|
|
441
|
+
const root = doc.root;
|
|
442
|
+
const last = root.node === "chain" && Array.isArray(root.steps) ? root.steps[root.steps.length - 1] : root;
|
|
443
|
+
if (!isNode(last) || (last.node !== "report" && last.node !== "artifact"))
|
|
444
|
+
add("", "terminal-last", "STRUCTURE_INVALID", "/root: the terminal node (report or artifact) must be the last step of the root chain");
|
|
445
|
+
}
|
|
446
|
+
return out;
|
|
447
|
+
}
|
|
448
|
+
/** The result of an operation from `before` to `after`: which node of the input each node of the output is (by the
|
|
449
|
+
* object it was copied from), and the structure checked. A break `after` has that `before` did not throws. */
|
|
450
|
+
function finish(draft, before, after) {
|
|
451
|
+
const old = entriesOf(before), now = entriesOf(after);
|
|
452
|
+
const placements = new Map();
|
|
453
|
+
for (const entry of old)
|
|
454
|
+
placements.set(entry.node, [...(placements.get(entry.node) ?? []), entry.path]);
|
|
455
|
+
const prevOf = new Map(), nextOf = new Map();
|
|
456
|
+
for (const entry of now) {
|
|
457
|
+
const candidates = (placements.get(draft.source(entry.node)) ?? []).filter((path) => !nextOf.has(path));
|
|
458
|
+
const from = candidates.includes(entry.path) ? entry.path : candidates[0];
|
|
459
|
+
if (from !== undefined) {
|
|
460
|
+
prevOf.set(entry.path, from);
|
|
461
|
+
nextOf.set(from, entry.path);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
const moved = new Map();
|
|
465
|
+
for (const entry of old) {
|
|
466
|
+
const to = nextOf.get(entry.path);
|
|
467
|
+
if (to !== undefined && to !== entry.path)
|
|
468
|
+
moved.set(entry.path, to);
|
|
469
|
+
}
|
|
470
|
+
const checks = new Map(workflowGraph(before).nodes.map((node) => [node.path, node.changeCheck]));
|
|
471
|
+
const result = {
|
|
472
|
+
doc: after,
|
|
473
|
+
moved,
|
|
474
|
+
added: now.filter((entry) => !prevOf.has(entry.path)).map((entry) => entry.path),
|
|
475
|
+
removed: old.filter((entry) => !nextOf.has(entry.path)).map((entry) => entry.path),
|
|
476
|
+
changed: workflowGraph(after).nodes.filter((node) => prevOf.has(node.path) && checks.get(prevOf.get(node.path)) !== node.changeCheck).map((node) => node.path),
|
|
477
|
+
};
|
|
478
|
+
// The breaks the input had, at the paths their nodes now have; a break with more instances after is new.
|
|
479
|
+
const had = new Map();
|
|
480
|
+
for (const problem of problemsOf(before)) {
|
|
481
|
+
if (problem.at !== "" && !nextOf.has(problem.at))
|
|
482
|
+
continue;
|
|
483
|
+
const key = `${problem.at === "" ? "" : nextOf.get(problem.at)}|${problem.rule}`;
|
|
484
|
+
had.set(key, (had.get(key) ?? 0) + 1);
|
|
485
|
+
}
|
|
486
|
+
for (const problem of problemsOf(after)) {
|
|
487
|
+
const key = `${problem.at}|${problem.rule}`;
|
|
488
|
+
const left = had.get(key) ?? 0;
|
|
489
|
+
if (left > 0) {
|
|
490
|
+
had.set(key, left - 1);
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
throw new EditError(problem.code, problem.at === "" ? "/root" : prevOf.get(problem.at) ?? problem.at, problem.message);
|
|
494
|
+
}
|
|
495
|
+
return result;
|
|
496
|
+
}
|
|
497
|
+
// ---- shared steps ------------------------------------------------------------------------------------------------------
|
|
498
|
+
const documentOf = (doc) => {
|
|
499
|
+
if (!isObject(doc))
|
|
500
|
+
throw new EditError("DOCUMENT_INVALID", "", "the document is not a workflow object");
|
|
501
|
+
return doc;
|
|
502
|
+
};
|
|
503
|
+
const find = (entries, path) => {
|
|
504
|
+
const entry = entries.find((candidate) => candidate.path === path);
|
|
505
|
+
if (!entry)
|
|
506
|
+
throw new EditError("PATH_NOT_FOUND", String(path), `no node at ${String(path)}`);
|
|
507
|
+
return entry;
|
|
508
|
+
};
|
|
509
|
+
const nodeOf = (value, path) => {
|
|
510
|
+
if (!isNode(value) || !KINDS.has(String(value.node)))
|
|
511
|
+
throw new EditError("NODE_INVALID", path, `the value is not a node of a known kind: ${JSON.stringify(isObject(value) ? value.node : value)}`);
|
|
512
|
+
for (const { node } of entriesOf({ root: value })) {
|
|
513
|
+
for (const name of [node.label, node.as, node.failedAs])
|
|
514
|
+
refusePrototypeName(name, path);
|
|
515
|
+
if (node.node === "route" && isObject(node.branches))
|
|
516
|
+
for (const name of Object.keys(node.branches))
|
|
517
|
+
refusePrototypeName(name, path);
|
|
518
|
+
}
|
|
519
|
+
return value;
|
|
520
|
+
};
|
|
521
|
+
function slotAt(doc, entries, parentPath, slot) {
|
|
522
|
+
const at = (keys, many) => {
|
|
523
|
+
const value = keys.reduce((inner, key) => isObject(inner) || Array.isArray(inner) ? inner[key] : undefined, doc);
|
|
524
|
+
return { path: `${parentPath}/${slot}`, parentPath, slot, many, keys, size: many ? (Array.isArray(value) ? value.length : 0) : value === undefined ? 0 : 1 };
|
|
525
|
+
};
|
|
526
|
+
if (parentPath === "") {
|
|
527
|
+
if (slot !== "root")
|
|
528
|
+
throw new EditError("SLOT_INVALID", "", `the document holds its root at "root", not "${String(slot)}"`);
|
|
529
|
+
return at(["root"], false);
|
|
530
|
+
}
|
|
531
|
+
const parent = find(entries, parentPath);
|
|
532
|
+
const kind = parent.node.node;
|
|
533
|
+
if (kind === "chain" && slot === "steps")
|
|
534
|
+
return at([...parent.keys, "steps"], true);
|
|
535
|
+
if (kind === "parallel" && slot === "branches")
|
|
536
|
+
return at([...parent.keys, "branches"], true);
|
|
537
|
+
if ((kind === "map" || kind === "loop") && slot === "body")
|
|
538
|
+
return at([...parent.keys, "body"], false);
|
|
539
|
+
if (kind === "workflow" && slot === "workflow/root" && isObject(parent.node.workflow))
|
|
540
|
+
return at([...parent.keys, "workflow", "root"], false);
|
|
541
|
+
const branch = kind === "route" && typeof slot === "string" ? /^branches\/([^/]*)\/body$/.exec(slot) : null;
|
|
542
|
+
if (branch && isObject(parent.node.branches) && Object.hasOwn(parent.node.branches, unescape(branch[1])) && isObject(parent.node.branches[unescape(branch[1])])) {
|
|
543
|
+
return at([...parent.keys, "branches", unescape(branch[1]), "body"], false);
|
|
544
|
+
}
|
|
545
|
+
throw new EditError("SLOT_INVALID", parentPath, `a ${String(kind)} node at ${parentPath} has no slot "${String(slot)}"`);
|
|
546
|
+
}
|
|
547
|
+
const checkIndex = (slot, index) => {
|
|
548
|
+
const most = slot.many ? slot.size : slot.size === 0 ? 0 : 1;
|
|
549
|
+
if (!Number.isInteger(index) || index < 0 || index > most)
|
|
550
|
+
throw new EditError("INDEX_OUT_OF_RANGE", slot.parentPath, `index ${index} is outside ${slot.path} (0 to ${most})`);
|
|
551
|
+
};
|
|
552
|
+
/** `doc` with `node` placed in `slot` at `index`: into the array, into the empty slot, or in a new chain with the slot's
|
|
553
|
+
* one node. */
|
|
554
|
+
function place(draft, doc, slot, index, node) {
|
|
555
|
+
checkIndex(slot, index);
|
|
556
|
+
if (slot.many)
|
|
557
|
+
return draft.update(doc, slot.keys, (value) => {
|
|
558
|
+
const list = Array.isArray(value) ? value : [];
|
|
559
|
+
return [...list.slice(0, index), node, ...list.slice(index)];
|
|
560
|
+
});
|
|
561
|
+
return draft.update(doc, slot.keys, (value) => value === undefined ? node : { node: "chain", steps: index === 0 ? [node, value] : [value, node] });
|
|
562
|
+
}
|
|
563
|
+
/** `doc` without the node `entry` names: spliced out of its array, or its slot emptied. */
|
|
564
|
+
const takeOut = (draft, doc, entry) => entry.many
|
|
565
|
+
? draft.update(doc, entry.keys.slice(0, -1), (value) => value.filter((_, index) => index !== entry.index))
|
|
566
|
+
: draft.update(doc, entry.keys, () => DELETE);
|
|
567
|
+
/** Replace the node `entry` names by `nodes`: spliced into its array, or, in a slot that holds one, the one node. */
|
|
568
|
+
const putInstead = (draft, doc, entry, nodes, count = 1) => entry.many
|
|
569
|
+
? draft.update(doc, entry.keys.slice(0, -1), (value) => { const list = value; return [...list.slice(0, entry.index), ...nodes, ...list.slice(entry.index + count)]; })
|
|
570
|
+
: draft.update(doc, entry.keys, () => nodes.length === 1 ? nodes[0] : { node: "chain", steps: nodes });
|
|
571
|
+
// ---- names, keys and references ---------------------------------------------------------------------------------------
|
|
572
|
+
const KEY_NAME = /^[A-Za-z0-9_]+$/;
|
|
573
|
+
const WHOLE_PLACEHOLDER = /^\{([a-zA-Z0-9_.$]+)(\?)?\}$/;
|
|
574
|
+
const INNER_PLACEHOLDER = /\{([a-zA-Z0-9_.$]+)\}/g;
|
|
575
|
+
/** Whether a node writes state under its label: an agent, decide, extract or code node with no `as`. A code node writes
|
|
576
|
+
* there when its code returns something other than a record; a record's own keys are its code's. */
|
|
577
|
+
const labelIsKey = (node) => (node.node === "agent" || node.node === "decide" || node.node === "extract" || node.node === "code") && node.as === undefined;
|
|
578
|
+
/** The state keys a node writes, as its fields name them (the keys of a record a code node returns are its code's). */
|
|
579
|
+
const keysWritten = (node) => [
|
|
580
|
+
...(typeof node.as === "string" ? [node.as] : []),
|
|
581
|
+
...(labelIsKey(node) && typeof node.label === "string" ? [node.label] : []),
|
|
582
|
+
...(typeof node.failedAs === "string" ? [node.failedAs] : []),
|
|
583
|
+
];
|
|
584
|
+
/** The literal sources of a code node or a call: never interpolated, never rewritten. */
|
|
585
|
+
const sourcesOf = (node) => (node.node === "code" || node.node === "call" ? ["code", "command"] : []).flatMap((field) => typeof node[field] === "string" ? [node[field]] : []);
|
|
586
|
+
/** Whether `text` names `word` as a whole word, or one of its engine-owned `<word>$...` keys. */
|
|
587
|
+
const mentions = (text, word) => new RegExp(`(^|[^A-Za-z0-9_$])${word.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}($|[^A-Za-z0-9_])`).test(text);
|
|
588
|
+
/** Refuse a name `Object.prototype` has (`constructor`, `toString`, `__proto__` and the rest), or `prototype`, as a
|
|
589
|
+
* label, an `as`, a `failedAs` or a route branch (vocabulary.ts isPrototypeName, the validator's rule too). */
|
|
590
|
+
const refusePrototypeName = (name, path) => {
|
|
591
|
+
if (typeof name === "string" && isPrototypeName(name))
|
|
592
|
+
throw new EditError("NAME_INVALID", path, `"${name}" is a name an object's prototype has`);
|
|
593
|
+
};
|
|
594
|
+
const renamePath = (path, rename, prefixed, at, optional = false) => {
|
|
595
|
+
const prefix = prefixed && path.startsWith("state.") ? "state." : "";
|
|
596
|
+
const [head, ...tail] = path.slice(prefix.length).split(".");
|
|
597
|
+
const next = rename(head, at, optional);
|
|
598
|
+
return next === head ? path : prefix + [next, ...tail].join(".");
|
|
599
|
+
};
|
|
600
|
+
/** A rewrite of `key` to `name` in a path's head, its engine-owned `<key>$...` keys included. */
|
|
601
|
+
const renameHead = (key, name) => (head) => head === key ? name : head.startsWith(`${key}$`) ? name + head.slice(key.length) : head;
|
|
602
|
+
/** A value with each `{placeholder}` in its strings rewritten, the same value when none changes. `at` is the value's
|
|
603
|
+
* pointer from the node. */
|
|
604
|
+
const renamePlaceholders = (value, rename, at) => {
|
|
605
|
+
if (typeof value === "string") {
|
|
606
|
+
const whole = WHOLE_PLACEHOLDER.exec(value);
|
|
607
|
+
if (whole) {
|
|
608
|
+
const path = renamePath(whole[1], rename, true, at, whole[2] !== undefined);
|
|
609
|
+
return path === whole[1] ? value : `{${path}${whole[2] ?? ""}}`;
|
|
610
|
+
}
|
|
611
|
+
const next = value.replace(INNER_PLACEHOLDER, (all, path) => { const renamed = renamePath(path, rename, true, at); return renamed === path ? all : `{${renamed}}`; });
|
|
612
|
+
return next === value ? value : next;
|
|
613
|
+
}
|
|
614
|
+
if (Array.isArray(value)) {
|
|
615
|
+
const next = value.map((inner, i) => renamePlaceholders(inner, rename, `${at}/${i}`));
|
|
616
|
+
return next.some((inner, i) => inner !== value[i]) ? next : value;
|
|
617
|
+
}
|
|
618
|
+
if (isObject(value)) {
|
|
619
|
+
const next = Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, renamePlaceholders(inner, rename, `${at}/${escape(key)}`)]));
|
|
620
|
+
return Object.keys(value).some((key) => next[key] !== value[key]) ? next : value;
|
|
621
|
+
}
|
|
622
|
+
return value;
|
|
623
|
+
};
|
|
624
|
+
/** A predicate with the state paths it reads (`path`, `key`, quote_missing's `pages`, and those of a `not`'s `of`) and
|
|
625
|
+
* the placeholders of its `ask` (`state`, `images`) rewritten. A quote_missing `field` names a field of each quote's
|
|
626
|
+
* record, not a state path. */
|
|
627
|
+
const renamePredicate = (value, rename, at) => {
|
|
628
|
+
if (!isObject(value))
|
|
629
|
+
return value;
|
|
630
|
+
const next = { ...value };
|
|
631
|
+
if (typeof value.path === "string")
|
|
632
|
+
next.path = renamePath(value.path, rename, false, `${at}/path`);
|
|
633
|
+
if (typeof value.key === "string")
|
|
634
|
+
next.key = renamePath(value.key, rename, false, `${at}/key`);
|
|
635
|
+
if (Array.isArray(value.pages)) {
|
|
636
|
+
const pages = value.pages.map((page, i) => typeof page === "string" ? renamePath(page, rename, false, `${at}/pages/${i}`) : page);
|
|
637
|
+
if (pages.some((page, i) => page !== value.pages[i]))
|
|
638
|
+
next.pages = pages;
|
|
639
|
+
}
|
|
640
|
+
if (value.state !== undefined)
|
|
641
|
+
next.state = renamePlaceholders(value.state, rename, `${at}/state`);
|
|
642
|
+
if (value.images !== undefined)
|
|
643
|
+
next.images = renamePlaceholders(value.images, rename, `${at}/images`);
|
|
644
|
+
if (value.of !== undefined)
|
|
645
|
+
next.of = renamePredicate(value.of, rename, `${at}/of`);
|
|
646
|
+
return Object.keys(value).some((key) => next[key] !== value[key]) ? next : value;
|
|
647
|
+
};
|
|
648
|
+
/** The keys a pick's or sift's describe gives its own candidate. */
|
|
649
|
+
const OWN_ITEM = new Set(["item", "item_index"]);
|
|
650
|
+
/** The node with each state reference of `mode` rewritten; the same node when none changes. Each reference is visited
|
|
651
|
+
* once, with the pointer, from the node, of the value it sits in. */
|
|
652
|
+
function renameReads(node, mode, rename) {
|
|
653
|
+
const next = { ...node };
|
|
654
|
+
const field = (name, fn) => { if (node[name] !== undefined)
|
|
655
|
+
next[name] = fn(node[name], `/${name}`); };
|
|
656
|
+
const path = (value, at) => typeof value === "string" ? renamePath(value, rename, false, at) : value;
|
|
657
|
+
const paths = (value, at) => {
|
|
658
|
+
if (!Array.isArray(value))
|
|
659
|
+
return value;
|
|
660
|
+
const renamed = value.map((inner, i) => path(inner, `${at}/${i}`));
|
|
661
|
+
return renamed.some((inner, i) => inner !== value[i]) ? renamed : value;
|
|
662
|
+
};
|
|
663
|
+
if (mode === "resultPath")
|
|
664
|
+
field("resultPath", path);
|
|
665
|
+
else if (mode === "until")
|
|
666
|
+
field("until", (value, at) => renamePredicate(value, rename, at));
|
|
667
|
+
else if (mode === "verify")
|
|
668
|
+
field("verify", (value, at) => isObject(value) ? renamePredicate({ ...value }, rename, at) : value);
|
|
669
|
+
else if (mode === "childOutput")
|
|
670
|
+
field("workflow", (child, at) => {
|
|
671
|
+
if (!isObject(child) || !isObject(child.output) || typeof child.output.path !== "string")
|
|
672
|
+
return child;
|
|
673
|
+
const renamed = path(child.output.path, `${at}/output/path`);
|
|
674
|
+
return renamed === child.output.path ? child : { ...child, output: { ...child.output, path: renamed } };
|
|
675
|
+
});
|
|
676
|
+
else {
|
|
677
|
+
for (const name of ["state", "images", "args", "env", "produces", "summary"])
|
|
678
|
+
field(name, (value, at) => renamePlaceholders(value, rename, at));
|
|
679
|
+
// A pick's or sift's describe reads the state, and its own candidate as `item` and `item_index`, which are no state's.
|
|
680
|
+
field("describe", (value, at) => renamePlaceholders(value, (head, inner) => OWN_ITEM.has(head) ? head : rename(head, inner), at));
|
|
681
|
+
if (node.node === "workflow" || node.node === "call")
|
|
682
|
+
field("input", (value, at) => renamePlaceholders(value, rename, at));
|
|
683
|
+
field("verify", (value, at) => isObject(value) ? renamePredicate({ ...value }, rename, at) : value);
|
|
684
|
+
for (const name of ["itemsPath", "valuePath", "resultPath"])
|
|
685
|
+
field(name, path);
|
|
686
|
+
field("requires", paths);
|
|
687
|
+
for (const name of ["until", "when"])
|
|
688
|
+
field(name, (value, at) => renamePredicate(value, rename, at));
|
|
689
|
+
}
|
|
690
|
+
return Object.keys(node).some((key) => next[key] !== node[key]) ? next : node;
|
|
691
|
+
}
|
|
692
|
+
/** The heads of the state paths a node's own fields read; a pick's or sift's describe counts all but its own item. */
|
|
693
|
+
function headsRead(node) {
|
|
694
|
+
const heads = new Set();
|
|
695
|
+
renameReads(node, "own", (head) => { heads.add(head); return head; });
|
|
696
|
+
return heads;
|
|
697
|
+
}
|
|
698
|
+
/** Each entry's path and place in its list, built once per list: namesInScope asks readersOf about every writer. */
|
|
699
|
+
const indexes = new WeakMap();
|
|
700
|
+
const indexOf = (entries) => {
|
|
701
|
+
let index = indexes.get(entries);
|
|
702
|
+
if (!index) {
|
|
703
|
+
index = { byPath: new Map(entries.map((entry) => [entry.path, entry])), place: new Map(entries.map((entry, i) => [entry, i])) };
|
|
704
|
+
indexes.set(entries, index);
|
|
705
|
+
}
|
|
706
|
+
return index;
|
|
707
|
+
};
|
|
708
|
+
/** The nodes that read what the node at `writer` writes, each with how much of it reads, and whether the document's
|
|
709
|
+
* `output.path` does. When the key is the writer's own `as` (`viaAs`), the writer reads it too: a route writes its
|
|
710
|
+
* choice before its branches run, and a verifier sees the submission under the node's `as`. */
|
|
711
|
+
function readersOf(entries, writer, viaAs = false) {
|
|
712
|
+
const { byPath, place } = indexOf(entries);
|
|
713
|
+
const readers = [];
|
|
714
|
+
// entriesOf lists a node's subtree right after it, so the subtree ends at the first entry outside it.
|
|
715
|
+
const subtree = (root) => {
|
|
716
|
+
for (let i = place.get(root) ?? entries.length; i < entries.length; i += 1) {
|
|
717
|
+
const entry = entries[i];
|
|
718
|
+
if (entry.path !== root.path && !entry.path.startsWith(`${root.path}/`))
|
|
719
|
+
break;
|
|
720
|
+
if (entry.scope === root.scope)
|
|
721
|
+
readers.push({ entry, mode: "own" });
|
|
722
|
+
}
|
|
723
|
+
};
|
|
724
|
+
if (viaAs && writer.node.node === "route")
|
|
725
|
+
for (const body of entries)
|
|
726
|
+
if (body.parentPath === writer.path)
|
|
727
|
+
subtree(body);
|
|
728
|
+
if (viaAs && writer.node.verify !== undefined)
|
|
729
|
+
readers.push({ entry: writer, mode: "verify" });
|
|
730
|
+
for (let at = writer;;) {
|
|
731
|
+
const parent = byPath.get(at.parentPath);
|
|
732
|
+
if (!parent)
|
|
733
|
+
return { readers, output: true };
|
|
734
|
+
switch (parent.node.node) {
|
|
735
|
+
case "chain":
|
|
736
|
+
for (const step of entries)
|
|
737
|
+
if (step.parentPath === parent.path && step.many && step.index > at.index)
|
|
738
|
+
subtree(step);
|
|
739
|
+
break;
|
|
740
|
+
case "map":
|
|
741
|
+
readers.push({ entry: parent, mode: "resultPath" });
|
|
742
|
+
return { readers, output: false };
|
|
743
|
+
case "loop": {
|
|
744
|
+
// A later pass reads what an earlier one wrote: the whole body is in scope, the writer and the steps before it too.
|
|
745
|
+
const body = entries.find((entry) => entry.parentPath === parent.path && entry.slot === "body");
|
|
746
|
+
if (body)
|
|
747
|
+
subtree(body);
|
|
748
|
+
readers.push({ entry: parent, mode: "until" });
|
|
749
|
+
break;
|
|
750
|
+
}
|
|
751
|
+
case "workflow":
|
|
752
|
+
readers.push({ entry: parent, mode: "childOutput" });
|
|
753
|
+
return { readers, output: false };
|
|
754
|
+
}
|
|
755
|
+
at = parent;
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
/** The workflow object a scope reads: the document, or a workflow node's child. */
|
|
759
|
+
const workflowOf = (doc, entries, scope) => {
|
|
760
|
+
if (scope === "")
|
|
761
|
+
return doc;
|
|
762
|
+
const owner = entries.find((entry) => entry.path === scope)?.node.workflow;
|
|
763
|
+
return isObject(owner) ? owner : {};
|
|
764
|
+
};
|
|
765
|
+
/** The keys a scope starts with: its input schema's properties and, for a child, the keys its input maps. */
|
|
766
|
+
const inputKeys = (doc, entries, scope) => {
|
|
767
|
+
const workflow = workflowOf(doc, entries, scope);
|
|
768
|
+
const id = isObject(workflow.input) ? workflow.input.schemaId : undefined;
|
|
769
|
+
const schema = typeof id === "string" && isObject(workflow.schemas) && Object.hasOwn(workflow.schemas, id) ? workflow.schemas[id] : undefined;
|
|
770
|
+
const keys = new Set(isObject(schema) && isObject(schema.properties) ? Object.keys(schema.properties) : []);
|
|
771
|
+
const owner = entries.find((entry) => entry.path === scope)?.node;
|
|
772
|
+
if (owner && isObject(owner.input))
|
|
773
|
+
for (const key of Object.keys(owner.input))
|
|
774
|
+
keys.add(key);
|
|
775
|
+
return keys;
|
|
776
|
+
};
|
|
777
|
+
/** Every name a key of the scope could clash with: the scope's labels (all but `self`'s), keys written, input keys, the
|
|
778
|
+
* heads of references and of the output path, the words of code and shell sources (the key a `<key>$...` head or word
|
|
779
|
+
* names included), and the engine's own keys. Another workflow's labels are not among them: a child runs on state of
|
|
780
|
+
* its own, and a run names its steps `<child>/<step>`. */
|
|
781
|
+
const namesUsed = (doc, entries, scope, self) => {
|
|
782
|
+
const used = new Set([...RESERVED_KEYS, ...inputKeys(doc, entries, scope)]);
|
|
783
|
+
for (const entry of entries) {
|
|
784
|
+
if (entry.scope !== scope)
|
|
785
|
+
continue;
|
|
786
|
+
if (typeof entry.node.label === "string" && entry !== self)
|
|
787
|
+
used.add(entry.node.label);
|
|
788
|
+
for (const key of keysWritten(entry.node))
|
|
789
|
+
used.add(key);
|
|
790
|
+
for (const head of headsRead(entry.node))
|
|
791
|
+
used.add(head).add(head.split("$")[0]);
|
|
792
|
+
for (const source of sourcesOf(entry.node))
|
|
793
|
+
for (const word of source.match(/[A-Za-z0-9_$]+/g) ?? [])
|
|
794
|
+
used.add(word).add(word.split("$")[0]);
|
|
795
|
+
}
|
|
796
|
+
const output = workflowOf(doc, entries, scope).output;
|
|
797
|
+
if (isObject(output) && typeof output.path === "string")
|
|
798
|
+
used.add(output.path.split(".")[0]).add(output.path.split(".")[0].split("$")[0]);
|
|
799
|
+
return used;
|
|
800
|
+
};
|
|
801
|
+
/** A name no name in `used` has, added to it: `base` itself when free, else its stem with the smallest `_<n>` from 2. */
|
|
802
|
+
const fresh = (base, used) => {
|
|
803
|
+
const stem = base.replace(/_\d+$/, "") || "node";
|
|
804
|
+
if (!used.has(stem) && stem === base && !RESERVED_KEYS.has(stem) && !isPrototypeName(stem)) {
|
|
805
|
+
used.add(stem);
|
|
806
|
+
return stem;
|
|
807
|
+
}
|
|
808
|
+
for (let n = 2;; n += 1) {
|
|
809
|
+
const name = `${stem}_${n}`;
|
|
810
|
+
if (!used.has(name)) {
|
|
811
|
+
used.add(name);
|
|
812
|
+
return name;
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
/** Rewrite, in `doc`, the reads of `key` by the readers of each writer: in each reader's fields, and the document's
|
|
817
|
+
* `output.path` when it reads. Returns the next document and the readers whose code mentions the key. */
|
|
818
|
+
function carry(draft, doc, entries, writers, rename, key, within, asKey) {
|
|
819
|
+
const seen = new Set();
|
|
820
|
+
const found = [];
|
|
821
|
+
let next = doc;
|
|
822
|
+
let output = false;
|
|
823
|
+
const inside = (path) => within === undefined || path === within || path.startsWith(`${within}/`);
|
|
824
|
+
for (const writer of writers) {
|
|
825
|
+
const scope = readersOf(entries, writer, asKey !== undefined && writer.node.as === asKey);
|
|
826
|
+
output ||= scope.output && within === undefined;
|
|
827
|
+
for (const { entry, mode } of scope.readers) {
|
|
828
|
+
if (!inside(entry.path) || seen.has(`${entry.path}|${mode}`))
|
|
829
|
+
continue;
|
|
830
|
+
seen.add(`${entry.path}|${mode}`);
|
|
831
|
+
if (mode === "own" && sourcesOf(entry.node).some((source) => mentions(source, key)) && !found.includes(entry.path))
|
|
832
|
+
found.push(entry.path);
|
|
833
|
+
next = draft.revise(next, entry.keys, (node) => renameReads(node, mode, rename));
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
if (output && isObject(doc.output) && typeof doc.output.path === "string") {
|
|
837
|
+
const path = renamePath(doc.output.path, rename, false, "/output/path");
|
|
838
|
+
if (path !== doc.output.path)
|
|
839
|
+
next = draft.update(next, ["output", "path"], () => path);
|
|
840
|
+
}
|
|
841
|
+
return { doc: next, mentions: found };
|
|
842
|
+
}
|
|
843
|
+
// ---- the operations ---------------------------------------------------------------------------------------------------
|
|
844
|
+
/** Put `node` (copied) into `slot` of the node at `parentPath`, at `index`. In a chain's steps or a parallel's branches
|
|
845
|
+
* the index is a position, 0 to the count. A slot that holds one node takes index 0 when empty; when it holds a node,
|
|
846
|
+
* 0 puts the new one first and 1 puts it last, in a new chain of the two. */
|
|
847
|
+
export function insert(doc, parentPath, slot, index, node) {
|
|
848
|
+
const before = documentOf(doc);
|
|
849
|
+
const added = nodeOf(node, `${parentPath}/${slot}`);
|
|
850
|
+
const draft = new Draft();
|
|
851
|
+
return finish(draft, before, place(draft, before, slotAt(before, entriesOf(before), parentPath, slot), index, clone(added)));
|
|
852
|
+
}
|
|
853
|
+
/** Take out the node at `path`, and everything inside it. */
|
|
854
|
+
export function remove(doc, path) {
|
|
855
|
+
const before = documentOf(doc);
|
|
856
|
+
const draft = new Draft();
|
|
857
|
+
return finish(draft, before, takeOut(draft, before, find(entriesOf(before), path)));
|
|
858
|
+
}
|
|
859
|
+
/** Move the node at `fromPath` into `slot` of the node at `toParentPath`, at `index`, counted in the document as given:
|
|
860
|
+
* the drop point a canvas shows. A node never moves inside itself. */
|
|
861
|
+
export function move(doc, fromPath, toParentPath, slot, index) {
|
|
862
|
+
const before = documentOf(doc);
|
|
863
|
+
const entries = entriesOf(before);
|
|
864
|
+
const from = find(entries, fromPath);
|
|
865
|
+
if (toParentPath === fromPath || toParentPath.startsWith(`${fromPath}/`))
|
|
866
|
+
throw new EditError("MOVE_INTO_SELF", fromPath, `${fromPath} cannot move inside itself (${toParentPath})`);
|
|
867
|
+
const target = slotAt(before, entries, toParentPath, slot);
|
|
868
|
+
checkIndex(target, index);
|
|
869
|
+
// Taking the node out shifts the later items of its array down by one: the target's parent and, in the same array, its index.
|
|
870
|
+
const holder = `${from.parentPath}/${from.slot}`;
|
|
871
|
+
const shift = (path) => {
|
|
872
|
+
if (!from.many || !path.startsWith(`${holder}/`))
|
|
873
|
+
return path;
|
|
874
|
+
const [at, ...rest] = path.slice(holder.length + 1).split("/");
|
|
875
|
+
return Number(at) > from.index ? [holder, String(Number(at) - 1), ...rest].join("/") : path;
|
|
876
|
+
};
|
|
877
|
+
const sameArray = from.many && target.many && target.path === holder;
|
|
878
|
+
const draft = new Draft();
|
|
879
|
+
const without = takeOut(draft, before, from);
|
|
880
|
+
const parent = shift(toParentPath);
|
|
881
|
+
return finish(draft, before, place(draft, without, slotAt(without, entriesOf(without), parent, slot), sameArray && from.index < index ? index - 1 : index, from.node));
|
|
882
|
+
}
|
|
883
|
+
/** Put a copy of the node at `path` right after it: the next step or branch, or, in a slot that holds one node, the
|
|
884
|
+
* second step of a new chain. Every node of the copy gets a fresh label, every key it writes a fresh name, and its own
|
|
885
|
+
* references follow its keys; the copy's code and shell sources that mention an old key are listed in `mentions`. */
|
|
886
|
+
export function duplicate(doc, path) {
|
|
887
|
+
const before = documentOf(doc);
|
|
888
|
+
const entries = entriesOf(before);
|
|
889
|
+
const source = find(entries, path);
|
|
890
|
+
// The copy as a document of its own: its nodes named afresh, then its reads of its own keys carried.
|
|
891
|
+
const scratch = new Draft();
|
|
892
|
+
let copy = { root: clone(source.node) };
|
|
893
|
+
const labels = new Set(entries.flatMap((entry) => typeof entry.node.label === "string" ? [entry.node.label] : []));
|
|
894
|
+
const names = new Set([...labels, ...namesUsed(before, entries, source.scope)]);
|
|
895
|
+
const renamed = new Map();
|
|
896
|
+
const inCopy = entriesOf(copy);
|
|
897
|
+
// A copied child workflow's keys also stay off the names its own scope uses: the keys its input gives it, first.
|
|
898
|
+
const childNames = new Map();
|
|
899
|
+
for (const entry of inCopy)
|
|
900
|
+
if (entry.scope !== "" && !childNames.has(entry.scope))
|
|
901
|
+
childNames.set(entry.scope, namesUsed(copy, inCopy, entry.scope));
|
|
902
|
+
for (const entry of inCopy) {
|
|
903
|
+
const key = (old) => {
|
|
904
|
+
const scope = renamed.get(entry.scope) ?? new Map();
|
|
905
|
+
renamed.set(entry.scope, scope);
|
|
906
|
+
if (!scope.has(old)) {
|
|
907
|
+
const name = fresh(old, entry.scope === "" ? names : new Set([...names, ...childNames.get(entry.scope)]));
|
|
908
|
+
names.add(name);
|
|
909
|
+
scope.set(old, name);
|
|
910
|
+
}
|
|
911
|
+
return scope.get(old);
|
|
912
|
+
};
|
|
913
|
+
copy = scratch.update(copy, entry.keys, (value) => {
|
|
914
|
+
const node = { ...value };
|
|
915
|
+
if (typeof node.label === "string")
|
|
916
|
+
node.label = labelIsKey(node) ? key(node.label) : fresh(node.label, labels);
|
|
917
|
+
if (typeof node.label === "string") {
|
|
918
|
+
labels.add(node.label);
|
|
919
|
+
names.add(node.label);
|
|
920
|
+
}
|
|
921
|
+
if (typeof node.as === "string")
|
|
922
|
+
node.as = key(node.as);
|
|
923
|
+
if (typeof node.failedAs === "string")
|
|
924
|
+
node.failedAs = key(node.failedAs);
|
|
925
|
+
return node;
|
|
926
|
+
});
|
|
927
|
+
}
|
|
928
|
+
for (const [scope, keys] of renamed)
|
|
929
|
+
for (const [old, name] of keys) {
|
|
930
|
+
const at = entriesOf(copy);
|
|
931
|
+
const writers = at.filter((entry) => entry.scope === scope && keysWritten(entry.node).includes(name));
|
|
932
|
+
copy = carry(scratch, copy, at, writers, renameHead(old, name), old, "/root", name).doc;
|
|
933
|
+
}
|
|
934
|
+
// Code is copied as it is, so the copy's code that names a key it writes afresh still names the old key. The copy's
|
|
935
|
+
// nodes are placed as they are, so they are found in the result by identity.
|
|
936
|
+
const named = new Set(entriesOf(copy).filter((entry) => {
|
|
937
|
+
const old = [...(renamed.get(entry.scope)?.keys() ?? [])];
|
|
938
|
+
return sourcesOf(entry.node).some((source) => old.some((key) => mentions(source, key)));
|
|
939
|
+
}).map((entry) => entry.node));
|
|
940
|
+
const draft = new Draft();
|
|
941
|
+
const target = slotAt(before, entries, source.parentPath, source.slot);
|
|
942
|
+
const result = finish(draft, before, place(draft, before, target, source.many ? source.index + 1 : 1, copy.root));
|
|
943
|
+
return { ...result, mentions: entriesOf(result.doc).filter((entry) => named.has(entry.node)).map((entry) => entry.path) };
|
|
944
|
+
}
|
|
945
|
+
/** Put the nodes at `paths` (one node, or consecutive steps or branches of one container, in any order) into a new
|
|
946
|
+
* container of `kind`, where the first of them was. A map's, loop's or route's body is the one node or a chain of
|
|
947
|
+
* them; a parallel takes each as a branch. The new container's fields are placeholders the validator flags. */
|
|
948
|
+
export function wrap(doc, paths, kind) {
|
|
949
|
+
const before = documentOf(doc);
|
|
950
|
+
if (!["map", "loop", "route", "parallel", "chain"].includes(kind))
|
|
951
|
+
throw new EditError("WRAP_INVALID", paths?.[0] ?? "", `"${String(kind)}" is not a container wrap makes`);
|
|
952
|
+
if (!Array.isArray(paths) || !paths.length)
|
|
953
|
+
throw new EditError("WRAP_INVALID", "", "wrap needs at least one node");
|
|
954
|
+
const entries = entriesOf(before);
|
|
955
|
+
const picked = paths.map((path) => find(entries, path)).sort((a, b) => a.index - b.index);
|
|
956
|
+
if (new Set(paths).size !== paths.length)
|
|
957
|
+
throw new EditError("WRAP_INVALID", paths[0], "a node is named twice");
|
|
958
|
+
const first = picked[0];
|
|
959
|
+
if (picked.length > 1 && !picked.every((entry, i) => entry.many && entry.parentPath === first.parentPath && entry.slot === first.slot && entry.index === first.index + i)) {
|
|
960
|
+
throw new EditError("WRAP_INVALID", first.path, "the nodes to wrap must be consecutive steps or branches of one container");
|
|
961
|
+
}
|
|
962
|
+
if (kind === "parallel" && picked.length < 2)
|
|
963
|
+
throw new EditError("WRAP_INVALID", first.path, "a parallel needs at least two nodes, one per branch");
|
|
964
|
+
const nodes = picked.map((entry) => entry.node);
|
|
965
|
+
const body = nodes.length === 1 ? nodes[0] : { node: "chain", steps: nodes };
|
|
966
|
+
const labels = new Set(entries.flatMap((entry) => typeof entry.node.label === "string" ? [entry.node.label] : []));
|
|
967
|
+
const names = new Set([...labels, ...namesUsed(before, entries, first.scope)]);
|
|
968
|
+
const label = kind === "chain" ? "" : fresh(kind, labels);
|
|
969
|
+
if (label)
|
|
970
|
+
names.add(label);
|
|
971
|
+
const container = kind === "chain" ? { node: "chain", steps: nodes }
|
|
972
|
+
: kind === "parallel" ? { node: "parallel", label, branches: nodes }
|
|
973
|
+
: kind === "map" ? { node: "map", label, itemsPath: placeholder("itemsPath"), as: fresh("results", names), body }
|
|
974
|
+
: kind === "loop" ? { node: "loop", label, body, until: placeholder("until"), maxIters: placeholder("maxIters") }
|
|
975
|
+
: { node: "route", label, valuePath: placeholder("valuePath"), branches: { match: { body }, skip: { body: { node: "code", label: fresh("skip", names), code: "s => ({})" } } }, otherwise: "skip" };
|
|
976
|
+
const draft = new Draft();
|
|
977
|
+
return finish(draft, before, putInstead(draft, before, first, [container], picked.length));
|
|
978
|
+
}
|
|
979
|
+
/** Whether the subtree at `body` reads one of `keys` (a key, or a key with a "$" suffix): a reference in its fields, or
|
|
980
|
+
* a word of its code. With `maps`, a nested map's body is left out: its `item` is that map's own. */
|
|
981
|
+
const bodyReads = (entries, owner, body, keys, maps) => {
|
|
982
|
+
const under = (path, root) => path === root || path.startsWith(`${root}/`);
|
|
983
|
+
// A nested map, the body itself included, reads its own item in its body; its own fields still read the outer one.
|
|
984
|
+
const nested = maps ? entries.filter((entry) => entry.node.node === "map" && under(entry.path, body)).map((entry) => `${entry.path}/body`) : [];
|
|
985
|
+
const reads = (head) => keys.some((key) => head === key || head.startsWith(`${key}$`));
|
|
986
|
+
return entries.some((entry) => entry.scope === owner.scope && under(entry.path, body) && !nested.some((inner) => under(entry.path, inner))
|
|
987
|
+
&& ([...headsRead(entry.node)].some(reads) || sourcesOf(entry.node).some((source) => keys.some((key) => mentions(source, key)))));
|
|
988
|
+
};
|
|
989
|
+
/** Put the children of the container at `path` where it was: a chain's steps or a parallel's branches, the body of a
|
|
990
|
+
* map or a loop, or the body of the route branch `branch` names. Into a chain they are spliced; a parallel's branches
|
|
991
|
+
* join an enclosing parallel; a slot that holds one node takes one child, or a chain of a parallel's branches. */
|
|
992
|
+
export function unwrap(doc, path, branch) {
|
|
993
|
+
const before = documentOf(doc);
|
|
994
|
+
const entries = entriesOf(before);
|
|
995
|
+
const entry = find(entries, path);
|
|
996
|
+
const node = entry.node;
|
|
997
|
+
const kind = String(node.node);
|
|
998
|
+
if (branch !== undefined && kind !== "route")
|
|
999
|
+
throw new EditError("UNWRAP_INVALID", path, `a ${kind} has no branch to keep`);
|
|
1000
|
+
let children;
|
|
1001
|
+
switch (kind) {
|
|
1002
|
+
case "chain":
|
|
1003
|
+
children = Array.isArray(node.steps) ? node.steps : [];
|
|
1004
|
+
break;
|
|
1005
|
+
case "parallel":
|
|
1006
|
+
children = Array.isArray(node.branches) ? node.branches : [];
|
|
1007
|
+
break;
|
|
1008
|
+
case "map":
|
|
1009
|
+
if (bodyReads(entries, entry, `${path}/body`, ["item", "item_index"], true))
|
|
1010
|
+
throw new EditError("UNWRAP_INVALID", path, `the body of ${path} reads the map's item; it cannot run outside the map`);
|
|
1011
|
+
children = [node.body];
|
|
1012
|
+
break;
|
|
1013
|
+
case "loop":
|
|
1014
|
+
children = [node.body];
|
|
1015
|
+
break;
|
|
1016
|
+
case "route":
|
|
1017
|
+
if (branch === undefined)
|
|
1018
|
+
throw new EditError("UNWRAP_INVALID", path, `name the branch of ${path} to keep`);
|
|
1019
|
+
if (!isObject(node.branches) || !Object.hasOwn(node.branches, branch) || !isObject(node.branches[branch]))
|
|
1020
|
+
throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch "${branch}"`);
|
|
1021
|
+
if (typeof node.as === "string" && bodyReads(entries, entry, `${path}/branches/${escape(branch)}/body`, [node.as], false))
|
|
1022
|
+
throw new EditError("UNWRAP_INVALID", path, `branch "${branch}" of ${path} reads the route's choice ("${node.as}"); it cannot run outside the route`);
|
|
1023
|
+
children = [node.branches[branch].body];
|
|
1024
|
+
break;
|
|
1025
|
+
default: throw new EditError("UNWRAP_INVALID", path, kind === "workflow" ? `${path} runs a child workflow on its own state; it is not unwrapped` : `a ${kind} node holds no nodes to unwrap`);
|
|
1026
|
+
}
|
|
1027
|
+
if (!children.length || !children.every(isNode))
|
|
1028
|
+
throw new EditError("UNWRAP_INVALID", path, `${path} holds no nodes to unwrap`);
|
|
1029
|
+
const nodes = children;
|
|
1030
|
+
const intoParallel = entry.many && entry.slot === "branches";
|
|
1031
|
+
if (intoParallel && kind !== "parallel" && nodes.length > 1)
|
|
1032
|
+
throw new EditError("UNWRAP_INVALID", path, `${path} is a parallel's branch; its ${nodes.length} steps cannot each become one`);
|
|
1033
|
+
if (!entry.many && kind === "chain" && nodes.length > 1)
|
|
1034
|
+
throw new EditError("UNWRAP_INVALID", path, `${path} is the one node of its slot; its steps have nowhere else to go`);
|
|
1035
|
+
const draft = new Draft();
|
|
1036
|
+
return finish(draft, before, putInstead(draft, before, entry, nodes));
|
|
1037
|
+
}
|
|
1038
|
+
/** Add a branch to the parallel or route at `path`: `node` (copied) last among a parallel's branches, or as the body of
|
|
1039
|
+
* a new route branch `name`, after the others. */
|
|
1040
|
+
export function addBranch(doc, path, node, name) {
|
|
1041
|
+
const before = documentOf(doc);
|
|
1042
|
+
const entry = find(entriesOf(before), path);
|
|
1043
|
+
const added = clone(nodeOf(node, path));
|
|
1044
|
+
const draft = new Draft();
|
|
1045
|
+
if (entry.node.node === "parallel") {
|
|
1046
|
+
if (name !== undefined)
|
|
1047
|
+
throw new EditError("NAME_INVALID", path, "a parallel's branches have no names");
|
|
1048
|
+
return finish(draft, before, draft.update(before, [...entry.keys, "branches"], (value) => [...(Array.isArray(value) ? value : []), added]));
|
|
1049
|
+
}
|
|
1050
|
+
if (entry.node.node !== "route")
|
|
1051
|
+
throw new EditError("SLOT_INVALID", path, `a ${String(entry.node.node)} node has no branches`);
|
|
1052
|
+
if (typeof name !== "string" || !name.trim())
|
|
1053
|
+
throw new EditError("NAME_INVALID", path, "a route branch needs a name");
|
|
1054
|
+
refusePrototypeName(name, path);
|
|
1055
|
+
if (isObject(entry.node.branches) && Object.hasOwn(entry.node.branches, name))
|
|
1056
|
+
throw new EditError("BRANCH_TAKEN", path, `${path} already has a branch "${name}"`);
|
|
1057
|
+
return finish(draft, before, draft.update(before, [...entry.keys, "branches"], (value) => Object.fromEntries([...Object.entries(isObject(value) ? value : {}), [name, { body: added }]])));
|
|
1058
|
+
}
|
|
1059
|
+
/** Take out a branch of the parallel or route at `path`: a parallel's by its index, a route's by its name. */
|
|
1060
|
+
export function removeBranch(doc, path, branch) {
|
|
1061
|
+
const before = documentOf(doc);
|
|
1062
|
+
const entry = find(entriesOf(before), path);
|
|
1063
|
+
const node = entry.node;
|
|
1064
|
+
const draft = new Draft();
|
|
1065
|
+
if (node.node === "parallel") {
|
|
1066
|
+
if (!Array.isArray(node.branches) || !Number.isInteger(branch) || branch < 0 || branch >= node.branches.length)
|
|
1067
|
+
throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch ${String(branch)}`);
|
|
1068
|
+
return finish(draft, before, draft.update(before, [...entry.keys, "branches"], (value) => value.filter((_, index) => index !== branch)));
|
|
1069
|
+
}
|
|
1070
|
+
if (node.node !== "route")
|
|
1071
|
+
throw new EditError("SLOT_INVALID", path, `a ${String(node.node)} node has no branches`);
|
|
1072
|
+
if (typeof branch !== "string" || !isObject(node.branches) || !Object.hasOwn(node.branches, branch))
|
|
1073
|
+
throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch "${String(branch)}"`);
|
|
1074
|
+
if (node.otherwise === branch || (isObject(node.unsure) && node.unsure.branch === branch))
|
|
1075
|
+
throw new EditError("BRANCH_IN_USE", path, `${node.otherwise === branch ? "otherwise" : "unsure"} names branch "${branch}" of ${path}`);
|
|
1076
|
+
return finish(draft, before, draft.update(before, [...entry.keys, "branches"], (value) => Object.fromEntries(Object.entries(value).filter(([key]) => key !== branch))));
|
|
1077
|
+
}
|
|
1078
|
+
/** Rename branch `from` of the route at `path` to `to`, in its place among the others; `otherwise` and `unsure` follow. */
|
|
1079
|
+
export function renameBranch(doc, path, from, to) {
|
|
1080
|
+
const before = documentOf(doc);
|
|
1081
|
+
const entry = find(entriesOf(before), path);
|
|
1082
|
+
const node = entry.node;
|
|
1083
|
+
if (node.node !== "route")
|
|
1084
|
+
throw new EditError("SLOT_INVALID", path, `a ${String(node.node)} node has no named branches`);
|
|
1085
|
+
if (!isObject(node.branches) || typeof from !== "string" || !Object.hasOwn(node.branches, from))
|
|
1086
|
+
throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch "${String(from)}"`);
|
|
1087
|
+
if (typeof to !== "string" || !to.trim())
|
|
1088
|
+
throw new EditError("NAME_INVALID", path, "a route branch needs a name");
|
|
1089
|
+
const draft = new Draft();
|
|
1090
|
+
if (to === from)
|
|
1091
|
+
return finish(draft, before, before);
|
|
1092
|
+
refusePrototypeName(to, path);
|
|
1093
|
+
if (Object.hasOwn(node.branches, to))
|
|
1094
|
+
throw new EditError("BRANCH_TAKEN", path, `${path} already has a branch "${to}"`);
|
|
1095
|
+
return finish(draft, before, draft.revise(before, entry.keys, (value) => {
|
|
1096
|
+
const route = { ...value };
|
|
1097
|
+
route.branches = Object.fromEntries(Object.entries(route.branches).map(([key, inner]) => [key === from ? to : key, inner]));
|
|
1098
|
+
if (route.otherwise === from)
|
|
1099
|
+
route.otherwise = to;
|
|
1100
|
+
if (isObject(route.unsure) && route.unsure.branch === from)
|
|
1101
|
+
route.unsure = { ...route.unsure, branch: to };
|
|
1102
|
+
return route;
|
|
1103
|
+
}));
|
|
1104
|
+
}
|
|
1105
|
+
/** Write `value` (copied) at the field of the node at `path`, in its place; `undefined` removes an optional field. */
|
|
1106
|
+
export function setField(doc, path, field, value) {
|
|
1107
|
+
const before = documentOf(doc);
|
|
1108
|
+
const entry = find(entriesOf(before), path);
|
|
1109
|
+
const kind = String(entry.node.node);
|
|
1110
|
+
if (field === "node")
|
|
1111
|
+
throw new EditError("FIELD_INVALID", path, "a node's kind is fixed; insert a node of the other kind instead");
|
|
1112
|
+
if ((SLOT_FIELDS[kind] ?? []).includes(field))
|
|
1113
|
+
throw new EditError("FIELD_INVALID", path, `"${field}" holds the ${kind}'s children; insert, remove, move and the branch operations write it`);
|
|
1114
|
+
if (!editableFields(entry.node).includes(field))
|
|
1115
|
+
throw new EditError("FIELD_INVALID", path, `a ${isByValue(entry.node) ? "route by value" : kind} node has no field "${field}"`);
|
|
1116
|
+
if (value === undefined && requiredFields(entry.node).includes(field))
|
|
1117
|
+
throw new EditError("FIELD_INVALID", path, `a ${kind} node needs "${field}"; it cannot be removed`);
|
|
1118
|
+
// Writing the value the field already holds is no change, whatever the name.
|
|
1119
|
+
if ((field === "label" || field === "as" || field === "failedAs") && value !== entry.node[field])
|
|
1120
|
+
refusePrototypeName(value, path);
|
|
1121
|
+
const draft = new Draft();
|
|
1122
|
+
return finish(draft, before, draft.update(before, [...entry.keys, field], () => value === undefined ? DELETE : clone(value)));
|
|
1123
|
+
}
|
|
1124
|
+
/** Another node of `entry`'s workflow labelled `name`. A label is unique in its workflow: a child workflow's labels are
|
|
1125
|
+
* its own (a run names its steps `<child>/<step>`). */
|
|
1126
|
+
const labelHolder = (entries, entry, name) => entries.find((other) => other !== entry && other.scope === entry.scope && other.node.label === name);
|
|
1127
|
+
/** Refuse a key another node of the scope or the scope's input also writes: a rename cannot tell whose readers are whose. */
|
|
1128
|
+
const checkUnshared = (doc, entries, entry, key) => {
|
|
1129
|
+
const others = entries.filter((other) => other !== entry && other.scope === entry.scope && keysWritten(other.node).includes(key));
|
|
1130
|
+
if (others.length || inputKeys(doc, entries, entry.scope).has(key)) {
|
|
1131
|
+
throw new EditError("NAME_SHARED", entry.path, `"${key}" is also written by ${others.length ? others.map((other) => other.path).join(", ") : "the workflow's input"}; a rename cannot tell whose readers are whose`, others.map((other) => other.path));
|
|
1132
|
+
}
|
|
1133
|
+
};
|
|
1134
|
+
/** Rename the label of the node at `path`. When the label is the key the node writes (an agent, decide, extract or code
|
|
1135
|
+
* node with no `as`), every reference in scope follows it, and the code and shell sources in scope that mention the old
|
|
1136
|
+
* key are listed in `mentions`, unchanged: a code node's own code included, when it names the key. */
|
|
1137
|
+
export function rename(doc, path, name) {
|
|
1138
|
+
const before = documentOf(doc);
|
|
1139
|
+
const entries = entriesOf(before);
|
|
1140
|
+
const entry = find(entries, path);
|
|
1141
|
+
const node = entry.node;
|
|
1142
|
+
if (!editableFields(node).includes("label"))
|
|
1143
|
+
throw new EditError("FIELD_INVALID", path, `a ${String(node.node)} node has no label`);
|
|
1144
|
+
const draft = new Draft();
|
|
1145
|
+
if (name === node.label)
|
|
1146
|
+
return { ...finish(draft, before, before), mentions: [] };
|
|
1147
|
+
if (typeof name !== "string" || !name.trim() || name.includes("$"))
|
|
1148
|
+
throw new EditError("NAME_INVALID", path, `a label is a non-empty name with no "$": ${JSON.stringify(name)}`);
|
|
1149
|
+
refusePrototypeName(name, path);
|
|
1150
|
+
const keyed = labelIsKey(node) && typeof node.label === "string";
|
|
1151
|
+
if (keyed && !KEY_NAME.test(name))
|
|
1152
|
+
throw new EditError("NAME_INVALID", path, `the label of ${path} is the key it writes, so it takes letters, digits and "_" only: ${JSON.stringify(name)}`);
|
|
1153
|
+
const holder = labelHolder(entries, entry, name);
|
|
1154
|
+
if (holder)
|
|
1155
|
+
throw new EditError("NAME_TAKEN", path, `${holder.path} is labelled "${name}"`, [holder.path]);
|
|
1156
|
+
const relabel = () => draft.update(before, [...entry.keys, "label"], () => name);
|
|
1157
|
+
if (!keyed)
|
|
1158
|
+
return { ...finish(draft, before, relabel()), mentions: [] };
|
|
1159
|
+
const key = node.label;
|
|
1160
|
+
if (namesUsed(before, entries, entry.scope).has(name))
|
|
1161
|
+
throw new EditError("NAME_TAKEN", path, `"${name}" is already a key, a reference, an input or a word of code in this workflow`);
|
|
1162
|
+
checkUnshared(before, entries, entry, key);
|
|
1163
|
+
const carried = carry(draft, relabel(), entries, [entry], renameHead(key, name), key);
|
|
1164
|
+
// A code node whose record names its own label still writes that key, under the old name: the caller must see it. In
|
|
1165
|
+
// a loop, the node reads its own key and carry has listed it already.
|
|
1166
|
+
const own = sourcesOf(node).some((source) => mentions(source, key)) && !carried.mentions.includes(path) ? [path] : [];
|
|
1167
|
+
return { ...finish(draft, before, carried.doc), mentions: [...own, ...carried.mentions] };
|
|
1168
|
+
}
|
|
1169
|
+
/** Rename the state key the node at `path` writes: its `as` when it has one, else its label when the label is the key
|
|
1170
|
+
* (an agent, decide, extract or code node with no `as`, where this is `rename`); or, with `field: "failedAs"`, the key a
|
|
1171
|
+
* map writes its failed items under. Every reference in scope follows it, `<key>$answers` and `<key>$verify` included,
|
|
1172
|
+
* and the code and shell sources in scope that mention the old key are listed in `mentions`, unchanged. */
|
|
1173
|
+
export function renameKey(doc, path, name, options = {}) {
|
|
1174
|
+
const before = documentOf(doc);
|
|
1175
|
+
const entries = entriesOf(before);
|
|
1176
|
+
const entry = find(entries, path);
|
|
1177
|
+
const node = entry.node;
|
|
1178
|
+
const field = options?.field ?? "as";
|
|
1179
|
+
if (field !== "as" && field !== "failedAs")
|
|
1180
|
+
throw new EditError("FIELD_INVALID", path, `renameKey renames "as" or "failedAs", not ${JSON.stringify(field)}`);
|
|
1181
|
+
if (typeof node[field] !== "string") {
|
|
1182
|
+
if (field === "as" && labelIsKey(node) && typeof node.label === "string")
|
|
1183
|
+
return rename(before, path, name);
|
|
1184
|
+
throw new EditError("FIELD_INVALID", path, field === "as"
|
|
1185
|
+
? `a ${String(node.node)} node ${node.as === undefined ? "with no as " : ""}writes no key of its own to rename`
|
|
1186
|
+
: `a ${String(node.node)} node with no failedAs has no failedAs to rename`);
|
|
1187
|
+
}
|
|
1188
|
+
const draft = new Draft();
|
|
1189
|
+
const key = node[field];
|
|
1190
|
+
if (name === key)
|
|
1191
|
+
return { ...finish(draft, before, before), mentions: [] };
|
|
1192
|
+
if (typeof name !== "string" || !KEY_NAME.test(name))
|
|
1193
|
+
throw new EditError("NAME_INVALID", path, `a state key takes letters, digits and "_" only: ${JSON.stringify(name)}`);
|
|
1194
|
+
refusePrototypeName(name, path);
|
|
1195
|
+
// The node's own label is a name, not a key: its key may take it.
|
|
1196
|
+
const holder = labelHolder(entries, entry, name);
|
|
1197
|
+
if (holder)
|
|
1198
|
+
throw new EditError("NAME_TAKEN", path, `${holder.path} is labelled "${name}"`, [holder.path]);
|
|
1199
|
+
if (namesUsed(before, entries, entry.scope, entry).has(name))
|
|
1200
|
+
throw new EditError("NAME_TAKEN", path, `"${name}" is already a key, a reference, an input or a word of code in this workflow`);
|
|
1201
|
+
checkUnshared(before, entries, entry, key);
|
|
1202
|
+
const carried = carry(draft, draft.update(before, [...entry.keys, field], () => name), entries, [entry], renameHead(key, name), key, undefined, field === "as" ? key : undefined);
|
|
1203
|
+
return { ...finish(draft, before, carried.doc), mentions: carried.mentions };
|
|
1204
|
+
}
|
|
1205
|
+
// ---- what an editor's property panel reads and writes --------------------------------------------------------------
|
|
1206
|
+
/** Write `criteria`, the text Jev reads to choose it, on branch `branch` of the judged route at `path`, in its place;
|
|
1207
|
+
* `undefined` removes it. A route by value matches its branches by name and takes no criteria. */
|
|
1208
|
+
export function setBranchCriteria(doc, path, branch, criteria) {
|
|
1209
|
+
const before = documentOf(doc);
|
|
1210
|
+
const entry = find(entriesOf(before), path);
|
|
1211
|
+
const node = entry.node;
|
|
1212
|
+
if (node.node !== "route")
|
|
1213
|
+
throw new EditError("SLOT_INVALID", path, `a ${String(node.node)} node has no branches`);
|
|
1214
|
+
if (isByValue(node))
|
|
1215
|
+
throw new EditError("FIELD_INVALID", path, `${path} is a route by value: it matches its branches by name and takes no criteria`);
|
|
1216
|
+
if (!isObject(node.branches) || typeof branch !== "string" || !Object.hasOwn(node.branches, branch) || !isObject(node.branches[branch]))
|
|
1217
|
+
throw new EditError("BRANCH_NOT_FOUND", path, `${path} has no branch "${String(branch)}"`);
|
|
1218
|
+
if (criteria !== undefined && typeof criteria !== "string")
|
|
1219
|
+
throw new EditError("FIELD_INVALID", path, `a branch's criteria are a text: ${JSON.stringify(criteria)}`);
|
|
1220
|
+
const draft = new Draft();
|
|
1221
|
+
return finish(draft, before, draft.update(before, [...entry.keys, "branches", branch, "criteria"], () => criteria === undefined ? DELETE : criteria));
|
|
1222
|
+
}
|
|
1223
|
+
/** The workflow a scope names: the document for "", or the child of the workflow node at that path. */
|
|
1224
|
+
const scopeOf = (doc, entries, scope) => {
|
|
1225
|
+
if (scope === "")
|
|
1226
|
+
return { workflow: doc, pointer: "", keys: [] };
|
|
1227
|
+
const entry = find(entries, scope);
|
|
1228
|
+
if (entry.node.node !== "workflow" || !isObject(entry.node.workflow))
|
|
1229
|
+
throw new EditError("SLOT_INVALID", scope, `a ${String(entry.node.node)} node holds no child workflow`);
|
|
1230
|
+
return { workflow: entry.node.workflow, pointer: `${scope}/workflow`, keys: [...entry.keys, "workflow"] };
|
|
1231
|
+
};
|
|
1232
|
+
/** The pointers, in `schema` (at `pointer`), of each `$ref` that names the workflow schema `id`: `#/definitions/<id>`.
|
|
1233
|
+
* One under the schema's own `definitions` counts too: the validator resolves it there only when the schema is the
|
|
1234
|
+
* one a field names, not when another schema's `$ref` reaches it. */
|
|
1235
|
+
const refsTo = (schema, id, pointer) => {
|
|
1236
|
+
const out = [];
|
|
1237
|
+
const visit = (value, at) => {
|
|
1238
|
+
if (Array.isArray(value))
|
|
1239
|
+
value.forEach((inner, i) => visit(inner, `${at}/${i}`));
|
|
1240
|
+
else if (isObject(value))
|
|
1241
|
+
for (const [key, inner] of Object.entries(value)) {
|
|
1242
|
+
if (key === "$ref" && inner === `#/definitions/${id}`)
|
|
1243
|
+
out.push(`${at}/${escape(key)}`);
|
|
1244
|
+
else
|
|
1245
|
+
visit(inner, `${at}/${escape(key)}`);
|
|
1246
|
+
}
|
|
1247
|
+
};
|
|
1248
|
+
visit(schema, pointer);
|
|
1249
|
+
return out;
|
|
1250
|
+
};
|
|
1251
|
+
/** The JSON Pointers of the values that name schema `id` of a scope ("" for the document, or a workflow node's path
|
|
1252
|
+
* for its child's schemas): the workflow's `input.schemaId` and `output.schemaId`, a `$ref` from another of its
|
|
1253
|
+
* schemas, and the `out` and `verify.out` of its nodes (a workflow node's `out` names its parent's schema). */
|
|
1254
|
+
export function schemaUsers(doc, id, scope = "") {
|
|
1255
|
+
const before = documentOf(doc);
|
|
1256
|
+
const entries = entriesOf(before);
|
|
1257
|
+
const { workflow, pointer } = scopeOf(before, entries, scope);
|
|
1258
|
+
const out = [];
|
|
1259
|
+
if (isObject(workflow.input) && workflow.input.schemaId === id)
|
|
1260
|
+
out.push(`${pointer}/input/schemaId`);
|
|
1261
|
+
if (isObject(workflow.output) && workflow.output.schemaId === id)
|
|
1262
|
+
out.push(`${pointer}/output/schemaId`);
|
|
1263
|
+
if (isObject(workflow.schemas))
|
|
1264
|
+
for (const [name, schema] of Object.entries(workflow.schemas))
|
|
1265
|
+
if (name !== id)
|
|
1266
|
+
out.push(...refsTo(schema, id, `${pointer}/schemas/${escape(name)}`));
|
|
1267
|
+
for (const entry of entries) {
|
|
1268
|
+
if (entry.scope !== scope)
|
|
1269
|
+
continue;
|
|
1270
|
+
if (entry.node.out === id)
|
|
1271
|
+
out.push(`${entry.path}/out`);
|
|
1272
|
+
if (isObject(entry.node.verify) && entry.node.verify.out === id)
|
|
1273
|
+
out.push(`${entry.path}/verify/out`);
|
|
1274
|
+
}
|
|
1275
|
+
return out;
|
|
1276
|
+
}
|
|
1277
|
+
/** Write `schema` (copied) as schema `id` of a scope ("" for the document, or a workflow node's path for its child), in
|
|
1278
|
+
* its place when it exists; `undefined` removes it, unless something still names it (`schemaUsers`). */
|
|
1279
|
+
export function setSchema(doc, id, schema, scope = "") {
|
|
1280
|
+
const before = documentOf(doc);
|
|
1281
|
+
const entries = entriesOf(before);
|
|
1282
|
+
const { workflow, keys } = scopeOf(before, entries, scope);
|
|
1283
|
+
if (typeof id !== "string" || !id.trim() || id === "__proto__")
|
|
1284
|
+
throw new EditError("NAME_INVALID", scope, `a schema id is a non-empty name other than "__proto__": ${JSON.stringify(id)}`);
|
|
1285
|
+
const schemas = isObject(workflow.schemas) ? workflow.schemas : undefined;
|
|
1286
|
+
const draft = new Draft();
|
|
1287
|
+
if (schema === undefined) {
|
|
1288
|
+
if (!schemas || !Object.hasOwn(schemas, id))
|
|
1289
|
+
throw new EditError("SCHEMA_NOT_FOUND", scope, `${scope || "the document"} has no schema "${id}"`);
|
|
1290
|
+
const users = schemaUsers(before, id, scope);
|
|
1291
|
+
if (users.length)
|
|
1292
|
+
throw new EditError("SCHEMA_IN_USE", scope, `schema "${id}" is named by ${users.join(", ")}`, users);
|
|
1293
|
+
return finish(draft, before, draft.update(before, [...keys, "schemas", id], () => DELETE));
|
|
1294
|
+
}
|
|
1295
|
+
if (!isObject(schema))
|
|
1296
|
+
throw new EditError("SCHEMA_INVALID", scope, `a schema is a JSON object: ${JSON.stringify(schema)}`);
|
|
1297
|
+
if (!schemas)
|
|
1298
|
+
return finish(draft, before, draft.update(before, [...keys, "schemas"], () => ({ [id]: clone(schema) })));
|
|
1299
|
+
return finish(draft, before, draft.update(before, [...keys, "schemas", id], () => clone(schema)));
|
|
1300
|
+
}
|
|
1301
|
+
/** The engine-owned keys a node writes beside `key`: a judge's, a pick's or a judged route's answers under
|
|
1302
|
+
* `<as>$answers`, and a verified node's verdict under `<key>$verify`. */
|
|
1303
|
+
const sidecarsOf = (node, key) => [
|
|
1304
|
+
...(key === node.as && (node.node === "judge" || node.node === "pick" || (node.node === "route" && !isByValue(node))) ? [`${key}$answers`] : []),
|
|
1305
|
+
...(node.verify !== undefined && key !== node.failedAs ? [`${key}$verify`] : []),
|
|
1306
|
+
];
|
|
1307
|
+
/** Whether the node sits in a map's body, in its own scope: it reads that map's `item` and `item_index`. */
|
|
1308
|
+
const inMapBody = (entries, target) => {
|
|
1309
|
+
const byPath = new Map(entries.map((entry) => [entry.path, entry]));
|
|
1310
|
+
for (let at = target;;) {
|
|
1311
|
+
const parent = byPath.get(at.parentPath);
|
|
1312
|
+
if (!parent || parent.scope !== target.scope)
|
|
1313
|
+
return false;
|
|
1314
|
+
if (parent.node.node === "map" && at.slot === "body")
|
|
1315
|
+
return true;
|
|
1316
|
+
at = parent;
|
|
1317
|
+
}
|
|
1318
|
+
};
|
|
1319
|
+
/** The names the node at `path` may read, each with what gives it, by the scope rules rename carries a key along: its
|
|
1320
|
+
* workflow's input keys, a map body's `item` and `item_index`, and the keys (with their `<key>$answers` and
|
|
1321
|
+
* `<key>$verify`) of each node whose write it runs after and sees. With `field`, the names that one field of the node
|
|
1322
|
+
* reads, where it sees more than the rest: a map's `resultPath` its body's keys and item, a loop's `until` its body's
|
|
1323
|
+
* keys, `verify` the node's own `as` and `submission`, a pick's or sift's `describe` its own `item` and `item_index`,
|
|
1324
|
+
* and a workflow node's `workflow` (its child's `output.path`) the child's state. */
|
|
1325
|
+
export function namesInScope(doc, path, field) {
|
|
1326
|
+
const before = documentOf(doc);
|
|
1327
|
+
const entries = entriesOf(before);
|
|
1328
|
+
const target = find(entries, path);
|
|
1329
|
+
const child = field === "workflow" && target.node.node === "workflow";
|
|
1330
|
+
const out = [];
|
|
1331
|
+
const seen = new Set();
|
|
1332
|
+
const add = (name, from) => { const key = JSON.stringify([name, from]); if (!seen.has(key)) {
|
|
1333
|
+
seen.add(key);
|
|
1334
|
+
out.push({ name, from });
|
|
1335
|
+
} };
|
|
1336
|
+
for (const key of inputKeys(before, entries, child ? target.path : target.scope))
|
|
1337
|
+
add(key, "input");
|
|
1338
|
+
// A map's body, and its resultPath, read the item; so does a pick's or sift's describe, its own candidate. A verifier
|
|
1339
|
+
// reads the node's result as `submission` too.
|
|
1340
|
+
const item = inMapBody(entries, target) || (field === "resultPath" && target.node.node === "map") || (field === "describe" && (target.node.node === "pick" || target.node.node === "sift"));
|
|
1341
|
+
if (!child && item)
|
|
1342
|
+
for (const key of OWN_ITEM)
|
|
1343
|
+
add(key, "engine");
|
|
1344
|
+
if (field === "verify" && target.node.verify !== undefined)
|
|
1345
|
+
add("submission", "engine");
|
|
1346
|
+
const modes = child ? ["childOutput"] : ["own", ...(field === "resultPath" || field === "until" || field === "verify" ? [field] : [])];
|
|
1347
|
+
const reads = (readers) => readers.some(({ entry, mode }) => entry === target && modes.includes(mode));
|
|
1348
|
+
for (const writer of entries) {
|
|
1349
|
+
const keys = keysWritten(writer.node);
|
|
1350
|
+
if (!keys.length)
|
|
1351
|
+
continue;
|
|
1352
|
+
// A key a node writes reaches its readers. Its own `as` also reaches a route's branches, which run after the route
|
|
1353
|
+
// wrote its choice and answers, and the node's verifier, which runs before its verdict is written.
|
|
1354
|
+
if (reads(readersOf(entries, writer).readers)) {
|
|
1355
|
+
for (const key of keys)
|
|
1356
|
+
for (const name of [key, ...sidecarsOf(writer.node, key)])
|
|
1357
|
+
add(name, writer.path);
|
|
1358
|
+
}
|
|
1359
|
+
else if (typeof writer.node.as === "string" && reads(readersOf(entries, writer, true).readers))
|
|
1360
|
+
for (const name of [writer.node.as, ...(writer.node.node === "route" ? sidecarsOf(writer.node, writer.node.as) : [])])
|
|
1361
|
+
add(name, writer.path);
|
|
1362
|
+
}
|
|
1363
|
+
return out;
|
|
1364
|
+
}
|
|
1365
|
+
/** Each `{placeholder}` and state path the node at `path` reads, in its fields' order: the references rename carries,
|
|
1366
|
+
* found by the same walk. A workflow node's include its child's `output.path`, which reads the child's state. */
|
|
1367
|
+
export function readsOf(doc, path) {
|
|
1368
|
+
const before = documentOf(doc);
|
|
1369
|
+
const entry = find(entriesOf(before), path);
|
|
1370
|
+
const out = [];
|
|
1371
|
+
const collect = (head, at, optional) => { out.push({ pointer: `${path}${at}`, name: head, ...(optional ? { optional: true } : {}) }); return head; };
|
|
1372
|
+
renameReads(entry.node, "own", collect);
|
|
1373
|
+
if (entry.node.node === "workflow")
|
|
1374
|
+
renameReads(entry.node, "childOutput", collect);
|
|
1375
|
+
return out;
|
|
1376
|
+
}
|
|
1377
|
+
/** The `{placeholder` open at `offset` in `text`: the index of its `{` and the name typed after it up to the cursor, by
|
|
1378
|
+
* the placeholder grammar (letters, digits, "_", "." and "$"; a reference may start with `state.`). Undefined when no
|
|
1379
|
+
* placeholder's name holds the cursor. The placeholder may already be closed after it. */
|
|
1380
|
+
export function openPlaceholderAt(text, offset) {
|
|
1381
|
+
if (typeof text !== "string" || !Number.isInteger(offset) || offset < 0 || offset > text.length)
|
|
1382
|
+
return undefined;
|
|
1383
|
+
let start = offset;
|
|
1384
|
+
while (start > 0 && /[A-Za-z0-9_.$]/.test(text[start - 1]))
|
|
1385
|
+
start -= 1;
|
|
1386
|
+
if (start === 0 || text[start - 1] !== "{")
|
|
1387
|
+
return undefined;
|
|
1388
|
+
return { start: start - 1, prefix: text.slice(start, offset) };
|
|
1389
|
+
}
|
|
1390
|
+
/** `base`, or its stem (`base` without a `_<n>` ending) with the smallest `_<n>` from 2, so that no label, key,
|
|
1391
|
+
* reference, input key or word of code of any scope of the document holds it (a child workflow's that holds no node
|
|
1392
|
+
* yet among them), nor an engine key or a name `Object.prototype` has. `base` is a state key name. */
|
|
1393
|
+
export function freshName(doc, base) {
|
|
1394
|
+
const before = documentOf(doc);
|
|
1395
|
+
if (typeof base !== "string" || !KEY_NAME.test(base))
|
|
1396
|
+
throw new EditError("NAME_INVALID", "", `a name takes letters, digits and "_" only: ${JSON.stringify(base)}`);
|
|
1397
|
+
const entries = entriesOf(before);
|
|
1398
|
+
const used = new Set();
|
|
1399
|
+
// Each workflow node's path is a scope, its child's first node not yet inserted included: that node is named here.
|
|
1400
|
+
const scopes = ["", ...entries.filter((entry) => entry.node.node === "workflow").map((entry) => entry.path)];
|
|
1401
|
+
for (const scope of scopes)
|
|
1402
|
+
for (const name of namesUsed(before, entries, scope))
|
|
1403
|
+
used.add(name);
|
|
1404
|
+
// `base` itself when free, numbered or not, and no reserved name (vocabulary.ts isPrototypeName, the validator's rule);
|
|
1405
|
+
// `fresh` alone numbers a numbered base from its stem even when it is free.
|
|
1406
|
+
if (!used.has(base) && !RESERVED_KEYS.has(base) && !isPrototypeName(base))
|
|
1407
|
+
return base;
|
|
1408
|
+
return fresh(base, used);
|
|
1409
|
+
}
|
|
1410
|
+
/** The smallest node of `kind` for `doc`: its required fields in the schema's order, a fresh name as its label (and its
|
|
1411
|
+
* `as`, where it needs one), and each other field's placeholder. A container is made by wrapping nodes that exist. */
|
|
1412
|
+
export function placeholderNode(doc, kind) {
|
|
1413
|
+
if (typeof kind !== "string" || !KINDS.has(kind))
|
|
1414
|
+
throw new EditError("NODE_INVALID", "", `no node kind "${String(kind)}"`);
|
|
1415
|
+
if (SLOT_FIELDS[kind])
|
|
1416
|
+
throw new EditError("NODE_INVALID", "", `a ${kind} holds nodes; wrap makes one of nodes that exist`);
|
|
1417
|
+
const name = freshName(doc, kind);
|
|
1418
|
+
const node = {};
|
|
1419
|
+
for (const field of requiredFields({ node: kind }))
|
|
1420
|
+
node[field] = field === "node" ? kind : field === "label" || field === "as" ? name : placeholder(field);
|
|
1421
|
+
return node;
|
|
1422
|
+
}
|