@cacheable/net 2.0.8 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +578 -72
- package/dist/index.cjs +1309 -699
- package/dist/index.d.cts +420 -225
- package/dist/index.d.mts +499 -0
- package/dist/index.mjs +1291 -0
- package/package.json +17 -11
- package/dist/index.d.ts +0 -304
- package/dist/index.js +0 -677
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1291 @@
|
|
|
1
|
+
import { Cacheable } from "cacheable";
|
|
2
|
+
import { Hookified } from "hookified";
|
|
3
|
+
import { coalesceAsync } from "@cacheable/utils";
|
|
4
|
+
import CachePolicy from "http-cache-semantics";
|
|
5
|
+
import { createConnection, isIPv4, isIPv6 } from "node:net";
|
|
6
|
+
import { domainToASCII } from "node:url";
|
|
7
|
+
//#region src/fetch.ts
|
|
8
|
+
const runtimeFetch = globalThis.fetch.bind(globalThis);
|
|
9
|
+
const NULL_BODY_STATUSES = new Set([
|
|
10
|
+
101,
|
|
11
|
+
103,
|
|
12
|
+
204,
|
|
13
|
+
205,
|
|
14
|
+
304
|
|
15
|
+
]);
|
|
16
|
+
/**
|
|
17
|
+
* Reconstruct a `Response` while preserving the properties the WHATWG
|
|
18
|
+
* `Response` constructor does not let you set. Native `fetch` exposes the final
|
|
19
|
+
* URL via `response.url`; rebuilding with `new Response()` resets it to "".
|
|
20
|
+
* We reattach `url` (and `redirected`/`type` when rebuilding from a live
|
|
21
|
+
* response) so callers see the same shape native `fetch` returns.
|
|
22
|
+
*
|
|
23
|
+
* @param body The response body.
|
|
24
|
+
* @param init Standard response init (status, statusText, headers).
|
|
25
|
+
* @param source Optional source values to reattach (url, redirected, type).
|
|
26
|
+
* @returns A Response with native-`fetch` properties preserved.
|
|
27
|
+
*/
|
|
28
|
+
function makeResponse(body, init, source) {
|
|
29
|
+
const safeBody = init.status !== void 0 && NULL_BODY_STATUSES.has(init.status) ? null : body;
|
|
30
|
+
const response = new Response(safeBody, init);
|
|
31
|
+
Object.defineProperty(response, "url", {
|
|
32
|
+
value: source.url,
|
|
33
|
+
configurable: true,
|
|
34
|
+
enumerable: true
|
|
35
|
+
});
|
|
36
|
+
if (source.redirected !== void 0) Object.defineProperty(response, "redirected", {
|
|
37
|
+
value: source.redirected,
|
|
38
|
+
configurable: true,
|
|
39
|
+
enumerable: true
|
|
40
|
+
});
|
|
41
|
+
if (source.type !== void 0) Object.defineProperty(response, "type", {
|
|
42
|
+
value: source.type,
|
|
43
|
+
configurable: true,
|
|
44
|
+
enumerable: true
|
|
45
|
+
});
|
|
46
|
+
return response;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Fetch data from a URL with optional request options.
|
|
50
|
+
*
|
|
51
|
+
* When `httpCachePolicy` is enabled (default), cache entries will have their TTL
|
|
52
|
+
* set based on HTTP cache headers (e.g., Cache-Control: max-age). When disabled,
|
|
53
|
+
* the default TTL from the Cacheable instance is used.
|
|
54
|
+
*
|
|
55
|
+
* If no cache is provided, the request will be made without any caching.
|
|
56
|
+
*
|
|
57
|
+
* @param {string} url The URL to fetch.
|
|
58
|
+
* @param {FetchOptions} options Optional request options. If `cache` is not provided, no caching will be used.
|
|
59
|
+
* @returns {Promise<UndiciResponse>} The response from the fetch.
|
|
60
|
+
*/
|
|
61
|
+
async function fetch(url, options) {
|
|
62
|
+
const fetchOptions = {
|
|
63
|
+
...options,
|
|
64
|
+
cache: "no-cache"
|
|
65
|
+
};
|
|
66
|
+
if (!options?.cache) return runtimeFetch(url, fetchOptions);
|
|
67
|
+
if (options.method === "POST" || options.method === "PATCH" || options.method === "DELETE" || options.method === "HEAD") return runtimeFetch(url, fetchOptions);
|
|
68
|
+
const httpCachePolicy = options.httpCachePolicy !== false;
|
|
69
|
+
const method = options.method || "GET";
|
|
70
|
+
const cacheKey = `${method}:${url}`;
|
|
71
|
+
if (!httpCachePolicy) {
|
|
72
|
+
const cache = options.cache;
|
|
73
|
+
const cachedData = await coalesceAsync(`net:simple:${cacheKey}`, async () => {
|
|
74
|
+
const existing = await cache.get(cacheKey);
|
|
75
|
+
if (existing) return existing;
|
|
76
|
+
const response = await runtimeFetch(url, fetchOptions);
|
|
77
|
+
const result = {
|
|
78
|
+
body: await response.text(),
|
|
79
|
+
status: response.status,
|
|
80
|
+
statusText: response.statusText,
|
|
81
|
+
headers: Object.fromEntries(response.headers.entries()),
|
|
82
|
+
url: response.url,
|
|
83
|
+
redirected: response.redirected,
|
|
84
|
+
type: response.type
|
|
85
|
+
};
|
|
86
|
+
if (response.ok) await cache.set(cacheKey, result);
|
|
87
|
+
return result;
|
|
88
|
+
});
|
|
89
|
+
return makeResponse(cachedData.body, {
|
|
90
|
+
status: cachedData.status,
|
|
91
|
+
statusText: cachedData.statusText,
|
|
92
|
+
headers: cachedData.headers
|
|
93
|
+
}, {
|
|
94
|
+
url: cachedData.url ?? url,
|
|
95
|
+
redirected: cachedData.redirected,
|
|
96
|
+
type: cachedData.type
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
const policyKey = `${cacheKey}:policy`;
|
|
100
|
+
const [cachedResponse, cachedPolicyData] = await Promise.all([options.cache.get(cacheKey), options.cache.get(policyKey)]);
|
|
101
|
+
let policy;
|
|
102
|
+
let cachedBody;
|
|
103
|
+
let cachedStatus;
|
|
104
|
+
let cachedStatusText;
|
|
105
|
+
let cachedHeaders;
|
|
106
|
+
let cachedUrl;
|
|
107
|
+
let cachedRedirected;
|
|
108
|
+
let cachedType;
|
|
109
|
+
if (cachedPolicyData && cachedResponse) {
|
|
110
|
+
policy = CachePolicy.fromObject(cachedPolicyData);
|
|
111
|
+
cachedBody = cachedResponse.body;
|
|
112
|
+
cachedStatus = cachedResponse.status;
|
|
113
|
+
cachedStatusText = cachedResponse.statusText;
|
|
114
|
+
cachedHeaders = cachedResponse.headers;
|
|
115
|
+
cachedUrl = cachedResponse.url;
|
|
116
|
+
cachedRedirected = cachedResponse.redirected;
|
|
117
|
+
cachedType = cachedResponse.type;
|
|
118
|
+
}
|
|
119
|
+
const request = {
|
|
120
|
+
url,
|
|
121
|
+
method,
|
|
122
|
+
headers: fetchOptions.headers || {}
|
|
123
|
+
};
|
|
124
|
+
if (policy?.satisfiesWithoutRevalidation(request)) {
|
|
125
|
+
const headers = policy.responseHeaders();
|
|
126
|
+
return makeResponse(cachedBody, {
|
|
127
|
+
status: cachedStatus,
|
|
128
|
+
statusText: cachedStatusText,
|
|
129
|
+
headers
|
|
130
|
+
}, {
|
|
131
|
+
url: cachedUrl ?? url,
|
|
132
|
+
redirected: cachedRedirected,
|
|
133
|
+
type: cachedType
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
let revalidationHeaders = {};
|
|
137
|
+
if (policy?.revalidationHeaders(request)) revalidationHeaders = policy.revalidationHeaders(request);
|
|
138
|
+
const response = await runtimeFetch(url, {
|
|
139
|
+
...fetchOptions,
|
|
140
|
+
headers: {
|
|
141
|
+
...fetchOptions.headers,
|
|
142
|
+
...revalidationHeaders
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
if (response.status === 304 && policy) {
|
|
146
|
+
const { policy: updatedPolicy, modified } = policy.revalidatedPolicy(request, {
|
|
147
|
+
status: response.status,
|
|
148
|
+
headers: Object.fromEntries(response.headers.entries())
|
|
149
|
+
});
|
|
150
|
+
/* v8 ignore next -- @preserve */
|
|
151
|
+
if (!modified) {
|
|
152
|
+
const ttl = updatedPolicy.timeToLive();
|
|
153
|
+
await options.cache.set(policyKey, updatedPolicy.toObject(), ttl);
|
|
154
|
+
await options.cache.set(cacheKey, {
|
|
155
|
+
body: cachedBody,
|
|
156
|
+
status: cachedStatus,
|
|
157
|
+
statusText: cachedStatusText,
|
|
158
|
+
headers: cachedHeaders,
|
|
159
|
+
url: cachedUrl,
|
|
160
|
+
redirected: cachedRedirected,
|
|
161
|
+
type: cachedType
|
|
162
|
+
}, ttl);
|
|
163
|
+
const headers = updatedPolicy.responseHeaders();
|
|
164
|
+
return makeResponse(cachedBody, {
|
|
165
|
+
status: cachedStatus,
|
|
166
|
+
statusText: cachedStatusText,
|
|
167
|
+
headers
|
|
168
|
+
}, {
|
|
169
|
+
url: cachedUrl ?? url,
|
|
170
|
+
redirected: cachedRedirected,
|
|
171
|
+
type: cachedType
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const body = await response.text();
|
|
176
|
+
if (!response.ok) return makeResponse(body, {
|
|
177
|
+
status: response.status,
|
|
178
|
+
statusText: response.statusText,
|
|
179
|
+
headers: response.headers
|
|
180
|
+
}, {
|
|
181
|
+
url: response.url,
|
|
182
|
+
redirected: response.redirected,
|
|
183
|
+
type: response.type
|
|
184
|
+
});
|
|
185
|
+
const responseForPolicy = {
|
|
186
|
+
status: response.status,
|
|
187
|
+
statusText: response.statusText,
|
|
188
|
+
headers: Object.fromEntries(response.headers.entries())
|
|
189
|
+
};
|
|
190
|
+
const newPolicy = new CachePolicy(request, responseForPolicy);
|
|
191
|
+
if (newPolicy.storable()) {
|
|
192
|
+
const ttl = newPolicy.timeToLive();
|
|
193
|
+
await Promise.all([options.cache.set(cacheKey, {
|
|
194
|
+
body,
|
|
195
|
+
status: response.status,
|
|
196
|
+
statusText: response.statusText,
|
|
197
|
+
headers: responseForPolicy.headers,
|
|
198
|
+
url: response.url,
|
|
199
|
+
redirected: response.redirected,
|
|
200
|
+
type: response.type
|
|
201
|
+
}, ttl), options.cache.set(policyKey, newPolicy.toObject(), ttl)]);
|
|
202
|
+
}
|
|
203
|
+
return makeResponse(body, {
|
|
204
|
+
status: response.status,
|
|
205
|
+
statusText: response.statusText,
|
|
206
|
+
headers: response.headers
|
|
207
|
+
}, {
|
|
208
|
+
url: response.url,
|
|
209
|
+
redirected: response.redirected,
|
|
210
|
+
type: response.type
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Perform a GET request to a URL with optional request options.
|
|
215
|
+
* @param {string} url The URL to fetch.
|
|
216
|
+
* @param {Omit<FetchOptions, 'method'>} options Optional request options. The `cache` property is required.
|
|
217
|
+
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
|
|
218
|
+
*/
|
|
219
|
+
async function get(url, options) {
|
|
220
|
+
const response = await fetch(url, {
|
|
221
|
+
...options,
|
|
222
|
+
method: "GET"
|
|
223
|
+
});
|
|
224
|
+
const text = await response.text();
|
|
225
|
+
let data;
|
|
226
|
+
try {
|
|
227
|
+
data = JSON.parse(text);
|
|
228
|
+
} catch {
|
|
229
|
+
data = text;
|
|
230
|
+
}
|
|
231
|
+
const newResponse = makeResponse(text, {
|
|
232
|
+
status: response.status,
|
|
233
|
+
statusText: response.statusText,
|
|
234
|
+
headers: response.headers
|
|
235
|
+
}, {
|
|
236
|
+
url: response.url,
|
|
237
|
+
redirected: response.redirected,
|
|
238
|
+
type: response.type
|
|
239
|
+
});
|
|
240
|
+
return {
|
|
241
|
+
data,
|
|
242
|
+
response: newResponse
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Perform a POST request to a URL with data and optional request options.
|
|
247
|
+
* @param {string} url The URL to fetch.
|
|
248
|
+
* @param {unknown} data The data to send in the request body.
|
|
249
|
+
* @param {Omit<FetchOptions, 'method' | 'body'>} options Optional request options. The `cache` property is required.
|
|
250
|
+
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
|
|
251
|
+
*/
|
|
252
|
+
async function post(url, data, options) {
|
|
253
|
+
let body;
|
|
254
|
+
const headers = { ...options.headers };
|
|
255
|
+
if (typeof data === "string") body = data;
|
|
256
|
+
else if (data instanceof FormData || data instanceof URLSearchParams || data instanceof Blob) body = data;
|
|
257
|
+
else {
|
|
258
|
+
body = JSON.stringify(data);
|
|
259
|
+
/* v8 ignore next -- @preserve */
|
|
260
|
+
if (!headers["Content-Type"] && !headers["content-type"]) headers["Content-Type"] = "application/json";
|
|
261
|
+
}
|
|
262
|
+
const response = await fetch(url, {
|
|
263
|
+
...options,
|
|
264
|
+
headers,
|
|
265
|
+
body,
|
|
266
|
+
method: "POST"
|
|
267
|
+
});
|
|
268
|
+
const text = await response.text();
|
|
269
|
+
let responseData;
|
|
270
|
+
try {
|
|
271
|
+
responseData = JSON.parse(text);
|
|
272
|
+
} catch {
|
|
273
|
+
responseData = text;
|
|
274
|
+
}
|
|
275
|
+
const newResponse = makeResponse(text, {
|
|
276
|
+
status: response.status,
|
|
277
|
+
statusText: response.statusText,
|
|
278
|
+
headers: response.headers
|
|
279
|
+
}, {
|
|
280
|
+
url: response.url,
|
|
281
|
+
redirected: response.redirected,
|
|
282
|
+
type: response.type
|
|
283
|
+
});
|
|
284
|
+
return {
|
|
285
|
+
data: responseData,
|
|
286
|
+
response: newResponse
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Perform a PATCH request to a URL with data and optional request options.
|
|
291
|
+
* @param {string} url The URL to fetch.
|
|
292
|
+
* @param {unknown} data The data to send in the request body.
|
|
293
|
+
* @param {Omit<FetchOptions, 'method' | 'body'>} options Optional request options. The `cache` property is required.
|
|
294
|
+
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
|
|
295
|
+
*/
|
|
296
|
+
async function patch(url, data, options) {
|
|
297
|
+
let body;
|
|
298
|
+
const headers = { ...options.headers };
|
|
299
|
+
if (typeof data === "string") body = data;
|
|
300
|
+
else if (data instanceof FormData || data instanceof URLSearchParams || data instanceof Blob) body = data;
|
|
301
|
+
else {
|
|
302
|
+
/* v8 ignore next -- @preserve */
|
|
303
|
+
body = JSON.stringify(data);
|
|
304
|
+
/* v8 ignore next -- @preserve */
|
|
305
|
+
if (!headers["Content-Type"] && !headers["content-type"]) headers["Content-Type"] = "application/json";
|
|
306
|
+
}
|
|
307
|
+
const response = await fetch(url, {
|
|
308
|
+
...options,
|
|
309
|
+
headers,
|
|
310
|
+
body,
|
|
311
|
+
method: "PATCH"
|
|
312
|
+
});
|
|
313
|
+
const text = await response.text();
|
|
314
|
+
let responseData;
|
|
315
|
+
try {
|
|
316
|
+
responseData = JSON.parse(text);
|
|
317
|
+
} catch {
|
|
318
|
+
responseData = text;
|
|
319
|
+
}
|
|
320
|
+
const newResponse = makeResponse(text, {
|
|
321
|
+
status: response.status,
|
|
322
|
+
statusText: response.statusText,
|
|
323
|
+
headers: response.headers
|
|
324
|
+
}, {
|
|
325
|
+
url: response.url,
|
|
326
|
+
redirected: response.redirected,
|
|
327
|
+
type: response.type
|
|
328
|
+
});
|
|
329
|
+
return {
|
|
330
|
+
data: responseData,
|
|
331
|
+
response: newResponse
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Perform a DELETE request to a URL with optional data and request options.
|
|
336
|
+
* @param {string} url The URL to fetch.
|
|
337
|
+
* @param {unknown} data Optional data to send in the request body.
|
|
338
|
+
* @param {Omit<FetchOptions, 'method' | 'body'>} options Optional request options. The `cache` property is required.
|
|
339
|
+
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
|
|
340
|
+
*/
|
|
341
|
+
async function del(url, data, options) {
|
|
342
|
+
let actualData;
|
|
343
|
+
let actualOptions;
|
|
344
|
+
if (data !== void 0 && typeof data === "object" && data !== null && "cache" in data) {
|
|
345
|
+
actualData = void 0;
|
|
346
|
+
actualOptions = data;
|
|
347
|
+
} else if (options) {
|
|
348
|
+
actualData = data;
|
|
349
|
+
actualOptions = options;
|
|
350
|
+
} else throw new Error("Fetch options must include a cache instance or options.");
|
|
351
|
+
let body;
|
|
352
|
+
const headers = { ...actualOptions.headers };
|
|
353
|
+
if (actualData !== void 0) if (typeof actualData === "string") body = actualData;
|
|
354
|
+
else if (actualData instanceof FormData || actualData instanceof URLSearchParams || actualData instanceof Blob) body = actualData;
|
|
355
|
+
else {
|
|
356
|
+
/* v8 ignore next -- @preserve */
|
|
357
|
+
body = JSON.stringify(actualData);
|
|
358
|
+
/* v8 ignore next -- @preserve */
|
|
359
|
+
if (!headers["Content-Type"] && !headers["content-type"]) headers["Content-Type"] = "application/json";
|
|
360
|
+
}
|
|
361
|
+
const response = await fetch(url, {
|
|
362
|
+
...actualOptions,
|
|
363
|
+
headers,
|
|
364
|
+
body,
|
|
365
|
+
method: "DELETE"
|
|
366
|
+
});
|
|
367
|
+
const text = await response.text();
|
|
368
|
+
let responseData;
|
|
369
|
+
try {
|
|
370
|
+
responseData = JSON.parse(text);
|
|
371
|
+
} catch {
|
|
372
|
+
responseData = text;
|
|
373
|
+
}
|
|
374
|
+
const newResponse = makeResponse(text, {
|
|
375
|
+
status: response.status,
|
|
376
|
+
statusText: response.statusText,
|
|
377
|
+
headers: response.headers
|
|
378
|
+
}, {
|
|
379
|
+
url: response.url,
|
|
380
|
+
redirected: response.redirected,
|
|
381
|
+
type: response.type
|
|
382
|
+
});
|
|
383
|
+
return {
|
|
384
|
+
data: responseData,
|
|
385
|
+
response: newResponse
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Perform a HEAD request to a URL with optional request options.
|
|
390
|
+
* @param {string} url The URL to fetch.
|
|
391
|
+
* @param {Omit<FetchOptions, 'method'>} options Optional request options. The `cache` property is required.
|
|
392
|
+
* @returns {Promise<UndiciResponse>} The response from the fetch (no body).
|
|
393
|
+
*/
|
|
394
|
+
async function head(url, options) {
|
|
395
|
+
return await fetch(url, {
|
|
396
|
+
...options,
|
|
397
|
+
method: "HEAD"
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
//#endregion
|
|
401
|
+
//#region src/whois.ts
|
|
402
|
+
/**
|
|
403
|
+
* The default WHOIS port as defined by RFC 3912.
|
|
404
|
+
*/
|
|
405
|
+
const WHOIS_PORT = 43;
|
|
406
|
+
/**
|
|
407
|
+
* The IANA WHOIS server used to bootstrap discovery of the authoritative
|
|
408
|
+
* registry / RIR server for any domain, IP address, or ASN.
|
|
409
|
+
*/
|
|
410
|
+
const IANA_WHOIS_SERVER = "whois.iana.org";
|
|
411
|
+
/**
|
|
412
|
+
* The default socket timeout in milliseconds.
|
|
413
|
+
*/
|
|
414
|
+
const DEFAULT_TIMEOUT = 1e4;
|
|
415
|
+
/**
|
|
416
|
+
* The default number of registry → registrar referral hops to follow.
|
|
417
|
+
*/
|
|
418
|
+
const DEFAULT_FOLLOW_DEPTH = 2;
|
|
419
|
+
/**
|
|
420
|
+
* Line prefixes that mark a comment / disclaimer in WHOIS output and should be
|
|
421
|
+
* skipped when parsing key/value fields (IANA `%`, ICANN `>>>`, etc.).
|
|
422
|
+
*/
|
|
423
|
+
const COMMENT_PREFIXES = [
|
|
424
|
+
"%",
|
|
425
|
+
"#",
|
|
426
|
+
">>>",
|
|
427
|
+
"*"
|
|
428
|
+
];
|
|
429
|
+
/**
|
|
430
|
+
* Field names (case-insensitive) that carry a referral to another WHOIS server,
|
|
431
|
+
* in priority order. The first one present in a response is followed.
|
|
432
|
+
*/
|
|
433
|
+
const REFERRAL_KEYS = [
|
|
434
|
+
"refer",
|
|
435
|
+
"whois",
|
|
436
|
+
"registrar whois server",
|
|
437
|
+
"referralserver"
|
|
438
|
+
];
|
|
439
|
+
/**
|
|
440
|
+
* Open a raw WHOIS connection to a single server on TCP port 43, write the
|
|
441
|
+
* query, and resolve with the full text response. This is the low-level
|
|
442
|
+
* primitive used by {@link whois}; host and port are explicit so it can be
|
|
443
|
+
* pointed at any server (including a local test server).
|
|
444
|
+
*
|
|
445
|
+
* @param {QueryWhoisServerOptions} options The connection and query options.
|
|
446
|
+
* @returns {Promise<string>} The raw text returned by the server.
|
|
447
|
+
*/
|
|
448
|
+
function queryWhoisServer(options) {
|
|
449
|
+
const { host, port = WHOIS_PORT, query, queryPrefix = "", timeout = DEFAULT_TIMEOUT, encoding = "utf8" } = options;
|
|
450
|
+
return new Promise((resolve, reject) => {
|
|
451
|
+
const chunks = [];
|
|
452
|
+
let settled = false;
|
|
453
|
+
const socket = createConnection({
|
|
454
|
+
host,
|
|
455
|
+
port
|
|
456
|
+
});
|
|
457
|
+
socket.setTimeout(timeout);
|
|
458
|
+
const settle = (finish) => {
|
|
459
|
+
if (settled) return;
|
|
460
|
+
settled = true;
|
|
461
|
+
socket.destroy();
|
|
462
|
+
finish();
|
|
463
|
+
};
|
|
464
|
+
socket.on("connect", () => {
|
|
465
|
+
socket.write(`${queryPrefix}${query}\r\n`);
|
|
466
|
+
});
|
|
467
|
+
socket.on("data", (chunk) => {
|
|
468
|
+
chunks.push(chunk);
|
|
469
|
+
});
|
|
470
|
+
socket.on("timeout", () => {
|
|
471
|
+
settle(() => reject(/* @__PURE__ */ new Error(`WHOIS query to ${host}:${port} timed out after ${timeout}ms`)));
|
|
472
|
+
});
|
|
473
|
+
socket.on("error", (error) => {
|
|
474
|
+
settle(() => reject(error));
|
|
475
|
+
});
|
|
476
|
+
socket.on("close", () => {
|
|
477
|
+
settle(() => resolve(Buffer.concat(chunks).toString(encoding)));
|
|
478
|
+
});
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Normalize a WHOIS query by stripping URL scheme, `www.`, path/query/hash, and
|
|
483
|
+
* trailing dots, lowercasing, and converting internationalized domains to
|
|
484
|
+
* punycode.
|
|
485
|
+
*
|
|
486
|
+
* @param {string} input The raw query (domain, URL, IP, or ASN).
|
|
487
|
+
* @returns {string} The normalized query.
|
|
488
|
+
*/
|
|
489
|
+
function normalizeWhoisQuery(input) {
|
|
490
|
+
let value = input.trim().toLowerCase();
|
|
491
|
+
value = value.replace(/^[a-z][a-z0-9+.-]*:\/\//, "");
|
|
492
|
+
value = value.replace(/^www\./, "");
|
|
493
|
+
value = value.split(/[/?#]/)[0];
|
|
494
|
+
const colonIndex = value.indexOf(":");
|
|
495
|
+
if (colonIndex !== -1 && value.indexOf(":", colonIndex + 1) === -1) {
|
|
496
|
+
const portPart = value.slice(colonIndex + 1);
|
|
497
|
+
if (portPart.length > 0 && /^\d+$/.test(portPart)) value = value.slice(0, colonIndex);
|
|
498
|
+
}
|
|
499
|
+
while (value.endsWith(".")) value = value.slice(0, -1);
|
|
500
|
+
value = value.trim();
|
|
501
|
+
if ([...value].some((char) => char.charCodeAt(0) > 127)) {
|
|
502
|
+
const ascii = domainToASCII(value);
|
|
503
|
+
if (ascii !== "") value = ascii;
|
|
504
|
+
}
|
|
505
|
+
return value;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Detect whether a normalized query is a domain, IPv4 address, IPv6 address, or
|
|
509
|
+
* autonomous system number.
|
|
510
|
+
*
|
|
511
|
+
* @param {string} value The normalized query.
|
|
512
|
+
* @returns {WhoisQueryType} The detected query type.
|
|
513
|
+
*/
|
|
514
|
+
function detectQueryType(value) {
|
|
515
|
+
if (/^as\d+$/i.test(value) || /^\d+$/.test(value)) return "asn";
|
|
516
|
+
if (isIPv4(value)) return "ipv4";
|
|
517
|
+
if (isIPv6(value)) return "ipv6";
|
|
518
|
+
return "domain";
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Parse raw WHOIS text into a key/value object. Comment and disclaimer lines are
|
|
522
|
+
* ignored, and repeated keys are grouped into arrays.
|
|
523
|
+
*
|
|
524
|
+
* @param {string} raw The raw WHOIS text.
|
|
525
|
+
* @returns {WhoisFields} The parsed fields.
|
|
526
|
+
*/
|
|
527
|
+
function parseWhois(raw) {
|
|
528
|
+
const fields = Object.create(null);
|
|
529
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
530
|
+
const trimmed = line.trim();
|
|
531
|
+
if (trimmed === "") continue;
|
|
532
|
+
if (COMMENT_PREFIXES.some((prefix) => trimmed.startsWith(prefix))) continue;
|
|
533
|
+
const index = trimmed.indexOf(":");
|
|
534
|
+
if (index === -1) continue;
|
|
535
|
+
const key = trimmed.slice(0, index).trim();
|
|
536
|
+
const value = trimmed.slice(index + 1).trim();
|
|
537
|
+
if (key === "" || value === "") continue;
|
|
538
|
+
const existing = fields[key];
|
|
539
|
+
if (existing === void 0) fields[key] = value;
|
|
540
|
+
else if (Array.isArray(existing)) existing.push(value);
|
|
541
|
+
else fields[key] = [existing, value];
|
|
542
|
+
}
|
|
543
|
+
return fields;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Look up a field by name, ignoring case, returning the first value.
|
|
547
|
+
*/
|
|
548
|
+
function getFieldCaseInsensitive(fields, name) {
|
|
549
|
+
const lower = name.toLowerCase();
|
|
550
|
+
for (const [key, value] of Object.entries(fields)) if (key.toLowerCase() === lower) return Array.isArray(value) ? value[0] : value;
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Parse a referral value (e.g. `whois.example.com`, `whois://host:43`) into a
|
|
554
|
+
* host and port.
|
|
555
|
+
*/
|
|
556
|
+
function parseReferralValue(value) {
|
|
557
|
+
const [host, portString] = value.trim().replace(/^[a-z]+:\/\//i, "").split(/[/\s]/)[0].split(":");
|
|
558
|
+
if (host === "") return;
|
|
559
|
+
const port = portString === void 0 ? WHOIS_PORT : Number.parseInt(portString, 10);
|
|
560
|
+
return {
|
|
561
|
+
host,
|
|
562
|
+
port: Number.isNaN(port) ? WHOIS_PORT : port
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Extract the first referral server from a parsed response, if any.
|
|
567
|
+
*/
|
|
568
|
+
function extractReferral(fields) {
|
|
569
|
+
for (const key of REFERRAL_KEYS) {
|
|
570
|
+
const value = getFieldCaseInsensitive(fields, key);
|
|
571
|
+
if (value !== void 0) return parseReferralValue(value);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Merge the fields of one hop into an accumulator, grouping repeated keys into
|
|
576
|
+
* arrays so no data is lost across hops.
|
|
577
|
+
*/
|
|
578
|
+
function mergeFields(target, source) {
|
|
579
|
+
for (const [key, value] of Object.entries(source)) {
|
|
580
|
+
const existing = target[key];
|
|
581
|
+
if (existing === void 0) {
|
|
582
|
+
target[key] = value;
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
const base = Array.isArray(existing) ? existing : [existing];
|
|
586
|
+
const incoming = Array.isArray(value) ? value : [value];
|
|
587
|
+
target[key] = [...base, ...incoming];
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Resolve the configured follow option into a concrete referral depth.
|
|
592
|
+
*/
|
|
593
|
+
function resolveFollowDepth(follow) {
|
|
594
|
+
if (follow === void 0 || follow === true) return DEFAULT_FOLLOW_DEPTH;
|
|
595
|
+
if (follow === false) return 0;
|
|
596
|
+
return follow;
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* Build the cache key used to remember which server is authoritative for a query.
|
|
600
|
+
*/
|
|
601
|
+
function serverCacheKey(normalized, type) {
|
|
602
|
+
if (type === "domain") return `whois:server:${normalized.slice(normalized.lastIndexOf(".") + 1)}`;
|
|
603
|
+
return `whois:server:${type}:${normalized}`;
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Resolve the first server to query for a normalized query, using (in order) an
|
|
607
|
+
* explicit override, the cached mapping, or a live IANA bootstrap lookup.
|
|
608
|
+
*/
|
|
609
|
+
async function resolveBootstrapServer(normalized, type, options) {
|
|
610
|
+
if (options.server !== void 0) return {
|
|
611
|
+
host: options.server,
|
|
612
|
+
port: options.port ?? WHOIS_PORT
|
|
613
|
+
};
|
|
614
|
+
const cache = options.cache;
|
|
615
|
+
const key = serverCacheKey(normalized, type);
|
|
616
|
+
if (cache) {
|
|
617
|
+
const cached = await cache.get(key);
|
|
618
|
+
if (cached) return cached;
|
|
619
|
+
}
|
|
620
|
+
const refer = getFieldCaseInsensitive(parseWhois(await queryWhoisServer({
|
|
621
|
+
/* v8 ignore next -- @preserve the real IANA host is only used off the test harness */
|
|
622
|
+
host: options.bootstrapServer ?? IANA_WHOIS_SERVER,
|
|
623
|
+
port: options.bootstrapPort ?? WHOIS_PORT,
|
|
624
|
+
query: normalized,
|
|
625
|
+
timeout: options.timeout,
|
|
626
|
+
encoding: options.encoding
|
|
627
|
+
})), "refer");
|
|
628
|
+
const referral = refer === void 0 ? void 0 : parseReferralValue(refer);
|
|
629
|
+
if (referral === void 0) throw new Error(`No WHOIS server found for "${normalized}" via IANA`);
|
|
630
|
+
if (cache) await cache.set(key, referral);
|
|
631
|
+
return referral;
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* Run the full WHOIS pipeline: resolve the authoritative server, query it,
|
|
635
|
+
* follow referrals up to the configured depth, and combine the results.
|
|
636
|
+
*/
|
|
637
|
+
async function runWhois(normalized, type, options) {
|
|
638
|
+
let remaining = resolveFollowDepth(options.follow);
|
|
639
|
+
const visited = /* @__PURE__ */ new Set();
|
|
640
|
+
const hops = [];
|
|
641
|
+
let next = await resolveBootstrapServer(normalized, type, options);
|
|
642
|
+
while (next !== void 0) {
|
|
643
|
+
const id = `${next.host.toLowerCase()}:${next.port}`;
|
|
644
|
+
if (visited.has(id)) break;
|
|
645
|
+
visited.add(id);
|
|
646
|
+
const raw = await queryWhoisServer({
|
|
647
|
+
host: next.host,
|
|
648
|
+
port: next.port,
|
|
649
|
+
query: normalized,
|
|
650
|
+
queryPrefix: options.queryPrefix,
|
|
651
|
+
timeout: options.timeout,
|
|
652
|
+
encoding: options.encoding
|
|
653
|
+
});
|
|
654
|
+
const fields = parseWhois(raw);
|
|
655
|
+
hops.push({
|
|
656
|
+
server: next.host,
|
|
657
|
+
port: next.port,
|
|
658
|
+
raw,
|
|
659
|
+
fields
|
|
660
|
+
});
|
|
661
|
+
if (remaining <= 0) break;
|
|
662
|
+
const referral = extractReferral(fields);
|
|
663
|
+
if (referral === void 0) break;
|
|
664
|
+
remaining -= 1;
|
|
665
|
+
next = referral;
|
|
666
|
+
}
|
|
667
|
+
const mergedFields = Object.create(null);
|
|
668
|
+
for (const hop of hops) mergeFields(mergedFields, hop.fields);
|
|
669
|
+
return {
|
|
670
|
+
query: normalized,
|
|
671
|
+
type,
|
|
672
|
+
server: hops[hops.length - 1].server,
|
|
673
|
+
raw: hops.map((hop) => hop.raw).join("\n\n"),
|
|
674
|
+
fields: mergedFields,
|
|
675
|
+
hops
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Perform a WHOIS lookup for a domain, IP address, or ASN and return both the
|
|
680
|
+
* raw text and parsed JSON fields. The authoritative server is discovered
|
|
681
|
+
* dynamically through IANA (and cached), and registry → registrar referrals are
|
|
682
|
+
* followed by default. When a cache is provided, results are cached and
|
|
683
|
+
* concurrent identical lookups are coalesced.
|
|
684
|
+
*
|
|
685
|
+
* @param {string} query The domain, URL, IP address, or ASN to look up.
|
|
686
|
+
* @param {WhoisOptions} options Optional lookup options.
|
|
687
|
+
* @returns {Promise<WhoisResult>} The raw text and parsed fields.
|
|
688
|
+
*/
|
|
689
|
+
async function whois(query, options = {}) {
|
|
690
|
+
const normalized = normalizeWhoisQuery(query);
|
|
691
|
+
const type = detectQueryType(normalized);
|
|
692
|
+
const cache = options.caching === false ? void 0 : options.cache;
|
|
693
|
+
const effectiveOptions = {
|
|
694
|
+
...options,
|
|
695
|
+
cache
|
|
696
|
+
};
|
|
697
|
+
if (!cache) return runWhois(normalized, type, effectiveOptions);
|
|
698
|
+
const cacheKey = `whois:${normalized}:${JSON.stringify({
|
|
699
|
+
follow: resolveFollowDepth(options.follow),
|
|
700
|
+
server: options.server,
|
|
701
|
+
port: options.port,
|
|
702
|
+
bootstrapServer: options.bootstrapServer,
|
|
703
|
+
bootstrapPort: options.bootstrapPort,
|
|
704
|
+
queryPrefix: options.queryPrefix,
|
|
705
|
+
encoding: options.encoding
|
|
706
|
+
})}`;
|
|
707
|
+
return coalesceAsync(`net:${cacheKey}`, async () => {
|
|
708
|
+
const existing = await cache.get(cacheKey);
|
|
709
|
+
if (existing) return existing;
|
|
710
|
+
const result = await runWhois(normalized, type, effectiveOptions);
|
|
711
|
+
await cache.set(cacheKey, result, options.ttl);
|
|
712
|
+
return result;
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* Perform a WHOIS lookup and return only the raw text response.
|
|
717
|
+
*
|
|
718
|
+
* @param {string} query The domain, URL, IP address, or ASN to look up.
|
|
719
|
+
* @param {WhoisOptions} options Optional lookup options.
|
|
720
|
+
* @returns {Promise<string>} The raw WHOIS text.
|
|
721
|
+
*/
|
|
722
|
+
async function whoisRaw(query, options) {
|
|
723
|
+
return (await whois(query, options)).raw;
|
|
724
|
+
}
|
|
725
|
+
//#endregion
|
|
726
|
+
//#region src/rdap.ts
|
|
727
|
+
/**
|
|
728
|
+
* The base URL of the IANA RDAP bootstrap registries.
|
|
729
|
+
* @see https://data.iana.org/rdap/
|
|
730
|
+
*/
|
|
731
|
+
const IANA_RDAP_BOOTSTRAP = "https://data.iana.org/rdap";
|
|
732
|
+
/**
|
|
733
|
+
* Remove a trailing slash from a URL, if present.
|
|
734
|
+
*/
|
|
735
|
+
function trimTrailingSlash(url) {
|
|
736
|
+
return url.endsWith("/") ? url.slice(0, -1) : url;
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Ensure a URL ends with a single trailing slash.
|
|
740
|
+
*/
|
|
741
|
+
function ensureTrailingSlash(url) {
|
|
742
|
+
return url.endsWith("/") ? url : `${url}/`;
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* Map a query type to the IANA RDAP bootstrap registry file name.
|
|
746
|
+
*/
|
|
747
|
+
function bootstrapFileForType(type) {
|
|
748
|
+
switch (type) {
|
|
749
|
+
case "ipv4": return "ipv4.json";
|
|
750
|
+
case "ipv6": return "ipv6.json";
|
|
751
|
+
case "asn": return "asn.json";
|
|
752
|
+
default: return "dns.json";
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* Map a query type to the RDAP path segment used to look it up.
|
|
757
|
+
*/
|
|
758
|
+
function rdapPathForType(type) {
|
|
759
|
+
switch (type) {
|
|
760
|
+
case "ipv4":
|
|
761
|
+
case "ipv6": return "ip";
|
|
762
|
+
case "asn": return "autnum";
|
|
763
|
+
default: return "domain";
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Build the fetch options used for RDAP requests, including the cache instance
|
|
768
|
+
* when caching is enabled.
|
|
769
|
+
*/
|
|
770
|
+
function buildFetchOptions(headers, cache) {
|
|
771
|
+
const fetchOptions = {
|
|
772
|
+
headers: {
|
|
773
|
+
accept: "application/rdap+json",
|
|
774
|
+
...headers
|
|
775
|
+
},
|
|
776
|
+
httpCachePolicy: false
|
|
777
|
+
};
|
|
778
|
+
if (cache) fetchOptions.cache = cache;
|
|
779
|
+
return fetchOptions;
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Convert an IPv6 address (including `::` compression) to a BigInt.
|
|
783
|
+
*/
|
|
784
|
+
function ipv6ToBigInt(ip) {
|
|
785
|
+
const [head, tail] = ip.split("::");
|
|
786
|
+
const headParts = head ? head.split(":") : [];
|
|
787
|
+
const tailParts = tail ? tail.split(":") : [];
|
|
788
|
+
const missing = Math.max(0, 8 - headParts.length - tailParts.length);
|
|
789
|
+
return [
|
|
790
|
+
...headParts,
|
|
791
|
+
...Array(missing).fill("0"),
|
|
792
|
+
...tailParts
|
|
793
|
+
].reduce((accumulator, part) => (accumulator << 16n) + BigInt(Number.parseInt(part, 16)), 0n);
|
|
794
|
+
}
|
|
795
|
+
/**
|
|
796
|
+
* Convert an IP address to a BigInt for range comparison.
|
|
797
|
+
*/
|
|
798
|
+
function ipToBigInt(ip, type) {
|
|
799
|
+
if (type === "ipv4") return ip.split(".").reduce((accumulator, part) => (accumulator << 8n) + BigInt(Number(part)), 0n);
|
|
800
|
+
return ipv6ToBigInt(ip);
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Determine whether an IP address falls within a CIDR block.
|
|
804
|
+
*/
|
|
805
|
+
function ipInCidr(ip, cidr, type) {
|
|
806
|
+
const [network, prefixString] = cidr.split("/");
|
|
807
|
+
const bits = type === "ipv4" ? 32 : 128;
|
|
808
|
+
const shift = BigInt(bits - (prefixString ? Number.parseInt(prefixString, 10) : bits));
|
|
809
|
+
return ipToBigInt(ip, type) >> shift === ipToBigInt(network, type) >> shift;
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Determine whether an ASN falls within an IANA bootstrap range (e.g. `36864-37887`).
|
|
813
|
+
*/
|
|
814
|
+
function asnInRange(asn, range) {
|
|
815
|
+
const [startString, endString] = range.split("-");
|
|
816
|
+
const start = Number.parseInt(startString, 10);
|
|
817
|
+
return asn >= start && asn <= (endString ? Number.parseInt(endString, 10) : start);
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* Determine whether a bootstrap service's keys match the query.
|
|
821
|
+
*/
|
|
822
|
+
function matchesService(type, normalized, keys) {
|
|
823
|
+
if (type === "domain") {
|
|
824
|
+
const tld = normalized.slice(normalized.lastIndexOf(".") + 1);
|
|
825
|
+
return keys.some((key) => key.toLowerCase() === tld);
|
|
826
|
+
}
|
|
827
|
+
if (type === "asn") {
|
|
828
|
+
const asn = Number.parseInt(normalized.replace(/^as/i, ""), 10);
|
|
829
|
+
return keys.some((range) => asnInRange(asn, range));
|
|
830
|
+
}
|
|
831
|
+
return keys.some((cidr) => ipInCidr(normalized, cidr, type));
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Find the RDAP base URL for a query within a bootstrap registry. The first URL
|
|
835
|
+
* advertised for the matching service is used (IANA lists the preferred HTTPS
|
|
836
|
+
* endpoint first).
|
|
837
|
+
*/
|
|
838
|
+
function findRdapBase(bootstrap, type, normalized) {
|
|
839
|
+
for (const [keys, urls] of bootstrap.services) if (matchesService(type, normalized, keys)) return urls[0];
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Resolve the RDAP base URL for a query, using an explicit override or a (cached)
|
|
843
|
+
* IANA bootstrap lookup.
|
|
844
|
+
*/
|
|
845
|
+
async function resolveRdapBase(normalized, type, options, cache) {
|
|
846
|
+
if (options.server !== void 0) return options.server;
|
|
847
|
+
const url = `${trimTrailingSlash(options.bootstrapUrl ?? IANA_RDAP_BOOTSTRAP)}/${bootstrapFileForType(type)}`;
|
|
848
|
+
const response = await fetch(url, buildFetchOptions(void 0, cache));
|
|
849
|
+
if (!response.ok) throw new Error(`Failed to fetch RDAP bootstrap from ${url}: ${response.status} ${response.statusText}`);
|
|
850
|
+
const rdapBase = findRdapBase(JSON.parse(await response.text()), type, normalized);
|
|
851
|
+
if (rdapBase === void 0) throw new Error(`No RDAP server found for "${normalized}"`);
|
|
852
|
+
return rdapBase;
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Run the full RDAP pipeline: resolve the base URL, query the endpoint, and parse
|
|
856
|
+
* the JSON response.
|
|
857
|
+
*/
|
|
858
|
+
async function runRdap(normalized, type, options, cache) {
|
|
859
|
+
const base = await resolveRdapBase(normalized, type, options, cache);
|
|
860
|
+
const key = type === "asn" ? normalized.replace(/^as/i, "") : normalized;
|
|
861
|
+
const response = await fetch(`${ensureTrailingSlash(base)}${rdapPathForType(type)}/${key}`, buildFetchOptions(options.headers, void 0));
|
|
862
|
+
const raw = await response.text();
|
|
863
|
+
if (!response.ok) throw new Error(`RDAP query for "${normalized}" failed with status ${response.status}`);
|
|
864
|
+
let data;
|
|
865
|
+
try {
|
|
866
|
+
data = JSON.parse(raw);
|
|
867
|
+
} catch {
|
|
868
|
+
throw new Error(`RDAP response for "${normalized}" was not valid JSON`);
|
|
869
|
+
}
|
|
870
|
+
return {
|
|
871
|
+
query: normalized,
|
|
872
|
+
type,
|
|
873
|
+
server: base,
|
|
874
|
+
raw,
|
|
875
|
+
data
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* Perform an RDAP lookup for a domain, IP address, or ASN and return both the raw
|
|
880
|
+
* JSON text and the parsed object. The RDAP server is discovered dynamically
|
|
881
|
+
* through the IANA bootstrap registries (fetched through the package's cached
|
|
882
|
+
* fetch). When a cache is provided, results are cached and concurrent identical
|
|
883
|
+
* lookups are coalesced.
|
|
884
|
+
*
|
|
885
|
+
* @param {string} query The domain, URL, IP address, or ASN to look up.
|
|
886
|
+
* @param {RdapOptions} options Optional lookup options.
|
|
887
|
+
* @returns {Promise<RdapResult>} The raw JSON text and parsed data.
|
|
888
|
+
*/
|
|
889
|
+
async function rdap(query, options = {}) {
|
|
890
|
+
const normalized = normalizeWhoisQuery(query);
|
|
891
|
+
const type = detectQueryType(normalized);
|
|
892
|
+
const cache = options.caching === false ? void 0 : options.cache;
|
|
893
|
+
if (!cache) return runRdap(normalized, type, options, void 0);
|
|
894
|
+
const cacheKey = `rdap:${normalized}:${JSON.stringify({
|
|
895
|
+
server: options.server,
|
|
896
|
+
bootstrapUrl: options.bootstrapUrl,
|
|
897
|
+
headers: options.headers
|
|
898
|
+
})}`;
|
|
899
|
+
return coalesceAsync(`net:${cacheKey}`, async () => {
|
|
900
|
+
const existing = await cache.get(cacheKey);
|
|
901
|
+
if (existing) return existing;
|
|
902
|
+
const result = await runRdap(normalized, type, options, cache);
|
|
903
|
+
await cache.set(cacheKey, result, options.ttl);
|
|
904
|
+
return result;
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
//#endregion
|
|
908
|
+
//#region src/index.ts
|
|
909
|
+
var CacheableNet = class extends Hookified {
|
|
910
|
+
_cache = new Cacheable();
|
|
911
|
+
_httpCachePolicy = true;
|
|
912
|
+
_stringify = JSON.stringify;
|
|
913
|
+
_parse = JSON.parse;
|
|
914
|
+
constructor(options) {
|
|
915
|
+
super(options);
|
|
916
|
+
if (options?.cache) this._cache = options.cache instanceof Cacheable ? options.cache : new Cacheable(options.cache);
|
|
917
|
+
if (options?.httpCachePolicy !== void 0) this._httpCachePolicy = options.httpCachePolicy;
|
|
918
|
+
if (options?.stringify) this._stringify = options?.stringify;
|
|
919
|
+
if (options?.parse) this._parse = options?.parse;
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
922
|
+
* Get the stringify function used for converting objects to strings.
|
|
923
|
+
* @returns {StringifyType} The current stringify function
|
|
924
|
+
*/
|
|
925
|
+
get stringify() {
|
|
926
|
+
return this._stringify;
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Set the stringify function for converting objects to strings.
|
|
930
|
+
* @param {StringifyType} value - The stringify function to use
|
|
931
|
+
*/
|
|
932
|
+
set stringify(value) {
|
|
933
|
+
this._stringify = value;
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* Get the parse function used for converting strings to objects.
|
|
937
|
+
* @returns {ParseType} The current parse function
|
|
938
|
+
*/
|
|
939
|
+
get parse() {
|
|
940
|
+
return this._parse;
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* Set the parse function for converting strings to objects.
|
|
944
|
+
* @param {ParseType} value - The parse function to use
|
|
945
|
+
*/
|
|
946
|
+
set parse(value) {
|
|
947
|
+
this._parse = value;
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* Get the Cacheable instance used for caching fetch operations.
|
|
951
|
+
* @returns {Cacheable} The current Cacheable instance
|
|
952
|
+
*/
|
|
953
|
+
get cache() {
|
|
954
|
+
return this._cache;
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* Set the Cacheable instance for caching fetch operations.
|
|
958
|
+
* @param {Cacheable} value - The Cacheable instance to use for caching
|
|
959
|
+
*/
|
|
960
|
+
set cache(value) {
|
|
961
|
+
this._cache = value;
|
|
962
|
+
}
|
|
963
|
+
/**
|
|
964
|
+
* Get the current HTTP cache policy setting.
|
|
965
|
+
* @returns {boolean} Whether HTTP cache semantics are enabled
|
|
966
|
+
*/
|
|
967
|
+
get httpCachePolicy() {
|
|
968
|
+
return this._httpCachePolicy;
|
|
969
|
+
}
|
|
970
|
+
/**
|
|
971
|
+
* Set whether to use HTTP cache semantics.
|
|
972
|
+
* @param {boolean} value - Enable or disable HTTP cache semantics
|
|
973
|
+
*/
|
|
974
|
+
set httpCachePolicy(value) {
|
|
975
|
+
this._httpCachePolicy = value;
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* Fetch data from a URL with optional request options. Will use the cache that is already set in the instance.
|
|
979
|
+
*
|
|
980
|
+
* When `httpCachePolicy` is enabled (default), cache entries will have their TTL
|
|
981
|
+
* set based on HTTP cache headers (e.g., Cache-Control: max-age). When disabled,
|
|
982
|
+
* the default TTL from the Cacheable instance is used.
|
|
983
|
+
*
|
|
984
|
+
* @param {string} url The URL to fetch.
|
|
985
|
+
* @param {Omit<FetchOptions, "cache">} options Optional request options.
|
|
986
|
+
* @returns {Promise<FetchResponse>} The response from the fetch.
|
|
987
|
+
*/
|
|
988
|
+
async fetch(url, options) {
|
|
989
|
+
return fetch(url, {
|
|
990
|
+
...options,
|
|
991
|
+
cache: this._cache,
|
|
992
|
+
httpCachePolicy: this._httpCachePolicy
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* Perform a GET request to a URL with optional request options. By default caching is enabled on all requests. To
|
|
997
|
+
* disable set `options.caching` to false.
|
|
998
|
+
* @param {string} url The URL to fetch.
|
|
999
|
+
* @param {NetFetchOptions} options Optional request options (method will be set to GET).
|
|
1000
|
+
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
|
|
1001
|
+
*/
|
|
1002
|
+
async get(url, options) {
|
|
1003
|
+
const fetchOptions = {
|
|
1004
|
+
...options,
|
|
1005
|
+
cache: this._cache,
|
|
1006
|
+
httpCachePolicy: this._httpCachePolicy,
|
|
1007
|
+
method: "GET"
|
|
1008
|
+
};
|
|
1009
|
+
if (options?.caching !== void 0) delete fetchOptions.cache;
|
|
1010
|
+
const response = await fetch(url, fetchOptions);
|
|
1011
|
+
const text = await response.text();
|
|
1012
|
+
let data;
|
|
1013
|
+
const parseFn = options?.parse || this._parse;
|
|
1014
|
+
try {
|
|
1015
|
+
data = parseFn(text);
|
|
1016
|
+
} catch {
|
|
1017
|
+
data = text;
|
|
1018
|
+
}
|
|
1019
|
+
const newResponse = makeResponse(text, {
|
|
1020
|
+
status: response.status,
|
|
1021
|
+
statusText: response.statusText,
|
|
1022
|
+
headers: response.headers
|
|
1023
|
+
}, {
|
|
1024
|
+
url: response.url,
|
|
1025
|
+
redirected: response.redirected,
|
|
1026
|
+
type: response.type
|
|
1027
|
+
});
|
|
1028
|
+
return {
|
|
1029
|
+
data,
|
|
1030
|
+
response: newResponse
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* Perform a POST request to a URL with data and optional request options. By default caching is not enabled. To enable it
|
|
1035
|
+
* set `options.caching` to true. Note, setting caching to tru means it will not post if the data is the same.
|
|
1036
|
+
* @param {string} url The URL to fetch.
|
|
1037
|
+
* @param {unknown} data The data to send in the request body.
|
|
1038
|
+
* @param {Omit<NetFetchOptions, "method" | "body" >} options Optional request options (method and body will be set).
|
|
1039
|
+
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
|
|
1040
|
+
*/
|
|
1041
|
+
async post(url, data, options) {
|
|
1042
|
+
let body;
|
|
1043
|
+
const headers = { ...options?.headers };
|
|
1044
|
+
if (typeof data === "string") body = data;
|
|
1045
|
+
else if (data instanceof FormData || data instanceof URLSearchParams || data instanceof Blob) body = data;
|
|
1046
|
+
else {
|
|
1047
|
+
body = (options?.stringify || this._stringify)(data);
|
|
1048
|
+
this.setContentType(headers);
|
|
1049
|
+
}
|
|
1050
|
+
const fetchOptions = {
|
|
1051
|
+
...options,
|
|
1052
|
+
headers,
|
|
1053
|
+
body,
|
|
1054
|
+
httpCachePolicy: this._httpCachePolicy,
|
|
1055
|
+
method: "POST"
|
|
1056
|
+
};
|
|
1057
|
+
if (options?.caching === true) fetchOptions.cache = this._cache;
|
|
1058
|
+
const response = await fetch(url, fetchOptions);
|
|
1059
|
+
const text = await response.text();
|
|
1060
|
+
let responseData;
|
|
1061
|
+
const parseFn = options?.parse || this._parse;
|
|
1062
|
+
try {
|
|
1063
|
+
responseData = parseFn(text);
|
|
1064
|
+
} catch {
|
|
1065
|
+
responseData = text;
|
|
1066
|
+
}
|
|
1067
|
+
const newResponse = makeResponse(text, {
|
|
1068
|
+
status: response.status,
|
|
1069
|
+
statusText: response.statusText,
|
|
1070
|
+
headers: response.headers
|
|
1071
|
+
}, {
|
|
1072
|
+
url: response.url,
|
|
1073
|
+
redirected: response.redirected,
|
|
1074
|
+
type: response.type
|
|
1075
|
+
});
|
|
1076
|
+
return {
|
|
1077
|
+
data: responseData,
|
|
1078
|
+
response: newResponse
|
|
1079
|
+
};
|
|
1080
|
+
}
|
|
1081
|
+
/**
|
|
1082
|
+
* Perform a HEAD request to a URL with optional request options. By default caching is enabled on all requests. To
|
|
1083
|
+
* disable set `options.caching` to false.
|
|
1084
|
+
* @param {string} url The URL to fetch.
|
|
1085
|
+
* @param {NetFetchOptions} options Optional request options (method will be set to HEAD).
|
|
1086
|
+
* @returns {Promise<FetchResponse>} The response from the fetch (no body).
|
|
1087
|
+
*/
|
|
1088
|
+
async head(url, options) {
|
|
1089
|
+
const fetchOptions = {
|
|
1090
|
+
...options,
|
|
1091
|
+
cache: this._cache,
|
|
1092
|
+
httpCachePolicy: this._httpCachePolicy,
|
|
1093
|
+
method: "HEAD"
|
|
1094
|
+
};
|
|
1095
|
+
if (options?.caching !== void 0 && !options.caching) delete fetchOptions.cache;
|
|
1096
|
+
return await fetch(url, fetchOptions);
|
|
1097
|
+
}
|
|
1098
|
+
/**
|
|
1099
|
+
* Perform a PUT request to a URL with data and optional request options. By default caching is not enabled. To enable it
|
|
1100
|
+
* set `options.caching` to true. Note, setting caching to true means it will not put if the data is the same.
|
|
1101
|
+
* @param {string} url The URL to fetch.
|
|
1102
|
+
* @param {unknown} data The data to send in the request body.
|
|
1103
|
+
* @param {Omit<NetFetchOptions, 'method' | 'body'>} options Optional request options (method and body will be set).
|
|
1104
|
+
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
|
|
1105
|
+
*/
|
|
1106
|
+
async put(url, data, options) {
|
|
1107
|
+
let body;
|
|
1108
|
+
const headers = { ...options?.headers };
|
|
1109
|
+
if (typeof data === "string") body = data;
|
|
1110
|
+
else if (data instanceof FormData || data instanceof URLSearchParams || data instanceof Blob) body = data;
|
|
1111
|
+
else {
|
|
1112
|
+
body = (options?.stringify || this._stringify)(data);
|
|
1113
|
+
this.setContentType(headers);
|
|
1114
|
+
}
|
|
1115
|
+
const fetchOptions = {
|
|
1116
|
+
...options,
|
|
1117
|
+
headers,
|
|
1118
|
+
body,
|
|
1119
|
+
httpCachePolicy: this._httpCachePolicy,
|
|
1120
|
+
method: "PUT"
|
|
1121
|
+
};
|
|
1122
|
+
if (options?.caching === true) fetchOptions.cache = this._cache;
|
|
1123
|
+
const response = await fetch(url, fetchOptions);
|
|
1124
|
+
const text = await response.text();
|
|
1125
|
+
let responseData;
|
|
1126
|
+
const parseFn = options?.parse || this._parse;
|
|
1127
|
+
try {
|
|
1128
|
+
responseData = parseFn(text);
|
|
1129
|
+
} catch {
|
|
1130
|
+
responseData = text;
|
|
1131
|
+
}
|
|
1132
|
+
const newResponse = makeResponse(text, {
|
|
1133
|
+
status: response.status,
|
|
1134
|
+
statusText: response.statusText,
|
|
1135
|
+
headers: response.headers
|
|
1136
|
+
}, {
|
|
1137
|
+
url: response.url,
|
|
1138
|
+
redirected: response.redirected,
|
|
1139
|
+
type: response.type
|
|
1140
|
+
});
|
|
1141
|
+
return {
|
|
1142
|
+
data: responseData,
|
|
1143
|
+
response: newResponse
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
/**
|
|
1147
|
+
* Perform a PATCH request to a URL with data and optional request options. By default caching is not enabled. To enable it
|
|
1148
|
+
* set `options.caching` to true. Note, setting caching to true means it will not patch if the data is the same.
|
|
1149
|
+
* @param {string} url The URL to fetch.
|
|
1150
|
+
* @param {unknown} data The data to send in the request body.
|
|
1151
|
+
* @param {Omit<NetFetchOptions, 'method' | 'body'>} options Optional request options (method and body will be set).
|
|
1152
|
+
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
|
|
1153
|
+
*/
|
|
1154
|
+
async patch(url, data, options) {
|
|
1155
|
+
let body;
|
|
1156
|
+
const headers = { ...options?.headers };
|
|
1157
|
+
if (typeof data === "string") body = data;
|
|
1158
|
+
else if (data instanceof FormData || data instanceof URLSearchParams || data instanceof Blob) body = data;
|
|
1159
|
+
else {
|
|
1160
|
+
body = (options?.stringify || this._stringify)(data);
|
|
1161
|
+
this.setContentType(headers);
|
|
1162
|
+
}
|
|
1163
|
+
const fetchOptions = {
|
|
1164
|
+
...options,
|
|
1165
|
+
headers,
|
|
1166
|
+
body,
|
|
1167
|
+
httpCachePolicy: this._httpCachePolicy,
|
|
1168
|
+
method: "PATCH"
|
|
1169
|
+
};
|
|
1170
|
+
if (options?.caching === true) fetchOptions.cache = this._cache;
|
|
1171
|
+
const response = await fetch(url, fetchOptions);
|
|
1172
|
+
const text = await response.text();
|
|
1173
|
+
let responseData;
|
|
1174
|
+
const parseFn = options?.parse || this._parse;
|
|
1175
|
+
try {
|
|
1176
|
+
responseData = parseFn(text);
|
|
1177
|
+
} catch {
|
|
1178
|
+
responseData = text;
|
|
1179
|
+
}
|
|
1180
|
+
const newResponse = makeResponse(text, {
|
|
1181
|
+
status: response.status,
|
|
1182
|
+
statusText: response.statusText,
|
|
1183
|
+
headers: response.headers
|
|
1184
|
+
}, {
|
|
1185
|
+
url: response.url,
|
|
1186
|
+
redirected: response.redirected,
|
|
1187
|
+
type: response.type
|
|
1188
|
+
});
|
|
1189
|
+
return {
|
|
1190
|
+
data: responseData,
|
|
1191
|
+
response: newResponse
|
|
1192
|
+
};
|
|
1193
|
+
}
|
|
1194
|
+
/**
|
|
1195
|
+
* Perform a DELETE request to a URL with optional data and request options. By default caching is not enabled. To enable it
|
|
1196
|
+
* set `options.caching` to true. Note, setting caching to true means it will not delete if the data is the same.
|
|
1197
|
+
* @param {string} url The URL to fetch.
|
|
1198
|
+
* @param {unknown} data Optional data to send in the request body.
|
|
1199
|
+
* @param {Omit<NetFetchOptions, 'method' | 'body'>} options Optional request options (method and body will be set).
|
|
1200
|
+
* @returns {Promise<DataResponse<T>>} The typed data and response from the fetch.
|
|
1201
|
+
*/
|
|
1202
|
+
async delete(url, data, options) {
|
|
1203
|
+
let body;
|
|
1204
|
+
const headers = { ...options?.headers };
|
|
1205
|
+
if (data !== void 0) if (typeof data === "string") body = data;
|
|
1206
|
+
else if (data instanceof FormData || data instanceof URLSearchParams || data instanceof Blob) body = data;
|
|
1207
|
+
else {
|
|
1208
|
+
body = (options?.stringify || this._stringify)(data);
|
|
1209
|
+
this.setContentType(headers);
|
|
1210
|
+
}
|
|
1211
|
+
const fetchOptions = {
|
|
1212
|
+
...options,
|
|
1213
|
+
headers,
|
|
1214
|
+
body,
|
|
1215
|
+
httpCachePolicy: this._httpCachePolicy,
|
|
1216
|
+
method: "DELETE"
|
|
1217
|
+
};
|
|
1218
|
+
if (options?.caching === true) fetchOptions.cache = this._cache;
|
|
1219
|
+
const response = await fetch(url, fetchOptions);
|
|
1220
|
+
const text = await response.text();
|
|
1221
|
+
let responseData;
|
|
1222
|
+
const parseFn = options?.parse || this._parse;
|
|
1223
|
+
try {
|
|
1224
|
+
responseData = parseFn(text);
|
|
1225
|
+
} catch {
|
|
1226
|
+
responseData = text;
|
|
1227
|
+
}
|
|
1228
|
+
const newResponse = makeResponse(text, {
|
|
1229
|
+
status: response.status,
|
|
1230
|
+
statusText: response.statusText,
|
|
1231
|
+
headers: response.headers
|
|
1232
|
+
}, {
|
|
1233
|
+
url: response.url,
|
|
1234
|
+
redirected: response.redirected,
|
|
1235
|
+
type: response.type
|
|
1236
|
+
});
|
|
1237
|
+
return {
|
|
1238
|
+
data: responseData,
|
|
1239
|
+
response: newResponse
|
|
1240
|
+
};
|
|
1241
|
+
}
|
|
1242
|
+
/**
|
|
1243
|
+
* Perform a WHOIS lookup for a domain, IP address, or ASN, returning both the
|
|
1244
|
+
* raw text and parsed JSON fields. Uses the instance cache so repeated lookups
|
|
1245
|
+
* are served from cache and concurrent identical lookups are coalesced. To
|
|
1246
|
+
* disable caching for a single lookup, set `options.caching` to false.
|
|
1247
|
+
* @param {string} query The domain, URL, IP address, or ASN to look up.
|
|
1248
|
+
* @param {WhoisOptions} options Optional lookup options.
|
|
1249
|
+
* @returns {Promise<WhoisResult>} The raw text and parsed fields.
|
|
1250
|
+
*/
|
|
1251
|
+
async whois(query, options) {
|
|
1252
|
+
const whoisOptions = {
|
|
1253
|
+
...options,
|
|
1254
|
+
cache: this._cache
|
|
1255
|
+
};
|
|
1256
|
+
if (options?.caching === false) delete whoisOptions.cache;
|
|
1257
|
+
return whois(query, whoisOptions);
|
|
1258
|
+
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Perform an RDAP lookup for a domain, IP address, or ASN, returning both the
|
|
1261
|
+
* raw JSON text and the parsed object. Uses the instance cache so repeated
|
|
1262
|
+
* lookups are served from cache and concurrent identical lookups are
|
|
1263
|
+
* coalesced. To disable caching for a single lookup, set `options.caching` to
|
|
1264
|
+
* false.
|
|
1265
|
+
* @param {string} query The domain, URL, IP address, or ASN to look up.
|
|
1266
|
+
* @param {RdapOptions} options Optional lookup options.
|
|
1267
|
+
* @returns {Promise<RdapResult>} The raw JSON text and parsed data.
|
|
1268
|
+
*/
|
|
1269
|
+
async rdap(query, options) {
|
|
1270
|
+
const rdapOptions = {
|
|
1271
|
+
...options,
|
|
1272
|
+
cache: this._cache
|
|
1273
|
+
};
|
|
1274
|
+
if (options?.caching === false) delete rdapOptions.cache;
|
|
1275
|
+
return rdap(query, rdapOptions);
|
|
1276
|
+
}
|
|
1277
|
+
/**
|
|
1278
|
+
* Sets the Content-Type header if not already set.
|
|
1279
|
+
* Checks both "Content-Type" and "content-type" to handle case variations.
|
|
1280
|
+
* @param headers - The headers object to modify
|
|
1281
|
+
* @param contentType - The content type to set (defaults to "application/json")
|
|
1282
|
+
* @private
|
|
1283
|
+
*/
|
|
1284
|
+
setContentType(headers, contentType = "application/json") {
|
|
1285
|
+
/* v8 ignore next -- @preserve */
|
|
1286
|
+
if (!headers["Content-Type"] && !headers["content-type"]) headers["Content-Type"] = contentType;
|
|
1287
|
+
}
|
|
1288
|
+
};
|
|
1289
|
+
const Net = CacheableNet;
|
|
1290
|
+
//#endregion
|
|
1291
|
+
export { CacheableNet, Net, del, detectQueryType, fetch, get, head, normalizeWhoisQuery, parseWhois, patch, post, queryWhoisServer, rdap, whois, whoisRaw };
|