yaml-flow 2.1.0 → 2.2.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.
@@ -852,6 +852,408 @@ function applyTaskCreation(state, taskName, taskConfig) {
852
852
  };
853
853
  }
854
854
 
855
+ // src/event-graph/plan.ts
856
+ function buildProducerMap(tasks) {
857
+ const map = {};
858
+ for (const [name, config] of Object.entries(tasks)) {
859
+ for (const token of getProvides(config)) {
860
+ if (!map[token]) map[token] = [];
861
+ map[token].push(name);
862
+ }
863
+ if (config.on) {
864
+ for (const tokens of Object.values(config.on)) {
865
+ for (const token of tokens) {
866
+ if (!map[token]) map[token] = [];
867
+ if (!map[token].includes(name)) map[token].push(name);
868
+ }
869
+ }
870
+ }
871
+ if (config.on_failure) {
872
+ for (const token of config.on_failure) {
873
+ if (!map[token]) map[token] = [];
874
+ if (!map[token].includes(name)) map[token].push(name);
875
+ }
876
+ }
877
+ }
878
+ return map;
879
+ }
880
+ function buildDependencies(tasks, producerMap) {
881
+ const deps = {};
882
+ for (const [name, config] of Object.entries(tasks)) {
883
+ const required = getRequires(config);
884
+ const taskDeps = /* @__PURE__ */ new Set();
885
+ for (const token of required) {
886
+ const producers = producerMap[token] || [];
887
+ for (const producer of producers) {
888
+ if (producer !== name) taskDeps.add(producer);
889
+ }
890
+ }
891
+ deps[name] = [...taskDeps];
892
+ }
893
+ return deps;
894
+ }
895
+ function computePhases(taskNames, dependencies) {
896
+ const taskSet = new Set(taskNames);
897
+ const inDegree = {};
898
+ const dependents = {};
899
+ for (const name of taskNames) {
900
+ inDegree[name] = 0;
901
+ dependents[name] = [];
902
+ }
903
+ for (const name of taskNames) {
904
+ for (const dep of dependencies[name] || []) {
905
+ if (taskSet.has(dep)) {
906
+ inDegree[name]++;
907
+ dependents[dep].push(name);
908
+ }
909
+ }
910
+ }
911
+ const phases = [];
912
+ const remaining = new Set(taskNames);
913
+ while (remaining.size > 0) {
914
+ const phase = [];
915
+ for (const name of remaining) {
916
+ if (inDegree[name] === 0) {
917
+ phase.push(name);
918
+ }
919
+ }
920
+ if (phase.length === 0) {
921
+ phases.push([...remaining]);
922
+ break;
923
+ }
924
+ phase.sort();
925
+ phases.push(phase);
926
+ for (const name of phase) {
927
+ remaining.delete(name);
928
+ for (const dependent of dependents[name] || []) {
929
+ if (remaining.has(dependent)) {
930
+ inDegree[dependent]--;
931
+ }
932
+ }
933
+ }
934
+ }
935
+ return phases;
936
+ }
937
+ function planExecution(graph) {
938
+ const tasks = getAllTasks(graph);
939
+ const taskNames = Object.keys(tasks);
940
+ if (taskNames.length === 0) {
941
+ return {
942
+ phases: [],
943
+ dependencies: {},
944
+ conflicts: {},
945
+ entryPoints: [],
946
+ leafTasks: [],
947
+ unreachableTokens: [],
948
+ blockedTasks: [],
949
+ depth: 0,
950
+ maxParallelism: 0
951
+ };
952
+ }
953
+ const producerMap = buildProducerMap(tasks);
954
+ const dependencies = buildDependencies(tasks, producerMap);
955
+ const conflicts = {};
956
+ for (const [token, producers] of Object.entries(producerMap)) {
957
+ if (producers.length > 1) {
958
+ conflicts[token] = producers;
959
+ }
960
+ }
961
+ const entryPoints = taskNames.filter((name) => getRequires(tasks[name]).length === 0);
962
+ const dependedOn = /* @__PURE__ */ new Set();
963
+ for (const deps of Object.values(dependencies)) {
964
+ for (const dep of deps) dependedOn.add(dep);
965
+ }
966
+ const leafTasks = taskNames.filter((name) => !dependedOn.has(name));
967
+ const allRequired = /* @__PURE__ */ new Set();
968
+ for (const config of Object.values(tasks)) {
969
+ for (const token of getRequires(config)) {
970
+ allRequired.add(token);
971
+ }
972
+ }
973
+ const unreachableTokens = [...allRequired].filter((token) => !producerMap[token]);
974
+ const unreachableSet = new Set(unreachableTokens);
975
+ const blockedTasks = taskNames.filter(
976
+ (name) => getRequires(tasks[name]).some((token) => unreachableSet.has(token))
977
+ );
978
+ const phases = computePhases(taskNames, dependencies);
979
+ return {
980
+ phases,
981
+ dependencies,
982
+ conflicts,
983
+ entryPoints,
984
+ leafTasks: leafTasks.sort(),
985
+ unreachableTokens: unreachableTokens.sort(),
986
+ blockedTasks: blockedTasks.sort(),
987
+ depth: phases.length,
988
+ maxParallelism: Math.max(0, ...phases.map((p) => p.length))
989
+ };
990
+ }
991
+
992
+ // src/event-graph/mermaid.ts
993
+ function sanitizeId(name) {
994
+ return name.replace(/[^a-zA-Z0-9_]/g, "_");
995
+ }
996
+ function graphToMermaid(graph, options = {}) {
997
+ const { direction = "TD", showTokens = true, title } = options;
998
+ const tasks = getAllTasks(graph);
999
+ const taskNames = Object.keys(tasks);
1000
+ if (taskNames.length === 0) {
1001
+ return `graph ${direction}
1002
+ empty[No tasks defined]`;
1003
+ }
1004
+ const producerMap = {};
1005
+ for (const [name, config] of Object.entries(tasks)) {
1006
+ for (const token of getProvides(config)) {
1007
+ if (!producerMap[token]) producerMap[token] = [];
1008
+ producerMap[token].push(name);
1009
+ }
1010
+ if (config.on) {
1011
+ for (const tokens of Object.values(config.on)) {
1012
+ for (const token of tokens) {
1013
+ if (!producerMap[token]) producerMap[token] = [];
1014
+ if (!producerMap[token].includes(name)) producerMap[token].push(name);
1015
+ }
1016
+ }
1017
+ }
1018
+ }
1019
+ const lines = [];
1020
+ const diagramTitle = title || graph.id || "Event Graph";
1021
+ lines.push(`%% ${diagramTitle}`);
1022
+ lines.push(`graph ${direction}`);
1023
+ const allRequired = /* @__PURE__ */ new Set();
1024
+ for (const config of Object.values(tasks)) {
1025
+ for (const token of getRequires(config)) {
1026
+ allRequired.add(token);
1027
+ }
1028
+ }
1029
+ const leafTaskSet = new Set(
1030
+ taskNames.filter((name) => {
1031
+ const prov = getProvides(tasks[name]);
1032
+ return prov.length === 0 || prov.every((token) => !allRequired.has(token));
1033
+ })
1034
+ );
1035
+ for (const name of taskNames) {
1036
+ const id = sanitizeId(name);
1037
+ const req = getRequires(tasks[name]);
1038
+ if (req.length === 0) {
1039
+ lines.push(` ${id}([${name}])`);
1040
+ } else if (leafTaskSet.has(name)) {
1041
+ lines.push(` ${id}[[${name}]]`);
1042
+ } else {
1043
+ lines.push(` ${id}[${name}]`);
1044
+ }
1045
+ }
1046
+ const edgeSet = /* @__PURE__ */ new Set();
1047
+ for (const [name, config] of Object.entries(tasks)) {
1048
+ const required = getRequires(config);
1049
+ for (const token of required) {
1050
+ const producers = producerMap[token] || [];
1051
+ for (const producer of producers) {
1052
+ if (producer === name) continue;
1053
+ const edgeKey = `${producer}->${name}:${token}`;
1054
+ if (edgeSet.has(edgeKey)) continue;
1055
+ edgeSet.add(edgeKey);
1056
+ const fromId = sanitizeId(producer);
1057
+ const toId = sanitizeId(name);
1058
+ if (showTokens) {
1059
+ lines.push(` ${fromId} -->|${token}| ${toId}`);
1060
+ } else {
1061
+ lines.push(` ${fromId} --> ${toId}`);
1062
+ }
1063
+ }
1064
+ }
1065
+ for (const token of required) {
1066
+ if (!producerMap[token]) {
1067
+ const warnId = `warn_${sanitizeId(token)}`;
1068
+ const toId = sanitizeId(name);
1069
+ lines.push(` ${warnId}{{\u26A0 ${token}}} -.->|missing| ${toId}`);
1070
+ }
1071
+ }
1072
+ }
1073
+ return lines.join("\n");
1074
+ }
1075
+ function flowToMermaid(flow, options = {}) {
1076
+ const { direction = "TD", title } = options;
1077
+ const steps = flow.steps;
1078
+ const terminals = flow.terminal_states;
1079
+ const startStep = flow.settings.start_step;
1080
+ const lines = [];
1081
+ const diagramTitle = title || flow.id || "Step Machine";
1082
+ lines.push(`%% ${diagramTitle}`);
1083
+ lines.push(`graph ${direction}`);
1084
+ lines.push(` START(( ))`);
1085
+ lines.push(` START --> ${sanitizeId(startStep)}`);
1086
+ for (const name of Object.keys(steps)) {
1087
+ const id = sanitizeId(name);
1088
+ lines.push(` ${id}[${name}]`);
1089
+ }
1090
+ for (const [name, config] of Object.entries(terminals)) {
1091
+ const id = sanitizeId(name);
1092
+ lines.push(` ${id}([${name}: ${config.return_intent}])`);
1093
+ }
1094
+ for (const [stepName, stepConfig] of Object.entries(steps)) {
1095
+ const fromId = sanitizeId(stepName);
1096
+ for (const [result, target] of Object.entries(stepConfig.transitions)) {
1097
+ const toId = sanitizeId(target);
1098
+ lines.push(` ${fromId} -->|${result}| ${toId}`);
1099
+ }
1100
+ }
1101
+ return lines.join("\n");
1102
+ }
1103
+
1104
+ // src/event-graph/loader.ts
1105
+ function validateGraphConfig(config) {
1106
+ const errors = [];
1107
+ if (!config || typeof config !== "object") {
1108
+ return ["Graph config must be an object"];
1109
+ }
1110
+ const c = config;
1111
+ if (!c.settings || typeof c.settings !== "object") {
1112
+ errors.push('Graph config must have a "settings" object');
1113
+ } else {
1114
+ const settings = c.settings;
1115
+ if (!settings.completion || typeof settings.completion !== "string") {
1116
+ errors.push("settings.completion must be a string");
1117
+ }
1118
+ if (settings.completion === "goal-reached") {
1119
+ if (!Array.isArray(settings.goal) || settings.goal.length === 0) {
1120
+ errors.push('settings.goal must be a non-empty array when completion is "goal-reached"');
1121
+ }
1122
+ }
1123
+ }
1124
+ if (!c.tasks || typeof c.tasks !== "object") {
1125
+ errors.push('Graph config must have a "tasks" object');
1126
+ } else {
1127
+ const tasks = c.tasks;
1128
+ if (Object.keys(tasks).length === 0) {
1129
+ errors.push("Graph config must have at least one task");
1130
+ }
1131
+ for (const [name, task] of Object.entries(tasks)) {
1132
+ if (!task || typeof task !== "object") {
1133
+ errors.push(`Task "${name}" must be an object`);
1134
+ continue;
1135
+ }
1136
+ const t = task;
1137
+ if (!Array.isArray(t.provides)) {
1138
+ errors.push(`Task "${name}" must have a "provides" array`);
1139
+ }
1140
+ if (t.requires !== void 0 && !Array.isArray(t.requires)) {
1141
+ errors.push(`Task "${name}".requires must be an array if present`);
1142
+ }
1143
+ if (t.on !== void 0) {
1144
+ if (typeof t.on !== "object" || Array.isArray(t.on)) {
1145
+ errors.push(`Task "${name}".on must be an object mapping result keys to token arrays`);
1146
+ } else {
1147
+ for (const [key, tokens] of Object.entries(t.on)) {
1148
+ if (!Array.isArray(tokens)) {
1149
+ errors.push(`Task "${name}".on.${key} must be an array of tokens`);
1150
+ }
1151
+ }
1152
+ }
1153
+ }
1154
+ }
1155
+ }
1156
+ return errors;
1157
+ }
1158
+ async function parseGraphYaml(yamlString) {
1159
+ const yaml = await import('yaml');
1160
+ return yaml.parse(yamlString);
1161
+ }
1162
+ async function loadGraphConfig(source) {
1163
+ let config;
1164
+ if (typeof source === "string") {
1165
+ if (source.startsWith("http://") || source.startsWith("https://")) {
1166
+ const response = await fetch(source);
1167
+ if (!response.ok) {
1168
+ throw new Error(`Failed to load graph config from ${source}: ${response.statusText}`);
1169
+ }
1170
+ const text = await response.text();
1171
+ const contentType = response.headers.get("content-type") ?? "";
1172
+ if (contentType.includes("json") || source.endsWith(".json")) {
1173
+ config = JSON.parse(text);
1174
+ } else {
1175
+ config = await parseGraphYaml(text);
1176
+ }
1177
+ } else if (source.includes("{")) {
1178
+ config = JSON.parse(source);
1179
+ } else {
1180
+ const fs = await import('fs/promises');
1181
+ const text = await fs.readFile(source, "utf-8");
1182
+ if (source.endsWith(".json")) {
1183
+ config = JSON.parse(text);
1184
+ } else {
1185
+ config = await parseGraphYaml(text);
1186
+ }
1187
+ }
1188
+ } else {
1189
+ config = source;
1190
+ }
1191
+ const errors = validateGraphConfig(config);
1192
+ if (errors.length > 0) {
1193
+ throw new Error(`Invalid graph configuration:
1194
+ - ${errors.join("\n- ")}`);
1195
+ }
1196
+ return config;
1197
+ }
1198
+ function exportGraphConfig(config, options = {}) {
1199
+ const { format = "json", indent = 2 } = options;
1200
+ if (format === "yaml") {
1201
+ return toYaml(config, indent);
1202
+ }
1203
+ return JSON.stringify(config, null, indent);
1204
+ }
1205
+ async function exportGraphConfigToFile(config, filePath, options = {}) {
1206
+ const format = options.format ?? (filePath.endsWith(".yaml") || filePath.endsWith(".yml") ? "yaml" : "json");
1207
+ const content = exportGraphConfig(config, { ...options, format });
1208
+ const fs = await import('fs/promises');
1209
+ await fs.writeFile(filePath, content, "utf-8");
1210
+ }
1211
+ function toYaml(obj, indent, depth = 0) {
1212
+ const pad = " ".repeat(indent * depth);
1213
+ if (obj === null || obj === void 0) return "null";
1214
+ if (typeof obj === "boolean") return String(obj);
1215
+ if (typeof obj === "number") return String(obj);
1216
+ if (typeof obj === "string") {
1217
+ if (obj.includes(":") || obj.includes("#") || obj.includes("\n") || obj.includes('"') || obj.includes("'") || obj.startsWith(" ") || obj.startsWith("{") || obj.startsWith("[") || obj === "") {
1218
+ return JSON.stringify(obj);
1219
+ }
1220
+ return obj;
1221
+ }
1222
+ if (Array.isArray(obj)) {
1223
+ if (obj.length === 0) return "[]";
1224
+ if (obj.every((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean")) {
1225
+ return `[${obj.map((v) => typeof v === "string" ? toYaml(v, indent, 0) : String(v)).join(", ")}]`;
1226
+ }
1227
+ return obj.map((item) => {
1228
+ const val = toYaml(item, indent, depth + 1);
1229
+ if (typeof item === "object" && item !== null && !Array.isArray(item)) {
1230
+ const lines = val.trimStart().split("\n");
1231
+ return `${pad}- ${lines[0]}
1232
+ ${lines.slice(1).map((l) => `${pad} ${l.trimStart() ? l : ""}`).filter(Boolean).join("\n")}`;
1233
+ }
1234
+ return `${pad}- ${val}`;
1235
+ }).join("\n");
1236
+ }
1237
+ if (typeof obj === "object") {
1238
+ const entries = Object.entries(obj);
1239
+ if (entries.length === 0) return "{}";
1240
+ return entries.map(([key, value]) => {
1241
+ if (value === void 0) return "";
1242
+ const serialized = toYaml(value, indent, depth + 1);
1243
+ if (typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length > 0) {
1244
+ return `${pad}${key}:
1245
+ ${serialized}`;
1246
+ }
1247
+ if (Array.isArray(value) && value.length > 0 && !value.every((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean")) {
1248
+ return `${pad}${key}:
1249
+ ${serialized}`;
1250
+ }
1251
+ return `${pad}${key}: ${serialized}`;
1252
+ }).filter(Boolean).join("\n");
1253
+ }
1254
+ return String(obj);
1255
+ }
1256
+
855
1257
  exports.COMPLETION_STRATEGIES = COMPLETION_STRATEGIES;
856
1258
  exports.CONFLICT_STRATEGIES = CONFLICT_STRATEGIES;
857
1259
  exports.DEFAULTS = DEFAULTS;
@@ -871,6 +1273,9 @@ exports.computeAvailableOutputs = computeAvailableOutputs;
871
1273
  exports.createDefaultTaskState = createDefaultTaskState;
872
1274
  exports.createInitialExecutionState = createInitialExecutionState;
873
1275
  exports.detectStuckState = detectStuckState;
1276
+ exports.exportGraphConfig = exportGraphConfig;
1277
+ exports.exportGraphConfigToFile = exportGraphConfigToFile;
1278
+ exports.flowToMermaid = flowToMermaid;
874
1279
  exports.getAllTasks = getAllTasks;
875
1280
  exports.getCandidateTasks = getCandidateTasks;
876
1281
  exports.getNonConflictingTasks = getNonConflictingTasks;
@@ -878,6 +1283,7 @@ exports.getProvides = getProvides;
878
1283
  exports.getRepeatableMax = getRepeatableMax;
879
1284
  exports.getRequires = getRequires;
880
1285
  exports.getTask = getTask;
1286
+ exports.graphToMermaid = graphToMermaid;
881
1287
  exports.groupTasksByProvides = groupTasksByProvides;
882
1288
  exports.hasOutputConflict = hasOutputConflict;
883
1289
  exports.hasTask = hasTask;
@@ -886,10 +1292,13 @@ exports.isNonActiveTask = isNonActiveTask;
886
1292
  exports.isRepeatableTask = isRepeatableTask;
887
1293
  exports.isTaskCompleted = isTaskCompleted;
888
1294
  exports.isTaskRunning = isTaskRunning;
1295
+ exports.loadGraphConfig = loadGraphConfig;
889
1296
  exports.next = next;
1297
+ exports.planExecution = planExecution;
890
1298
  exports.removeKeyFromProvides = removeKeyFromProvides;
891
1299
  exports.removeKeyFromRequires = removeKeyFromRequires;
892
1300
  exports.selectBestAlternative = selectBestAlternative;
893
1301
  exports.selectRandomTasks = selectRandomTasks;
1302
+ exports.validateGraphConfig = validateGraphConfig;
894
1303
  //# sourceMappingURL=index.cjs.map
895
1304
  //# sourceMappingURL=index.cjs.map