-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_api_markdown.js
More file actions
534 lines (457 loc) · 17.1 KB
/
test_api_markdown.js
File metadata and controls
534 lines (457 loc) · 17.1 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
#!/usr/bin/env node
/**
* Test script for Gnosis Wraith /api/markdown endpoint
* Tests both single URL and batch URL processing
* Node.js equivalent of test_api_markdown.py
*/
const https = require('https');
const http = require('http');
// Configuration
const REMOTE_SERVER = "https://wraith.nuts.services";
// const REMOTE_SERVER = "http://localhost:5678";
const API_KEY = "Ij8zhKKL_iKUcumU5oQKnpsECg9qvYTdXlH2IGth7k_ewGBdy6se_g"; // Your API key
// const API_KEY = "pfr3lKBeacc4W5ZiOA6jFYRFvywhd4_MoHg8MkFmeesSvdmPMNheA";
// Test URLs
const TEST_URLS = [
"https://example.com",
"https://www.wikipedia.org",
"https://news.ycombinator.com",
"https://www.python.org",
"https://docs.python.org/3/"
];
/**
* Make HTTP request helper
*/
function makeRequest(url, options, payload) {
return new Promise((resolve, reject) => {
const urlObj = new URL(url);
const protocol = urlObj.protocol === 'https:' ? https : http;
const reqOptions = {
hostname: urlObj.hostname,
port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
path: urlObj.pathname + urlObj.search,
method: options.method || 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`,
...options.headers
}
};
const req = protocol.request(reqOptions, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
const jsonData = JSON.parse(data);
resolve({ status: res.statusCode, data: jsonData });
} catch (e) {
resolve({ status: res.statusCode, data: data });
}
});
});
req.on('error', reject);
if (payload) {
req.write(JSON.stringify(payload));
}
req.end();
});
}
/**
* Test single URL markdown extraction (backward compatible)
*/
async function testSingleUrlMarkdown() {
console.log("\n=== Testing Single URL Markdown ===");
const payload = {
url: TEST_URLS[0],
javascript_enabled: true,
screenshot_mode: null // No screenshot for speed
};
try {
const startTime = Date.now();
const response = await makeRequest(
`${REMOTE_SERVER}/api/markdown`,
{ method: 'POST' },
payload
);
const elapsed = (Date.now() - startTime) / 1000;
console.log(`URL: ${TEST_URLS[0]}`);
console.log(`Status: ${response.status}`);
console.log(`Time: ${elapsed.toFixed(2)}s`);
if (response.status === 200) {
const data = response.data;
console.log("✅ Success");
console.log(`Response keys: ${Object.keys(data).join(', ')}`);
// Check various response fields
if ('success' in data) {
console.log(`Success: ${data.success}`);
}
if ('url' in data) {
console.log(`URL: ${data.url}`);
}
if ('markdown_url' in data) {
console.log(`Markdown URL: ${data.markdown_url}`);
}
if ('json_url' in data) {
console.log(`JSON URL: ${data.json_url}`);
}
if ('stats' in data) {
console.log(`Stats:`, data.stats);
}
} else {
console.log(`❌ Error:`, response.data);
}
return response.status === 200;
} catch (error) {
console.log(`❌ Exception: ${error.message}`);
return false;
}
}
/**
* Test synchronous batch processing
*/
async function testBatchSync() {
console.log("\n=== Testing Batch Markdown (Sync) ===");
const payload = {
urls: TEST_URLS.slice(0, 3), // Test with 3 URLs
async: false, // Wait for completion
javascript_enabled: true,
screenshot_mode: null
};
try {
const startTime = Date.now();
const response = await makeRequest(
`${REMOTE_SERVER}/api/markdown`,
{ method: 'POST' },
payload
);
const elapsed = (Date.now() - startTime) / 1000;
console.log(`URLs: ${payload.urls.length} URLs`);
console.log(`Status: ${response.status}`);
console.log(`Time: ${elapsed.toFixed(2)}s`);
if (response.status === 200) {
const data = response.data;
console.log("✅ Success");
console.log(`Mode: ${data.mode || 'N/A'}`);
console.log(`Job ID: ${data.job_id || 'N/A'}`);
if ('results' in data) {
console.log(`\nResults: ${data.results.length} items`);
data.results.slice(0, 2).forEach((result, i) => {
console.log(`\nResult ${i + 1}:`);
console.log(` URL: ${result.url || 'N/A'}`);
console.log(` Status: ${result.status || 'N/A'}`);
console.log(` Markdown URL: ${result.markdown_url || 'N/A'}`);
console.log(` JSON URL: ${result.json_url || 'N/A'}`);
});
}
} else {
console.log(`❌ Error:`, response.data);
}
return response.status === 200;
} catch (error) {
console.log(`❌ Exception: ${error.message}`);
return false;
}
}
/**
* Test asynchronous batch processing
*/
async function testBatchAsync() {
console.log("\n=== Testing Batch Markdown (Async) ===");
const payload = {
urls: TEST_URLS.slice(0, 4), // Test with 4 URLs
async: true, // Don't wait for completion
javascript_enabled: false, // Faster without JS
screenshot_mode: null
};
try {
const startTime = Date.now();
const response = await makeRequest(
`${REMOTE_SERVER}/api/markdown`,
{ method: 'POST' },
payload
);
const elapsed = (Date.now() - startTime) / 1000;
console.log(`URLs: ${payload.urls.length} URLs`);
console.log(`Status: ${response.status}`);
console.log(`Time: ${elapsed.toFixed(2)}s (should be fast for async)`);
if ([200, 202].includes(response.status)) { // 202 Accepted for async
const data = response.data;
console.log(`✅ Success (Status: ${response.status})`);
console.log(`Mode: ${data.mode || 'N/A'}`);
console.log(`Job ID: ${data.job_id || 'N/A'}`);
console.log(`Status URL: ${data.status_url || 'N/A'}`);
if ('results' in data) {
console.log(`\nPredicted URLs: ${data.results.length} items`);
data.results.slice(0, 2).forEach((result, i) => {
console.log(` ${i + 1}. ${result.url || 'N/A'} - Status: ${result.status || 'N/A'}`);
});
}
} else {
console.log(`❌ Error:`, response.data);
}
return [200, 202].includes(response.status);
} catch (error) {
console.log(`❌ Exception: ${error.message}`);
return false;
}
}
/**
* Test batch processing with collation
*/
async function testBatchWithCollation() {
console.log("\n=== Testing Batch with Collation ===");
const payload = {
urls: [
"https://docs.python.org/3/tutorial/introduction.html",
"https://docs.python.org/3/tutorial/controlflow.html"
],
async: false, // Wait for completion to get collated result
collate: true,
collate_options: {
title: "Python Tutorial Collection",
add_toc: true,
add_source_headers: true
},
javascript_enabled: false
};
try {
const startTime = Date.now();
const response = await makeRequest(
`${REMOTE_SERVER}/api/markdown`,
{ method: 'POST' },
payload
);
const elapsed = (Date.now() - startTime) / 1000;
console.log(`URLs: ${payload.urls.length} URLs`);
console.log(`Status: ${response.status}`);
console.log(`Time: ${elapsed.toFixed(2)}s`);
if (response.status === 200) {
const data = response.data;
console.log("✅ Success");
if ('collated_url' in data) {
console.log(`Collated file URL: ${data.collated_url}`);
}
if ('results' in data) {
console.log(`Individual results: ${data.results.length}`);
}
} else {
console.log(`❌ Error:`, response.data);
}
return response.status === 200;
} catch (error) {
console.log(`❌ Exception: ${error.message}`);
return false;
}
}
/**
* Test markdown extraction with content filters
*/
async function testWithFilters() {
console.log("\n=== Testing with Content Filters ===");
try {
// Test with pruning filter
console.log("Testing Pruning Filter...");
let payload = {
url: "https://en.wikipedia.org/wiki/Python_(programming_language)",
filter: "pruning",
filter_options: {
threshold: 0.5,
min_words: 3
},
javascript_enabled: false
};
let startTime = Date.now();
let response = await makeRequest(
`${REMOTE_SERVER}/api/markdown`,
{ method: 'POST' },
payload
);
let elapsed = (Date.now() - startTime) / 1000;
if (response.status === 200) {
const data = response.data;
console.log(` ✅ Pruning filter success (Time: ${elapsed.toFixed(2)}s)`);
if ('stats' in data) {
console.log(` Stats:`, data.stats);
}
} else {
console.log(` ❌ Pruning filter failed: Status ${response.status}`);
}
// Test with BM25 filter
console.log("\nTesting BM25 Filter...");
payload = {
url: "https://en.wikipedia.org/wiki/Python_(programming_language)",
filter: "bm25",
filter_options: {
query: "python programming syntax",
threshold: 0.4
},
javascript_enabled: false
};
startTime = Date.now();
response = await makeRequest(
`${REMOTE_SERVER}/api/markdown`,
{ method: 'POST' },
payload
);
elapsed = (Date.now() - startTime) / 1000;
if (response.status === 200) {
const data = response.data;
console.log(` ✅ BM25 filter success (Time: ${elapsed.toFixed(2)}s)`);
if ('stats' in data) {
console.log(` Stats:`, data.stats);
}
} else {
console.log(` ❌ BM25 filter failed: Status ${response.status}`);
}
return true;
} catch (error) {
console.log(`❌ Exception: ${error.message}`);
return false;
}
}
/**
* Test error handling with invalid URLs
*/
async function testErrorHandling() {
console.log("\n=== Testing Error Handling ===");
try {
// Test invalid URL
console.log("Testing invalid URL...");
let response = await makeRequest(
`${REMOTE_SERVER}/api/markdown`,
{ method: 'POST' },
{ url: "not-a-valid-url" }
);
console.log(` Status: ${response.status}`);
console.log(` Response:`, response.data);
// Test missing URL
console.log("\nTesting missing URL...");
response = await makeRequest(
`${REMOTE_SERVER}/api/markdown`,
{ method: 'POST' },
{}
);
console.log(` Status: ${response.status}`);
console.log(` Response:`, response.data);
// Test too many URLs
console.log("\nTesting too many URLs...");
response = await makeRequest(
`${REMOTE_SERVER}/api/markdown`,
{ method: 'POST' },
{ urls: Array(51).fill("https://example.com") } // Over 50 limit
);
console.log(` Status: ${response.status}`);
console.log(` Response:`, response.data);
return true;
} catch (error) {
console.log(`❌ Exception: ${error.message}`);
return false;
}
}
/**
* Test minimal response format
*/
async function testMinimalResponseFormat() {
console.log("\n=== Testing Minimal Response Format ===");
const payload = {
url: "https://example.com",
javascript_enabled: false, // Faster without JS
screenshot_mode: null,
response_format: "minimal" // Request minimal format
};
try {
const startTime = Date.now();
const response = await makeRequest(
`${REMOTE_SERVER}/api/markdown`,
{ method: 'POST' },
payload
);
const elapsed = (Date.now() - startTime) / 1000;
console.log(`URL: ${payload.url}`);
console.log(`Response Format: ${payload.response_format}`);
console.log(`Status: ${response.status}`);
console.log(`Time: ${elapsed.toFixed(2)}s`);
if (response.status === 200) {
const data = response.data;
console.log("✅ Success");
console.log(`Response keys: ${Object.keys(data).join(', ')}`);
// Output the content
console.log("\n--- CONTENT OUTPUT ---");
if ('content' in data) {
console.log("Content field:");
console.log(data.content ? data.content.substring(0, 500) + '...' : 'No content');
}
if ('markdown' in data) {
console.log("\nMarkdown field:");
console.log(data.markdown ? data.markdown.substring(0, 500) + '...' : 'No markdown');
}
console.log("--- END CONTENT ---\n");
// Check what fields are included in minimal format
console.log("\nFields included:");
const fields = ['success', 'url', 'title', 'content', 'markdown', 'markdown_url', 'json_url', 'stats', 'html_content', 'extracted_text'];
fields.forEach(field => {
if (field in data) {
console.log(` ✓ ${field}: ${typeof data[field] === 'string' && data[field].length > 50 ? data[field].substring(0, 50) + '...' : JSON.stringify(data[field])}`);
} else {
console.log(` ✗ ${field}: not included`);
}
});
} else {
console.log(`❌ Error:`, response.data);
}
return response.status === 200;
} catch (error) {
console.log(`❌ Exception: ${error.message}`);
return false;
}
}
/**
* Main test runner
*/
async function main() {
console.log("=".repeat(60));
console.log("Gnosis Wraith /api/markdown Endpoint Tests");
console.log(`Server: ${REMOTE_SERVER}`);
console.log(`API Key: ${API_KEY.substring(0, 10)}...`);
console.log("=".repeat(60));
// Run tests
const tests = [
{ name: "Minimal Response Format", func: testMinimalResponseFormat }, // Run this first
{ name: "Single URL", func: testSingleUrlMarkdown },
{ name: "Batch Sync", func: testBatchSync },
{ name: "Batch Async", func: testBatchAsync },
{ name: "Batch with Collation", func: testBatchWithCollation },
{ name: "Content Filters", func: testWithFilters },
{ name: "Error Handling", func: testErrorHandling }
];
const results = [];
for (const test of tests) {
try {
const result = await test.func();
results.push({ name: test.name, passed: result });
} catch (error) {
console.log(`\n❌ Test '${test.name}' crashed: ${error.message}`);
results.push({ name: test.name, passed: false });
}
}
// Summary
console.log("\n" + "=".repeat(60));
console.log("Test Summary");
console.log("=".repeat(60));
const passed = results.filter(r => r.passed).length;
const total = results.length;
results.forEach(result => {
const status = result.passed ? "✅ PASSED" : "❌ FAILED";
console.log(`${result.name}: ${status}`);
});
console.log(`\nTotal: ${passed}/${total} tests passed`);
console.log("\n📝 Implementation Notes:");
console.log("- The /api/markdown endpoint supports both single and batch URLs");
console.log("- Batch mode is triggered by providing 'urls' array instead of 'url'");
console.log("- Maximum 50 URLs per batch");
console.log("- Supports async processing with webhooks");
console.log("- Supports content filters (pruning, BM25)");
console.log("- Supports collation to merge results");
}
// Run the tests
main().catch(console.error);