@3lineas/groovepack 1.1.0 → 1.3.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 +32 -23
- package/dist/api-action/index.d.ts +1 -4
- package/dist/api-action/index.js +2 -3
- package/dist/api-action/index.js.map +1 -1
- package/dist/api-client/index.d.ts +9 -3
- package/dist/api-client/index.js.map +1 -1
- package/dist/api-toast/index.d.ts +23 -12
- package/dist/api-toast/index.js +110 -8
- package/dist/api-toast/index.js.map +1 -1
- package/dist/{chunk-PDWE3D4J.js → chunk-OSPD6EX4.js} +20 -40
- package/dist/chunk-OSPD6EX4.js.map +1 -0
- package/dist/i18n/index.d.ts +10 -20
- package/dist/i18n/index.js +3 -5
- package/dist/logger/index.js +4 -7
- package/dist/logger/index.js.map +1 -1
- package/dist/vite/index.d.ts +34 -0
- package/dist/vite/index.js +78 -0
- package/dist/vite/index.js.map +1 -0
- package/package.json +11 -7
- package/dist/chunk-PDWE3D4J.js.map +0 -1
- package/dist/groovepack-locale.type-CaXo9vLj.d.ts +0 -3
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Zero-dependency & modular infrastructure primitives for **TypeScript**, **Cloudflare Workers (D1, Hono)**, **React**, and **Astro**.
|
|
4
4
|
|
|
5
|
-
`@3lineas/groovepack` provides standardized, production-tested building blocks for backend pipelines, atomic Cloudflare D1 transactions, structured logging, typed Hono RPC / REST clients, standardized `ActionResponse<T>` wrappers, and
|
|
5
|
+
`@3lineas/groovepack` provides standardized, production-tested building blocks for backend pipelines, atomic Cloudflare D1 transactions, structured logging, typed Hono RPC / REST clients, standardized `ActionResponse<T>` wrappers, and Shadcn v4 (`@base-ui/react/toast`) toast orchestration — exposed via **Subpath Exports** with `sideEffects: false` and **optional peer dependencies**.
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -24,7 +24,7 @@ Zero-dependency & modular infrastructure primitives for **TypeScript**, **Cloudf
|
|
|
24
24
|
|
|
25
25
|
## Why Subpath Exports?
|
|
26
26
|
|
|
27
|
-
- **Zero Dead Weight**: Backend workers importing `/logger` and `/pipeline` never bundle `
|
|
27
|
+
- **Zero Dead Weight**: Backend workers importing `/logger` and `/pipeline` never bundle `@base-ui/react` or frontend code. Frontend apps importing `/api-toast` never bundle server utilities.
|
|
28
28
|
- **No Barrel Files**: Every module has its own dedicated entry point for optimal tree-shaking.
|
|
29
29
|
- **Immutable Infrastructure**: Lives in `node_modules` with SemVer guarantees, preventing accidental local drift across monorepo apps.
|
|
30
30
|
|
|
@@ -47,7 +47,8 @@ Install only what your app actually uses:
|
|
|
47
47
|
| `/pipeline/with-d1-transaction` | *None (0 deps)* | Cloudflare Workers (D1 / Drizzle) |
|
|
48
48
|
| `/api-action` | *None (0 deps)* | React, Astro, Next.js, Node |
|
|
49
49
|
| `/api-client` | `hono >= 4.0.0` *(only if using `createHonoClient`)* | Frontend / Edge |
|
|
50
|
-
| `/api-toast` |
|
|
50
|
+
| `/api-toast` | `@base-ui/react >= 1.0.0` (Shadcn v4 `toast`) | React / Browser |
|
|
51
|
+
| `/vite` | *None (0 deps)* | Vite `vite.config.ts` |
|
|
51
52
|
|
|
52
53
|
---
|
|
53
54
|
|
|
@@ -58,7 +59,7 @@ Install only what your app actually uses:
|
|
|
58
59
|
3. `@3lineas/groovepack/pipeline/with-d1-transaction` — Standalone `withD1Transaction` wrapper.
|
|
59
60
|
4. `@3lineas/groovepack/api-client` — `createApiClient` (REST) & `createHonoClient` (Hono RPC).
|
|
60
61
|
5. `@3lineas/groovepack/api-action` — Polymorphic `apiAction` wrapper returning `ActionResponse<T>`.
|
|
61
|
-
6. `@3lineas/groovepack/api-toast` — `apiToast
|
|
62
|
+
6. `@3lineas/groovepack/api-toast` — `apiToast` and `createApiToast` for Shadcn v4 (`@base-ui/react/toast`).
|
|
62
63
|
|
|
63
64
|
---
|
|
64
65
|
|
|
@@ -250,30 +251,38 @@ export async function createProductAction(
|
|
|
250
251
|
|
|
251
252
|
## 6. `@3lineas/groovepack/api-toast`
|
|
252
253
|
|
|
253
|
-
Orchestrates async actions with **
|
|
254
|
+
Orchestrates async actions with **Shadcn Toast** loading, success, and error toasts, returning the resolved `ActionResponse<T>`. Automatically resolves `toastManager` from `/src/components/ui/toast` (or `GROOVEPACK_SHADCN_PATH` / `NEXT_PUBLIC_GROOVEPACK_SHADCN_PATH`), and reads the active language strictly from `GROOVEPACK_LOCALE` / `NEXT_PUBLIC_GROOVEPACK_LOCALE` (defaulting to `"en"`).
|
|
254
255
|
|
|
255
256
|
```typescript
|
|
256
|
-
import { apiToast
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
257
|
+
import { apiToast } from "@3lineas/groovepack/api-toast";
|
|
258
|
+
|
|
259
|
+
await apiToast({
|
|
260
|
+
action: () => loginAction(values),
|
|
261
|
+
onSuccess: () => {
|
|
262
|
+
router.push("/dashboard");
|
|
263
|
+
router.refresh();
|
|
264
|
+
},
|
|
264
265
|
});
|
|
266
|
+
```
|
|
265
267
|
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
268
|
+
### Vite Plugin (`@3lineas/groovepack/vite`)
|
|
269
|
+
|
|
270
|
+
For Vite apps, register `groovepack()` in `vite.config.ts` so `${shadcnPath}/toast` is statically resolved in both `vite dev` and `vite build`:
|
|
271
|
+
|
|
272
|
+
```typescript
|
|
273
|
+
import { defineConfig } from "vite";
|
|
274
|
+
import { groovepack } from "@3lineas/groovepack/vite";
|
|
275
|
+
|
|
276
|
+
export default defineConfig({
|
|
277
|
+
plugins: [groovepack()],
|
|
270
278
|
});
|
|
279
|
+
```
|
|
271
280
|
|
|
272
|
-
//
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
281
|
+
// Or passing the toast manager directly per call
|
|
282
|
+
await apiToast({
|
|
283
|
+
toast: toastManager,
|
|
284
|
+
action: () => deleteProductAction(id),
|
|
285
|
+
loadingMessage: "Eliminando...",
|
|
277
286
|
});
|
|
278
287
|
```
|
|
279
288
|
|
|
@@ -317,7 +326,7 @@ export const enToast = createApiToast({
|
|
|
317
326
|
1. Explicit message string passed to the call or factory (`defaultErrorMessage`, `loadingMessage`, `successMessage`, `errorMessage`).
|
|
318
327
|
2. Explicit `locale` option (`apiAction({ locale: "es", ... })`, `apiToast({ locale: "pt", ... })`, `createApiToast({ locale: "fr" })`).
|
|
319
328
|
3. Runtime locale configured via `setGroovepackLocale("es")` from `@3lineas/groovepack/i18n`.
|
|
320
|
-
4. Environment variable (`GROOVEPACK_LOCALE
|
|
329
|
+
4. Environment variable (`GROOVEPACK_LOCALE` or `NEXT_PUBLIC_GROOVEPACK_LOCALE` in Vinext).
|
|
321
330
|
5. Default fallback: `"en"`.
|
|
322
331
|
|
|
323
332
|
```ts
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { A as ActionResponse } from '../action-response.type-XlzII9Lr.js';
|
|
2
|
-
import { G as GroovepackLocale } from '../groovepack-locale.type-CaXo9vLj.js';
|
|
3
2
|
|
|
4
3
|
/**
|
|
5
4
|
* Minimal `Response`-like contract compatible with `fetch`, Hono `ClientResponse`,
|
|
@@ -27,8 +26,6 @@ type ErrorLogger = (message: string, context?: Record<string, unknown>) => void;
|
|
|
27
26
|
interface ApiActionOptions<T = unknown> {
|
|
28
27
|
/** Async call returning either a `Response`/`ClientResponse` or an `ActionResponse<T>`. */
|
|
29
28
|
apiCall: () => Promise<ApiCallResult<T>>;
|
|
30
|
-
/** Optional locale override (`"en" | "es" | "pt" | "it" | "fr"`). */
|
|
31
|
-
locale?: GroovepackLocale;
|
|
32
29
|
/** Default fallback error message when the server does not provide one. */
|
|
33
30
|
defaultErrorMessage?: string;
|
|
34
31
|
/** Optional logger for unexpected exceptions or malformed payloads. */
|
|
@@ -39,6 +36,6 @@ interface ApiActionOptions<T = unknown> {
|
|
|
39
36
|
* Universal wrapper for API calls (Hono RPC, `fetch`, or Server Actions)
|
|
40
37
|
* guaranteeing a standardized `ActionResponse<T>` without throwing uncaught errors.
|
|
41
38
|
*/
|
|
42
|
-
declare function apiAction<T = unknown>({ apiCall,
|
|
39
|
+
declare function apiAction<T = unknown>({ apiCall, defaultErrorMessage, onError, }: ApiActionOptions<T>): Promise<ActionResponse<T>>;
|
|
43
40
|
|
|
44
41
|
export { ActionResponse, type ApiActionOptions, type ApiCallResult, type ErrorLogger, type MinimalResponse, apiAction };
|
package/dist/api-action/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
resolveLocaleMessages
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-OSPD6EX4.js";
|
|
4
4
|
|
|
5
5
|
// src/api-action/default-error-logger.ts
|
|
6
6
|
var defaultErrorLogger = (message, context) => {
|
|
@@ -66,11 +66,10 @@ async function handleHttpResponse(response, fallbackErrorMessage, serverRequestF
|
|
|
66
66
|
// src/api-action/index.ts
|
|
67
67
|
async function apiAction({
|
|
68
68
|
apiCall,
|
|
69
|
-
locale,
|
|
70
69
|
defaultErrorMessage,
|
|
71
70
|
onError = defaultErrorLogger
|
|
72
71
|
}) {
|
|
73
|
-
const messages = resolveLocaleMessages(
|
|
72
|
+
const messages = resolveLocaleMessages();
|
|
74
73
|
const resolvedDefaultError = defaultErrorMessage ?? messages.unexpectedError;
|
|
75
74
|
try {
|
|
76
75
|
const actionResult = await apiCall();
|
|
@@ -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
|
|
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,6 +1,12 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
1
2
|
import * as hono_utils_types from 'hono/utils/types';
|
|
2
3
|
import * as node_modules_hono_dist_types_client_types from 'node_modules/hono/dist/types/client/types';
|
|
3
|
-
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Constraint matching any `Hono<E, S, BasePath>` instance (including
|
|
7
|
+
* routers with custom `Bindings` and `Variables`).
|
|
8
|
+
*/
|
|
9
|
+
type AnyHonoApp = Hono<any, any, any>;
|
|
4
10
|
|
|
5
11
|
/**
|
|
6
12
|
* Configuration options for `createApiClient`.
|
|
@@ -41,6 +47,6 @@ declare function createApiClient(config?: ApiClientConfig): RestApiClient;
|
|
|
41
47
|
* Creates a typed Hono RPC client (`hc<TApp>()`) with automatic Bearer token injection.
|
|
42
48
|
* Requires `hono` to be installed in the consumer project.
|
|
43
49
|
*/
|
|
44
|
-
declare function createHonoClient<TApp extends
|
|
50
|
+
declare function createHonoClient<TApp extends AnyHonoApp>(config?: ApiClientConfig): hono_utils_types.UnionToIntersection<node_modules_hono_dist_types_client_types.Client<TApp, string>>;
|
|
45
51
|
|
|
46
|
-
export { type ApiClientConfig, type RestApiClient, createApiClient, createHonoClient };
|
|
52
|
+
export { type AnyHonoApp, type ApiClientConfig, type RestApiClient, createApiClient, createHonoClient };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/api-client/get-stored-token.ts","../../src/api-client/resolve-headers.ts","../../src/api-client/resolve-url.ts","../../src/api-client/serialize-body.ts","../../src/api-client/set-stored-token.ts","../../src/api-client/remove-stored-token.ts","../../src/api-client/create-api-client.ts","../../src/api-client/create-hono-client.ts"],"sourcesContent":["/**\n * Safely reads a stored token from `globalThis.localStorage` when running in a browser.\n */\nexport function getStoredToken(storageKey: string): string | null {\n try {\n if (\n typeof globalThis !== \"undefined\" &&\n \"localStorage\" in globalThis &&\n globalThis.localStorage\n ) {\n return globalThis.localStorage.getItem(storageKey);\n }\n } catch {\n return null;\n }\n return null;\n}\n","import { getStoredToken } from \"@/api-client/get-stored-token\";\n\n/**\n * Resolves request headers by merging `defaultHeaders`, per-request headers,\n * `Content-Type: application/json` (when not FormData), and `Authorization: Bearer`.\n */\nexport async function resolveHeaders(\n defaultHeaders: Record<string, string> | undefined,\n tokenStorageKey: string,\n getToken: (() => string | null | Promise<string | null>) | undefined,\n extraHeaders?: HeadersInit,\n isFormData = false,\n): Promise<Headers> {\n const headers = new Headers(defaultHeaders);\n\n if (!isFormData && !headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n\n if (extraHeaders) {\n new Headers(extraHeaders).forEach((headerValue, headerKey) => {\n headers.set(headerKey, headerValue);\n });\n }\n\n const token = getToken ? await getToken() : getStoredToken(tokenStorageKey);\n if (token && !headers.has(\"Authorization\")) {\n headers.set(\"Authorization\", `Bearer ${token}`);\n }\n\n return headers;\n}\n","/**\n * Resolves a relative or absolute path against `baseUrl`.\n */\nexport function resolveUrl(baseUrl: string, path: string): string {\n if (path.startsWith(\"http://\") || path.startsWith(\"https://\")) {\n return path;\n }\n const normalizedBase = baseUrl.replace(/\\/+$/, \"\");\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n return `${normalizedBase}${normalizedPath}`;\n}\n","/**\n * Serializes a request body to `BodyInit | undefined`, supporting `FormData`,\n * `URLSearchParams`, `Blob`, `string`, and JSON with `BigInt` safety.\n */\nexport function serializeBody(body: unknown): BodyInit | undefined {\n if (body === undefined) {\n return undefined;\n }\n\n if (\n typeof body === \"string\" ||\n body instanceof FormData ||\n body instanceof URLSearchParams ||\n body instanceof Blob\n ) {\n return body;\n }\n\n return JSON.stringify(body, (_key, fieldValue) =>\n typeof fieldValue === \"bigint\" ? fieldValue.toString() : fieldValue,\n );\n}\n","/**\n * Safely persists a token to `globalThis.localStorage` when running in a browser.\n */\nexport function setStoredToken(storageKey: string, token: string): void {\n try {\n if (\n typeof globalThis !== \"undefined\" &&\n \"localStorage\" in globalThis &&\n globalThis.localStorage\n ) {\n globalThis.localStorage.setItem(storageKey, token);\n }\n } catch {\n // Ignore storage errors in restricted environments\n }\n}\n","/**\n * Safely removes a stored token from `globalThis.localStorage` when running in a browser.\n */\nexport function removeStoredToken(storageKey: string): void {\n try {\n if (\n typeof globalThis !== \"undefined\" &&\n \"localStorage\" in globalThis &&\n globalThis.localStorage\n ) {\n globalThis.localStorage.removeItem(storageKey);\n }\n } catch {\n // Ignore storage errors in restricted environments\n }\n}\n","import type { ApiClientConfig } from \"@/types/api-client/api-client-config.type\";\nimport type { RestApiClient } from \"@/types/api-client/rest-api-client.type\";\nimport { resolveHeaders } from \"@/api-client/resolve-headers\";\nimport { resolveUrl } from \"@/api-client/resolve-url\";\nimport { serializeBody } from \"@/api-client/serialize-body\";\nimport { setStoredToken } from \"@/api-client/set-stored-token\";\nimport { removeStoredToken } from \"@/api-client/remove-stored-token\";\n\n/**\n * Creates a standardized REST API client with automatic Bearer token injection,\n * `BigInt`-safe JSON serialization, and `FormData` support.\n */\nexport function createApiClient(config: ApiClientConfig = {}): RestApiClient {\n const {\n baseUrl = \"\",\n tokenStorageKey = \"token\",\n getToken,\n defaultHeaders,\n fetcher = fetch,\n } = config;\n\n async function request(\n method: string,\n path: string,\n body?: unknown,\n init?: RequestInit,\n ): Promise<Response> {\n const isFormData =\n typeof FormData !== \"undefined\" && body instanceof FormData;\n const headers = await resolveHeaders(\n defaultHeaders,\n tokenStorageKey,\n getToken,\n init?.headers,\n isFormData,\n );\n\n return fetcher(resolveUrl(baseUrl, path), {\n ...init,\n method,\n headers,\n body: serializeBody(body),\n });\n }\n\n return {\n get: (path, init) => request(\"GET\", path, undefined, init),\n post: (path, body, init) => request(\"POST\", path, body, init),\n put: (path, body, init) => request(\"PUT\", path, body, init),\n patch: (path, body, init) => request(\"PATCH\", path, body, init),\n delete: (path, init) => request(\"DELETE\", path, undefined, init),\n setToken: (token) => setStoredToken(tokenStorageKey, token),\n removeToken: () => removeStoredToken(tokenStorageKey),\n };\n}\n","import
|
|
1
|
+
{"version":3,"sources":["../../src/api-client/get-stored-token.ts","../../src/api-client/resolve-headers.ts","../../src/api-client/resolve-url.ts","../../src/api-client/serialize-body.ts","../../src/api-client/set-stored-token.ts","../../src/api-client/remove-stored-token.ts","../../src/api-client/create-api-client.ts","../../src/api-client/create-hono-client.ts"],"sourcesContent":["/**\n * Safely reads a stored token from `globalThis.localStorage` when running in a browser.\n */\nexport function getStoredToken(storageKey: string): string | null {\n try {\n if (\n typeof globalThis !== \"undefined\" &&\n \"localStorage\" in globalThis &&\n globalThis.localStorage\n ) {\n return globalThis.localStorage.getItem(storageKey);\n }\n } catch {\n return null;\n }\n return null;\n}\n","import { getStoredToken } from \"@/api-client/get-stored-token\";\n\n/**\n * Resolves request headers by merging `defaultHeaders`, per-request headers,\n * `Content-Type: application/json` (when not FormData), and `Authorization: Bearer`.\n */\nexport async function resolveHeaders(\n defaultHeaders: Record<string, string> | undefined,\n tokenStorageKey: string,\n getToken: (() => string | null | Promise<string | null>) | undefined,\n extraHeaders?: HeadersInit,\n isFormData = false,\n): Promise<Headers> {\n const headers = new Headers(defaultHeaders);\n\n if (!isFormData && !headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n\n if (extraHeaders) {\n new Headers(extraHeaders).forEach((headerValue, headerKey) => {\n headers.set(headerKey, headerValue);\n });\n }\n\n const token = getToken ? await getToken() : getStoredToken(tokenStorageKey);\n if (token && !headers.has(\"Authorization\")) {\n headers.set(\"Authorization\", `Bearer ${token}`);\n }\n\n return headers;\n}\n","/**\n * Resolves a relative or absolute path against `baseUrl`.\n */\nexport function resolveUrl(baseUrl: string, path: string): string {\n if (path.startsWith(\"http://\") || path.startsWith(\"https://\")) {\n return path;\n }\n const normalizedBase = baseUrl.replace(/\\/+$/, \"\");\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n return `${normalizedBase}${normalizedPath}`;\n}\n","/**\n * Serializes a request body to `BodyInit | undefined`, supporting `FormData`,\n * `URLSearchParams`, `Blob`, `string`, and JSON with `BigInt` safety.\n */\nexport function serializeBody(body: unknown): BodyInit | undefined {\n if (body === undefined) {\n return undefined;\n }\n\n if (\n typeof body === \"string\" ||\n body instanceof FormData ||\n body instanceof URLSearchParams ||\n body instanceof Blob\n ) {\n return body;\n }\n\n return JSON.stringify(body, (_key, fieldValue) =>\n typeof fieldValue === \"bigint\" ? fieldValue.toString() : fieldValue,\n );\n}\n","/**\n * Safely persists a token to `globalThis.localStorage` when running in a browser.\n */\nexport function setStoredToken(storageKey: string, token: string): void {\n try {\n if (\n typeof globalThis !== \"undefined\" &&\n \"localStorage\" in globalThis &&\n globalThis.localStorage\n ) {\n globalThis.localStorage.setItem(storageKey, token);\n }\n } catch {\n // Ignore storage errors in restricted environments\n }\n}\n","/**\n * Safely removes a stored token from `globalThis.localStorage` when running in a browser.\n */\nexport function removeStoredToken(storageKey: string): void {\n try {\n if (\n typeof globalThis !== \"undefined\" &&\n \"localStorage\" in globalThis &&\n globalThis.localStorage\n ) {\n globalThis.localStorage.removeItem(storageKey);\n }\n } catch {\n // Ignore storage errors in restricted environments\n }\n}\n","import type { ApiClientConfig } from \"@/types/api-client/api-client-config.type\";\nimport type { RestApiClient } from \"@/types/api-client/rest-api-client.type\";\nimport { resolveHeaders } from \"@/api-client/resolve-headers\";\nimport { resolveUrl } from \"@/api-client/resolve-url\";\nimport { serializeBody } from \"@/api-client/serialize-body\";\nimport { setStoredToken } from \"@/api-client/set-stored-token\";\nimport { removeStoredToken } from \"@/api-client/remove-stored-token\";\n\n/**\n * Creates a standardized REST API client with automatic Bearer token injection,\n * `BigInt`-safe JSON serialization, and `FormData` support.\n */\nexport function createApiClient(config: ApiClientConfig = {}): RestApiClient {\n const {\n baseUrl = \"\",\n tokenStorageKey = \"token\",\n getToken,\n defaultHeaders,\n fetcher = fetch,\n } = config;\n\n async function request(\n method: string,\n path: string,\n body?: unknown,\n init?: RequestInit,\n ): Promise<Response> {\n const isFormData =\n typeof FormData !== \"undefined\" && body instanceof FormData;\n const headers = await resolveHeaders(\n defaultHeaders,\n tokenStorageKey,\n getToken,\n init?.headers,\n isFormData,\n );\n\n return fetcher(resolveUrl(baseUrl, path), {\n ...init,\n method,\n headers,\n body: serializeBody(body),\n });\n }\n\n return {\n get: (path, init) => request(\"GET\", path, undefined, init),\n post: (path, body, init) => request(\"POST\", path, body, init),\n put: (path, body, init) => request(\"PUT\", path, body, init),\n patch: (path, body, init) => request(\"PATCH\", path, body, init),\n delete: (path, init) => request(\"DELETE\", path, undefined, init),\n setToken: (token) => setStoredToken(tokenStorageKey, token),\n removeToken: () => removeStoredToken(tokenStorageKey),\n };\n}\n","import { hc } from \"hono/client\";\nimport type { AnyHonoApp } from \"@/types/api-client/any-hono-app.type\";\nimport type { ApiClientConfig } from \"@/types/api-client/api-client-config.type\";\nimport { resolveHeaders } from \"@/api-client/resolve-headers\";\n\n/**\n * Creates a typed Hono RPC client (`hc<TApp>()`) with automatic Bearer token injection.\n * Requires `hono` to be installed in the consumer project.\n */\nexport function createHonoClient<TApp extends AnyHonoApp>(\n config: ApiClientConfig = {},\n) {\n const {\n baseUrl = \"\",\n tokenStorageKey = \"token\",\n getToken,\n defaultHeaders,\n fetcher = fetch,\n } = config;\n\n return hc<TApp>(baseUrl, {\n fetch: async (input: RequestInfo | URL, init?: RequestInit) => {\n const isFormData =\n typeof FormData !== \"undefined\" && init?.body instanceof FormData;\n const headers = await resolveHeaders(\n defaultHeaders,\n tokenStorageKey,\n getToken,\n init?.headers,\n isFormData,\n );\n\n return fetcher(input, {\n ...init,\n headers,\n });\n },\n });\n}\n"],"mappings":";AAGO,SAAS,eAAe,YAAmC;AAChE,MAAI;AACF,QACE,OAAO,eAAe,eACtB,kBAAkB,cAClB,WAAW,cACX;AACA,aAAO,WAAW,aAAa,QAAQ,UAAU;AAAA,IACnD;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;ACVA,eAAsB,eACpB,gBACA,iBACA,UACA,cACA,aAAa,OACK;AAClB,QAAM,UAAU,IAAI,QAAQ,cAAc;AAE1C,MAAI,CAAC,cAAc,CAAC,QAAQ,IAAI,cAAc,GAAG;AAC/C,YAAQ,IAAI,gBAAgB,kBAAkB;AAAA,EAChD;AAEA,MAAI,cAAc;AAChB,QAAI,QAAQ,YAAY,EAAE,QAAQ,CAAC,aAAa,cAAc;AAC5D,cAAQ,IAAI,WAAW,WAAW;AAAA,IACpC,CAAC;AAAA,EACH;AAEA,QAAM,QAAQ,WAAW,MAAM,SAAS,IAAI,eAAe,eAAe;AAC1E,MAAI,SAAS,CAAC,QAAQ,IAAI,eAAe,GAAG;AAC1C,YAAQ,IAAI,iBAAiB,U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.type-XlzII9Lr.js';
|
|
2
|
-
import { G as GroovepackLocale } from '../groovepack-locale.type-CaXo9vLj.js';
|
|
3
2
|
|
|
4
3
|
/**
|
|
5
4
|
* Options for `apiToast`.
|
|
@@ -7,8 +6,6 @@ import { G as GroovepackLocale } from '../groovepack-locale.type-CaXo9vLj.js';
|
|
|
7
6
|
interface ApiToastOptions<T = unknown> {
|
|
8
7
|
/** Async action returning an `ActionResponse<T>`. */
|
|
9
8
|
action: () => Promise<ActionResponse<T>>;
|
|
10
|
-
/** Optional locale override (`"en" | "es" | "pt" | "it" | "fr"`). */
|
|
11
|
-
locale?: GroovepackLocale;
|
|
12
9
|
/** Message displayed while the action is pending. */
|
|
13
10
|
loadingMessage?: string;
|
|
14
11
|
/** Fallback message displayed when `action` succeeds without a `message` field. */
|
|
@@ -25,8 +22,6 @@ interface ApiToastOptions<T = unknown> {
|
|
|
25
22
|
* Default configuration for `createApiToast`.
|
|
26
23
|
*/
|
|
27
24
|
interface ApiToastDefaults {
|
|
28
|
-
/** Optional locale override (`"en" | "es" | "pt" | "it" | "fr"`). */
|
|
29
|
-
locale?: GroovepackLocale;
|
|
30
25
|
/** Default loading message when not specified per call. */
|
|
31
26
|
defaultLoadingMessage?: string;
|
|
32
27
|
/** Default success message when not specified per call. */
|
|
@@ -36,7 +31,6 @@ interface ApiToastDefaults {
|
|
|
36
31
|
}
|
|
37
32
|
type ToastedOptions<T = unknown> = {
|
|
38
33
|
action: () => Promise<ActionResponse<T>>;
|
|
39
|
-
locale?: GroovepackLocale;
|
|
40
34
|
loadingMessage?: string;
|
|
41
35
|
successMessage?: string;
|
|
42
36
|
errorMessage?: string;
|
|
@@ -45,14 +39,31 @@ type ToastedOptions<T = unknown> = {
|
|
|
45
39
|
};
|
|
46
40
|
|
|
47
41
|
/**
|
|
48
|
-
*
|
|
49
|
-
* messages and/or locale.
|
|
42
|
+
* Toast payload accepted by `@base-ui/react/toast` (`Toast.createToastManager()`).
|
|
50
43
|
*/
|
|
51
|
-
|
|
44
|
+
interface BaseUiToastPayload {
|
|
45
|
+
title?: string;
|
|
46
|
+
description?: string;
|
|
47
|
+
type?: "loading" | "success" | "error" | "info" | "warning" | (string & {});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Contract for `@base-ui/react/toast` manager (`Toast.createToastManager()`).
|
|
52
|
+
*/
|
|
53
|
+
interface BaseUiToastManager {
|
|
54
|
+
add: (options: BaseUiToastPayload) => string;
|
|
55
|
+
update: (id: string, updates: BaseUiToastPayload) => void;
|
|
56
|
+
close: (id: string) => void;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Factory creating a pre-configured `apiToast` helper backed by Shadcn Toast.
|
|
61
|
+
*/
|
|
62
|
+
declare function createApiToast(defaults?: ApiToastDefaults): <T = unknown>({ action, loadingMessage, successMessage, errorMessage, onSuccess, onError, }: ApiToastOptions<T>) => Promise<ActionResponse<T>>;
|
|
52
63
|
|
|
53
64
|
/**
|
|
54
|
-
* Wraps an `ActionResponse<T>` promise with `
|
|
65
|
+
* Wraps an `ActionResponse<T>` promise with Shadcn v4 (`@base-ui/react/toast`) loading, success, and error states.
|
|
55
66
|
*/
|
|
56
|
-
declare const apiToast: <T = unknown>({ action,
|
|
67
|
+
declare const apiToast: <T = unknown>({ action, loadingMessage, successMessage, errorMessage, onSuccess, onError, }: ApiToastOptions<T>) => Promise<ActionResponse<T>>;
|
|
57
68
|
|
|
58
|
-
export { ActionResponse, type ApiToastDefaults, type ApiToastOptions, type ToastedOptions, apiToast, createApiToast };
|
|
69
|
+
export { ActionResponse, type ApiToastDefaults, type ApiToastOptions, type BaseUiToastManager, type BaseUiToastPayload, type ToastedOptions, apiToast, createApiToast };
|
package/dist/api-toast/index.js
CHANGED
|
@@ -1,39 +1,141 @@
|
|
|
1
1
|
import {
|
|
2
2
|
resolveLocaleMessages
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-OSPD6EX4.js";
|
|
4
|
+
|
|
5
|
+
// src/api-toast/read-shadcn-ui-path.ts
|
|
6
|
+
var DEFAULT_SHADCN_UI_PATH = "/src/components/ui";
|
|
7
|
+
var ENV_SHADCN_PATH_KEYS = [
|
|
8
|
+
"GROOVEPACK_SHADCN_PATH",
|
|
9
|
+
"NEXT_PUBLIC_GROOVEPACK_SHADCN_PATH"
|
|
10
|
+
];
|
|
11
|
+
function normalizePath(candidate) {
|
|
12
|
+
if (typeof candidate !== "string") {
|
|
13
|
+
return void 0;
|
|
14
|
+
}
|
|
15
|
+
const trimmed = candidate.trim().replace(/\/+$/, "");
|
|
16
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
17
|
+
}
|
|
18
|
+
function readShadcnPathFromProcessEnv() {
|
|
19
|
+
const globalRecord = globalThis;
|
|
20
|
+
const processValue = globalRecord["process"];
|
|
21
|
+
if (typeof processValue !== "object" || processValue === null) {
|
|
22
|
+
return void 0;
|
|
23
|
+
}
|
|
24
|
+
const envValue = processValue["env"];
|
|
25
|
+
if (typeof envValue !== "object" || envValue === null) {
|
|
26
|
+
return void 0;
|
|
27
|
+
}
|
|
28
|
+
const record = envValue;
|
|
29
|
+
for (const key of ENV_SHADCN_PATH_KEYS) {
|
|
30
|
+
const normalized = normalizePath(record[key]);
|
|
31
|
+
if (normalized) {
|
|
32
|
+
return normalized;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return void 0;
|
|
36
|
+
}
|
|
37
|
+
function readShadcnPathFromImportMeta() {
|
|
38
|
+
try {
|
|
39
|
+
return normalizePath(import.meta.env?.GROOVEPACK_SHADCN_PATH) ?? normalizePath(import.meta.env?.NEXT_PUBLIC_GROOVEPACK_SHADCN_PATH);
|
|
40
|
+
} catch {
|
|
41
|
+
return void 0;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function readShadcnUiPath() {
|
|
45
|
+
return readShadcnPathFromProcessEnv() ?? readShadcnPathFromImportMeta() ?? DEFAULT_SHADCN_UI_PATH;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// src/api-toast/resolve-toast-manager.ts
|
|
49
|
+
var toastManagerCache = /* @__PURE__ */ new Map();
|
|
50
|
+
function buildMissingShadcnToastMessage(toastModulePath) {
|
|
51
|
+
return `[@3lineas/groovepack/api-toast] Could not load a valid Shadcn toastManager from "${toastModulePath}". Run "pnpm dlx shadcn@latest add toast" or set GROOVEPACK_SHADCN_PATH / NEXT_PUBLIC_GROOVEPACK_SHADCN_PATH to your Shadcn UI directory.`;
|
|
52
|
+
}
|
|
53
|
+
function isValidToastManager(candidate) {
|
|
54
|
+
if (typeof candidate !== "object" || candidate === null) {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
const record = candidate;
|
|
58
|
+
return typeof record["add"] === "function" && typeof record["update"] === "function";
|
|
59
|
+
}
|
|
60
|
+
function extractToastManager(loadedModule) {
|
|
61
|
+
if (typeof loadedModule !== "object" || loadedModule === null) {
|
|
62
|
+
return void 0;
|
|
63
|
+
}
|
|
64
|
+
const record = loadedModule;
|
|
65
|
+
const candidate = record["toastManager"] ?? record["toast"] ?? record["default"];
|
|
66
|
+
return isValidToastManager(candidate) ? candidate : void 0;
|
|
67
|
+
}
|
|
68
|
+
async function resolveToastManager() {
|
|
69
|
+
const toastModulePath = `${readShadcnUiPath()}/toast`;
|
|
70
|
+
const cached = toastManagerCache.get(toastModulePath);
|
|
71
|
+
if (cached) {
|
|
72
|
+
return cached;
|
|
73
|
+
}
|
|
74
|
+
const missingMessage = buildMissingShadcnToastMessage(toastModulePath);
|
|
75
|
+
try {
|
|
76
|
+
const loadedModule = await import(
|
|
77
|
+
/* @vite-ignore */
|
|
78
|
+
toastModulePath
|
|
79
|
+
);
|
|
80
|
+
const manager = extractToastManager(loadedModule);
|
|
81
|
+
if (!manager) {
|
|
82
|
+
console.error(missingMessage);
|
|
83
|
+
throw new Error(missingMessage);
|
|
84
|
+
}
|
|
85
|
+
toastManagerCache.set(toastModulePath, manager);
|
|
86
|
+
return manager;
|
|
87
|
+
} catch (caughtError) {
|
|
88
|
+
if (caughtError instanceof Error && caughtError.message === missingMessage) {
|
|
89
|
+
throw caughtError;
|
|
90
|
+
}
|
|
91
|
+
console.error(missingMessage);
|
|
92
|
+
throw new Error(missingMessage);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
4
95
|
|
|
5
96
|
// src/api-toast/create-api-toast.ts
|
|
6
|
-
import { toast } from "sonner";
|
|
7
97
|
function createApiToast(defaults = {}) {
|
|
8
98
|
return async function configuredApiToast({
|
|
9
99
|
action,
|
|
10
|
-
locale = defaults.locale,
|
|
11
100
|
loadingMessage,
|
|
12
101
|
successMessage,
|
|
13
102
|
errorMessage,
|
|
14
103
|
onSuccess,
|
|
15
104
|
onError
|
|
16
105
|
}) {
|
|
17
|
-
const
|
|
106
|
+
const toastManager = await resolveToastManager();
|
|
107
|
+
const messages = resolveLocaleMessages();
|
|
18
108
|
const resolvedLoading = loadingMessage ?? defaults.defaultLoadingMessage ?? messages.loading;
|
|
19
109
|
const resolvedSuccess = successMessage ?? defaults.defaultSuccessMessage ?? messages.success;
|
|
20
110
|
const resolvedError = errorMessage ?? defaults.defaultErrorMessage ?? messages.operationFailed;
|
|
21
|
-
const toastId =
|
|
111
|
+
const toastId = toastManager.add({
|
|
112
|
+
title: resolvedLoading,
|
|
113
|
+
type: "loading"
|
|
114
|
+
});
|
|
22
115
|
try {
|
|
23
116
|
const actionResult = await action();
|
|
24
117
|
if (actionResult.success) {
|
|
25
118
|
const displayMessage = actionResult.message ?? resolvedSuccess;
|
|
26
|
-
|
|
119
|
+
toastManager.update(toastId, {
|
|
120
|
+
title: displayMessage,
|
|
121
|
+
type: "success"
|
|
122
|
+
});
|
|
27
123
|
onSuccess?.(actionResult.data, actionResult);
|
|
28
124
|
return actionResult;
|
|
29
125
|
}
|
|
30
126
|
const displayError = actionResult.error ?? actionResult.message ?? resolvedError;
|
|
31
|
-
|
|
127
|
+
toastManager.update(toastId, {
|
|
128
|
+
title: displayError,
|
|
129
|
+
type: "error"
|
|
130
|
+
});
|
|
32
131
|
onError?.(displayError, actionResult);
|
|
33
132
|
return actionResult;
|
|
34
133
|
} catch (caughtError) {
|
|
35
134
|
const fallbackError = caughtError instanceof Error ? caughtError.message : resolvedError;
|
|
36
|
-
|
|
135
|
+
toastManager.update(toastId, {
|
|
136
|
+
title: fallbackError,
|
|
137
|
+
type: "error"
|
|
138
|
+
});
|
|
37
139
|
onError?.(fallbackError);
|
|
38
140
|
return {
|
|
39
141
|
success: false,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/api-toast/create-api-toast.ts","../../src/api-toast/index.ts"],"sourcesContent":["import { toast } from \"sonner\";\nimport type { ActionResponse } from \"@/types/common/action-response.type\";\nimport type { ApiToastDefaults } from \"@/types/api-toast/api-toast-defaults.type\";\nimport type { ApiToastOptions } from \"@/types/api-toast/api-toast-options.type\";\nimport { resolveLocaleMessages } from \"@/i18n/resolve-locale-messages\";\n\n/**\n * Factory creating a pre-configured `apiToast` helper with custom default\n * messages and/or locale.\n */\nexport function createApiToast(defaults: ApiToastDefaults = {}) {\n return async function configuredApiToast<T = unknown>({\n action,\n locale = defaults.locale,\n loadingMessage,\n successMessage,\n errorMessage,\n onSuccess,\n onError,\n }: ApiToastOptions<T>): Promise<ActionResponse<T>> {\n const messages = resolveLocaleMessages(locale);\n const resolvedLoading =\n loadingMessage ?? defaults.defaultLoadingMessage ?? messages.loading;\n const resolvedSuccess =\n successMessage ?? defaults.defaultSuccessMessage ?? messages.success;\n const resolvedError =\n errorMessage ?? defaults.defaultErrorMessage ?? messages.operationFailed;\n\n const toastId = toast.loading(resolvedLoading);\n\n try {\n const actionResult = await action();\n\n if (actionResult.success) {\n const displayMessage = actionResult.message ?? resolvedSuccess;\n toast.success(displayMessage, { id: toastId });\n onSuccess?.(actionResult.data, actionResult);\n return actionResult;\n }\n\n const displayError =\n actionResult.error ?? actionResult.message ?? resolvedError;\n toast.error(displayError, { id: toastId });\n onError?.(displayError, actionResult);\n return actionResult;\n } catch (caughtError) {\n const fallbackError =\n caughtError instanceof Error ? caughtError.message : resolvedError;\n toast.error(fallbackError, { id: toastId });\n onError?.(fallbackError);\n\n return {\n success: false,\n error: fallbackError,\n };\n }\n };\n}\n","import { createApiToast } from \"@/api-toast/create-api-toast\";\n\nexport type { ActionResponse } from \"@/types/common/action-response.type\";\nexport type { ApiToastOptions } from \"@/types/api-toast/api-toast-options.type\";\nexport type {\n ApiToastDefaults,\n ToastedOptions,\n} from \"@/types/api-toast/api-toast-defaults.type\";\nexport { createApiToast } from \"@/api-toast/create-api-toast\";\n\n/**\n * Wraps an `ActionResponse<T>` promise with `sonner` loading, success, and error toasts.\n */\nexport const apiToast = createApiToast();\n"],"mappings":";;;;;AAAA,SAAS,aAAa;AAUf,SAAS,eAAe,WAA6B,CAAC,GAAG;AAC9D,SAAO,eAAe,mBAAgC;AAAA,IACpD;AAAA,IACA,SAAS,SAAS;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAAmD;AACjD,UAAM,WAAW,sBAAsB,MAAM;AAC7C,UAAM,kBACJ,kBAAkB,SAAS,yBAAyB,SAAS;AAC/D,UAAM,kBACJ,kBAAkB,SAAS,yBAAyB,SAAS;AAC/D,UAAM,gBACJ,gBAAgB,SAAS,uBAAuB,SAAS;AAE3D,UAAM,UAAU,MAAM,QAAQ,eAAe;AAE7C,QAAI;AACF,YAAM,eAAe,MAAM,OAAO;AAElC,UAAI,aAAa,SAAS;AACxB,cAAM,iBAAiB,aAAa,WAAW;AAC/C,cAAM,QAAQ,gBAAgB,EAAE,IAAI,QAAQ,CAAC;AAC7C,oBAAY,aAAa,MAAM,YAAY;AAC3C,eAAO;AAAA,MACT;AAEA,YAAM,eACJ,aAAa,SAAS,aAAa,WAAW;AAChD,YAAM,MAAM,cAAc,EAAE,IAAI,QAAQ,CAAC;AACzC,gBAAU,cAAc,YAAY;AACpC,aAAO;AAAA,IACT,SAAS,aAAa;AACpB,YAAM,gBACJ,uBAAuB,QAAQ,YAAY,UAAU;AACvD,YAAM,MAAM,eAAe,EAAE,IAAI,QAAQ,CAAC;AAC1C,gBAAU,aAAa;AAEvB,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;;;AC5CO,IAAM,WAAW,eAAe;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/api-toast/read-shadcn-ui-path.ts","../../src/api-toast/resolve-toast-manager.ts","../../src/api-toast/create-api-toast.ts","../../src/api-toast/index.ts"],"sourcesContent":["const DEFAULT_SHADCN_UI_PATH = \"/src/components/ui\";\n\nconst ENV_SHADCN_PATH_KEYS = [\n \"GROOVEPACK_SHADCN_PATH\",\n \"NEXT_PUBLIC_GROOVEPACK_SHADCN_PATH\",\n] as const;\n\nfunction normalizePath(candidate: unknown): string | undefined {\n if (typeof candidate !== \"string\") {\n return undefined;\n }\n\n const trimmed = candidate.trim().replace(/\\/+$/, \"\");\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction readShadcnPathFromProcessEnv(): string | undefined {\n const globalRecord = globalThis as Record<string, unknown>;\n const processValue = globalRecord[\"process\"];\n if (typeof processValue !== \"object\" || processValue === null) {\n return undefined;\n }\n\n const envValue = (processValue as Record<string, unknown>)[\"env\"];\n if (typeof envValue !== \"object\" || envValue === null) {\n return undefined;\n }\n\n const record = envValue as Record<string, unknown>;\n for (const key of ENV_SHADCN_PATH_KEYS) {\n const normalized = normalizePath(record[key]);\n if (normalized) {\n return normalized;\n }\n }\n\n return undefined;\n}\n\nfunction readShadcnPathFromImportMeta(): string | undefined {\n try {\n return (\n normalizePath(import.meta.env?.GROOVEPACK_SHADCN_PATH) ??\n normalizePath(import.meta.env?.NEXT_PUBLIC_GROOVEPACK_SHADCN_PATH)\n );\n } catch {\n return undefined;\n }\n}\n\n/**\n * Resolves the Shadcn UI base directory from `GROOVEPACK_SHADCN_PATH` or\n * `NEXT_PUBLIC_GROOVEPACK_SHADCN_PATH`, defaulting to `\"/src/components/ui\"`.\n */\nexport function readShadcnUiPath(): string {\n return (\n readShadcnPathFromProcessEnv() ??\n readShadcnPathFromImportMeta() ??\n DEFAULT_SHADCN_UI_PATH\n );\n}\n","import type { BaseUiToastManager } from \"@/types/api-toast/base-ui-toast-manager.type\";\nimport { readShadcnUiPath } from \"@/api-toast/read-shadcn-ui-path\";\n\nconst toastManagerCache = new Map<string, BaseUiToastManager>();\n\nfunction buildMissingShadcnToastMessage(toastModulePath: string): string {\n return (\n `[@3lineas/groovepack/api-toast] Could not load a valid Shadcn toastManager from \"${toastModulePath}\". ` +\n 'Run \"pnpm dlx shadcn@latest add toast\" or set GROOVEPACK_SHADCN_PATH / NEXT_PUBLIC_GROOVEPACK_SHADCN_PATH to your Shadcn UI directory.'\n );\n}\n\nfunction isValidToastManager(\n candidate: unknown,\n): candidate is BaseUiToastManager {\n if (typeof candidate !== \"object\" || candidate === null) {\n return false;\n }\n\n const record = candidate as Record<string, unknown>;\n return (\n typeof record[\"add\"] === \"function\" &&\n typeof record[\"update\"] === \"function\"\n );\n}\n\nfunction extractToastManager(loadedModule: unknown): BaseUiToastManager | undefined {\n if (typeof loadedModule !== \"object\" || loadedModule === null) {\n return undefined;\n }\n\n const record = loadedModule as Record<string, unknown>;\n const candidate = record[\"toastManager\"] ?? record[\"toast\"] ?? record[\"default\"];\n\n return isValidToastManager(candidate) ? candidate : undefined;\n}\n\n/**\n * Automatically resolves the Shadcn `toastManager` from `${shadcnPath}/toast`\n * (default `\"/src/components/ui/toast\"`) or throws a descriptive error.\n */\nexport async function resolveToastManager(): Promise<BaseUiToastManager> {\n const toastModulePath = `${readShadcnUiPath()}/toast`;\n const cached = toastManagerCache.get(toastModulePath);\n if (cached) {\n return cached;\n }\n\n const missingMessage = buildMissingShadcnToastMessage(toastModulePath);\n\n try {\n const loadedModule: unknown = await import(/* @vite-ignore */ toastModulePath);\n const manager = extractToastManager(loadedModule);\n\n if (!manager) {\n console.error(missingMessage);\n throw new Error(missingMessage);\n }\n\n toastManagerCache.set(toastModulePath, manager);\n return manager;\n } catch (caughtError) {\n if (caughtError instanceof Error && caughtError.message === missingMessage) {\n throw caughtError;\n }\n\n console.error(missingMessage);\n throw new Error(missingMessage);\n }\n}\n","import type { ActionResponse } from \"@/types/common/action-response.type\";\nimport type { ApiToastDefaults } from \"@/types/api-toast/api-toast-defaults.type\";\nimport type { ApiToastOptions } from \"@/types/api-toast/api-toast-options.type\";\nimport { resolveToastManager } from \"@/api-toast/resolve-toast-manager\";\nimport { resolveLocaleMessages } from \"@/i18n/resolve-locale-messages\";\n\n/**\n * Factory creating a pre-configured `apiToast` helper backed by Shadcn Toast.\n */\nexport function createApiToast(defaults: ApiToastDefaults = {}) {\n return async function configuredApiToast<T = unknown>({\n action,\n loadingMessage,\n successMessage,\n errorMessage,\n onSuccess,\n onError,\n }: ApiToastOptions<T>): Promise<ActionResponse<T>> {\n const toastManager = await resolveToastManager();\n const messages = resolveLocaleMessages();\n const resolvedLoading =\n loadingMessage ?? defaults.defaultLoadingMessage ?? messages.loading;\n const resolvedSuccess =\n successMessage ?? defaults.defaultSuccessMessage ?? messages.success;\n const resolvedError =\n errorMessage ?? defaults.defaultErrorMessage ?? messages.operationFailed;\n\n const toastId = toastManager.add({\n title: resolvedLoading,\n type: \"loading\",\n });\n\n try {\n const actionResult = await action();\n\n if (actionResult.success) {\n const displayMessage = actionResult.message ?? resolvedSuccess;\n toastManager.update(toastId, {\n title: displayMessage,\n type: \"success\",\n });\n onSuccess?.(actionResult.data, actionResult);\n return actionResult;\n }\n\n const displayError =\n actionResult.error ?? actionResult.message ?? resolvedError;\n toastManager.update(toastId, {\n title: displayError,\n type: \"error\",\n });\n onError?.(displayError, actionResult);\n return actionResult;\n } catch (caughtError) {\n const fallbackError =\n caughtError instanceof Error ? caughtError.message : resolvedError;\n toastManager.update(toastId, {\n title: fallbackError,\n type: \"error\",\n });\n onError?.(fallbackError);\n\n return {\n success: false,\n error: fallbackError,\n };\n }\n };\n}\n","import { createApiToast } from \"@/api-toast/create-api-toast\";\n\nexport type { ActionResponse } from \"@/types/common/action-response.type\";\nexport type { ApiToastOptions } from \"@/types/api-toast/api-toast-options.type\";\nexport type {\n ApiToastDefaults,\n ToastedOptions,\n} from \"@/types/api-toast/api-toast-defaults.type\";\nexport type { BaseUiToastManager } from \"@/types/api-toast/base-ui-toast-manager.type\";\nexport type { BaseUiToastPayload } from \"@/types/api-toast/base-ui-toast-payload.type\";\nexport { createApiToast } from \"@/api-toast/create-api-toast\";\n\n/**\n * Wraps an `ActionResponse<T>` promise with Shadcn v4 (`@base-ui/react/toast`) loading, success, and error states.\n */\nexport const apiToast = createApiToast();\n"],"mappings":";;;;;AAAA,IAAM,yBAAyB;AAE/B,IAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AACF;AAEA,SAAS,cAAc,WAAwC;AAC7D,MAAI,OAAO,cAAc,UAAU;AACjC,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,UAAU,KAAK,EAAE,QAAQ,QAAQ,EAAE;AACnD,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAEA,SAAS,+BAAmD;AAC1D,QAAM,eAAe;AACrB,QAAM,eAAe,aAAa,SAAS;AAC3C,MAAI,OAAO,iBAAiB,YAAY,iBAAiB,MAAM;AAC7D,WAAO;AAAA,EACT;AAEA,QAAM,WAAY,aAAyC,KAAK;AAChE,MAAI,OAAO,aAAa,YAAY,aAAa,MAAM;AACrD,WAAO;AAAA,EACT;AAEA,QAAM,SAAS;AACf,aAAW,OAAO,sBAAsB;AACtC,UAAM,aAAa,cAAc,OAAO,GAAG,CAAC;AAC5C,QAAI,YAAY;AACd,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;AAEA,SAAS,+BAAmD;AAC1D,MAAI;AACF,WACE,cAAc,YAAY,KAAK,sBAAsB,KACrD,cAAc,YAAY,KAAK,kCAAkC;AAAA,EAErE,QAAQ;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D,SAAO,eAAe,mBAAgC;AAAA,IACpD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAAmD;AACjD,UAAM,eAAe,MAAM,oBAAoB;AAC/C,UAAM,WAAW,sBAAsB;AACvC,UAAM,kBACJ,kBAAkB,SAAS,yBAAyB,SAAS;AAC/D,UAAM,kBACJ,kBAAkB,SAAS,yBAAyB,SAAS;AAC/D,UAAM,gBACJ,gBAAgB,SAAS,uBAAuB,SAAS;AAE3D,UAAM,UAAU,aAAa,IAAI;AAAA,MAC/B,OAAO;AAAA,MACP,MAAM;AAAA,IACR,CAAC;AAED,QAAI;AACF,YAAM,eAAe,MAAM,OAAO;AAElC,UAAI,aAAa,SAAS;AACxB,cAAM,iBAAiB,aAAa,WAAW;AAC/C,qBAAa,OAAO,SAAS;AAAA,UAC3B,OAAO;AAAA,UACP,MAAM;AAAA,QACR,CAAC;AACD,oBAAY,aAAa,MAAM,YAAY;AAC3C,eAAO;AAAA,MACT;AAEA,YAAM,eACJ,aAAa,SAAS,aAAa,WAAW;AAChD,mBAAa,OAAO,SAAS;AAAA,QAC3B,OAAO;AAAA,QACP,MAAM;AAAA,MACR,CAAC;AACD,gBAAU,cAAc,YAAY;AACpC,aAAO;AAAA,IACT,SAAS,aAAa;AACpB,YAAM,gBACJ,uBAAuB,QAAQ,YAAY,UAAU;AACvD,mBAAa,OAAO,SAAS;AAAA,QAC3B,OAAO;AAAA,QACP,MAAM;AAAA,MACR,CAAC;AACD,gBAAU,aAAa;AAEvB,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACF;;;ACrDO,IAAM,WAAW,eAAe;","names":[]}
|
|
@@ -18,23 +18,9 @@ function normalizeSupportedLocale(candidate) {
|
|
|
18
18
|
// src/i18n/read-env-locale.ts
|
|
19
19
|
var ENV_LOCALE_KEYS = [
|
|
20
20
|
"GROOVEPACK_LOCALE",
|
|
21
|
-
"NEXT_PUBLIC_GROOVEPACK_LOCALE"
|
|
22
|
-
"VITE_GROOVEPACK_LOCALE",
|
|
23
|
-
"PUBLIC_GROOVEPACK_LOCALE"
|
|
21
|
+
"NEXT_PUBLIC_GROOVEPACK_LOCALE"
|
|
24
22
|
];
|
|
25
|
-
function
|
|
26
|
-
if (!record) {
|
|
27
|
-
return void 0;
|
|
28
|
-
}
|
|
29
|
-
for (const key of ENV_LOCALE_KEYS) {
|
|
30
|
-
const normalized = normalizeSupportedLocale(record[key]);
|
|
31
|
-
if (normalized) {
|
|
32
|
-
return normalized;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
return void 0;
|
|
36
|
-
}
|
|
37
|
-
function getProcessEnvRecord() {
|
|
23
|
+
function readLocaleFromProcessEnv() {
|
|
38
24
|
const globalRecord = globalThis;
|
|
39
25
|
const processValue = globalRecord["process"];
|
|
40
26
|
if (typeof processValue !== "object" || processValue === null) {
|
|
@@ -44,34 +30,29 @@ function getProcessEnvRecord() {
|
|
|
44
30
|
if (typeof envValue !== "object" || envValue === null) {
|
|
45
31
|
return void 0;
|
|
46
32
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
33
|
+
const record = envValue;
|
|
34
|
+
for (const key of ENV_LOCALE_KEYS) {
|
|
35
|
+
const normalized = normalizeSupportedLocale(record[key]);
|
|
36
|
+
if (normalized) {
|
|
37
|
+
return normalized;
|
|
38
|
+
}
|
|
53
39
|
}
|
|
54
|
-
|
|
55
|
-
|
|
40
|
+
return void 0;
|
|
41
|
+
}
|
|
42
|
+
function readLocaleFromImportMeta() {
|
|
43
|
+
try {
|
|
44
|
+
return normalizeSupportedLocale(import.meta.env?.GROOVEPACK_LOCALE) ?? normalizeSupportedLocale(import.meta.env?.NEXT_PUBLIC_GROOVEPACK_LOCALE);
|
|
45
|
+
} catch {
|
|
56
46
|
return void 0;
|
|
57
47
|
}
|
|
58
|
-
return envValue;
|
|
59
48
|
}
|
|
60
49
|
function readEnvLocale() {
|
|
61
|
-
return
|
|
50
|
+
return readLocaleFromProcessEnv() ?? readLocaleFromImportMeta();
|
|
62
51
|
}
|
|
63
52
|
|
|
64
53
|
// src/i18n/locale-state.ts
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
if (locale === void 0) {
|
|
68
|
-
configuredLocale = void 0;
|
|
69
|
-
return;
|
|
70
|
-
}
|
|
71
|
-
configuredLocale = normalizeSupportedLocale(locale);
|
|
72
|
-
}
|
|
73
|
-
function getGroovepackLocale(overrideLocale) {
|
|
74
|
-
return normalizeSupportedLocale(overrideLocale) ?? configuredLocale ?? readEnvLocale() ?? "en";
|
|
54
|
+
function getGroovepackLocale() {
|
|
55
|
+
return readEnvLocale() ?? "en";
|
|
75
56
|
}
|
|
76
57
|
|
|
77
58
|
// src/i18n/messages.ts
|
|
@@ -114,17 +95,16 @@ var GROOVEPACK_MESSAGES = {
|
|
|
114
95
|
};
|
|
115
96
|
|
|
116
97
|
// src/i18n/resolve-locale-messages.ts
|
|
117
|
-
function resolveLocaleMessages(
|
|
118
|
-
const activeLocale = getGroovepackLocale(
|
|
98
|
+
function resolveLocaleMessages() {
|
|
99
|
+
const activeLocale = getGroovepackLocale();
|
|
119
100
|
return GROOVEPACK_MESSAGES[activeLocale];
|
|
120
101
|
}
|
|
121
102
|
|
|
122
103
|
export {
|
|
123
104
|
normalizeSupportedLocale,
|
|
124
105
|
readEnvLocale,
|
|
125
|
-
setGroovepackLocale,
|
|
126
106
|
getGroovepackLocale,
|
|
127
107
|
GROOVEPACK_MESSAGES,
|
|
128
108
|
resolveLocaleMessages
|
|
129
109
|
};
|
|
130
|
-
//# sourceMappingURL=chunk-
|
|
110
|
+
//# sourceMappingURL=chunk-OSPD6EX4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/i18n/is-supported-locale.ts","../src/i18n/read-env-locale.ts","../src/i18n/locale-state.ts","../src/i18n/messages.ts","../src/i18n/resolve-locale-messages.ts"],"sourcesContent":["import type { GroovepackLocale } from \"@/types/i18n/groovepack-locale.type\";\n\nconst SUPPORTED_LOCALE_SET = new Set<string>([\"en\", \"es\", \"pt\", \"it\", \"fr\"]);\n\n/**\n * Normalizes a candidate locale string (e.g. \"es-AR\" -> \"es\") and returns\n * a supported `GroovepackLocale`, or `undefined` if unsupported.\n */\nexport function normalizeSupportedLocale(\n candidate: unknown,\n): GroovepackLocale | undefined {\n if (typeof candidate !== \"string\") {\n return undefined;\n }\n\n const trimmed = candidate.trim().toLowerCase();\n if (trimmed.length === 0) {\n return undefined;\n }\n\n const baseTag = trimmed.split(/[-_]/)[0];\n if (!baseTag || !SUPPORTED_LOCALE_SET.has(baseTag)) {\n return undefined;\n }\n\n return baseTag as GroovepackLocale;\n}\n","import type { GroovepackLocale } from \"@/types/i18n/groovepack-locale.type\";\nimport { normalizeSupportedLocale } from \"@/i18n/is-supported-locale\";\n\nconst ENV_LOCALE_KEYS = [\n \"GROOVEPACK_LOCALE\",\n \"NEXT_PUBLIC_GROOVEPACK_LOCALE\",\n] as const;\n\nfunction readLocaleFromProcessEnv(): GroovepackLocale | undefined {\n const globalRecord = globalThis as Record<string, unknown>;\n const processValue = globalRecord[\"process\"];\n if (typeof processValue !== \"object\" || processValue === null) {\n return undefined;\n }\n\n const envValue = (processValue as Record<string, unknown>)[\"env\"];\n if (typeof envValue !== \"object\" || envValue === null) {\n return undefined;\n }\n\n const record = envValue as Record<string, unknown>;\n for (const key of ENV_LOCALE_KEYS) {\n const normalized = normalizeSupportedLocale(record[key]);\n if (normalized) {\n return normalized;\n }\n }\n\n return undefined;\n}\n\nfunction readLocaleFromImportMeta(): GroovepackLocale | undefined {\n try {\n return (\n normalizeSupportedLocale(import.meta.env?.GROOVEPACK_LOCALE) ??\n normalizeSupportedLocale(import.meta.env?.NEXT_PUBLIC_GROOVEPACK_LOCALE)\n );\n } catch {\n return undefined;\n }\n}\n\n/**\n * Safely reads `GROOVEPACK_LOCALE` or `NEXT_PUBLIC_GROOVEPACK_LOCALE` in Vinext\n * (Cloudflare Workers + Vite 8 `ModuleRunner`) without dynamic `import.meta.env` access.\n */\nexport function readEnvLocale(): GroovepackLocale | undefined {\n return readLocaleFromProcessEnv() ?? readLocaleFromImportMeta();\n}\n","import type { GroovepackLocale } from \"@/types/i18n/groovepack-locale.type\";\nimport { readEnvLocale } from \"@/i18n/read-env-locale\";\n\n/**\n * Resolves the active locale strictly from environment variables\n * (`GROOVEPACK_LOCALE` or `NEXT_PUBLIC_GROOVEPACK_LOCALE`), defaulting to `\"en\"`.\n */\nexport function getGroovepackLocale(): GroovepackLocale {\n return readEnvLocale() ?? \"en\";\n}\n","import type { GroovepackLocale } from \"@/types/i18n/groovepack-locale.type\";\nimport type { GroovepackLocaleMessages } from \"@/types/i18n/locale-messages.type\";\n\nexport const GROOVEPACK_MESSAGES = {\n en: {\n loading: \"Processing...\",\n success: \"Operation completed successfully.\",\n unexpectedError:\n \"An unexpected error occurred while processing your request. Please try again.\",\n serverRequestFailed:\n \"Could not process the request on the server. Please try again.\",\n operationFailed: \"The operation could not be completed.\",\n },\n es: {\n loading: \"Procesando...\",\n success: \"Operación completada con éxito.\",\n unexpectedError:\n \"Ocurrió un error inesperado al procesar la solicitud. Por favor, intenta de nuevo.\",\n serverRequestFailed:\n \"No se pudo procesar la solicitud en el servidor. Por favor, intenta de nuevo.\",\n operationFailed: \"La operación no se pudo completar.\",\n },\n pt: {\n loading: \"Processando...\",\n success: \"Operação concluída com sucesso.\",\n unexpectedError:\n \"Ocorreu um erro inesperado ao processar a solicitação. Por favor, tente novamente.\",\n serverRequestFailed:\n \"Não foi possível processar a solicitação no servidor. Por favor, tente novamente.\",\n operationFailed: \"Não foi possível concluir a operação.\",\n },\n it: {\n loading: \"Elaborazione in corso...\",\n success: \"Operazione completata con successo.\",\n unexpectedError:\n \"Si è verificato un errore imprevisto durante l'elaborazione della richiesta. Riprova.\",\n serverRequestFailed:\n \"Impossibile elaborare la richiesta sul server. Riprova.\",\n operationFailed: \"Impossibile completare l'operazione.\",\n },\n fr: {\n loading: \"Traitement en cours...\",\n success: \"Opération terminée avec succès.\",\n unexpectedError:\n \"Une erreur inattendue s'est produite lors du traitement de la demande. Veuillez réessayer.\",\n serverRequestFailed:\n \"Impossible de traiter la demande sur le serveur. Veuillez réessayer.\",\n operationFailed: \"L'opération n'a pas pu être terminée.\",\n },\n} as const satisfies Record<GroovepackLocale, GroovepackLocaleMessages>;\n","import type { GroovepackLocaleMessages } from \"@/types/i18n/locale-messages.type\";\nimport { getGroovepackLocale } from \"@/i18n/locale-state\";\nimport { GROOVEPACK_MESSAGES } from \"@/i18n/messages\";\n\n/**\n * Returns the localized message dictionary resolved from environment variables\n * or the default `\"en\"` locale.\n */\nexport function resolveLocaleMessages(): GroovepackLocaleMessages {\n const activeLocale = getGroovepackLocale();\n return GROOVEPACK_MESSAGES[activeLocale];\n}\n"],"mappings":";AAEA,IAAM,uBAAuB,oBAAI,IAAY,CAAC,MAAM,MAAM,MAAM,MAAM,IAAI,CAAC;AAMpE,SAAS,yBACd,WAC8B;AAC9B,MAAI,OAAO,cAAc,UAAU;AACjC,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,UAAU,KAAK,EAAE,YAAY;AAC7C,MAAI,QAAQ,WAAW,GAAG;AACxB,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,QAAQ,MAAM,MAAM,EAAE,CAAC;AACvC,MAAI,CAAC,WAAW,CAAC,qBAAqB,IAAI,OAAO,GAAG;AAClD,WAAO;AAAA,EACT;AAEA,SAAO;AACT;;;ACvBA,IAAM,kBAAkB;AAAA,EACtB;AAAA,EACA;AACF;AAEA,SAAS,2BAAyD;AAChE,QAAM,eAAe;AACrB,QAAM,eAAe,aAAa,SAAS;AAC3C,MAAI,OAAO,iBAAiB,YAAY,iBAAiB,MAAM;AAC7D,WAAO;AAAA,EACT;AAEA,QAAM,WAAY,aAAyC,KAAK;AAChE,MAAI,OAAO,aAAa,YAA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1
|
+
type GroovepackLocale = "en" | "es" | "pt" | "it" | "fr";
|
|
2
2
|
|
|
3
3
|
interface GroovepackLocaleMessages {
|
|
4
4
|
readonly loading: string;
|
|
@@ -53,31 +53,21 @@ declare const GROOVEPACK_MESSAGES: {
|
|
|
53
53
|
declare function normalizeSupportedLocale(candidate: unknown): GroovepackLocale | undefined;
|
|
54
54
|
|
|
55
55
|
/**
|
|
56
|
-
* Safely reads `GROOVEPACK_LOCALE`
|
|
57
|
-
*
|
|
58
|
-
* requiring `@types/node` or Vite ambient types.
|
|
56
|
+
* Safely reads `GROOVEPACK_LOCALE` or `NEXT_PUBLIC_GROOVEPACK_LOCALE` in Vinext
|
|
57
|
+
* (Cloudflare Workers + Vite 8 `ModuleRunner`) without dynamic `import.meta.env` access.
|
|
59
58
|
*/
|
|
60
59
|
declare function readEnvLocale(): GroovepackLocale | undefined;
|
|
61
60
|
|
|
62
61
|
/**
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
* variables or `"en"`.
|
|
62
|
+
* Resolves the active locale strictly from environment variables
|
|
63
|
+
* (`GROOVEPACK_LOCALE` or `NEXT_PUBLIC_GROOVEPACK_LOCALE`), defaulting to `"en"`.
|
|
66
64
|
*/
|
|
67
|
-
declare function
|
|
68
|
-
/**
|
|
69
|
-
* Resolves the active locale using precedence:
|
|
70
|
-
* 1. Explicit `overrideLocale`
|
|
71
|
-
* 2. Runtime locale set via `setGroovepackLocale()`
|
|
72
|
-
* 3. Environment variable (`GROOVEPACK_LOCALE` / framework-prefixed)
|
|
73
|
-
* 4. Default `"en"`
|
|
74
|
-
*/
|
|
75
|
-
declare function getGroovepackLocale(overrideLocale?: GroovepackLocale): GroovepackLocale;
|
|
65
|
+
declare function getGroovepackLocale(): GroovepackLocale;
|
|
76
66
|
|
|
77
67
|
/**
|
|
78
|
-
* Returns the localized message dictionary
|
|
79
|
-
* or the
|
|
68
|
+
* Returns the localized message dictionary resolved from environment variables
|
|
69
|
+
* or the default `"en"` locale.
|
|
80
70
|
*/
|
|
81
|
-
declare function resolveLocaleMessages(
|
|
71
|
+
declare function resolveLocaleMessages(): GroovepackLocaleMessages;
|
|
82
72
|
|
|
83
|
-
export { GROOVEPACK_MESSAGES, GroovepackLocale, type GroovepackLocaleMessages, getGroovepackLocale, normalizeSupportedLocale, readEnvLocale, resolveLocaleMessages
|
|
73
|
+
export { GROOVEPACK_MESSAGES, type GroovepackLocale, type GroovepackLocaleMessages, getGroovepackLocale, normalizeSupportedLocale, readEnvLocale, resolveLocaleMessages };
|
package/dist/i18n/index.js
CHANGED
|
@@ -3,15 +3,13 @@ import {
|
|
|
3
3
|
getGroovepackLocale,
|
|
4
4
|
normalizeSupportedLocale,
|
|
5
5
|
readEnvLocale,
|
|
6
|
-
resolveLocaleMessages
|
|
7
|
-
|
|
8
|
-
} from "../chunk-PDWE3D4J.js";
|
|
6
|
+
resolveLocaleMessages
|
|
7
|
+
} from "../chunk-OSPD6EX4.js";
|
|
9
8
|
export {
|
|
10
9
|
GROOVEPACK_MESSAGES,
|
|
11
10
|
getGroovepackLocale,
|
|
12
11
|
normalizeSupportedLocale,
|
|
13
12
|
readEnvLocale,
|
|
14
|
-
resolveLocaleMessages
|
|
15
|
-
setGroovepackLocale
|
|
13
|
+
resolveLocaleMessages
|
|
16
14
|
};
|
|
17
15
|
//# sourceMappingURL=index.js.map
|
package/dist/logger/index.js
CHANGED
|
@@ -14,14 +14,11 @@ function checkIsDevelopment() {
|
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
return envValue["DEV"] === true;
|
|
22
|
-
}
|
|
17
|
+
try {
|
|
18
|
+
return Boolean(import.meta.env?.DEV);
|
|
19
|
+
} catch {
|
|
20
|
+
return false;
|
|
23
21
|
}
|
|
24
|
-
return false;
|
|
25
22
|
}
|
|
26
23
|
|
|
27
24
|
// src/logger/format-dev-log.ts
|
package/dist/logger/index.js.map
CHANGED
|
@@ -1 +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 runtime is in development or test mode\n *
|
|
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;AAC5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AAI;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,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for the `@3lineas/groovepack/vite` plugin.
|
|
3
|
+
*/
|
|
4
|
+
interface GroovepackVitePluginOptions {
|
|
5
|
+
/** Custom Shadcn UI directory (defaults to env vars or `"/src/components/ui"`). */
|
|
6
|
+
shadcnPath?: string;
|
|
7
|
+
}
|
|
8
|
+
interface GroovepackViteResolvedConfig {
|
|
9
|
+
root?: string;
|
|
10
|
+
}
|
|
11
|
+
interface GroovepackVitePlugin {
|
|
12
|
+
name: string;
|
|
13
|
+
enforce?: "pre" | "post";
|
|
14
|
+
config?: () => {
|
|
15
|
+
optimizeDeps?: {
|
|
16
|
+
exclude?: string[];
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
configResolved?: (config: GroovepackViteResolvedConfig) => void;
|
|
20
|
+
resolveId?: (source: string) => string | undefined;
|
|
21
|
+
load?: (id: string) => string | undefined;
|
|
22
|
+
transform?: (code: string, id: string) => {
|
|
23
|
+
code: string;
|
|
24
|
+
map: null;
|
|
25
|
+
} | undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Optional Vite plugin for `@3lineas/groovepack/api-toast`.
|
|
30
|
+
* Statically resolves `${shadcnPath}/toast` in both `vite dev` and `vite build`.
|
|
31
|
+
*/
|
|
32
|
+
declare function groovepack(options?: GroovepackVitePluginOptions): GroovepackVitePlugin;
|
|
33
|
+
|
|
34
|
+
export { type GroovepackVitePlugin, type GroovepackVitePluginOptions, type GroovepackViteResolvedConfig, groovepack };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// src/vite/groovepack-plugin.ts
|
|
2
|
+
import { existsSync } from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
var DEFAULT_SHADCN_UI_PATH = "/src/components/ui";
|
|
5
|
+
var VIRTUAL_MISSING_TOAST_ID = "\0groovepack-missing-toast";
|
|
6
|
+
var DYNAMIC_IMPORT_PATTERN = /import\(\s*\/\*\s*@vite-ignore\s*\*\/\s*[^)]+\)/g;
|
|
7
|
+
var TOAST_EXTENSIONS = [
|
|
8
|
+
"",
|
|
9
|
+
".ts",
|
|
10
|
+
".tsx",
|
|
11
|
+
".js",
|
|
12
|
+
".jsx",
|
|
13
|
+
"/index.ts",
|
|
14
|
+
"/index.tsx"
|
|
15
|
+
];
|
|
16
|
+
function resolveShadcnPath(options) {
|
|
17
|
+
const candidate = options?.shadcnPath ?? process.env["GROOVEPACK_SHADCN_PATH"] ?? process.env["NEXT_PUBLIC_GROOVEPACK_SHADCN_PATH"] ?? DEFAULT_SHADCN_UI_PATH;
|
|
18
|
+
return candidate.trim().replace(/\/+$/, "") || DEFAULT_SHADCN_UI_PATH;
|
|
19
|
+
}
|
|
20
|
+
function hasToastModuleOnDisk(rootDir, shadcnPath) {
|
|
21
|
+
const relativeBase = shadcnPath.startsWith("/") ? shadcnPath.slice(1) : shadcnPath;
|
|
22
|
+
const baseTarget = path.resolve(rootDir, relativeBase, "toast");
|
|
23
|
+
return TOAST_EXTENSIONS.some((ext) => existsSync(`${baseTarget}${ext}`));
|
|
24
|
+
}
|
|
25
|
+
function groovepack(options) {
|
|
26
|
+
let rootDir = process.cwd();
|
|
27
|
+
const shadcnPath = resolveShadcnPath(options);
|
|
28
|
+
const toastImportTarget = `${shadcnPath}/toast`;
|
|
29
|
+
return {
|
|
30
|
+
name: "groovepack",
|
|
31
|
+
enforce: "pre",
|
|
32
|
+
config() {
|
|
33
|
+
return {
|
|
34
|
+
optimizeDeps: {
|
|
35
|
+
exclude: ["@3lineas/groovepack"]
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
},
|
|
39
|
+
configResolved(resolvedConfig) {
|
|
40
|
+
if (resolvedConfig.root) {
|
|
41
|
+
rootDir = resolvedConfig.root;
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
resolveId(source) {
|
|
45
|
+
if (source === VIRTUAL_MISSING_TOAST_ID) {
|
|
46
|
+
return VIRTUAL_MISSING_TOAST_ID;
|
|
47
|
+
}
|
|
48
|
+
return void 0;
|
|
49
|
+
},
|
|
50
|
+
load(id) {
|
|
51
|
+
if (id === VIRTUAL_MISSING_TOAST_ID) {
|
|
52
|
+
return "export default undefined;";
|
|
53
|
+
}
|
|
54
|
+
return void 0;
|
|
55
|
+
},
|
|
56
|
+
transform(code, id) {
|
|
57
|
+
if (!id.includes("groovepack") || !id.includes("api-toast")) {
|
|
58
|
+
return void 0;
|
|
59
|
+
}
|
|
60
|
+
const target = hasToastModuleOnDisk(rootDir, shadcnPath) ? toastImportTarget : VIRTUAL_MISSING_TOAST_ID;
|
|
61
|
+
const transformed = code.replace(
|
|
62
|
+
DYNAMIC_IMPORT_PATTERN,
|
|
63
|
+
`import(${JSON.stringify(target)})`
|
|
64
|
+
);
|
|
65
|
+
if (transformed === code) {
|
|
66
|
+
return void 0;
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
code: transformed,
|
|
70
|
+
map: null
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
export {
|
|
76
|
+
groovepack
|
|
77
|
+
};
|
|
78
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/vite/groovepack-plugin.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n GroovepackVitePlugin,\n GroovepackVitePluginOptions,\n GroovepackViteResolvedConfig,\n} from \"@/types/vite/vite-plugin.type\";\n\nconst DEFAULT_SHADCN_UI_PATH = \"/src/components/ui\";\nconst VIRTUAL_MISSING_TOAST_ID = \"\\0groovepack-missing-toast\";\nconst DYNAMIC_IMPORT_PATTERN =\n /import\\(\\s*\\/\\*\\s*@vite-ignore\\s*\\*\\/\\s*[^)]+\\)/g;\nconst TOAST_EXTENSIONS = [\n \"\",\n \".ts\",\n \".tsx\",\n \".js\",\n \".jsx\",\n \"/index.ts\",\n \"/index.tsx\",\n] as const;\n\nfunction resolveShadcnPath(options?: GroovepackVitePluginOptions): string {\n const candidate =\n options?.shadcnPath ??\n process.env[\"GROOVEPACK_SHADCN_PATH\"] ??\n process.env[\"NEXT_PUBLIC_GROOVEPACK_SHADCN_PATH\"] ??\n DEFAULT_SHADCN_UI_PATH;\n\n return candidate.trim().replace(/\\/+$/, \"\") || DEFAULT_SHADCN_UI_PATH;\n}\n\nfunction hasToastModuleOnDisk(rootDir: string, shadcnPath: string): boolean {\n const relativeBase = shadcnPath.startsWith(\"/\")\n ? shadcnPath.slice(1)\n : shadcnPath;\n const baseTarget = path.resolve(rootDir, relativeBase, \"toast\");\n\n return TOAST_EXTENSIONS.some((ext) => existsSync(`${baseTarget}${ext}`));\n}\n\n/**\n * Optional Vite plugin for `@3lineas/groovepack/api-toast`.\n * Statically resolves `${shadcnPath}/toast` in both `vite dev` and `vite build`.\n */\nexport function groovepack(\n options?: GroovepackVitePluginOptions,\n): GroovepackVitePlugin {\n let rootDir = process.cwd();\n const shadcnPath = resolveShadcnPath(options);\n const toastImportTarget = `${shadcnPath}/toast`;\n\n return {\n name: \"groovepack\",\n enforce: \"pre\",\n config() {\n return {\n optimizeDeps: {\n exclude: [\"@3lineas/groovepack\"],\n },\n };\n },\n configResolved(resolvedConfig: GroovepackViteResolvedConfig) {\n if (resolvedConfig.root) {\n rootDir = resolvedConfig.root;\n }\n },\n resolveId(source: string) {\n if (source === VIRTUAL_MISSING_TOAST_ID) {\n return VIRTUAL_MISSING_TOAST_ID;\n }\n\n return undefined;\n },\n load(id: string) {\n if (id === VIRTUAL_MISSING_TOAST_ID) {\n return \"export default undefined;\";\n }\n\n return undefined;\n },\n transform(code: string, id: string) {\n if (!id.includes(\"groovepack\") || !id.includes(\"api-toast\")) {\n return undefined;\n }\n\n const target = hasToastModuleOnDisk(rootDir, shadcnPath)\n ? toastImportTarget\n : VIRTUAL_MISSING_TOAST_ID;\n\n const transformed = code.replace(\n DYNAMIC_IMPORT_PATTERN,\n `import(${JSON.stringify(target)})`,\n );\n\n if (transformed === code) {\n return undefined;\n }\n\n return {\n code: transformed,\n map: null,\n };\n },\n };\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AAOjB,IAAM,yBAAyB;AAC/B,IAAM,2BAA2B;AACjC,IAAM,yBACJ;AACF,IAAM,mBAAmB;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,kBAAkB,SAA+C;AACxE,QAAM,YACJ,SAAS,cACT,QAAQ,IAAI,wBAAwB,KACpC,QAAQ,IAAI,oCAAoC,KAChD;AAEF,SAAO,UAAU,KAAK,EAAE,QAAQ,QAAQ,EAAE,KAAK;AACjD;AAEA,SAAS,qBAAqB,SAAiB,YAA6B;AAC1E,QAAM,eAAe,WAAW,WAAW,GAAG,IAC1C,WAAW,MAAM,CAAC,IAClB;AACJ,QAAM,aAAa,KAAK,QAAQ,SAAS,cAAc,OAAO;AAE9D,SAAO,iBAAiB,KAAK,CAAC,QAAQ,WAAW,GAAG,UAAU,GAAG,GAAG,EAAE,CAAC;AACzE;AAMO,SAAS,WACd,SACsB;AACtB,MAAI,UAAU,QAAQ,IAAI;AAC1B,QAAM,aAAa,kBAAkB,OAAO;AAC5C,QAAM,oBAAoB,GAAG,UAAU;AAEvC,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT,SAAS;AACP,aAAO;AAAA,QACL,cAAc;AAAA,UACZ,SAAS,CAAC,qBAAqB;AAAA,QACjC;AAAA,MACF;AAAA,IACF;AAAA,IACA,eAAe,gBAA8C;AAC3D,UAAI,eAAe,MAAM;AACvB,kBAAU,eAAe;AAAA,MAC3B;AAAA,IACF;AAAA,IACA,UAAU,QAAgB;AACxB,UAAI,WAAW,0BAA0B;AACvC,eAAO;AAAA,MACT;AAEA,aAAO;AAAA,IACT;AAAA,IACA,KAAK,IAAY;AACf,UAAI,OAAO,0BAA0B;AACnC,eAAO;AAAA,MACT;AAEA,aAAO;AAAA,IACT;AAAA,IACA,UAAU,MAAc,IAAY;AAClC,UAAI,CAAC,GAAG,SAAS,YAAY,KAAK,CAAC,GAAG,SAAS,WAAW,GAAG;AAC3D,eAAO;AAAA,MACT;AAEA,YAAM,SAAS,qBAAqB,SAAS,UAAU,IACnD,oBACA;AAEJ,YAAM,cAAc,KAAK;AAAA,QACvB;AAAA,QACA,UAAU,KAAK,UAAU,MAAM,CAAC;AAAA,MAClC;AAEA,UAAI,gBAAgB,MAAM;AACxB,eAAO;AAAA,MACT;AAEA,aAAO;AAAA,QACL,MAAM;AAAA,QACN,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@3lineas/groovepack",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.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,
|
|
@@ -36,6 +36,10 @@
|
|
|
36
36
|
"./i18n": {
|
|
37
37
|
"types": "./dist/i18n/index.d.ts",
|
|
38
38
|
"import": "./dist/i18n/index.js"
|
|
39
|
+
},
|
|
40
|
+
"./vite": {
|
|
41
|
+
"types": "./dist/vite/index.d.ts",
|
|
42
|
+
"import": "./dist/vite/index.js"
|
|
39
43
|
}
|
|
40
44
|
},
|
|
41
45
|
"publishConfig": {
|
|
@@ -56,21 +60,20 @@
|
|
|
56
60
|
"test": "tsx --test test/*.test.ts"
|
|
57
61
|
},
|
|
58
62
|
"peerDependencies": {
|
|
59
|
-
"
|
|
60
|
-
"
|
|
63
|
+
"@base-ui/react": ">=1.0.0",
|
|
64
|
+
"hono": ">=4.0.0"
|
|
61
65
|
},
|
|
62
66
|
"peerDependenciesMeta": {
|
|
63
|
-
"
|
|
67
|
+
"@base-ui/react": {
|
|
64
68
|
"optional": true
|
|
65
69
|
},
|
|
66
|
-
"
|
|
70
|
+
"hono": {
|
|
67
71
|
"optional": true
|
|
68
72
|
}
|
|
69
73
|
},
|
|
70
74
|
"devDependencies": {
|
|
71
75
|
"@types/node": "^22.10.1",
|
|
72
76
|
"hono": "^4.7.0",
|
|
73
|
-
"sonner": "^2.0.0",
|
|
74
77
|
"tsup": "^8.3.5",
|
|
75
78
|
"tsx": "^4.19.2",
|
|
76
79
|
"typescript": "^5.7.2"
|
|
@@ -83,7 +86,8 @@
|
|
|
83
86
|
"logger",
|
|
84
87
|
"api-client",
|
|
85
88
|
"api-action",
|
|
86
|
-
"
|
|
89
|
+
"base-ui",
|
|
90
|
+
"shadcn"
|
|
87
91
|
],
|
|
88
92
|
"author": "3lineas",
|
|
89
93
|
"license": "MIT"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/i18n/is-supported-locale.ts","../src/i18n/read-env-locale.ts","../src/i18n/locale-state.ts","../src/i18n/messages.ts","../src/i18n/resolve-locale-messages.ts"],"sourcesContent":["import type { GroovepackLocale } from \"@/types/i18n/groovepack-locale.type\";\n\nconst SUPPORTED_LOCALE_SET = new Set<string>([\"en\", \"es\", \"pt\", \"it\", \"fr\"]);\n\n/**\n * Normalizes a candidate locale string (e.g. \"es-AR\" -> \"es\") and returns\n * a supported `GroovepackLocale`, or `undefined` if unsupported.\n */\nexport function normalizeSupportedLocale(\n candidate: unknown,\n): GroovepackLocale | undefined {\n if (typeof candidate !== \"string\") {\n return undefined;\n }\n\n const trimmed = candidate.trim().toLowerCase();\n if (trimmed.length === 0) {\n return undefined;\n }\n\n const baseTag = trimmed.split(/[-_]/)[0];\n if (!baseTag || !SUPPORTED_LOCALE_SET.has(baseTag)) {\n return undefined;\n }\n\n return baseTag as GroovepackLocale;\n}\n","import type { GroovepackLocale } from \"@/types/i18n/groovepack-locale.type\";\nimport { normalizeSupportedLocale } from \"@/i18n/is-supported-locale\";\n\nconst ENV_LOCALE_KEYS = [\n \"GROOVEPACK_LOCALE\",\n \"NEXT_PUBLIC_GROOVEPACK_LOCALE\",\n \"VITE_GROOVEPACK_LOCALE\",\n \"PUBLIC_GROOVEPACK_LOCALE\",\n] as const;\n\nfunction readLocaleFromRecord(\n record: Record<string, unknown> | undefined,\n): GroovepackLocale | undefined {\n if (!record) {\n return undefined;\n }\n\n for (const key of ENV_LOCALE_KEYS) {\n const normalized = normalizeSupportedLocale(record[key]);\n if (normalized) {\n return normalized;\n }\n }\n\n return undefined;\n}\n\nfunction getProcessEnvRecord(): Record<string, unknown> | undefined {\n const globalRecord = globalThis as Record<string, unknown>;\n const processValue = globalRecord[\"process\"];\n if (typeof processValue !== \"object\" || processValue === null) {\n return undefined;\n }\n\n const envValue = (processValue as Record<string, unknown>)[\"env\"];\n if (typeof envValue !== \"object\" || envValue === null) {\n return undefined;\n }\n\n return envValue as Record<string, unknown>;\n}\n\nfunction getImportMetaEnvRecord(): Record<string, unknown> | undefined {\n const metaValue = import.meta as unknown as Record<string, unknown> | undefined;\n if (typeof metaValue !== \"object\" || metaValue === null) {\n return undefined;\n }\n\n const envValue = metaValue[\"env\"];\n if (typeof envValue !== \"object\" || envValue === null) {\n return undefined;\n }\n\n return envValue as Record<string, unknown>;\n}\n\n/**\n * Safely reads `GROOVEPACK_LOCALE` (or framework-prefixed equivalents)\n * across Node.js, Cloudflare Workers, Next.js, Vite, and Astro without\n * requiring `@types/node` or Vite ambient types.\n */\nexport function readEnvLocale(): GroovepackLocale | undefined {\n return (\n readLocaleFromRecord(getProcessEnvRecord()) ??\n readLocaleFromRecord(getImportMetaEnvRecord())\n );\n}\n","import type { GroovepackLocale } from \"@/types/i18n/groovepack-locale.type\";\nimport { normalizeSupportedLocale } from \"@/i18n/is-supported-locale\";\nimport { readEnvLocale } from \"@/i18n/read-env-locale\";\n\nlet configuredLocale: GroovepackLocale | undefined;\n\n/**\n * Sets the global runtime locale for `@3lineas/groovepack` fallback messages.\n * Pass `undefined` to clear the runtime override and fall back to environment\n * variables or `\"en\"`.\n */\nexport function setGroovepackLocale(locale: GroovepackLocale | undefined): void {\n if (locale === undefined) {\n configuredLocale = undefined;\n return;\n }\n\n configuredLocale = normalizeSupportedLocale(locale);\n}\n\n/**\n * Resolves the active locale using precedence:\n * 1. Explicit `overrideLocale`\n * 2. Runtime locale set via `setGroovepackLocale()`\n * 3. Environment variable (`GROOVEPACK_LOCALE` / framework-prefixed)\n * 4. Default `\"en\"`\n */\nexport function getGroovepackLocale(\n overrideLocale?: GroovepackLocale,\n): GroovepackLocale {\n return (\n normalizeSupportedLocale(overrideLocale) ??\n configuredLocale ??\n readEnvLocale() ??\n \"en\"\n );\n}\n","import type { GroovepackLocale } from \"@/types/i18n/groovepack-locale.type\";\nimport type { GroovepackLocaleMessages } from \"@/types/i18n/locale-messages.type\";\n\nexport const GROOVEPACK_MESSAGES = {\n en: {\n loading: \"Processing...\",\n success: \"Operation completed successfully.\",\n unexpectedError:\n \"An unexpected error occurred while processing your request. Please try again.\",\n serverRequestFailed:\n \"Could not process the request on the server. Please try again.\",\n operationFailed: \"The operation could not be completed.\",\n },\n es: {\n loading: \"Procesando...\",\n success: \"Operación completada con éxito.\",\n unexpectedError:\n \"Ocurrió un error inesperado al procesar la solicitud. Por favor, intenta de nuevo.\",\n serverRequestFailed:\n \"No se pudo procesar la solicitud en el servidor. Por favor, intenta de nuevo.\",\n operationFailed: \"La operación no se pudo completar.\",\n },\n pt: {\n loading: \"Processando...\",\n success: \"Operação concluída com sucesso.\",\n unexpectedError:\n \"Ocorreu um erro inesperado ao processar a solicitação. Por favor, tente novamente.\",\n serverRequestFailed:\n \"Não foi possível processar a solicitação no servidor. Por favor, tente novamente.\",\n operationFailed: \"Não foi possível concluir a operação.\",\n },\n it: {\n loading: \"Elaborazione in corso...\",\n success: \"Operazione completata con successo.\",\n unexpectedError:\n \"Si è verificato un errore imprevisto durante l'elaborazione della richiesta. Riprova.\",\n serverRequestFailed:\n \"Impossibile elaborare la richiesta sul server. Riprova.\",\n operationFailed: \"Impossibile completare l'operazione.\",\n },\n fr: {\n loading: \"Traitement en cours...\",\n success: \"Opération terminée avec succès.\",\n unexpectedError:\n \"Une erreur inattendue s'est produite lors du traitement de la demande. Veuillez réessayer.\",\n serverRequestFailed:\n \"Impossible de traiter la demande sur le serveur. Veuillez réessayer.\",\n operationFailed: \"L'opération n'a pas pu être terminée.\",\n },\n} as const satisfies Record<GroovepackLocale, GroovepackLocaleMessages>;\n","import type { GroovepackLocale } from \"@/types/i18n/groovepack-locale.type\";\nimport type { GroovepackLocaleMessages } from \"@/types/i18n/locale-messages.type\";\nimport { getGroovepackLocale } from \"@/i18n/locale-state\";\nimport { GROOVEPACK_MESSAGES } from \"@/i18n/messages\";\n\n/**\n * Returns the localized message dictionary for the given override locale,\n * or the active runtime/environment/default (`\"en\"`) locale.\n */\nexport function resolveLocaleMessages(\n overrideLocale?: GroovepackLocale,\n): GroovepackLocaleMessages {\n const activeLocale = getGroovepackLocale(overrideLocale);\n return GROOVEPACK_MESSAGES[activeLocale];\n}\n"],"mappings":";AAEA,IAAM,uBAAuB,oBAAI,IAAY,CAAC,MAAM,MAAM,MAAM,MAAM,IAAI,CAAC;AAMpE,SAAS,yBACd,WAC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