@sanity/workflow-engine 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/define.js CHANGED
@@ -1,965 +1,710 @@
1
- import * as v from "valibot";
2
- import { printGuardRead, andConditions, expandRequiredRoles, normalizeRoleAliases, RESERVED_CONDITION_VARS, GROQ_IDENTIFIER, CONDITION_VARS, formatValidationError, issuesFromValibot, AuthoringWorkflowSchema, WorkflowConfigSchema, AuthoringStageSchema, AuthoringActivitySchema, AuthoringActionSchema, AuthoringTransitionSchema, AuthoringFieldEntrySchema, AuthoringOpSchema, AuthoringGuardSchema, EffectSchema } from "./_chunks-es/schema.js";
3
- import { FILTER_SCOPE_VARS, GUARD_PREDICATE_VARS } from "./_chunks-es/schema.js";
1
+ import { printGuardRead, andConditions, expandRequiredRoles, normalizeRoleAliases, parseOrThrow, checkWorkflowInvariants, formatValidationError, AuthoringWorkflowSchema, labelFor, WorkflowConfigSchema, AuthoringStageSchema, AuthoringActivitySchema, AuthoringActionSchema, AuthoringTransitionSchema, AuthoringFieldEntrySchema, AuthoringOpSchema, GroupSchema, AuthoringGuardSchema, EffectSchema } from "./_chunks-es/invariants.js";
2
+
3
+ import { CONDITION_VARS, FILTER_SCOPE_VARS, GUARD_PREDICATE_VARS, RESERVED_CONDITION_VARS } from "./_chunks-es/invariants.js";
4
+
4
5
  function groq(strings, ...values) {
5
- return strings.reduce((out, part, i) => i === 0 ? part : `${out}${serializeGroqValue(values[i - 1])}${part}`, "");
6
+ return strings.reduce((out, part, i) => i === 0 ? part : `${out}${serializeGroqValue(values[i - 1])}${part}`, "");
6
7
  }
8
+
7
9
  function serializeGroqValue(value) {
8
- const serialized = JSON.stringify(value);
9
- if (serialized === void 0)
10
- throw new Error(
11
- `groq tag cannot serialize ${typeof value} \u2014 interpolate JSON-representable values only`
12
- );
13
- return serialized;
10
+ const serialized = JSON.stringify(value);
11
+ if (serialized === void 0) throw new Error(`groq tag cannot serialize ${typeof value} — interpolate JSON-representable values only`);
12
+ return serialized;
14
13
  }
14
+
15
15
  function desugarWorkflow(authoring) {
16
- const issues = [];
17
- checkReservedRoleAliasKeys(authoring.roleAliases, issues);
18
- const roleAliases = normalizeRoleAliases(authoring.roleAliases), ctx = {
19
- issues,
20
- claimFields: /* @__PURE__ */ new Map(),
21
- claimedFields: /* @__PURE__ */ new Set(),
22
- roleAliases
23
- }, workflowFields = desugarFieldEntries({ entries: authoring.fields, path: ["fields"], ctx }), workflowLayer = layerOf(workflowFields), stages = authoring.stages.map((stage, i) => {
24
- const path = ["stages", i], stageFields = desugarFieldEntries({ entries: stage.fields, path: [...path, "fields"], ctx }), stageEnv = {
25
- layers: [
26
- { scope: "stage", entries: layerOf(stageFields) },
27
- { scope: "workflow", entries: workflowLayer }
28
- ]
29
- }, activities = (stage.activities ?? []).map(
30
- (activity, j) => desugarActivity({ activity, path: [...path, "activities", j], stageEnv, ctx })
31
- ), transitions = (stage.transitions ?? []).map(
32
- (transition, k) => desugarTransition({ transition, path: [...path, "transitions", k], stageEnv, ctx })
33
- ), editable = desugarStageEditable({
34
- overrides: stage.editable,
35
- inScope: editableFieldNames({ workflowFields, stageFields, activities }),
36
- path: [...path, "editable"],
37
- ctx
16
+ const issues = [];
17
+ checkReservedRoleAliasKeys(authoring.roleAliases, issues);
18
+ const roleAliases = normalizeRoleAliases(authoring.roleAliases), ctx = {
19
+ issues: issues,
20
+ claimFields: /* @__PURE__ */ new Map,
21
+ claimedFields: /* @__PURE__ */ new Set,
22
+ roleAliases: roleAliases
23
+ }, workflowFields = desugarFieldEntries({
24
+ entries: authoring.fields,
25
+ path: [ "fields" ],
26
+ ctx: ctx
27
+ }), workflowLayer = layerOf(workflowFields), stages = authoring.stages.map((stage, i) => {
28
+ const path = [ "stages", i ], stageFields = desugarFieldEntries({
29
+ entries: stage.fields,
30
+ path: [ ...path, "fields" ],
31
+ ctx: ctx
32
+ }), stageEnv = {
33
+ layers: [ {
34
+ scope: "stage",
35
+ entries: layerOf(stageFields)
36
+ }, {
37
+ scope: "workflow",
38
+ entries: workflowLayer
39
+ } ]
40
+ }, activities = (stage.activities ?? []).map((activity, j) => desugarActivity({
41
+ activity: activity,
42
+ path: [ ...path, "activities", j ],
43
+ stageEnv: stageEnv,
44
+ ctx: ctx
45
+ })), transitions = (stage.transitions ?? []).map((transition, k) => desugarTransition({
46
+ transition: transition,
47
+ path: [ ...path, "transitions", k ],
48
+ stageEnv: stageEnv,
49
+ ctx: ctx
50
+ })), editable = desugarStageEditable({
51
+ overrides: stage.editable,
52
+ inScope: editableFieldNames({
53
+ workflowFields: workflowFields,
54
+ stageFields: stageFields,
55
+ activities: activities
56
+ }),
57
+ path: [ ...path, "editable" ],
58
+ ctx: ctx
59
+ });
60
+ return {
61
+ ...stripUndefined({
62
+ name: stage.name,
63
+ title: stage.title,
64
+ description: stage.description,
65
+ groups: stage.groups,
66
+ guards: stage.guards?.map(desugarGuard)
67
+ }),
68
+ ...stageFields ? {
69
+ fields: stageFields
70
+ } : {},
71
+ ...activities.length > 0 ? {
72
+ activities: activities
73
+ } : {},
74
+ ...transitions.length > 0 ? {
75
+ transitions: transitions
76
+ } : {},
77
+ ...editable ? {
78
+ editable: editable
79
+ } : {}
80
+ };
38
81
  });
39
- return {
40
- ...stripUndefined({
41
- name: stage.name,
42
- title: stage.title,
43
- description: stage.description,
44
- guards: stage.guards?.map(desugarGuard)
45
- }),
46
- ...stageFields ? { fields: stageFields } : {},
47
- ...activities.length > 0 ? { activities } : {},
48
- ...transitions.length > 0 ? { transitions } : {},
49
- ...editable ? { editable } : {}
82
+ return checkUnclaimedClaimFields(ctx), {
83
+ definition: {
84
+ ...stripUndefined({
85
+ name: authoring.name,
86
+ title: authoring.title,
87
+ description: authoring.description,
88
+ groups: authoring.groups,
89
+ lifecycle: authoring.lifecycle,
90
+ applicableWhen: authoring.applicableWhen,
91
+ initialStage: authoring.initialStage,
92
+ predicates: authoring.predicates,
93
+ roleAliases: roleAliases
94
+ }),
95
+ ...workflowFields ? {
96
+ fields: workflowFields
97
+ } : {},
98
+ stages: stages
99
+ },
100
+ issues: ctx.issues
50
101
  };
51
- });
52
- return checkUnclaimedClaimFields(ctx), { definition: {
53
- ...stripUndefined({
54
- name: authoring.name,
55
- title: authoring.title,
56
- description: authoring.description,
57
- lifecycle: authoring.lifecycle,
58
- initialStage: authoring.initialStage,
59
- predicates: authoring.predicates,
60
- roleAliases
61
- }),
62
- ...workflowFields ? { fields: workflowFields } : {},
63
- stages
64
- }, issues: ctx.issues };
65
102
  }
103
+
66
104
  function checkReservedRoleAliasKeys(aliases, issues) {
67
- for (const key of Object.keys(aliases ?? {}))
68
- key.startsWith("$") && issues.push({
69
- path: ["roleAliases", key],
70
- message: `role alias key "${key}" uses the reserved "$" prefix \u2014 that namespace is the engine's stored spelling for the universal fulfiller. Use "*" to mean "fulfills any gate", or rename the role.`
105
+ for (const key of Object.keys(aliases ?? {})) key.startsWith("$") && issues.push({
106
+ path: [ "roleAliases", key ],
107
+ message: `role alias key "${key}" uses the reserved "$" prefix — that namespace is the engine's stored spelling for the universal fulfiller. Use "*" to mean "fulfills any gate", or rename the role.`
71
108
  });
72
109
  }
73
- const TODOLIST_OF = [
74
- { type: "string", name: "label", title: "Label" },
75
- { type: "string", name: "status", title: "Status" },
76
- { type: "assignee", name: "assignee", title: "Assignee" },
77
- { type: "date", name: "dueDate", title: "Due date" }
78
- ], NOTES_OF = [
79
- { type: "text", name: "body", title: "Body" },
80
- { type: "actor", name: "actor", title: "Actor" },
81
- { type: "datetime", name: "at", title: "At" }
82
- ];
83
- function desugarFieldEntries({
84
- entries,
85
- path,
86
- ctx
87
- }) {
88
- return !entries || entries.length === 0 ? entries === void 0 ? void 0 : [] : entries.map((entry, i) => desugarFieldEntry({ entry, path: [...path, i], ctx }));
89
- }
90
- function desugarFieldEntry({
91
- entry,
92
- path,
93
- ctx
94
- }) {
95
- if (entry.type === "claim") return desugarClaimField({ entry, path, ctx });
96
- if (entry.type === "todoList" || entry.type === "notes")
97
- return desugarListField({ entry, path, ctx });
98
- const editable = normalizeEditable({ editable: entry.editable, path: [...path, "editable"], ctx });
99
- return {
100
- ...stripUndefined({
101
- type: entry.type,
102
- name: entry.name,
103
- title: entry.title,
104
- description: entry.description,
105
- required: entry.required,
106
- initialValue: entry.initialValue,
107
- editable,
108
- fields: entry.fields,
109
- of: entry.of
110
- })
111
- };
112
- }
113
- function desugarClaimField({
114
- entry,
115
- path,
116
- ctx
117
- }) {
118
- const desugared = {
119
- ...stripUndefined({ name: entry.name, title: entry.title, description: entry.description }),
120
- type: "actor"
121
- };
122
- return ctx.claimFields.set(desugared, { name: entry.name, path }), desugared;
123
- }
124
- function desugarListField({
125
- entry,
126
- path,
127
- ctx
128
- }) {
129
- const editable = normalizeEditable({ editable: entry.editable, path: [...path, "editable"], ctx });
130
- return {
131
- ...stripUndefined({
132
- name: entry.name,
133
- title: entry.title,
134
- description: entry.description,
135
- required: entry.required,
136
- initialValue: entry.initialValue,
137
- editable
138
- }),
139
- type: "array",
140
- of: entry.type === "todoList" ? TODOLIST_OF : NOTES_OF
141
- };
142
- }
143
- function normalizeEditable({
144
- editable,
145
- path,
146
- ctx
147
- }) {
148
- if (editable === void 0 || editable === !0) return editable;
149
- if (Array.isArray(editable)) {
150
- const condition = rolesCondition(editable, ctx.roleAliases);
151
- if (condition === void 0) {
152
- ctx.issues.push({
153
- path,
154
- message: "editable: [] names no roles \u2014 use `true` to open the field to anyone in its scope, or list at least one role"
155
- });
156
- return;
157
- }
158
- return condition;
159
- }
160
- return editable;
161
- }
162
- function editableFieldNames({
163
- workflowFields,
164
- stageFields,
165
- activities
166
- }) {
167
- const names = /* @__PURE__ */ new Set(), collect = (entries) => {
168
- for (const entry of entries ?? []) entry.editable !== void 0 && names.add(entry.name);
169
- };
170
- collect(workflowFields), collect(stageFields);
171
- for (const activity of activities) collect(activity.fields);
172
- return names;
173
- }
174
- function desugarStageEditable({
175
- overrides,
176
- inScope,
177
- path,
178
- ctx
179
- }) {
180
- if (overrides === void 0) return;
181
- const out = {};
182
- for (const [name, value] of Object.entries(overrides)) {
183
- if (!inScope.has(name)) {
184
- ctx.issues.push({
185
- path: [...path, name],
186
- message: `stage editable override "${name}" does not narrow an editable field in scope \u2014 name a workflow/stage/activity field of this stage that declares \`editable\``
187
- });
188
- continue;
189
- }
190
- const normalized = normalizeEditable({ editable: value, path: [...path, name], ctx });
191
- normalized !== void 0 && (out[name] = normalized);
192
- }
193
- return Object.keys(out).length > 0 ? out : void 0;
194
- }
195
- function layerOf(entries) {
196
- return new Map((entries ?? []).map((entry) => [entry.name, entry]));
197
- }
198
- function desugarActivity({
199
- activity,
200
- path,
201
- stageEnv,
202
- ctx
203
- }) {
204
- const activityFields = desugarFieldEntries({
205
- entries: activity.fields,
206
- path: [...path, "fields"],
207
- ctx
208
- }), env = {
209
- layers: [{ scope: "activity", entries: layerOf(activityFields) }, ...stageEnv.layers]
210
- }, ops = desugarOps({
211
- ops: activity.ops,
212
- path: [...path, "ops"],
213
- env,
214
- firingActivity: activity.name,
215
- ctx
216
- }), actions = (activity.actions ?? []).map(
217
- (action, a) => desugarAction({ action, path: [...path, "actions", a], env, activityName: activity.name, ctx })
218
- ), target = desugarTarget({ target: activity.target, env, path: [...path, "target"], ctx });
219
- return {
220
- ...stripUndefined({
221
- name: activity.name,
222
- title: activity.title,
223
- description: activity.description,
224
- kind: activity.kind,
225
- filter: activity.filter,
226
- requirements: activity.requirements,
227
- completeWhen: activity.completeWhen,
228
- failWhen: activity.failWhen,
229
- effects: activity.effects,
230
- subworkflows: activity.subworkflows
231
- }),
232
- activation: activity.activation ?? "manual",
233
- ...target ? { target } : {},
234
- ...activityFields ? { fields: activityFields } : {},
235
- ...ops ? { ops } : {},
236
- ...actions.length > 0 ? { actions } : {}
237
- };
238
- }
239
- const TARGET_DOC_KINDS = ["doc.ref", "doc.refs", "release.ref"];
240
- function desugarTarget({
241
- target,
242
- env,
243
- path,
244
- ctx
245
- }) {
246
- if (target === void 0 || target.type === "url") return target;
247
- const ref = typeof target.field == "string" ? { field: target.field } : target.field, field = resolveRef({ ref, env, path: [...path, "field"], ctx }) ?? fallbackRef(ref), entry = entryAt(env, field);
248
- return entry && !TARGET_DOC_KINDS.includes(entry.type) && ctx.issues.push({
249
- path: [...path, "field"],
250
- message: `manual activity target references "${field.field}" of kind "${entry.type}" \u2014 a deep-link target needs a document-valued entry (${TARGET_DOC_KINDS.join(", ")})`
251
- }), { type: "field", field };
252
- }
253
- function desugarAction({
254
- action,
255
- path,
256
- env,
257
- activityName,
258
- ctx
259
- }) {
260
- if ("type" in action)
261
- return desugarClaimAction({ action, path, env, ctx });
262
- const filter = andConditions([rolesCondition(action.roles, ctx.roleAliases), action.filter]), ops = desugarOps({ ops: action.ops, path: [...path, "ops"], env, firingActivity: activityName, ctx }) ?? [];
263
- return action.status !== void 0 && ops.push({ type: "status.set", activity: activityName, status: action.status }), {
264
- ...stripUndefined({
265
- name: action.name,
266
- title: action.title,
267
- description: action.description,
268
- params: action.params,
269
- effects: action.effects
270
- }),
271
- ...filter ? { filter } : {},
272
- ...ops.length > 0 ? { ops } : {}
273
- };
274
- }
275
- function desugarClaimAction({
276
- action,
277
- path,
278
- env,
279
- ctx
280
- }) {
281
- const ref = typeof action.field == "string" ? { field: action.field } : action.field, resolved = resolveRef({ ref, env, path: [...path, "field"], ctx });
282
- if (resolved) {
283
- const entry = entryAt(env, resolved);
284
- entry && entry.type !== "actor" && ctx.issues.push({
285
- path: [...path, "field"],
286
- message: `claim action "${action.name}" references "${resolved.field}" of kind "${entry.type}" \u2014 a claim pair needs an actor-valued entry (a "claim" or "actor" field declaration)`
287
- }), checkShadowedClaimTarget({
288
- actionName: action.name,
289
- field: ref.field,
290
- resolved,
291
- env,
292
- path: [...path, "field"],
293
- ctx
294
- }), entry && ctx.claimedFields.add(entry);
295
- }
296
- const noSteal = `!defined($fields.${ref.field})`, filter = andConditions([
297
- noSteal,
298
- rolesCondition(action.roles, ctx.roleAliases),
299
- action.filter
300
- ]), ops = resolved ? [{ type: "field.set", target: resolved, value: { type: "actor" } }] : [];
301
- return {
302
- ...stripUndefined({
303
- name: action.name,
304
- title: action.title,
305
- description: action.description,
306
- params: action.params,
307
- effects: action.effects
308
- }),
309
- filter,
310
- ...ops.length > 0 ? { ops } : {}
311
- };
312
- }
313
- function checkShadowedClaimTarget({
314
- actionName,
315
- field,
316
- resolved,
317
- env,
318
- path,
319
- ctx
320
- }) {
321
- const nearest = env.layers.find((l) => l.entries.has(field));
322
- nearest === void 0 || nearest.scope === resolved.scope || ctx.issues.push({
323
- path,
324
- message: `claim action "${actionName}" targets "${field}" at scope "${resolved.scope}", but a nearer ${nearest.scope}-scope entry of the same name shadows it in $fields \u2014 the no-steal filter would read the shadowing entry while the claim writes the "${resolved.scope}" one. Rename one of the entries or claim the nearer one`
325
- });
326
- }
327
- function checkUnclaimedClaimFields(ctx) {
328
- for (const [entry, { name, path }] of ctx.claimFields)
329
- ctx.claimedFields.has(entry) || ctx.issues.push({
330
- path,
331
- message: `claim field "${name}" is never referenced by a claim action \u2014 you announced the pattern and wrote half of it. Declare a defineAction({ type: "claim", field: "${name}" }) or use a raw actor entry`
110
+
111
+ const TODOLIST_OF = [ {
112
+ type: "string",
113
+ name: "label",
114
+ title: "Label"
115
+ }, {
116
+ type: "string",
117
+ name: "status",
118
+ title: "Status"
119
+ }, {
120
+ type: "assignee",
121
+ name: "assignee",
122
+ title: "Assignee"
123
+ }, {
124
+ type: "date",
125
+ name: "dueDate",
126
+ title: "Due date"
127
+ } ], NOTES_OF = [ {
128
+ type: "text",
129
+ name: "body",
130
+ title: "Body"
131
+ }, {
132
+ type: "actor",
133
+ name: "actor",
134
+ title: "Actor"
135
+ }, {
136
+ type: "datetime",
137
+ name: "at",
138
+ title: "At"
139
+ } ];
140
+
141
+ function desugarFieldEntries({entries: entries, path: path, ctx: ctx}) {
142
+ return !entries || entries.length === 0 ? entries === void 0 ? void 0 : [] : entries.map((entry, i) => desugarFieldEntry({
143
+ entry: entry,
144
+ path: [ ...path, i ],
145
+ ctx: ctx
146
+ }));
147
+ }
148
+
149
+ function desugarFieldEntry({entry: entry, path: path, ctx: ctx}) {
150
+ if (entry.type === "claim") return desugarClaimField({
151
+ entry: entry,
152
+ path: path,
153
+ ctx: ctx
154
+ });
155
+ if (entry.type === "todoList" || entry.type === "notes") return desugarListField({
156
+ entry: entry,
157
+ path: path,
158
+ ctx: ctx
332
159
  });
160
+ const editable = normalizeEditable({
161
+ editable: entry.editable,
162
+ path: [ ...path, "editable" ],
163
+ ctx: ctx
164
+ });
165
+ return {
166
+ ...stripUndefined({
167
+ type: entry.type,
168
+ name: entry.name,
169
+ title: entry.title,
170
+ description: entry.description,
171
+ group: normalizeGroup(entry.group),
172
+ required: entry.required,
173
+ initialValue: entry.initialValue,
174
+ editable: editable,
175
+ types: entry.types,
176
+ fields: entry.fields,
177
+ of: entry.of
178
+ })
179
+ };
333
180
  }
334
- function desugarTransition({
335
- transition,
336
- path,
337
- stageEnv,
338
- ctx
339
- }) {
340
- const ops = desugarOps({
341
- ops: transition.ops,
342
- path: [...path, "ops"],
343
- env: stageEnv,
344
- firingActivity: void 0,
345
- ctx
346
- });
347
- return {
348
- ...stripUndefined({
349
- name: transition.name,
350
- title: transition.title,
351
- description: transition.description,
352
- to: transition.to,
353
- effects: transition.effects
354
- }),
355
- filter: transition.filter ?? "$allActivitiesDone",
356
- ...ops ? { ops } : {}
357
- };
181
+
182
+ function desugarClaimField({entry: entry, path: path, ctx: ctx}) {
183
+ const desugared = {
184
+ ...stripUndefined({
185
+ name: entry.name,
186
+ title: entry.title,
187
+ description: entry.description,
188
+ group: normalizeGroup(entry.group)
189
+ }),
190
+ type: "actor"
191
+ };
192
+ return ctx.claimFields.set(desugared, {
193
+ name: entry.name,
194
+ path: path
195
+ }), desugared;
196
+ }
197
+
198
+ function desugarListField({entry: entry, path: path, ctx: ctx}) {
199
+ const editable = normalizeEditable({
200
+ editable: entry.editable,
201
+ path: [ ...path, "editable" ],
202
+ ctx: ctx
203
+ });
204
+ return {
205
+ ...stripUndefined({
206
+ name: entry.name,
207
+ title: entry.title,
208
+ description: entry.description,
209
+ group: normalizeGroup(entry.group),
210
+ required: entry.required,
211
+ initialValue: entry.initialValue,
212
+ editable: editable
213
+ }),
214
+ type: "array",
215
+ of: entry.type === "todoList" ? TODOLIST_OF : NOTES_OF
216
+ };
358
217
  }
359
- function desugarGuard(guard) {
360
- const { match, metadata, ...rest } = guard, { idRefs, ...matchRest } = match;
361
- return {
362
- ...rest,
363
- match: {
364
- ...matchRest,
365
- ...idRefs !== void 0 ? { idRefs: idRefs.map(printGuardRead) } : {}
366
- },
367
- ...metadata !== void 0 ? {
368
- metadata: Object.fromEntries(
369
- Object.entries(metadata).map(([key, read]) => [key, printGuardRead(read)])
370
- )
371
- } : {}
372
- };
373
- }
374
- function desugarOps({
375
- ops,
376
- path,
377
- env,
378
- firingActivity,
379
- ctx
380
- }) {
381
- if (ops)
382
- return ops.map((op, i) => desugarOp({ op, path: [...path, i], env, firingActivity, ctx }));
383
- }
384
- function desugarOp({
385
- op,
386
- path,
387
- env,
388
- firingActivity,
389
- ctx
390
- }) {
391
- if (op.type === "status.set") {
392
- const activity = op.activity ?? firingActivity;
393
- return activity === void 0 && ctx.issues.push({
394
- path: [...path, "activity"],
395
- message: "status.set outside an action must name its target activity"
396
- }), { type: "status.set", activity: activity ?? "", status: op.status };
397
- }
398
- if (op.type === "audit") return desugarAuditOp({ op, path, env, ctx });
399
- const target = resolveRef({ ref: op.target, env, path: [...path, "target"], ctx }) ?? fallbackRef(op.target);
400
- return { ...op, target };
401
- }
402
- const AUDIT_STAMPS = { actor: { type: "actor" }, at: { type: "now" } };
403
- function desugarAuditOp({
404
- op,
405
- path,
406
- env,
407
- ctx
408
- }) {
409
- const target = resolveRef({ ref: op.target, env, path: [...path, "target"], ctx }) ?? fallbackRef(op.target);
410
- if (op.value.type !== "object")
411
- return ctx.issues.push({
412
- path: [...path, "value"],
413
- message: `audit value must be an object source carrying the domain fields (got "${op.value.type}")`
414
- }), { type: "field.append", target, value: op.value };
415
- const actorField = op.stampFields?.actor ?? "actor", atField = op.stampFields?.at ?? "at", fields = { ...op.value.fields };
416
- for (const [stamp, source] of [
417
- [actorField, AUDIT_STAMPS.actor],
418
- [atField, AUDIT_STAMPS.at]
419
- ]) {
420
- if (stamp in fields) {
421
- ctx.issues.push({
422
- path: [...path, "value", "fields", stamp],
423
- message: `audit stamp field "${stamp}" collides with an authored domain field \u2014 rename yours or remap the stamp via stampFields`
424
- });
425
- continue;
218
+
219
+ function normalizeEditable({editable: editable, path: path, ctx: ctx}) {
220
+ if (editable === void 0 || editable === !0) return editable;
221
+ if (Array.isArray(editable)) {
222
+ const condition = rolesCondition(editable, ctx.roleAliases);
223
+ if (condition === void 0) {
224
+ ctx.issues.push({
225
+ path: path,
226
+ message: "editable: [] names no roles — use `true` to open the field to anyone in its scope, or list at least one role"
227
+ });
228
+ return;
229
+ }
230
+ return condition;
426
231
  }
427
- fields[stamp] = source;
428
- }
429
- return { type: "field.append", target, value: { type: "object", fields } };
430
- }
431
- function resolveRef({
432
- ref,
433
- env,
434
- path,
435
- ctx
436
- }) {
437
- const layers = ref.scope === void 0 ? env.layers : env.layers.filter((l) => l.scope === ref.scope);
438
- for (const layer of layers)
439
- if (layer.entries.has(ref.field)) return { scope: layer.scope, field: ref.field };
440
- const reachable = env.layers.flatMap((l) => [...l.entries.keys()].map((n) => `${l.scope}:${n}`));
441
- ctx.issues.push({
442
- path,
443
- message: `field reference "${ref.field}"${ref.scope ? ` (scope "${ref.scope}")` : ""} does not resolve to a declared entry. Reachable: ${reachable.join(", ") || "(none)"}`
444
- });
232
+ return editable;
445
233
  }
446
- function entryAt(env, ref) {
447
- return env.layers.find((l) => l.scope === ref.scope)?.entries.get(ref.field);
234
+
235
+ function editableFieldNames({workflowFields: workflowFields, stageFields: stageFields, activities: activities}) {
236
+ const names = /* @__PURE__ */ new Set, collect = entries => {
237
+ for (const entry of entries ?? []) entry.editable !== void 0 && names.add(entry.name);
238
+ };
239
+ collect(workflowFields), collect(stageFields);
240
+ for (const activity of activities) collect(activity.fields);
241
+ return names;
242
+ }
243
+
244
+ function desugarStageEditable({overrides: overrides, inScope: inScope, path: path, ctx: ctx}) {
245
+ if (overrides === void 0) return;
246
+ const out = {};
247
+ for (const [name, value] of Object.entries(overrides)) {
248
+ if (!inScope.has(name)) {
249
+ ctx.issues.push({
250
+ path: [ ...path, name ],
251
+ message: `stage editable override "${name}" does not narrow an editable field in scope — name a workflow/stage/activity field of this stage that declares \`editable\``
252
+ });
253
+ continue;
254
+ }
255
+ const normalized = normalizeEditable({
256
+ editable: value,
257
+ path: [ ...path, name ],
258
+ ctx: ctx
259
+ });
260
+ normalized !== void 0 && (out[name] = normalized);
261
+ }
262
+ return Object.keys(out).length > 0 ? out : void 0;
448
263
  }
449
- function fallbackRef(ref) {
450
- return { scope: ref.scope ?? "workflow", field: ref.field };
264
+
265
+ function layerOf(entries) {
266
+ return new Map((entries ?? []).map(entry => [ entry.name, entry ]));
451
267
  }
452
- function rolesCondition(roles, aliases) {
453
- if (!(!roles || roles.length === 0))
454
- return groq`count($actor.roles[@ in ${expandRequiredRoles(roles, aliases)}]) > 0`;
268
+
269
+ function normalizeGroup(group) {
270
+ return group === void 0 || Array.isArray(group) ? group : [ group ];
455
271
  }
456
- function stripUndefined(obj) {
457
- const out = {};
458
- for (const [k, value] of Object.entries(obj))
459
- value !== void 0 && (out[k] = value);
460
- return out;
461
- }
462
- const PREDICATE_CALLER_VARS = CONDITION_VARS.filter((v2) => v2.binding === "caller").map(
463
- (v2) => v2.name
464
- );
465
- function knownList(ids) {
466
- return [...ids].map((s) => `"${s}"`).join(", ");
467
- }
468
- function checkDuplicates({
469
- names,
470
- what,
471
- issues
472
- }) {
473
- const seen = /* @__PURE__ */ new Set();
474
- for (const { name, path } of names)
475
- seen.has(name) && issues.push({ path, message: `duplicate ${what} "${name}" (already declared earlier)` }), seen.add(name);
476
- return seen;
477
- }
478
- function checkStages(def, issues) {
479
- const stageNames = checkDuplicates({
480
- names: def.stages.map((stage, i) => ({ name: stage.name, path: ["stages", i, "name"] })),
481
- what: "stage name",
482
- issues
483
- });
484
- for (const [i, stage] of def.stages.entries()) {
485
- const activityNames = checkDuplicates({
486
- names: (stage.activities ?? []).map((activity, j) => ({
487
- name: activity.name,
488
- path: ["stages", i, "activities", j, "name"]
489
- })),
490
- what: `activity name in stage "${stage.name}"`,
491
- issues
492
- });
493
- checkDuplicates({
494
- names: (stage.transitions ?? []).map((t, k) => ({
495
- name: t.name,
496
- path: ["stages", i, "transitions", k, "name"]
497
- })),
498
- what: `transition name in stage "${stage.name}"`,
499
- issues
500
- }), checkActivities({ def, i, activityNames, issues });
501
- }
502
- return stageNames;
503
- }
504
- function checkActivities({
505
- def,
506
- i,
507
- activityNames,
508
- issues
509
- }) {
510
- const stage = def.stages[i];
511
- for (const [j, activity] of (stage.activities ?? []).entries()) {
512
- const path = ["stages", i, "activities", j];
513
- checkDuplicates({
514
- names: (activity.actions ?? []).map((action, a) => ({
515
- name: action.name,
516
- path: [...path, "actions", a, "name"]
517
- })),
518
- what: `action name in activity "${activity.name}"`,
519
- issues
520
- }), checkStatusSetTargets({ activity, activityNames, path, issues });
521
- }
522
- }
523
- function checkStatusSetTargets({
524
- activity,
525
- activityNames,
526
- path,
527
- issues
528
- }) {
529
- checkStatusSetOps({ ops: activity.ops, activityNames, path: [...path, "ops"], issues });
530
- for (const [a, action] of (activity.actions ?? []).entries())
531
- checkStatusSetOps({
532
- ops: action.ops,
533
- activityNames,
534
- path: [...path, "actions", a, "ops"],
535
- issues
272
+
273
+ function desugarActivity({activity: activity, path: path, stageEnv: stageEnv, ctx: ctx}) {
274
+ const activityFields = desugarFieldEntries({
275
+ entries: activity.fields,
276
+ path: [ ...path, "fields" ],
277
+ ctx: ctx
278
+ }), env = {
279
+ layers: [ {
280
+ scope: "activity",
281
+ entries: layerOf(activityFields)
282
+ }, ...stageEnv.layers ]
283
+ }, ops = desugarOps({
284
+ ops: activity.ops,
285
+ path: [ ...path, "ops" ],
286
+ env: env,
287
+ firingActivity: activity.name,
288
+ ctx: ctx
289
+ }), actions = (activity.actions ?? []).map((action, a) => desugarAction({
290
+ action: action,
291
+ path: [ ...path, "actions", a ],
292
+ env: env,
293
+ activityName: activity.name,
294
+ ctx: ctx
295
+ })), target = desugarTarget({
296
+ target: activity.target,
297
+ env: env,
298
+ path: [ ...path, "target" ],
299
+ ctx: ctx
536
300
  });
301
+ return {
302
+ ...stripUndefined({
303
+ name: activity.name,
304
+ title: activity.title,
305
+ description: activity.description,
306
+ groups: activity.groups,
307
+ group: normalizeGroup(activity.group),
308
+ kind: activity.kind,
309
+ filter: activity.filter,
310
+ requirements: activity.requirements,
311
+ completeWhen: activity.completeWhen,
312
+ failWhen: activity.failWhen,
313
+ effects: activity.effects,
314
+ subworkflows: activity.subworkflows
315
+ }),
316
+ activation: activity.activation ?? "manual",
317
+ ...target ? {
318
+ target: target
319
+ } : {},
320
+ ...activityFields ? {
321
+ fields: activityFields
322
+ } : {},
323
+ ...ops ? {
324
+ ops: ops
325
+ } : {},
326
+ ...actions.length > 0 ? {
327
+ actions: actions
328
+ } : {}
329
+ };
330
+ }
331
+
332
+ const TARGET_DOC_KINDS = [ "doc.ref", "doc.refs", "release.ref" ];
333
+
334
+ function desugarTarget({target: target, env: env, path: path, ctx: ctx}) {
335
+ if (target === void 0 || target.type === "url") return target;
336
+ const ref = typeof target.field == "string" ? {
337
+ field: target.field
338
+ } : target.field, field = resolveRef({
339
+ ref: ref,
340
+ env: env,
341
+ path: [ ...path, "field" ],
342
+ ctx: ctx
343
+ }) ?? fallbackRef(ref), entry = entryAt(env, field);
344
+ return entry && !TARGET_DOC_KINDS.includes(entry.type) && ctx.issues.push({
345
+ path: [ ...path, "field" ],
346
+ message: `manual activity target references "${field.field}" of kind "${entry.type}" — a deep-link target needs a document-valued entry (${TARGET_DOC_KINDS.join(", ")})`
347
+ }), {
348
+ type: "field",
349
+ field: field
350
+ };
537
351
  }
538
- function checkStatusSetOps({
539
- ops,
540
- activityNames,
541
- path,
542
- issues
543
- }) {
544
- for (const [o, op] of (ops ?? []).entries())
545
- op.type !== "status.set" || activityNames.has(op.activity) || issues.push({
546
- path: [...path, o, "activity"],
547
- message: `status.set targets activity "${op.activity}" which is not declared in this stage. Known activities: ${knownList(activityNames)}`
352
+
353
+ function desugarAction({action: action, path: path, env: env, activityName: activityName, ctx: ctx}) {
354
+ if ("type" in action) return desugarClaimAction({
355
+ action: action,
356
+ path: path,
357
+ env: env,
358
+ ctx: ctx
548
359
  });
360
+ const filter = andConditions([ rolesCondition(action.roles, ctx.roleAliases), action.filter ]), ops = desugarOps({
361
+ ops: action.ops,
362
+ path: [ ...path, "ops" ],
363
+ env: env,
364
+ firingActivity: activityName,
365
+ ctx: ctx
366
+ }) ?? [];
367
+ return action.status !== void 0 && ops.push({
368
+ type: "status.set",
369
+ activity: activityName,
370
+ status: action.status
371
+ }), {
372
+ ...stripUndefined({
373
+ name: action.name,
374
+ title: action.title,
375
+ description: action.description,
376
+ group: normalizeGroup(action.group),
377
+ params: action.params,
378
+ effects: action.effects
379
+ }),
380
+ ...filter ? {
381
+ filter: filter
382
+ } : {},
383
+ ...ops.length > 0 ? {
384
+ ops: ops
385
+ } : {}
386
+ };
549
387
  }
550
- function checkInitialStage({
551
- def,
552
- stageNames,
553
- issues
554
- }) {
555
- stageNames.has(def.initialStage) || issues.push({
556
- path: ["initialStage"],
557
- message: `initialStage "${def.initialStage}" is not a declared stage. Known stages: ${knownList(stageNames)}`
558
- });
559
- }
560
- function checkTransitionTargets({
561
- def,
562
- stageNames,
563
- issues
564
- }) {
565
- for (const [i, stage] of def.stages.entries())
566
- for (const [k, t] of (stage.transitions ?? []).entries())
567
- stageNames.has(t.to) || issues.push({
568
- path: ["stages", i, "transitions", k, "to"],
569
- message: `transition target "${t.to}" is not a declared stage. Known stages: ${knownList(stageNames)}`
570
- });
571
- }
572
- function checkEffectNames(def, issues) {
573
- const sites = [];
574
- for (const [i, stage] of def.stages.entries()) {
575
- for (const [j, activity] of (stage.activities ?? []).entries()) {
576
- collectEffects({
577
- effects: activity.effects,
578
- path: ["stages", i, "activities", j, "effects"],
579
- sites
580
- });
581
- for (const [a, action] of (activity.actions ?? []).entries())
582
- collectEffects({
583
- effects: action.effects,
584
- path: ["stages", i, "activities", j, "actions", a, "effects"],
585
- sites
586
- });
587
- }
588
- for (const [k, t] of (stage.transitions ?? []).entries())
589
- collectEffects({ effects: t.effects, path: ["stages", i, "transitions", k, "effects"], sites });
590
- }
591
- checkDuplicates({
592
- names: sites,
593
- what: "effect name (registry key \u2014 unique per definition)",
594
- issues
595
- });
596
- }
597
- function collectEffects({
598
- effects,
599
- path,
600
- sites
601
- }) {
602
- for (const [e, effect] of (effects ?? []).entries())
603
- sites.push({ name: effect.name, path: [...path, e, "name"] });
604
- }
605
- function checkGuardNames(def, issues) {
606
- const sites = def.stages.flatMap(
607
- (stage, i) => (stage.guards ?? []).map((guard, g) => ({
608
- name: guard.name,
609
- path: ["stages", i, "guards", g, "name"]
610
- }))
611
- );
612
- checkDuplicates({
613
- names: sites,
614
- what: "guard name (the guard lake _id derives from it \u2014 unique per definition)",
615
- issues
616
- });
617
- }
618
- function fieldScopes(def) {
619
- const scopes = [
620
- { entries: def.fields, scope: "workflow", path: ["fields"], label: "workflow fields" }
621
- ];
622
- for (const [i, stage] of def.stages.entries()) {
623
- scopes.push({
624
- entries: stage.fields,
625
- scope: "stage",
626
- path: ["stages", i, "fields"],
627
- label: `stage "${stage.name}" fields`
388
+
389
+ function desugarClaimAction({action: action, path: path, env: env, ctx: ctx}) {
390
+ const ref = typeof action.field == "string" ? {
391
+ field: action.field
392
+ } : action.field, resolved = resolveRef({
393
+ ref: ref,
394
+ env: env,
395
+ path: [ ...path, "field" ],
396
+ ctx: ctx
628
397
  });
629
- for (const [j, activity] of (stage.activities ?? []).entries())
630
- scopes.push({
631
- entries: activity.fields,
632
- scope: "activity",
633
- path: ["stages", i, "activities", j, "fields"],
634
- label: `activity "${activity.name}" fields`
635
- });
636
- }
637
- return scopes;
638
- }
639
- function checkRequiredField(def, issues) {
640
- for (const { entries, scope, path, label } of fieldScopes(def))
641
- for (const [n, entry] of (entries ?? []).entries())
642
- if (entry.required === !0) {
643
- if (scope !== "workflow")
644
- issues.push({
645
- path: [...path, n, "required"],
646
- message: `${label} entry "${entry.name}" is \`required\`, but \`required\` applies only to workflow-scope \`input\` entries \u2014 only those are caller-supplied at start/spawn`
647
- });
648
- else if (entry.initialValue?.type !== "input") {
649
- const seed = entry.initialValue?.type ?? "working memory (no initialValue)";
650
- issues.push({
651
- path: [...path, n, "required"],
652
- message: `field entry "${entry.name}" has initialValue "${seed}" \u2014 \`required\` applies only to \`input\`-sourced entries (the caller fills them at start/spawn)`
653
- });
398
+ if (resolved) {
399
+ const entry = entryAt(env, resolved);
400
+ entry && entry.type !== "actor" && ctx.issues.push({
401
+ path: [ ...path, "field" ],
402
+ message: `claim action "${action.name}" references "${resolved.field}" of kind "${entry.type}" — a claim pair needs an actor-valued entry (a "claim" or "actor" field declaration)`
403
+ }), checkShadowedClaimTarget({
404
+ actionName: action.name,
405
+ field: ref.field,
406
+ resolved: resolved,
407
+ env: env,
408
+ path: [ ...path, "field" ],
409
+ ctx: ctx
410
+ }), entry && ctx.claimedFields.add(entry);
411
+ }
412
+ const noSteal = `!defined($fields.${ref.field})`, filter = andConditions([ noSteal, rolesCondition(action.roles, ctx.roleAliases), action.filter ]), ops = resolved ? [ {
413
+ type: "field.set",
414
+ target: resolved,
415
+ value: {
416
+ type: "actor"
654
417
  }
655
- }
656
- }
657
- function checkFieldEntryNames(def, issues) {
658
- for (const { entries, path, label } of fieldScopes(def))
659
- checkDuplicates({
660
- names: (entries ?? []).map((entry, n) => ({ name: entry.name, path: [...path, n, "name"] })),
661
- what: `field entry name in ${label}`,
662
- issues
663
- });
418
+ } ] : [];
419
+ return {
420
+ ...stripUndefined({
421
+ name: action.name,
422
+ title: action.title,
423
+ description: action.description,
424
+ group: normalizeGroup(action.group),
425
+ params: action.params,
426
+ effects: action.effects
427
+ }),
428
+ filter: filter,
429
+ ...ops.length > 0 ? {
430
+ ops: ops
431
+ } : {}
432
+ };
664
433
  }
665
- function checkPredicates(def, issues) {
666
- const reserved = new Set(RESERVED_CONDITION_VARS), names = Object.keys(def.predicates ?? {});
667
- for (const name of names)
668
- reserved.has(name) && issues.push({
669
- path: ["predicates", name],
670
- message: `predicate "${name}" shadows the built-in $${name} \u2014 pick another name`
671
- });
672
- for (const [name, groq2] of Object.entries(def.predicates ?? {}))
673
- checkPredicateBody({ name, groq: groq2, names, issues });
674
- }
675
- function checkPredicateBody({
676
- name,
677
- groq: groq2,
678
- names,
679
- issues
680
- }) {
681
- for (const caller of PREDICATE_CALLER_VARS)
682
- referencesVar(groq2, caller) && issues.push({
683
- path: ["predicates", name],
684
- message: `predicate "${name}" reads $${caller} \u2014 predicates are instance-level (pre-evaluated once, without a caller); compose caller gates at the condition site instead`
434
+
435
+ function checkShadowedClaimTarget({actionName: actionName, field: field, resolved: resolved, env: env, path: path, ctx: ctx}) {
436
+ const nearest = env.layers.find(l => l.entries.has(field));
437
+ nearest === void 0 || nearest.scope === resolved.scope || ctx.issues.push({
438
+ path: path,
439
+ message: `claim action "${actionName}" targets "${field}" at scope "${resolved.scope}", but a nearer ${nearest.scope}-scope entry of the same name shadows it in $fields — the no-steal filter would read the shadowing entry while the claim writes the "${resolved.scope}" one. Rename one of the entries or claim the nearer one`
685
440
  });
686
- for (const other of names)
687
- other === name || !referencesVar(groq2, other) || issues.push({
688
- path: ["predicates", name],
689
- message: `predicate "${name}" references predicate $${other} \u2014 predicates may read built-in vars only (no cross-references; compose at the condition site instead)`
690
- });
691
- }
692
- function referencesVar(groq2, name) {
693
- return GROQ_IDENTIFIER.test(name) ? new RegExp(`\\$${name}\\b`).test(groq2) : !1;
694
441
  }
695
- function checkCanOutsideActionFilters(def, issues) {
696
- for (const site of nonActionFilterConditionSites(def))
697
- referencesVar(site.groq, "can") && issues.push({
698
- path: site.path,
699
- message: `${site.label} reads $can \u2014 $can (the caller's grants) is bound only when an action fires, so it may appear in action filters only`
442
+
443
+ function checkUnclaimedClaimFields(ctx) {
444
+ for (const [entry, {name: name, path: path}] of ctx.claimFields) ctx.claimedFields.has(entry) || ctx.issues.push({
445
+ path: path,
446
+ message: `claim field "${name}" is never referenced by a claim action — you announced the pattern and wrote half of it. Declare a defineAction({ type: "claim", field: "${name}" }) or use a raw actor entry`
700
447
  });
701
448
  }
702
- function nonActionFilterConditionSites(def) {
703
- const sites = [];
704
- for (const [i, stage] of def.stages.entries()) {
705
- for (const [k, t] of (stage.transitions ?? []).entries())
706
- sites.push({
707
- groq: t.filter,
708
- path: ["stages", i, "transitions", k, "filter"],
709
- label: `transition "${t.name}" filter`
710
- }), collectBindingSites({
711
- effects: t.effects,
712
- path: ["stages", i, "transitions", k, "effects"],
713
- label: `transition "${t.name}"`,
714
- sites
715
- }), collectOpWhereSites({
716
- ops: t.ops,
717
- path: ["stages", i, "transitions", k, "ops"],
718
- label: `transition "${t.name}"`,
719
- sites
720
- });
721
- for (const [j, activity] of (stage.activities ?? []).entries())
722
- collectActivityConditionSites({ activity, path: ["stages", i, "activities", j], sites });
723
- }
724
- return sites;
725
- }
726
- function collectOpWhereSites({
727
- ops,
728
- path,
729
- label,
730
- sites
731
- }) {
732
- for (const [o, op] of (ops ?? []).entries())
733
- op.where !== void 0 && sites.push({
734
- groq: op.where,
735
- path: [...path, o, "where"],
736
- label: `${label} ${op.type} where`
449
+
450
+ function desugarTransition({transition: transition, path: path, stageEnv: stageEnv, ctx: ctx}) {
451
+ const ops = desugarOps({
452
+ ops: transition.ops,
453
+ path: [ ...path, "ops" ],
454
+ env: stageEnv,
455
+ firingActivity: void 0,
456
+ ctx: ctx
737
457
  });
458
+ return {
459
+ ...stripUndefined({
460
+ name: transition.name,
461
+ title: transition.title,
462
+ description: transition.description,
463
+ to: transition.to,
464
+ effects: transition.effects
465
+ }),
466
+ filter: transition.filter ?? "$allActivitiesDone",
467
+ ...ops ? {
468
+ ops: ops
469
+ } : {}
470
+ };
738
471
  }
739
- function collectActivityConditionSites({
740
- activity,
741
- path,
742
- sites
743
- }) {
744
- for (const field of ["filter", "completeWhen", "failWhen"]) {
745
- const groq2 = activity[field];
746
- groq2 !== void 0 && sites.push({ groq: groq2, path: [...path, field], label: `activity "${activity.name}".${field}` });
747
- }
748
- collectBindingSites({
749
- effects: activity.effects,
750
- path: [...path, "effects"],
751
- label: `activity "${activity.name}"`,
752
- sites
753
- }), collectOpWhereSites({
754
- ops: activity.ops,
755
- path: [...path, "ops"],
756
- label: `activity "${activity.name}"`,
757
- sites
758
- });
759
- for (const [a, action] of (activity.actions ?? []).entries())
760
- collectBindingSites({
761
- effects: action.effects,
762
- path: [...path, "actions", a, "effects"],
763
- label: `action "${action.name}"`,
764
- sites
765
- }), collectOpWhereSites({
766
- ops: action.ops,
767
- path: [...path, "actions", a, "ops"],
768
- label: `action "${action.name}"`,
769
- sites
770
- });
771
- collectSubworkflowSites({ activity, path, sites });
772
- }
773
- function collectSubworkflowSites({
774
- activity,
775
- path,
776
- sites
777
- }) {
778
- const sub = activity.subworkflows;
779
- if (sub === void 0) return;
780
- const subPath = [...path, "subworkflows"];
781
- sites.push({
782
- groq: sub.forEach,
783
- path: [...subPath, "forEach"],
784
- label: `activity "${activity.name}".subworkflows.forEach`
785
- });
786
- for (const [group, record] of [
787
- ["with", sub.with],
788
- ["context", sub.context]
789
- ])
790
- for (const [key, groq2] of Object.entries(record ?? {}))
791
- sites.push({
792
- groq: groq2,
793
- path: [...subPath, group, key],
794
- label: `activity "${activity.name}".subworkflows.${group} "${key}"`
795
- });
796
- }
797
- function collectBindingSites({
798
- effects,
799
- path,
800
- label,
801
- sites
802
- }) {
803
- for (const [e, effect] of (effects ?? []).entries())
804
- for (const [key, groq2] of Object.entries(effect.bindings ?? {}))
805
- sites.push({
806
- groq: groq2,
807
- path: [...path, e, "bindings", key],
808
- label: `${label} effect "${effect.name}" binding "${key}"`
809
- });
810
- }
811
- function checkAssigneesEntries(def, issues) {
812
- for (const { entries, path } of fieldScopes(def))
813
- (entries ?? []).filter((e) => e.type === "assignees").length <= 1 || issues.push({
814
- path,
815
- message: "at most one assignees-kind field entry per scope \u2014 the inbox reads it by kind"
472
+
473
+ function desugarGuard(guard) {
474
+ const {match: match, metadata: metadata, ...rest} = guard, {idRefs: idRefs, ...matchRest} = match;
475
+ return {
476
+ ...rest,
477
+ match: {
478
+ ...matchRest,
479
+ ...idRefs !== void 0 ? {
480
+ idRefs: idRefs.map(printGuardRead)
481
+ } : {}
482
+ },
483
+ ...metadata !== void 0 ? {
484
+ metadata: Object.fromEntries(Object.entries(metadata).map(([key, read]) => [ key, printGuardRead(read) ]))
485
+ } : {}
486
+ };
487
+ }
488
+
489
+ function desugarOps({ops: ops, path: path, env: env, firingActivity: firingActivity, ctx: ctx}) {
490
+ if (ops) return ops.map((op, i) => desugarOp({
491
+ op: op,
492
+ path: [ ...path, i ],
493
+ env: env,
494
+ firingActivity: firingActivity,
495
+ ctx: ctx
496
+ }));
497
+ }
498
+
499
+ function desugarOp({op: op, path: path, env: env, firingActivity: firingActivity, ctx: ctx}) {
500
+ if (op.type === "status.set") {
501
+ const activity = op.activity ?? firingActivity;
502
+ return activity === void 0 && ctx.issues.push({
503
+ path: [ ...path, "activity" ],
504
+ message: "status.set outside an action must name its target activity"
505
+ }), {
506
+ type: "status.set",
507
+ activity: activity ?? "",
508
+ status: op.status
509
+ };
510
+ }
511
+ if (op.type === "audit") return desugarAuditOp({
512
+ op: op,
513
+ path: path,
514
+ env: env,
515
+ ctx: ctx
816
516
  });
517
+ const target = resolveRef({
518
+ ref: op.target,
519
+ env: env,
520
+ path: [ ...path, "target" ],
521
+ ctx: ctx
522
+ }) ?? fallbackRef(op.target);
523
+ return {
524
+ ...op,
525
+ target: target
526
+ };
817
527
  }
818
- function activityShape(activity) {
819
- return {
820
- hasActions: (activity.actions ?? []).length > 0,
821
- hasEffects: (activity.effects ?? []).length > 0,
822
- hasCompleteWhen: activity.completeWhen !== void 0,
823
- hasSubworkflows: activity.subworkflows !== void 0
824
- };
825
- }
826
- const KIND_SHAPE_RULES = {
827
- user: (s) => s.hasActions ? [] : ["needs at least one action for a person to fire"],
828
- service: (s) => s.hasEffects ? [] : ["needs at least one effect \u2014 the automated work it performs"],
829
- manual: (s) => [
830
- s.hasActions || s.hasCompleteWhen ? void 0 : "needs a way to complete \u2014 an action to acknowledge it, or a `completeWhen` predicate to verify it (otherwise it auto-resolves on activation)",
831
- s.hasSubworkflows ? "is off-system work, not a fan-out \u2014 drop `subworkflows` or move it to its own activity" : void 0
832
- ].filter((m) => m !== void 0),
833
- receive: (s) => [
834
- s.hasCompleteWhen || s.hasSubworkflows ? void 0 : "needs a `completeWhen` (or `subworkflows`) condition to wait on",
835
- s.hasActions ? "has no actor, so it cannot carry actions" : void 0
836
- ].filter((m) => m !== void 0),
837
- script: (s) => [
838
- s.hasActions ? "runs inline with no actor, so it cannot carry actions" : void 0,
839
- s.hasCompleteWhen ? "resolves on activation, so it cannot carry a `completeWhen` (that is a `receive`/`service` wait)" : void 0,
840
- s.hasSubworkflows ? "resolves on activation, so it cannot fan out with `subworkflows`" : void 0
841
- ].filter((m) => m !== void 0)
528
+
529
+ const AUDIT_STAMPS = {
530
+ actor: {
531
+ type: "actor"
532
+ },
533
+ at: {
534
+ type: "now"
535
+ }
842
536
  };
843
- function checkActivityKinds(def, issues) {
844
- for (const [i, stage] of def.stages.entries())
845
- for (const [j, activity] of (stage.activities ?? []).entries()) {
846
- const path = ["stages", i, "activities", j];
847
- if (activity.target !== void 0 && activity.kind !== "manual" && issues.push({
848
- path: [...path, "target"],
849
- message: `activity "${activity.name}" has a \`target\` but is not \`kind: "manual"\` \u2014 a target is the deep-link for off-system manual work`
850
- }), activity.kind !== void 0)
851
- for (const fault of KIND_SHAPE_RULES[activity.kind](activityShape(activity)))
852
- issues.push({
853
- path: [...path, "kind"],
854
- message: `activity "${activity.name}" declares kind "${activity.kind}" but ${fault}`
855
- });
537
+
538
+ function desugarAuditOp({op: op, path: path, env: env, ctx: ctx}) {
539
+ const target = resolveRef({
540
+ ref: op.target,
541
+ env: env,
542
+ path: [ ...path, "target" ],
543
+ ctx: ctx
544
+ }) ?? fallbackRef(op.target);
545
+ if (op.value.type !== "object") return ctx.issues.push({
546
+ path: [ ...path, "value" ],
547
+ message: `audit value must be an object source carrying the domain fields (got "${op.value.type}")`
548
+ }), {
549
+ type: "field.append",
550
+ target: target,
551
+ value: op.value
552
+ };
553
+ const actorField = op.stampFields?.actor ?? "actor", atField = op.stampFields?.at ?? "at", fields = {
554
+ ...op.value.fields
555
+ };
556
+ for (const [stamp, source] of [ [ actorField, AUDIT_STAMPS.actor ], [ atField, AUDIT_STAMPS.at ] ]) {
557
+ if (stamp in fields) {
558
+ ctx.issues.push({
559
+ path: [ ...path, "value", "fields", stamp ],
560
+ message: `audit stamp field "${stamp}" collides with an authored domain field — rename yours or remap the stamp via stampFields`
561
+ });
562
+ continue;
563
+ }
564
+ fields[stamp] = source;
856
565
  }
566
+ return {
567
+ type: "field.append",
568
+ target: target,
569
+ value: {
570
+ type: "object",
571
+ fields: fields
572
+ }
573
+ };
857
574
  }
858
- function checkWorkflowInvariants(def) {
859
- const issues = [], stageNames = checkStages(def, issues);
860
- return checkInitialStage({ def, stageNames, issues }), checkTransitionTargets({ def, stageNames, issues }), checkEffectNames(def, issues), checkGuardNames(def, issues), checkFieldEntryNames(def, issues), checkRequiredField(def, issues), checkPredicates(def, issues), checkCanOutsideActionFilters(def, issues), checkAssigneesEntries(def, issues), checkActivityKinds(def, issues), issues;
575
+
576
+ function resolveRef({ref: ref, env: env, path: path, ctx: ctx}) {
577
+ const layers = ref.scope === void 0 ? env.layers : env.layers.filter(l => l.scope === ref.scope);
578
+ for (const layer of layers) if (layer.entries.has(ref.field)) return {
579
+ scope: layer.scope,
580
+ field: ref.field
581
+ };
582
+ const reachable = env.layers.flatMap(l => [ ...l.entries.keys() ].map(n => `${l.scope}:${n}`));
583
+ ctx.issues.push({
584
+ path: path,
585
+ message: `field reference "${ref.field}"${ref.scope ? ` (scope "${ref.scope}")` : ""} does not resolve to a declared entry. Reachable: ${reachable.join(", ") || "(none)"}`
586
+ });
861
587
  }
862
- function defineWorkflow(definition) {
863
- const label = labelFor("defineWorkflow", definition), parsed = parseOrThrow({ schema: AuthoringWorkflowSchema, input: definition, label }), { definition: stored, issues: desugarIssues } = desugarWorkflow(parsed), issues = [...desugarIssues, ...checkWorkflowInvariants(stored)];
864
- if (issues.length > 0) throw new Error(formatValidationError(label, issues));
865
- return stored;
588
+
589
+ function entryAt(env, ref) {
590
+ return env.layers.find(l => l.scope === ref.scope)?.entries.get(ref.field);
866
591
  }
592
+
593
+ function fallbackRef(ref) {
594
+ return {
595
+ scope: ref.scope ?? "workflow",
596
+ field: ref.field
597
+ };
598
+ }
599
+
600
+ function rolesCondition(roles, aliases) {
601
+ if (!(!roles || roles.length === 0)) return groq`count($actor.roles[@ in ${expandRequiredRoles(roles, aliases)}]) > 0`;
602
+ }
603
+
604
+ function stripUndefined(obj) {
605
+ const out = {};
606
+ for (const [k, value] of Object.entries(obj)) value !== void 0 && (out[k] = value);
607
+ return out;
608
+ }
609
+
610
+ function defineWorkflow(definition) {
611
+ const label = labelFor("defineWorkflow", definition), parsed = parseOrThrow({
612
+ schema: AuthoringWorkflowSchema,
613
+ input: definition,
614
+ label: label
615
+ }), {definition: stored, issues: desugarIssues} = desugarWorkflow(parsed), issues = [ ...desugarIssues, ...checkWorkflowInvariants(stored) ];
616
+ if (issues.length > 0) throw new Error(formatValidationError(label, issues));
617
+ return stored;
618
+ }
619
+
867
620
  function defineWorkflowConfig(config) {
868
- return parseOrThrow({ schema: WorkflowConfigSchema, input: config, label: "defineWorkflowConfig" });
621
+ return parseOrThrow({
622
+ schema: WorkflowConfigSchema,
623
+ input: config,
624
+ label: "defineWorkflowConfig"
625
+ });
869
626
  }
627
+
870
628
  function defineStage(stage) {
871
- return parseOrThrow({
872
- schema: AuthoringStageSchema,
873
- input: stage,
874
- label: labelFor("defineStage", stage)
875
- });
629
+ return parseOrThrow({
630
+ schema: AuthoringStageSchema,
631
+ input: stage,
632
+ label: labelFor("defineStage", stage)
633
+ });
876
634
  }
635
+
877
636
  function defineActivity(activity) {
878
- return parseOrThrow({
879
- schema: AuthoringActivitySchema,
880
- input: activity,
881
- label: labelFor("defineActivity", activity)
882
- });
637
+ return parseOrThrow({
638
+ schema: AuthoringActivitySchema,
639
+ input: activity,
640
+ label: labelFor("defineActivity", activity)
641
+ });
883
642
  }
643
+
884
644
  function defineAction(action) {
885
- return parseOrThrow({
886
- schema: AuthoringActionSchema,
887
- input: action,
888
- label: labelFor("defineAction", action)
889
- });
645
+ return parseOrThrow({
646
+ schema: AuthoringActionSchema,
647
+ input: action,
648
+ label: labelFor("defineAction", action)
649
+ });
890
650
  }
651
+
891
652
  function defineTransition(transition) {
892
- return parseOrThrow({
893
- schema: AuthoringTransitionSchema,
894
- input: transition,
895
- label: transitionLabel(transition)
896
- });
653
+ return parseOrThrow({
654
+ schema: AuthoringTransitionSchema,
655
+ input: transition,
656
+ label: transitionLabel(transition)
657
+ });
897
658
  }
659
+
898
660
  function defineField(entry) {
899
- return parseOrThrow({
900
- schema: AuthoringFieldEntrySchema,
901
- input: entry,
902
- label: labelFor("defineField", entry)
903
- });
661
+ return parseOrThrow({
662
+ schema: AuthoringFieldEntrySchema,
663
+ input: entry,
664
+ label: labelFor("defineField", entry)
665
+ });
904
666
  }
667
+
905
668
  function defineOp(op) {
906
- return parseOrThrow({ schema: AuthoringOpSchema, input: op, label: "defineOp" });
669
+ return parseOrThrow({
670
+ schema: AuthoringOpSchema,
671
+ input: op,
672
+ label: "defineOp"
673
+ });
907
674
  }
675
+
676
+ function defineGroup(group) {
677
+ return parseOrThrow({
678
+ schema: GroupSchema,
679
+ input: group,
680
+ label: labelFor("defineGroup", group)
681
+ });
682
+ }
683
+
908
684
  function defineGuard(guard) {
909
- return parseOrThrow({
910
- schema: AuthoringGuardSchema,
911
- input: guard,
912
- label: labelFor("defineGuard", guard)
913
- });
685
+ return parseOrThrow({
686
+ schema: AuthoringGuardSchema,
687
+ input: guard,
688
+ label: labelFor("defineGuard", guard)
689
+ });
914
690
  }
691
+
915
692
  function defineEffect(effect) {
916
- return parseOrThrow({
917
- schema: EffectSchema,
918
- input: effect,
919
- label: labelFor("defineEffect", effect)
920
- });
693
+ return parseOrThrow({
694
+ schema: EffectSchema,
695
+ input: effect,
696
+ label: labelFor("defineEffect", effect)
697
+ });
921
698
  }
699
+
922
700
  function transitionLabel(transition) {
923
- const { name, to } = transition;
924
- return typeof name == "string" ? `defineTransition("${name}")` : typeof to == "string" ? `defineTransition(\u2192 "${to}")` : "defineTransition";
701
+ const {name: name, to: to} = transition;
702
+ return typeof name == "string" ? `defineTransition("${name}")` : typeof to == "string" ? `defineTransition( "${to}")` : "defineTransition";
925
703
  }
704
+
926
705
  function defineEffectDescriptor(descriptor) {
927
- if (!descriptor.name) throw new Error("EffectDescriptor missing name");
928
- return descriptor;
929
- }
930
- function parseOrThrow({
931
- schema,
932
- input,
933
- label
934
- }) {
935
- const result = v.safeParse(schema, input);
936
- if (!result.success)
937
- throw new Error(formatValidationError(label, issuesFromValibot(result.issues)));
938
- return result.output;
939
- }
940
- function labelFor(fn, value) {
941
- if (value && typeof value == "object" && "name" in value) {
942
- const raw = value.name;
943
- if (typeof raw == "string") return `${fn}("${raw}")`;
944
- }
945
- return fn;
946
- }
947
- export {
948
- CONDITION_VARS,
949
- FILTER_SCOPE_VARS,
950
- GUARD_PREDICATE_VARS,
951
- RESERVED_CONDITION_VARS,
952
- defineAction,
953
- defineActivity,
954
- defineEffect,
955
- defineEffectDescriptor,
956
- defineField,
957
- defineGuard,
958
- defineOp,
959
- defineStage,
960
- defineTransition,
961
- defineWorkflow,
962
- defineWorkflowConfig,
963
- groq
964
- };
965
- //# sourceMappingURL=define.js.map
706
+ if (!descriptor.name) throw new Error("EffectDescriptor missing name");
707
+ return descriptor;
708
+ }
709
+
710
+ export { CONDITION_VARS, FILTER_SCOPE_VARS, GUARD_PREDICATE_VARS, RESERVED_CONDITION_VARS, defineAction, defineActivity, defineEffect, defineEffectDescriptor, defineField, defineGroup, defineGuard, defineOp, defineStage, defineTransition, defineWorkflow, defineWorkflowConfig, groq };