# If Condition

> 针对输入载荷求值一个布尔条件，将执行流一分为二。

Source: https://docs.sommatic.ai/zh/nodes/flow.if/

- 标识: `flow.if`
- 类别: 流程控制
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

针对输入载荷求值一个布尔条件，将执行流一分为二。

该算子是一个网关：根据所配置表达式的结果，将执行路由到“true”或“false”端口。它支持两种求值模式：以 Sommatic AI Expression Engine（{{ }} 语法，通过 vm.Script 运行完整 JavaScript）为主引擎；对未使用 {{ }} 包裹的表达式，则以原生 JSONata 作为更简单的后备方案。

**行为：**
- 表达式结果为真值时，执行经由“true”端口继续。
- 表达式结果为假值时，执行经由“false”端口继续。
- 若将“treat_missing_as”设为 true，且表达式结果为 undefined/null，则按 false 处理。

## 配置

- `expr` (string, 必填, 支持表达式): 结果必须为布尔值的表达式。用 {{ }} 包裹即可使用 Sommatic AI Expression Engine（JavaScript），并可引用 $json、$input 或 $("Node Name") 等变量，例如 {{ $json.age >= 18 }} 或 {{ $json.status === "active" }}。不加 {{ }} 时，文本会作为 JSONata 针对载荷求值，字段直接引用即可：age >= 18 或 status = "active"。JSONata 中未绑定 $json，因此不加 {{ }} 的 $json.age >= 18 始终为 false。
- `treat_missing_as` (boolean, 可选): 启用后，表达式结果为 undefined 或 null 时会自动路由到 False 端口，而不是抛出错误。 默认值: `false`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `true` (默认): 表达式为真时激活。
- `false`: 表达式为假时激活。
- `error`: 表达式求值失败时激活。

## 输入契约

- `payload` (object, 可选)

## 输出契约

- `payload` (object, 可选)

## 在表达式中

后续节点可通过 `$("If Condition").item.json.<路径>` 读取此节点输出中的内容（请把 `If Condition` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `true` 返回的路径，依据“端口”一节所示的输出。

- `$("If Condition").item.json.payload` (object) **worker 不返回：读取结果为 undefined.**
- `$("If Condition").item.json.order_id` (string) = `"ord_123"` (编辑器不提示)
- `$("If Condition").item.json.amount` (number) = `1250` (编辑器不提示)
- `$("If Condition").item.json.status` (string) = `"active"` (编辑器不提示)


## 工作原理

对条件求值，并将原样的 payload 从 `true` 或 `false` 端口输出。

1. 解析 `expr`：`{{ }}` 由 Expression Engine 求值（隔离上下文中的 JavaScript，限时 100 毫秒），可使用 `$json`、`$("Node")`、`$now` 等引擎变量。
2. 若解析结果为 `undefined`、`null` 或 `""`，返回不带端口的错误信封（见错误）。
3. 布尔值直接使用。
4. 字符串会作为 JSONata 针对 payload 求值，字段直接引用：`amount > 1000`、`status = "active"`。返回字符串的 `{{ }}`，以及在引擎中失败的 `{{ }}`（其原始文本会被当作 JSONata 解析并失败）也按此处理。
5. 其他类型（数字、对象、数组）无法作为 JSONata 编译，会走 `error`。
6. 用 `!!result` 转换结果，并将 payload 从 `true` 或 `false` 输出，附带 `meta.evaluation` `{ expr, result, raw_result }`（`expr` 为原始文本）。

## 在工作流中

### 节点

```json
{
  "node_id": "node-high-value",
  "label": "High value?",
  "operator_slug": "flow.if",
  "operator_version": "1.0.0",
  "config": {
    "expr": "{{ $json.amount > 1000 }}",
    "treat_missing_as": false
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "order_id": "ord_123",
    "amount": 1250,
    "status": "active"
  },
  "port": "true",
  "meta": {
    "evaluation": {
      "expr": "{{ $json.amount > 1000 }}",
      "result": true,
      "raw_result": true
    }
  }
}
```

## 输出端口 (代码中的行为)

### `true`

条件为真值。

```json
{
  "order_id": "ord_123",
  "amount": 1250,
  "status": "active"
}
```

### `false`

条件为假值，包括 JSONata 返回 `undefined` 和 `null` 的情况。

```json
{
  "order_id": "ord_124",
  "amount": 80,
  "status": "active"
}
```

### `error`

JSONata 编译或求值失败。

```json
{
  "ok": false,
  "errors": [
    "Expression evaluation failed: path.charAt is not a function"
  ],
  "port": "error"
}
```

## 代码中的行为

- `expr`: 不使用 `{{ }}` 时，JSONata 中没有绑定 `$json`：`$json.amount > 1000` 永远为假。返回字符串的 `{{ }}`（如 `{{ $json.name }}`）会再次作为 JSONata 路径求值，通常为假。
- `treat_missing_as`: 没有可见效果：`undefined` 和 `null` 结果总是走 `false`，两种情况下都不会抛错。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Missing configuration: expr is required.` | `out` | `expr` 为空，或其 `{{ }}` 返回 `undefined`、`null` 或 `""`（例如字段缺失时的 `{{ $json.flag }}`）。信封没有端口，引擎会把它路由到本节点并不存在的 `out`：分支会静默停止。请显式比较，例如 `{{ $json.flag === true }}`。 |
| `Expression evaluation failed: path.charAt is not a function` | `error` | `{{ }}` 返回了数字、对象或数组。请返回布尔值，例如 `{{ $json.items.length > 0 }}`。 |
| `Expression evaluation failed: <JSONata message>` | `error` | JSONata 无效，或 `{{ }}` 存在 JavaScript 错误、其原始文本随后被当作 JSONata 解析（例如 `Expected ":", got "}"`）。 |

## 说明与限制

- `meta` 只记录在运行步骤中：下游节点收到的 payload 是 `data`，无法通过 `$json` 或 `$("Node")` 读取 `meta`。
- 当返回的信封没有 `data`（或 `data` 为假值）时，引擎会把整个信封作为节点输出：经 `error` 端口时，下一个节点收到的 payload 是 `{ ok: false, errors: [...], port: "error" }`。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "flow.if",
  "name": "If Condition",
  "category": "flow",
  "description": "Evaluates a boolean condition against the input payload to bifurcate the execution flow.\n\n  This operator functions as a gateway that routes execution to either the 'true' or 'false' port based on the result of the configured expression. It supports two evaluation modes: the Sommatic AI Expression Engine ({{ }} syntax, full JavaScript via vm.Script) as the primary engine, and raw JSONata as a simpler fallback for expressions entered without {{ }}.\n\n  **Behavior:**\n  - If the expression evaluates to a truthy value, execution proceeds through the 'true' port.\n  - If the expression evaluates to a falsy value, execution proceeds through the 'false' port.\n  - If 'treat_missing_as' is set to true and the expression yields undefined/null, it is treated as false.",
  "capabilities": [
    "branching",
    "logic",
    "expression-engine",
    "jsonata"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "expr"
    ],
    "properties": {
      "expr": {
        "type": "string",
        "title": "Condition Expression",
        "description": "An expression that must evaluate to a boolean. Wrap it in {{ }} to use the Sommatic AI Expression Engine (JavaScript) with variables like $json, $input or $(\"Node Name\"), e.g. {{ $json.age >= 18 }} or {{ $json.status === \"active\" }}. Without {{ }} the text is evaluated as JSONata against the payload, where fields are referenced directly: age >= 18 or status = \"active\". $json is not bound in JSONata, so $json.age >= 18 without {{ }} always evaluates to false.",
        "format": "expression"
      },
      "treat_missing_as": {
        "type": "boolean",
        "title": "Treat Missing as False",
        "description": "If enabled, undefined or null results from the expression will automatically route to the False port instead of throwing an error.",
        "default": false
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "description": "The JSON payload to be evaluated by the expression.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "The original payload is passed through to the selected output port.",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "true",
      "label": "True",
      "is_default": true,
      "supports_condition": true,
      "description": "Active when expression is true."
    },
    {
      "port_id": "false",
      "label": "False",
      "supports_condition": true,
      "description": "Active when expression is false."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Active when expression evaluation fails."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "logic",
    "condition",
    "branch",
    "control-flow"
  ],
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "expr"
  ],
  "properties": {
    "expr": {
      "type": "string",
      "title": "Condition Expression",
      "description": "An expression that must evaluate to a boolean. Wrap it in {{ }} to use the Sommatic AI Expression Engine (JavaScript) with variables like $json, $input or $(\"Node Name\"), e.g. {{ $json.age >= 18 }} or {{ $json.status === \"active\" }}. Without {{ }} the text is evaluated as JSONata against the payload, where fields are referenced directly: age >= 18 or status = \"active\". $json is not bound in JSONata, so $json.age >= 18 without {{ }} always evaluates to false.",
      "format": "expression"
    },
    "treat_missing_as": {
      "type": "boolean",
      "title": "Treat Missing as False",
      "description": "If enabled, undefined or null results from the expression will automatically route to the False port instead of throwing an error.",
      "default": false
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "description": "The JSON payload to be evaluated by the expression.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "The original payload is passed through to the selected output port.",
  "properties": {
    "payload": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "true",
    "label": "True",
    "is_default": true,
    "supports_condition": true,
    "description": "Active when expression is true."
  },
  {
    "port_id": "false",
    "label": "False",
    "supports_condition": true,
    "description": "Active when expression is false."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Active when expression evaluation fails."
  }
]
```
