@3lineas/groovepack 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -9
- package/dist/api-action/index.d.ts +42 -4
- package/dist/api-action/index.js +62 -9
- package/dist/api-action/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -223,30 +223,40 @@ const response = await api.post("/orders", { total: BigInt(1500) });
|
|
|
223
223
|
|
|
224
224
|
## 5. `@3lineas/groovepack/api-action`
|
|
225
225
|
|
|
226
|
-
Polymorphic wrapper that normalizes Hono RPC responses, standard `fetch` responses, `ActionResponse<T>`, or raw promises
|
|
226
|
+
Polymorphic wrapper that normalizes Hono RPC responses, standard `fetch` responses, `ActionResponse<T>`, or raw promises. Supports three TypeScript-overloaded modes while logging **exclusively on errors**:
|
|
227
227
|
|
|
228
|
+
1. **Default `ActionResponse<T>` mode** (mutations & `apiToast`):
|
|
228
229
|
```typescript
|
|
229
230
|
import { apiAction, type ActionResponse } from "@3lineas/groovepack/api-action";
|
|
230
|
-
import { Logger } from "@3lineas/groovepack/logger";
|
|
231
231
|
import { rpc } from "@/lib/rpc";
|
|
232
232
|
|
|
233
|
-
const logger = new Logger("Web:Products");
|
|
234
|
-
|
|
235
233
|
export async function createProductAction(
|
|
236
234
|
input: { name: string; price: number },
|
|
237
235
|
): Promise<ActionResponse<Product>> {
|
|
238
236
|
return apiAction<Product>({
|
|
239
|
-
actionName: "createProduct",
|
|
240
|
-
logger,
|
|
241
237
|
defaultErrorMessage: "Could not create product. Please try again.",
|
|
242
238
|
apiCall: () => rpc.v1.products.$post({ json: input }),
|
|
243
|
-
onSuccess: (product) => {
|
|
244
|
-
console.log("Created:", product.id);
|
|
245
|
-
},
|
|
246
239
|
});
|
|
247
240
|
}
|
|
248
241
|
```
|
|
249
242
|
|
|
243
|
+
2. **`fallback` mode** (Server Components / `page.tsx` returning `Promise<T>`):
|
|
244
|
+
```typescript
|
|
245
|
+
const products = await apiAction<Product[]>({
|
|
246
|
+
apiCall: () => rpc.v1.products.$get(),
|
|
247
|
+
fallback: [],
|
|
248
|
+
});
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
3. **`throwOnError: true` mode** (Error Boundaries / `error.tsx` returning `Promise<T>` or throwing `Error`):
|
|
252
|
+
```typescript
|
|
253
|
+
const product = await apiAction<Product>({
|
|
254
|
+
apiCall: () => rpc.v1.products[":id"].$get({ param: { id } }),
|
|
255
|
+
throwOnError: true,
|
|
256
|
+
defaultErrorMessage: "Product could not be loaded.",
|
|
257
|
+
});
|
|
258
|
+
```
|
|
259
|
+
|
|
250
260
|
---
|
|
251
261
|
|
|
252
262
|
## 6. `@3lineas/groovepack/api-toast`
|
|
@@ -21,9 +21,9 @@ type ApiCallResult<T> = MinimalResponse | ActionResponse<T>;
|
|
|
21
21
|
type ErrorLogger = (message: string, context?: Record<string, unknown>) => void;
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
|
-
*
|
|
24
|
+
* Shared options across all `apiAction` execution modes.
|
|
25
25
|
*/
|
|
26
|
-
interface
|
|
26
|
+
interface ApiActionBaseOptions<T = unknown> {
|
|
27
27
|
/** Async call returning either a `Response`/`ClientResponse` or an `ActionResponse<T>`. */
|
|
28
28
|
apiCall: () => Promise<ApiCallResult<T>>;
|
|
29
29
|
/** Default fallback error message when the server does not provide one. */
|
|
@@ -32,10 +32,48 @@ interface ApiActionOptions<T = unknown> {
|
|
|
32
32
|
onError?: ErrorLogger;
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
/**
|
|
36
|
+
* Default options for `apiAction`, returning a standardized `ActionResponse<T>`.
|
|
37
|
+
*/
|
|
38
|
+
interface ApiActionOptions<T = unknown> extends ApiActionBaseOptions<T> {
|
|
39
|
+
/** Disallowed in default `ActionResponse` mode. */
|
|
40
|
+
fallback?: never;
|
|
41
|
+
/** Disallowed in default `ActionResponse` mode. */
|
|
42
|
+
throwOnError?: never;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Options for `apiAction` in unwrapped fallback mode, returning `Promise<T>` directly.
|
|
47
|
+
*/
|
|
48
|
+
interface ApiActionWithFallbackOptions<T = unknown> extends ApiActionBaseOptions<T> {
|
|
49
|
+
/** Fallback value returned when the request fails or `data` is `undefined`. */
|
|
50
|
+
fallback: NoInfer<T>;
|
|
51
|
+
/** Mutually exclusive with `fallback`. */
|
|
52
|
+
throwOnError?: never;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Options for `apiAction` in unwrapped throwing mode, returning `Promise<T>` or throwing `Error`.
|
|
57
|
+
*/
|
|
58
|
+
interface ApiActionThrowOptions<T = unknown> extends ApiActionBaseOptions<T> {
|
|
59
|
+
/** Mutually exclusive with `throwOnError`. */
|
|
60
|
+
fallback?: never;
|
|
61
|
+
/** Throws an `Error` if the request fails or `data` is `undefined`. */
|
|
62
|
+
throwOnError: true;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Executes an API call and returns the unwrapped `data` or `fallback` on failure.
|
|
67
|
+
*/
|
|
68
|
+
declare function apiAction<T = unknown>(options: ApiActionWithFallbackOptions<T>): Promise<T>;
|
|
69
|
+
/**
|
|
70
|
+
* Executes an API call and returns the unwrapped `data` or throws `Error` on failure.
|
|
71
|
+
*/
|
|
72
|
+
declare function apiAction<T = unknown>(options: ApiActionThrowOptions<T>): Promise<T>;
|
|
35
73
|
/**
|
|
36
74
|
* Universal wrapper for API calls (Hono RPC, `fetch`, or Server Actions)
|
|
37
75
|
* guaranteeing a standardized `ActionResponse<T>` without throwing uncaught errors.
|
|
38
76
|
*/
|
|
39
|
-
declare function apiAction<T = unknown>(
|
|
77
|
+
declare function apiAction<T = unknown>(options: ApiActionOptions<T>): Promise<ActionResponse<T>>;
|
|
40
78
|
|
|
41
|
-
export { ActionResponse, type ApiActionOptions, type ApiCallResult, type ErrorLogger, type MinimalResponse, apiAction };
|
|
79
|
+
export { ActionResponse, type ApiActionBaseOptions, type ApiActionOptions, type ApiActionThrowOptions, type ApiActionWithFallbackOptions, type ApiCallResult, type ErrorLogger, type MinimalResponse, apiAction };
|
package/dist/api-action/index.js
CHANGED
|
@@ -63,21 +63,15 @@ async function handleHttpResponse(response, fallbackErrorMessage, serverRequestF
|
|
|
63
63
|
};
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
-
// src/api-action/
|
|
67
|
-
async function
|
|
68
|
-
apiCall,
|
|
69
|
-
defaultErrorMessage,
|
|
70
|
-
onError = defaultErrorLogger
|
|
71
|
-
}) {
|
|
72
|
-
const messages = resolveLocaleMessages();
|
|
73
|
-
const resolvedDefaultError = defaultErrorMessage ?? messages.unexpectedError;
|
|
66
|
+
// src/api-action/execute-api-call.ts
|
|
67
|
+
async function executeApiCall(apiCall, resolvedDefaultError, serverRequestFailedMessage, onError) {
|
|
74
68
|
try {
|
|
75
69
|
const actionResult = await apiCall();
|
|
76
70
|
if (isMinimalResponse(actionResult)) {
|
|
77
71
|
return await handleHttpResponse(
|
|
78
72
|
actionResult,
|
|
79
73
|
resolvedDefaultError,
|
|
80
|
-
|
|
74
|
+
serverRequestFailedMessage,
|
|
81
75
|
onError
|
|
82
76
|
);
|
|
83
77
|
}
|
|
@@ -98,6 +92,65 @@ async function apiAction({
|
|
|
98
92
|
};
|
|
99
93
|
}
|
|
100
94
|
}
|
|
95
|
+
|
|
96
|
+
// src/api-action/unwrap-action-response.ts
|
|
97
|
+
function unwrapActionResponse(response, defaultErrorMessage, onError, errorLogged, strategy) {
|
|
98
|
+
if (response.success && response.data !== void 0) {
|
|
99
|
+
return response.data;
|
|
100
|
+
}
|
|
101
|
+
const failureMessage = response.success ? response.error ?? defaultErrorMessage : response.error ?? response.message ?? defaultErrorMessage;
|
|
102
|
+
if (!errorLogged) {
|
|
103
|
+
onError(failureMessage, {
|
|
104
|
+
success: response.success,
|
|
105
|
+
hasData: response.data !== void 0
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
if (strategy.mode === "throw") {
|
|
109
|
+
throw new Error(failureMessage);
|
|
110
|
+
}
|
|
111
|
+
return strategy.fallback;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// src/api-action/index.ts
|
|
115
|
+
async function apiAction(options) {
|
|
116
|
+
const {
|
|
117
|
+
apiCall,
|
|
118
|
+
defaultErrorMessage,
|
|
119
|
+
onError = defaultErrorLogger
|
|
120
|
+
} = options;
|
|
121
|
+
const messages = resolveLocaleMessages();
|
|
122
|
+
const resolvedDefaultError = defaultErrorMessage ?? messages.unexpectedError;
|
|
123
|
+
let errorLogged = false;
|
|
124
|
+
const trackedOnError = (message, details) => {
|
|
125
|
+
errorLogged = true;
|
|
126
|
+
onError(message, details);
|
|
127
|
+
};
|
|
128
|
+
const response = await executeApiCall(
|
|
129
|
+
apiCall,
|
|
130
|
+
resolvedDefaultError,
|
|
131
|
+
messages.serverRequestFailed,
|
|
132
|
+
trackedOnError
|
|
133
|
+
);
|
|
134
|
+
if ("fallback" in options) {
|
|
135
|
+
return unwrapActionResponse(
|
|
136
|
+
response,
|
|
137
|
+
resolvedDefaultError,
|
|
138
|
+
onError,
|
|
139
|
+
errorLogged,
|
|
140
|
+
{ mode: "fallback", fallback: options.fallback }
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
if ("throwOnError" in options && options.throwOnError === true) {
|
|
144
|
+
return unwrapActionResponse(
|
|
145
|
+
response,
|
|
146
|
+
resolvedDefaultError,
|
|
147
|
+
onError,
|
|
148
|
+
errorLogged,
|
|
149
|
+
{ mode: "throw" }
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
return response;
|
|
153
|
+
}
|
|
101
154
|
export {
|
|
102
155
|
apiAction
|
|
103
156
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/api-action/default-error-logger.ts","../../src/api-action/is-minimal-response.ts","../../src/api-action/is-action-response.ts","../../src/api-action/try-parse-json.ts","../../src/api-action/handle-http-response.ts","../../src/api-action/index.ts"],"sourcesContent":["import type { ErrorLogger } from \"@/types/api-action/error-logger.type\";\n\n/**\n * Default error logger used when `onError` is not provided to `apiAction`.\n */\nexport const defaultErrorLogger: ErrorLogger = (message, context) => {\n if (context) {\n console.error(`[apiAction] ${message}`, context);\n return;\n }\n console.error(`[apiAction] ${message}`);\n};\n","import type { MinimalResponse } from \"@/types/api-action/minimal-response.type\";\n\n/**\n * Type guard verifying whether a value implements `MinimalResponse`.\n */\nexport function isMinimalResponse(\n candidateValue: unknown,\n): candidateValue is MinimalResponse {\n return (\n typeof candidateValue === \"object\" &&\n candidateValue !== null &&\n \"ok\" in candidateValue &&\n typeof candidateValue.ok === \"boolean\" &&\n \"status\" in candidateValue &&\n typeof candidateValue.status === \"number\" &&\n \"json\" in candidateValue &&\n typeof candidateValue.json === \"function\"\n );\n}\n","import type { ActionResponse } from \"@/types/common/action-response.type\";\n\n/**\n * Type guard verifying whether a value implements `ActionResponse<T>`.\n */\nexport function isActionResponse<T>(\n candidateValue: unknown,\n): candidateValue is ActionResponse<T> {\n return (\n typeof candidateValue === \"object\" &&\n candidateValue !== null &&\n \"success\" in candidateValue &&\n typeof candidateValue.success === \"boolean\"\n );\n}\n","/**\n * Safely parses JSON from a `MinimalResponse`, returning `null` if parsing fails.\n */\nexport async function tryParseJson(\n response: { json: () => Promise<unknown> },\n): Promise<Record<string, unknown> | null> {\n try {\n const parsed = await response.json();\n if (typeof parsed === \"object\" && parsed !== null) {\n return parsed as Record<string, unknown>;\n }\n return null;\n } catch {\n return null;\n }\n}\n","import type { ActionResponse } from \"@/types/common/action-response.type\";\nimport type { ErrorLogger } from \"@/types/api-action/error-logger.type\";\nimport type { MinimalResponse } from \"@/types/api-action/minimal-response.type\";\nimport { isActionResponse } from \"@/api-action/is-action-response\";\nimport { tryParseJson } from \"@/api-action/try-parse-json\";\n\n/**\n * Normalizes a `MinimalResponse` (Fetch / Hono RPC) into an `ActionResponse<T>`.\n */\nexport async function handleHttpResponse<T>(\n response: MinimalResponse,\n fallbackErrorMessage: string,\n serverRequestFailedMessage: string,\n logError: ErrorLogger,\n): Promise<ActionResponse<T>> {\n const payload = await tryParseJson(response);\n\n if (!response.ok) {\n const serverError =\n payload && typeof payload[\"error\"] === \"string\"\n ? payload[\"error\"]\n : undefined;\n const serverMessage =\n payload && typeof payload[\"message\"] === \"string\"\n ? payload[\"message\"]\n : undefined;\n\n return {\n success: false,\n error: serverError ?? serverMessage ?? fallbackErrorMessage,\n };\n }\n\n if (isActionResponse<T>(payload)) {\n return payload;\n }\n\n if (payload !== null) {\n return {\n success: true,\n data: payload as T,\n };\n }\n\n logError(\"Received non-JSON 2xx response from server\", {\n status: response.status,\n });\n\n return {\n success: false,\n error: serverRequestFailedMessage,\n };\n}\n","import type { ActionResponse } from \"@/types/common/action-response.type\";\nimport type { ApiActionOptions } from \"@/types/api-action/api-action-options.type\";\nimport { resolveLocaleMessages } from \"@/i18n/resolve-locale-messages\";\nimport { defaultErrorLogger } from \"@/api-action/default-error-logger\";\nimport { isMinimalResponse } from \"@/api-action/is-minimal-response\";\nimport { isActionResponse } from \"@/api-action/is-action-response\";\nimport { handleHttpResponse } from \"@/api-action/handle-http-response\";\n\nexport type { ActionResponse } from \"@/types/common/action-response.type\";\nexport type { MinimalResponse } from \"@/types/api-action/minimal-response.type\";\nexport type { ErrorLogger } from \"@/types/api-action/error-logger.type\";\nexport type { ApiCallResult } from \"@/types/api-action/api-call-result.type\";\nexport type { ApiActionOptions } from \"@/types/api-action/api-action-options.type\";\n\n/**\n * Universal wrapper for API calls (Hono RPC, `fetch`, or Server Actions)\n * guaranteeing a standardized `ActionResponse<T>` without throwing uncaught errors.\n */\nexport async function apiAction<T = unknown>({\n apiCall,\n defaultErrorMessage,\n onError = defaultErrorLogger,\n}: ApiActionOptions<T>): Promise<ActionResponse<T>> {\n const messages = resolveLocaleMessages();\n const resolvedDefaultError = defaultErrorMessage ?? messages.unexpectedError;\n\n try {\n const actionResult = await apiCall();\n\n if (isMinimalResponse(actionResult)) {\n return await handleHttpResponse<T>(\n actionResult,\n resolvedDefaultError,\n messages.serverRequestFailed,\n onError,\n );\n }\n\n if (isActionResponse<T>(actionResult)) {\n return actionResult;\n }\n\n return {\n success: true,\n data: actionResult as T,\n };\n } catch (caughtError) {\n onError(\"Unexpected error in apiAction\", {\n error:\n caughtError instanceof Error ? caughtError.message : String(caughtError),\n });\n\n return {\n success: false,\n error: resolvedDefaultError,\n };\n }\n}\n"],"mappings":";;;;;AAKO,IAAM,qBAAkC,CAAC,SAAS,YAAY;AACnE,MAAI,SAAS;AACX,YAAQ,MAAM,eAAe,OAAO,IAAI,OAAO;AAC/C;AAAA,EACF;AACA,UAAQ,MAAM,eAAe,OAAO,EAAE;AACxC;;;ACNO,SAAS,kBACd,gBACmC;AACnC,SACE,OAAO,mBAAmB,YAC1B,mBAAmB,QACnB,QAAQ,kBACR,OAAO,eAAe,OAAO,aAC7B,YAAY,kBACZ,OAAO,eAAe,WAAW,YACjC,UAAU,kBACV,OAAO,eAAe,SAAS;AAEnC;;;ACbO,SAAS,iBACd,gBACqC;AACrC,SACE,OAAO,mBAAmB,YAC1B,mBAAmB,QACnB,aAAa,kBACb,OAAO,eAAe,YAAY;AAEtC;;;ACXA,eAAsB,aACpB,UACyC;AACzC,MAAI;AACF,UAAM,SAAS,MAAM,SAAS,KAAK;AACnC,QAAI,OAAO,WAAW,YAAY,WAAW,MAAM;AACjD,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ACNA,eAAsB,mBACpB,UACA,sBACA,4BACA,UAC4B;AAC5B,QAAM,UAAU,MAAM,aAAa,QAAQ;AAE3C,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,cACJ,WAAW,OAAO,QAAQ,OAAO,MAAM,WACnC,QAAQ,OAAO,IACf;AACN,UAAM,gBACJ,WAAW,OAAO,QAAQ,SAAS,MAAM,WACrC,QAAQ,SAAS,IACjB;AAEN,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO,eAAe,iBAAiB;AAAA,IACzC;AAAA,EACF;AAEA,MAAI,iBAAoB,OAAO,GAAG;AAChC,WAAO;AAAA,EACT;AAEA,MAAI,YAAY,MAAM;AACpB,WAAO;AAAA,MACL,SAAS;AAAA,MACT,MAAM;AAAA,IACR;AAAA,EACF;AAEA,WAAS,8CAA8C;AAAA,IACrD,QAAQ,SAAS;AAAA,EACnB,CAAC;AAED,SAAO;AAAA,IACL,SAAS;AAAA,IACT,OAAO;AAAA,EACT;AACF;;;AClCA,eAAsB,UAAuB;AAAA,EAC3C;AAAA,EACA;AAAA,EACA,UAAU;AACZ,GAAoD;AAClD,QAAM,WAAW,sBAAsB;AACvC,QAAM,uBAAuB,uBAAuB,SAAS;AAE7D,MAAI;AACF,UAAM,eAAe,MAAM,QAAQ;AAEnC,QAAI,kBAAkB,YAAY,GAAG;AACnC,aAAO,MAAM;AAAA,QACX;AAAA,QACA;AAAA,QACA,SAAS;AAAA,QACT;AAAA,MACF;AAAA,IACF;AAEA,QAAI,iBAAoB,YAAY,GAAG;AACrC,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,MAAM;AAAA,IACR;AAAA,EACF,SAAS,aAAa;AACpB,YAAQ,iCAAiC;AAAA,MACvC,OACE,uBAAuB,QAAQ,YAAY,UAAU,OAAO,WAAW;AAAA,IAC3E,CAAC;AAED,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/api-action/default-error-logger.ts","../../src/api-action/is-minimal-response.ts","../../src/api-action/is-action-response.ts","../../src/api-action/try-parse-json.ts","../../src/api-action/handle-http-response.ts","../../src/api-action/execute-api-call.ts","../../src/api-action/unwrap-action-response.ts","../../src/api-action/index.ts"],"sourcesContent":["import type { ErrorLogger } from \"@/types/api-action/error-logger.type\";\n\n/**\n * Default error logger used when `onError` is not provided to `apiAction`.\n */\nexport const defaultErrorLogger: ErrorLogger = (message, context) => {\n if (context) {\n console.error(`[apiAction] ${message}`, context);\n return;\n }\n console.error(`[apiAction] ${message}`);\n};\n","import type { MinimalResponse } from \"@/types/api-action/minimal-response.type\";\n\n/**\n * Type guard verifying whether a value implements `MinimalResponse`.\n */\nexport function isMinimalResponse(\n candidateValue: unknown,\n): candidateValue is MinimalResponse {\n return (\n typeof candidateValue === \"object\" &&\n candidateValue !== null &&\n \"ok\" in candidateValue &&\n typeof candidateValue.ok === \"boolean\" &&\n \"status\" in candidateValue &&\n typeof candidateValue.status === \"number\" &&\n \"json\" in candidateValue &&\n typeof candidateValue.json === \"function\"\n );\n}\n","import type { ActionResponse } from \"@/types/common/action-response.type\";\n\n/**\n * Type guard verifying whether a value implements `ActionResponse<T>`.\n */\nexport function isActionResponse<T>(\n candidateValue: unknown,\n): candidateValue is ActionResponse<T> {\n return (\n typeof candidateValue === \"object\" &&\n candidateValue !== null &&\n \"success\" in candidateValue &&\n typeof candidateValue.success === \"boolean\"\n );\n}\n","/**\n * Safely parses JSON from a `MinimalResponse`, returning `null` if parsing fails.\n */\nexport async function tryParseJson(\n response: { json: () => Promise<unknown> },\n): Promise<Record<string, unknown> | null> {\n try {\n const parsed = await response.json();\n if (typeof parsed === \"object\" && parsed !== null) {\n return parsed as Record<string, unknown>;\n }\n return null;\n } catch {\n return null;\n }\n}\n","import type { ActionResponse } from \"@/types/common/action-response.type\";\nimport type { ErrorLogger } from \"@/types/api-action/error-logger.type\";\nimport type { MinimalResponse } from \"@/types/api-action/minimal-response.type\";\nimport { isActionResponse } from \"@/api-action/is-action-response\";\nimport { tryParseJson } from \"@/api-action/try-parse-json\";\n\n/**\n * Normalizes a `MinimalResponse` (Fetch / Hono RPC) into an `ActionResponse<T>`.\n */\nexport async function handleHttpResponse<T>(\n response: MinimalResponse,\n fallbackErrorMessage: string,\n serverRequestFailedMessage: string,\n logError: ErrorLogger,\n): Promise<ActionResponse<T>> {\n const payload = await tryParseJson(response);\n\n if (!response.ok) {\n const serverError =\n payload && typeof payload[\"error\"] === \"string\"\n ? payload[\"error\"]\n : undefined;\n const serverMessage =\n payload && typeof payload[\"message\"] === \"string\"\n ? payload[\"message\"]\n : undefined;\n\n return {\n success: false,\n error: serverError ?? serverMessage ?? fallbackErrorMessage,\n };\n }\n\n if (isActionResponse<T>(payload)) {\n return payload;\n }\n\n if (payload !== null) {\n return {\n success: true,\n data: payload as T,\n };\n }\n\n logError(\"Received non-JSON 2xx response from server\", {\n status: response.status,\n });\n\n return {\n success: false,\n error: serverRequestFailedMessage,\n };\n}\n","import type { ActionResponse } from \"@/types/common/action-response.type\";\nimport type { ApiCallResult } from \"@/types/api-action/api-call-result.type\";\nimport type { ErrorLogger } from \"@/types/api-action/error-logger.type\";\nimport { isMinimalResponse } from \"@/api-action/is-minimal-response\";\nimport { isActionResponse } from \"@/api-action/is-action-response\";\nimport { handleHttpResponse } from \"@/api-action/handle-http-response\";\n\n/**\n * Executes `apiCall` and normalizes any `MinimalResponse`, `ActionResponse`,\n * raw value, or thrown exception into a standardized `ActionResponse<T>`.\n */\nexport async function executeApiCall<T>(\n apiCall: () => Promise<ApiCallResult<T>>,\n resolvedDefaultError: string,\n serverRequestFailedMessage: string,\n onError: ErrorLogger,\n): Promise<ActionResponse<T>> {\n try {\n const actionResult = await apiCall();\n\n if (isMinimalResponse(actionResult)) {\n return await handleHttpResponse<T>(\n actionResult,\n resolvedDefaultError,\n serverRequestFailedMessage,\n onError,\n );\n }\n\n if (isActionResponse<T>(actionResult)) {\n return actionResult;\n }\n\n return {\n success: true,\n data: actionResult as T,\n };\n } catch (caughtError) {\n onError(\"Unexpected error in apiAction\", {\n error:\n caughtError instanceof Error ? caughtError.message : String(caughtError),\n });\n\n return {\n success: false,\n error: resolvedDefaultError,\n };\n }\n}\n","import type { ActionResponse } from \"@/types/common/action-response.type\";\nimport type { ErrorLogger } from \"@/types/api-action/error-logger.type\";\nimport type { UnwrapStrategy } from \"@/types/api-action/unwrap-strategy.type\";\n\n/**\n * Unwraps an `ActionResponse<T>` for `fallback` or `throwOnError` modes,\n * guaranteeing `onError` is invoked at most once per failed call.\n */\nexport function unwrapActionResponse<T>(\n response: ActionResponse<T>,\n defaultErrorMessage: string,\n onError: ErrorLogger,\n errorLogged: boolean,\n strategy: UnwrapStrategy<T>,\n): T {\n if (response.success && response.data !== undefined) {\n return response.data;\n }\n\n const failureMessage = response.success\n ? (response.error ?? defaultErrorMessage)\n : (response.error ?? response.message ?? defaultErrorMessage);\n\n if (!errorLogged) {\n onError(failureMessage, {\n success: response.success,\n hasData: response.data !== undefined,\n });\n }\n\n if (strategy.mode === \"throw\") {\n throw new Error(failureMessage);\n }\n\n return strategy.fallback;\n}\n","import type { ActionResponse } from \"@/types/common/action-response.type\";\nimport type { ApiActionOptions } from \"@/types/api-action/api-action-options.type\";\nimport type { ApiActionWithFallbackOptions } from \"@/types/api-action/api-action-with-fallback-options.type\";\nimport type { ApiActionThrowOptions } from \"@/types/api-action/api-action-throw-options.type\";\nimport type { ErrorLogger } from \"@/types/api-action/error-logger.type\";\nimport { resolveLocaleMessages } from \"@/i18n/resolve-locale-messages\";\nimport { defaultErrorLogger } from \"@/api-action/default-error-logger\";\nimport { executeApiCall } from \"@/api-action/execute-api-call\";\nimport { unwrapActionResponse } from \"@/api-action/unwrap-action-response\";\n\nexport type { ActionResponse } from \"@/types/common/action-response.type\";\nexport type { MinimalResponse } from \"@/types/api-action/minimal-response.type\";\nexport type { ErrorLogger } from \"@/types/api-action/error-logger.type\";\nexport type { ApiCallResult } from \"@/types/api-action/api-call-result.type\";\nexport type { ApiActionBaseOptions } from \"@/types/api-action/api-action-base-options.type\";\nexport type { ApiActionOptions } from \"@/types/api-action/api-action-options.type\";\nexport type { ApiActionWithFallbackOptions } from \"@/types/api-action/api-action-with-fallback-options.type\";\nexport type { ApiActionThrowOptions } from \"@/types/api-action/api-action-throw-options.type\";\n\n/**\n * Executes an API call and returns the unwrapped `data` or `fallback` on failure.\n */\nexport async function apiAction<T = unknown>(\n options: ApiActionWithFallbackOptions<T>,\n): Promise<T>;\n/**\n * Executes an API call and returns the unwrapped `data` or throws `Error` on failure.\n */\nexport async function apiAction<T = unknown>(\n options: ApiActionThrowOptions<T>,\n): Promise<T>;\n/**\n * Universal wrapper for API calls (Hono RPC, `fetch`, or Server Actions)\n * guaranteeing a standardized `ActionResponse<T>` without throwing uncaught errors.\n */\nexport async function apiAction<T = unknown>(\n options: ApiActionOptions<T>,\n): Promise<ActionResponse<T>>;\nexport async function apiAction<T = unknown>(\n options:\n | ApiActionOptions<T>\n | ApiActionWithFallbackOptions<T>\n | ApiActionThrowOptions<T>,\n): Promise<ActionResponse<T> | T> {\n const {\n apiCall,\n defaultErrorMessage,\n onError = defaultErrorLogger,\n } = options;\n const messages = resolveLocaleMessages();\n const resolvedDefaultError = defaultErrorMessage ?? messages.unexpectedError;\n\n let errorLogged = false;\n const trackedOnError: ErrorLogger = (message, details) => {\n errorLogged = true;\n onError(message, details);\n };\n\n const response = await executeApiCall<T>(\n apiCall,\n resolvedDefaultError,\n messages.serverRequestFailed,\n trackedOnError,\n );\n\n if (\"fallback\" in options) {\n return unwrapActionResponse<T>(\n response,\n resolvedDefaultError,\n onError,\n errorLogged,\n { mode: \"fallback\", fallback: options.fallback as T },\n );\n }\n\n if (\"throwOnError\" in options && options.throwOnError === true) {\n return unwrapActionResponse<T>(\n response,\n resolvedDefaultError,\n onError,\n errorLogged,\n { mode: \"throw\" },\n );\n }\n\n return response;\n}\n"],"mappings":";;;;;AAKO,IAAM,qBAAkC,CAAC,SAAS,YAAY;AACnE,MAAI,SAAS;AACX,YAAQ,MAAM,eAAe,OAAO,IAAI,OAAO;AAC/C;AAAA,EACF;AACA,UAAQ,MAAM,eAAe,OAAO,EAAE;AACxC;;;ACNO,SAAS,kBACd,gBACmC;AACnC,SACE,OAAO,mBAAmB,YAC1B,mBAAmB,QACnB,QAAQ,kBACR,OAAO,eAAe,O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