-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdemo_cli.js
More file actions
169 lines (149 loc) · 4.76 KB
/
demo_cli.js
File metadata and controls
169 lines (149 loc) · 4.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import "./src/utils/load_env.js";
import axios from "axios";
import { EventSource } from "eventsource";
import {
DEMO_TARGET_ENV_VAR,
resolveDemoBaseUrl,
} from "./src/utils/demo_base_url.js";
/**
* 🚀 WEBHOOK DEBUGGER & LOGGER - LIVE DEMO
* ------------------------------------------
*
* This script demonstrates the real-time SSE streaming capabilities
* of your newly created Actor.
*/
const AUTH_KEY = process.env.AUTH_KEY || "";
const SECTION_DIVIDER = "------------------------------------------";
const API_CONTRACT_PATH = ".actor/web_server_schema.json";
const PRETTY_JSON_INDENT = 2;
const BODY_PREVIEW_LENGTH = 100;
const DEMO_STEP_DELAY_MS = {
jsonPayload: 1500,
formData: 3000,
forcedUnauthorized: 4500,
};
const BASE_URL = resolveDemoBaseUrl(process.env[DEMO_TARGET_ENV_VAR]);
/**
* Resolves the error message from an error object or string.
* @param {unknown} err - The error object or string.
* @returns {string} The resolved error message.
*/
function resolveErrorMessage(err) {
return err instanceof Error ||
(err && typeof err === "object" && "message" in err)
? err.message
: String(err);
}
/**
* @param {number} delayMs
* @param {string} label
* @param {() => Promise<void>} action
* @returns {void}
*/
function scheduleDemoStep(delayMs, label, action) {
setTimeout(() => {
void (async () => {
console.log(`[ACTION] ${label}...`);
try {
await action();
} catch (err) {
console.error(`[ACTION] ${label} failed: ${resolveErrorMessage(err)}`);
}
})();
}, delayMs);
}
async function runDemo() {
console.log("\n🚀 WEBHOOK DEBUGGER & LOGGER - LIVE DEMO");
console.log(SECTION_DIVIDER);
console.log(`[API] Contract: ${API_CONTRACT_PATH}`);
console.log("[API] Validate: npm run validate:web-server-schema");
console.log(
`[DEMO] Base URL: ${BASE_URL} (${DEMO_TARGET_ENV_VAR}=localhost|ipv4|ipv6)`,
);
console.log(SECTION_DIVIDER);
try {
const headers = {};
if (AUTH_KEY) {
headers["Authorization"] = `Bearer ${AUTH_KEY}`;
console.log(`[AUTH] Using provided AUTH_KEY...`);
}
// 1. Get active webhooks
const infoRes = await axios.get(`${BASE_URL}/info`, { headers });
const active = infoRes.data.system?.activeWebhooks || [];
if (active.length === 0) {
console.log("[ERROR] No active webhooks found. Is the Actor running?");
return;
}
const targetId = active[0].id;
console.log(`[URLS] Generated: ${active.map((a) => a.id).join(", ")}`);
console.log(`[URLS] Using for demo: ${targetId}`);
if (infoRes.data.system?.authActive) {
console.log(
"[WARN] Authentication is ENABLED. This demo might return 401s if not configured with the key.",
);
}
console.log("");
// 2. Connect to SSE Stream
console.log("[STREAM] Connecting to Live Stream...");
const streamOptions = AUTH_KEY
? { headers: { Authorization: `Bearer ${AUTH_KEY}` } }
: {};
const es = new EventSource(`${BASE_URL}/log-stream`, streamOptions);
es.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("\n[EVENT RECEIVED]");
console.log(`- Method: ${data.method}`);
console.log(`- Status: ${data.statusCode}`);
console.log(`- Path: /webhook/${data.webhookId}`);
console.log(
`- Body: ${JSON.stringify(data.body, null, PRETTY_JSON_INDENT).substring(0, BODY_PREVIEW_LENGTH)}...`,
);
console.log(SECTION_DIVIDER);
};
es.onerror = (err) => {
console.error("[STREAM] Connection error:", resolveErrorMessage(err));
};
// 3. Send test requests
scheduleDemoStep(
DEMO_STEP_DELAY_MS.jsonPayload,
"Sending JSON payload",
async () => {
await axios.post(
`${BASE_URL}/webhook/${targetId}`,
{
hello: "Apify World!",
},
{ headers },
);
},
);
scheduleDemoStep(
DEMO_STEP_DELAY_MS.formData,
"Sending Form Data",
async () => {
const params = new URLSearchParams();
params.append("user", "tester");
params.append("action", "login");
await axios.post(`${BASE_URL}/webhook/${targetId}`, params, {
headers,
});
},
);
scheduleDemoStep(
DEMO_STEP_DELAY_MS.forcedUnauthorized,
"Forcing 401 Unauthorized (via __status parameter)",
async () => {
await axios
.get(`${BASE_URL}/webhook/${targetId}?__status=401`, { headers })
.catch(() => {});
console.log("\n✨ Demo complete. Press Ctrl+C to exit.");
},
);
} catch (err) {
console.error(`[ERROR] Setup failed: ${resolveErrorMessage(err)}`);
console.log(
"👉 Make sure the Actor is running locally on port 8080 (npm start).",
);
}
}
runDemo();