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