@cacheable/net 2.0.1 → 2.0.2

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 +1,719 @@
1
- "use strict";var v=Object.create;var w=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var J=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty;var A=(c,e)=>{for(var t in e)w(c,t,{get:e[t],enumerable:!0})},I=(c,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of q(e))!$.call(c,n)&&n!==t&&w(c,n,{get:()=>e[n],enumerable:!(s=L(e,n))||s.enumerable});return c};var G=(c,e,t)=>(t=c!=null?v(J(c)):{},I(e||!c||!c.__esModule?w(t,"default",{value:c,enumerable:!0}):t,c)),K=c=>I(w({},"__esModule",{value:!0}),c);var z={};A(z,{CacheableNet:()=>b,Net:()=>W,del:()=>E,fetch:()=>y,get:()=>k,head:()=>B,patch:()=>S,post:()=>H});module.exports=K(z);var R=require("cacheable"),U=require("hookified");var F=G(require("http-cache-semantics"),1),m=require("undici");async function y(c,e){let t={...e,cache:"no-cache"};if(!e.cache){let p=await(0,m.fetch)(c,t);if(!p.ok)throw new Error(`Fetch failed with status ${p.status}`);return p}if(e.method==="POST"||e.method==="PATCH"||e.method==="DELETE"||e.method==="HEAD"){let p=await(0,m.fetch)(c,t);if(!p.ok)throw new Error(`Fetch failed with status ${p.status}`);return p}let s=e.httpCachePolicy!==!1,n=e.method||"GET",a=`${n}:${c}`;if(!s){let p=await e.cache.getOrSet(a,async()=>{let T=await(0,m.fetch)(c,t);if(!T.ok)throw new Error(`Fetch failed with status ${T.status}`);return{body:await T.text(),status:T.status,statusText:T.statusText,headers:Object.fromEntries(T.headers.entries())}});if(!p)throw new Error("Failed to get or set cache data");return new Response(p.body,{status:p.status,statusText:p.statusText,headers:p.headers})}let o=`${a}:policy`,[i,r]=await Promise.all([e.cache.get(a),e.cache.get(o)]),h,u,f,l,P;r&&i&&(h=F.default.fromObject(r),u=i.body,f=i.status,l=i.statusText,P=i.headers);let N=t.headers||{},g={url:c,method:n,headers:N};if(h?.satisfiesWithoutRevalidation(g)){let p=h.responseHeaders();return new Response(u,{status:f,statusText:l,headers:p})}let C={};h?.revalidationHeaders(g)&&(C=h.revalidationHeaders(g));let d=await(0,m.fetch)(c,{...t,headers:{...t.headers,...C}});if(d.status===304&&h){let{policy:p,modified:T}=h.revalidatedPolicy(g,{status:d.status,headers:Object.fromEntries(d.headers.entries())});if(!T){let x=p.timeToLive();await e.cache.set(o,p.toObject(),x),await e.cache.set(a,{body:u,status:f,statusText:l,headers:P},x);let j=p.responseHeaders();return new Response(u,{status:f,statusText:l,headers:j})}}if(!d.ok&&d.status!==304)throw new Error(`Fetch failed with status ${d.status}`);let _=await d.text(),D={status:d.status,statusText:d.statusText,headers:Object.fromEntries(d.headers.entries())},O=new F.default(g,D);if(O.storable()){let p=O.timeToLive();await Promise.all([e.cache.set(a,{body:_,status:d.status,statusText:d.statusText,headers:D.headers},p),e.cache.set(o,O.toObject(),p)])}return new Response(_,{status:d.status,statusText:d.statusText,headers:d.headers})}async function k(c,e){let t=await y(c,{...e,method:"GET"}),s=await t.text(),n;try{n=JSON.parse(s)}catch{n=s}let a=new Response(s,{status:t.status,statusText:t.statusText,headers:t.headers});return{data:n,response:a}}async function H(c,e,t){let s,n={...t.headers};typeof e=="string"||e instanceof FormData||e instanceof URLSearchParams||e instanceof Blob?s=e:(s=JSON.stringify(e),!n["Content-Type"]&&!n["content-type"]&&(n["Content-Type"]="application/json"));let a=await y(c,{...t,headers:n,body:s,method:"POST"}),o=await a.text(),i;try{i=JSON.parse(o)}catch{i=o}let r=new Response(o,{status:a.status,statusText:a.statusText,headers:a.headers});return{data:i,response:r}}async function S(c,e,t){let s,n={...t.headers};typeof e=="string"||e instanceof FormData||e instanceof URLSearchParams||e instanceof Blob?s=e:(s=JSON.stringify(e),!n["Content-Type"]&&!n["content-type"]&&(n["Content-Type"]="application/json"));let a=await y(c,{...t,headers:n,body:s,method:"PATCH"}),o=await a.text(),i;try{i=JSON.parse(o)}catch{i=o}let r=new Response(o,{status:a.status,statusText:a.statusText,headers:a.headers});return{data:i,response:r}}async function E(c,e,t){let s,n;if(e!==void 0&&typeof e=="object"&&e!==null&&"cache"in e)s=void 0,n=e;else if(t)s=e,n=t;else throw new Error("Fetch options must include a cache instance or options.");let a,o={...n.headers};s!==void 0&&(typeof s=="string"||s instanceof FormData||s instanceof URLSearchParams||s instanceof Blob?a=s:(a=JSON.stringify(s),!o["Content-Type"]&&!o["content-type"]&&(o["Content-Type"]="application/json")));let i=await y(c,{...n,headers:o,body:a,method:"DELETE"}),r=await i.text(),h;try{h=JSON.parse(r)}catch{h=r}let u=new Response(r,{status:i.status,statusText:i.statusText,headers:i.headers});return{data:h,response:u}}async function B(c,e){return await y(c,{...e,method:"HEAD"})}var b=class extends U.Hookified{_cache=new R.Cacheable;_httpCachePolicy=!0;_stringify=JSON.stringify;_parse=JSON.parse;constructor(e){super(e),e?.cache&&(this._cache=e.cache instanceof R.Cacheable?e.cache:new R.Cacheable(e.cache)),e?.httpCachePolicy!==void 0&&(this._httpCachePolicy=e.httpCachePolicy),e?.stringify&&(this._stringify=e?.stringify),e?.parse&&(this._parse=e?.parse)}get stringify(){return this._stringify}set stringify(e){this._stringify=e}get parse(){return this._parse}set parse(e){this._parse=e}get cache(){return this._cache}set cache(e){this._cache=e}get httpCachePolicy(){return this._httpCachePolicy}set httpCachePolicy(e){this._httpCachePolicy=e}async fetch(e,t){let s={...t,cache:this._cache,httpCachePolicy:this._httpCachePolicy};return y(e,s)}async get(e,t){let s={...t,cache:this._cache,httpCachePolicy:this._httpCachePolicy,method:"GET"};t?.caching!==void 0&&delete s.cache;let n=await y(e,s),a=await n.text(),o,i=t?.parse||this._parse;try{o=i(a)}catch{o=a}let r=new Response(a,{status:n.status,statusText:n.statusText,headers:n.headers});return{data:o,response:r}}async post(e,t,s){let n,a={...s?.headers};typeof t=="string"||t instanceof FormData||t instanceof URLSearchParams||t instanceof Blob?n=t:(n=(s?.stringify||this._stringify)(t),!a["Content-Type"]&&!a["content-type"]&&(a["Content-Type"]="application/json"));let o={...s,headers:a,body:n,httpCachePolicy:this._httpCachePolicy,method:"POST"};s?.caching===!0&&(o.cache=this._cache);let i=await y(e,o),r=await i.text(),h,u=s?.parse||this._parse;try{h=u(r)}catch{h=r}let f=new Response(r,{status:i.status,statusText:i.statusText,headers:i.headers});return{data:h,response:f}}async head(e,t){let s={...t,cache:this._cache,httpCachePolicy:this._httpCachePolicy,method:"HEAD"};return t?.caching!==void 0&&!t.caching&&delete s.cache,await y(e,s)}async put(e,t,s){let n,a={...s?.headers};typeof t=="string"||t instanceof FormData||t instanceof URLSearchParams||t instanceof Blob?n=t:(n=(s?.stringify||this._stringify)(t),!a["Content-Type"]&&!a["content-type"]&&(a["Content-Type"]="application/json"));let o={...s,headers:a,body:n,httpCachePolicy:this._httpCachePolicy,method:"PUT"};s?.caching===!0&&(o.cache=this._cache);let i=await y(e,o),r=await i.text(),h,u=s?.parse||this._parse;try{h=u(r)}catch{h=r}let f=new Response(r,{status:i.status,statusText:i.statusText,headers:i.headers});return{data:h,response:f}}async patch(e,t,s){let n,a={...s?.headers};typeof t=="string"||t instanceof FormData||t instanceof URLSearchParams||t instanceof Blob?n=t:(n=(s?.stringify||this._stringify)(t),!a["Content-Type"]&&!a["content-type"]&&(a["Content-Type"]="application/json"));let o={...s,headers:a,body:n,httpCachePolicy:this._httpCachePolicy,method:"PATCH"};s?.caching===!0&&(o.cache=this._cache);let i=await y(e,o),r=await i.text(),h,u=s?.parse||this._parse;try{h=u(r)}catch{h=r}let f=new Response(r,{status:i.status,statusText:i.statusText,headers:i.headers});return{data:h,response:f}}async delete(e,t,s){let n,a={...s?.headers};t!==void 0&&(typeof t=="string"||t instanceof FormData||t instanceof URLSearchParams||t instanceof Blob?n=t:(n=(s?.stringify||this._stringify)(t),!a["Content-Type"]&&!a["content-type"]&&(a["Content-Type"]="application/json")));let o={...s,headers:a,body:n,httpCachePolicy:this._httpCachePolicy,method:"DELETE"};s?.caching===!0&&(o.cache=this._cache);let i=await y(e,o),r=await i.text(),h,u=s?.parse||this._parse;try{h=u(r)}catch{h=r}let f=new Response(r,{status:i.status,statusText:i.statusText,headers:i.headers});return{data:h,response:f}}},W=b;0&&(module.exports={CacheableNet,Net,del,fetch,get,head,patch,post});
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ 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
+ 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;
19
+ };
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 import_undici = require("undici");
49
+ async function fetch(url, options) {
50
+ const fetchOptions = {
51
+ ...options,
52
+ cache: "no-cache"
53
+ };
54
+ if (!options.cache) {
55
+ const response2 = await (0, import_undici.fetch)(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 (0, import_undici.fetch)(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 (0, import_undici.fetch)(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 (0, import_undici.fetch)(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
+ });
198
+ }
199
+ 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
+ };
217
+ }
218
+ 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
+ };
253
+ }
254
+ 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
+ };
289
+ }
290
+ 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
+ };
338
+ }
339
+ 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
+ }
706
+ };
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 */