react-command-flow
Version:
A beautiful interactive CLI-style command interface for React apps
1,376 lines (1,356 loc) • 326 kB
JavaScript
import React, { useEffect, useRef, useMemo, useCallback, forwardRef, useState, useImperativeHandle } from 'react';
function _arrayLikeToArray(r, a) {
(null == a || a > r.length) && (a = r.length);
for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
return n;
}
function _arrayWithHoles(r) {
if (Array.isArray(r)) return r;
}
function _arrayWithoutHoles(r) {
if (Array.isArray(r)) return _arrayLikeToArray(r);
}
function asyncGeneratorStep(n, t, e, r, o, a, c) {
try {
var i = n[a](c),
u = i.value;
} catch (n) {
return void e(n);
}
i.done ? t(u) : Promise.resolve(u).then(r, o);
}
function _asyncToGenerator(n) {
return function () {
var t = this,
e = arguments;
return new Promise(function (r, o) {
var a = n.apply(t, e);
function _next(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
}
function _throw(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
}
_next(void 0);
});
};
}
function _classCallCheck(a, n) {
if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
}
function _defineProperties(e, r) {
for (var t = 0; t < r.length; t++) {
var o = r[t];
o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
}
}
function _createClass(e, r, t) {
return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
writable: !1
}), e;
}
function _createForOfIteratorHelper(r, e) {
var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (!t) {
if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
t && (r = t);
var n = 0,
F = function () {};
return {
s: F,
n: function () {
return n >= r.length ? {
done: !0
} : {
done: !1,
value: r[n++]
};
},
e: function (r) {
throw r;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var o,
a = !0,
u = !1;
return {
s: function () {
t = t.call(r);
},
n: function () {
var r = t.next();
return a = r.done, r;
},
e: function (r) {
u = !0, o = r;
},
f: function () {
try {
a || null == t.return || t.return();
} finally {
if (u) throw o;
}
}
};
}
function _defineProperty(e, r, t) {
return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t, e;
}
function _iterableToArray(r) {
if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
}
function _iterableToArrayLimit(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = !0,
o = !1;
try {
if (i = (t = t.call(r)).next, 0 === l) {
if (Object(t) !== t) return;
f = !1;
} else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
} catch (r) {
o = !0, n = r;
} finally {
try {
if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
} finally {
if (o) throw n;
}
}
return a;
}
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function (r) {
return Object.getOwnPropertyDescriptor(e, r).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
_defineProperty(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
function _regeneratorRuntime() {
_regeneratorRuntime = function () {
return e;
};
var t,
e = {},
r = Object.prototype,
n = r.hasOwnProperty,
o = Object.defineProperty || function (t, e, r) {
t[e] = r.value;
},
i = "function" == typeof Symbol ? Symbol : {},
a = i.iterator || "@@iterator",
c = i.asyncIterator || "@@asyncIterator",
u = i.toStringTag || "@@toStringTag";
function define(t, e, r) {
return Object.defineProperty(t, e, {
value: r,
enumerable: !0,
configurable: !0,
writable: !0
}), t[e];
}
try {
define({}, "");
} catch (t) {
define = function (t, e, r) {
return t[e] = r;
};
}
function wrap(t, e, r, n) {
var i = e && e.prototype instanceof Generator ? e : Generator,
a = Object.create(i.prototype),
c = new Context(n || []);
return o(a, "_invoke", {
value: makeInvokeMethod(t, r, c)
}), a;
}
function tryCatch(t, e, r) {
try {
return {
type: "normal",
arg: t.call(e, r)
};
} catch (t) {
return {
type: "throw",
arg: t
};
}
}
e.wrap = wrap;
var h = "suspendedStart",
l = "suspendedYield",
f = "executing",
s = "completed",
y = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var p = {};
define(p, a, function () {
return this;
});
var d = Object.getPrototypeOf,
v = d && d(d(values([])));
v && v !== r && n.call(v, a) && (p = v);
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
function defineIteratorMethods(t) {
["next", "throw", "return"].forEach(function (e) {
define(t, e, function (t) {
return this._invoke(e, t);
});
});
}
function AsyncIterator(t, e) {
function invoke(r, o, i, a) {
var c = tryCatch(t[r], t, o);
if ("throw" !== c.type) {
var u = c.arg,
h = u.value;
return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
invoke("next", t, i, a);
}, function (t) {
invoke("throw", t, i, a);
}) : e.resolve(h).then(function (t) {
u.value = t, i(u);
}, function (t) {
return invoke("throw", t, i, a);
});
}
a(c.arg);
}
var r;
o(this, "_invoke", {
value: function (t, n) {
function callInvokeWithMethodAndArg() {
return new e(function (e, r) {
invoke(t, n, e, r);
});
}
return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
}
});
}
function makeInvokeMethod(e, r, n) {
var o = h;
return function (i, a) {
if (o === f) throw Error("Generator is already running");
if (o === s) {
if ("throw" === i) throw a;
return {
value: t,
done: !0
};
}
for (n.method = i, n.arg = a;;) {
var c = n.delegate;
if (c) {
var u = maybeInvokeDelegate(c, n);
if (u) {
if (u === y) continue;
return u;
}
}
if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
if (o === h) throw o = s, n.arg;
n.dispatchException(n.arg);
} else "return" === n.method && n.abrupt("return", n.arg);
o = f;
var p = tryCatch(e, r, n);
if ("normal" === p.type) {
if (o = n.done ? s : l, p.arg === y) continue;
return {
value: p.arg,
done: n.done
};
}
"throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
}
};
}
function maybeInvokeDelegate(e, r) {
var n = r.method,
o = e.iterator[n];
if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
var i = tryCatch(o, e.iterator, r.arg);
if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
var a = i.arg;
return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
}
function pushTryEntry(t) {
var e = {
tryLoc: t[0]
};
1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
}
function resetTryEntry(t) {
var e = t.completion || {};
e.type = "normal", delete e.arg, t.completion = e;
}
function Context(t) {
this.tryEntries = [{
tryLoc: "root"
}], t.forEach(pushTryEntry, this), this.reset(!0);
}
function values(e) {
if (e || "" === e) {
var r = e[a];
if (r) return r.call(e);
if ("function" == typeof e.next) return e;
if (!isNaN(e.length)) {
var o = -1,
i = function next() {
for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
return next.value = t, next.done = !0, next;
};
return i.next = i;
}
}
throw new TypeError(typeof e + " is not iterable");
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
value: GeneratorFunctionPrototype,
configurable: !0
}), o(GeneratorFunctionPrototype, "constructor", {
value: GeneratorFunction,
configurable: !0
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
var e = "function" == typeof t && t.constructor;
return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
}, e.mark = function (t) {
return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
}, e.awrap = function (t) {
return {
__await: t
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
return this;
}), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
void 0 === i && (i = Promise);
var a = new AsyncIterator(wrap(t, r, n, o), i);
return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
return t.done ? t.value : a.next();
});
}, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
return this;
}), define(g, "toString", function () {
return "[object Generator]";
}), e.keys = function (t) {
var e = Object(t),
r = [];
for (var n in e) r.push(n);
return r.reverse(), function next() {
for (; r.length;) {
var t = r.pop();
if (t in e) return next.value = t, next.done = !1, next;
}
return next.done = !0, next;
};
}, e.values = values, Context.prototype = {
constructor: Context,
reset: function (e) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
},
stop: function () {
this.done = !0;
var t = this.tryEntries[0].completion;
if ("throw" === t.type) throw t.arg;
return this.rval;
},
dispatchException: function (e) {
if (this.done) throw e;
var r = this;
function handle(n, o) {
return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
}
for (var o = this.tryEntries.length - 1; o >= 0; --o) {
var i = this.tryEntries[o],
a = i.completion;
if ("root" === i.tryLoc) return handle("end");
if (i.tryLoc <= this.prev) {
var c = n.call(i, "catchLoc"),
u = n.call(i, "finallyLoc");
if (c && u) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
} else if (c) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
} else {
if (!u) throw Error("try statement without catch or finally");
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
}
}
}
},
abrupt: function (t, e) {
for (var r = this.tryEntries.length - 1; r >= 0; --r) {
var o = this.tryEntries[r];
if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
var i = o;
break;
}
}
i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
var a = i ? i.completion : {};
return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
},
complete: function (t, e) {
if ("throw" === t.type) throw t.arg;
return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
},
finish: function (t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
}
},
catch: function (t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.tryLoc === t) {
var n = r.completion;
if ("throw" === n.type) {
var o = n.arg;
resetTryEntry(r);
}
return o;
}
}
throw Error("illegal catch attempt");
},
delegateYield: function (e, r, n) {
return this.delegate = {
iterator: values(e),
resultName: r,
nextLoc: n
}, "next" === this.method && (this.arg = t), y;
}
}, e;
}
function _slicedToArray(r, e) {
return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _toConsumableArray(r) {
return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
}
function _toPrimitive(t, r) {
if ("object" != typeof t || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != typeof i) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
function _toPropertyKey(t) {
var i = _toPrimitive(t, "string");
return "symbol" == typeof i ? i : i + "";
}
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
function _unsupportedIterableToArray(r, a) {
if (r) {
if ("string" == typeof r) return _arrayLikeToArray(r, a);
var t = {}.toString.call(r).slice(8, -1);
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
}
}
// Central place for all translations used in the application
var defaultTranslations$1 = {
// CommandLine related translations
welcome: "✨ Welcome to React Command Flow Terminal ✨",
loading: "Loading",
pleaseWait: "⌛ Please wait...",
suggestions: "Suggestions: ",
errorReadingHistory: "Error reading history from localStorage:",
errorSavingHistory: "Error saving history to localStorage:",
devWarningPromise: "[DEV WARNING] React tried to render a Promise at output index {idx}. Did you forget to await onComplete?",
// useCommandFlow related translations
helpTip: "Type `help` to see available commands.",
errorReadingOutput: "Error reading output from localStorage:",
errorSavingOutput: "Error saving output to localStorage:",
commandCancelled: "❌ Command cancelled.",
errorOccurred: "❌ An error occurred.",
didYouMean: "Did you mean: {suggestions}?",
// CommandFlowEngine related translations
unknownCommand: "Unknown command: {commandName}. Type `help` for help.",
noActiveSession: "No active command session.",
failedToResolvePrompt: "Failed to resolve prompt.",
failedToResolveNextPrompt: "Failed to resolve next prompt.",
// Response options
yes: "y",
no: "n",
exitCommands: ["exit", "cancel", "quit"],
backCommands: ["back"]
};
// Helper function to apply translations with variable replacements
function getTranslation(key) {
var translations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var replacements = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var text = translations[key] || defaultTranslations$1[key] || key;
// Replace placeholders with actual values
Object.entries(replacements).forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
placeholder = _ref2[0],
value = _ref2[1];
text = text.replace("{".concat(placeholder, "}"), value);
});
return text;
}
var SessionManager = /*#__PURE__*/function () {
function SessionManager() {
_classCallCheck(this, SessionManager);
this.session = null;
this.currentCommandName = null;
}
return _createClass(SessionManager, [{
key: "startSession",
value: function startSession(commandName, command) {
var initialData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
this.currentCommandName = commandName;
this.session = {
name: commandName,
stepIndex: 0,
data: initialData,
command: command,
promptedStepHistory: []
};
}
}, {
key: "endSession",
value: function endSession() {
this.session = null;
this.currentCommandName = null;
}
}, {
key: "isInSession",
value: function isInSession() {
return this.session !== null;
}
}, {
key: "getCurrentStep",
value: function getCurrentStep() {
if (!this.session) return null;
var steps = this.session.command.steps;
var data = this.session.data || {};
var step = steps[this.session.stepIndex];
// Skip steps whose condition evaluates to false (conditional steps).
// When skipping, auto-fill the step's field from _lastCreatedUuid so
// that subprocess-created entities are captured in the session data.
while (step && typeof step.condition === "function" && !step.condition(data)) {
if (step.field && data._lastCreatedUuid) {
data[step.field] = data._lastCreatedUuid;
}
this.session.stepIndex += 1;
step = steps[this.session.stepIndex];
}
return step;
}
}, {
key: "moveToNextStep",
value: function moveToNextStep() {
if (this.session) {
this.session.stepIndex++;
}
}
}, {
key: "recordPromptedStep",
value: function recordPromptedStep(stepIndex) {
if (this.session) {
this.session.promptedStepHistory.push(stepIndex);
}
}
}, {
key: "moveToPreviousPromptedStep",
value: function moveToPreviousPromptedStep() {
if (!this.session || !this.session.promptedStepHistory.length) {
return false;
}
this.session.stepIndex = this.session.promptedStepHistory.pop();
return true;
}
}, {
key: "isAtFirstPromptedStep",
value: function isAtFirstPromptedStep() {
if (!this.session) return true;
return this.session.promptedStepHistory.length === 0;
}
}, {
key: "hasMoreSteps",
value: function hasMoreSteps() {
if (!this.session) return false;
return this.session.stepIndex < this.session.command.steps.length;
}
}, {
key: "getCurrentStepIndex",
value: function getCurrentStepIndex() {
var _this$session;
return ((_this$session = this.session) === null || _this$session === void 0 ? void 0 : _this$session.stepIndex) || 0;
}
}, {
key: "getTotalSteps",
value: function getTotalSteps() {
var _this$session2;
return ((_this$session2 = this.session) === null || _this$session2 === void 0 || (_this$session2 = _this$session2.command) === null || _this$session2 === void 0 || (_this$session2 = _this$session2.steps) === null || _this$session2 === void 0 ? void 0 : _this$session2.length) || 0;
}
}, {
key: "getSessionData",
value: function getSessionData() {
var _this$session3;
return ((_this$session3 = this.session) === null || _this$session3 === void 0 ? void 0 : _this$session3.data) || {};
}
}, {
key: "updateSessionData",
value: function updateSessionData(key, value) {
if (this.session) {
if (!this.session.data) {
this.session.data = {};
}
this.session.data[key] = value;
}
}
// Bulk update session data
}, {
key: "mergeSessionData",
value: function mergeSessionData(data) {
if (this.session && data && _typeof(data) === "object") {
if (!this.session.data) {
this.session.data = {};
}
Object.assign(this.session.data, data);
}
}
}]);
}();
/**
* Step Data Loader
*
* Handles the `load` step property that allows pre-loading data
* for use throughout the step lifecycle (intro, prompt, validate, outro)
*/
/**
* Execute the load function and cache the result
* @param {Object} step - The step configuration
* @param {Object} sessionData - Current session data
* @param {Object} callbacks - Available callbacks
* @returns {Promise<Object>} Loaded data
*/
function executeStepLoader(_x, _x2) {
return _executeStepLoader.apply(this, arguments);
}
/**
* Create an enhanced context object that includes loaded data
* @param {Object} sessionData - Current session data
* @param {Object} loadedData - Data from the load function
* @param {Object} callbacks - Available callbacks
* @returns {Object} Enhanced context for step functions
*/
function _executeStepLoader() {
_executeStepLoader = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(step, sessionData) {
var callbacks,
loadedData,
_args = arguments;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
callbacks = _args.length > 2 && _args[2] !== undefined ? _args[2] : {};
if (!(!step.load || typeof step.load !== "function")) {
_context.next = 3;
break;
}
return _context.abrupt("return", null);
case 3:
_context.prev = 3;
_context.next = 6;
return step.load(sessionData, callbacks);
case 6:
loadedData = _context.sent;
return _context.abrupt("return", loadedData || {});
case 10:
_context.prev = 10;
_context.t0 = _context["catch"](3);
console.error("❌ Error in step load function:", _context.t0);
throw new Error("Step load failed: ".concat(_context.t0.message));
case 14:
case "end":
return _context.stop();
}
}, _callee, null, [[3, 10]]);
}));
return _executeStepLoader.apply(this, arguments);
}
function createStepContext(sessionData) {
var loadedData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var callbacks = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var context = _objectSpread2(_objectSpread2({}, sessionData), {}, {
// Add loaded data under a special key to avoid conflicts
$loaded: loadedData,
$callbacks: callbacks
});
// Add convenience methods for accessing loaded data
context.$get = function (key) {
var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
return loadedData && loadedData[key] !== undefined ? loadedData[key] : defaultValue;
};
context.$has = function (key) {
return loadedData && loadedData.hasOwnProperty(key);
};
context.$loadedKeys = function () {
return loadedData ? Object.keys(loadedData) : [];
};
return context;
}
/**
* Execute a step function with enhanced context that includes loaded data
* @param {Function} stepFunction - The function to execute (intro, prompt, validate, etc.)
* @param {any} inputValue - Input value (for functions that need it)
* @param {Object} sessionData - Current session data
* @param {Object} loadedData - Data from the load function
* @param {Object} callbacks - Available callbacks
* @returns {Promise<any>} Result of the step function
*/
function executeStepFunction(_x3, _x4, _x5) {
return _executeStepFunction.apply(this, arguments);
}
/**
* Check if a step has a load function
* @param {Object} step - The step configuration
* @returns {boolean} True if step has a load function
*/
function _executeStepFunction() {
_executeStepFunction = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(stepFunction, inputValue, sessionData) {
var loadedData,
callbacks,
context,
funcString,
paramCount,
_args2 = arguments;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
loadedData = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : null;
callbacks = _args2.length > 4 && _args2[4] !== undefined ? _args2[4] : {};
if (!(typeof stepFunction === "string")) {
_context2.next = 4;
break;
}
return _context2.abrupt("return", stepFunction);
case 4:
if (!(!stepFunction || typeof stepFunction !== "function")) {
_context2.next = 6;
break;
}
return _context2.abrupt("return", null);
case 6:
context = createStepContext(sessionData, loadedData, callbacks);
_context2.prev = 7;
// Determine function signature and call appropriately
funcString = stepFunction.toString();
paramCount = stepFunction.length;
console.log("🔍 executeStepFunction:", {
paramCount: paramCount,
hasInput: inputValue !== null && inputValue !== undefined,
callbacksType: _typeof(callbacks),
callbacksKeys: callbacks ? Object.keys(callbacks) : "null",
hasFire: callbacks !== null && callbacks !== void 0 && callbacks.fire ? "yes" : "no"
});
if (!(paramCount === 0)) {
_context2.next = 17;
break;
}
_context2.next = 14;
return stepFunction();
case 14:
return _context2.abrupt("return", _context2.sent);
case 17:
if (!(paramCount === 1)) {
_context2.next = 29;
break;
}
if (!(funcString.includes("$loaded") || funcString.includes("$get") || funcString.includes("sessionData"))) {
_context2.next = 24;
break;
}
_context2.next = 21;
return stepFunction(context);
case 21:
return _context2.abrupt("return", _context2.sent);
case 24:
_context2.next = 26;
return stepFunction(inputValue !== null ? inputValue : sessionData);
case 26:
return _context2.abrupt("return", _context2.sent);
case 27:
_context2.next = 45;
break;
case 29:
if (!(paramCount === 2)) {
_context2.next = 42;
break;
}
if (!(inputValue === null || inputValue === undefined)) {
_context2.next = 37;
break;
}
// No input - this is intro/prompt/outro: (sessionData, callbacks)
console.log("📞 Calling with (sessionData, callbacks)");
_context2.next = 34;
return stepFunction(sessionData, callbacks);
case 34:
return _context2.abrupt("return", _context2.sent);
case 37:
_context2.next = 39;
return stepFunction(inputValue, sessionData);
case 39:
return _context2.abrupt("return", _context2.sent);
case 40:
_context2.next = 45;
break;
case 42:
_context2.next = 44;
return stepFunction(inputValue, sessionData, callbacks);
case 44:
return _context2.abrupt("return", _context2.sent);
case 45:
_context2.next = 51;
break;
case 47:
_context2.prev = 47;
_context2.t0 = _context2["catch"](7);
console.error("❌ Error executing step function:", _context2.t0);
throw _context2.t0;
case 51:
case "end":
return _context2.stop();
}
}, _callee2, null, [[7, 47]]);
}));
return _executeStepFunction.apply(this, arguments);
}
function hasStepLoader(step) {
return step && typeof step.load === "function";
}
/**
* Validate loaded data structure
* @param {any} loadedData - Data returned from load function
* @returns {boolean} True if data is valid
*/
function validateLoadedData(loadedData) {
// Loaded data should be an object or null
return loadedData === null || loadedData === undefined || _typeof(loadedData) === "object" && !Array.isArray(loadedData);
}
/**
* Create a debug summary of loaded data for logging
* @param {Object} loadedData - Data from the load function
* @returns {string} Debug summary
*/
function createLoadedDataSummary(loadedData) {
if (!loadedData) {
return "No data loaded";
}
var keys = Object.keys(loadedData);
var summary = keys.map(function (key) {
var value = loadedData[key];
var type = _typeof(value);
var preview = type === "object" ? Array.isArray(value) ? "Array(".concat(value.length, ")") : "Object" : type === "string" && value.length > 20 ? "\"".concat(value.substring(0, 20), "...\"") : JSON.stringify(value);
return "".concat(key, ": ").concat(preview);
}).join(", ");
return "Loaded ".concat(keys.length, " properties: {").concat(summary, "}");
}
var stepDataLoader = {
executeStepLoader: executeStepLoader,
createStepContext: createStepContext,
executeStepFunction: executeStepFunction,
hasStepLoader: hasStepLoader,
validateLoadedData: validateLoadedData,
createLoadedDataSummary: createLoadedDataSummary
};
var stepDataLoader$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
executeStepLoader: executeStepLoader,
createStepContext: createStepContext,
executeStepFunction: executeStepFunction,
hasStepLoader: hasStepLoader,
validateLoadedData: validateLoadedData,
createLoadedDataSummary: createLoadedDataSummary,
'default': stepDataLoader
});
var CommandProcessor = /*#__PURE__*/function () {
function CommandProcessor(commands, translations) {
var store = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
_classCallCheck(this, CommandProcessor);
this.commands = commands;
this.translations = translations;
this.store = store; // Store reference for accessing callback registry
}
return _createClass(CommandProcessor, [{
key: "processSteplessCommand",
value: function () {
var _processSteplessCommand = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(command, commandName) {
var initialData,
callbacks,
output,
introOutput,
commandOutput,
outroOutput,
redirectResult,
_args = arguments;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
initialData = _args.length > 2 && _args[2] !== undefined ? _args[2] : {};
callbacks = _args.length > 3 && _args[3] !== undefined ? _args[3] : {};
output = ""; // Add intro if present
if (!command.intro) {
_context.next = 8;
break;
}
_context.next = 6;
return executeStepFunction(command.intro, null, initialData, null, callbacks);
case 6:
introOutput = _context.sent;
if (introOutput) {
output += introOutput;
output += "\n";
}
case 8:
if (!command.onComplete) {
_context.next = 13;
break;
}
_context.next = 11;
return executeStepFunction(command.onComplete, null, initialData, null, callbacks);
case 11:
commandOutput = _context.sent;
if (commandOutput) {
output += commandOutput;
}
case 13:
if (!command.outro) {
_context.next = 19;
break;
}
if (output) output += "\n";
_context.next = 17;
return executeStepFunction(command.outro, null, initialData, null, callbacks);
case 17:
outroOutput = _context.sent;
if (outroOutput) {
output += outroOutput;
}
case 19:
_context.next = 21;
return this.handleRedirect(null, command, null, initialData, callbacks);
case 21:
redirectResult = _context.sent;
if (!redirectResult) {
_context.next = 24;
break;
}
return _context.abrupt("return", {
output: output,
nextCommand: redirectResult.command,
nextCommandData: redirectResult.payload || {}
});
case 24:
return _context.abrupt("return", {
output: output
});
case 25:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function processSteplessCommand(_x, _x2) {
return _processSteplessCommand.apply(this, arguments);
}
return processSteplessCommand;
}()
}, {
key: "validateInput",
value: function () {
var _validateInput = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(step, input) {
var sessionData,
loadedData,
callbacks,
_args2 = arguments;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
sessionData = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : {};
loadedData = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : null;
callbacks = _args2.length > 4 && _args2[4] !== undefined ? _args2[4] : {};
if (step) {
_context2.next = 5;
break;
}
return _context2.abrupt("return", true);
case 5:
if (step.validate) {
_context2.next = 7;
break;
}
return _context2.abrupt("return", true);
case 7:
_context2.next = 9;
return executeStepFunction(step.validate, input, sessionData, loadedData, callbacks);
case 9:
return _context2.abrupt("return", _context2.sent);
case 10:
case "end":
return _context2.stop();
}
}, _callee2);
}));
function validateInput(_x3, _x4) {
return _validateInput.apply(this, arguments);
}
return validateInput;
}()
}, {
key: "processStepOutro",
value: function () {
var _processStepOutro = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(step, input, sessionData) {
var loadedData,
callbacks,
_args3 = arguments;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
loadedData = _args3.length > 3 && _args3[3] !== undefined ? _args3[3] : null;
callbacks = _args3.length > 4 && _args3[4] !== undefined ? _args3[4] : {};
if (step.outro) {
_context3.next = 4;
break;
}
return _context3.abrupt("return", "");
case 4:
_context3.next = 6;
return executeStepFunction(step.outro, input, sessionData, loadedData, callbacks);
case 6:
return _context3.abrupt("return", _context3.sent);
case 7:
case "end":
return _context3.stop();
}
}, _callee3);
}));
function processStepOutro(_x5, _x6, _x7) {
return _processStepOutro.apply(this, arguments);
}
return processStepOutro;
}()
}, {
key: "processCommandCompletion",
value: function () {
var _processCommandCompletion = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(command, sessionData) {
var callbacks,
output,
commandOutput,
outroOutput,
_args4 = arguments;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
callbacks = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : {};
output = "";
console.log("🎬 Processing command completion:", {
commandName: command.name,
hasOnComplete: !!command.onComplete,
hasOutro: !!command.outro
});
if (!command.onComplete) {
_context4.next = 9;
break;
}
_context4.next = 6;
return executeStepFunction(command.onComplete, null,
// no input for onComplete
sessionData, null,
// no loadedData
callbacks);
case 6:
commandOutput = _context4.sent;
console.log("✅ onComplete output:", commandOutput);
output += commandOutput;
case 9:
if (!command.outro) {
_context4.next = 16;
break;
}
if (output) output += "\n";
_context4.next = 13;
return executeStepFunction(command.outro, null,
// no input for outro
sessionData, null,
// no loadedData
callbacks);
case 13:
outroOutput = _context4.sent;
console.log("👋 outro output:", outroOutput);
if (outroOutput) {
output += outroOutput;
}
case 16:
console.log("📦 Total completion output:", output);
return _context4.abrupt("return", output);
case 18:
case "end":
return _context4.stop();
}
}, _callee4);
}));
function processCommandCompletion(_x8, _x9) {
return _processCommandCompletion.apply(this, arguments);
}
return processCommandCompletion;
}()
}, {
key: "handleRedirect",
value: function () {
var _handleRedirect = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(step, command, input, sessionData) {
var callbacks,
redirectFunction,
redirectResult,
commandExists,
_command,
payload,
_commandExists,
_args5 = arguments;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
callbacks = _args5.length > 4 && _args5[4] !== undefined ? _args5[4] : {};
// Check for redirect function - prioritize step.redirect, fallback to command.redirect
redirectFunction = (step === null || step === void 0 ? void 0 : step.redirect) || (command === null || command === void 0 ? void 0 : command.redirect);
if (redirectFunction) {
_context5.next = 4;
break;
}
return _context5.abrupt("return", null);
case 4:
_context5.prev = 4;
_context5.next = 7;
return executeStepFunction(redirectFunction, input, sessionData, null, callbacks);
case 7:
redirectResult = _context5.sent;
console.log("🎯 Redirect function returned:", redirectResult);
console.log("Redirect result type:", _typeof(redirectResult));
// Handle both string returns and object returns with payload
if (!(typeof redirectResult === "string")) {
_context5.next = 17;
break;
}
console.log("\uD83D\uDD0D Checking if command \"".concat(redirectResult, "\" exists..."));
commandExists = !!this.commands[redirectResult];
if (!commandExists) {
console.warn("Redirect target \"".concat(redirectResult, "\" not found. Available commands:"), Object.keys(this.commands));
}
return _context5.abrupt("return", commandExists ? {
command: redirectResult
} : null);
case 17:
if (!(redirectResult && _typeof(redirectResult) === "object")) {
_context5.next = 23;
break;
}
_command = redirectResult.command, payload = redirectResult.payload;
console.log("\uD83D\uDD0D Checking if object command \"".concat(_command, "\" exists..."));
_commandExists = _command && !!this.commands[_command];
if (!_commandExists && _command) {
console.warn("Redirect target \"".concat(_command, "\" not found. Available commands:"), Object.keys(this.commands));
}
return _context5.abrupt("return", _commandExists ? {
command: _command,
payload: payload
} : null);
case 23:
if (redirectResult !== null && redirectResult !== undefined) {
console.warn("Redirect function returned unexpected type:", _typeof(redirectResult), redirectResult);
}
return _context5.abrupt("return", null);
case 27:
_context5.prev = 27;
_context5.t0 = _context5["catch"](4);
console.error("Error in redirect function:", _context5.t0);
return _context5.abrupt("return", null);
case 31:
case "end":
return _context5.stop();
}
}, _callee5, this, [[4, 27]]);
}));
function handleRedirect(_x10, _x11, _x12, _x13) {
return _handleRedirect.apply(this, arguments);
}
return handleRedirect;
}()
}]);
}();
var PromptResolver = /*#__PURE__*/function () {
function PromptResolver() {
_classCallCheck(this, PromptResolver);
}
return _createClass(PromptResolver, [{
key: "resolvePrompt",
value: function () {
var _resolvePrompt = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(step) {
var options,
_options$skipIntro,
skipIntro,
_options$sessionData,
sessionData,
_options$callbacks,
callbacks,
_options$loadedData,
loadedData,
_options$attributes,
attributes,
fullPrompt,
dynamicIntro,
dynamicPrompt,
_args = arguments;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
options = _args.length > 1 && _args[1] !== undefined ? _args[1] : {};
if (step) {
_context.next = 3;
break;
}
return _context.abrupt("return", null);
case 3:
_options$skipIntro = options.skipIntro, skipIntro = _options$skipIntro === void 0 ? false : _options$skipIntro, _options$sessionData = options.sessionData, sessionData = _options$sessionData === void 0 ? {} : _options$sessionData, _options$callbacks = options.callbacks, callbacks = _options$callbacks === void 0 ? {} : _options$callbacks, _options$loadedData = options.loadedData, loadedData = _options$loadedData === void 0 ? null : _options$loadedData, _options$attributes = options.attributes, attributes = _options$attributes === void 0 ? {} : _options$attributes;
fullPrompt = "";
_context.prev = 5;
if (!(!skipIntro && step.intro)) {
_context.next = 12;
break;
}
console.log("🔍 Resolving step intro...");
_context.next = 10;
return executeStepFunction(step.intro, null,
// intro doesn't take input
sessionData, loadedData, callbacks, attributes);
case 10:
dynamicIntro = _context.sent;
if (dynamicIntro) {
fullPrompt += dynamicIntro;
fullPrompt += "\n";
}
case 12:
if (step.prompt) {
_context.next = 14;
break;
}
return _context.abrupt("return", fullPrompt || null);
case 14:
// Add the main prompt
console.log("🔍 Resolving step prompt...");
_context.next = 17;
return executeStepFunction(step.prompt, null,
// prompt doesn't take input
sessionData, loadedData, callbacks, attributes);
case 17:
dynamicPrompt = _context.sent;
if (dynamicPrompt) {
fullPrompt += dynamicPrompt;
}
console.log("✅ Prompt resolved:", fullPrompt);
return _context.abrupt("return", fullPrompt);
case 23:
_context.prev = 23;
_context.t0 = _context["catch"](5);
console.error("❌ Error resolving prompt:", _context.t0);
return _context.abrupt("return", null);
case 27:
case "end":
return _context.stop();
}
}, _callee, null, [[5, 23]]);
}));
function resolvePrompt(_x) {
return _resolvePrompt.apply(this, arguments);
}
return resolvePrompt;
}()
}, {
key: "buildIntroMessage",
value: function () {
var _buildIntroMessage = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(command) {
var sessionData,
callbacks,
introMessage,
dynamicIntro,
_args2 = arguments;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
sessionData = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {};
callbacks = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : {};
introMessage = "";
if (!command.intro) {
_context2.next = 8;
break;
}
_context2.next = 6;
return executeStepFunction(command.intro, null,
// intro doesn't take input
sessionData, null,
// no loaded data at command level
callbacks);
case 6:
dynamicIntro = _context2.sent;
if (dynamicIntro) {
introMessage += dynamicIntro;
introMessage += "\n";
}
case 8:
return _context2.abrupt("return", introMessage);
case 9:
case "end":
return _context2.stop();