@enfyra/sdk-nuxt 0.3.18 → 0.3.20

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.
Files changed (59) hide show
  1. package/dist/auth.d.ts +43 -0
  2. package/dist/auth.d.ts.map +1 -0
  3. package/dist/auth.js +1 -0
  4. package/dist/index.d.ts +141 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +1 -0
  7. package/dist/module.cjs +97 -0
  8. package/dist/module.d.cts +10 -0
  9. package/dist/module.d.mts +10 -0
  10. package/dist/module.json +12 -0
  11. package/dist/module.mjs +94 -0
  12. package/dist/runtime/composables/useEnfyraApi.d.ts +0 -0
  13. package/dist/runtime/composables/useEnfyraApi.js +345 -0
  14. package/dist/runtime/composables/useEnfyraAuth.d.ts +0 -0
  15. package/dist/runtime/composables/useEnfyraAuth.js +81 -0
  16. package/dist/runtime/constants/auth.d.ts +0 -0
  17. package/dist/runtime/constants/auth.js +3 -0
  18. package/dist/runtime/constants/config.d.ts +0 -0
  19. package/dist/runtime/constants/config.js +1 -0
  20. package/dist/runtime/server/api/all.js +1 -1
  21. package/dist/runtime/server/api/login.post.js +2 -2
  22. package/dist/runtime/server/api/logout.post.js +2 -2
  23. package/dist/runtime/server/middleware/auth.js +2 -2
  24. package/dist/runtime/shims.d.ts +72 -0
  25. package/dist/runtime/utils/http.d.ts +0 -0
  26. package/dist/runtime/utils/http.js +61 -0
  27. package/dist/runtime/utils/server/proxy.d.ts +0 -0
  28. package/dist/runtime/utils/server/proxy.js +14 -0
  29. package/dist/runtime/utils/server/refreshToken.d.ts +0 -0
  30. package/dist/runtime/utils/server/refreshToken.js +69 -0
  31. package/dist/runtime/utils/url.d.ts +0 -0
  32. package/dist/runtime/utils/url.js +56 -0
  33. package/dist/types.d.mts +7 -0
  34. package/dist/types.d.ts +7 -0
  35. package/index.ts +1 -1
  36. package/module.d.ts +16 -6
  37. package/package.json +30 -32
  38. package/src/module.ts +129 -0
  39. package/src/{composables → runtime/composables}/useEnfyraApi.ts +17 -17
  40. package/src/{composables → runtime/composables}/useEnfyraAuth.ts +2 -2
  41. package/src/runtime/server/api/all.ts +1 -1
  42. package/src/runtime/server/api/login.post.ts +2 -2
  43. package/src/runtime/server/api/logout.post.ts +2 -2
  44. package/src/runtime/server/middleware/auth.ts +2 -2
  45. package/src/runtime/shims.d.ts +72 -0
  46. package/src/{utils → runtime/utils}/server/proxy.ts +1 -1
  47. package/src/{utils → runtime/utils}/server/refreshToken.ts +3 -3
  48. package/src/{utils → runtime/utils}/url.ts +11 -4
  49. package/dist/runtime/plugin/config-error.client.mjs +0 -107
  50. package/dist/runtime/server/api/all.mjs +0 -5
  51. package/dist/runtime/server/api/login.post.mjs +0 -62
  52. package/dist/runtime/server/api/logout.post.mjs +0 -35
  53. package/dist/runtime/server/middleware/auth.mjs +0 -36
  54. package/module.ts +0 -110
  55. package/src/types/nuxt-imports.d.ts +0 -61
  56. package/src/utils/config.ts +0 -22
  57. /package/src/{constants → runtime/constants}/auth.ts +0 -0
  58. /package/src/{constants → runtime/constants}/config.ts +0 -0
  59. /package/src/{utils → runtime/utils}/http.ts +0 -0
@@ -0,0 +1,345 @@
1
+ import { ref, unref, toRaw } 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
+ const result = useFetch(finalUrl, fetchOptions);
100
+ return {
101
+ ...result,
102
+ loading: result.pending,
103
+ pending: result.pending
104
+ // Keep for backward compatibility
105
+ };
106
+ }
107
+ const data = ref(null);
108
+ const error = ref(null);
109
+ const pending = ref(false);
110
+ const execute = async (executeOpts) => {
111
+ pending.value = true;
112
+ error.value = null;
113
+ try {
114
+ const config = useRuntimeConfig().public.enfyraSDK;
115
+ const apiUrl = getAppUrl();
116
+ const apiPrefix = config?.apiPrefix;
117
+ const basePath = (typeof path === "function" ? path() : path).replace(/^\/?api\/?/, "").replace(/^\/+/, "");
118
+ const finalBody = executeOpts?.body || unref(body);
119
+ const finalQuery = executeOpts?.query || unref(query);
120
+ 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);
121
+ const effectiveBatchSize = isBatchOperation ? executeOpts?.batchSize ?? batchSize : void 0;
122
+ const effectiveConcurrent = isBatchOperation ? executeOpts?.concurrent ?? concurrent : void 0;
123
+ const effectiveOnProgress = isBatchOperation ? executeOpts?.onProgress ?? onProgress : void 0;
124
+ const buildPath = (...segments) => {
125
+ return segments.filter(Boolean).join("/");
126
+ };
127
+ const fullBaseURL = normalizeUrl(apiUrl, apiPrefix || ENFYRA_API_PREFIX);
128
+ async function processBatch(items, processor) {
129
+ const results = [];
130
+ const progressResults = [];
131
+ const startTime = Date.now();
132
+ let completed = 0;
133
+ let failed = 0;
134
+ const chunks = effectiveBatchSize ? Array.from(
135
+ { length: Math.ceil(items.length / effectiveBatchSize) },
136
+ (_, i) => items.slice(
137
+ i * effectiveBatchSize,
138
+ i * effectiveBatchSize + effectiveBatchSize
139
+ )
140
+ ) : [items];
141
+ const totalBatches = chunks.length;
142
+ let currentBatch = 0;
143
+ const updateProgress = (inProgress = 0) => {
144
+ if (effectiveOnProgress) {
145
+ const elapsed = Date.now() - startTime;
146
+ const progress = items.length > 0 ? Math.round(completed / items.length * 100) : 0;
147
+ const averageTime = completed > 0 ? elapsed / completed : void 0;
148
+ const operationsPerSecond = completed > 0 ? completed / elapsed * 1e3 : void 0;
149
+ const estimatedTimeRemaining = averageTime && items.length > completed ? Math.round(averageTime * (items.length - completed)) : void 0;
150
+ const progressData = {
151
+ progress,
152
+ completed,
153
+ total: items.length,
154
+ failed,
155
+ inProgress,
156
+ estimatedTimeRemaining,
157
+ averageTime,
158
+ currentBatch: currentBatch + 1,
159
+ totalBatches,
160
+ operationsPerSecond,
161
+ results: [...progressResults]
162
+ };
163
+ effectiveOnProgress(progressData);
164
+ }
165
+ };
166
+ updateProgress(0);
167
+ if (!effectiveBatchSize && !effectiveConcurrent) {
168
+ updateProgress(items.length);
169
+ const promises = items.map(async (item, index) => {
170
+ const itemStartTime = Date.now();
171
+ try {
172
+ const result = await processor(item, index);
173
+ const duration = Date.now() - itemStartTime;
174
+ completed++;
175
+ progressResults.push({
176
+ index,
177
+ status: "completed",
178
+ result,
179
+ duration
180
+ });
181
+ updateProgress(items.length - completed);
182
+ return result;
183
+ } catch (error2) {
184
+ const duration = Date.now() - itemStartTime;
185
+ failed++;
186
+ completed++;
187
+ progressResults.push({
188
+ index,
189
+ status: "failed",
190
+ error: error2,
191
+ duration
192
+ });
193
+ updateProgress(items.length - completed);
194
+ throw error2;
195
+ }
196
+ });
197
+ const results2 = await Promise.all(promises);
198
+ updateProgress(0);
199
+ return results2;
200
+ }
201
+ for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
202
+ currentBatch = chunkIndex;
203
+ const chunk = chunks[chunkIndex];
204
+ if (effectiveConcurrent && chunk.length > effectiveConcurrent) {
205
+ for (let i = 0; i < chunk.length; i += effectiveConcurrent) {
206
+ const batch = chunk.slice(i, i + effectiveConcurrent);
207
+ const baseIndex = chunkIndex * (effectiveBatchSize || items.length) + i;
208
+ updateProgress(batch.length);
209
+ const batchPromises = batch.map(async (item, batchItemIndex) => {
210
+ const globalIndex = baseIndex + batchItemIndex;
211
+ const itemStartTime = Date.now();
212
+ try {
213
+ const result = await processor(item, globalIndex);
214
+ const duration = Date.now() - itemStartTime;
215
+ completed++;
216
+ progressResults.push({
217
+ index: globalIndex,
218
+ status: "completed",
219
+ result,
220
+ duration
221
+ });
222
+ updateProgress(
223
+ Math.max(0, batch.length - (batchItemIndex + 1))
224
+ );
225
+ return result;
226
+ } catch (error2) {
227
+ const duration = Date.now() - itemStartTime;
228
+ failed++;
229
+ completed++;
230
+ progressResults.push({
231
+ index: globalIndex,
232
+ status: "failed",
233
+ error: error2,
234
+ duration
235
+ });
236
+ updateProgress(
237
+ Math.max(0, batch.length - (batchItemIndex + 1))
238
+ );
239
+ throw error2;
240
+ }
241
+ });
242
+ const batchResults = await Promise.all(batchPromises);
243
+ results.push(...batchResults);
244
+ }
245
+ } else {
246
+ const baseIndex = chunkIndex * (effectiveBatchSize || items.length);
247
+ updateProgress(chunk.length);
248
+ const chunkPromises = chunk.map(async (item, chunkItemIndex) => {
249
+ const globalIndex = baseIndex + chunkItemIndex;
250
+ const itemStartTime = Date.now();
251
+ try {
252
+ const result = await processor(item, globalIndex);
253
+ const duration = Date.now() - itemStartTime;
254
+ completed++;
255
+ progressResults.push({
256
+ index: globalIndex,
257
+ status: "completed",
258
+ result,
259
+ duration
260
+ });
261
+ updateProgress(
262
+ Math.max(0, chunk.length - (chunkItemIndex + 1))
263
+ );
264
+ return result;
265
+ } catch (error2) {
266
+ const duration = Date.now() - itemStartTime;
267
+ failed++;
268
+ completed++;
269
+ progressResults.push({
270
+ index: globalIndex,
271
+ status: "failed",
272
+ error: error2,
273
+ duration
274
+ });
275
+ updateProgress(
276
+ Math.max(0, chunk.length - (chunkItemIndex + 1))
277
+ );
278
+ throw error2;
279
+ }
280
+ });
281
+ const chunkResults = await Promise.all(chunkPromises);
282
+ results.push(...chunkResults);
283
+ }
284
+ }
285
+ updateProgress(0);
286
+ return results;
287
+ }
288
+ if (isBatchOperation && executeOpts?.ids && executeOpts.ids.length > 0) {
289
+ const responses = await processBatch(
290
+ executeOpts.ids,
291
+ async (id) => {
292
+ const finalPath2 = buildPath(basePath, id);
293
+ return $fetch(finalPath2, {
294
+ baseURL: fullBaseURL,
295
+ method,
296
+ body: finalBody ? toRaw(finalBody) : void 0,
297
+ headers: opts.headers,
298
+ query: finalQuery
299
+ });
300
+ }
301
+ );
302
+ data.value = responses;
303
+ return responses;
304
+ }
305
+ if (isBatchOperation && executeOpts?.files && Array.isArray(executeOpts.files) && executeOpts.files.length > 0) {
306
+ const responses = await processBatch(
307
+ executeOpts.files,
308
+ async (fileObj) => {
309
+ return $fetch(basePath, {
310
+ baseURL: fullBaseURL,
311
+ method,
312
+ body: fileObj,
313
+ headers: opts.headers,
314
+ query: finalQuery
315
+ });
316
+ }
317
+ );
318
+ data.value = responses;
319
+ return responses;
320
+ }
321
+ const finalPath = executeOpts?.id ? buildPath(basePath, executeOpts.id) : basePath;
322
+ const response = await $fetch(finalPath, {
323
+ baseURL: fullBaseURL,
324
+ method,
325
+ body: finalBody ? toRaw(finalBody) : void 0,
326
+ headers: opts.headers,
327
+ query: finalQuery
328
+ });
329
+ data.value = response;
330
+ return response;
331
+ } catch (err) {
332
+ const apiError = handleError(err, errorContext, onError);
333
+ error.value = apiError;
334
+ return null;
335
+ } finally {
336
+ pending.value = false;
337
+ }
338
+ };
339
+ return {
340
+ data,
341
+ error,
342
+ pending,
343
+ execute
344
+ };
345
+ }
File without changes
@@ -0,0 +1,81 @@
1
+ import { ref, computed } from "vue";
2
+ import { useEnfyraApi } from "./useEnfyraApi.js";
3
+ const me = ref(null);
4
+ const isLoading = ref(false);
5
+ export function useEnfyraAuth() {
6
+ const {
7
+ data: loginData,
8
+ execute: executeLogin,
9
+ error: loginError
10
+ } = useEnfyraApi("/login", {
11
+ method: "post",
12
+ errorContext: "Login"
13
+ });
14
+ const { execute: executeLogout } = useEnfyraApi("/logout", {
15
+ method: "post",
16
+ errorContext: "Logout"
17
+ });
18
+ const {
19
+ data: meData,
20
+ execute: executeFetchUser,
21
+ error: fetchUserError
22
+ } = useEnfyraApi("/me", {
23
+ errorContext: "Fetch User Profile"
24
+ });
25
+ const fetchUser = async (options) => {
26
+ isLoading.value = true;
27
+ try {
28
+ const queryParams = {};
29
+ if (options?.fields && options.fields.length > 0) {
30
+ queryParams.fields = options.fields.join(",");
31
+ }
32
+ await executeFetchUser({
33
+ query: queryParams
34
+ });
35
+ if (fetchUserError.value) {
36
+ me.value = null;
37
+ return;
38
+ }
39
+ me.value = meData.value?.data?.[0];
40
+ } finally {
41
+ isLoading.value = false;
42
+ }
43
+ };
44
+ const login = async (payload) => {
45
+ isLoading.value = true;
46
+ try {
47
+ await executeLogin({ body: payload });
48
+ if (loginError.value) {
49
+ return null;
50
+ }
51
+ return loginData.value;
52
+ } finally {
53
+ isLoading.value = false;
54
+ }
55
+ };
56
+ const logout = async () => {
57
+ isLoading.value = true;
58
+ try {
59
+ await executeLogout();
60
+ me.value = null;
61
+ if (typeof window !== "undefined") {
62
+ window.location.reload();
63
+ }
64
+ } catch (error) {
65
+ me.value = null;
66
+ if (typeof window !== "undefined") {
67
+ window.location.reload();
68
+ }
69
+ } finally {
70
+ isLoading.value = false;
71
+ }
72
+ };
73
+ const isLoggedIn = computed(() => !!me.value);
74
+ return {
75
+ me,
76
+ login,
77
+ logout,
78
+ fetchUser,
79
+ isLoggedIn
80
+ };
81
+ }
File without changes
@@ -0,0 +1,3 @@
1
+ export const ACCESS_TOKEN_KEY = "accessToken";
2
+ export const REFRESH_TOKEN_KEY = "refreshToken";
3
+ export const EXP_TIME_KEY = "expTime";
File without changes
@@ -0,0 +1 @@
1
+ export const ENFYRA_API_PREFIX = "/enfyra/api";
@@ -1,5 +1,5 @@
1
1
  import { defineEventHandler } from "h3";
2
- import { proxyToAPI } from "../../../utils/server/proxy";
2
+ import { proxyToAPI } from "../../utils/server/proxy.js";
3
3
  export default defineEventHandler(async (event) => {
4
4
  return proxyToAPI(event);
5
5
  });
@@ -12,8 +12,8 @@ import {
12
12
  ACCESS_TOKEN_KEY,
13
13
  REFRESH_TOKEN_KEY,
14
14
  EXP_TIME_KEY
15
- } from "../../../constants/auth";
16
- import { normalizeUrl } from "../../../utils/url";
15
+ } from "../../constants/auth.js";
16
+ import { normalizeUrl } from "../../utils/url.js";
17
17
  export default defineEventHandler(async (event) => {
18
18
  const config = useRuntimeConfig();
19
19
  const apiUrl = config.public.enfyraSDK?.apiUrl;
@@ -5,8 +5,8 @@ import {
5
5
  ACCESS_TOKEN_KEY,
6
6
  REFRESH_TOKEN_KEY,
7
7
  EXP_TIME_KEY
8
- } from "../../../constants/auth";
9
- import { normalizeUrl } from "../../../utils/url";
8
+ } from "../../constants/auth.js";
9
+ import { normalizeUrl } from "../../utils/url.js";
10
10
  export default defineEventHandler(async (event) => {
11
11
  const config = useRuntimeConfig();
12
12
  const apiUrl = config.public?.enfyraSDK?.apiUrl;
@@ -3,8 +3,8 @@ import { useRuntimeConfig } from "#imports";
3
3
  import {
4
4
  validateTokens,
5
5
  refreshAccessToken
6
- } from "../../../utils/server/refreshToken";
7
- import { REFRESH_TOKEN_KEY } from "../../../constants/auth";
6
+ } from "../../utils/server/refreshToken.js";
7
+ import { REFRESH_TOKEN_KEY } from "../../constants/auth.js";
8
8
  export default defineEventHandler(async (event) => {
9
9
  if (event.node.req.url === "/api/login" || event.node.req.url === "/api/logout") {
10
10
  return;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Type shims for Nuxt auto-imports used in module runtime.
3
+ * These types are provided by Nuxt at runtime but need declarations for TypeScript.
4
+ */
5
+
6
+ declare module "#imports" {
7
+ // Nuxt composables
8
+ export const useRuntimeConfig: () => {
9
+ public: {
10
+ enfyraSDK?: {
11
+ apiUrl?: string;
12
+ apiPrefix?: string;
13
+ configError?: boolean;
14
+ configErrorMessage?: string;
15
+ };
16
+ };
17
+ [key: string]: any;
18
+ };
19
+
20
+ export const useRequestHeaders: (
21
+ headers?: string[]
22
+ ) => Record<string, string | undefined>;
23
+
24
+ export const useRequestURL: () => URL;
25
+
26
+ export const useFetch: <T = any>(
27
+ url: string | (() => string),
28
+ options?: any
29
+ ) => any;
30
+
31
+ export const useNuxtApp: () => {
32
+ payload: {
33
+ data: Record<string, any>;
34
+ [key: string]: any;
35
+ };
36
+ static: {
37
+ data: Record<string, any>;
38
+ [key: string]: any;
39
+ };
40
+ [key: string]: any;
41
+ };
42
+
43
+ // Nuxt plugin
44
+ export const defineNuxtPlugin: (plugin: any) => any;
45
+
46
+ // Server utilities (from nitro)
47
+ export const defineCachedEventHandler: (
48
+ handler: any,
49
+ options?: any
50
+ ) => any;
51
+ export const getCookie: (
52
+ event: any,
53
+ name: string
54
+ ) => string | undefined;
55
+ export const setCookie: (
56
+ event: any,
57
+ name: string,
58
+ value: string,
59
+ options?: any
60
+ ) => void;
61
+ export const deleteCookie: (
62
+ event: any,
63
+ name: string,
64
+ options?: any
65
+ ) => void;
66
+ export const createError: (options: {
67
+ statusCode?: number;
68
+ statusMessage?: string;
69
+ message?: string;
70
+ data?: any;
71
+ }) => Error;
72
+ }
File without changes
@@ -0,0 +1,61 @@
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
+ }
File without changes
@@ -0,0 +1,14 @@
1
+ import { proxyRequest } from "h3";
2
+ import { useRuntimeConfig } from "#imports";
3
+ import { ENFYRA_API_PREFIX } from "../../constants/config.js";
4
+ import { normalizeUrl } from "../url.js";
5
+ export function proxyToAPI(event, customPath) {
6
+ const config = useRuntimeConfig();
7
+ const apiPrefix = config.public?.enfyraSDK?.apiPrefix || ENFYRA_API_PREFIX;
8
+ const rawPath = customPath || event.path.replace(new RegExp(`^${apiPrefix}`), "");
9
+ const targetUrl = normalizeUrl(config.public?.enfyraSDK?.apiUrl, rawPath);
10
+ const headers = event.context.proxyHeaders || {};
11
+ return proxyRequest(event, targetUrl, {
12
+ headers
13
+ });
14
+ }
File without changes