@3lineas/groovepack 1.3.0 → 1.5.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 +140 -9
- package/dist/api-action/index.d.ts +43 -5
- package/dist/api-action/index.js +109 -18
- package/dist/api-action/index.js.map +1 -1
- package/dist/chunk-H76QJ2LB.js +90 -0
- package/dist/chunk-H76QJ2LB.js.map +1 -0
- package/dist/chunk-QRQSSZCB.js +33 -0
- package/dist/chunk-QRQSSZCB.js.map +1 -0
- package/dist/errors/index.d.ts +54 -0
- package/dist/errors/index.js +49 -0
- package/dist/errors/index.js.map +1 -0
- package/dist/logger/index.js +3 -85
- package/dist/logger/index.js.map +1 -1
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -17,6 +17,7 @@ Zero-dependency & modular infrastructure primitives for **TypeScript**, **Cloudf
|
|
|
17
17
|
- [4. `@3lineas/groovepack/api-client`](#4-3lineasgroovepackapi-client)
|
|
18
18
|
- [5. `@3lineas/groovepack/api-action`](#5-3lineasgroovepackapi-action)
|
|
19
19
|
- [6. `@3lineas/groovepack/api-toast`](#6-3lineasgroovepackapi-toast)
|
|
20
|
+
- [7. `@3lineas/groovepack/errors`](#7-3lineasgroovepackerrors)
|
|
20
21
|
- [End-to-End Architecture Example](#end-to-end-architecture-example)
|
|
21
22
|
- [Migrating from v0.x (CLI Copy-Paste)](#migrating-from-v0x-cli-copy-paste)
|
|
22
23
|
|
|
@@ -43,6 +44,7 @@ Install only what your app actually uses:
|
|
|
43
44
|
| Subpath | Required Peer Dependency | Target Environment |
|
|
44
45
|
| :--- | :--- | :--- |
|
|
45
46
|
| `/logger` | *None (0 deps)* | Node, Cloudflare Workers, Browser |
|
|
47
|
+
| `/errors` | *None (0 deps)* | Node, Cloudflare Workers, Browser |
|
|
46
48
|
| `/pipeline` | *None (0 deps)* | Cloudflare Workers, Node |
|
|
47
49
|
| `/pipeline/with-d1-transaction` | *None (0 deps)* | Cloudflare Workers (D1 / Drizzle) |
|
|
48
50
|
| `/api-action` | *None (0 deps)* | React, Astro, Next.js, Node |
|
|
@@ -60,6 +62,7 @@ Install only what your app actually uses:
|
|
|
60
62
|
4. `@3lineas/groovepack/api-client` — `createApiClient` (REST) & `createHonoClient` (Hono RPC).
|
|
61
63
|
5. `@3lineas/groovepack/api-action` — Polymorphic `apiAction` wrapper returning `ActionResponse<T>`.
|
|
62
64
|
6. `@3lineas/groovepack/api-toast` — `apiToast` and `createApiToast` for Shadcn v4 (`@base-ui/react/toast`).
|
|
65
|
+
7. `@3lineas/groovepack/errors` — `AppError` & `createAppError` for agnostic domain custom exceptions.
|
|
63
66
|
|
|
64
67
|
---
|
|
65
68
|
|
|
@@ -223,30 +226,50 @@ const response = await api.post("/orders", { total: BigInt(1500) });
|
|
|
223
226
|
|
|
224
227
|
## 5. `@3lineas/groovepack/api-action`
|
|
225
228
|
|
|
226
|
-
Polymorphic wrapper that normalizes Hono RPC responses, standard `fetch` responses, `ActionResponse<T>`, or raw promises
|
|
229
|
+
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
230
|
|
|
231
|
+
1. **Default `ActionResponse<T>` mode** (mutations & `apiToast`):
|
|
228
232
|
```typescript
|
|
229
233
|
import { apiAction, type ActionResponse } from "@3lineas/groovepack/api-action";
|
|
230
|
-
import { Logger } from "@3lineas/groovepack/logger";
|
|
231
234
|
import { rpc } from "@/lib/rpc";
|
|
232
235
|
|
|
233
|
-
const logger = new Logger("Web:Products");
|
|
234
|
-
|
|
235
236
|
export async function createProductAction(
|
|
236
237
|
input: { name: string; price: number },
|
|
237
238
|
): Promise<ActionResponse<Product>> {
|
|
238
239
|
return apiAction<Product>({
|
|
239
|
-
actionName: "createProduct",
|
|
240
|
-
logger,
|
|
241
240
|
defaultErrorMessage: "Could not create product. Please try again.",
|
|
242
241
|
apiCall: () => rpc.v1.products.$post({ json: input }),
|
|
243
|
-
onSuccess: (product) => {
|
|
244
|
-
console.log("Created:", product.id);
|
|
245
|
-
},
|
|
246
242
|
});
|
|
247
243
|
}
|
|
248
244
|
```
|
|
249
245
|
|
|
246
|
+
2. **`fallback` mode** (Server Components / `page.tsx` returning `Promise<T>`):
|
|
247
|
+
```typescript
|
|
248
|
+
import { createAppError } from "@3lineas/groovepack/errors";
|
|
249
|
+
|
|
250
|
+
const listProductsError = createAppError({
|
|
251
|
+
name: "ListProductsError",
|
|
252
|
+
statusCode: 500,
|
|
253
|
+
code: "PRODUCTS_LIST_FAILED",
|
|
254
|
+
defaultMessage: "Could not load products.",
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
const products = await apiAction<Product[]>({
|
|
258
|
+
apiCall: () => rpc.v1.products.$get(),
|
|
259
|
+
fallback: [],
|
|
260
|
+
onError: listProductsError,
|
|
261
|
+
});
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
3. **`throwOnError: true` mode** (Error Boundaries / `error.tsx` returning `Promise<T>` or throwing `Error`):
|
|
265
|
+
```typescript
|
|
266
|
+
const product = await apiAction<Product>({
|
|
267
|
+
apiCall: () => rpc.v1.products[":id"].$get({ param: { id } }),
|
|
268
|
+
throwOnError: true,
|
|
269
|
+
defaultErrorMessage: "Product could not be loaded.",
|
|
270
|
+
});
|
|
271
|
+
```
|
|
272
|
+
|
|
250
273
|
---
|
|
251
274
|
|
|
252
275
|
## 6. `@3lineas/groovepack/api-toast`
|
|
@@ -278,6 +301,7 @@ export default defineConfig({
|
|
|
278
301
|
});
|
|
279
302
|
```
|
|
280
303
|
|
|
304
|
+
```typescript
|
|
281
305
|
// Or passing the toast manager directly per call
|
|
282
306
|
await apiToast({
|
|
283
307
|
toast: toastManager,
|
|
@@ -288,6 +312,113 @@ await apiToast({
|
|
|
288
312
|
|
|
289
313
|
---
|
|
290
314
|
|
|
315
|
+
## 7. `@3lineas/groovepack/errors`
|
|
316
|
+
|
|
317
|
+
Framework-agnostic custom exception primitives (`createAppError` and `AppError`) for **backend APIs, domain/pipeline actions, queues, and frontend Server Actions**. Every custom exception extends `AppError`, carries explicit `statusCode` and `code` metadata, and automatically logs via `@3lineas/groovepack/logger` unless `silent: true`.
|
|
318
|
+
|
|
319
|
+
### A. Defining Domain Custom Exceptions (`createAppError`)
|
|
320
|
+
|
|
321
|
+
Define each domain error as an atomic callable factory (`1` export per file):
|
|
322
|
+
|
|
323
|
+
```typescript
|
|
324
|
+
// src/errors/stores/slug-conflict.error.ts
|
|
325
|
+
import { createAppError } from "@3lineas/groovepack/errors";
|
|
326
|
+
|
|
327
|
+
export const slugConflictError = createAppError({
|
|
328
|
+
name: "SlugConflictError",
|
|
329
|
+
statusCode: 409,
|
|
330
|
+
code: "SLUG_ALREADY_IN_USE",
|
|
331
|
+
defaultMessage: "This URL slug is already taken. Please choose another one.",
|
|
332
|
+
silent: true, // Expected business conflict: suppress error log noise
|
|
333
|
+
});
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
```typescript
|
|
337
|
+
// src/errors/users/list-users.error.ts
|
|
338
|
+
import { createAppError } from "@3lineas/groovepack/errors";
|
|
339
|
+
|
|
340
|
+
export const listUsersError = createAppError({
|
|
341
|
+
name: "ListUsersError",
|
|
342
|
+
statusCode: 500,
|
|
343
|
+
code: "USERS_LIST_FAILED",
|
|
344
|
+
defaultMessage: "Could not load users right now.",
|
|
345
|
+
});
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
### B. Throwing in Domain Logic, Pipelines & Backend Actions
|
|
349
|
+
|
|
350
|
+
```typescript
|
|
351
|
+
import { slugConflictError } from "@/errors/stores/slug-conflict.error";
|
|
352
|
+
|
|
353
|
+
// Uses defaultMessage:
|
|
354
|
+
if (existingStore) {
|
|
355
|
+
throw slugConflictError(undefined, { slug });
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// Or overrides the message dynamically:
|
|
359
|
+
throw slugConflictError(`The slug "${slug}" is already registered.`, { slug });
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
### C. Catching, Type-Guarding & Global Error Handlers
|
|
363
|
+
|
|
364
|
+
```typescript
|
|
365
|
+
import { AppError } from "@3lineas/groovepack/errors";
|
|
366
|
+
import { slugConflictError } from "@/errors/stores/slug-conflict.error";
|
|
367
|
+
|
|
368
|
+
try {
|
|
369
|
+
await createStore(input);
|
|
370
|
+
} catch (caughtError) {
|
|
371
|
+
// Match a specific custom exception:
|
|
372
|
+
if (slugConflictError.is(caughtError)) {
|
|
373
|
+
return { status: caughtError.statusCode, code: caughtError.code };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// Or handle any AppError uniformly (e.g., Hono globalErrorHandler):
|
|
377
|
+
if (caughtError instanceof AppError) {
|
|
378
|
+
return ctx.json(
|
|
379
|
+
{ success: false, error: caughtError.message, code: caughtError.code },
|
|
380
|
+
caughtError.statusCode,
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
throw caughtError;
|
|
385
|
+
}
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
### D. Class Inheritance (`extends AppError`)
|
|
389
|
+
|
|
390
|
+
When you need custom class hierarchy or extra properties, extend `AppError` directly:
|
|
391
|
+
|
|
392
|
+
```typescript
|
|
393
|
+
import { AppError } from "@3lineas/groovepack/errors";
|
|
394
|
+
|
|
395
|
+
export class PaymentGatewayError extends AppError {
|
|
396
|
+
constructor(message: string, details?: Record<string, unknown>, cause?: unknown) {
|
|
397
|
+
super({
|
|
398
|
+
message,
|
|
399
|
+
statusCode: 502,
|
|
400
|
+
code: "PAYMENT_GATEWAY_ERROR",
|
|
401
|
+
details,
|
|
402
|
+
cause,
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
### E. Direct Integration with `apiAction`
|
|
409
|
+
|
|
410
|
+
Because `createAppError` factories share the `(message?, details?)` signature, pass them directly to `onError` without wrappers across all three `apiAction` modes (`ActionResponse<T>`, `fallback`, and `throwOnError: true`):
|
|
411
|
+
|
|
412
|
+
```typescript
|
|
413
|
+
const users = await apiAction<User[]>({
|
|
414
|
+
apiCall: () => rpc.v1.users.$get(),
|
|
415
|
+
fallback: [],
|
|
416
|
+
onError: listUsersError,
|
|
417
|
+
});
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
---
|
|
421
|
+
|
|
291
422
|
## End-to-End Architecture Example
|
|
292
423
|
|
|
293
424
|
```text
|
|
@@ -18,12 +18,12 @@ type ApiCallResult<T> = MinimalResponse | ActionResponse<T>;
|
|
|
18
18
|
/**
|
|
19
19
|
* Optional error logger callback invoked when `apiAction` catches an unexpected error.
|
|
20
20
|
*/
|
|
21
|
-
type ErrorLogger = (message: string, context?: Record<string, unknown>) => void;
|
|
21
|
+
type ErrorLogger = (message: string, context?: Record<string, unknown>) => Error | 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
|
@@ -1,14 +1,16 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AppError
|
|
3
|
+
} from "../chunk-QRQSSZCB.js";
|
|
4
|
+
import {
|
|
5
|
+
logger
|
|
6
|
+
} from "../chunk-H76QJ2LB.js";
|
|
1
7
|
import {
|
|
2
8
|
resolveLocaleMessages
|
|
3
9
|
} from "../chunk-OSPD6EX4.js";
|
|
4
10
|
|
|
5
11
|
// src/api-action/default-error-logger.ts
|
|
6
12
|
var defaultErrorLogger = (message, context) => {
|
|
7
|
-
|
|
8
|
-
console.error(`[apiAction] ${message}`, context);
|
|
9
|
-
return;
|
|
10
|
-
}
|
|
11
|
-
console.error(`[apiAction] ${message}`);
|
|
13
|
+
logger.error(`[apiAction] ${message}`, context);
|
|
12
14
|
};
|
|
13
15
|
|
|
14
16
|
// src/api-action/is-minimal-response.ts
|
|
@@ -35,17 +37,27 @@ async function tryParseJson(response) {
|
|
|
35
37
|
}
|
|
36
38
|
|
|
37
39
|
// src/api-action/handle-http-response.ts
|
|
38
|
-
async function handleHttpResponse(response, fallbackErrorMessage, serverRequestFailedMessage, logError) {
|
|
40
|
+
async function handleHttpResponse(response, fallbackErrorMessage, serverRequestFailedMessage, logError, hasCustomOnError) {
|
|
39
41
|
const payload = await tryParseJson(response);
|
|
40
42
|
if (!response.ok) {
|
|
41
43
|
const serverError = payload && typeof payload["error"] === "string" ? payload["error"] : void 0;
|
|
42
44
|
const serverMessage = payload && typeof payload["message"] === "string" ? payload["message"] : void 0;
|
|
45
|
+
const resolvedMessage = serverError ?? serverMessage ?? fallbackErrorMessage;
|
|
46
|
+
if (hasCustomOnError) {
|
|
47
|
+
logError(resolvedMessage, { status: response.status });
|
|
48
|
+
}
|
|
43
49
|
return {
|
|
44
50
|
success: false,
|
|
45
|
-
error:
|
|
51
|
+
error: resolvedMessage
|
|
46
52
|
};
|
|
47
53
|
}
|
|
48
54
|
if (isActionResponse(payload)) {
|
|
55
|
+
if (!payload.success && hasCustomOnError) {
|
|
56
|
+
logError(
|
|
57
|
+
payload.error ?? payload.message ?? fallbackErrorMessage,
|
|
58
|
+
{ success: false, status: response.status }
|
|
59
|
+
);
|
|
60
|
+
}
|
|
49
61
|
return payload;
|
|
50
62
|
}
|
|
51
63
|
if (payload !== null) {
|
|
@@ -63,25 +75,26 @@ async function handleHttpResponse(response, fallbackErrorMessage, serverRequestF
|
|
|
63
75
|
};
|
|
64
76
|
}
|
|
65
77
|
|
|
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;
|
|
78
|
+
// src/api-action/execute-api-call.ts
|
|
79
|
+
async function executeApiCall(apiCall, resolvedDefaultError, serverRequestFailedMessage, onError, hasCustomOnError) {
|
|
74
80
|
try {
|
|
75
81
|
const actionResult = await apiCall();
|
|
76
82
|
if (isMinimalResponse(actionResult)) {
|
|
77
83
|
return await handleHttpResponse(
|
|
78
84
|
actionResult,
|
|
79
85
|
resolvedDefaultError,
|
|
80
|
-
|
|
81
|
-
onError
|
|
86
|
+
serverRequestFailedMessage,
|
|
87
|
+
onError,
|
|
88
|
+
hasCustomOnError
|
|
82
89
|
);
|
|
83
90
|
}
|
|
84
91
|
if (isActionResponse(actionResult)) {
|
|
92
|
+
if (!actionResult.success && hasCustomOnError) {
|
|
93
|
+
onError(
|
|
94
|
+
actionResult.error ?? actionResult.message ?? resolvedDefaultError,
|
|
95
|
+
{ success: false }
|
|
96
|
+
);
|
|
97
|
+
}
|
|
85
98
|
return actionResult;
|
|
86
99
|
}
|
|
87
100
|
return {
|
|
@@ -89,7 +102,7 @@ async function apiAction({
|
|
|
89
102
|
data: actionResult
|
|
90
103
|
};
|
|
91
104
|
} catch (caughtError) {
|
|
92
|
-
onError(
|
|
105
|
+
onError(resolvedDefaultError, {
|
|
93
106
|
error: caughtError instanceof Error ? caughtError.message : String(caughtError)
|
|
94
107
|
});
|
|
95
108
|
return {
|
|
@@ -98,6 +111,84 @@ async function apiAction({
|
|
|
98
111
|
};
|
|
99
112
|
}
|
|
100
113
|
}
|
|
114
|
+
|
|
115
|
+
// src/api-action/unwrap-action-response.ts
|
|
116
|
+
function unwrapActionResponse(response, defaultErrorMessage, onError, errorLogged, createdError, strategy) {
|
|
117
|
+
if (response.success && response.data !== void 0) {
|
|
118
|
+
return response.data;
|
|
119
|
+
}
|
|
120
|
+
const failureMessage = response.success ? response.error ?? defaultErrorMessage : response.error ?? response.message ?? defaultErrorMessage;
|
|
121
|
+
let resolvedError = createdError;
|
|
122
|
+
if (!errorLogged) {
|
|
123
|
+
const loggedResult = onError(failureMessage, {
|
|
124
|
+
success: response.success,
|
|
125
|
+
hasData: response.data !== void 0
|
|
126
|
+
});
|
|
127
|
+
if (loggedResult instanceof Error) {
|
|
128
|
+
resolvedError = loggedResult;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (strategy.mode === "throw") {
|
|
132
|
+
throw resolvedError instanceof Error ? resolvedError : new AppError({
|
|
133
|
+
name: "ApiActionError",
|
|
134
|
+
message: failureMessage,
|
|
135
|
+
statusCode: 500,
|
|
136
|
+
code: "API_ACTION_FAILED",
|
|
137
|
+
silent: true
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return strategy.fallback;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// src/api-action/index.ts
|
|
144
|
+
async function apiAction(options) {
|
|
145
|
+
const {
|
|
146
|
+
apiCall,
|
|
147
|
+
defaultErrorMessage,
|
|
148
|
+
onError = defaultErrorLogger
|
|
149
|
+
} = options;
|
|
150
|
+
const hasCustomOnError = options.onError !== void 0;
|
|
151
|
+
const messages = resolveLocaleMessages();
|
|
152
|
+
const resolvedDefaultError = defaultErrorMessage ?? messages.unexpectedError;
|
|
153
|
+
let errorLogged = false;
|
|
154
|
+
let createdError;
|
|
155
|
+
const trackedOnError = (message, details) => {
|
|
156
|
+
errorLogged = true;
|
|
157
|
+
const result = onError(message, details);
|
|
158
|
+
if (result instanceof Error) {
|
|
159
|
+
createdError = result;
|
|
160
|
+
}
|
|
161
|
+
return result;
|
|
162
|
+
};
|
|
163
|
+
const response = await executeApiCall(
|
|
164
|
+
apiCall,
|
|
165
|
+
resolvedDefaultError,
|
|
166
|
+
messages.serverRequestFailed,
|
|
167
|
+
trackedOnError,
|
|
168
|
+
hasCustomOnError
|
|
169
|
+
);
|
|
170
|
+
if ("fallback" in options) {
|
|
171
|
+
return unwrapActionResponse(
|
|
172
|
+
response,
|
|
173
|
+
resolvedDefaultError,
|
|
174
|
+
onError,
|
|
175
|
+
errorLogged,
|
|
176
|
+
createdError,
|
|
177
|
+
{ mode: "fallback", fallback: options.fallback }
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
if ("throwOnError" in options && options.throwOnError === true) {
|
|
181
|
+
return unwrapActionResponse(
|
|
182
|
+
response,
|
|
183
|
+
resolvedDefaultError,
|
|
184
|
+
onError,
|
|
185
|
+
errorLogged,
|
|
186
|
+
createdError,
|
|
187
|
+
{ mode: "throw" }
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
return response;
|
|
191
|
+
}
|
|
101
192
|
export {
|
|
102
193
|
apiAction
|
|
103
194
|
};
|
|
@@ -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 { logger } from \"@/logger/index\";\nimport 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 logger.error(`[apiAction] ${message}`, context);\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 hasCustomOnError: boolean,\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 const resolvedMessage =\n serverError ?? serverMessage ?? fallbackErrorMessage;\n\n if (hasCustomOnError) {\n logError(resolvedMessage, { status: response.status });\n }\n\n return {\n success: false,\n error: resolvedMessage,\n };\n }\n\n if (isActionResponse<T>(payload)) {\n if (!payload.success && hasCustomOnError) {\n logError(\n payload.error ?? payload.message ?? fallbackErrorMessage,\n { success: false, status: response.status },\n );\n }\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 hasCustomOnError: boolean,\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 hasCustomOnError,\n );\n }\n\n if (isActionResponse<T>(actionResult)) {\n if (!actionResult.success && hasCustomOnError) {\n onError(\n actionResult.error ?? actionResult.message ?? resolvedDefaultError,\n { success: false },\n );\n }\n return actionResult;\n }\n\n return {\n success: true,\n data: actionResult as T,\n };\n } catch (caughtError) {\n onError(resolvedDefaultError, {\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 { AppError } from \"@/errors/app-error\";\nimport 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 createdError: Error | undefined,\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 let resolvedError = createdError;\n\n if (!errorLogged) {\n const loggedResult = onError(failureMessage, {\n success: response.success,\n hasData: response.data !== undefined,\n });\n if (loggedResult instanceof Error) {\n resolvedError = loggedResult;\n }\n }\n\n if (strategy.mode === \"throw\") {\n throw resolvedError instanceof Error\n ? resolvedError\n : new AppError({\n name: \"ApiActionError\",\n message: failureMessage,\n statusCode: 500,\n code: \"API_ACTION_FAILED\",\n silent: true,\n });\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 hasCustomOnError = options.onError !== undefined;\n const messages = resolveLocaleMessages();\n const resolvedDefaultError = defaultErrorMessage ?? messages.unexpectedError;\n\n let errorLogged = false;\n let createdError: Error | undefined;\n const trackedOnError: ErrorLogger = (message, details) => {\n errorLogged = true;\n const result = onError(message, details);\n if (result instanceof Error) {\n createdError = result;\n }\n return result;\n };\n\n const response = await executeApiCall<T>(\n apiCall,\n resolvedDefaultError,\n messages.serverRequestFailed,\n trackedOnError,\n hasCustomOnError,\n );\n\n if (\"fallback\" in options) {\n return unwrapActionResponse<T>(\n response,\n resolvedDefaultError,\n onError,\n errorLogged,\n createdError,\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 createdError,\n { mode: \"throw\" },\n );\n }\n\n return response;\n}\n"],"mappings":"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","names":[]}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// src/logger/check-is-development.ts
|
|
2
|
+
function checkIsDevelopment() {
|
|
3
|
+
const globalRecord = globalThis;
|
|
4
|
+
const processValue = globalRecord["process"];
|
|
5
|
+
if (typeof processValue === "object" && processValue !== null) {
|
|
6
|
+
const envValue = processValue["env"];
|
|
7
|
+
if (typeof envValue === "object" && envValue !== null) {
|
|
8
|
+
const nodeEnv = envValue["NODE_ENV"];
|
|
9
|
+
if (nodeEnv === "development" || nodeEnv === "test") {
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
12
|
+
if (nodeEnv === "production") {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
return Boolean(import.meta.env?.DEV);
|
|
19
|
+
} catch {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// src/logger/format-dev-log.ts
|
|
25
|
+
var LEVEL_COLORS = {
|
|
26
|
+
INFO: "\x1B[32m",
|
|
27
|
+
WARN: "\x1B[33m",
|
|
28
|
+
ERROR: "\x1B[31m",
|
|
29
|
+
DEBUG: "\x1B[36m"
|
|
30
|
+
};
|
|
31
|
+
var RESET_COLOR = "\x1B[0m";
|
|
32
|
+
var DIM_COLOR = "\x1B[2m";
|
|
33
|
+
function formatDevLog(level, message, context, timestamp) {
|
|
34
|
+
const color = LEVEL_COLORS[level];
|
|
35
|
+
const resolvedTimestamp = timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
36
|
+
const baseLine = `${DIM_COLOR}${resolvedTimestamp}${RESET_COLOR} ${color}[${level}]${RESET_COLOR} ${message}`;
|
|
37
|
+
if (!context || Object.keys(context).length === 0) {
|
|
38
|
+
return baseLine;
|
|
39
|
+
}
|
|
40
|
+
return `${baseLine} ${DIM_COLOR}${JSON.stringify(context)}${RESET_COLOR}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// src/logger/index.ts
|
|
44
|
+
var Logger = class {
|
|
45
|
+
write(level, message, context) {
|
|
46
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
47
|
+
const isDev = checkIsDevelopment();
|
|
48
|
+
if (isDev) {
|
|
49
|
+
const formatted = formatDevLog(level, message, context, timestamp);
|
|
50
|
+
this.emitToConsole(level, formatted);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const payload = JSON.stringify({
|
|
54
|
+
timestamp,
|
|
55
|
+
level,
|
|
56
|
+
message,
|
|
57
|
+
...context ? { context } : {}
|
|
58
|
+
});
|
|
59
|
+
this.emitToConsole(level, payload);
|
|
60
|
+
}
|
|
61
|
+
emitToConsole(level, line) {
|
|
62
|
+
if (level === "ERROR") {
|
|
63
|
+
console.error(line);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (level === "WARN") {
|
|
67
|
+
console.warn(line);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
console.log(line);
|
|
71
|
+
}
|
|
72
|
+
info(message, context) {
|
|
73
|
+
this.write("INFO", message, context);
|
|
74
|
+
}
|
|
75
|
+
warn(message, context) {
|
|
76
|
+
this.write("WARN", message, context);
|
|
77
|
+
}
|
|
78
|
+
error(message, context) {
|
|
79
|
+
this.write("ERROR", message, context);
|
|
80
|
+
}
|
|
81
|
+
debug(message, context) {
|
|
82
|
+
this.write("DEBUG", message, context);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
var logger = new Logger();
|
|
86
|
+
|
|
87
|
+
export {
|
|
88
|
+
logger
|
|
89
|
+
};
|
|
90
|
+
//# sourceMappingURL=chunk-H76QJ2LB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/logger/check-is-development.ts","../src/logger/format-dev-log.ts","../src/logger/index.ts"],"sourcesContent":["/**\n * Safely checks whether the current Vinext / Cloudflare Workers runtime is in\n * development or test mode using static `import.meta.env.DEV` access compatible\n * with Vite 8's `ModuleRunner`.\n */\nexport function checkIsDevelopment(): boolean {\n const globalRecord = globalThis as Record<string, unknown>;\n const processValue = globalRecord[\"process\"];\n if (typeof processValue === \"object\" && processValue !== null) {\n const envValue = (processValue as Record<string, unknown>)[\"env\"];\n if (typeof envValue === \"object\" && envValue !== null) {\n const nodeEnv = (envValue as Record<string, unknown>)[\"NODE_ENV\"];\n if (nodeEnv === \"development\" || nodeEnv === \"test\") {\n return true;\n }\n if (nodeEnv === \"production\") {\n return false;\n }\n }\n }\n\n try {\n return Boolean(import.meta.env?.DEV);\n } catch {\n return false;\n }\n}\n","import type { LogContext } from \"@/types/logger/log-context.type\";\nimport type { LogLevel } from \"@/types/logger/log-level.type\";\n\nconst LEVEL_COLORS: Record<LogLevel, string> = {\n INFO: \"\\x1b[32m\",\n WARN: \"\\x1b[33m\",\n ERROR: \"\\x1b[31m\",\n DEBUG: \"\\x1b[36m\",\n};\n\nconst RESET_COLOR = \"\\x1b[0m\";\nconst DIM_COLOR = \"\\x1b[2m\";\n\n/**\n * Formats a log entry with ANSI colors for human-readable development output.\n */\nexport function formatDevLog(\n level: LogLevel,\n message: string,\n context?: LogContext,\n timestamp?: string,\n): string {\n const color = LEVEL_COLORS[level];\n const resolvedTimestamp = timestamp ?? new Date().toISOString();\n const baseLine = `${DIM_COLOR}${resolvedTimestamp}${RESET_COLOR} ${color}[${level}]${RESET_COLOR} ${message}`;\n\n if (!context || Object.keys(context).length === 0) {\n return baseLine;\n }\n\n return `${baseLine} ${DIM_COLOR}${JSON.stringify(context)}${RESET_COLOR}`;\n}\n","import type { LogContext } from \"@/types/logger/log-context.type\";\nimport type { LogLevel } from \"@/types/logger/log-level.type\";\nimport { checkIsDevelopment } from \"@/logger/check-is-development\";\nimport { formatDevLog } from \"@/logger/format-dev-log\";\n\nexport type { LogLevel } from \"@/types/logger/log-level.type\";\nexport type { LogContext } from \"@/types/logger/log-context.type\";\n\n/**\n * Universal structured logger.\n * Outputs ANSI-colored lines in development/test and structured JSON in production.\n */\nclass Logger {\n private write(level: LogLevel, message: string, context?: LogContext): void {\n const timestamp = new Date().toISOString();\n const isDev = checkIsDevelopment();\n\n if (isDev) {\n const formatted = formatDevLog(level, message, context, timestamp);\n this.emitToConsole(level, formatted);\n return;\n }\n\n const payload = JSON.stringify({\n timestamp,\n level,\n message,\n ...(context ? { context } : {}),\n });\n this.emitToConsole(level, payload);\n }\n\n private emitToConsole(level: LogLevel, line: string): void {\n if (level === \"ERROR\") {\n console.error(line);\n return;\n }\n if (level === \"WARN\") {\n console.warn(line);\n return;\n }\n console.log(line);\n }\n\n public info(message: string, context?: LogContext): void {\n this.write(\"INFO\", message, context);\n }\n\n public warn(message: string, context?: LogContext): void {\n this.write(\"WARN\", message, context);\n }\n\n public error(message: string, context?: LogContext): void {\n this.write(\"ERROR\", message, context);\n }\n\n public debug(message: string, context?: LogContext): void {\n this.write(\"DEBUG\", message, context);\n }\n}\n\nexport const logger = new Logger();\n"],"mappings":";AAKO,SAAS,qBAA8B;AAC5C,QAAM,eAAe;AACrB,QAAM,eAAe,aAAa,SAAS;AAC3C,MAAI,OAAO,iBAAiB,YAAY,iBAAiB,MAAM;AAC7D,UAAM,WAAY,aAAyC,KAAK;AAChE,QAAI,OAAO,aAAa,YAAY,aAAa,MAAM;AACrD,YAAM,UAAW,SAAqC,UAAU;AAChE,UAAI,YAAY,iBAAiB,YAAY,QAAQ;AACnD,eAAO;AAAA,MACT;AACA,UAAI,YAAY,cAAc;AAC5B,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAEA,MAAI;AACF,WAAO,QAAQ,YAAY,KAAK,GAAG;AAAA,EACrC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ACvBA,IAAM,eAAyC;AAAA,EAC7C,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AACT;AAEA,IAAM,cAAc;AACpB,IAAM,YAAY;AAKX,SAAS,aACd,OACA,SACA,SACA,WACQ;AACR,QAAM,QAAQ,aAAa,KAAK;AAChC,QAAM,oBAAoB,cAAa,oBAAI,KAAK,GAAE,YAAY;AAC9D,QAAM,WAAW,GAAG,SAAS,GAAG,iBAAiB,GAAG,WAAW,IAAI,KAAK,IAAI,KAAK,IAAI,WAAW,IAAI,OAAO;AAE3G,MAAI,CAAC,WAAW,OAAO,KAAK,OAAO,EAAE,WAAW,GAAG;AACjD,WAAO;AAAA,EACT;AAEA,SAAO,GAAG,QAAQ,IAAI,SAAS,GAAG,KAAK,UAAU,OAAO,CAAC,GAAG,WAAW;AACzE;;;ACnBA,IAAM,SAAN,MAAa;AAAA,EACH,MAAM,OAAiB,SAAiB,SAA4B;AAC1E,UAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AACzC,UAAM,QAAQ,mBAAmB;AAEjC,QAAI,OAAO;AACT,YAAM,YAAY,aAAa,OAAO,SAAS,SAAS,SAAS;AACjE,WAAK,cAAc,OAAO,SAAS;AACnC;AAAA,IACF;AAEA,UAAM,UAAU,KAAK,UAAU;AAAA,MAC7B;AAAA,MACA;AAAA,MACA;AAAA,MACA,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC/B,CAAC;AACD,SAAK,cAAc,OAAO,OAAO;AAAA,EACnC;AAAA,EAEQ,cAAc,OAAiB,MAAoB;AACzD,QAAI,UAAU,SAAS;AACrB,cAAQ,MAAM,IAAI;AAClB;AAAA,IACF;AACA,QAAI,UAAU,QAAQ;AACpB,cAAQ,KAAK,IAAI;AACjB;AAAA,IACF;AACA,YAAQ,IAAI,IAAI;AAAA,EAClB;AAAA,EAEO,KAAK,SAAiB,SAA4B;AACvD,SAAK,MAAM,QAAQ,SAAS,OAAO;AAAA,EACrC;AAAA,EAEO,KAAK,SAAiB,SAA4B;AACvD,SAAK,MAAM,QAAQ,SAAS,OAAO;AAAA,EACrC;AAAA,EAEO,MAAM,SAAiB,SAA4B;AACxD,SAAK,MAAM,SAAS,SAAS,OAAO;AAAA,EACtC;AAAA,EAEO,MAAM,SAAiB,SAA4B;AACxD,SAAK,MAAM,SAAS,SAAS,OAAO;AAAA,EACtC;AACF;AAEO,IAAM,SAAS,IAAI,OAAO;","names":[]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import {
|
|
2
|
+
logger
|
|
3
|
+
} from "./chunk-H76QJ2LB.js";
|
|
4
|
+
|
|
5
|
+
// src/errors/app-error.ts
|
|
6
|
+
var AppError = class extends Error {
|
|
7
|
+
statusCode;
|
|
8
|
+
code;
|
|
9
|
+
silent;
|
|
10
|
+
details;
|
|
11
|
+
constructor(params) {
|
|
12
|
+
super(
|
|
13
|
+
params.message,
|
|
14
|
+
params.cause !== void 0 ? { cause: params.cause } : void 0
|
|
15
|
+
);
|
|
16
|
+
this.name = params.name ?? new.target.name;
|
|
17
|
+
this.statusCode = params.statusCode;
|
|
18
|
+
this.code = params.code;
|
|
19
|
+
this.silent = params.silent ?? false;
|
|
20
|
+
this.details = params.details;
|
|
21
|
+
if (!this.silent) {
|
|
22
|
+
logger.error(`[${this.code}] ${this.message}`, {
|
|
23
|
+
statusCode: this.statusCode,
|
|
24
|
+
...this.details !== void 0 ? { details: this.details } : {}
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export {
|
|
31
|
+
AppError
|
|
32
|
+
};
|
|
33
|
+
//# sourceMappingURL=chunk-QRQSSZCB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors/app-error.ts"],"sourcesContent":["import { logger } from \"@/logger/index\";\nimport type { AppErrorParams } from \"@/types/errors/app-error-params.type\";\n\n/**\n * Base domain exception carrying HTTP status code, semantic error code,\n * optional structured details, and automatic structured logging unless `silent`.\n */\nexport class AppError extends Error {\n readonly statusCode: number;\n readonly code: string;\n readonly silent: boolean;\n readonly details?: Record<string, unknown>;\n\n constructor(params: AppErrorParams) {\n super(\n params.message,\n params.cause !== undefined ? { cause: params.cause } : undefined,\n );\n this.name = params.name ?? new.target.name;\n this.statusCode = params.statusCode;\n this.code = params.code;\n this.silent = params.silent ?? false;\n this.details = params.details;\n\n if (!this.silent) {\n logger.error(`[${this.code}] ${this.message}`, {\n statusCode: this.statusCode,\n ...(this.details !== undefined ? { details: this.details } : {}),\n });\n }\n }\n}\n"],"mappings":";;;;;AAOO,IAAM,WAAN,cAAuB,MAAM;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,QAAwB;AAClC;AAAA,MACE,OAAO;AAAA,MACP,OAAO,UAAU,SAAY,EAAE,OAAO,OAAO,MAAM,IAAI;AAAA,IACzD;AACA,SAAK,OAAO,OAAO,QAAQ,WAAW;AACtC,SAAK,aAAa,OAAO;AACzB,SAAK,OAAO,OAAO;AACnB,SAAK,SAAS,OAAO,UAAU;AAC/B,SAAK,UAAU,OAAO;AAEtB,QAAI,CAAC,KAAK,QAAQ;AAChB,aAAO,MAAM,IAAI,KAAK,IAAI,KAAK,KAAK,OAAO,IAAI;AAAA,QAC7C,YAAY,KAAK;AAAA,QACjB,GAAI,KAAK,YAAY,SAAY,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;AAAA,MAChE,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Constructor options for creating an `AppError` instance.
|
|
3
|
+
*/
|
|
4
|
+
interface AppErrorParams {
|
|
5
|
+
message: string;
|
|
6
|
+
statusCode: number;
|
|
7
|
+
code: string;
|
|
8
|
+
silent?: boolean;
|
|
9
|
+
details?: Record<string, unknown>;
|
|
10
|
+
cause?: unknown;
|
|
11
|
+
name?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Base domain exception carrying HTTP status code, semantic error code,
|
|
16
|
+
* optional structured details, and automatic structured logging unless `silent`.
|
|
17
|
+
*/
|
|
18
|
+
declare class AppError extends Error {
|
|
19
|
+
readonly statusCode: number;
|
|
20
|
+
readonly code: string;
|
|
21
|
+
readonly silent: boolean;
|
|
22
|
+
readonly details?: Record<string, unknown>;
|
|
23
|
+
constructor(params: AppErrorParams);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Callable custom exception factory compatible with `apiAction` `onError` and `throw`.
|
|
28
|
+
*/
|
|
29
|
+
interface AppErrorFactory {
|
|
30
|
+
(message?: string, details?: Record<string, unknown>): AppError;
|
|
31
|
+
readonly code: string;
|
|
32
|
+
readonly statusCode: number;
|
|
33
|
+
is(caughtError: unknown): caughtError is AppError;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Configuration options for defining a reusable domain `AppErrorFactory`.
|
|
38
|
+
*/
|
|
39
|
+
interface CreateAppErrorOptions {
|
|
40
|
+
name?: string;
|
|
41
|
+
statusCode: number;
|
|
42
|
+
code: string;
|
|
43
|
+
defaultMessage: string;
|
|
44
|
+
silent?: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Creates a reusable callable `AppErrorFactory` for a specific domain error.
|
|
49
|
+
*
|
|
50
|
+
* Compatible with both `throw myError(message?, details?)` and `apiAction({ onError: myError })`.
|
|
51
|
+
*/
|
|
52
|
+
declare function createAppError(options: CreateAppErrorOptions): AppErrorFactory;
|
|
53
|
+
|
|
54
|
+
export { AppError, type AppErrorFactory, type AppErrorParams, type CreateAppErrorOptions, createAppError };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AppError
|
|
3
|
+
} from "../chunk-QRQSSZCB.js";
|
|
4
|
+
import "../chunk-H76QJ2LB.js";
|
|
5
|
+
|
|
6
|
+
// src/errors/create-app-error.ts
|
|
7
|
+
function createAppError(options) {
|
|
8
|
+
const factory = (message, details) => {
|
|
9
|
+
const resolvedMessage = message !== void 0 && message.trim().length > 0 ? message : options.defaultMessage;
|
|
10
|
+
const appError = new AppError({
|
|
11
|
+
name: options.name ?? options.code,
|
|
12
|
+
message: resolvedMessage,
|
|
13
|
+
statusCode: options.statusCode,
|
|
14
|
+
code: options.code,
|
|
15
|
+
silent: options.silent,
|
|
16
|
+
details
|
|
17
|
+
});
|
|
18
|
+
if (typeof Error.captureStackTrace === "function") {
|
|
19
|
+
Error.captureStackTrace(appError, factory);
|
|
20
|
+
}
|
|
21
|
+
return appError;
|
|
22
|
+
};
|
|
23
|
+
Object.defineProperties(factory, {
|
|
24
|
+
code: {
|
|
25
|
+
value: options.code,
|
|
26
|
+
writable: false,
|
|
27
|
+
enumerable: true,
|
|
28
|
+
configurable: false
|
|
29
|
+
},
|
|
30
|
+
statusCode: {
|
|
31
|
+
value: options.statusCode,
|
|
32
|
+
writable: false,
|
|
33
|
+
enumerable: true,
|
|
34
|
+
configurable: false
|
|
35
|
+
},
|
|
36
|
+
is: {
|
|
37
|
+
value: (caughtError) => caughtError instanceof AppError && caughtError.code === options.code,
|
|
38
|
+
writable: false,
|
|
39
|
+
enumerable: true,
|
|
40
|
+
configurable: false
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
return factory;
|
|
44
|
+
}
|
|
45
|
+
export {
|
|
46
|
+
AppError,
|
|
47
|
+
createAppError
|
|
48
|
+
};
|
|
49
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/errors/create-app-error.ts"],"sourcesContent":["import { AppError } from \"@/errors/app-error\";\nimport type { AppErrorFactory } from \"@/types/errors/app-error-factory.type\";\nimport type { CreateAppErrorOptions } from \"@/types/errors/create-app-error-options.type\";\n\n/**\n * Creates a reusable callable `AppErrorFactory` for a specific domain error.\n *\n * Compatible with both `throw myError(message?, details?)` and `apiAction({ onError: myError })`.\n */\nexport function createAppError(options: CreateAppErrorOptions): AppErrorFactory {\n const factory = (\n message?: string,\n details?: Record<string, unknown>,\n ): AppError => {\n const resolvedMessage =\n message !== undefined && message.trim().length > 0\n ? message\n : options.defaultMessage;\n\n const appError = new AppError({\n name: options.name ?? options.code,\n message: resolvedMessage,\n statusCode: options.statusCode,\n code: options.code,\n silent: options.silent,\n details,\n });\n\n if (typeof Error.captureStackTrace === \"function\") {\n Error.captureStackTrace(appError, factory);\n }\n\n return appError;\n };\n\n Object.defineProperties(factory, {\n code: {\n value: options.code,\n writable: false,\n enumerable: true,\n configurable: false,\n },\n statusCode: {\n value: options.statusCode,\n writable: false,\n enumerable: true,\n configurable: false,\n },\n is: {\n value: (caughtError: unknown): caughtError is AppError =>\n caughtError instanceof AppError && caughtError.code === options.code,\n writable: false,\n enumerable: true,\n configurable: false,\n },\n });\n\n return factory as AppErrorFactory;\n}\n"],"mappings":";;;;;;AASO,SAAS,eAAe,SAAiD;AAC9E,QAAM,UAAU,CACd,SACA,YACa;AACb,UAAM,kBACJ,YAAY,UAAa,QAAQ,KAAK,EAAE,SAAS,IAC7C,UACA,QAAQ;AAEd,UAAM,WAAW,IAAI,SAAS;AAAA,MAC5B,MAAM,QAAQ,QAAQ,QAAQ;AAAA,MAC9B,SAAS;AAAA,MACT,YAAY,QAAQ;AAAA,MACpB,MAAM,QAAQ;AAAA,MACd,QAAQ,QAAQ;AAAA,MAChB;AAAA,IACF,CAAC;AAED,QAAI,OAAO,MAAM,sBAAsB,YAAY;AACjD,YAAM,kBAAkB,UAAU,OAAO;AAAA,IAC3C;AAEA,WAAO;AAAA,EACT;AAEA,SAAO,iBAAiB,SAAS;AAAA,IAC/B,MAAM;AAAA,MACJ,OAAO,QAAQ;AAAA,MACf,UAAU;AAAA,MACV,YAAY;AAAA,MACZ,cAAc;AAAA,IAChB;AAAA,IACA,YAAY;AAAA,MACV,OAAO,QAAQ;AAAA,MACf,UAAU;AAAA,MACV,YAAY;AAAA,MACZ,cAAc;AAAA,IAChB;AAAA,IACA,IAAI;AAAA,MACF,OAAO,CAAC,gBACN,uBAAuB,YAAY,YAAY,SAAS,QAAQ;AAAA,MAClE,UAAU;AAAA,MACV,YAAY;AAAA,MACZ,cAAc;AAAA,IAChB;AAAA,EACF,CAAC;AAED,SAAO;AACT;","names":[]}
|
package/dist/logger/index.js
CHANGED
|
@@ -1,88 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
const processValue = globalRecord["process"];
|
|
5
|
-
if (typeof processValue === "object" && processValue !== null) {
|
|
6
|
-
const envValue = processValue["env"];
|
|
7
|
-
if (typeof envValue === "object" && envValue !== null) {
|
|
8
|
-
const nodeEnv = envValue["NODE_ENV"];
|
|
9
|
-
if (nodeEnv === "development" || nodeEnv === "test") {
|
|
10
|
-
return true;
|
|
11
|
-
}
|
|
12
|
-
if (nodeEnv === "production") {
|
|
13
|
-
return false;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
try {
|
|
18
|
-
return Boolean(import.meta.env?.DEV);
|
|
19
|
-
} catch {
|
|
20
|
-
return false;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
// src/logger/format-dev-log.ts
|
|
25
|
-
var LEVEL_COLORS = {
|
|
26
|
-
INFO: "\x1B[32m",
|
|
27
|
-
WARN: "\x1B[33m",
|
|
28
|
-
ERROR: "\x1B[31m",
|
|
29
|
-
DEBUG: "\x1B[36m"
|
|
30
|
-
};
|
|
31
|
-
var RESET_COLOR = "\x1B[0m";
|
|
32
|
-
var DIM_COLOR = "\x1B[2m";
|
|
33
|
-
function formatDevLog(level, message, context, timestamp) {
|
|
34
|
-
const color = LEVEL_COLORS[level];
|
|
35
|
-
const resolvedTimestamp = timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
36
|
-
const baseLine = `${DIM_COLOR}${resolvedTimestamp}${RESET_COLOR} ${color}[${level}]${RESET_COLOR} ${message}`;
|
|
37
|
-
if (!context || Object.keys(context).length === 0) {
|
|
38
|
-
return baseLine;
|
|
39
|
-
}
|
|
40
|
-
return `${baseLine} ${DIM_COLOR}${JSON.stringify(context)}${RESET_COLOR}`;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
// src/logger/index.ts
|
|
44
|
-
var Logger = class {
|
|
45
|
-
write(level, message, context) {
|
|
46
|
-
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
47
|
-
const isDev = checkIsDevelopment();
|
|
48
|
-
if (isDev) {
|
|
49
|
-
const formatted = formatDevLog(level, message, context, timestamp);
|
|
50
|
-
this.emitToConsole(level, formatted);
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
const payload = JSON.stringify({
|
|
54
|
-
timestamp,
|
|
55
|
-
level,
|
|
56
|
-
message,
|
|
57
|
-
...context ? { context } : {}
|
|
58
|
-
});
|
|
59
|
-
this.emitToConsole(level, payload);
|
|
60
|
-
}
|
|
61
|
-
emitToConsole(level, line) {
|
|
62
|
-
if (level === "ERROR") {
|
|
63
|
-
console.error(line);
|
|
64
|
-
return;
|
|
65
|
-
}
|
|
66
|
-
if (level === "WARN") {
|
|
67
|
-
console.warn(line);
|
|
68
|
-
return;
|
|
69
|
-
}
|
|
70
|
-
console.log(line);
|
|
71
|
-
}
|
|
72
|
-
info(message, context) {
|
|
73
|
-
this.write("INFO", message, context);
|
|
74
|
-
}
|
|
75
|
-
warn(message, context) {
|
|
76
|
-
this.write("WARN", message, context);
|
|
77
|
-
}
|
|
78
|
-
error(message, context) {
|
|
79
|
-
this.write("ERROR", message, context);
|
|
80
|
-
}
|
|
81
|
-
debug(message, context) {
|
|
82
|
-
this.write("DEBUG", message, context);
|
|
83
|
-
}
|
|
84
|
-
};
|
|
85
|
-
var logger = new Logger();
|
|
1
|
+
import {
|
|
2
|
+
logger
|
|
3
|
+
} from "../chunk-H76QJ2LB.js";
|
|
86
4
|
export {
|
|
87
5
|
logger
|
|
88
6
|
};
|
package/dist/logger/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@3lineas/groovepack",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "Zero-dependency & modular infrastructure primitives for TypeScript, Cloudflare Workers (D1, Hono), React, and Astro.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -9,6 +9,10 @@
|
|
|
9
9
|
"README.md"
|
|
10
10
|
],
|
|
11
11
|
"exports": {
|
|
12
|
+
"./errors": {
|
|
13
|
+
"types": "./dist/errors/index.d.ts",
|
|
14
|
+
"import": "./dist/errors/index.js"
|
|
15
|
+
},
|
|
12
16
|
"./logger": {
|
|
13
17
|
"types": "./dist/logger/index.d.ts",
|
|
14
18
|
"import": "./dist/logger/index.js"
|