@enfyra/sdk-nuxt 0.3.23 → 0.3.25

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,351 +0,0 @@
1
- import { ref, unref, toRaw, computed } from "vue";
2
- import { $fetch } from "../utils/http.js";
3
- import { getAppUrl, normalizeUrl } from "../utils/url.js";
4
- import { ENFYRA_API_PREFIX } from "../constants/config.js";
5
- import { useRuntimeConfig, useFetch, useRequestHeaders, useNuxtApp } from "#imports";
6
- function handleError(error, context, customHandler) {
7
- const apiError = {
8
- message: error?.message || error?.data?.message || "Request failed",
9
- status: error?.status || error?.response?.status,
10
- data: error?.data || error?.response?.data,
11
- response: error?.response || error
12
- };
13
- if (customHandler) {
14
- customHandler(apiError, context);
15
- } else {
16
- console.error(`[Enfyra API Error]`, { error: apiError, context });
17
- }
18
- return apiError;
19
- }
20
- export function useEnfyraApi(path, opts = {}) {
21
- const { method = "get", body, query, errorContext, onError, ssr, key } = opts;
22
- const batchOptions = opts;
23
- const { batchSize, concurrent, onProgress } = batchOptions;
24
- if (ssr) {
25
- const config = useRuntimeConfig().public.enfyraSDK;
26
- const basePath = (typeof path === "function" ? path() : path).replace(/^\/?api\/?/, "").replace(/^\/+/, "");
27
- const appUrl = getAppUrl();
28
- const finalUrl = normalizeUrl(
29
- appUrl,
30
- config?.apiPrefix || ENFYRA_API_PREFIX,
31
- basePath
32
- );
33
- const clientHeaders = process.client ? {} : useRequestHeaders([
34
- "authorization",
35
- "cookie",
36
- "user-agent",
37
- "accept",
38
- "accept-language",
39
- "referer"
40
- ]);
41
- const serverHeaders = { ...clientHeaders };
42
- delete serverHeaders.connection;
43
- delete serverHeaders["keep-alive"];
44
- delete serverHeaders.host;
45
- delete serverHeaders["content-length"];
46
- const nuxtApp = useNuxtApp();
47
- const fetchOptions = {
48
- method,
49
- body,
50
- query,
51
- headers: {
52
- ...serverHeaders,
53
- ...opts.headers
54
- }
55
- };
56
- if (key !== void 0) {
57
- fetchOptions.key = key;
58
- }
59
- if (opts.default !== void 0) {
60
- fetchOptions.default = opts.default;
61
- }
62
- if (opts.server !== void 0) {
63
- fetchOptions.server = opts.server;
64
- }
65
- if (opts.lazy !== void 0) {
66
- fetchOptions.lazy = opts.lazy;
67
- }
68
- if (opts.immediate !== void 0) {
69
- fetchOptions.immediate = opts.immediate;
70
- }
71
- if (opts.transform !== void 0) {
72
- fetchOptions.transform = opts.transform;
73
- }
74
- if (opts.pick !== void 0) {
75
- fetchOptions.pick = opts.pick;
76
- }
77
- if (opts.watch !== void 0) {
78
- fetchOptions.watch = opts.watch;
79
- }
80
- if (opts.deep !== void 0) {
81
- fetchOptions.deep = opts.deep;
82
- }
83
- if (opts.getCachedData !== void 0) {
84
- fetchOptions.getCachedData = opts.getCachedData;
85
- } else {
86
- fetchOptions.getCachedData = (cacheKey) => {
87
- return nuxtApp.payload.data[cacheKey] || nuxtApp.static.data[cacheKey];
88
- };
89
- }
90
- if (opts.refresh !== void 0) {
91
- fetchOptions.refresh = opts.refresh;
92
- }
93
- if (opts.refreshInterval !== void 0) {
94
- fetchOptions.refreshInterval = opts.refreshInterval;
95
- }
96
- if (opts.dedupe !== void 0) {
97
- fetchOptions.dedupe = opts.dedupe;
98
- }
99
- if (opts.cache !== void 0) {
100
- fetchOptions.cache = opts.cache;
101
- }
102
- const result = useFetch(finalUrl, fetchOptions);
103
- const loading = computed(() => result.status.value === "pending");
104
- const returnValue = {
105
- ...result,
106
- loading
107
- };
108
- if (process.server) {
109
- return Promise.resolve(returnValue);
110
- }
111
- return returnValue;
112
- }
113
- const data = ref(null);
114
- const error = ref(null);
115
- const pending = ref(false);
116
- const execute = async (executeOpts) => {
117
- pending.value = true;
118
- error.value = null;
119
- try {
120
- const config = useRuntimeConfig().public.enfyraSDK;
121
- const apiUrl = getAppUrl();
122
- const apiPrefix = config?.apiPrefix;
123
- const basePath = (typeof path === "function" ? path() : path).replace(/^\/?api\/?/, "").replace(/^\/+/, "");
124
- const finalBody = executeOpts?.body || unref(body);
125
- const finalQuery = executeOpts?.query || unref(query);
126
- const isBatchOperation = !opts.disableBatch && (executeOpts?.ids && executeOpts.ids.length > 0 && (method.toLowerCase() === "patch" || method.toLowerCase() === "delete") || method.toLowerCase() === "post" && executeOpts?.files && Array.isArray(executeOpts.files) && executeOpts.files.length > 0);
127
- const effectiveBatchSize = isBatchOperation ? executeOpts?.batchSize ?? batchSize : void 0;
128
- const effectiveConcurrent = isBatchOperation ? executeOpts?.concurrent ?? concurrent : void 0;
129
- const effectiveOnProgress = isBatchOperation ? executeOpts?.onProgress ?? onProgress : void 0;
130
- const buildPath = (...segments) => {
131
- return segments.filter(Boolean).join("/");
132
- };
133
- const fullBaseURL = normalizeUrl(apiUrl, apiPrefix || ENFYRA_API_PREFIX);
134
- async function processBatch(items, processor) {
135
- const results = [];
136
- const progressResults = [];
137
- const startTime = Date.now();
138
- let completed = 0;
139
- let failed = 0;
140
- const chunks = effectiveBatchSize ? Array.from(
141
- { length: Math.ceil(items.length / effectiveBatchSize) },
142
- (_, i) => items.slice(
143
- i * effectiveBatchSize,
144
- i * effectiveBatchSize + effectiveBatchSize
145
- )
146
- ) : [items];
147
- const totalBatches = chunks.length;
148
- let currentBatch = 0;
149
- const updateProgress = (inProgress = 0) => {
150
- if (effectiveOnProgress) {
151
- const elapsed = Date.now() - startTime;
152
- const progress = items.length > 0 ? Math.round(completed / items.length * 100) : 0;
153
- const averageTime = completed > 0 ? elapsed / completed : void 0;
154
- const operationsPerSecond = completed > 0 ? completed / elapsed * 1e3 : void 0;
155
- const estimatedTimeRemaining = averageTime && items.length > completed ? Math.round(averageTime * (items.length - completed)) : void 0;
156
- const progressData = {
157
- progress,
158
- completed,
159
- total: items.length,
160
- failed,
161
- inProgress,
162
- estimatedTimeRemaining,
163
- averageTime,
164
- currentBatch: currentBatch + 1,
165
- totalBatches,
166
- operationsPerSecond,
167
- results: [...progressResults]
168
- };
169
- effectiveOnProgress(progressData);
170
- }
171
- };
172
- updateProgress(0);
173
- if (!effectiveBatchSize && !effectiveConcurrent) {
174
- updateProgress(items.length);
175
- const promises = items.map(async (item, index) => {
176
- const itemStartTime = Date.now();
177
- try {
178
- const result = await processor(item, index);
179
- const duration = Date.now() - itemStartTime;
180
- completed++;
181
- progressResults.push({
182
- index,
183
- status: "completed",
184
- result,
185
- duration
186
- });
187
- updateProgress(items.length - completed);
188
- return result;
189
- } catch (error2) {
190
- const duration = Date.now() - itemStartTime;
191
- failed++;
192
- completed++;
193
- progressResults.push({
194
- index,
195
- status: "failed",
196
- error: error2,
197
- duration
198
- });
199
- updateProgress(items.length - completed);
200
- throw error2;
201
- }
202
- });
203
- const results2 = await Promise.all(promises);
204
- updateProgress(0);
205
- return results2;
206
- }
207
- for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
208
- currentBatch = chunkIndex;
209
- const chunk = chunks[chunkIndex];
210
- if (effectiveConcurrent && chunk.length > effectiveConcurrent) {
211
- for (let i = 0; i < chunk.length; i += effectiveConcurrent) {
212
- const batch = chunk.slice(i, i + effectiveConcurrent);
213
- const baseIndex = chunkIndex * (effectiveBatchSize || items.length) + i;
214
- updateProgress(batch.length);
215
- const batchPromises = batch.map(async (item, batchItemIndex) => {
216
- const globalIndex = baseIndex + batchItemIndex;
217
- const itemStartTime = Date.now();
218
- try {
219
- const result = await processor(item, globalIndex);
220
- const duration = Date.now() - itemStartTime;
221
- completed++;
222
- progressResults.push({
223
- index: globalIndex,
224
- status: "completed",
225
- result,
226
- duration
227
- });
228
- updateProgress(
229
- Math.max(0, batch.length - (batchItemIndex + 1))
230
- );
231
- return result;
232
- } catch (error2) {
233
- const duration = Date.now() - itemStartTime;
234
- failed++;
235
- completed++;
236
- progressResults.push({
237
- index: globalIndex,
238
- status: "failed",
239
- error: error2,
240
- duration
241
- });
242
- updateProgress(
243
- Math.max(0, batch.length - (batchItemIndex + 1))
244
- );
245
- throw error2;
246
- }
247
- });
248
- const batchResults = await Promise.all(batchPromises);
249
- results.push(...batchResults);
250
- }
251
- } else {
252
- const baseIndex = chunkIndex * (effectiveBatchSize || items.length);
253
- updateProgress(chunk.length);
254
- const chunkPromises = chunk.map(async (item, chunkItemIndex) => {
255
- const globalIndex = baseIndex + chunkItemIndex;
256
- const itemStartTime = Date.now();
257
- try {
258
- const result = await processor(item, globalIndex);
259
- const duration = Date.now() - itemStartTime;
260
- completed++;
261
- progressResults.push({
262
- index: globalIndex,
263
- status: "completed",
264
- result,
265
- duration
266
- });
267
- updateProgress(
268
- Math.max(0, chunk.length - (chunkItemIndex + 1))
269
- );
270
- return result;
271
- } catch (error2) {
272
- const duration = Date.now() - itemStartTime;
273
- failed++;
274
- completed++;
275
- progressResults.push({
276
- index: globalIndex,
277
- status: "failed",
278
- error: error2,
279
- duration
280
- });
281
- updateProgress(
282
- Math.max(0, chunk.length - (chunkItemIndex + 1))
283
- );
284
- throw error2;
285
- }
286
- });
287
- const chunkResults = await Promise.all(chunkPromises);
288
- results.push(...chunkResults);
289
- }
290
- }
291
- updateProgress(0);
292
- return results;
293
- }
294
- if (isBatchOperation && executeOpts?.ids && executeOpts.ids.length > 0) {
295
- const responses = await processBatch(
296
- executeOpts.ids,
297
- async (id) => {
298
- const finalPath2 = buildPath(basePath, id);
299
- return $fetch(finalPath2, {
300
- baseURL: fullBaseURL,
301
- method,
302
- body: finalBody ? toRaw(finalBody) : void 0,
303
- headers: opts.headers,
304
- query: finalQuery
305
- });
306
- }
307
- );
308
- data.value = responses;
309
- return responses;
310
- }
311
- if (isBatchOperation && executeOpts?.files && Array.isArray(executeOpts.files) && executeOpts.files.length > 0) {
312
- const responses = await processBatch(
313
- executeOpts.files,
314
- async (fileObj) => {
315
- return $fetch(basePath, {
316
- baseURL: fullBaseURL,
317
- method,
318
- body: fileObj,
319
- headers: opts.headers,
320
- query: finalQuery
321
- });
322
- }
323
- );
324
- data.value = responses;
325
- return responses;
326
- }
327
- const finalPath = executeOpts?.id ? buildPath(basePath, executeOpts.id) : basePath;
328
- const response = await $fetch(finalPath, {
329
- baseURL: fullBaseURL,
330
- method,
331
- body: finalBody ? toRaw(finalBody) : void 0,
332
- headers: opts.headers,
333
- query: finalQuery
334
- });
335
- data.value = response;
336
- return response;
337
- } catch (err) {
338
- const apiError = handleError(err, errorContext, onError);
339
- error.value = apiError;
340
- return null;
341
- } finally {
342
- pending.value = false;
343
- }
344
- };
345
- return {
346
- data,
347
- error,
348
- pending,
349
- execute
350
- };
351
- }
@@ -1,8 +0,0 @@
1
- export declare function $fetch<T = any>(path: string, options?: {
2
- method?: string;
3
- body?: any;
4
- headers?: Record<string, string>;
5
- query?: Record<string, any>;
6
- baseURL?: string;
7
- }): Promise<T>;
8
- //# sourceMappingURL=http.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../../src/runtime/utils/http.ts"],"names":[],"mappings":"AAAA,wBAAsB,MAAM,CAAC,CAAC,GAAG,GAAG,EAClC,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE;IACP,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,GAAG,CAAC;IACX,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC5B,OAAO,CAAC,EAAE,MAAM,CAAC;CACb,GACL,OAAO,CAAC,CAAC,CAAC,CAoEZ"}
@@ -1,61 +0,0 @@
1
- export async function $fetch(path, options = {}) {
2
- const {
3
- method = "GET",
4
- body,
5
- headers: optionHeaders = {},
6
- query = {},
7
- baseURL
8
- } = options;
9
- if (!baseURL) {
10
- throw new Error("baseURL is required for $fetch");
11
- }
12
- const url = new URL(
13
- path.startsWith("/") ? path.slice(1) : path,
14
- baseURL.endsWith("/") ? baseURL : `${baseURL}/`
15
- );
16
- Object.entries(query).forEach(([key, value]) => {
17
- if (value !== void 0 && value !== null) {
18
- if (typeof value === "object") {
19
- url.searchParams.append(key, JSON.stringify(value));
20
- } else {
21
- url.searchParams.append(key, String(value));
22
- }
23
- }
24
- });
25
- const headers = {
26
- "Content-Type": "application/json",
27
- ...optionHeaders
28
- };
29
- const fetchOptions = {
30
- method: method.toUpperCase(),
31
- headers
32
- };
33
- if (body && method.toUpperCase() !== "GET") {
34
- if (body instanceof FormData) {
35
- delete headers["Content-Type"];
36
- fetchOptions.body = body;
37
- } else {
38
- fetchOptions.body = JSON.stringify(body);
39
- }
40
- }
41
- try {
42
- const response = await fetch(url.toString(), fetchOptions);
43
- if (!response.ok) {
44
- let errorData;
45
- try {
46
- errorData = await response.json();
47
- } catch {
48
- errorData = { message: response.statusText };
49
- }
50
- throw { response: { data: errorData } };
51
- }
52
- const contentType = response.headers.get("content-type");
53
- if (contentType?.includes("application/json")) {
54
- return await response.json();
55
- } else {
56
- return await response.text();
57
- }
58
- } catch (error) {
59
- throw error;
60
- }
61
- }