echo-parser.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /** 语句:echo 打印信息(写入 log + UI) */
  2. const types = ['echo']
  3. function parse(action, parseContext) {
  4. const { extractVarName } = parseContext
  5. const parsed = { type: 'echo' }
  6. if (action.inVars && Array.isArray(action.inVars)) {
  7. parsed.inVars = action.inVars.map(v => extractVarName(v))
  8. } else parsed.inVars = []
  9. if (action.value) parsed.value = action.value
  10. return Object.assign({}, action, parsed)
  11. }
  12. async function execute(action, ctx) {
  13. const { folderPath, variableContext, extractVarName, replaceVariablesInString, logMessage } = ctx
  14. let message = ''
  15. if (action.inVars && action.inVars.length > 0) {
  16. const messages = action.inVars.map(varWithBraces => {
  17. const varName = extractVarName(varWithBraces)
  18. const varValue = variableContext[varName]
  19. if (varWithBraces.startsWith('{') && varWithBraces.endsWith('}')) {
  20. return varValue !== undefined ? String(varValue) : varWithBraces
  21. }
  22. return varWithBraces
  23. })
  24. message = messages.join(' ')
  25. } else if (action.value) {
  26. message = replaceVariablesInString(action.value, variableContext)
  27. const doubleBracePattern = /\{\{([\w-]+)\}\}/g
  28. let match
  29. const variablesInValue = []
  30. while ((match = doubleBracePattern.exec(action.value)) !== null) variablesInValue.push(match[1])
  31. if (!message || message === action.value) {
  32. const missingVars = variablesInValue.filter(vn => {
  33. const v = variableContext[vn]
  34. return v === undefined || v === null || v === ''
  35. })
  36. if (missingVars.length > 0) message = `${action.value} [变量未定义或为空: ${missingVars.join(', ')}]`
  37. }
  38. }
  39. const now = new Date()
  40. const timeStr = `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
  41. const messageWithTime = message ? `${message} [系统时间: ${timeStr}]` : `[空消息] [系统时间: ${timeStr}]`
  42. await logMessage(messageWithTime, folderPath)
  43. if (typeof window !== 'undefined') {
  44. const logEvent = new CustomEvent('log-message', { detail: { message } })
  45. window.dispatchEvent(logEvent)
  46. }
  47. return { success: true }
  48. }
  49. module.exports = { types, parse, execute }