-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathindex.ts
121 lines (108 loc) · 3.1 KB
/
index.ts
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
import * as undici from "undici";
import { EngineScrapeResult } from "..";
import { Meta } from "../..";
import { TimeoutError } from "../../error";
import { specialtyScrapeCheck } from "../utils/specialtyHandler";
import {
InsecureConnectionError,
makeSecureDispatcher,
} from "../utils/safeFetch";
import { MockState, saveMock } from "../../lib/mock";
import { TextDecoder } from "util";
export async function scrapeURLWithFetch(
meta: Meta,
timeToRun: number | undefined,
): Promise<EngineScrapeResult> {
const timeout = timeToRun ?? 300000;
const mockOptions = {
url: meta.url,
// irrelevant
method: "GET",
ignoreResponse: false,
ignoreFailure: false,
tryCount: 1,
};
let response: {
url: string;
body: string,
status: number;
headers: any;
};
if (meta.mock !== null) {
const makeRequestTypeId = (
request: MockState["requests"][number]["options"],
) => request.url + ";" + request.method;
const thisId = makeRequestTypeId(mockOptions);
const matchingMocks = meta.mock.requests
.filter((x) => makeRequestTypeId(x.options) === thisId)
.sort((a, b) => a.time - b.time);
const nextI = meta.mock.tracker[thisId] ?? 0;
meta.mock.tracker[thisId] = nextI + 1;
if (!matchingMocks[nextI]) {
throw new Error("Failed to mock request -- no mock targets found.");
}
response = {
...matchingMocks[nextI].result,
};
} else {
try {
const x = await Promise.race([
undici.fetch(meta.url, {
dispatcher: await makeSecureDispatcher(meta.url),
redirect: "follow",
headers: meta.options.headers,
signal: meta.internalOptions.abort,
}),
(async () => {
await new Promise((resolve) =>
setTimeout(() => resolve(null), timeout),
);
throw new TimeoutError(
"Fetch was unable to scrape the page before timing out",
{ cause: { timeout } },
);
})(),
]);
const buf = Buffer.from(await x.arrayBuffer());
let text = buf.toString("utf8");
const charset = (text.match(/<meta\b[^>]*charset\s*=\s*["']?([^"'\s\/>]+)/i) ?? [])[1]
try {
if (charset) {
text = new TextDecoder(charset.trim()).decode(buf);
}
} catch (error) {
meta.logger.warn("Failed to re-parse with correct charset", { charset, error })
}
response = {
url: x.url,
body: text,
status: x.status,
headers: [...x.headers],
};
if (meta.mock === null) {
await saveMock(
mockOptions,
response,
);
}
} catch (error) {
if (
error instanceof TypeError &&
error.cause instanceof InsecureConnectionError
) {
throw error.cause;
} else {
throw error;
}
}
}
await specialtyScrapeCheck(
meta.logger.child({ method: "scrapeURLWithFetch/specialtyScrapeCheck" }),
Object.fromEntries(response.headers as any),
);
return {
url: response.url,
html: response.body,
statusCode: response.status,
};
}