# Switch (Route)

> Dirige el flujo de ejecución hacia uno de varios puertos según una condición de coincidencia.

Source: https://docs.sommatic.ai/es/nodes/flow.switch/

- Slug: `flow.switch`
- Familia: Control de flujo
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: sync

Dirige el flujo de ejecución hacia uno de varios puertos según una condición de coincidencia.

Este operador funciona de forma parecida a un switch-case o a una cadena de if-else-if. Evalúa en orden una lista de 'cases' definidos. El primer caso cuya expresión resulte verdadera activa su puerto de salida correspondiente. Si ningún caso coincide, la ejecución se dirige al puerto 'default'.

**Comportamiento:**
- **Evaluación secuencial:** Los casos se revisan en el orden en que se definieron.
- **Primera coincidencia:** De forma predeterminada, se detiene en la primera condición verdadera.
- **Camino predeterminado:** Si no se cumple ninguna condición, se activa el puerto 'default'.

**Casos de uso:**
- Enrutar pedidos según su estado (p. ej., 'pending' -> puerto A, 'shipped' -> puerto B).
- Clasificar tickets de soporte por prioridad.
- Manejar distintos tipos de evento en un webhook.

## Configuración

- `cases` (array<object>, obligatorio): Define las condiciones y sus puertos de salida correspondientes.
- `first_match` (boolean, opcional): Si está activado, solo se activa el primer puerto que coincida. Si está desactivado, se activan todos los puertos que coincidan (multicast). Por defecto: `true`.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `default` (por defecto): Se activa cuando ningún caso coincide.
- `error`: Se activa si ocurre un error de evaluación.

## Contrato de entrada

- `payload` (object, obligatorio)

## Contrato de salida

- `payload` (object, opcional)

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Switch (Route)").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Switch (Route)`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `default`, según la salida que muestra Puertos.

- `$("Switch (Route)").item.json.payload` (object) **El worker no la devuelve: se lee como undefined.**
- `$("Switch (Route)").item.json.order_id` (string) = `"ord_125"` (El editor no la sugiere)
- `$("Switch (Route)").item.json.amount` (number) = `40` (El editor no la sugiere)
- `$("Switch (Route)").item.json.status` (string) = `"active"` (El editor no la sugiere)


## Cómo funciona

Evalúa los casos de enrutamiento en orden y envía el payload sin cambios por el puerto del primer caso que coincide, o por `default`.

1. Resuelve la configuración: el Expression Engine evalúa los `{{ }}` del `expr` de cada caso.
2. Si `cases` no es un arreglo, el payload va a `default`.
3. Omite un caso cuyo `port` está vacío o cuyo `expr` resuelto es falsy (`false`, `0`, `""`, `undefined`).
4. Un `expr` booleano se usa tal cual; cualquier otro valor se evalúa como JSONata sobre el payload (`amount > 1000`).
5. Reúne el puerto de cada caso verdadero y se detiene en el primero cuando `first_match` es true (por defecto).
6. Envía el payload por el primer puerto coincidente con `meta.matched` listando las coincidencias, o por `default` si ninguno coincidió.

## En un workflow

### Nodo

```json
{
  "node_id": "node-route-order",
  "label": "Route order",
  "operator_slug": "flow.switch",
  "operator_version": "1.0.0",
  "config": {
    "cases": [
      {
        "expr": "{{ $json.amount > 1000 }}",
        "port": "high_value"
      },
      {
        "expr": "status = \"on_hold\"",
        "port": "on_hold"
      }
    ],
    "first_match": true
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "order_id": "ord_123",
    "amount": 1250,
    "status": "active"
  },
  "port": "high_value",
  "meta": {
    "matched": [
      "high_value"
    ]
  }
}
```

## Puertos de salida (comportamiento en el código)

### `default`

Ningún caso coincidió, o `cases` no es un arreglo. Un caso que coincide envía el mismo payload por el puerto que nombra.

```json
{
  "order_id": "ord_125",
  "amount": 40,
  "status": "active"
}
```

### `error`

Un caso no se pudo compilar o evaluar como JSONata.

```json
{
  "ok": false,
  "errors": [
    "Switch evaluation error: <JSONata message>"
  ],
  "port": "error"
}
```

## Comportamiento en el código

- `cases`: Cada caso es `{ expr, port }`. El puerto del caso es un nombre libre (`^[a-z0-9_-]+$`) que debe coincidir con el `from.port` de una arista; un puerto coincidente sin arista termina la rama. El ejemplo de la definición `$json.amount > 1000` sin `{{ }}` nunca coincide, porque `$json` no está disponible en JSONata: escribe `amount > 1000` o `{{ $json.amount > 1000 }}`.
- `first_match`: Con false se evalúan todos los casos y se listan en `meta.matched`, pero solo se activa el primer puerto coincidente: no hay multidifusión.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Switch evaluation error: <JSONata message>` | `error` | Un `expr` de caso es JSONata no válido. Con `first_match` en true no se evalúan los casos posteriores a una coincidencia. |
| `Switch evaluation error: path.charAt is not a function` | `error` | Un `{{ }}` de caso devolvió un número distinto de cero, un objeto o un arreglo. Devuelve un booleano. |

## Notas y límites

- Una arista cuyo `from.port` es `*` recibe el payload sea cual sea el puerto activado.
- `meta` solo queda en los pasos de la ejecución: los nodos siguientes reciben `data` como payload y no pueden leer `meta` con `$json` ni con `$("Node")`.
- Cuando el sobre no trae `data` (o `data` es falsy), el motor guarda el sobre completo como salida del nodo: por `error` el siguiente nodo recibe `{ ok: false, errors: [...], port: "error" }` como payload.


## Contratos (JSON Schema)

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

```json
{
  "slug": "flow.switch",
  "name": "Switch (Route)",
  "category": "flow",
  "version": "1.0.0",
  "description": "Routes the execution flow to one of multiple ports based on a matching condition.\n\n  This operator functions similarly to a switch-case or if-else-if ladder. It evaluates a list of defined 'cases' in order. The first case whose expression evaluates to true triggers its corresponding output port. If no cases match, execution is routed to the 'default' port.\n\n  **Behavior:**\n  - **Sequential Evaluation:** Cases are checked in the order defined.\n  - **First Match:** By default, stops after the first true condition.\n  - **Default Path:** If no conditions are met, the 'default' port is activated.\n\n  **Use Cases:**\n  - Routing orders based on status (e.g., 'pending' -> Port A, 'shipped' -> Port B).\n  - Categorizing support tickets by priority.\n  - Handling different event types in a webhook.",
  "capabilities": [
    "branching",
    "logic",
    "jsonata",
    "router"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "cases"
    ],
    "properties": {
      "cases": {
        "type": "array",
        "title": "Routing Cases",
        "description": "Define the conditions and their corresponding output ports.",
        "items": {
          "type": "object",
          "properties": {
            "expr": {
              "type": "string",
              "title": "Condition Expression",
              "format": "expression",
              "description": "Expression that must evaluate to true. Use the Expression Editor for JavaScript with full variable access, or enter raw JSONata without {{ }} (see jsonata.org). Example: $json.amount > 1000"
            },
            "port": {
              "type": "string",
              "title": "Output Port Name",
              "description": "The name of the port to signal if this case matches (e.g., \"high_value\").",
              "pattern": "^[a-z0-9_-]+$"
            }
          },
          "required": [
            "expr",
            "port"
          ]
        }
      },
      "first_match": {
        "type": "boolean",
        "title": "Stop on First Match",
        "default": true,
        "description": "If enabled, only the first matching port is activated. If disabled, all matching ports are activated (multicast)."
      },
      "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 against the switch cases.",
    "properties": {
      "payload": {
        "type": "object"
      }
    },
    "required": [
      "payload"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "description": "The original payload is passed through to the matched output port(s).",
    "properties": {
      "payload": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "default",
      "label": "Default",
      "is_default": true,
      "description": "Activated when no cases match."
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Activated if an evaluation error occurs."
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "logic",
    "router",
    "multi-path",
    "conditional"
  ],
  "is_stateful": false,
  "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": [
    "cases"
  ],
  "properties": {
    "cases": {
      "type": "array",
      "title": "Routing Cases",
      "description": "Define the conditions and their corresponding output ports.",
      "items": {
        "type": "object",
        "properties": {
          "expr": {
            "type": "string",
            "title": "Condition Expression",
            "format": "expression",
            "description": "Expression that must evaluate to true. Use the Expression Editor for JavaScript with full variable access, or enter raw JSONata without {{ }} (see jsonata.org). Example: $json.amount > 1000"
          },
          "port": {
            "type": "string",
            "title": "Output Port Name",
            "description": "The name of the port to signal if this case matches (e.g., \"high_value\").",
            "pattern": "^[a-z0-9_-]+$"
          }
        },
        "required": [
          "expr",
          "port"
        ]
      }
    },
    "first_match": {
      "type": "boolean",
      "title": "Stop on First Match",
      "default": true,
      "description": "If enabled, only the first matching port is activated. If disabled, all matching ports are activated (multicast)."
    },
    "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 against the switch cases.",
  "properties": {
    "payload": {
      "type": "object"
    }
  },
  "required": [
    "payload"
  ]
}
```

### output_contract_schema

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

### ports

```json
[
  {
    "port_id": "default",
    "label": "Default",
    "is_default": true,
    "description": "Activated when no cases match."
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Activated if an evaluation error occurs."
  }
]
```
