soon-fetch 4.0.2-beta.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -447,7 +447,7 @@ Handle baseURL, path parameters and query parameters to generate complete URL.
447
447
  - `url`: Original URL
448
448
  - `config`: Configuration object, including query parameters, path parameters and base URL
449
449
 
450
- **Returns:** Processed complete URL
450
+ **Returns:** Object containing `url` (complete URL string), `path` (URL without query string), and `query` (URLSearchParams instance)
451
451
 
452
452
  **Example:**
453
453
 
@@ -460,6 +460,30 @@ const { url } = parseUrl("/api/users/:id", {
460
460
  // Returns: 'https://api.example.com/api/users/123?filter=active'
461
461
  ```
462
462
 
463
+ #### parseQuery2Arr
464
+
465
+ Parse query parameters into a `[key, value][]` array.
466
+ Supports multiple input formats: string, URLSearchParams, Record, and array-of-tuples.
467
+
468
+ **Parameters:**
469
+
470
+ - `query`: Query parameters in any supported format (string, URLSearchParams, Record, array-of-tuples)
471
+
472
+ **Returns:** Array of `[key, value]` pairs
473
+
474
+ **Example:**
475
+
476
+ ```typescript
477
+ parseQuery2Arr("page=1&size=10");
478
+ // Returns: [["page", "1"], ["size", "10"]]
479
+
480
+ parseQuery2Arr({ id: 123, status: "active" });
481
+ // Returns: [["id", "123"], ["status", "active"]]
482
+
483
+ parseQuery2Arr(new URLSearchParams("page=1"));
484
+ // Returns: [["page", "1"]]
485
+ ```
486
+
463
487
  #### mergeOptions
464
488
 
465
489
  Merge multiple option objects.
@@ -506,8 +530,32 @@ isBodyJson("string"); // false
506
530
 
507
531
  #### genRequestKey
508
532
 
533
+ Generate a unique identification key for the request (sync).
534
+ Generate a unique key value based on the request's URL, method, headers, query parameters, etc., used for caching and request sharing.
535
+
536
+ > **Note:** This is the synchronous version. For body types like `Blob`/`FormData` that require async processing (e.g., SHA-256 digest), it falls back to a non-deterministic key (nonce-based) to avoid blocking. Use `genRequestKeyAsync` for fully deterministic key generation.
537
+ > **Note:** The SHA-256 digest used by `genRequestKeyAsync` requires a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS). Under plain HTTP, `crypto.subtle.digest` is unavailable, and `genRequestKeyAsync` will fall back to a non-deterministic key for `Blob`/`ArrayBuffer`/`DataView` bodies, preventing incorrect cache hits or request sharing.
538
+
539
+ **Parameters:**
540
+
541
+ - `req`: Request object containing url and options
542
+ - `sortObjKeys?`: Whether to sort object keys for stable serialization
543
+
544
+ **Returns:** The unique identification string of the request
545
+
546
+ **Example:**
547
+
548
+ ```typescript
549
+ const key = genRequestKey({
550
+ url: "/api/users",
551
+ options: { method: "GET", params: { id: 1 } },
552
+ });
553
+ ```
554
+
555
+ #### genRequestKeyAsync
556
+
509
557
  Generate a unique identification key for the request (async).
510
- Generate a unique key value based on the request's URL, method, headers, body, query parameters, etc., used for caching and request sharing. Supports serializing special body types like Blob and FormData for deterministic key generation.
558
+ Same as `genRequestKey`, but supports async digest of `Blob`/`FormData` bodies for fully deterministic key generation.
511
559
 
512
560
  **Parameters:**
513
561
 
@@ -519,7 +567,7 @@ Generate a unique key value based on the request's URL, method, headers, body, q
519
567
  **Example:**
520
568
 
521
569
  ```typescript
522
- const key = await genRequestKey({
570
+ const key = await genRequestKeyAsync({
523
571
  url: "/api/users",
524
572
  options: { method: "GET", params: { id: 1 } },
525
573
  });
@@ -534,7 +582,6 @@ Provides request caching, sharing, and race condition handling.
534
582
 
535
583
  - `options`: Configuration options
536
584
  - `maxCacheSize`: Maximum cache size (default: 100000)
537
- - `checkInterval`: Cache check interval in milliseconds (default: 60000)
538
585
 
539
586
  **Returns:** Request store object with the following methods:
540
587
  - `entry(key)`: Get entry for specific request key
@@ -551,7 +598,7 @@ Provides request caching, sharing, and race condition handling.
551
598
  **Example:**
552
599
 
553
600
  ```typescript
554
- const store = createRequestStore({ maxCacheSize: 1000, checkInterval: 30000 });
601
+ const store = createRequestStore({ maxCacheSize: 1000 });
555
602
  // Use store in requests
556
603
  ```
557
604
 
@@ -1153,17 +1200,41 @@ const mergedSignal = mergeSignals(
1153
1200
  - `url`: 原始 URL
1154
1201
  - `config`: 配置对象,包含查询参数、路径参数和基础 URL
1155
1202
 
1156
- **返回:** 处理后的完整 URL
1203
+ **返回:** 包含 `url`(完整 URL 字符串)、`path`(不含查询参数的 URL)和 `query`(URLSearchParams 实例)的对象
1157
1204
 
1158
1205
  **示例:**
1159
1206
 
1160
1207
  ```typescript
1161
- const url = parseUrl("/api/users/:id", {
1208
+ const { url } = parseUrl("/api/users/:id", {
1162
1209
  params: { id: "123" },
1163
1210
  query: { filter: "active" },
1164
1211
  baseURL: "https://api.example.com",
1165
1212
  });
1166
- // 返回: 'https://api.example.com/api/users/123?filter=active'
1213
+ // url: 'https://api.example.com/api/users/123?filter=active'
1214
+ ```
1215
+
1216
+ #### parseQuery2Arr
1217
+
1218
+ 将查询参数解析为 `[key, value][]` 数组。
1219
+ 支持多种输入格式:string、URLSearchParams、Record 和元组数组。
1220
+
1221
+ **参数:**
1222
+
1223
+ - `query`: 任意支持的查询参数格式(string、URLSearchParams、Record、元组数组)
1224
+
1225
+ **返回:** `[key, value]` 键值对数组
1226
+
1227
+ **示例:**
1228
+
1229
+ ```typescript
1230
+ parseQuery2Arr("page=1&size=10");
1231
+ // 返回: [["page", "1"], ["size", "10"]]
1232
+
1233
+ parseQuery2Arr({ id: 123, status: "active" });
1234
+ // 返回: [["id", "123"], ["status", "active"]]
1235
+
1236
+ parseQuery2Arr(new URLSearchParams("page=1"));
1237
+ // 返回: [["page", "1"]]
1167
1238
  ```
1168
1239
 
1169
1240
  #### mergeOptions
@@ -1212,8 +1283,32 @@ isBodyJson("string"); // false
1212
1283
 
1213
1284
  #### genRequestKey
1214
1285
 
1286
+ 生成请求的唯一标识键(同步)。
1287
+ 根据请求的 URL、方法、headers、查询参数等生成唯一键值,用于缓存和请求共享。
1288
+
1289
+ > **注意:** 这是同步版本。对于 `Blob`/`FormData` 等需要异步处理的 body 类型,会回退为非确定性 key(基于 nonce)。使用 `genRequestKeyAsync` 可生成完全确定性的 key。
1290
+ > **注意:** `genRequestKeyAsync` 使用的 SHA-256 摘要需要[安全上下文](https://developer.mozilla.org/zh-CN/docs/Web/Security/Secure_Contexts)(HTTPS)。在纯 HTTP 下 `crypto.subtle.digest` 不可用,`genRequestKeyAsync` 会对 `Blob`/`ArrayBuffer`/`DataView` body 回退为非确定性 key,避免错误命中缓存或请求共享。
1291
+
1292
+ **参数:**
1293
+
1294
+ - `req`: 包含 url 和 options 的请求对象
1295
+ - `sortObjKeys?`: 是否对对象键进行排序以获得稳定序列化
1296
+
1297
+ **返回:** 唯一标识字符串
1298
+
1299
+ **示例:**
1300
+
1301
+ ```typescript
1302
+ const key = genRequestKey({
1303
+ url: "/api/users",
1304
+ options: { method: "GET", params: { id: 1 } },
1305
+ });
1306
+ ```
1307
+
1308
+ #### genRequestKeyAsync
1309
+
1215
1310
  生成请求的唯一标识键(异步)。
1216
- 根据请求的 URL、方法、headers、body、查询参数等生成唯一键值,用于缓存和请求共享。支持序列化 Blob 和 FormData 等特殊 body 类型以生成确定性键。
1311
+ 与 `genRequestKey` 功能相同,但支持异步处理 `Blob`/`FormData` body,生成完全确定性的 key。
1217
1312
 
1218
1313
  **参数:**
1219
1314
 
@@ -1225,7 +1320,7 @@ isBodyJson("string"); // false
1225
1320
  **示例:**
1226
1321
 
1227
1322
  ```typescript
1228
- const key = await genRequestKey({
1323
+ const key = await genRequestKeyAsync({
1229
1324
  url: "/api/users",
1230
1325
  options: { method: "GET", params: { id: 1 } },
1231
1326
  });
@@ -1240,7 +1335,6 @@ const key = await genRequestKey({
1240
1335
 
1241
1336
  - `options`: 配置选项
1242
1337
  - `maxCacheSize`: 最大缓存大小(默认: 100000)
1243
- - `checkInterval`: 缓存检查间隔(毫秒,默认: 60000)
1244
1338
 
1245
1339
  **返回:** 请求存储对象,包含以下方法:
1246
1340
  - `entry(key)`: 获取特定请求键的条目
@@ -1257,7 +1351,7 @@ const key = await genRequestKey({
1257
1351
  **示例:**
1258
1352
 
1259
1353
  ```typescript
1260
- const store = createRequestStore({ maxCacheSize: 1000, checkInterval: 30000 });
1354
+ const store = createRequestStore({ maxCacheSize: 1000 });
1261
1355
  // 在请求中使用 store
1262
1356
  ```
1263
1357
 
package/dist/index.d.ts CHANGED
@@ -1,8 +1,5 @@
1
- declare type BodyType = "json" | "formdata" | "blob" | "arraybuffer" | "dataview" | "readable_stream" | "urlsearchparams" | "typedarray" | "string" | "none";
2
-
3
1
  export declare function createRequestStore(options?: {
4
2
  maxCacheSize?: number;
5
- checkInterval?: number;
6
3
  }): {
7
4
  entry: (key: string) => {
8
5
  cache: {
@@ -798,19 +795,27 @@ export declare function genRequestKey(req: {
798
795
  url: string;
799
796
  options?: {
800
797
  method?: string;
801
- headers?: RequestInit["headers"];
802
798
  body?: RequestInit["body"] | object;
803
- query?: Record<string, string | number | boolean | null | undefined | (string | number | boolean | null | undefined)[]> | URLSearchParams;
799
+ headers?: RequestInit["headers"];
804
800
  params?: Record<string, string | number>;
801
+ query?: Record<string, string | number | boolean | null | undefined | (string | number | boolean | null | undefined)[]> | URLSearchParams;
805
802
  };
806
- }, sortObjKeys?: boolean, body_type?: BodyType): Promise<string>;
803
+ }, sortObjKeys?: boolean): string;
807
804
 
808
- export declare function getBodyType(body: unknown): BodyType;
805
+ export declare function genRequestKeyAsync(req: {
806
+ url: string;
807
+ options?: {
808
+ method?: string;
809
+ body?: RequestInit["body"] | object;
810
+ headers?: RequestInit["headers"];
811
+ params?: Record<string, string | number>;
812
+ query?: Record<string, string | number | boolean | null | undefined | (string | number | boolean | null | undefined)[]> | URLSearchParams;
813
+ };
814
+ }, sortObjKeys?: boolean): Promise<string>;
809
815
 
810
816
  declare type GetUrlKey<Url> = Url extends `${string}/:${infer Key}/${infer Right}` ? `${Key}` | GetUrlKey<`/${Right}`> : Url extends `${string}/:${infer Key}` ? `${Key}` : never;
811
817
 
812
- /** @deprecated 使用 getBodyType 替代 */
813
- export declare function isBodyJson(body: any): boolean;
818
+ export declare function isBodyJson(body: unknown): boolean;
814
819
 
815
820
  export declare const mergeHeaders: (...headersList: (HeadersInit | undefined)[]) => Headers;
816
821
 
@@ -838,12 +843,12 @@ export declare function parseOptions<Options extends SoonOptions>(urlOptions: {
838
843
  body?: RequestInit["body"];
839
844
  query: URLSearchParams;
840
845
  };
841
- body_type: BodyType;
842
- /** @deprecated 使用 body_type 替代 */
843
846
  is_body_json: boolean;
844
847
  abortController: AbortController;
845
848
  };
846
849
 
850
+ export declare const parseQuery2Arr: (query?: string | string[][] | Record<string, string | number | boolean | null | undefined | (string | number | boolean | null | undefined)[]> | URLSearchParams) => string[][];
851
+
847
852
  export declare const parseUrl: (url: string, config: {
848
853
  query?: Record<string, string | number | boolean | null | undefined | (string | number | boolean | null | undefined)[]> | URLSearchParams;
849
854
  params?: Record<string, string | number>;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var e=e=>{const t=[],r=e.match(/:([^:/\d]+)\/?/g);return r&&r.forEach(e=>{t.push(e.replace(/\//g,"").replace(/:/g,""))}),t},t=(e="")=>e.endsWith("/")?e.slice(0,-1):e,r=(e="")=>e.startsWith("/")?e:"/"+e,o=(e="")=>e.startsWith("http"),n=(e,n)=>o(e)?e:t(o(n)?n:r(n))+t(r(e)),a=e=>{if(!e)return[];if(e instanceof URLSearchParams||"string"==typeof e||Array.isArray(e))return Array.from(new URLSearchParams(e).entries());const t=[];return Object.entries(e).forEach(([e,r])=>{(Array.isArray(r)?r:[r]).forEach(r=>{t.push([e,String(r??"")])})}),t},s=(t,r)=>{const{query:o,params:s,baseURL:c}=r;let i=t.trim();e(t).forEach(e=>{s&&(i=i.replace(":"+e,""+s[e]))});const[u,l]=i.split("?"),f=new URLSearchParams([...a(l),...a(o)]);let h=n(u,c),p=h;return f.size&&(p=h+"?"+f),{query:f,url:p,path:h}},c=(...e)=>{const t=new Headers;return e.forEach(e=>{e&&(e instanceof Headers?e.forEach((e,r)=>t.set(r,e)):Array.isArray(e)?e.forEach(([e,r])=>t.set(e,r)):Object.entries(e).forEach(([e,r])=>t.set(e,r)))}),t};function i(e,t){const r=(e??[]).filter(e=>!!e);return t&&r.push(AbortSignal.timeout(t)),r.length?AbortSignal.any(r):void 0}function u(e){return"json"===d(e)}function l(e){const t=new FormData;return e&&"object"==typeof e&&!Array.isArray(e)&&Object.entries(e).forEach(([e,r])=>{if(null==r||"function"==typeof r)return;let o;o=r instanceof Blob?r:"object"==typeof r?JSON.stringify(r):String(r),t.append(e,o)}),t}var f=0;function h(e){return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function p(e){const t=await e.arrayBuffer();return h(await globalThis.crypto.subtle.digest("SHA-256",t))}async function y(e,t){switch(t){case"none":case"string":case"json":case"typedarray":return e;case"formdata":{const t={},r=[];e.forEach((e,t)=>r.push([t,e]));for(const[e,o]of r)o instanceof Blob?t[e]=`__blob_${await p(o)}__`:t[e]=o;return t}case"blob":return`__blob_${await p(e)}__`;case"arraybuffer":return`__ab_${h(await globalThis.crypto.subtle.digest("SHA-256",e))}__`;case"dataview":{const t=e,r=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return`__ab_${h(await globalThis.crypto.subtle.digest("SHA-256",r))}__`}case"urlsearchparams":return e.toString();case"readable_stream":return`__nonce_${Date.now()}_${f++}__`}}function d(e){return null==e?"none":"object"!=typeof e?typeof e:e instanceof FormData?"formdata":e instanceof Blob?"blob":e instanceof ArrayBuffer?"arraybuffer":e instanceof DataView?"dataview":e instanceof ReadableStream?"readable_stream":e instanceof URLSearchParams?"urlsearchparams":(t=e,[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array].some(e=>t instanceof e)?"typedarray":"json");var t}var b=e=>{if(e instanceof Response)return e.clone();if("function"==typeof e||e instanceof Promise||null===e||"object"!=typeof e)return e;try{return structuredClone(e)}catch(t){return JSON.parse(JSON.stringify(e))}};function m(...e){const t=Object.assign({},...e);return t.headers=c(...e.map(e=>e?.headers)),t.signal=i(e.map(e=>e?.signal),t.timeout),t}function g(e){const{url:t,options:r,baseURL:o,baseOptions:n}=e,a=m(n,r),{url:c,query:u}=s(t,{...a,baseURL:o});a.query=u;const l=a?.body,f=d(l);a.body="json"===f?JSON.stringify(l):l,"json"===f&&a.headers.append("Content-Type","application/json");const h=new AbortController;return a.signal=i([a.signal,h.signal]),{url:c,options:a,body_type:f,is_body_json:"json"===f,abortController:h}}var O=["get","post","put","delete","patch"];function _(e,t){const r={};return e.forEach(e=>{r[e]=t(e)}),r}function A(t){const r=(r,o,n)=>{const a=!!e(r).length;return(...e)=>{const s=[...e],{hasBody:c,hasQuery:i,isFormData:u,options:f}=n||{},h=a?s.shift():void 0,p=i?s.shift():void 0;let y=c?s.shift():void 0;u&&(y=l(y));const d=s.shift(),b=f?{...f,...d}:d;return t(r,o,h,p,y,b)}},o={hasBody:!0},n={hasQuery:!0},a={isFormData:!0},s={};return O.forEach(e=>{const t=e.toUpperCase();s[t]=t=>({Ok:()=>r(t,e),Options:o=>({Ok:()=>r(t,e,{options:o})}),Body:()=>({Ok:()=>r(t,e,{...o}),Options:n=>({Ok:()=>r(t,e,{...o,options:n})})}),FormData:()=>({Ok:()=>r(t,e,{...o,...a}),Options:n=>({Ok:()=>r(t,e,{...o,...a,options:n})})}),Params:()=>({Ok:()=>r(t,e),Options:o=>({Ok:()=>r(t,e,{options:o})}),Body:()=>({Ok:()=>r(t,e,{...o}),Options:n=>({Ok:()=>r(t,e,{...o,options:n})})}),FormData:()=>({Ok:()=>r(t,e,{...o,...a}),Options:n=>({Ok:()=>r(t,e,{...o,...a,options:n})})}),Query:()=>({Ok:()=>r(t,e,{...n}),Options:o=>({Ok:()=>r(t,e,{...n,options:o})}),Body:()=>({Ok:()=>r(t,e,{...o,...n}),Options:a=>({Ok:()=>r(t,e,{...o,...n,options:a})})}),FormData:()=>({Ok:()=>r(t,e,{...o,...n,...a}),Options:s=>({Ok:()=>r(t,e,{...o,...n,...a,options:s})})})})}),Query:()=>({Ok:()=>r(t,e,{...n}),Options:o=>({Ok:()=>r(t,e,{...n,options:o})}),Body:()=>({Ok:()=>r(t,e,{...o,...n}),Options:a=>({Ok:()=>r(t,e,{...o,...n,options:a})})}),FormData:()=>({Ok:()=>r(t,e,{...o,...n,...a}),Options:s=>({Ok:()=>r(t,e,{...o,...n,...a,options:s})})})})})}),s}function w(e,t=!1){if(Array.isArray(e)){const r=[...e];return t&&r.sort(),r.map(e=>w(e,t))}if("object"==typeof e&&null!==e){const r={};return Object.keys(e).sort().forEach(o=>{r[o]=w(e[o],t)}),r}return e}async function E(e,t,r){const{url:o,options:n}=e,{headers:a,method:s,body:c,query:i,params:u}=n??{},l=Object.fromEntries(new Headers(a).entries()),f={params:u,query:i,body:await y(c,r??d(c)),headers:l};return(s??"get").toLowerCase()+o+JSON.stringify(t?f:w(f))}function k(e={}){const t=e.maxCacheSize??1e5,r=e.checkInterval??6e4,o={},n=e=>o[e],a=(e,t)=>{const r=o[e];r?Object.assign(r,t):o[e]={...t}},s=e=>{delete o[e]},c=(e,t)=>{try{const r=n(e);r&&(t(r),Object.keys(r).some(e=>void 0!==r[e])?a(e,r):s(e))}catch(r){console.error("Error during request cleanup:",r);try{s(e)}catch(o){console.error("Failed to remove request after cleanup error:",o)}}},i=e=>delete e.cache,u=e=>delete e.cache_expiredTime;function l(e,r,s){const l=n(e)||{};l.cache=b(r),l.cache_expiredTime=s,a(e,l),(()=>{try{const e=Object.entries(o).filter(([e,t])=>void 0!==t.cache);if(e.length>t){e.sort(([,e],[,t])=>(e.cache_expiredTime||0)-(t.cache_expiredTime||0));const r=e.length-t;e.slice(0,r).forEach(([e])=>{c(e,e=>{i(e),u(e)})})}}catch(e){console.error("Error during cache size management:",e)}})()}const f=setInterval(()=>{try{const e=Date.now();Object.entries(o).forEach(([t,r])=>{r.cache_expiredTime&&r.cache_expiredTime<e&&c(t,e=>{i(e),u(e)})})}catch(e){console.warn("Error during periodic cache cleanup:",e)}},r);return{entry:e=>({cache:{get:()=>function(e){const t=n(e);if(t&&void 0!==t.cache)return t.cache_expiredTime&&t.cache_expiredTime>Date.now()?b(t.cache):void c(e,e=>{i(e),u(e)})}(e),remove:()=>function(e){c(e,e=>{i(e),u(e)})}(e),set:(t,r)=>l(e,t,r)},share:{get:()=>function(e){return n(e)?.promise}(e),set:t=>function(e,t){const r=n(e)||{};r.promise=t,a(e,r),t.finally(()=>{c(e,e=>{delete e.promise})})}(e,t)},abort(t,r){r&&r.length>0&&r[r.length-1]!==n(e)?.abortController&&(r.pop()?.abort("race abort"),r.push(t),a(e,{abortController:t}))}}),dispose:()=>{clearInterval(f)},get:n,set:a,remove:s,getAll:()=>({...o}),removeAll:()=>{Object.keys(o).forEach(e=>{delete o[e]})},clearCache:()=>{Object.entries(o).forEach(([e,t])=>{void 0!==t.cache&&c(e,e=>{i(e),u(e)})})},clearExpiredCache:()=>{const e=Date.now();Object.entries(o).forEach(([t,r])=>{r.cache_expiredTime&&r.cache_expiredTime<e&&c(t,e=>{i(e),u(e)})})},abortAll:()=>{Object.entries(o).forEach(([e,t])=>{t.abortController&&t.abortController.abort("abort all")})}}}function v(e){let t=[],r=!1;return(o,n)=>{t.push({success:o,fail:n}),r||(r=!0,e().then(()=>{t.forEach(e=>e.success())}).catch(e=>{t.forEach(e=>e.fail())}).finally(()=>{r=!1,t=[]}))}}function j(e,t,r=0){return new Promise((o,n)=>{let a=0;const s=e.getReader(),c=[];!function e(){s.read().then(({done:n,value:s})=>{if(n){const e=new Uint8Array(a);let n=0;return c.forEach(t=>{e.set(t,n),n+=t.length}),t(100,a,r),void o(e.buffer)}s&&(c.push(s),a+=s.length,r>0?t(Math.min(100,Math.round(a/r*100)),a,r):t(0,a,0)),e()}).catch(e=>{console.error("Error reading response body:",e),n(e)})}()})}function S(e,t){return new Promise((r,o)=>{if(!e.body)return void o(/* @__PURE__ */new Error("Response body is null"));const n=e.headers.get("content-length"),a=n?parseInt(n,10):0;j(e.body,t,a).then(r).catch(o)})}function C(e,t,r,o,n){return new Promise((a,s)=>{const c=e.entry(r),{share:i,aborts:u,staleTime:l}=n??{},f=new AbortController;if(f.signal.addEventListener("abort",()=>{s(f.signal.reason)}),c.abort(i?f:o,u),i){const e=c.share.get();if(e)return a(e.then(e=>b(e)))}if(l){const e=c.cache.get();if(void 0!==e)return a(e)}const h=t();i&&c.share.set(h),h.then(e=>{a(e),l&&c.cache.set(e,/* @__PURE__ */(new Date).getTime()+l)}).catch(e=>s(e))})}var T=k(),U=async e=>{const t=g(e);if("readable_stream"===t.body_type)return fetch(t.url,t.options);const r=await E({url:e.url,options:{method:t.options?.method,headers:t.options?.headers,body:t.options?.body,query:t.options?.query}},e.sortRequestKey,t.body_type);return C(e.store??T,()=>fetch(t.url,t.options),r,t.abortController,t.options)};function D(e){const t=A((t,r,o,n,a,s)=>e(t,{...s,method:r,params:o,query:n,body:a})),r=_([...O,"head","options"],t=>(r,o)=>e(r,{...o,method:t}));return{request:e,...t,...r,fork:(t,r)=>D((o,a)=>e(n(o,t),r?{...r,...a}:a))}}export{k as createRequestStore,A as createShortApi,_ as createShortMethods,v as createSilentRefresh,D as createSoon,w as deepSort,E as genRequestKey,d as getBodyType,u as isBodyJson,c as mergeHeaders,m as mergeOptions,i as mergeSignals,g as parseOptions,s as parseUrl,S as progressDownload,j as progressReadBody,C as requestWithStore,U as soonFetch,l as toFormData};
1
+ var t=t=>{const e=[],r=t.match(/:([^:/]+)\/?/g);return r&&r.forEach(t=>{e.push(t.replace(/\//g,"").replace(/:/g,""))}),e},e=(t="")=>t.endsWith("/")?t.slice(0,-1):t,r=(t="")=>t.startsWith("/")?t:"/"+t,n=(t="")=>t.startsWith("http"),o=(t,o)=>n(t)?t:e(n(o)?o:r(o))+e(r(t)),a=t=>{if(!t)return[];if(t instanceof URLSearchParams||"string"==typeof t||Array.isArray(t))return Array.from(new URLSearchParams(t).entries());const e=[];return Object.entries(t).forEach(([t,r])=>{(Array.isArray(r)?r:[r]).forEach(r=>{e.push([t,String(r??"")])})}),e},s=(e,r)=>{const{query:n,params:s,baseURL:i}=r;let c=e.trim();t(e).forEach(t=>{s&&void 0!==s[t]&&(c=c.split(":"+t).join(""+s[t]))});const[f,u]=c.split("?"),l=new URLSearchParams([...a(u),...a(n)]),h=o(f??"",i);let p=h;return l.size&&(p=h+"?"+l),{query:l,url:p,path:h}},i=(...t)=>{const e=new Headers;return t.forEach(t=>{t&&(t instanceof Headers?t.forEach((t,r)=>e.set(r,t)):Array.isArray(t)?t.forEach(([t,r])=>e.set(t,r)):Object.entries(t).forEach(([t,r])=>e.set(t,r)))}),e};function c(t,e){const r=(t??[]).filter(t=>!!t);return e&&r.push(AbortSignal.timeout(e)),r.length?AbortSignal.any(r):void 0}function f(t){return[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array].some(e=>t instanceof e)}function u(t){return null!=t&&("object"==typeof t&&(!(t instanceof FormData)&&(!(t instanceof Blob)&&(!(t instanceof ArrayBuffer)&&(!(t instanceof DataView)&&(!(t instanceof ReadableStream)&&(!(t instanceof URLSearchParams)&&!f(t))))))))}function l(t){const e=new FormData;return t&&"object"==typeof t&&!Array.isArray(t)&&Object.entries(t).forEach(([t,r])=>{if(null==r||"function"==typeof r)return;let n;n=r instanceof Blob?r:"object"==typeof r?JSON.stringify(r):String(r),e.append(t,n)}),e}var h=0,p=(t="")=>`${t}_nonce_${Date.now()}_${h++}__`;function y(t){return Array.from(new Uint8Array(t)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function b(t){const e=await t.arrayBuffer();return globalThis.crypto?.subtle?.digest?y(await globalThis.crypto.subtle.digest("SHA-256",e)):p("blob")}async function d(t){if(null==t)return t;if("string"==typeof t)return t;if("object"!=typeof t)return String(t);if(t instanceof FormData){const e={},r=[];t.forEach((t,e)=>r.push([e,t]));for(const[t,n]of r)e[t]=n instanceof Blob?`__blob_${await b(n)}__`:n;return e}if(t instanceof Blob)return`__blob_${await b(t)}__`;if(t instanceof ArrayBuffer)return globalThis.crypto?.subtle?.digest?`__ab_${y(await globalThis.crypto.subtle.digest("SHA-256",t))}__`:p("__ab");if(t instanceof DataView){const e=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return globalThis.crypto?.subtle?.digest?`__ab_${y(await globalThis.crypto.subtle.digest("SHA-256",e))}__`:p("__ab")}return t instanceof URLSearchParams?t.toString():t instanceof ReadableStream?p("_"):(f(t),t)}var g=t=>{if(t instanceof Response)return t.clone();if("function"==typeof t||t instanceof Promise||null===t||"object"!=typeof t)return t;try{return structuredClone(t)}catch(e){return JSON.parse(JSON.stringify(t))}};function m(...t){const e=Object.assign({},...t);return e.headers=i(...t.map(t=>t?.headers)),e.signal=c(t.map(t=>t?.signal),e.timeout),e}function O(t){const{url:e,options:r,baseURL:n,baseOptions:o}=t,a=m(o,r),{url:i,query:f}=s(e,{...a,baseURL:n});a.query=f;const l=a?.body,h=u(l);a.body=h?JSON.stringify(l):null!=l&&"string"!=typeof l&&"object"!=typeof l?String(l):l,h&&a.headers.set("Content-Type","application/json");const p=new AbortController;return a.signal=c([a.signal,p.signal]),{url:i,options:a,is_body_json:h,abortController:p}}var _=["get","post","put","delete","patch"];function A(t,e){const r={};return t.forEach(t=>{r[t]=e(t)}),r}function E(e){const r=(r,n,o)=>{const a=!!t(r).length;return(...t)=>{const s=[...t],{hasBody:i,hasQuery:c,isFormData:f,options:u}=o||{},h=a?s.shift():void 0,p=c?s.shift():void 0;let y=i?s.shift():void 0;f&&(y=l(y));const b=s.shift(),d=u?{...u,...b}:b;return e(r,n,h,p,y,d)}},n={hasBody:!0},o={hasQuery:!0},a={isFormData:!0},s={};return _.forEach(t=>{const e=t.toUpperCase();s[e]=e=>({Ok:()=>r(e,t),Options:n=>({Ok:()=>r(e,t,{options:n})}),Body:()=>({Ok:()=>r(e,t,{...n}),Options:o=>({Ok:()=>r(e,t,{...n,options:o})})}),FormData:()=>({Ok:()=>r(e,t,{...n,...a}),Options:o=>({Ok:()=>r(e,t,{...n,...a,options:o})})}),Params:()=>({Ok:()=>r(e,t),Options:n=>({Ok:()=>r(e,t,{options:n})}),Body:()=>({Ok:()=>r(e,t,{...n}),Options:o=>({Ok:()=>r(e,t,{...n,options:o})})}),FormData:()=>({Ok:()=>r(e,t,{...n,...a}),Options:o=>({Ok:()=>r(e,t,{...n,...a,options:o})})}),Query:()=>({Ok:()=>r(e,t,{...o}),Options:n=>({Ok:()=>r(e,t,{...o,options:n})}),Body:()=>({Ok:()=>r(e,t,{...n,...o}),Options:a=>({Ok:()=>r(e,t,{...n,...o,options:a})})}),FormData:()=>({Ok:()=>r(e,t,{...n,...o,...a}),Options:s=>({Ok:()=>r(e,t,{...n,...o,...a,options:s})})})})}),Query:()=>({Ok:()=>r(e,t,{...o}),Options:n=>({Ok:()=>r(e,t,{...o,options:n})}),Body:()=>({Ok:()=>r(e,t,{...n,...o}),Options:a=>({Ok:()=>r(e,t,{...n,...o,options:a})})}),FormData:()=>({Ok:()=>r(e,t,{...n,...o,...a}),Options:s=>({Ok:()=>r(e,t,{...n,...o,...a,options:s})})})})})}),s}function k(t,e=!1){if(Array.isArray(t)){const r=[...t];return e&&r.sort(),r.map(t=>k(t,e))}if("object"==typeof t&&null!==t){const r={};return Object.keys(t).sort().forEach(n=>{r[n]=k(t[n],e)}),r}return t}function S(t,e,r){const n={body:e,headers:Object.fromEntries(t.headers.entries())};return(t.method??"get").toLowerCase()+t.url+JSON.stringify(r?k(n):n)}async function w(t,e){const{url:r,options:n}=O(t);return S({url:r,...n},await d(t.options?.body),e)}function v(t,e){const{url:r,options:n}=O(t);return S({url:r,...n},function(t){if(null==t)return t;if("string"==typeof t)return t;if("object"!=typeof t)return String(t);if(t instanceof FormData){const e={},r=[];t.forEach((t,e)=>r.push([e,t]));for(const[t,n]of r)e[t]=n instanceof Blob?p("__blob"):n;return e}return t instanceof URLSearchParams?t.toString():u(t)||f(t)?t:p("_")}(t.options?.body),e)}function j(t={}){const e=t.maxCacheSize??1e5,r={},n=t=>r[t],o=(t,e)=>{const n=r[t];n?Object.assign(n,e):r[t]={...e}},a=t=>{delete r[t]},s=(t,e)=>{try{const r=n(t);r&&(e(r),Object.keys(r).some(t=>void 0!==r[t])?o(t,r):a(t))}catch(r){console.error("Error during request cleanup:",r);try{a(t)}catch(s){console.error("Failed to remove request after cleanup error:",s)}}},i=t=>delete t.cache,c=t=>delete t.cache_expiredTime;function f(t,a,f){const u=n(t)||{};u.cache=g(a),u.cache_expiredTime=f,o(t,u),(()=>{try{const t=Object.entries(r).filter(([t,e])=>void 0!==e.cache);if(t.length>e){t.sort(([,t],[,e])=>(t.cache_expiredTime||0)-(e.cache_expiredTime||0));const r=t.length-e;t.slice(0,r).forEach(([t])=>{s(t,t=>{i(t),c(t)})})}}catch(t){console.error("Error during cache size management:",t)}})()}const u=()=>{Object.keys(r).forEach(t=>{delete r[t]})},l=()=>{Object.entries(r).forEach(([t,e])=>{e.abortController&&e.abortController.abort("abort all")})};return{entry:t=>({cache:{get:()=>function(t){const e=n(t);if(e&&void 0!==e.cache)return e.cache_expiredTime&&e.cache_expiredTime>Date.now()?g(e.cache):void s(t,t=>{i(t),c(t)})}(t),remove:()=>function(t){s(t,t=>{i(t),c(t)})}(t),set:(e,r)=>f(t,e,r)},share:{get:()=>function(t){return n(t)?.promise}(t),set:e=>function(t,e){const r=n(t)||{};r.promise=e,o(t,r),e.finally(()=>{s(t,t=>{delete t.promise})})}(t,e)},abort(e,r){r&&r.length>0&&r[r.length-1]!==n(t)?.abortController&&(r.pop()?.abort("race abort"),r.push(e),o(t,{abortController:e}))}}),dispose:()=>{l(),u()},get:n,set:o,remove:a,getAll:()=>({...r}),removeAll:u,clearCache:()=>{Object.entries(r).forEach(([t,e])=>{void 0!==e.cache&&s(t,t=>{i(t),c(t)})})},clearExpiredCache:()=>{const t=Date.now();Object.entries(r).forEach(([e,r])=>{r.cache_expiredTime&&r.cache_expiredTime<t&&s(e,t=>{i(t),c(t)})})},abortAll:l}}function T(t){let e=[],r=!1;return(n,o)=>{e.push({success:n,fail:o}),r||(r=!0,t().then(()=>{e.forEach(t=>t.success())}).catch(t=>{e.forEach(t=>t.fail())}).finally(()=>{r=!1,e=[]}))}}function U(t,e,r=0){return new Promise((n,o)=>{let a=0;const s=t.getReader(),i=[];!function t(){s.read().then(({done:o,value:s})=>{if(o){const t=new Uint8Array(a);let o=0;return i.forEach(e=>{t.set(e,o),o+=e.length}),e(100,a,r),void n(t.buffer)}s&&(i.push(s),a+=s.length,r>0?e(Math.min(100,Math.round(a/r*100)),a,r):e(0,a,0)),t()}).catch(t=>{console.error("Error reading response body:",t),o(t)})}()})}function B(t,e){return new Promise((r,n)=>{if(!t.body)return void n(/* @__PURE__ */new Error("Response body is null"));const o=t.headers.get("content-length"),a=o?parseInt(o,10):0;U(t.body,e,a).then(r).catch(n)})}function C(t,e,r,n,o){return new Promise((a,s)=>{const i=t.entry(r),{share:c,aborts:f,staleTime:u}=o??{},l=new AbortController,h=()=>l.signal.removeEventListener("abort",p),p=()=>{h(),s(l.signal.reason)};if(l.signal.addEventListener("abort",p),i.abort(c?l:n,f),c){const t=i.share.get();if(t)return h(),a(t.then(t=>g(t)))}if(u){const t=i.cache.get();if(void 0!==t)return h(),a(t)}const y=e();c&&i.share.set(y),y.then(t=>{h(),a(t),u&&i.cache.set(t,/* @__PURE__ */(new Date).getTime()+u)}).catch(t=>{h(),s(t)})})}var D=j(),R=async t=>{const e=O(t),r=e.options,n=e.url,{share:o,staleTime:a,aborts:s}=r??{};if(!o&&!a&&!s)return fetch(n,r);const i=S({url:n,...r},await d(t.options?.body),t.sortRequestKey);return C(t.store??D,()=>fetch(n,r),i,e.abortController,r)};function F(t){const e=E((e,r,n,o,a,s)=>t(e,{...s,method:r,params:n,query:o,body:a})),r=A([..._,"head","options"],e=>(r,n)=>t(r,{...n,method:e}));return{request:t,...e,...r,fork:(e,r)=>F((n,a)=>t(o(n,e),r?{...r,...a}:a))}}export{j as createRequestStore,E as createShortApi,A as createShortMethods,T as createSilentRefresh,F as createSoon,k as deepSort,v as genRequestKey,w as genRequestKeyAsync,u as isBodyJson,i as mergeHeaders,m as mergeOptions,c as mergeSignals,O as parseOptions,a as parseQuery2Arr,s as parseUrl,B as progressDownload,U as progressReadBody,C as requestWithStore,R as soonFetch,l as toFormData};
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SoonFetch={})}(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});var t=e=>{const t=[],r=e.match(/:([^:/\d]+)\/?/g);return r&&r.forEach(e=>{t.push(e.replace(/\//g,"").replace(/:/g,""))}),t},r=(e="")=>e.endsWith("/")?e.slice(0,-1):e,o=(e="")=>e.startsWith("/")?e:"/"+e,n=(e="")=>e.startsWith("http"),a=(e,t)=>n(e)?e:r(n(t)?t:o(t))+r(o(e)),s=e=>{if(!e)return[];if(e instanceof URLSearchParams||"string"==typeof e||Array.isArray(e))return Array.from(new URLSearchParams(e).entries());const t=[];return Object.entries(e).forEach(([e,r])=>{(Array.isArray(r)?r:[r]).forEach(r=>{t.push([e,String(r??"")])})}),t},i=(e,r)=>{const{query:o,params:n,baseURL:i}=r;let c=e.trim();t(e).forEach(e=>{n&&(c=c.replace(":"+e,""+n[e]))});const[u,l]=c.split("?"),f=new URLSearchParams([...s(l),...s(o)]);let h=a(u,i),p=h;return f.size&&(p=h+"?"+f),{query:f,url:p,path:h}},c=(...e)=>{const t=new Headers;return e.forEach(e=>{e&&(e instanceof Headers?e.forEach((e,r)=>t.set(r,e)):Array.isArray(e)?e.forEach(([e,r])=>t.set(e,r)):Object.entries(e).forEach(([e,r])=>t.set(e,r)))}),t};function u(e,t){const r=(e??[]).filter(e=>!!e);return t&&r.push(AbortSignal.timeout(t)),r.length?AbortSignal.any(r):void 0}function l(e){const t=new FormData;return e&&"object"==typeof e&&!Array.isArray(e)&&Object.entries(e).forEach(([e,r])=>{if(null==r||"function"==typeof r)return;let o;o=r instanceof Blob?r:"object"==typeof r?JSON.stringify(r):String(r),t.append(e,o)}),t}var f=0;function h(e){return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function p(e){const t=await e.arrayBuffer();return h(await globalThis.crypto.subtle.digest("SHA-256",t))}async function d(e,t){switch(t){case"none":case"string":case"json":case"typedarray":return e;case"formdata":{const t={},r=[];e.forEach((e,t)=>r.push([t,e]));for(const[e,o]of r)o instanceof Blob?t[e]=`__blob_${await p(o)}__`:t[e]=o;return t}case"blob":return`__blob_${await p(e)}__`;case"arraybuffer":return`__ab_${h(await globalThis.crypto.subtle.digest("SHA-256",e))}__`;case"dataview":{const t=e,r=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return`__ab_${h(await globalThis.crypto.subtle.digest("SHA-256",r))}__`}case"urlsearchparams":return e.toString();case"readable_stream":return`__nonce_${Date.now()}_${f++}__`}}function y(e){return null==e?"none":"object"!=typeof e?typeof e:e instanceof FormData?"formdata":e instanceof Blob?"blob":e instanceof ArrayBuffer?"arraybuffer":e instanceof DataView?"dataview":e instanceof ReadableStream?"readable_stream":e instanceof URLSearchParams?"urlsearchparams":(t=e,[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array].some(e=>t instanceof e)?"typedarray":"json");var t}var b=e=>{if(e instanceof Response)return e.clone();if("function"==typeof e||e instanceof Promise||null===e||"object"!=typeof e)return e;try{return structuredClone(e)}catch(t){return JSON.parse(JSON.stringify(e))}};function m(...e){const t=Object.assign({},...e);return t.headers=c(...e.map(e=>e?.headers)),t.signal=u(e.map(e=>e?.signal),t.timeout),t}function g(e){const{url:t,options:r,baseURL:o,baseOptions:n}=e,a=m(n,r),{url:s,query:c}=i(t,{...a,baseURL:o});a.query=c;const l=a?.body,f=y(l);a.body="json"===f?JSON.stringify(l):l,"json"===f&&a.headers.append("Content-Type","application/json");const h=new AbortController;return a.signal=u([a.signal,h.signal]),{url:s,options:a,body_type:f,is_body_json:"json"===f,abortController:h}}var O=["get","post","put","delete","patch"];function _(e,t){const r={};return e.forEach(e=>{r[e]=t(e)}),r}function A(e){const r=(r,o,n)=>{const a=!!t(r).length;return(...t)=>{const s=[...t],{hasBody:i,hasQuery:c,isFormData:u,options:f}=n||{},h=a?s.shift():void 0,p=c?s.shift():void 0;let d=i?s.shift():void 0;u&&(d=l(d));const y=s.shift(),b=f?{...f,...y}:y;return e(r,o,h,p,d,b)}},o={hasBody:!0},n={hasQuery:!0},a={isFormData:!0},s={};return O.forEach(e=>{const t=e.toUpperCase();s[t]=t=>({Ok:()=>r(t,e),Options:o=>({Ok:()=>r(t,e,{options:o})}),Body:()=>({Ok:()=>r(t,e,{...o}),Options:n=>({Ok:()=>r(t,e,{...o,options:n})})}),FormData:()=>({Ok:()=>r(t,e,{...o,...a}),Options:n=>({Ok:()=>r(t,e,{...o,...a,options:n})})}),Params:()=>({Ok:()=>r(t,e),Options:o=>({Ok:()=>r(t,e,{options:o})}),Body:()=>({Ok:()=>r(t,e,{...o}),Options:n=>({Ok:()=>r(t,e,{...o,options:n})})}),FormData:()=>({Ok:()=>r(t,e,{...o,...a}),Options:n=>({Ok:()=>r(t,e,{...o,...a,options:n})})}),Query:()=>({Ok:()=>r(t,e,{...n}),Options:o=>({Ok:()=>r(t,e,{...n,options:o})}),Body:()=>({Ok:()=>r(t,e,{...o,...n}),Options:a=>({Ok:()=>r(t,e,{...o,...n,options:a})})}),FormData:()=>({Ok:()=>r(t,e,{...o,...n,...a}),Options:s=>({Ok:()=>r(t,e,{...o,...n,...a,options:s})})})})}),Query:()=>({Ok:()=>r(t,e,{...n}),Options:o=>({Ok:()=>r(t,e,{...n,options:o})}),Body:()=>({Ok:()=>r(t,e,{...o,...n}),Options:a=>({Ok:()=>r(t,e,{...o,...n,options:a})})}),FormData:()=>({Ok:()=>r(t,e,{...o,...n,...a}),Options:s=>({Ok:()=>r(t,e,{...o,...n,...a,options:s})})})})})}),s}function w(e,t=!1){if(Array.isArray(e)){const r=[...e];return t&&r.sort(),r.map(e=>w(e,t))}if("object"==typeof e&&null!==e){const r={};return Object.keys(e).sort().forEach(o=>{r[o]=w(e[o],t)}),r}return e}async function S(e,t,r){const{url:o,options:n}=e,{headers:a,method:s,body:i,query:c,params:u}=n??{},l=Object.fromEntries(new Headers(a).entries()),f={params:u,query:c,body:await d(i,r??y(i)),headers:l};return(s??"get").toLowerCase()+o+JSON.stringify(t?f:w(f))}function j(e={}){const t=e.maxCacheSize??1e5,r=e.checkInterval??6e4,o={},n=e=>o[e],a=(e,t)=>{const r=o[e];r?Object.assign(r,t):o[e]={...t}},s=e=>{delete o[e]},i=(e,t)=>{try{const r=n(e);r&&(t(r),Object.keys(r).some(e=>void 0!==r[e])?a(e,r):s(e))}catch(r){console.error("Error during request cleanup:",r);try{s(e)}catch(o){console.error("Failed to remove request after cleanup error:",o)}}},c=e=>delete e.cache,u=e=>delete e.cache_expiredTime;function l(e,r,s){const l=n(e)||{};l.cache=b(r),l.cache_expiredTime=s,a(e,l),(()=>{try{const e=Object.entries(o).filter(([e,t])=>void 0!==t.cache);if(e.length>t){e.sort(([,e],[,t])=>(e.cache_expiredTime||0)-(t.cache_expiredTime||0));const r=e.length-t;e.slice(0,r).forEach(([e])=>{i(e,e=>{c(e),u(e)})})}}catch(e){console.error("Error during cache size management:",e)}})()}const f=setInterval(()=>{try{const e=Date.now();Object.entries(o).forEach(([t,r])=>{r.cache_expiredTime&&r.cache_expiredTime<e&&i(t,e=>{c(e),u(e)})})}catch(e){console.warn("Error during periodic cache cleanup:",e)}},r);return{entry:e=>({cache:{get:()=>function(e){const t=n(e);if(t&&void 0!==t.cache)return t.cache_expiredTime&&t.cache_expiredTime>Date.now()?b(t.cache):void i(e,e=>{c(e),u(e)})}(e),remove:()=>function(e){i(e,e=>{c(e),u(e)})}(e),set:(t,r)=>l(e,t,r)},share:{get:()=>function(e){return n(e)?.promise}(e),set:t=>function(e,t){const r=n(e)||{};r.promise=t,a(e,r),t.finally(()=>{i(e,e=>{delete e.promise})})}(e,t)},abort(t,r){r&&r.length>0&&r[r.length-1]!==n(e)?.abortController&&(r.pop()?.abort("race abort"),r.push(t),a(e,{abortController:t}))}}),dispose:()=>{clearInterval(f)},get:n,set:a,remove:s,getAll:()=>({...o}),removeAll:()=>{Object.keys(o).forEach(e=>{delete o[e]})},clearCache:()=>{Object.entries(o).forEach(([e,t])=>{void 0!==t.cache&&i(e,e=>{c(e),u(e)})})},clearExpiredCache:()=>{const e=Date.now();Object.entries(o).forEach(([t,r])=>{r.cache_expiredTime&&r.cache_expiredTime<e&&i(t,e=>{c(e),u(e)})})},abortAll:()=>{Object.entries(o).forEach(([e,t])=>{t.abortController&&t.abortController.abort("abort all")})}}}function v(e,t,r=0){return new Promise((o,n)=>{let a=0;const s=e.getReader(),i=[];!function e(){s.read().then(({done:n,value:s})=>{if(n){const e=new Uint8Array(a);let n=0;return i.forEach(t=>{e.set(t,n),n+=t.length}),t(100,a,r),void o(e.buffer)}s&&(i.push(s),a+=s.length,r>0?t(Math.min(100,Math.round(a/r*100)),a,r):t(0,a,0)),e()}).catch(e=>{console.error("Error reading response body:",e),n(e)})}()})}function E(e,t,r,o,n){return new Promise((a,s)=>{const i=e.entry(r),{share:c,aborts:u,staleTime:l}=n??{},f=new AbortController;if(f.signal.addEventListener("abort",()=>{s(f.signal.reason)}),i.abort(c?f:o,u),c){const e=i.share.get();if(e)return a(e.then(e=>b(e)))}if(l){const e=i.cache.get();if(void 0!==e)return a(e)}const h=t();c&&i.share.set(h),h.then(e=>{a(e),l&&i.cache.set(e,(new Date).getTime()+l)}).catch(e=>s(e))})}var k=j();e.createRequestStore=j,e.createShortApi=A,e.createShortMethods=_,e.createSilentRefresh=function(e){let t=[],r=!1;return(o,n)=>{t.push({success:o,fail:n}),r||(r=!0,e().then(()=>{t.forEach(e=>e.success())}).catch(e=>{t.forEach(e=>e.fail())}).finally(()=>{r=!1,t=[]}))}},e.createSoon=function e(t){const r=A((e,r,o,n,a,s)=>t(e,{...s,method:r,params:o,query:n,body:a})),o=_([...O,"head","options"],e=>(r,o)=>t(r,{...o,method:e}));return{request:t,...r,...o,fork:(r,o)=>e((e,n)=>t(a(e,r),o?{...o,...n}:n))}},e.deepSort=w,e.genRequestKey=S,e.getBodyType=y,e.isBodyJson=function(e){return"json"===y(e)},e.mergeHeaders=c,e.mergeOptions=m,e.mergeSignals=u,e.parseOptions=g,e.parseUrl=i,e.progressDownload=function(e,t){return new Promise((r,o)=>{if(!e.body)return void o(new Error("Response body is null"));const n=e.headers.get("content-length"),a=n?parseInt(n,10):0;v(e.body,t,a).then(r).catch(o)})},e.progressReadBody=v,e.requestWithStore=E,e.soonFetch=async e=>{const t=g(e);if("readable_stream"===t.body_type)return fetch(t.url,t.options);const r=await S({url:e.url,options:{method:t.options?.method,headers:t.options?.headers,body:t.options?.body,query:t.options?.query}},e.sortRequestKey,t.body_type);return E(e.store??k,()=>fetch(t.url,t.options),r,t.abortController,t.options)},e.toFormData=l});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SoonFetch={})}(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});var t=e=>{const t=[],r=e.match(/:([^:/]+)\/?/g);return r&&r.forEach(e=>{t.push(e.replace(/\//g,"").replace(/:/g,""))}),t},r=(e="")=>e.endsWith("/")?e.slice(0,-1):e,o=(e="")=>e.startsWith("/")?e:"/"+e,n=(e="")=>e.startsWith("http"),a=(e,t)=>n(e)?e:r(n(t)?t:o(t))+r(o(e)),s=e=>{if(!e)return[];if(e instanceof URLSearchParams||"string"==typeof e||Array.isArray(e))return Array.from(new URLSearchParams(e).entries());const t=[];return Object.entries(e).forEach(([e,r])=>{(Array.isArray(r)?r:[r]).forEach(r=>{t.push([e,String(r??"")])})}),t},i=(e,r)=>{const{query:o,params:n,baseURL:i}=r;let c=e.trim();t(e).forEach(e=>{n&&void 0!==n[e]&&(c=c.split(":"+e).join(""+n[e]))});const[f,u]=c.split("?"),l=new URLSearchParams([...s(u),...s(o)]),h=a(f??"",i);let p=h;return l.size&&(p=h+"?"+l),{query:l,url:p,path:h}},c=(...e)=>{const t=new Headers;return e.forEach(e=>{e&&(e instanceof Headers?e.forEach((e,r)=>t.set(r,e)):Array.isArray(e)?e.forEach(([e,r])=>t.set(e,r)):Object.entries(e).forEach(([e,r])=>t.set(e,r)))}),t};function f(e,t){const r=(e??[]).filter(e=>!!e);return t&&r.push(AbortSignal.timeout(t)),r.length?AbortSignal.any(r):void 0}function u(e){return[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array].some(t=>e instanceof t)}function l(e){return null!=e&&("object"==typeof e&&(!(e instanceof FormData)&&(!(e instanceof Blob)&&(!(e instanceof ArrayBuffer)&&(!(e instanceof DataView)&&(!(e instanceof ReadableStream)&&(!(e instanceof URLSearchParams)&&!u(e))))))))}function h(e){const t=new FormData;return e&&"object"==typeof e&&!Array.isArray(e)&&Object.entries(e).forEach(([e,r])=>{if(null==r||"function"==typeof r)return;let o;o=r instanceof Blob?r:"object"==typeof r?JSON.stringify(r):String(r),t.append(e,o)}),t}var p=0,y=(e="")=>`${e}_nonce_${Date.now()}_${p++}__`;function d(e){return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function b(e){const t=await e.arrayBuffer();return globalThis.crypto?.subtle?.digest?d(await globalThis.crypto.subtle.digest("SHA-256",t)):y("blob")}async function g(e){if(null==e)return e;if("string"==typeof e)return e;if("object"!=typeof e)return String(e);if(e instanceof FormData){const t={},r=[];e.forEach((e,t)=>r.push([t,e]));for(const[e,o]of r)t[e]=o instanceof Blob?`__blob_${await b(o)}__`:o;return t}if(e instanceof Blob)return`__blob_${await b(e)}__`;if(e instanceof ArrayBuffer)return globalThis.crypto?.subtle?.digest?`__ab_${d(await globalThis.crypto.subtle.digest("SHA-256",e))}__`:y("__ab");if(e instanceof DataView){const t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);return globalThis.crypto?.subtle?.digest?`__ab_${d(await globalThis.crypto.subtle.digest("SHA-256",t))}__`:y("__ab")}return e instanceof URLSearchParams?e.toString():e instanceof ReadableStream?y("_"):(u(e),e)}var m=e=>{if(e instanceof Response)return e.clone();if("function"==typeof e||e instanceof Promise||null===e||"object"!=typeof e)return e;try{return structuredClone(e)}catch(t){return JSON.parse(JSON.stringify(e))}};function O(...e){const t=Object.assign({},...e);return t.headers=c(...e.map(e=>e?.headers)),t.signal=f(e.map(e=>e?.signal),t.timeout),t}function _(e){const{url:t,options:r,baseURL:o,baseOptions:n}=e,a=O(n,r),{url:s,query:c}=i(t,{...a,baseURL:o});a.query=c;const u=a?.body,h=l(u);a.body=h?JSON.stringify(u):null!=u&&"string"!=typeof u&&"object"!=typeof u?String(u):u,h&&a.headers.set("Content-Type","application/json");const p=new AbortController;return a.signal=f([a.signal,p.signal]),{url:s,options:a,is_body_json:h,abortController:p}}var A=["get","post","put","delete","patch"];function S(e,t){const r={};return e.forEach(e=>{r[e]=t(e)}),r}function E(e){const r=(r,o,n)=>{const a=!!t(r).length;return(...t)=>{const s=[...t],{hasBody:i,hasQuery:c,isFormData:f,options:u}=n||{},l=a?s.shift():void 0,p=c?s.shift():void 0;let y=i?s.shift():void 0;f&&(y=h(y));const d=s.shift(),b=u?{...u,...d}:d;return e(r,o,l,p,y,b)}},o={hasBody:!0},n={hasQuery:!0},a={isFormData:!0},s={};return A.forEach(e=>{const t=e.toUpperCase();s[t]=t=>({Ok:()=>r(t,e),Options:o=>({Ok:()=>r(t,e,{options:o})}),Body:()=>({Ok:()=>r(t,e,{...o}),Options:n=>({Ok:()=>r(t,e,{...o,options:n})})}),FormData:()=>({Ok:()=>r(t,e,{...o,...a}),Options:n=>({Ok:()=>r(t,e,{...o,...a,options:n})})}),Params:()=>({Ok:()=>r(t,e),Options:o=>({Ok:()=>r(t,e,{options:o})}),Body:()=>({Ok:()=>r(t,e,{...o}),Options:n=>({Ok:()=>r(t,e,{...o,options:n})})}),FormData:()=>({Ok:()=>r(t,e,{...o,...a}),Options:n=>({Ok:()=>r(t,e,{...o,...a,options:n})})}),Query:()=>({Ok:()=>r(t,e,{...n}),Options:o=>({Ok:()=>r(t,e,{...n,options:o})}),Body:()=>({Ok:()=>r(t,e,{...o,...n}),Options:a=>({Ok:()=>r(t,e,{...o,...n,options:a})})}),FormData:()=>({Ok:()=>r(t,e,{...o,...n,...a}),Options:s=>({Ok:()=>r(t,e,{...o,...n,...a,options:s})})})})}),Query:()=>({Ok:()=>r(t,e,{...n}),Options:o=>({Ok:()=>r(t,e,{...n,options:o})}),Body:()=>({Ok:()=>r(t,e,{...o,...n}),Options:a=>({Ok:()=>r(t,e,{...o,...n,options:a})})}),FormData:()=>({Ok:()=>r(t,e,{...o,...n,...a}),Options:s=>({Ok:()=>r(t,e,{...o,...n,...a,options:s})})})})})}),s}function k(e,t=!1){if(Array.isArray(e)){const r=[...e];return t&&r.sort(),r.map(e=>k(e,t))}if("object"==typeof e&&null!==e){const r={};return Object.keys(e).sort().forEach(o=>{r[o]=k(e[o],t)}),r}return e}function w(e,t,r){const o={body:t,headers:Object.fromEntries(e.headers.entries())};return(e.method??"get").toLowerCase()+e.url+JSON.stringify(r?k(o):o)}function j(e={}){const t=e.maxCacheSize??1e5,r={},o=e=>r[e],n=(e,t)=>{const o=r[e];o?Object.assign(o,t):r[e]={...t}},a=e=>{delete r[e]},s=(e,t)=>{try{const r=o(e);r&&(t(r),Object.keys(r).some(e=>void 0!==r[e])?n(e,r):a(e))}catch(r){console.error("Error during request cleanup:",r);try{a(e)}catch(s){console.error("Failed to remove request after cleanup error:",s)}}},i=e=>delete e.cache,c=e=>delete e.cache_expiredTime;function f(e,a,f){const u=o(e)||{};u.cache=m(a),u.cache_expiredTime=f,n(e,u),(()=>{try{const e=Object.entries(r).filter(([e,t])=>void 0!==t.cache);if(e.length>t){e.sort(([,e],[,t])=>(e.cache_expiredTime||0)-(t.cache_expiredTime||0));const r=e.length-t;e.slice(0,r).forEach(([e])=>{s(e,e=>{i(e),c(e)})})}}catch(e){console.error("Error during cache size management:",e)}})()}const u=()=>{Object.keys(r).forEach(e=>{delete r[e]})},l=()=>{Object.entries(r).forEach(([e,t])=>{t.abortController&&t.abortController.abort("abort all")})};return{entry:e=>({cache:{get:()=>function(e){const t=o(e);if(t&&void 0!==t.cache)return t.cache_expiredTime&&t.cache_expiredTime>Date.now()?m(t.cache):void s(e,e=>{i(e),c(e)})}(e),remove:()=>function(e){s(e,e=>{i(e),c(e)})}(e),set:(t,r)=>f(e,t,r)},share:{get:()=>function(e){return o(e)?.promise}(e),set:t=>function(e,t){const r=o(e)||{};r.promise=t,n(e,r),t.finally(()=>{s(e,e=>{delete e.promise})})}(e,t)},abort(t,r){r&&r.length>0&&r[r.length-1]!==o(e)?.abortController&&(r.pop()?.abort("race abort"),r.push(t),n(e,{abortController:t}))}}),dispose:()=>{l(),u()},get:o,set:n,remove:a,getAll:()=>({...r}),removeAll:u,clearCache:()=>{Object.entries(r).forEach(([e,t])=>{void 0!==t.cache&&s(e,e=>{i(e),c(e)})})},clearExpiredCache:()=>{const e=Date.now();Object.entries(r).forEach(([t,r])=>{r.cache_expiredTime&&r.cache_expiredTime<e&&s(t,e=>{i(e),c(e)})})},abortAll:l}}function v(e,t,r=0){return new Promise((o,n)=>{let a=0;const s=e.getReader(),i=[];!function e(){s.read().then(({done:n,value:s})=>{if(n){const e=new Uint8Array(a);let n=0;return i.forEach(t=>{e.set(t,n),n+=t.length}),t(100,a,r),void o(e.buffer)}s&&(i.push(s),a+=s.length,r>0?t(Math.min(100,Math.round(a/r*100)),a,r):t(0,a,0)),e()}).catch(e=>{console.error("Error reading response body:",e),n(e)})}()})}function T(e,t,r,o,n){return new Promise((a,s)=>{const i=e.entry(r),{share:c,aborts:f,staleTime:u}=n??{},l=new AbortController,h=()=>l.signal.removeEventListener("abort",p),p=()=>{h(),s(l.signal.reason)};if(l.signal.addEventListener("abort",p),i.abort(c?l:o,f),c){const e=i.share.get();if(e)return h(),a(e.then(e=>m(e)))}if(u){const e=i.cache.get();if(void 0!==e)return h(),a(e)}const y=t();c&&i.share.set(y),y.then(e=>{h(),a(e),u&&i.cache.set(e,(new Date).getTime()+u)}).catch(e=>{h(),s(e)})})}var R=j();e.createRequestStore=j,e.createShortApi=E,e.createShortMethods=S,e.createSilentRefresh=function(e){let t=[],r=!1;return(o,n)=>{t.push({success:o,fail:n}),r||(r=!0,e().then(()=>{t.forEach(e=>e.success())}).catch(e=>{t.forEach(e=>e.fail())}).finally(()=>{r=!1,t=[]}))}},e.createSoon=function e(t){const r=E((e,r,o,n,a,s)=>t(e,{...s,method:r,params:o,query:n,body:a})),o=S([...A,"head","options"],e=>(r,o)=>t(r,{...o,method:e}));return{request:t,...r,...o,fork:(r,o)=>e((e,n)=>t(a(e,r),o?{...o,...n}:n))}},e.deepSort=k,e.genRequestKey=function(e,t){const{url:r,options:o}=_(e);return w({url:r,...o},function(e){if(null==e)return e;if("string"==typeof e)return e;if("object"!=typeof e)return String(e);if(e instanceof FormData){const t={},r=[];e.forEach((e,t)=>r.push([t,e]));for(const[e,o]of r)t[e]=o instanceof Blob?y("__blob"):o;return t}return e instanceof URLSearchParams?e.toString():l(e)||u(e)?e:y("_")}(e.options?.body),t)},e.genRequestKeyAsync=async function(e,t){const{url:r,options:o}=_(e);return w({url:r,...o},await g(e.options?.body),t)},e.isBodyJson=l,e.mergeHeaders=c,e.mergeOptions=O,e.mergeSignals=f,e.parseOptions=_,e.parseQuery2Arr=s,e.parseUrl=i,e.progressDownload=function(e,t){return new Promise((r,o)=>{if(!e.body)return void o(new Error("Response body is null"));const n=e.headers.get("content-length"),a=n?parseInt(n,10):0;v(e.body,t,a).then(r).catch(o)})},e.progressReadBody=v,e.requestWithStore=T,e.soonFetch=async e=>{const t=_(e),r=t.options,o=t.url,{share:n,staleTime:a,aborts:s}=r??{};if(!n&&!a&&!s)return fetch(o,r);const i=w({url:o,...r},await g(e.options?.body),e.sortRequestKey);return T(e.store??R,()=>fetch(o,r),i,t.abortController,r)},e.toFormData=h});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soon-fetch",
3
- "version": "4.0.2-beta.0",
3
+ "version": "4.1.0",
4
4
  "description": "a request lib alternative to axios with timeout, request reusing, race, response cache ...",
5
5
  "homepage": "https://github.com/leafio/soon-fetch",
6
6
  "type": "module",