@net-vert/core 1.3.0 → 1.3.1

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.js CHANGED
@@ -1,11 +1,78 @@
1
1
  import { TaskQueue as F } from "id-queue";
2
2
  var h = /* @__PURE__ */ ((r) => (r.GET = "get", r.POST = "post", r.PUT = "put", r.DELETE = "delete", r))(h || {}), m = /* @__PURE__ */ ((r) => (r.CACHE = "cache", r.RETRY = "retry", r.IDEMPOTENT = "idempotent", r.CONCURRENT = "concurrent", r.SYNC = "sync", r))(m || {});
3
- const p = "default", j = {
3
+ const p = "default", I = /* @__PURE__ */ new Map(), ce = (r, e = p) => {
4
+ I.set(e, r);
5
+ }, j = (r = p) => {
6
+ const e = I.get(r);
7
+ if (!e) throw new Error(`Requestor实例 ${String(r)} 未注册`);
8
+ return e;
9
+ }, C = {
10
+ get: (r, e) => ({
11
+ url: r,
12
+ method: h.GET,
13
+ ...e,
14
+ params: e?.params
15
+ }),
16
+ post: (r, e, t) => ({
17
+ url: r,
18
+ method: h.POST,
19
+ data: e,
20
+ ...t
21
+ }),
22
+ delete: (r, e) => ({
23
+ url: r,
24
+ method: h.DELETE,
25
+ ...e
26
+ }),
27
+ put: (r, e, t) => ({
28
+ url: r,
29
+ method: h.PUT,
30
+ data: e,
31
+ ...t
32
+ }),
33
+ request: (r) => r
34
+ }, D = Object.keys(C);
35
+ function T(r, e, t) {
36
+ const n = {}, s = (o) => {
37
+ if (o === e.length)
38
+ return t(r);
39
+ const i = e[o];
40
+ return i({
41
+ config: r,
42
+ ctx: n,
43
+ next: () => s(o + 1)
44
+ });
45
+ };
46
+ return s(0);
47
+ }
48
+ function V(r, e) {
49
+ const t = {}, n = e ?? [];
50
+ return D.forEach(
51
+ (s) => {
52
+ t[s] = (...o) => {
53
+ const i = C[s](...o);
54
+ return T(
55
+ i,
56
+ n,
57
+ r
58
+ );
59
+ };
60
+ }
61
+ ), t;
62
+ }
63
+ function k(r) {
64
+ const { extensions: e, instanceKey: t } = r ?? {}, n = j(t);
65
+ return V(
66
+ n,
67
+ e
68
+ );
69
+ }
70
+ const q = {
4
71
  retries: 3,
5
72
  delay: 0,
6
73
  retryCondition: () => !0
7
- }, D = (r) => {
8
- const e = { ...j, ...r };
74
+ }, E = (r) => {
75
+ const e = { ...q, ...r };
9
76
  return Object.assign(async ({ config: n, next: s }) => {
10
77
  let o = 0, i;
11
78
  for (; o <= e.retries; )
@@ -27,18 +94,18 @@ const p = "default", j = {
27
94
  }
28
95
  throw i;
29
96
  }, { __middlewareType: m.RETRY });
30
- }, T = () => {
97
+ }, R = () => {
31
98
  const r = /* @__PURE__ */ new Map();
32
99
  return { getPromise: (o) => r.get(o), setPromise: (o, i) => {
33
100
  r.set(o, i), i.finally(() => r.delete(o));
34
101
  }, delPromise: (o) => r.delete(o), clearCache: () => r.clear() };
35
- }, V = (r) => {
102
+ }, $ = (r) => {
36
103
  const { config: e } = r, { method: t, url: n, data: s } = e;
37
104
  return [t, n, JSON.stringify(s)].join("|");
38
- }, q = {
39
- key: V
40
- }, E = (r) => {
41
- const e = { ...q, ...r }, t = T();
105
+ }, B = {
106
+ key: $
107
+ }, K = (r) => {
108
+ const e = { ...B, ...r }, t = R();
42
109
  return Object.assign(({ config: s, next: o }) => {
43
110
  const i = e.key({ config: s }), a = t.getPromise(i);
44
111
  if (a)
@@ -50,7 +117,7 @@ const p = "default", j = {
50
117
  promiseCache: t
51
118
  });
52
119
  };
53
- class R {
120
+ class _ {
54
121
  parallelCount;
55
122
  tasks;
56
123
  runningCount;
@@ -84,26 +151,26 @@ class R {
84
151
  }
85
152
  }
86
153
  }
87
- let $ = 0;
88
- const B = {
154
+ let A = 0;
155
+ const J = {
89
156
  parallelCount: 4,
90
- createId: () => $++
91
- }, K = (r) => {
92
- const { parallelCount: e, createId: t } = { ...B, ...r }, n = new R(e);
157
+ createId: () => A++
158
+ }, z = (r) => {
159
+ const { parallelCount: e, createId: t } = { ...J, ...r }, n = new _(e);
93
160
  return Object.assign(({ config: o, next: i }) => {
94
161
  const a = t({ config: o });
95
162
  return n.add(a, () => i());
96
163
  }, { __middlewareType: m.CONCURRENT, pool: n });
97
- }, I = /* @__PURE__ */ new Map(), y = (r, e) => {
98
- I.set(e, r);
164
+ }, S = /* @__PURE__ */ new Map(), y = (r, e) => {
165
+ S.set(e, r);
99
166
  };
100
- function _(r) {
101
- const e = I.get(r);
167
+ function G(r) {
168
+ const e = S.get(r);
102
169
  if (!e)
103
170
  throw new Error(`Store实例 ${String(r)} 未注册`);
104
171
  return e;
105
172
  }
106
- class A {
173
+ class U {
107
174
  store = /* @__PURE__ */ new Map();
108
175
  getItem(e) {
109
176
  return this.store.get(e);
@@ -132,7 +199,7 @@ class A {
132
199
  e(s, n, t), t++;
133
200
  }
134
201
  }
135
- const J = (r) => !!r && (typeof r == "object" || typeof r == "function") && typeof r.then == "function", C = (r) => typeof window < "u" ? r() : {
202
+ const M = (r) => !!r && (typeof r == "object" || typeof r == "function") && typeof r.then == "function", v = (r) => typeof window < "u" ? r() : {
136
203
  getItem() {
137
204
  return null;
138
205
  },
@@ -148,8 +215,8 @@ const J = (r) => !!r && (typeof r == "object" || typeof r == "function") && type
148
215
  get length() {
149
216
  return 0;
150
217
  }
151
- }, l = C(() => window.localStorage);
152
- class z {
218
+ }, l = v(() => window.localStorage);
219
+ class X {
153
220
  constructor() {
154
221
  }
155
222
  getItem(e) {
@@ -199,8 +266,8 @@ class z {
199
266
  });
200
267
  }
201
268
  }
202
- const d = C(() => window.sessionStorage);
203
- class G {
269
+ const d = v(() => window.sessionStorage);
270
+ class Y {
204
271
  constructor() {
205
272
  }
206
273
  getItem(e) {
@@ -250,7 +317,7 @@ class G {
250
317
  });
251
318
  }
252
319
  }
253
- class U {
320
+ class Z {
254
321
  dbName;
255
322
  storeName;
256
323
  dbPromise = null;
@@ -379,11 +446,11 @@ const g = {
379
446
  session: "session",
380
447
  indexeddb: "indexeddb"
381
448
  };
382
- function k(r, e) {
449
+ function b(r, e) {
383
450
  Object.assign(r, e);
384
451
  }
385
- function M(r) {
386
- return k(r, {
452
+ function H(r) {
453
+ return b(r, {
387
454
  async getItemOrDefault(e, t) {
388
455
  const n = await this.getItem(e);
389
456
  return n !== null ? n : t;
@@ -399,8 +466,8 @@ function M(r) {
399
466
  }
400
467
  }), r;
401
468
  }
402
- function X(r) {
403
- return k(r, {
469
+ function L(r) {
470
+ return b(r, {
404
471
  getItemOrDefault(e, t) {
405
472
  const n = this.getItem(e);
406
473
  return n !== null ? n : t;
@@ -416,47 +483,47 @@ function X(r) {
416
483
  }
417
484
  }), r;
418
485
  }
419
- function Y(r) {
486
+ function Q(r) {
420
487
  const e = r.getItem("");
421
- return J(e) ? M(r) : X(r);
488
+ return M(e) ? H(r) : L(r);
422
489
  }
423
490
  function f(r, ...e) {
424
- const t = _(r);
491
+ const t = G(r);
425
492
  let n;
426
493
  try {
427
494
  n = new t(...e);
428
495
  } catch {
429
496
  n = t(...e);
430
497
  }
431
- return Y(n);
498
+ return Q(n);
432
499
  }
433
- y(A, g.memory);
434
- y(z, g.local);
435
- y(G, g.session);
436
- y(U, g.indexeddb);
437
- function S(r, e) {
500
+ y(U, g.memory);
501
+ y(X, g.local);
502
+ y(Y, g.session);
503
+ y(Z, g.indexeddb);
504
+ function N(r, e) {
438
505
  return {
439
506
  value: r,
440
507
  expireAt: Date.now() + e
441
508
  };
442
509
  }
443
- function v(r, e = Date.now()) {
510
+ function P(r, e = Date.now()) {
444
511
  return r.expireAt <= e;
445
512
  }
446
- function Z(r, e = Date.now()) {
447
- return v(r, e) ? void 0 : r.value;
513
+ function W(r, e = Date.now()) {
514
+ return P(r, e) ? void 0 : r.value;
448
515
  }
449
- const H = (r) => {
516
+ const ee = (r) => {
450
517
  const { config: e } = r, { method: t, url: n, data: s } = e;
451
518
  return [t, n, JSON.stringify(s)].join("|");
452
- }, L = () => !0, b = 24 * 60 * 60 * 1e3, Q = {
453
- key: H,
454
- duration: b,
455
- isValid: L,
519
+ }, te = () => !0, x = 24 * 60 * 60 * 1e3, re = {
520
+ key: ee,
521
+ duration: x,
522
+ isValid: te,
456
523
  store: g.memory
457
524
  // 默认不持久化,使用内存存储
458
525
  };
459
- class W {
526
+ class ne {
460
527
  store;
461
528
  constructor(e) {
462
529
  return typeof e == "string" ? this.store = f(e) : (y(e.factory, e.key), this.store = f(e.key)), new Proxy(this, {
@@ -474,8 +541,8 @@ class W {
474
541
  * @param value 要缓存的值
475
542
  * @param duration 过期时长(毫秒),默认 24 小时
476
543
  */
477
- setCache(e, t, n = b) {
478
- const s = S(t, n);
544
+ setCache(e, t, n = x) {
545
+ const s = N(t, n);
479
546
  this.store.setItem(e, s);
480
547
  }
481
548
  /**
@@ -486,7 +553,7 @@ class W {
486
553
  async getCache(e) {
487
554
  const t = await this.store.getItem(e);
488
555
  if (t)
489
- return Z(t);
556
+ return W(t);
490
557
  }
491
558
  /**
492
559
  * 检查是否有有效的缓存(未过期)
@@ -495,11 +562,11 @@ class W {
495
562
  */
496
563
  async hasValidCache(e) {
497
564
  const t = await this.store.getItem(e);
498
- return t ? !v(t) : !1;
565
+ return t ? !P(t) : !1;
499
566
  }
500
567
  }
501
- const ee = W, te = (r) => {
502
- const e = { ...Q, ...r }, t = new ee(e.store), n = (o) => typeof e.duration == "function" ? e.duration(o) : e.duration;
568
+ const se = ne, oe = (r) => {
569
+ const e = { ...re, ...r }, t = new se(e.store), n = (o) => typeof e.duration == "function" ? e.duration(o) : e.duration;
503
570
  return Object.assign(async ({ config: o, next: i }) => {
504
571
  const a = e.key({ config: o }), c = await t.getCache(a);
505
572
  if (c) {
@@ -510,107 +577,41 @@ const ee = W, te = (r) => {
510
577
  })) return c;
511
578
  t.removeItem(a);
512
579
  }
513
- const u = await i(), w = n({ key: a, config: o, cachedData: c, response: u }), O = S(u, w);
580
+ const u = await i(), w = n({ key: a, config: o, cachedData: c, response: u }), O = N(u, w);
514
581
  return t.setItem(a, O), u;
515
582
  }, {
516
583
  __middlewareType: m.CACHE,
517
584
  storage: t
518
585
  });
519
- }, N = /* @__PURE__ */ new Map(), ce = (r, e = p) => {
520
- N.set(e, r);
521
- }, re = (r = p) => {
522
- const e = N.get(r);
523
- if (!e) throw new Error(`Requestor实例 ${String(r)} 未注册`);
524
- return e;
525
- }, P = {
526
- get: (r, e) => ({
527
- url: r,
528
- method: h.GET,
529
- ...e,
530
- params: e?.params
531
- }),
532
- post: (r, e, t) => ({
533
- url: r,
534
- method: h.POST,
535
- data: e,
536
- ...t
537
- }),
538
- delete: (r, e) => ({
539
- url: r,
540
- method: h.DELETE,
541
- ...e
542
- }),
543
- put: (r, e, t) => ({
544
- url: r,
545
- method: h.PUT,
546
- data: e,
547
- ...t
548
- }),
549
- request: (r) => r
550
- }, ne = Object.keys(P);
551
- function se(r, e, t) {
552
- const n = {}, s = (o) => {
553
- if (o === e.length)
554
- return t(r);
555
- const i = e[o];
556
- return i({
557
- config: r,
558
- ctx: n,
559
- next: () => s(o + 1)
560
- });
561
- };
562
- return s(0);
563
- }
564
- function oe(r, e) {
565
- const t = {}, n = e ?? [];
566
- return ne.forEach(
567
- (s) => {
568
- t[s] = (...o) => {
569
- const i = P[s](...o);
570
- return se(
571
- i,
572
- n,
573
- r
574
- );
575
- };
576
- }
577
- ), t;
578
- }
579
- function x(r) {
580
- const { extensions: e, instanceKey: t } = r ?? {}, n = re(t);
581
- return oe(
582
- n,
583
- e
584
- );
585
- }
586
+ };
586
587
  function ue(r) {
587
588
  const { instanceKey: e, key: t, duration: n, isValid: s, store: o, ...i } = r;
588
- return x({
589
+ return k({
589
590
  instanceKey: e,
590
591
  extensions: [
591
- E(i),
592
- te({ key: t, duration: n, isValid: s, store: o })
592
+ K(i),
593
+ oe({ key: t, duration: n, isValid: s, store: o })
593
594
  ]
594
595
  });
595
596
  }
596
597
  function le(r) {
597
598
  const { instanceKey: e, parallelCount: t, createId: n, retries: s, delay: o, retryCondition: i } = r;
598
- return x({
599
+ return k({
599
600
  instanceKey: e,
600
601
  extensions: [
601
- K({ parallelCount: t, createId: n }),
602
- D({ retries: s, delay: o, retryCondition: i })
602
+ z({ parallelCount: t, createId: n }),
603
+ E({ retries: s, delay: o, retryCondition: i })
603
604
  ]
604
605
  });
605
606
  }
606
607
  export {
607
- te as cache,
608
- K as concurrent,
608
+ oe as cache,
609
+ z as concurrent,
609
610
  ue as createCachedIdempotentRequestor,
610
611
  le as createConcurrentRetryRequestor,
611
- x as createRequestor,
612
- E as idempotent,
612
+ k as createRequestor,
613
+ K as idempotent,
613
614
  ce as inject,
614
- D as retry,
615
- re as useRequestor
615
+ E as retry,
616
+ j as useRequestor
616
617
  };
@@ -1 +1 @@
1
- (function(c,m){typeof exports=="object"&&typeof module<"u"?m(exports,require("id-queue")):typeof define=="function"&&define.amd?define(["exports","id-queue"],m):(c=typeof globalThis<"u"?globalThis:c||self,m(c.netVertCore={},c.idQueue))})(this,function(c,m){"use strict";var y=(r=>(r.GET="get",r.POST="post",r.PUT="put",r.DELETE="delete",r))(y||{}),g=(r=>(r.CACHE="cache",r.RETRY="retry",r.IDEMPOTENT="idempotent",r.CONCURRENT="concurrent",r.SYNC="sync",r))(g||{});const C="default",V={retries:3,delay:0,retryCondition:()=>!0},k=r=>{const e={...V,...r};return Object.assign(async({config:n,next:o})=>{let s=0,a;for(;s<=e.retries;)try{return await o()}catch(i){if(a=i,s===e.retries)throw i;const u={config:n,lastResponse:i,attempt:s};if(!e.retryCondition(u))throw i;s++;const h=typeof e.delay=="function"?e.delay(u):e.delay;h>0&&await new Promise(I=>setTimeout(I,h))}throw a},{__middlewareType:g.RETRY})},E=()=>{const r=new Map;return{getPromise:s=>r.get(s),setPromise:(s,a)=>{r.set(s,a),a.finally(()=>r.delete(s))},delPromise:s=>r.delete(s),clearCache:()=>r.clear()}},$={key:r=>{const{config:e}=r,{method:t,url:n,data:o}=e;return[t,n,JSON.stringify(o)].join("|")}},S=r=>{const e={...$,...r},t=E();return Object.assign(({config:o,next:s})=>{const a=e.key({config:o}),i=t.getPromise(a);if(i)return i;const u=s();return t.setPromise(a,u),u},{__middlewareType:g.IDEMPOTENT,promiseCache:t})};class B{parallelCount;tasks;runningCount;constructor(e=4){this.parallelCount=e,this.tasks=new m.TaskQueue,this.runningCount=0}add(e,t){return new Promise((n,o)=>{this.tasks.enqueue(e,{task:t,resolve:n,reject:o}),this._run()})}remove(e){this.tasks.remove(e)}execute(e){const{task:t,resolve:n,reject:o}=e;return t().then(n).catch(o).finally(()=>{this.runningCount--,this._run()})}_run(){for(;this.runningCount<this.parallelCount&&this.tasks.size>0;){const e=this.tasks.dequeue();this.runningCount++,this.execute(e)}}}let K=0;const _={parallelCount:4,createId:()=>K++},v=r=>{const{parallelCount:e,createId:t}={..._,...r},n=new B(e);return Object.assign(({config:s,next:a})=>{const i=t({config:s});return n.add(i,()=>a())},{__middlewareType:g.CONCURRENT,pool:n})},b=new Map,f=(r,e)=>{b.set(e,r)};function A(r){const e=b.get(r);if(!e)throw new Error(`Store实例 ${String(r)} 未注册`);return e}class J{store=new Map;getItem(e){return this.store.get(e)}setItem(e,t){return this.store.set(e,t),t}removeItem(e){this.store.delete(e)}clear(){this.store.clear()}length(){return this.store.size}key(e){return Array.from(this.store.keys())[e]}keys(){return Array.from(this.store.keys())}iterate(e){let t=0;for(const[n,o]of this.store.entries())e(o,n,t),t++}}const z=r=>!!r&&(typeof r=="object"||typeof r=="function")&&typeof r.then=="function",N=r=>typeof window<"u"?r():{getItem(){return null},setItem(){},removeItem(){},clear(){},key(){return null},get length(){return 0}},l=N(()=>window.localStorage);class G{constructor(){}getItem(e){const t=String(e),n=l.getItem(t);if(n!==null)try{return JSON.parse(n)}catch(o){console.error(`Failed to parse value for key: ${t}`,o);return}}setItem(e,t){const n=String(e);try{l.setItem(n,JSON.stringify(t))}catch(o){throw console.error(`Failed to set value for key: ${n}`,o),o}return t}removeItem(e){const t=String(e);l.removeItem(t)}clear(){l.clear()}length(){return l.length}key(e){return l.key(e)}keys(){const e=[];for(let t=0;t<l.length;t++){const n=l.key(t);n&&e.push(n)}return e}iterate(e){this.keys().forEach((t,n)=>{const o=this.getItem(t);o!==void 0&&e(o,t,n)})}}const d=N(()=>window.sessionStorage);class U{constructor(){}getItem(e){const t=String(e),n=d.getItem(t);if(n!==null)try{return JSON.parse(n)}catch(o){console.error(`Failed to parse value for key: ${t}`,o);return}}setItem(e,t){const n=String(e);try{d.setItem(n,JSON.stringify(t))}catch(o){throw console.error(`Failed to set value for key: ${n}`,o),o}return t}removeItem(e){const t=String(e);d.removeItem(t)}clear(){d.clear()}length(){return d.length}key(e){return d.key(e)}keys(){const e=[];for(let t=0;t<d.length;t++){const n=d.key(t);n&&e.push(n)}return e}iterate(e){this.keys().forEach((t,n)=>{const o=this.getItem(t);o!==void 0&&e(o,t,n)})}}class M{dbName;storeName;dbPromise=null;DB_VERSION=1;constructor(e,t){this.dbName=e,this.storeName=t,this.initDB()}initDB(){if(typeof window>"u"||!window.indexedDB){console.warn("IndexedDB is not available");return}this.dbPromise=new Promise((e,t)=>{const n=indexedDB.open(this.dbName,this.DB_VERSION);n.onerror=()=>{t(new Error(`Failed to open database: ${this.dbName}`))},n.onsuccess=()=>{e(n.result)},n.onupgradeneeded=o=>{const s=o.target.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName)}})}async getDB(){if(!this.dbPromise)throw new Error("IndexedDB is not initialized");return this.dbPromise}async withStore(e,t){const n=await this.getDB();return new Promise((o,s)=>{const a=n.transaction([this.storeName],e).objectStore(this.storeName),i=t(a);i.onsuccess=()=>{o(i.result)},i.onerror=()=>{s(i.error)}})}async getItem(e){try{const t=await this.withStore("readonly",n=>n.get(String(e)));return t===void 0?void 0:t}catch(t){console.error(`Failed to get value for key: ${String(e)}`,t);return}}async setItem(e,t){try{return await this.withStore("readwrite",n=>n.put(t,String(e))),t}catch(n){throw console.error(`Failed to set value for key: ${String(e)}`,n),n}}async removeItem(e){try{await this.withStore("readwrite",t=>t.delete(String(e)))}catch(t){throw console.error(`Failed to remove value for key: ${String(e)}`,t),t}}async clear(){try{await this.withStore("readwrite",e=>e.clear())}catch(e){throw console.error("Failed to clear storage",e),e}}async length(){try{return await this.withStore("readonly",e=>e.count())}catch(e){return console.error("Failed to get storage length",e),0}}async key(e){try{return(await this.withStore("readonly",t=>t.getAllKeys()))[e]}catch(t){console.error("Failed to get key",t);return}}async keys(){try{return await this.withStore("readonly",e=>e.getAllKeys())}catch(e){return console.error("Failed to get all keys",e),[]}}async iterate(e){try{const t=(await this.getDB()).transaction([this.storeName],"readonly").objectStore(this.storeName).openCursor();return new Promise((n,o)=>{let s=0;t.onsuccess=a=>{const i=a.target.result;if(i){const u=i.key,h=i.value;e(h,u,s),s++,i.continue()}else n()},t.onerror=()=>{o(t.error)}})}catch(t){console.error("Failed to iterate storage",t)}}}const w={memory:"memory",local:"local",session:"session",indexeddb:"indexeddb"};function P(r,e){Object.assign(r,e)}function X(r){return P(r,{async getItemOrDefault(e,t){const n=await this.getItem(e);return n!==null?n:t},async hasItem(e){return await this.getItem(e)!==null},async removeItems(e){await Promise.all(e.map(t=>this.removeItem(t)))},async getItems(e){return await Promise.all(e.map(t=>this.getItem(t)))}}),r}function Y(r){return P(r,{getItemOrDefault(e,t){const n=this.getItem(e);return n!==null?n:t},hasItem(e){return this.getItem(e)!==null},removeItems(e){e.forEach(t=>this.removeItem(t))},getItems(e){return e.map(t=>this.getItem(t))}}),r}function Z(r){const e=r.getItem("");return z(e)?X(r):Y(r)}function q(r,...e){const t=A(r);let n;try{n=new t(...e)}catch{n=t(...e)}return Z(n)}f(J,w.memory),f(G,w.local),f(U,w.session),f(M,w.indexeddb);function O(r,e){return{value:r,expireAt:Date.now()+e}}function R(r,e=Date.now()){return r.expireAt<=e}function H(r,e=Date.now()){return R(r,e)?void 0:r.value}const L=r=>{const{config:e}=r,{method:t,url:n,data:o}=e;return[t,n,JSON.stringify(o)].join("|")},Q=()=>!0,j=24*60*60*1e3,W={key:L,duration:j,isValid:Q,store:w.memory};class ee{store;constructor(e){return typeof e=="string"?this.store=q(e):(f(e.factory,e.key),this.store=q(e.key)),new Proxy(this,{get(t,n){if(n in t)return t[n];const o=t.store[n];return typeof o=="function"?o.bind(t.store):o}})}setCache(e,t,n=j){const o=O(t,n);this.store.setItem(e,o)}async getCache(e){const t=await this.store.getItem(e);if(t)return H(t)}async hasValidCache(e){const t=await this.store.getItem(e);return t?!R(t):!1}}const te=ee,x=r=>{const e={...W,...r},t=new te(e.store),n=s=>typeof e.duration=="function"?e.duration(s):e.duration;return Object.assign(async({config:s,next:a})=>{const i=e.key({config:s}),u=await t.getCache(i);if(u){if(await e.isValid({key:i,config:s,cachedData:u}))return u;t.removeItem(i)}const h=await a(),I=n({key:i,config:s,cachedData:u,response:h}),ce=O(h,I);return t.setItem(i,ce),h},{__middlewareType:g.CACHE,storage:t})},T=new Map,re=(r,e=C)=>{T.set(e,r)},F=(r=C)=>{const e=T.get(r);if(!e)throw new Error(`Requestor实例 ${String(r)} 未注册`);return e},D={get:(r,e)=>({url:r,method:y.GET,...e,params:e?.params}),post:(r,e,t)=>({url:r,method:y.POST,data:e,...t}),delete:(r,e)=>({url:r,method:y.DELETE,...e}),put:(r,e,t)=>({url:r,method:y.PUT,data:e,...t}),request:r=>r},ne=Object.keys(D);function oe(r,e,t){const n={},o=s=>{if(s===e.length)return t(r);const a=e[s];return a({config:r,ctx:n,next:()=>o(s+1)})};return o(0)}function se(r,e){const t={},n=e??[];return ne.forEach(o=>{t[o]=(...s)=>{const a=D[o](...s);return oe(a,n,r)}}),t}function p(r){const{extensions:e,instanceKey:t}=r??{},n=F(t);return se(n,e)}function ie(r){const{instanceKey:e,key:t,duration:n,isValid:o,store:s,...a}=r;return p({instanceKey:e,extensions:[S(a),x({key:t,duration:n,isValid:o,store:s})]})}function ae(r){const{instanceKey:e,parallelCount:t,createId:n,retries:o,delay:s,retryCondition:a}=r;return p({instanceKey:e,extensions:[v({parallelCount:t,createId:n}),k({retries:o,delay:s,retryCondition:a})]})}c.cache=x,c.concurrent=v,c.createCachedIdempotentRequestor=ie,c.createConcurrentRetryRequestor=ae,c.createRequestor=p,c.idempotent=S,c.inject=re,c.retry=k,c.useRequestor=F,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
1
+ (function(c,m){typeof exports=="object"&&typeof module<"u"?m(exports,require("id-queue")):typeof define=="function"&&define.amd?define(["exports","id-queue"],m):(c=typeof globalThis<"u"?globalThis:c||self,m(c.netVertCore={},c.idQueue))})(this,function(c,m){"use strict";var y=(r=>(r.GET="get",r.POST="post",r.PUT="put",r.DELETE="delete",r))(y||{}),g=(r=>(r.CACHE="cache",r.RETRY="retry",r.IDEMPOTENT="idempotent",r.CONCURRENT="concurrent",r.SYNC="sync",r))(g||{});const C="default",k=new Map,V=(r,e=C)=>{k.set(e,r)},S=(r=C)=>{const e=k.get(r);if(!e)throw new Error(`Requestor实例 ${String(r)} 未注册`);return e},v={get:(r,e)=>({url:r,method:y.GET,...e,params:e?.params}),post:(r,e,t)=>({url:r,method:y.POST,data:e,...t}),delete:(r,e)=>({url:r,method:y.DELETE,...e}),put:(r,e,t)=>({url:r,method:y.PUT,data:e,...t}),request:r=>r},E=Object.keys(v);function $(r,e,t){const n={},o=s=>{if(s===e.length)return t(r);const a=e[s];return a({config:r,ctx:n,next:()=>o(s+1)})};return o(0)}function B(r,e){const t={},n=e??[];return E.forEach(o=>{t[o]=(...s)=>{const a=v[o](...s);return $(a,n,r)}}),t}function p(r){const{extensions:e,instanceKey:t}=r??{},n=S(t);return B(n,e)}const K={retries:3,delay:0,retryCondition:()=>!0},b=r=>{const e={...K,...r};return Object.assign(async({config:n,next:o})=>{let s=0,a;for(;s<=e.retries;)try{return await o()}catch(i){if(a=i,s===e.retries)throw i;const u={config:n,lastResponse:i,attempt:s};if(!e.retryCondition(u))throw i;s++;const h=typeof e.delay=="function"?e.delay(u):e.delay;h>0&&await new Promise(I=>setTimeout(I,h))}throw a},{__middlewareType:g.RETRY})},_=()=>{const r=new Map;return{getPromise:s=>r.get(s),setPromise:(s,a)=>{r.set(s,a),a.finally(()=>r.delete(s))},delPromise:s=>r.delete(s),clearCache:()=>r.clear()}},A={key:r=>{const{config:e}=r,{method:t,url:n,data:o}=e;return[t,n,JSON.stringify(o)].join("|")}},N=r=>{const e={...A,...r},t=_();return Object.assign(({config:o,next:s})=>{const a=e.key({config:o}),i=t.getPromise(a);if(i)return i;const u=s();return t.setPromise(a,u),u},{__middlewareType:g.IDEMPOTENT,promiseCache:t})};class J{parallelCount;tasks;runningCount;constructor(e=4){this.parallelCount=e,this.tasks=new m.TaskQueue,this.runningCount=0}add(e,t){return new Promise((n,o)=>{this.tasks.enqueue(e,{task:t,resolve:n,reject:o}),this._run()})}remove(e){this.tasks.remove(e)}execute(e){const{task:t,resolve:n,reject:o}=e;return t().then(n).catch(o).finally(()=>{this.runningCount--,this._run()})}_run(){for(;this.runningCount<this.parallelCount&&this.tasks.size>0;){const e=this.tasks.dequeue();this.runningCount++,this.execute(e)}}}let z=0;const G={parallelCount:4,createId:()=>z++},P=r=>{const{parallelCount:e,createId:t}={...G,...r},n=new J(e);return Object.assign(({config:s,next:a})=>{const i=t({config:s});return n.add(i,()=>a())},{__middlewareType:g.CONCURRENT,pool:n})},q=new Map,f=(r,e)=>{q.set(e,r)};function U(r){const e=q.get(r);if(!e)throw new Error(`Store实例 ${String(r)} 未注册`);return e}class M{store=new Map;getItem(e){return this.store.get(e)}setItem(e,t){return this.store.set(e,t),t}removeItem(e){this.store.delete(e)}clear(){this.store.clear()}length(){return this.store.size}key(e){return Array.from(this.store.keys())[e]}keys(){return Array.from(this.store.keys())}iterate(e){let t=0;for(const[n,o]of this.store.entries())e(o,n,t),t++}}const X=r=>!!r&&(typeof r=="object"||typeof r=="function")&&typeof r.then=="function",O=r=>typeof window<"u"?r():{getItem(){return null},setItem(){},removeItem(){},clear(){},key(){return null},get length(){return 0}},l=O(()=>window.localStorage);class Y{constructor(){}getItem(e){const t=String(e),n=l.getItem(t);if(n!==null)try{return JSON.parse(n)}catch(o){console.error(`Failed to parse value for key: ${t}`,o);return}}setItem(e,t){const n=String(e);try{l.setItem(n,JSON.stringify(t))}catch(o){throw console.error(`Failed to set value for key: ${n}`,o),o}return t}removeItem(e){const t=String(e);l.removeItem(t)}clear(){l.clear()}length(){return l.length}key(e){return l.key(e)}keys(){const e=[];for(let t=0;t<l.length;t++){const n=l.key(t);n&&e.push(n)}return e}iterate(e){this.keys().forEach((t,n)=>{const o=this.getItem(t);o!==void 0&&e(o,t,n)})}}const d=O(()=>window.sessionStorage);class Z{constructor(){}getItem(e){const t=String(e),n=d.getItem(t);if(n!==null)try{return JSON.parse(n)}catch(o){console.error(`Failed to parse value for key: ${t}`,o);return}}setItem(e,t){const n=String(e);try{d.setItem(n,JSON.stringify(t))}catch(o){throw console.error(`Failed to set value for key: ${n}`,o),o}return t}removeItem(e){const t=String(e);d.removeItem(t)}clear(){d.clear()}length(){return d.length}key(e){return d.key(e)}keys(){const e=[];for(let t=0;t<d.length;t++){const n=d.key(t);n&&e.push(n)}return e}iterate(e){this.keys().forEach((t,n)=>{const o=this.getItem(t);o!==void 0&&e(o,t,n)})}}class H{dbName;storeName;dbPromise=null;DB_VERSION=1;constructor(e,t){this.dbName=e,this.storeName=t,this.initDB()}initDB(){if(typeof window>"u"||!window.indexedDB){console.warn("IndexedDB is not available");return}this.dbPromise=new Promise((e,t)=>{const n=indexedDB.open(this.dbName,this.DB_VERSION);n.onerror=()=>{t(new Error(`Failed to open database: ${this.dbName}`))},n.onsuccess=()=>{e(n.result)},n.onupgradeneeded=o=>{const s=o.target.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName)}})}async getDB(){if(!this.dbPromise)throw new Error("IndexedDB is not initialized");return this.dbPromise}async withStore(e,t){const n=await this.getDB();return new Promise((o,s)=>{const a=n.transaction([this.storeName],e).objectStore(this.storeName),i=t(a);i.onsuccess=()=>{o(i.result)},i.onerror=()=>{s(i.error)}})}async getItem(e){try{const t=await this.withStore("readonly",n=>n.get(String(e)));return t===void 0?void 0:t}catch(t){console.error(`Failed to get value for key: ${String(e)}`,t);return}}async setItem(e,t){try{return await this.withStore("readwrite",n=>n.put(t,String(e))),t}catch(n){throw console.error(`Failed to set value for key: ${String(e)}`,n),n}}async removeItem(e){try{await this.withStore("readwrite",t=>t.delete(String(e)))}catch(t){throw console.error(`Failed to remove value for key: ${String(e)}`,t),t}}async clear(){try{await this.withStore("readwrite",e=>e.clear())}catch(e){throw console.error("Failed to clear storage",e),e}}async length(){try{return await this.withStore("readonly",e=>e.count())}catch(e){return console.error("Failed to get storage length",e),0}}async key(e){try{return(await this.withStore("readonly",t=>t.getAllKeys()))[e]}catch(t){console.error("Failed to get key",t);return}}async keys(){try{return await this.withStore("readonly",e=>e.getAllKeys())}catch(e){return console.error("Failed to get all keys",e),[]}}async iterate(e){try{const t=(await this.getDB()).transaction([this.storeName],"readonly").objectStore(this.storeName).openCursor();return new Promise((n,o)=>{let s=0;t.onsuccess=a=>{const i=a.target.result;if(i){const u=i.key,h=i.value;e(h,u,s),s++,i.continue()}else n()},t.onerror=()=>{o(t.error)}})}catch(t){console.error("Failed to iterate storage",t)}}}const w={memory:"memory",local:"local",session:"session",indexeddb:"indexeddb"};function R(r,e){Object.assign(r,e)}function L(r){return R(r,{async getItemOrDefault(e,t){const n=await this.getItem(e);return n!==null?n:t},async hasItem(e){return await this.getItem(e)!==null},async removeItems(e){await Promise.all(e.map(t=>this.removeItem(t)))},async getItems(e){return await Promise.all(e.map(t=>this.getItem(t)))}}),r}function Q(r){return R(r,{getItemOrDefault(e,t){const n=this.getItem(e);return n!==null?n:t},hasItem(e){return this.getItem(e)!==null},removeItems(e){e.forEach(t=>this.removeItem(t))},getItems(e){return e.map(t=>this.getItem(t))}}),r}function W(r){const e=r.getItem("");return X(e)?L(r):Q(r)}function j(r,...e){const t=U(r);let n;try{n=new t(...e)}catch{n=t(...e)}return W(n)}f(M,w.memory),f(Y,w.local),f(Z,w.session),f(H,w.indexeddb);function x(r,e){return{value:r,expireAt:Date.now()+e}}function T(r,e=Date.now()){return r.expireAt<=e}function ee(r,e=Date.now()){return T(r,e)?void 0:r.value}const te=r=>{const{config:e}=r,{method:t,url:n,data:o}=e;return[t,n,JSON.stringify(o)].join("|")},re=()=>!0,F=24*60*60*1e3,ne={key:te,duration:F,isValid:re,store:w.memory};class oe{store;constructor(e){return typeof e=="string"?this.store=j(e):(f(e.factory,e.key),this.store=j(e.key)),new Proxy(this,{get(t,n){if(n in t)return t[n];const o=t.store[n];return typeof o=="function"?o.bind(t.store):o}})}setCache(e,t,n=F){const o=x(t,n);this.store.setItem(e,o)}async getCache(e){const t=await this.store.getItem(e);if(t)return ee(t)}async hasValidCache(e){const t=await this.store.getItem(e);return t?!T(t):!1}}const se=oe,D=r=>{const e={...ne,...r},t=new se(e.store),n=s=>typeof e.duration=="function"?e.duration(s):e.duration;return Object.assign(async({config:s,next:a})=>{const i=e.key({config:s}),u=await t.getCache(i);if(u){if(await e.isValid({key:i,config:s,cachedData:u}))return u;t.removeItem(i)}const h=await a(),I=n({key:i,config:s,cachedData:u,response:h}),ce=x(h,I);return t.setItem(i,ce),h},{__middlewareType:g.CACHE,storage:t})};function ie(r){const{instanceKey:e,key:t,duration:n,isValid:o,store:s,...a}=r;return p({instanceKey:e,extensions:[N(a),D({key:t,duration:n,isValid:o,store:s})]})}function ae(r){const{instanceKey:e,parallelCount:t,createId:n,retries:o,delay:s,retryCondition:a}=r;return p({instanceKey:e,extensions:[P({parallelCount:t,createId:n}),b({retries:o,delay:s,retryCondition:a})]})}c.cache=D,c.concurrent=P,c.createCachedIdempotentRequestor=ie,c.createConcurrentRetryRequestor=ae,c.createRequestor=p,c.idempotent=N,c.inject=V,c.retry=b,c.useRequestor=S,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,36 +1,36 @@
1
1
  {
2
- "name": "@net-vert/core",
3
- "version": "1.3.0",
4
- "description": "Dependency Inversion Network Library with Type-Safe Injection.",
5
- "main": "dist/index",
6
- "type": "module",
7
- "types": "dist/index.d.ts",
8
- "scripts": {
9
- "test": "vitest run",
10
- "build": "run-p type-check build-only",
11
- "build-only": "vite build",
12
- "type-check": "tsc --noEmit"
13
- },
14
- "files": [
15
- "dist"
16
- ],
17
- "sideEffects": false,
18
- "keywords": [
19
- "dependency-injection",
20
- "di",
21
- "network-library",
22
- "adapter-pattern",
23
- "extensible",
24
- "http-client",
25
- "lightweight"
26
- ],
27
- "author": "yuzinan <1589937631@qq.com>",
28
- "license": "MIT",
29
- "publishConfig": {
30
- "access": "public"
31
- },
32
- "dependencies": {
33
- "id-queue": "^1.1.1",
34
- "store-vert": "^0.2.0"
35
- }
36
- }
2
+ "name": "@net-vert/core",
3
+ "version": "1.3.1",
4
+ "description": "Dependency Inversion Network Library with Type-Safe Injection.",
5
+ "main": "dist/index",
6
+ "type": "module",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "sideEffects": false,
12
+ "keywords": [
13
+ "dependency-injection",
14
+ "di",
15
+ "network-library",
16
+ "adapter-pattern",
17
+ "extensible",
18
+ "http-client",
19
+ "lightweight"
20
+ ],
21
+ "author": "yuzinan <1589937631@qq.com>",
22
+ "license": "MIT",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "dependencies": {
27
+ "id-queue": "^1.1.1",
28
+ "store-vert": "^0.2.0"
29
+ },
30
+ "scripts": {
31
+ "test": "vitest run",
32
+ "build": "run-p type-check build-only",
33
+ "build-only": "vite build",
34
+ "type-check": "tsc --noEmit"
35
+ }
36
+ }