1 | import { ApifyClient } from 'apify-client@^2.19.0'; |
2 |
|
3 | type ApifyApiKey = { |
4 | api_key: string; |
5 | }; |
6 |
|
7 | type Apify = { |
8 | token: string; |
9 | }; |
10 |
|
11 | const createClient = (api_key?: ApifyApiKey, oauth_token?: Apify): ApifyClient => { |
12 | const token = oauth_token?.token ?? api_key?.api_key; |
13 | if (!token) { |
14 | throw new Error('Missing Apify API key or OAuth token'); |
15 | } |
16 |
|
17 | return new ApifyClient({ |
18 | token: token, |
19 | requestInterceptors: [ |
20 | (request) => { |
21 | if (!request.headers) { |
22 | request.headers = {}; |
23 | } |
24 | request.headers['x-apify-integration-platform'] = 'windmill'; |
25 | return request; |
26 | }, |
27 | ], |
28 | }); |
29 | }; |
30 |
|
31 | |
32 | |
33 | |
34 | const WEB_FETCH_STANDBY_URL = 'https://web-fetch.apify.actor/'; |
35 |
|
36 | type WebFetchFormat = 'markdown' | 'html' | 'text' | 'links' | 'raw'; |
37 |
|
38 | const WEB_FETCH_FORMATS: WebFetchFormat[] = ['markdown', 'html', 'text', 'links', 'raw']; |
39 |
|
40 | |
41 | |
42 | const WEB_FETCH_TIMEOUT_MS = 10 * 60 * 1000; |
43 |
|
44 | |
45 | |
46 | const MAX_RETRIES = 3; |
47 | const RETRY_BACKOFF_MS = 200; |
48 |
|
49 | const isValidHostname = (hostname: string): boolean => |
50 | /^(?=.{1,253}$)((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}$/.test(hostname); |
51 |
|
52 | |
53 | |
54 | function parseResponseBody(data: unknown): any { |
55 | if (Buffer.isBuffer(data) || typeof data === 'string') { |
56 | try { |
57 | return JSON.parse(data.toString()); |
58 | } catch { |
59 | return data; |
60 | } |
61 | } |
62 | return data; |
63 | } |
64 |
|
65 | |
66 | |
67 | function getWebFetchErrorMessage(status: number, body: any): string { |
68 | if (body && typeof body === 'object') { |
69 | if (typeof body.error === 'string') { |
70 | return typeof body.code === 'string' |
71 | ? `${body.error} (Web Fetch error code: ${body.code})` |
72 | : body.error; |
73 | } |
74 | if (typeof body.error?.message === 'string') { |
75 | return typeof body.error.type === 'string' |
76 | ? `${body.error.message} (Web Fetch error type: ${body.error.type})` |
77 | : body.error.message; |
78 | } |
79 | } |
80 | return `Web Fetch responded with HTTP status ${status}`; |
81 | } |
82 |
|
83 | const isWebFetchError = (body: any): boolean => |
84 | !!body && typeof body === 'object' && typeof body.code === 'string' && typeof body.error === 'string'; |
85 |
|
86 | const isRetryable = (status: number, body: any): boolean => |
87 | (status === 429 || status >= 500) && !isWebFetchError(body); |
88 |
|
89 | |
90 | |
91 | export async function main( |
92 | url: string, |
93 | formats: WebFetchFormat[] = ['markdown'], |
94 | headers?: Record<string, string>, |
95 | api_key?: ApifyApiKey, |
96 | oauth_token?: Apify, |
97 | ) { |
98 | |
99 | let parsedUrl: URL | undefined; |
100 | try { |
101 | parsedUrl = new URL(url); |
102 | } catch { |
103 | |
104 | } |
105 | if ( |
106 | !parsedUrl || |
107 | (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') || |
108 | !isValidHostname(parsedUrl.hostname) |
109 | ) { |
110 | return { |
111 | error: `Invalid URL: "${url}". Provide a full, valid URL including a domain name, e.g. https://example.com.`, |
112 | }; |
113 | } |
114 |
|
115 | |
116 | |
117 | if (formats != null && !Array.isArray(formats)) { |
118 | return { error: `Invalid formats. Allowed: ${WEB_FETCH_FORMATS.join(', ')}.` }; |
119 | } |
120 | const requestedFormats = formats ?? []; |
121 | const unknownFormats = requestedFormats.filter((format) => !WEB_FETCH_FORMATS.includes(format)); |
122 | if (unknownFormats.length > 0) { |
123 | return { |
124 | error: `Unknown format(s): ${unknownFormats.join(', ')}. Allowed: ${WEB_FETCH_FORMATS.join(', ')}.`, |
125 | }; |
126 | } |
127 |
|
128 | if ( |
129 | headers != null && |
130 | (typeof headers !== 'object' || |
131 | Array.isArray(headers) || |
132 | Object.values(headers).some((value) => typeof value !== 'string')) |
133 | ) { |
134 | return { |
135 | error: 'Invalid headers. Provide an object of header names and string values, e.g. {"Accept-Language": "fr-FR"}.', |
136 | }; |
137 | } |
138 |
|
139 | |
140 | const validHeaders = Object.fromEntries( |
141 | Object.entries(headers ?? {}).filter(([name]) => name.trim()), |
142 | ); |
143 |
|
144 | const client = createClient(api_key, oauth_token); |
145 |
|
146 | try { |
147 | |
148 | |
149 | |
150 | |
151 | const data = { |
152 | url, |
153 | ...(requestedFormats.length > 0 ? { formats: requestedFormats } : {}), |
154 | ...(Object.keys(validHeaders).length > 0 ? { headers: validHeaders } : {}), |
155 | }; |
156 | |
157 | const deadline = Date.now() + WEB_FETCH_TIMEOUT_MS; |
158 | let attempt = 0; |
159 | let response; |
160 | let body; |
161 | while (true) { |
162 | response = await client.httpClient.axios.request({ |
163 | url: WEB_FETCH_STANDBY_URL, |
164 | method: 'POST', |
165 | data, |
166 | timeout: Math.max(deadline - Date.now(), 1000), |
167 | }); |
168 | body = parseResponseBody(response.data); |
169 |
|
170 | const backoff = RETRY_BACKOFF_MS * 2 ** attempt; |
171 | if ( |
172 | response.status < 300 || |
173 | attempt >= MAX_RETRIES || |
174 | !isRetryable(response.status, body) || |
175 | Date.now() + backoff >= deadline |
176 | ) { |
177 | break; |
178 | } |
179 | await new Promise((resolve) => setTimeout(resolve, backoff)); |
180 | attempt += 1; |
181 | } |
182 |
|
183 | if (response.status >= 300) { |
184 | return { |
185 | error: `Failed to fetch URL. Reason: ${getWebFetchErrorMessage(response.status, body)}`, |
186 | }; |
187 | } |
188 |
|
189 | if (!body || typeof body !== 'object' || Array.isArray(body) || Buffer.isBuffer(body)) { |
190 | return { error: 'Failed to fetch URL. Reason: Web Fetch returned an unexpected response.' }; |
191 | } |
192 |
|
193 | |
194 | |
195 | return body; |
196 | } catch (error: any) { |
197 | if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') { |
198 | return { |
199 | error: |
200 | `Fetching ${url} took more than ${WEB_FETCH_TIMEOUT_MS / 1000} seconds. ` + |
201 | 'The website may be slow or too large. Try again or use a different URL.', |
202 | }; |
203 | } |
204 | return { |
205 | error: `Failed to fetch URL. Reason: ${error.message}`, |
206 | }; |
207 | } |
208 | } |