-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathscrapegraphai.test.ts
More file actions
1111 lines (929 loc) · 31 KB
/
scrapegraphai.test.ts
File metadata and controls
1111 lines (929 loc) · 31 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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { afterEach, describe, expect, spyOn, test } from "bun:test";
import * as sdk from "../src/scrapegraphai.js";
const API_KEY = "test-sgai-key";
const BASE = process.env.SGAI_API_URL || "https://v2-api.scrapegraphai.com/api";
function json(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
});
}
let fetchSpy: ReturnType<typeof spyOn<typeof globalThis, "fetch">>;
afterEach(() => {
fetchSpy?.mockRestore();
});
function expectRequest(
callIndex: number,
method: string,
path: string,
body?: object,
base = BASE,
) {
const [url, init] = fetchSpy.mock.calls[callIndex] as [string, RequestInit];
expect(url).toBe(`${base}${path}`);
expect(init.method).toBe(method);
expect((init.headers as Record<string, string>)["SGAI-APIKEY"]).toBe(API_KEY);
if (body) {
expect((init.headers as Record<string, string>)["Content-Type"]).toBe("application/json");
expect(JSON.parse(init.body as string)).toEqual(body);
}
}
describe("scrape", () => {
const params = { url: "https://example.com" };
test("success", async () => {
const body = {
results: { markdown: { data: ["# Hello"] } },
metadata: { contentType: "text/html" },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const res = await sdk.scrape(API_KEY, params);
expect(res.status).toBe("success");
expect(res.data).toEqual(body);
expect(res.elapsedMs).toBeGreaterThanOrEqual(0);
expectRequest(0, "POST", "/scrape", params);
});
test("with fetchConfig - js mode and stealth", async () => {
const body = {
results: { markdown: { data: ["# Hello"] } },
metadata: { contentType: "text/html", provider: "playwright" },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const paramsWithConfig = {
url: "https://example.com",
fetchConfig: {
mode: "js" as const,
stealth: true,
timeout: 45000,
wait: 2000,
scrolls: 3,
},
formats: [{ type: "markdown" as const }],
};
const res = await sdk.scrape(API_KEY, paramsWithConfig);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/scrape", paramsWithConfig);
});
test("with fetchConfig - headers and cookies", async () => {
const body = {
results: { html: { data: ["<html></html>"] } },
metadata: { contentType: "text/html" },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const paramsWithConfig = {
url: "https://example.com",
fetchConfig: {
mode: "fast" as const,
headers: { "X-Custom-Header": "test-value", Authorization: "Bearer token123" },
cookies: { session: "abc123", tracking: "xyz789" },
},
formats: [{ type: "html" as const }],
};
const res = await sdk.scrape(API_KEY, paramsWithConfig);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/scrape", paramsWithConfig);
});
test("with fetchConfig - country geo targeting", async () => {
const body = {
results: { markdown: { data: ["# Localized content"] } },
metadata: { contentType: "text/html" },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const paramsWithConfig = {
url: "https://example.com",
fetchConfig: { country: "de" },
formats: [{ type: "markdown" as const }],
};
const res = await sdk.scrape(API_KEY, paramsWithConfig);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/scrape", paramsWithConfig);
});
test("multiple formats - markdown, html, links, images", async () => {
const body = {
results: {
markdown: { data: ["# Title"] },
html: { data: ["<h1>Title</h1>"] },
links: { data: ["https://example.com/page1"], metadata: { count: 1 } },
images: { data: ["https://example.com/image.png"], metadata: { count: 1 } },
},
metadata: { contentType: "text/html" },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const multiFormatParams = {
url: "https://example.com",
formats: [
{ type: "markdown" as const, mode: "reader" as const },
{ type: "html" as const, mode: "prune" as const },
{ type: "links" as const },
{ type: "images" as const },
],
};
const res = await sdk.scrape(API_KEY, multiFormatParams);
expect(res.status).toBe("success");
expect(res.data?.results.markdown).toBeDefined();
expect(res.data?.results.html).toBeDefined();
expect(res.data?.results.links).toBeDefined();
expect(res.data?.results.images).toBeDefined();
expectRequest(0, "POST", "/scrape", multiFormatParams);
});
test("screenshot format with options", async () => {
const body = {
results: {
screenshot: {
data: { url: "https://storage.example.com/shot.png", width: 1920, height: 1080 },
metadata: { contentType: "image/png" },
},
},
metadata: { contentType: "text/html" },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const screenshotParams = {
url: "https://example.com",
formats: [
{
type: "screenshot" as const,
fullPage: true,
width: 1920,
height: 1080,
quality: 95,
},
],
};
const res = await sdk.scrape(API_KEY, screenshotParams);
expect(res.status).toBe("success");
expect(res.data?.results.screenshot?.data.url).toBeDefined();
expectRequest(0, "POST", "/scrape", screenshotParams);
});
test("json format with prompt and schema", async () => {
const body = {
results: {
json: {
data: { title: "Example", price: 99.99 },
metadata: { chunker: { chunks: [{ size: 500 }] } },
},
},
metadata: { contentType: "text/html" },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const jsonParams = {
url: "https://example.com/product",
formats: [
{
type: "json" as const,
prompt: "Extract product title and price",
schema: {
type: "object",
properties: {
title: { type: "string" },
price: { type: "number" },
},
},
},
],
};
const res = await sdk.scrape(API_KEY, jsonParams);
expect(res.status).toBe("success");
expect(res.data?.results.json?.data).toEqual({ title: "Example", price: 99.99 });
expectRequest(0, "POST", "/scrape", jsonParams);
});
test("summary format", async () => {
const body = {
results: {
summary: {
data: "This is a summary of the page content.",
metadata: { chunker: { chunks: [{ size: 1000 }] } },
},
},
metadata: { contentType: "text/html" },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const summaryParams = {
url: "https://example.com/article",
formats: [{ type: "summary" as const }],
};
const res = await sdk.scrape(API_KEY, summaryParams);
expect(res.status).toBe("success");
expect(res.data?.results.summary?.data).toBe("This is a summary of the page content.");
expectRequest(0, "POST", "/scrape", summaryParams);
});
test("branding format", async () => {
const body = {
results: {
branding: {
data: {
colorScheme: "light",
colors: {
primary: "#0066cc",
accent: "#ff6600",
background: "#ffffff",
textPrimary: "#333333",
link: "#0066cc",
},
typography: {
primary: { family: "Inter", fallback: "sans-serif" },
heading: { family: "Inter", fallback: "sans-serif" },
mono: { family: "Fira Code", fallback: "monospace" },
sizes: { h1: "2.5rem", h2: "2rem", body: "1rem" },
},
images: { logo: "", favicon: "", ogImage: "" },
spacing: { baseUnit: 8, borderRadius: "4px" },
frameworkHints: ["react"],
personality: { tone: "professional", energy: "medium", targetAudience: "developers" },
confidence: 0.85,
},
metadata: {
branding: {
title: "Example",
description: "Example site",
favicon: "",
language: "en",
themeColor: "#0066cc",
ogTitle: "Example",
ogDescription: "Example site",
ogImage: "",
ogUrl: "https://example.com",
},
},
},
},
metadata: { contentType: "text/html" },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const brandingParams = {
url: "https://example.com",
formats: [{ type: "branding" as const }],
};
const res = await sdk.scrape(API_KEY, brandingParams);
expect(res.status).toBe("success");
expect(res.data?.results.branding?.data.colorScheme).toBe("light");
expectRequest(0, "POST", "/scrape", brandingParams);
});
test("PDF document scraping", async () => {
const body = {
results: {
markdown: { data: ["# PDF Document\n\nThis is the content extracted from the PDF."] },
},
metadata: {
contentType: "application/pdf",
ocr: {
model: "gpt-4o",
pagesProcessed: 2,
pages: [
{
index: 0,
images: [],
tables: [],
hyperlinks: [],
dimensions: { dpi: 72, height: 792, width: 612 },
},
{
index: 1,
images: [],
tables: [],
hyperlinks: [],
dimensions: { dpi: 72, height: 792, width: 612 },
},
],
},
},
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const pdfParams = {
url: "https://pdfobject.com/pdf/sample.pdf",
contentType: "application/pdf" as const,
formats: [{ type: "markdown" as const }],
};
const res = await sdk.scrape(API_KEY, pdfParams);
expect(res.status).toBe("success");
expect(res.data?.metadata.contentType).toBe("application/pdf");
expect(res.data?.metadata.ocr?.pagesProcessed).toBe(2);
expectRequest(0, "POST", "/scrape", pdfParams);
});
test("DOCX document scraping", async () => {
const body = {
results: { markdown: { data: ["# Word Document\n\nContent from DOCX file."] } },
metadata: {
contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
},
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const docxParams = {
url: "https://example.com/document.docx",
contentType:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document" as const,
formats: [{ type: "markdown" as const }],
};
const res = await sdk.scrape(API_KEY, docxParams);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/scrape", docxParams);
});
test("image scraping with OCR", async () => {
const body = {
results: { markdown: { data: ["Text extracted from image via OCR"] } },
metadata: { contentType: "image/png" },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const imageParams = {
url: "https://example.com/screenshot.png",
contentType: "image/png" as const,
formats: [{ type: "markdown" as const }],
};
const res = await sdk.scrape(API_KEY, imageParams);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/scrape", imageParams);
});
test("HTTP 401", async () => {
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(
json({ detail: "Invalid key" }, 401),
);
const res = await sdk.scrape(API_KEY, params);
expect(res.status).toBe("error");
expect(res.error).toContain("Invalid or missing API key");
});
test("HTTP 402", async () => {
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json({}, 402));
const res = await sdk.scrape(API_KEY, params);
expect(res.status).toBe("error");
expect(res.error).toContain("Insufficient credits");
});
test("HTTP 422", async () => {
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json({}, 422));
const res = await sdk.scrape(API_KEY, params);
expect(res.status).toBe("error");
expect(res.error).toContain("Invalid parameters");
});
test("HTTP 429", async () => {
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json({}, 429));
const res = await sdk.scrape(API_KEY, params);
expect(res.status).toBe("error");
expect(res.error).toContain("Rate limited");
});
test("HTTP 500", async () => {
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json({}, 500));
const res = await sdk.scrape(API_KEY, params);
expect(res.status).toBe("error");
expect(res.error).toContain("Server error");
});
test("timeout", async () => {
fetchSpy = spyOn(globalThis, "fetch").mockRejectedValueOnce(
new DOMException("The operation was aborted", "TimeoutError"),
);
const res = await sdk.scrape(API_KEY, params);
expect(res.status).toBe("error");
expect(res.error).toBe("Request timed out");
});
test("network error", async () => {
fetchSpy = spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("fetch failed"));
const res = await sdk.scrape(API_KEY, params);
expect(res.status).toBe("error");
expect(res.error).toBe("fetch failed");
});
});
describe("extract", () => {
const params = { url: "https://example.com", prompt: "Extract prices" };
test("success", async () => {
const body = {
raw: null,
json: { prices: [10, 20] },
usage: { promptTokens: 100, completionTokens: 50 },
metadata: { chunker: { chunks: [{ size: 1000 }] } },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const res = await sdk.extract(API_KEY, params);
expect(res.status).toBe("success");
expect(res.data).toEqual(body);
expectRequest(0, "POST", "/extract", params);
});
test("with HTML input instead of URL", async () => {
const body = {
raw: null,
json: { title: "Test Page" },
usage: { promptTokens: 50, completionTokens: 20 },
metadata: { chunker: { chunks: [{ size: 200 }] } },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const htmlParams = {
html: "<html><head><title>Test Page</title></head><body><h1>Hello</h1></body></html>",
prompt: "Extract the page title",
};
const res = await sdk.extract(API_KEY, htmlParams);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/extract", htmlParams);
});
test("with markdown input instead of URL", async () => {
const body = {
raw: null,
json: { headings: ["Introduction", "Methods"] },
usage: { promptTokens: 30, completionTokens: 15 },
metadata: { chunker: { chunks: [{ size: 100 }] } },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const mdParams = {
markdown: "# Introduction\n\nSome content.\n\n# Methods\n\nMore content.",
prompt: "Extract all headings",
};
const res = await sdk.extract(API_KEY, mdParams);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/extract", mdParams);
});
test("with schema for structured output", async () => {
const body = {
raw: null,
json: { products: [{ name: "Widget", price: 29.99, inStock: true }] },
usage: { promptTokens: 150, completionTokens: 80 },
metadata: { chunker: { chunks: [{ size: 500 }] } },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const schemaParams = {
url: "https://example.com/products",
prompt: "Extract all products with their names, prices, and availability",
schema: {
type: "object",
properties: {
products: {
type: "array",
items: {
type: "object",
properties: {
name: { type: "string" },
price: { type: "number" },
inStock: { type: "boolean" },
},
},
},
},
},
};
const res = await sdk.extract(API_KEY, schemaParams);
expect(res.status).toBe("success");
expect(res.data?.json?.products).toHaveLength(1);
expectRequest(0, "POST", "/extract", schemaParams);
});
test("with fetchConfig and contentType for PDF", async () => {
const body = {
raw: "Raw text from PDF",
json: { sections: ["Abstract", "Introduction", "Conclusion"] },
usage: { promptTokens: 200, completionTokens: 50 },
metadata: { chunker: { chunks: [{ size: 2000 }] }, fetch: { provider: "playwright" } },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const pdfParams = {
url: "https://pdfobject.com/pdf/sample.pdf",
contentType: "application/pdf" as const,
prompt: "List all section headings in this document",
fetchConfig: { timeout: 60000 },
};
const res = await sdk.extract(API_KEY, pdfParams);
expect(res.status).toBe("success");
expect(res.data?.raw).toBe("Raw text from PDF");
expectRequest(0, "POST", "/extract", pdfParams);
});
test("with html mode options", async () => {
const body = {
raw: null,
json: { mainContent: "Article text without boilerplate" },
usage: { promptTokens: 100, completionTokens: 30 },
metadata: { chunker: { chunks: [{ size: 800 }] } },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const modeParams = {
url: "https://example.com/article",
prompt: "Extract the main article content",
mode: "reader" as const,
};
const res = await sdk.extract(API_KEY, modeParams);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/extract", modeParams);
});
});
describe("search", () => {
const params = { query: "best pizza NYC" };
test("success", async () => {
const body = {
results: [{ url: "https://example.com", title: "Pizza", content: "Great pizza" }],
metadata: { search: {}, pages: { requested: 3, scraped: 3 } },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const res = await sdk.search(API_KEY, params);
expect(res.status).toBe("success");
expect(res.data).toEqual(body);
expectRequest(0, "POST", "/search", params);
});
test("with numResults and format options", async () => {
const body = {
results: [
{ url: "https://example1.com", title: "Result 1", content: "<p>HTML content 1</p>" },
{ url: "https://example2.com", title: "Result 2", content: "<p>HTML content 2</p>" },
{ url: "https://example3.com", title: "Result 3", content: "<p>HTML content 3</p>" },
{ url: "https://example4.com", title: "Result 4", content: "<p>HTML content 4</p>" },
{ url: "https://example5.com", title: "Result 5", content: "<p>HTML content 5</p>" },
],
metadata: { search: { provider: "google" }, pages: { requested: 5, scraped: 5 } },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const searchParams = {
query: "typescript best practices",
numResults: 5,
format: "html" as const,
};
const res = await sdk.search(API_KEY, searchParams);
expect(res.status).toBe("success");
expect(res.data?.results).toHaveLength(5);
expectRequest(0, "POST", "/search", searchParams);
});
test("with prompt and schema for structured extraction", async () => {
const body = {
results: [{ url: "https://example.com", title: "Product", content: "Widget $29.99" }],
json: { products: [{ name: "Widget", price: 29.99 }] },
usage: { promptTokens: 100, completionTokens: 30 },
metadata: {
search: {},
pages: { requested: 3, scraped: 3 },
chunker: { chunks: [{ size: 500 }] },
},
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const searchParams = {
query: "buy widgets online",
prompt: "Extract product names and prices from search results",
schema: {
type: "object",
properties: {
products: {
type: "array",
items: {
type: "object",
properties: {
name: { type: "string" },
price: { type: "number" },
},
},
},
},
},
};
const res = await sdk.search(API_KEY, searchParams);
expect(res.status).toBe("success");
expect(res.data?.json).toBeDefined();
expectRequest(0, "POST", "/search", searchParams);
});
test("with location and time range filters", async () => {
const body = {
results: [
{ url: "https://news.example.com", title: "Breaking News", content: "Recent event" },
],
metadata: { search: {}, pages: { requested: 3, scraped: 3 } },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const searchParams = {
query: "local news",
locationGeoCode: "us",
timeRange: "past_24_hours" as const,
};
const res = await sdk.search(API_KEY, searchParams);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/search", searchParams);
});
test("with fetchConfig and html mode", async () => {
const body = {
results: [{ url: "https://example.com", title: "Test", content: "# Clean content" }],
metadata: { search: {}, pages: { requested: 2, scraped: 2 } },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const searchParams = {
query: "test query",
numResults: 2,
mode: "prune" as const,
fetchConfig: { mode: "js" as const, timeout: 45000 },
};
const res = await sdk.search(API_KEY, searchParams);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/search", searchParams);
});
});
describe("getCredits", () => {
test("success", async () => {
const body = {
remaining: 1000,
used: 500,
plan: "pro",
jobs: { crawl: { used: 1, limit: 5 }, monitor: { used: 2, limit: 10 } },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const res = await sdk.getCredits(API_KEY);
expect(res.status).toBe("success");
expect(res.data).toEqual(body);
expectRequest(0, "GET", "/credits");
});
});
describe("checkHealth", () => {
test("success", async () => {
const body = { status: "ok", uptime: 12345 };
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const res = await sdk.checkHealth(API_KEY);
expect(res.status).toBe("success");
expect(res.data).toEqual(body);
expectRequest(0, "GET", "/health");
});
});
describe("history", () => {
test("list success without params", async () => {
const body = {
data: [],
pagination: { page: 1, limit: 20, total: 0 },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const res = await sdk.history.list(API_KEY);
expect(res.status).toBe("success");
expect(res.data).toEqual(body);
expectRequest(0, "GET", "/history");
});
test("list success with params", async () => {
const body = {
data: [],
pagination: { page: 2, limit: 10, total: 50 },
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const res = await sdk.history.list(API_KEY, { page: 2, limit: 10, service: "scrape" });
expect(res.status).toBe("success");
const [url] = fetchSpy.mock.calls[0] as [string, RequestInit];
expect(url).toContain("page=2");
expect(url).toContain("limit=10");
expect(url).toContain("service=scrape");
});
test("get success", async () => {
const body = {
id: "abc-123",
service: "scrape",
status: "completed",
params: { url: "https://example.com" },
result: {},
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const res = await sdk.history.get(API_KEY, "abc-123");
expect(res.status).toBe("success");
expect(res.data).toEqual(body);
expectRequest(0, "GET", "/history/abc-123");
});
});
describe("crawl", () => {
const params = { url: "https://example.com" };
test("start success", async () => {
const body = {
id: "crawl-123",
status: "running",
total: 50,
finished: 0,
pages: [],
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const res = await sdk.crawl.start(API_KEY, params);
expect(res.status).toBe("success");
expect(res.data).toEqual(body);
expectRequest(0, "POST", "/crawl", params);
});
test("start with full config - formats and limits", async () => {
const body = {
id: "crawl-456",
status: "running",
total: 100,
finished: 0,
pages: [],
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const fullParams = {
url: "https://example.com",
formats: [
{ type: "markdown" as const, mode: "reader" as const },
{ type: "screenshot" as const, fullPage: false, width: 1280, height: 720, quality: 80 },
],
maxDepth: 3,
maxPages: 100,
maxLinksPerPage: 20,
};
const res = await sdk.crawl.start(API_KEY, fullParams);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/crawl", fullParams);
});
test("start with include/exclude patterns", async () => {
const body = {
id: "crawl-789",
status: "running",
total: 30,
finished: 0,
pages: [],
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const patternParams = {
url: "https://example.com",
includePatterns: ["/blog/*", "/docs/*"],
excludePatterns: ["/admin/*", "*.pdf"],
allowExternal: false,
};
const res = await sdk.crawl.start(API_KEY, patternParams);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/crawl", patternParams);
});
test("start with fetchConfig and contentTypes", async () => {
const body = {
id: "crawl-abc",
status: "running",
total: 50,
finished: 0,
pages: [],
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const configParams = {
url: "https://example.com",
contentTypes: ["text/html" as const, "application/pdf" as const],
fetchConfig: {
mode: "js" as const,
stealth: true,
timeout: 45000,
wait: 1000,
},
};
const res = await sdk.crawl.start(API_KEY, configParams);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/crawl", configParams);
});
test("get success", async () => {
const body = {
id: "crawl-123",
status: "completed",
total: 10,
finished: 10,
pages: [{ url: "https://example.com", status: "completed" }],
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const res = await sdk.crawl.get(API_KEY, "crawl-123");
expect(res.status).toBe("success");
expect(res.data).toEqual(body);
expectRequest(0, "GET", "/crawl/crawl-123");
});
test("stop success", async () => {
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json({ ok: true }));
const res = await sdk.crawl.stop(API_KEY, "crawl-123");
expect(res.status).toBe("success");
expect(res.data).toEqual({ ok: true });
expectRequest(0, "POST", "/crawl/crawl-123/stop");
});
test("resume success", async () => {
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json({ ok: true }));
const res = await sdk.crawl.resume(API_KEY, "crawl-123");
expect(res.status).toBe("success");
expect(res.data).toEqual({ ok: true });
expectRequest(0, "POST", "/crawl/crawl-123/resume");
});
test("delete success", async () => {
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json({ ok: true }));
const res = await sdk.crawl.delete(API_KEY, "crawl-123");
expect(res.status).toBe("success");
expect(res.data).toEqual({ ok: true });
expectRequest(0, "DELETE", "/crawl/crawl-123");
});
});
describe("monitor", () => {
const createParams = { url: "https://example.com", interval: "0 * * * *" };
test("create success", async () => {
const body = {
cronId: "mon-123",
scheduleId: "sched-456",
interval: "0 * * * *",
status: "active",
config: createParams,
createdAt: "2024-01-01T00:00:00Z",
updatedAt: "2024-01-01T00:00:00Z",
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const res = await sdk.monitor.create(API_KEY, createParams);
expect(res.status).toBe("success");
expect(res.data).toEqual(body);
expectRequest(0, "POST", "/monitor", createParams);
});
test("create with multiple formats and webhook", async () => {
const fullParams = {
url: "https://example.com/prices",
name: "Price Monitor",
interval: "0 */6 * * *",
formats: [
{ type: "markdown" as const, mode: "reader" as const },
{ type: "json" as const, prompt: "Extract all product prices", mode: "normal" as const },
{ type: "screenshot" as const, fullPage: true, width: 1440, height: 900, quality: 90 },
],
webhookUrl: "https://hooks.example.com/notify",
};
const body = {
cronId: "mon-456",
scheduleId: "sched-789",
interval: "0 */6 * * *",
status: "active",
config: fullParams,
createdAt: "2024-01-01T00:00:00Z",
updatedAt: "2024-01-01T00:00:00Z",
};
fetchSpy = spyOn(globalThis, "fetch").mockResolvedValueOnce(json(body));
const res = await sdk.monitor.create(API_KEY, fullParams);
expect(res.status).toBe("success");
expectRequest(0, "POST", "/monitor", fullParams);
});
test("create with fetchConfig", async () => {
const configParams = {
url: "https://spa-example.com",
interval: "0 0 * * *",
fetchConfig: {
mode: "js" as const,
stealth: true,
wait: 3000,
scrolls: 5,
},