{
  "version": 16,
  "name": "24_websocket",
  "description": "Example: WebSocket (Protocols → Add WebSocket, request ws). A WebSocket step opens the connection, waits for the server's greeting before sending, stops after a number of messages, at a stop text or after a time (not an error), and checks the messages it received with JSON paths ($.length, $[1].data.type). A code block keeps a connection open with websocket(): send(), next() with a match and a time limit, close(); http() with ws does one exchange. Then the REST-then-event pattern: a WebSocket step keeps a connection open as \"notifications\" (Keep open as), a REST call publishes, and a Wait for Message step waits for the event, checks it and extracts its id.\nAPIs: echo.websocket.org (greets with \"Request served by …\", then sends back every message); ntfy.sh (open-source notifications: publish with a POST, subscribe with a WebSocket; a fresh topic per run).",
  "tags": [
    "example",
    "websocket"
  ],
  "globals": [
    {
      "name": "$echoWs",
      "value": "wss://echo.websocket.org"
    },
    {
      "name": "$user",
      "value": "ann"
    },
    {
      "name": "$ntfyTopic",
      "value": ""
    },
    {
      "name": "$orderNo",
      "value": "A-17"
    },
    {
      "name": "$eventId",
      "value": ""
    }
  ],
  "globalFunctions": "// Assertion helpers, built on check(label, pass, details).\n// Each records a pass / fail line in the log and the report.\n// A failed one fails its step when the step is done;\n// the code keeps running. Change them or add your own.\n// r defaults to the last response.\n\nfunction assertTrue(value, label = \"is true\") {\n  return check(label, Boolean(value), { actual: value, expected: true });\n}\n\nfunction assertEqual(actual, expected, label = \"equals \" + JSON.stringify(expected)) {\n  return check(label, isEqual(actual, expected), { actual, expected });\n}\n\nfunction assertNotEqual(actual, unexpected, label = \"does not equal \" + JSON.stringify(unexpected)) {\n  return check(label, !isEqual(actual, unexpected), { actual, expected: \"not \" + JSON.stringify(unexpected) });\n}\n\n// text contains a part, or a list contains an item\nfunction assertContains(haystack, needle, label = \"contains \" + JSON.stringify(needle)) {\n  const pass = Array.isArray(haystack) ? haystack.some((x) => isEqual(x, needle)) : String(haystack).includes(needle);\n  return check(label, pass, { actual: haystack, expected: needle });\n}\n\nfunction assertMatch(text, regex, label = \"matches \" + regex) {\n  return check(label, new RegExp(regex).test(String(text)), { actual: text, expected: String(regex) });\n}\n\nfunction assertLessThan(actual, limit, label = \"< \" + limit) {\n  return check(label, Number(actual) < Number(limit), { actual, expected: \"< \" + limit });\n}\n\nfunction assertGreaterThan(actual, limit, label = \"> \" + limit) {\n  return check(label, Number(actual) > Number(limit), { actual, expected: \"> \" + limit });\n}\n\n// expected: 200, \"2xx\", or a list such as [200, 201]\nfunction assertStatus(expected, r = response) {\n  const list = [].concat(expected).map(String);\n  const status = String(r && r.status);\n  const pass = list.some((e) => e === status || (/^[1-5]xx$/i.test(e) && e[0] === status[0]));\n  return check(\"status is \" + list.join(\" or \"), pass, { actual: r && r.status, expected });\n}\n\nfunction assertTimeBelow(ms, r = response) {\n  return check(\"time < \" + ms + \" ms\", Boolean(r) && r.timeMs < ms, { actual: r && r.timeMs, expected: \"< \" + ms });\n}\n\n// without expected, the header only has to exist\nfunction assertHeader(name, expected, r = response) {\n  const value = r ? r.headers[String(name).toLowerCase()] : undefined;\n  if (expected === undefined) return check(\"header \" + name + \" exists\", value !== undefined, { actual: value });\n  return check(\"header \" + name + \" equals \" + expected, String(value) === String(expected), { actual: value, expected });\n}\n\n// e.g. assertJsonPath(\"$.items[0].id\", 42); without expected, the value only has to exist\nfunction assertJsonPath(path, expected, r = response) {\n  const value = jsonPath(path, r);\n  if (expected === undefined) return check(path + \" exists\", value !== undefined, { actual: value });\n  return check(path + \" equals \" + JSON.stringify(expected), isEqual(value, expected), { actual: value, expected });\n}\n\n// schema: a JSON Schema object\nfunction assertSchema(schema, r = response) {\n  const result = validateSchema(r, schema);\n  return check(\"matches the JSON Schema\", result.valid, { error: result.errors || undefined });\n}\n",
  "libraries": [],
  "activeEnvironment": "",
  "auth": {
    "type": "none"
  },
  "settings": {},
  "data": {
    "file": ""
  },
  "cookies": [],
  "steps": [
    {
      "id": "roundtrip",
      "type": "request",
      "name": "Echo round trip",
      "conditional": "true",
      "method": "GET",
      "url": "$echoWs",
      "params": [],
      "headers": [],
      "bodyMode": "raw",
      "body": "",
      "multipart": [],
      "bodyFile": {
        "path": "",
        "contentType": ""
      },
      "followRedirects": true,
      "httpVersion": "inherit",
      "auth": {
        "type": "inherit"
      },
      "extract": [],
      "checks": [
        {
          "enabled": true,
          "target": "status",
          "path": "",
          "op": "equals",
          "value": "101"
        },
        {
          "enabled": true,
          "target": "messages",
          "path": "$.length",
          "op": "equals",
          "value": "3"
        },
        {
          "enabled": true,
          "target": "messages",
          "path": "$[0].data",
          "op": "contains",
          "value": "Request served by"
        },
        {
          "enabled": true,
          "target": "messages",
          "path": "$[1].data.type",
          "op": "equals",
          "value": "hello"
        },
        {
          "enabled": true,
          "target": "messages",
          "path": "$[1].data.user",
          "op": "equals",
          "value": "$user"
        },
        {
          "enabled": true,
          "target": "messages",
          "path": "$[2].data",
          "op": "equals",
          "value": "ping"
        }
      ],
      "loop": {
        "enabled": false,
        "count": 5,
        "untilStatus": 200,
        "intervalMs": 1000
      },
      "saveResponse": {
        "enabled": false,
        "path": "",
        "onlyOk": true
      },
      "ws": {
        "enabled": true,
        "messages": [
          {
            "data": "{\"type\":\"hello\",\"user\":\"$user\"}",
            "waitFor": "Request served by"
          },
          {
            "data": "ping"
          }
        ],
        "maxMessages": 3,
        "until": "",
        "waitMs": 10000,
        "subprotocols": ""
      }
    },
    {
      "id": "until",
      "type": "request",
      "name": "Stop at a message",
      "conditional": "true",
      "method": "GET",
      "url": "$echoWs",
      "params": [],
      "headers": [],
      "bodyMode": "raw",
      "body": "",
      "multipart": [],
      "bodyFile": {
        "path": "",
        "contentType": ""
      },
      "followRedirects": true,
      "httpVersion": "inherit",
      "auth": {
        "type": "inherit"
      },
      "extract": [],
      "checks": [
        {
          "enabled": true,
          "target": "messages",
          "path": "$[-1].data",
          "op": "equals",
          "value": "done"
        },
        {
          "enabled": true,
          "target": "messages",
          "path": "$[*].data",
          "op": "contains",
          "value": "two"
        }
      ],
      "loop": {
        "enabled": false,
        "count": 5,
        "untilStatus": 200,
        "intervalMs": 1000
      },
      "saveResponse": {
        "enabled": false,
        "path": "",
        "onlyOk": true
      },
      "ws": {
        "enabled": true,
        "messages": [
          {
            "data": "one"
          },
          {
            "data": "two"
          },
          {
            "data": "done"
          }
        ],
        "maxMessages": 0,
        "until": "done",
        "waitMs": 10000,
        "subprotocols": ""
      }
    },
    {
      "id": "time",
      "type": "request",
      "name": "Listen for 1 second",
      "conditional": "true",
      "method": "GET",
      "url": "$echoWs",
      "params": [],
      "headers": [],
      "bodyMode": "raw",
      "body": "",
      "multipart": [],
      "bodyFile": {
        "path": "",
        "contentType": ""
      },
      "followRedirects": true,
      "httpVersion": "inherit",
      "auth": {
        "type": "inherit"
      },
      "extract": [],
      "checks": [
        {
          "enabled": true,
          "target": "messages",
          "path": "$.length",
          "op": "equals",
          "value": "2"
        },
        {
          "enabled": true,
          "target": "messages",
          "path": "$[1].data",
          "op": "equals",
          "value": "only this"
        }
      ],
      "loop": {
        "enabled": false,
        "count": 5,
        "untilStatus": 200,
        "intervalMs": 1000
      },
      "saveResponse": {
        "enabled": false,
        "path": "",
        "onlyOk": true
      },
      "ws": {
        "enabled": true,
        "messages": [
          {
            "data": "only this"
          }
        ],
        "maxMessages": 0,
        "until": "",
        "waitMs": 1000,
        "subprotocols": ""
      }
    },
    {
      "id": "code",
      "type": "code",
      "name": "Talk to it from code",
      "conditional": "true",
      "code": "// A connection that stays open while the code talks to it.\nconst ws = await websocket($echoWs);\nconst greeting = await ws.next();\nlog(\"greeting:\", greeting.data);\nfor (const n of [1, 2, 3]) {\n  await ws.send({ type: \"count\", n });\n  const echo = await ws.next((m) => m.data.type === \"count\", { timeoutMs: 5000 });\n  assertEqual(echo.data.n, n, \"echo of \" + n);\n}\nawait ws.close();\nlog(ws.messages.length + \" messages received\");\n\n// One exchange with http(): like a request step.\nconst r = await http({ url: $echoWs, ws: { enabled: true, messages: [{ data: \"hi\", waitFor: \"Request served by\" }], maxMessages: 2 } });\nassertEqual(r.status, 101, \"switched to WebSocket\");\nassertEqual(r.messages[1].data, \"hi\", \"echo of hi\");",
      "requests": []
    },
    {
      "id": "topic",
      "type": "code",
      "name": "A fresh topic for this run",
      "conditional": "true",
      "code": "$ntfyTopic = \"clem-example-\" + crypto.randomUUID().slice(0, 12);",
      "requests": []
    },
    {
      "id": "subscribe",
      "type": "request",
      "name": "Subscribe to the topic",
      "conditional": "true",
      "method": "GET",
      "url": "wss://ntfy.sh/$ntfyTopic/ws",
      "params": [],
      "headers": [],
      "bodyMode": "raw",
      "body": "",
      "multipart": [],
      "bodyFile": {
        "path": "",
        "contentType": ""
      },
      "followRedirects": true,
      "httpVersion": "inherit",
      "auth": {
        "type": "inherit"
      },
      "extract": [],
      "checks": [
        {
          "enabled": true,
          "target": "messages",
          "path": "$[0].data.event",
          "op": "equals",
          "value": "open"
        }
      ],
      "loop": {
        "enabled": false,
        "count": 5,
        "untilStatus": 200,
        "intervalMs": 1000
      },
      "saveResponse": {
        "enabled": false,
        "path": "",
        "onlyOk": true
      },
      "ws": {
        "enabled": true,
        "messages": [],
        "maxMessages": 0,
        "until": "\"event\":\"open\"",
        "waitMs": 10000,
        "subprotocols": "",
        "keepOpen": "notifications"
      }
    },
    {
      "id": "publish",
      "type": "request",
      "name": "Publish over REST",
      "conditional": "true",
      "method": "POST",
      "url": "https://ntfy.sh/$ntfyTopic",
      "params": [],
      "headers": [
        {
          "name": "Title",
          "value": "Order created"
        }
      ],
      "bodyMode": "raw",
      "body": "Order $orderNo was created",
      "multipart": [],
      "bodyFile": {
        "path": "",
        "contentType": ""
      },
      "followRedirects": true,
      "httpVersion": "inherit",
      "auth": {
        "type": "inherit"
      },
      "extract": [],
      "checks": [
        {
          "enabled": true,
          "target": "status",
          "path": "",
          "op": "equals",
          "value": "200"
        }
      ],
      "loop": {
        "enabled": false,
        "count": 5,
        "untilStatus": 200,
        "intervalMs": 1000
      },
      "saveResponse": {
        "enabled": false,
        "path": "",
        "onlyOk": true
      }
    },
    {
      "id": "event",
      "type": "wsWait",
      "name": "The notification arrives",
      "conditional": "true",
      "connection": "notifications",
      "send": "",
      "match": "Order $orderNo",
      "timeoutMs": 10000,
      "extract": [
        {
          "name": "$eventId",
          "before": "\"id\":\"",
          "after": "\"",
          "from": "Body",
          "ordinal": 1
        }
      ],
      "checks": [
        {
          "enabled": true,
          "target": "json",
          "path": "$.event",
          "op": "equals",
          "value": "message"
        },
        {
          "enabled": true,
          "target": "json",
          "path": "$.title",
          "op": "equals",
          "value": "Order created"
        },
        {
          "enabled": true,
          "target": "json",
          "path": "$.message",
          "op": "equals",
          "value": "Order $orderNo was created"
        },
        {
          "enabled": true,
          "target": "time",
          "path": "",
          "op": "lt",
          "value": "5000"
        }
      ]
    }
  ]
}
