@citruslime/vue-utils 2.0.4-beta.2 → 2.0.4-beta.3

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.
@@ -1,17 +1,18 @@
1
1
  import { replacePlaceholders as Y } from "@citruslime/utils";
2
- import { shallowRef as O, shallowReadonly as ie, toRef as le, readonly as V, ref as se, customRef as ue, toValue as E, getCurrentScope as ce, onScopeDispose as fe, watch as _, nextTick as Z, isRef as ne, computed as de } from "vue";
2
+ import { shallowRef as O, shallowReadonly as ae, toRef as le, readonly as z, ref as se, customRef as ue, toValue as E, getCurrentScope as ce, onScopeDispose as fe, watch as _, nextTick as Z, isRef as ne, computed as de } from "vue";
3
3
  const Pe = [
4
4
  "GET",
5
5
  "POST",
6
6
  "PUT",
7
7
  "DELETE"
8
8
  ];
9
- function De(e, t, i = null, u = null) {
9
+ function De(e, t, a = null, c = null, h = null) {
10
10
  return {
11
11
  url: e,
12
12
  type: t,
13
- headers: i ?? oe,
14
- hasBody: pe(t, u)
13
+ headers: a ?? oe,
14
+ hasBody: pe(t, c),
15
+ options: h ?? {}
15
16
  };
16
17
  }
17
18
  function oe() {
@@ -28,25 +29,25 @@ function re(e) {
28
29
  }
29
30
  // @__NO_SIDE_EFFECTS__
30
31
  function I() {
31
- const e = /* @__PURE__ */ new Set(), t = (a) => {
32
- e.delete(a);
32
+ const e = /* @__PURE__ */ new Set(), t = (l) => {
33
+ e.delete(l);
33
34
  };
34
35
  return {
35
- on: (a) => {
36
- e.add(a);
37
- const n = () => t(a);
36
+ on: (l) => {
37
+ e.add(l);
38
+ const n = () => t(l);
38
39
  return re(n), {
39
40
  off: n
40
41
  };
41
42
  },
42
43
  off: t,
43
- trigger: (...a) => Promise.all(Array.from(e).map((n) => n(...a))),
44
+ trigger: (...l) => Promise.all(Array.from(e).map((n) => n(...l))),
44
45
  clear: () => {
45
46
  e.clear();
46
47
  }
47
48
  };
48
49
  }
49
- const ae = typeof window < "u" && typeof document < "u";
50
+ const ie = typeof window < "u" && typeof document < "u";
50
51
  typeof WorkerGlobalScope < "u" && globalThis instanceof WorkerGlobalScope;
51
52
  const he = () => {
52
53
  };
@@ -54,145 +55,145 @@ function L(...e) {
54
55
  if (e.length !== 1)
55
56
  return le(...e);
56
57
  const t = e[0];
57
- return typeof t == "function" ? V(ue(() => ({ get: t, set: he }))) : se(t);
58
+ return typeof t == "function" ? z(ue(() => ({ get: t, set: he }))) : se(t);
58
59
  }
59
- function ee(e, t = !1, i = "Timeout") {
60
- return new Promise((u, v) => {
61
- setTimeout(t ? () => v(i) : u, e);
60
+ function ee(e, t = !1, a = "Timeout") {
61
+ return new Promise((c, h) => {
62
+ setTimeout(t ? () => h(a) : c, e);
62
63
  });
63
64
  }
64
65
  function ye(e, ...t) {
65
- return t.some((i) => i in e);
66
+ return t.some((a) => a in e);
66
67
  }
67
- function z(e, t = !1) {
68
- function i(o, { flush: d = "sync", deep: l = !1, timeout: m, throwOnTimeout: g } = {}) {
69
- let p = null;
68
+ function Q(e, t = !1) {
69
+ function a(o, { flush: u = "sync", deep: m = !1, timeout: i, throwOnTimeout: b } = {}) {
70
+ let y = null;
70
71
  const P = [new Promise((w) => {
71
- p = _(
72
+ y = _(
72
73
  e,
73
- (T) => {
74
- o(T) !== t && (p ? p() : Z(() => p?.()), w(T));
74
+ (v) => {
75
+ o(v) !== t && (y ? y() : Z(() => y?.()), w(v));
75
76
  },
76
77
  {
77
- flush: d,
78
- deep: l,
78
+ flush: u,
79
+ deep: m,
79
80
  immediate: !0
80
81
  }
81
82
  );
82
83
  })];
83
- return m != null && P.push(
84
- ee(m, g).then(() => E(e)).finally(() => p?.())
84
+ return i != null && P.push(
85
+ ee(i, b).then(() => E(e)).finally(() => y?.())
85
86
  ), Promise.race(P);
86
87
  }
87
- function u(o, d) {
88
+ function c(o, u) {
88
89
  if (!ne(o))
89
- return i((T) => T === o, d);
90
- const { flush: l = "sync", deep: m = !1, timeout: g, throwOnTimeout: p } = d ?? {};
91
- let y = null;
92
- const w = [new Promise((T) => {
93
- y = _(
90
+ return a((v) => v === o, u);
91
+ const { flush: m = "sync", deep: i = !1, timeout: b, throwOnTimeout: y } = u ?? {};
92
+ let T = null;
93
+ const w = [new Promise((v) => {
94
+ T = _(
94
95
  [e, o],
95
96
  ([J, D]) => {
96
- t !== (J === D) && (y ? y() : Z(() => y?.()), T(J));
97
+ t !== (J === D) && (T ? T() : Z(() => T?.()), v(J));
97
98
  },
98
99
  {
99
- flush: l,
100
- deep: m,
100
+ flush: m,
101
+ deep: i,
101
102
  immediate: !0
102
103
  }
103
104
  );
104
105
  })];
105
- return g != null && w.push(
106
- ee(g, p).then(() => E(e)).finally(() => (y?.(), E(e)))
106
+ return b != null && w.push(
107
+ ee(b, y).then(() => E(e)).finally(() => (T?.(), E(e)))
107
108
  ), Promise.race(w);
108
109
  }
109
- function v(o) {
110
- return i((d) => !!d, o);
110
+ function h(o) {
111
+ return a((u) => !!u, o);
111
112
  }
112
- function a(o) {
113
- return u(null, o);
113
+ function l(o) {
114
+ return c(null, o);
114
115
  }
115
116
  function n(o) {
116
- return u(void 0, o);
117
+ return c(void 0, o);
117
118
  }
118
119
  function r(o) {
119
- return i(Number.isNaN, o);
120
+ return a(Number.isNaN, o);
120
121
  }
121
- function F(o, d) {
122
- return i((l) => {
123
- const m = Array.from(l);
124
- return m.includes(o) || m.includes(E(o));
125
- }, d);
122
+ function p(o, u) {
123
+ return a((m) => {
124
+ const i = Array.from(m);
125
+ return i.includes(o) || i.includes(E(o));
126
+ }, u);
126
127
  }
127
- function s(o) {
128
- return h(1, o);
128
+ function g(o) {
129
+ return s(1, o);
129
130
  }
130
- function h(o = 1, d) {
131
- let l = -1;
132
- return i(() => (l += 1, l >= o), d);
131
+ function s(o = 1, u) {
132
+ let m = -1;
133
+ return a(() => (m += 1, m >= o), u);
133
134
  }
134
135
  return Array.isArray(E(e)) ? {
135
- toMatch: i,
136
- toContains: F,
137
- changed: s,
138
- changedTimes: h,
136
+ toMatch: a,
137
+ toContains: p,
138
+ changed: g,
139
+ changedTimes: s,
139
140
  get not() {
140
- return z(e, !t);
141
+ return Q(e, !t);
141
142
  }
142
143
  } : {
143
- toMatch: i,
144
- toBe: u,
145
- toBeTruthy: v,
146
- toBeNull: a,
144
+ toMatch: a,
145
+ toBe: c,
146
+ toBeTruthy: h,
147
+ toBeNull: l,
147
148
  toBeNaN: r,
148
149
  toBeUndefined: n,
149
- changed: s,
150
- changedTimes: h,
150
+ changed: g,
151
+ changedTimes: s,
151
152
  get not() {
152
- return z(e, !t);
153
+ return Q(e, !t);
153
154
  }
154
155
  };
155
156
  }
156
157
  function me(e) {
157
- return z(e);
158
+ return Q(e);
158
159
  }
159
- function Te(e, t, i = {}) {
160
+ function Te(e, t, a = {}) {
160
161
  const {
161
- immediate: u = !0,
162
- immediateCallback: v = !1
163
- } = i, a = O(!1);
162
+ immediate: c = !0,
163
+ immediateCallback: h = !1
164
+ } = a, l = O(!1);
164
165
  let n;
165
166
  function r() {
166
167
  n && (clearTimeout(n), n = void 0);
167
168
  }
168
- function F() {
169
- a.value = !1, r();
169
+ function p() {
170
+ l.value = !1, r();
170
171
  }
171
- function s(...h) {
172
- v && e(), r(), a.value = !0, n = setTimeout(() => {
173
- a.value = !1, n = void 0, e(...h);
172
+ function g(...s) {
173
+ h && e(), r(), l.value = !0, n = setTimeout(() => {
174
+ l.value = !1, n = void 0, e(...s);
174
175
  }, E(t));
175
176
  }
176
- return u && (a.value = !0, ae && s()), re(F), {
177
- isPending: ie(a),
178
- start: s,
179
- stop: F
177
+ return c && (l.value = !0, ie && g()), re(p), {
178
+ isPending: ae(l),
179
+ start: g,
180
+ stop: p
180
181
  };
181
182
  }
182
- const ve = ae ? window : void 0, ge = {
183
+ const ve = ie ? window : void 0, ge = {
183
184
  json: "application/json",
184
185
  text: "text/plain"
185
186
  };
186
187
  function te(e) {
187
188
  return e && ye(e, "immediate", "refetch", "initialData", "timeout", "beforeFetch", "afterFetch", "onFetchError", "fetch", "updateDataOnError");
188
189
  }
189
- function R(e) {
190
+ function V(e) {
190
191
  return typeof Headers < "u" && e instanceof Headers ? Object.fromEntries(e.entries()) : e;
191
192
  }
192
193
  function be(e, ...t) {
193
- var i, u;
194
- const v = typeof AbortController == "function";
195
- let a = {}, n = {
194
+ var a, c;
195
+ const h = typeof AbortController == "function";
196
+ let l = {}, n = {
196
197
  immediate: !0,
197
198
  refetch: !1,
198
199
  timeout: 0,
@@ -203,104 +204,104 @@ function be(e, ...t) {
203
204
  type: "text",
204
205
  payload: void 0
205
206
  };
206
- t.length > 0 && (te(t[0]) ? n = { ...n, ...t[0] } : a = t[0]), t.length > 1 && te(t[1]) && (n = { ...n, ...t[1] });
207
+ t.length > 0 && (te(t[0]) ? n = { ...n, ...t[0] } : l = t[0]), t.length > 1 && te(t[1]) && (n = { ...n, ...t[1] });
207
208
  const {
208
- fetch: F = (u = (i = ve) == null ? void 0 : i.fetch) != null ? u : globalThis?.fetch,
209
- initialData: s,
210
- timeout: h
211
- } = n, o = /* @__PURE__ */ I(), d = /* @__PURE__ */ I(), l = /* @__PURE__ */ I(), m = O(!1), g = O(!1), p = O(!1), y = O(null), P = O(null), w = O(null), T = O(s || null), J = de(() => v && g.value);
209
+ fetch: p = (c = (a = ve) == null ? void 0 : a.fetch) != null ? c : globalThis?.fetch,
210
+ initialData: g,
211
+ timeout: s
212
+ } = n, o = /* @__PURE__ */ I(), u = /* @__PURE__ */ I(), m = /* @__PURE__ */ I(), i = O(!1), b = O(!1), y = O(!1), T = O(null), P = O(null), w = O(null), v = O(g || null), J = de(() => h && b.value);
212
213
  let D, N;
213
- const M = (c) => {
214
- v && (D?.abort(c), D = new AbortController(), D.signal.onabort = () => p.value = !0, a = {
215
- ...a,
214
+ const M = (f) => {
215
+ h && (D?.abort(f), D = new AbortController(), D.signal.onabort = () => y.value = !0, l = {
216
+ ...l,
216
217
  signal: D.signal
217
218
  });
218
- }, $ = (c) => {
219
- g.value = c, m.value = !c;
219
+ }, $ = (f) => {
220
+ b.value = f, i.value = !f;
220
221
  };
221
- h && (N = Te(M, h, { immediate: !1 }));
222
+ s && (N = Te(M, s, { immediate: !1 }));
222
223
  let K = 0;
223
- const B = async (c = !1) => {
224
- var b, x;
225
- M(), $(!0), w.value = null, y.value = null, p.value = !1, K += 1;
226
- const U = K, A = {
224
+ const B = async (f = !1) => {
225
+ var F, x;
226
+ M(), $(!0), w.value = null, T.value = null, y.value = !1, K += 1;
227
+ const U = K, S = {
227
228
  method: r.method,
228
229
  headers: {}
229
230
  }, H = E(r.payload);
230
231
  if (H) {
231
- const f = R(A.headers), G = Object.getPrototypeOf(H);
232
- !r.payloadType && H && (G === Object.prototype || Array.isArray(G)) && !(H instanceof FormData) && (r.payloadType = "json"), r.payloadType && (f["Content-Type"] = (b = ge[r.payloadType]) != null ? b : r.payloadType), A.body = r.payloadType === "json" ? JSON.stringify(H) : H;
232
+ const d = V(S.headers), G = Object.getPrototypeOf(H);
233
+ !r.payloadType && H && (G === Object.prototype || Array.isArray(G)) && !(H instanceof FormData) && (r.payloadType = "json"), r.payloadType && (d["Content-Type"] = (F = ge[r.payloadType]) != null ? F : r.payloadType), S.body = r.payloadType === "json" ? JSON.stringify(H) : H;
233
234
  }
234
235
  let X = !1;
235
- const S = {
236
+ const A = {
236
237
  url: E(e),
237
238
  options: {
238
- ...A,
239
- ...a
239
+ ...S,
240
+ ...l
240
241
  },
241
242
  cancel: () => {
242
243
  X = !0;
243
244
  }
244
245
  };
245
- if (n.beforeFetch && Object.assign(S, await n.beforeFetch(S)), X || !F)
246
+ if (n.beforeFetch && Object.assign(A, await n.beforeFetch(A)), X || !p)
246
247
  return $(!1), Promise.resolve(null);
247
248
  let C = null;
248
- return N && N.start(), F(
249
- S.url,
249
+ return N && N.start(), p(
250
+ A.url,
250
251
  {
251
- ...A,
252
- ...S.options,
252
+ ...S,
253
+ ...A.options,
253
254
  headers: {
254
- ...R(A.headers),
255
- ...R((x = S.options) == null ? void 0 : x.headers)
255
+ ...V(S.headers),
256
+ ...V((x = A.options) == null ? void 0 : x.headers)
256
257
  }
257
258
  }
258
- ).then(async (f) => {
259
- if (P.value = f, y.value = f.status, C = await f.clone()[r.type](), !f.ok)
260
- throw T.value = s || null, new Error(f.statusText);
259
+ ).then(async (d) => {
260
+ if (P.value = d, T.value = d.status, C = await d.clone()[r.type](), !d.ok)
261
+ throw v.value = g || null, new Error(d.statusText);
261
262
  return n.afterFetch && ({ data: C } = await n.afterFetch({
262
263
  data: C,
263
- response: f,
264
- context: S,
264
+ response: d,
265
+ context: A,
265
266
  execute: B
266
- })), T.value = C, o.trigger(f), f;
267
- }).catch(async (f) => {
268
- let G = f.message || f.name;
267
+ })), v.value = C, o.trigger(d), d;
268
+ }).catch(async (d) => {
269
+ let G = d.message || d.name;
269
270
  if (n.onFetchError && ({ error: G, data: C } = await n.onFetchError({
270
271
  data: C,
271
- error: f,
272
+ error: d,
272
273
  response: P.value,
273
- context: S,
274
+ context: A,
274
275
  execute: B
275
- })), w.value = G, n.updateDataOnError && (T.value = C), d.trigger(f), c)
276
- throw f;
276
+ })), w.value = G, n.updateDataOnError && (v.value = C), u.trigger(d), f)
277
+ throw d;
277
278
  return null;
278
279
  }).finally(() => {
279
- U === K && $(!1), N && N.stop(), l.trigger(null);
280
+ U === K && $(!1), N && N.stop(), m.trigger(null);
280
281
  });
281
- }, Q = L(n.refetch);
282
+ }, R = L(n.refetch);
282
283
  _(
283
284
  [
284
- Q,
285
+ R,
285
286
  L(e)
286
287
  ],
287
- ([c]) => c && B(),
288
+ ([f]) => f && B(),
288
289
  { deep: !0 }
289
290
  );
290
291
  const W = {
291
- isFinished: V(m),
292
- isFetching: V(g),
293
- statusCode: y,
292
+ isFinished: z(i),
293
+ isFetching: z(b),
294
+ statusCode: T,
294
295
  response: P,
295
296
  error: w,
296
- data: T,
297
+ data: v,
297
298
  canAbort: J,
298
- aborted: p,
299
+ aborted: y,
299
300
  abort: M,
300
301
  execute: B,
301
302
  onFetchResponse: o.on,
302
- onFetchError: d.on,
303
- onFetchFinally: l.on,
303
+ onFetchError: u.on,
304
+ onFetchFinally: m.on,
304
305
  // method
305
306
  get: j("GET"),
306
307
  put: j("PUT"),
@@ -316,84 +317,88 @@ function be(e, ...t) {
316
317
  arrayBuffer: k("arrayBuffer"),
317
318
  formData: k("formData")
318
319
  };
319
- function j(c) {
320
- return (b, x) => {
321
- if (!g.value)
322
- return r.method = c, r.payload = b, r.payloadType = x, ne(r.payload) && _(
320
+ function j(f) {
321
+ return (F, x) => {
322
+ if (!b.value)
323
+ return r.method = f, r.payload = F, r.payloadType = x, ne(r.payload) && _(
323
324
  [
324
- Q,
325
+ R,
325
326
  L(r.payload)
326
327
  ],
327
328
  ([U]) => U && B(),
328
329
  { deep: !0 }
329
330
  ), {
330
331
  ...W,
331
- then(U, A) {
332
- return q().then(U, A);
332
+ then(U, S) {
333
+ return q().then(U, S);
333
334
  }
334
335
  };
335
336
  };
336
337
  }
337
338
  function q() {
338
- return new Promise((c, b) => {
339
- me(m).toBe(!0).then(() => c(W)).catch(b);
339
+ return new Promise((f, F) => {
340
+ me(i).toBe(!0).then(() => f(W)).catch(F);
340
341
  });
341
342
  }
342
- function k(c) {
343
+ function k(f) {
343
344
  return () => {
344
- if (!g.value)
345
- return r.type = c, {
345
+ if (!b.value)
346
+ return r.type = f, {
346
347
  ...W,
347
- then(b, x) {
348
- return q().then(b, x);
348
+ then(F, x) {
349
+ return q().then(F, x);
349
350
  }
350
351
  };
351
352
  };
352
353
  }
353
354
  return n.immediate && Promise.resolve().then(() => B()), {
354
355
  ...W,
355
- then(c, b) {
356
- return q().then(c, b);
356
+ then(f, F) {
357
+ return q().then(f, F);
357
358
  }
358
359
  };
359
360
  }
360
- function je(e, t, i = "/api/") {
361
- const u = {};
362
- return Object.keys(e).forEach((a) => {
363
- u[a] = (...n) => {
364
- const r = e[a], F = r.type;
365
- let s = r.url;
366
- s.startsWith("http") || (s = `${i}${s}`), r.hasBody ? s = Y(s, ...n.splice(1)) : s = Y(s, ...n);
367
- const h = {
361
+ function je(e, t, a = "/api/", c) {
362
+ const h = {};
363
+ return Object.keys(e).forEach((n) => {
364
+ h[n] = (...r) => {
365
+ const p = e[n], g = p.type;
366
+ let s = p.url;
367
+ s.startsWith("http") || (s = `${a}${s}`), p.hasBody ? s = Y(s, ...r.splice(1)) : s = Y(s, ...r);
368
+ const o = {
368
369
  ...oe(),
369
- ...r.headers()
370
+ ...p.headers()
370
371
  };
371
- Fe(h);
372
- const o = be(
372
+ Fe(o);
373
+ const u = be(
373
374
  s,
374
375
  {
375
- method: F
376
+ ...p.options,
377
+ method: g
376
378
  },
377
379
  {
378
380
  immediate: !1,
379
- beforeFetch({ options: l }) {
380
- return l.headers = {
381
- ...l.headers,
382
- ...h
383
- }, r.hasBody && n.length && (l.body = JSON.stringify(n[0])), {
384
- options: l
381
+ beforeFetch({ options: i }) {
382
+ return i.headers = {
383
+ ...i.headers,
384
+ ...o
385
+ }, p.hasBody && r.length && (i.body = JSON.stringify(r[0])), {
386
+ options: i
385
387
  };
386
388
  },
387
- onFetchError(l) {
388
- return l?.response && t(l), l;
389
+ onFetchError(i) {
390
+ return i?.response && t(i), i;
391
+ },
392
+ afterFetch(i) {
393
+ return c && c(i, p), i;
389
394
  }
390
395
  }
391
396
  );
392
397
  return {
393
- ...we(h) === "application/json" ? o.json() : o.text()
398
+ ...we(o) === "application/json" ? u.json() : u.text()
394
399
  };
395
400
  };
396
- }), u;
401
+ }), h;
397
402
  }
398
403
  function Fe(e) {
399
404
  e["content-type"] === "multipart/form-data" && delete e["content-type"];
@@ -401,11 +406,11 @@ function Fe(e) {
401
406
  function we(e) {
402
407
  return e.accept ?? "*/*";
403
408
  }
404
- function Ae(e) {
409
+ function Se(e) {
405
410
  return JSON.parse(JSON.stringify(e));
406
411
  }
407
412
  export {
408
- Ae as copy,
413
+ Se as copy,
409
414
  De as createEndpoint,
410
415
  oe as getDefaultHeaders,
411
416
  Pe as requestTypes,
@@ -1 +1 @@
1
- (function(y,H){typeof exports=="object"&&typeof module<"u"?H(exports,require("@citruslime/utils"),require("vue")):typeof define=="function"&&define.amd?define(["exports","@citruslime/utils","vue"],H):(y=typeof globalThis<"u"?globalThis:y||self,H(y.CitrusLimeVueUtils={},y.CLUtils,y.Vue))})(this,(function(y,H,t){"use strict";const ne=["GET","POST","PUT","DELETE"];function oe(e,n,l=null,u=null){return{url:e,type:n,headers:l??J,hasBody:re(n,u)}}function J(){return{accept:"application/json","content-type":"application/json"}}function re(e,n){return!!(n===null&&(e==="PUT"||e==="POST")||n)}function Q(e){return t.getCurrentScope()?(t.onScopeDispose(e),!0):!1}function M(){const e=new Set,n=a=>{e.delete(a)};return{on:a=>{e.add(a);const o=()=>n(a);return Q(o),{off:o}},off:n,trigger:(...a)=>Promise.all(Array.from(e).map(o=>o(...a))),clear:()=>{e.clear()}}}const X=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const ie=()=>{};function W(...e){if(e.length!==1)return t.toRef(...e);const n=e[0];return typeof n=="function"?t.readonly(t.customRef(()=>({get:n,set:ie}))):t.ref(n)}function Y(e,n=!1,l="Timeout"){return new Promise((u,b)=>{setTimeout(n?()=>b(l):u,e)})}function ae(e,...n){return n.some(l=>l in e)}function _(e,n=!1){function l(r,{flush:p="sync",deep:s=!1,timeout:w,throwOnTimeout:F}={}){let h=null;const D=[new Promise(P=>{h=t.watch(e,g=>{r(g)!==n&&(h?h():t.nextTick(()=>h?.()),P(g))},{flush:p,deep:s,immediate:!0})})];return w!=null&&D.push(Y(w,F).then(()=>t.toValue(e)).finally(()=>h?.())),Promise.race(D)}function u(r,p){if(!t.isRef(r))return l(g=>g===r,p);const{flush:s="sync",deep:w=!1,timeout:F,throwOnTimeout:h}=p??{};let T=null;const P=[new Promise(g=>{T=t.watch([e,r],([G,j])=>{n!==(G===j)&&(T?T():t.nextTick(()=>T?.()),g(G))},{flush:s,deep:w,immediate:!0})})];return F!=null&&P.push(Y(F,h).then(()=>t.toValue(e)).finally(()=>(T?.(),t.toValue(e)))),Promise.race(P)}function b(r){return l(p=>!!p,r)}function a(r){return u(null,r)}function o(r){return u(void 0,r)}function i(r){return l(Number.isNaN,r)}function E(r,p){return l(s=>{const w=Array.from(s);return w.includes(r)||w.includes(t.toValue(r))},p)}function c(r){return m(1,r)}function m(r=1,p){let s=-1;return l(()=>(s+=1,s>=r),p)}return Array.isArray(t.toValue(e))?{toMatch:l,toContains:E,changed:c,changedTimes:m,get not(){return _(e,!n)}}:{toMatch:l,toBe:u,toBeTruthy:b,toBeNull:a,toBeNaN:i,toBeUndefined:o,changed:c,changedTimes:m,get not(){return _(e,!n)}}}function le(e){return _(e)}function se(e,n,l={}){const{immediate:u=!0,immediateCallback:b=!1}=l,a=t.shallowRef(!1);let o;function i(){o&&(clearTimeout(o),o=void 0)}function E(){a.value=!1,i()}function c(...m){b&&e(),i(),a.value=!0,o=setTimeout(()=>{a.value=!1,o=void 0,e(...m)},t.toValue(n))}return u&&(a.value=!0,X&&c()),Q(E),{isPending:t.shallowReadonly(a),start:c,stop:E}}const ce=X?window:void 0,ue={json:"application/json",text:"text/plain"};function Z(e){return e&&ae(e,"immediate","refetch","initialData","timeout","beforeFetch","afterFetch","onFetchError","fetch","updateDataOnError")}function L(e){return typeof Headers<"u"&&e instanceof Headers?Object.fromEntries(e.entries()):e}function fe(e,...n){var l,u;const b=typeof AbortController=="function";let a={},o={immediate:!0,refetch:!1,timeout:0,updateDataOnError:!1};const i={method:"GET",type:"text",payload:void 0};n.length>0&&(Z(n[0])?o={...o,...n[0]}:a=n[0]),n.length>1&&Z(n[1])&&(o={...o,...n[1]});const{fetch:E=(u=(l=ce)==null?void 0:l.fetch)!=null?u:globalThis?.fetch,initialData:c,timeout:m}=o,r=M(),p=M(),s=M(),w=t.shallowRef(!1),F=t.shallowRef(!1),h=t.shallowRef(!1),T=t.shallowRef(null),D=t.shallowRef(null),P=t.shallowRef(null),g=t.shallowRef(c||null),G=t.computed(()=>b&&F.value);let j,R;const K=f=>{b&&(j?.abort(f),j=new AbortController,j.signal.onabort=()=>h.value=!0,a={...a,signal:j.signal})},$=f=>{F.value=f,w.value=!f};m&&(R=se(K,m,{immediate:!1}));let I=0;const V=async(f=!1)=>{var O,x;K(),$(!0),P.value=null,T.value=null,h.value=!1,I+=1;const k=I,A={method:i.method,headers:{}},N=t.toValue(i.payload);if(N){const d=L(A.headers),v=Object.getPrototypeOf(N);!i.payloadType&&N&&(v===Object.prototype||Array.isArray(v))&&!(N instanceof FormData)&&(i.payloadType="json"),i.payloadType&&(d["Content-Type"]=(O=ue[i.payloadType])!=null?O:i.payloadType),A.body=i.payloadType==="json"?JSON.stringify(N):N}let te=!1;const C={url:t.toValue(e),options:{...A,...a},cancel:()=>{te=!0}};if(o.beforeFetch&&Object.assign(C,await o.beforeFetch(C)),te||!E)return $(!1),Promise.resolve(null);let B=null;return R&&R.start(),E(C.url,{...A,...C.options,headers:{...L(A.headers),...L((x=C.options)==null?void 0:x.headers)}}).then(async d=>{if(D.value=d,T.value=d.status,B=await d.clone()[i.type](),!d.ok)throw g.value=c||null,new Error(d.statusText);return o.afterFetch&&({data:B}=await o.afterFetch({data:B,response:d,context:C,execute:V})),g.value=B,r.trigger(d),d}).catch(async d=>{let v=d.message||d.name;if(o.onFetchError&&({error:v,data:B}=await o.onFetchError({data:B,error:d,response:D.value,context:C,execute:V})),P.value=v,o.updateDataOnError&&(g.value=B),p.trigger(d),f)throw d;return null}).finally(()=>{k===I&&$(!1),R&&R.stop(),s.trigger(null)})},ee=W(o.refetch);t.watch([ee,W(e)],([f])=>f&&V(),{deep:!0});const q={isFinished:t.readonly(w),isFetching:t.readonly(F),statusCode:T,response:D,error:P,data:g,canAbort:G,aborted:h,abort:K,execute:V,onFetchResponse:r.on,onFetchError:p.on,onFetchFinally:s.on,get:S("GET"),put:S("PUT"),post:S("POST"),delete:S("DELETE"),patch:S("PATCH"),head:S("HEAD"),options:S("OPTIONS"),json:U("json"),text:U("text"),blob:U("blob"),arrayBuffer:U("arrayBuffer"),formData:U("formData")};function S(f){return(O,x)=>{if(!F.value)return i.method=f,i.payload=O,i.payloadType=x,t.isRef(i.payload)&&t.watch([ee,W(i.payload)],([k])=>k&&V(),{deep:!0}),{...q,then(k,A){return z().then(k,A)}}}}function z(){return new Promise((f,O)=>{le(w).toBe(!0).then(()=>f(q)).catch(O)})}function U(f){return()=>{if(!F.value)return i.type=f,{...q,then(O,x){return z().then(O,x)}}}}return o.immediate&&Promise.resolve().then(()=>V()),{...q,then(f,O){return z().then(f,O)}}}function de(e,n,l="/api/"){const u={};return Object.keys(e).forEach(a=>{u[a]=(...o)=>{const i=e[a],E=i.type;let c=i.url;c.startsWith("http")||(c=`${l}${c}`),i.hasBody?c=H.replacePlaceholders(c,...o.splice(1)):c=H.replacePlaceholders(c,...o);const m={...J(),...i.headers()};pe(m);const r=fe(c,{method:E},{immediate:!1,beforeFetch({options:s}){return s.headers={...s.headers,...m},i.hasBody&&o.length&&(s.body=JSON.stringify(o[0])),{options:s}},onFetchError(s){return s?.response&&n(s),s}});return{...he(m)==="application/json"?r.json():r.text()}}}),u}function pe(e){e["content-type"]==="multipart/form-data"&&delete e["content-type"]}function he(e){return e.accept??"*/*"}function ye(e){return JSON.parse(JSON.stringify(e))}y.copy=ye,y.createEndpoint=oe,y.getDefaultHeaders=J,y.requestTypes=ne,y.useApi=de,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(T,H){typeof exports=="object"&&typeof module<"u"?H(exports,require("@citruslime/utils"),require("vue")):typeof define=="function"&&define.amd?define(["exports","@citruslime/utils","vue"],H):(T=typeof globalThis<"u"?globalThis:T||self,H(T.CitrusLimeVueUtils={},T.CLUtils,T.Vue))})(this,(function(T,H,t){"use strict";const ne=["GET","POST","PUT","DELETE"];function oe(e,n,l=null,f=null,y=null){return{url:e,type:n,headers:l??J,hasBody:re(n,f),options:y??{}}}function J(){return{accept:"application/json","content-type":"application/json"}}function re(e,n){return!!(n===null&&(e==="PUT"||e==="POST")||n)}function Q(e){return t.getCurrentScope()?(t.onScopeDispose(e),!0):!1}function M(){const e=new Set,n=s=>{e.delete(s)};return{on:s=>{e.add(s);const o=()=>n(s);return Q(o),{off:o}},off:n,trigger:(...s)=>Promise.all(Array.from(e).map(o=>o(...s))),clear:()=>{e.clear()}}}const X=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const ie=()=>{};function W(...e){if(e.length!==1)return t.toRef(...e);const n=e[0];return typeof n=="function"?t.readonly(t.customRef(()=>({get:n,set:ie}))):t.ref(n)}function Y(e,n=!1,l="Timeout"){return new Promise((f,y)=>{setTimeout(n?()=>y(l):f,e)})}function ae(e,...n){return n.some(l=>l in e)}function _(e,n=!1){function l(r,{flush:c="sync",deep:w=!1,timeout:a,throwOnTimeout:O}={}){let m=null;const D=[new Promise(P=>{m=t.watch(e,b=>{r(b)!==n&&(m?m():t.nextTick(()=>m?.()),P(b))},{flush:c,deep:w,immediate:!0})})];return a!=null&&D.push(Y(a,O).then(()=>t.toValue(e)).finally(()=>m?.())),Promise.race(D)}function f(r,c){if(!t.isRef(r))return l(b=>b===r,c);const{flush:w="sync",deep:a=!1,timeout:O,throwOnTimeout:m}=c??{};let g=null;const P=[new Promise(b=>{g=t.watch([e,r],([G,j])=>{n!==(G===j)&&(g?g():t.nextTick(()=>g?.()),b(G))},{flush:w,deep:a,immediate:!0})})];return O!=null&&P.push(Y(O,m).then(()=>t.toValue(e)).finally(()=>(g?.(),t.toValue(e)))),Promise.race(P)}function y(r){return l(c=>!!c,r)}function s(r){return f(null,r)}function o(r){return f(void 0,r)}function i(r){return l(Number.isNaN,r)}function h(r,c){return l(w=>{const a=Array.from(w);return a.includes(r)||a.includes(t.toValue(r))},c)}function F(r){return u(1,r)}function u(r=1,c){let w=-1;return l(()=>(w+=1,w>=r),c)}return Array.isArray(t.toValue(e))?{toMatch:l,toContains:h,changed:F,changedTimes:u,get not(){return _(e,!n)}}:{toMatch:l,toBe:f,toBeTruthy:y,toBeNull:s,toBeNaN:i,toBeUndefined:o,changed:F,changedTimes:u,get not(){return _(e,!n)}}}function le(e){return _(e)}function se(e,n,l={}){const{immediate:f=!0,immediateCallback:y=!1}=l,s=t.shallowRef(!1);let o;function i(){o&&(clearTimeout(o),o=void 0)}function h(){s.value=!1,i()}function F(...u){y&&e(),i(),s.value=!0,o=setTimeout(()=>{s.value=!1,o=void 0,e(...u)},t.toValue(n))}return f&&(s.value=!0,X&&F()),Q(h),{isPending:t.shallowReadonly(s),start:F,stop:h}}const ue=X?window:void 0,ce={json:"application/json",text:"text/plain"};function Z(e){return e&&ae(e,"immediate","refetch","initialData","timeout","beforeFetch","afterFetch","onFetchError","fetch","updateDataOnError")}function L(e){return typeof Headers<"u"&&e instanceof Headers?Object.fromEntries(e.entries()):e}function fe(e,...n){var l,f;const y=typeof AbortController=="function";let s={},o={immediate:!0,refetch:!1,timeout:0,updateDataOnError:!1};const i={method:"GET",type:"text",payload:void 0};n.length>0&&(Z(n[0])?o={...o,...n[0]}:s=n[0]),n.length>1&&Z(n[1])&&(o={...o,...n[1]});const{fetch:h=(f=(l=ue)==null?void 0:l.fetch)!=null?f:globalThis?.fetch,initialData:F,timeout:u}=o,r=M(),c=M(),w=M(),a=t.shallowRef(!1),O=t.shallowRef(!1),m=t.shallowRef(!1),g=t.shallowRef(null),D=t.shallowRef(null),P=t.shallowRef(null),b=t.shallowRef(F||null),G=t.computed(()=>y&&O.value);let j,U;const K=d=>{y&&(j?.abort(d),j=new AbortController,j.signal.onabort=()=>m.value=!0,s={...s,signal:j.signal})},$=d=>{O.value=d,a.value=!d};u&&(U=se(K,u,{immediate:!1}));let I=0;const V=async(d=!1)=>{var E,x;K(),$(!0),P.value=null,g.value=null,m.value=!1,I+=1;const R=I,C={method:i.method,headers:{}},N=t.toValue(i.payload);if(N){const p=L(C.headers),v=Object.getPrototypeOf(N);!i.payloadType&&N&&(v===Object.prototype||Array.isArray(v))&&!(N instanceof FormData)&&(i.payloadType="json"),i.payloadType&&(p["Content-Type"]=(E=ce[i.payloadType])!=null?E:i.payloadType),C.body=i.payloadType==="json"?JSON.stringify(N):N}let te=!1;const A={url:t.toValue(e),options:{...C,...s},cancel:()=>{te=!0}};if(o.beforeFetch&&Object.assign(A,await o.beforeFetch(A)),te||!h)return $(!1),Promise.resolve(null);let B=null;return U&&U.start(),h(A.url,{...C,...A.options,headers:{...L(C.headers),...L((x=A.options)==null?void 0:x.headers)}}).then(async p=>{if(D.value=p,g.value=p.status,B=await p.clone()[i.type](),!p.ok)throw b.value=F||null,new Error(p.statusText);return o.afterFetch&&({data:B}=await o.afterFetch({data:B,response:p,context:A,execute:V})),b.value=B,r.trigger(p),p}).catch(async p=>{let v=p.message||p.name;if(o.onFetchError&&({error:v,data:B}=await o.onFetchError({data:B,error:p,response:D.value,context:A,execute:V})),P.value=v,o.updateDataOnError&&(b.value=B),c.trigger(p),d)throw p;return null}).finally(()=>{R===I&&$(!1),U&&U.stop(),w.trigger(null)})},ee=W(o.refetch);t.watch([ee,W(e)],([d])=>d&&V(),{deep:!0});const q={isFinished:t.readonly(a),isFetching:t.readonly(O),statusCode:g,response:D,error:P,data:b,canAbort:G,aborted:m,abort:K,execute:V,onFetchResponse:r.on,onFetchError:c.on,onFetchFinally:w.on,get:S("GET"),put:S("PUT"),post:S("POST"),delete:S("DELETE"),patch:S("PATCH"),head:S("HEAD"),options:S("OPTIONS"),json:k("json"),text:k("text"),blob:k("blob"),arrayBuffer:k("arrayBuffer"),formData:k("formData")};function S(d){return(E,x)=>{if(!O.value)return i.method=d,i.payload=E,i.payloadType=x,t.isRef(i.payload)&&t.watch([ee,W(i.payload)],([R])=>R&&V(),{deep:!0}),{...q,then(R,C){return z().then(R,C)}}}}function z(){return new Promise((d,E)=>{le(a).toBe(!0).then(()=>d(q)).catch(E)})}function k(d){return()=>{if(!O.value)return i.type=d,{...q,then(E,x){return z().then(E,x)}}}}return o.immediate&&Promise.resolve().then(()=>V()),{...q,then(d,E){return z().then(d,E)}}}function de(e,n,l="/api/",f){const y={};return Object.keys(e).forEach(o=>{y[o]=(...i)=>{const h=e[o],F=h.type;let u=h.url;u.startsWith("http")||(u=`${l}${u}`),h.hasBody?u=H.replacePlaceholders(u,...i.splice(1)):u=H.replacePlaceholders(u,...i);const r={...J(),...h.headers()};pe(r);const c=fe(u,{...h.options,method:F},{immediate:!1,beforeFetch({options:a}){return a.headers={...a.headers,...r},h.hasBody&&i.length&&(a.body=JSON.stringify(i[0])),{options:a}},onFetchError(a){return a?.response&&n(a),a},afterFetch(a){return f&&f(a,h),a}});return{...he(r)==="application/json"?c.json():c.text()}}}),y}function pe(e){e["content-type"]==="multipart/form-data"&&delete e["content-type"]}function he(e){return e.accept??"*/*"}function ye(e){return JSON.parse(JSON.stringify(e))}T.copy=ye,T.createEndpoint=oe,T.getDefaultHeaders=J,T.requestTypes=ne,T.useApi=de,Object.defineProperty(T,Symbol.toStringTag,{value:"Module"})}));
@@ -4,6 +4,7 @@ export interface Endpoint {
4
4
  type: typeof requestTypes[number];
5
5
  headers: () => HeadersInit;
6
6
  hasBody: boolean;
7
+ options: RequestInit;
7
8
  }
8
9
  /**
9
10
  * Creates an endpoint object, using the provided values.
@@ -12,9 +13,10 @@ export interface Endpoint {
12
13
  * @param type The type of HTTP request to make.
13
14
  * @param headers The headers this request will use.
14
15
  * @param hasBody Determines whether or not an endpoint should have a body.
16
+ * @param options The options to pass to the useFetch composable.
15
17
  * @returns The created Endpoint object.
16
18
  */
17
- export declare function createEndpoint(url: string, type: typeof requestTypes[number], headers?: (() => HeadersInit) | null, hasBody?: boolean | null): Endpoint;
19
+ export declare function createEndpoint(url: string, type: typeof requestTypes[number], headers?: (() => HeadersInit) | null, hasBody?: boolean | null, options?: RequestInit | null): Endpoint;
18
20
  /**
19
21
  * Gets a set of default headers.
20
22
  *
@@ -7,10 +7,14 @@ export type ApiRequest<TResponseModel> = ReturnType<typeof useFetch<TResponseMod
7
7
  * @param endpoints The endpoints provided to build with the factory.
8
8
  * @param handleFetchErrorResponse The error handler for the api factory.
9
9
  * @param prefix The prefix to append to the url (defaults to '/api/').
10
+ * @param handleAfterFetchResponse The optional after fetch response handler for the api factory.
10
11
  * @returns An API object containing request methods.
11
12
  */
12
13
  export declare function useApi<TEndpoint extends Record<keyof TEndpoint, Endpoint>>(endpoints: TEndpoint, handleFetchErrorResponse: (context: {
13
14
  data: unknown;
14
15
  response: Response | null;
15
16
  error: unknown;
16
- }) => void, prefix?: string): Record<keyof TEndpoint, <TResponseModel>(...values: unknown[]) => ApiRequest<TResponseModel>>;
17
+ }) => void, prefix?: string, handleAfterFetchResponse?: (context: {
18
+ data: unknown;
19
+ response: Response;
20
+ }, endPoint: Endpoint) => void): Record<keyof TEndpoint, <TResponseModel>(...values: unknown[]) => ApiRequest<TResponseModel>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@citruslime/vue-utils",
3
- "version": "2.0.4-beta.2",
3
+ "version": "2.0.4-beta.3",
4
4
  "type": "module",
5
5
  "author": {
6
6
  "name": "Citrus-Lime Ltd",