@3lineas/groovepack 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -19
- package/dist/api-action/index.js +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 +28 -6
- package/dist/api-toast/index.js +58 -6
- package/dist/api-toast/index.js.map +1 -1
- package/dist/{chunk-PDWE3D4J.js → chunk-3FQ5C44Y.js} +16 -27
- package/dist/chunk-3FQ5C44Y.js.map +1 -0
- package/dist/i18n/index.d.ts +2 -3
- package/dist/i18n/index.js +1 -1
- package/dist/logger/index.js +4 -7
- package/dist/logger/index.js.map +1 -1
- package/package.json +7 -7
- package/dist/chunk-PDWE3D4J.js.map +0 -1
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,7 @@ 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
51
|
|
|
52
52
|
---
|
|
53
53
|
|
|
@@ -58,7 +58,7 @@ Install only what your app actually uses:
|
|
|
58
58
|
3. `@3lineas/groovepack/pipeline/with-d1-transaction` — Standalone `withD1Transaction` wrapper.
|
|
59
59
|
4. `@3lineas/groovepack/api-client` — `createApiClient` (REST) & `createHonoClient` (Hono RPC).
|
|
60
60
|
5. `@3lineas/groovepack/api-action` — Polymorphic `apiAction` wrapper returning `ActionResponse<T>`.
|
|
61
|
-
6. `@3lineas/groovepack/api-toast` — `apiToast
|
|
61
|
+
6. `@3lineas/groovepack/api-toast` — `apiToast` and `createApiToast` for Shadcn v4 (`@base-ui/react/toast`).
|
|
62
62
|
|
|
63
63
|
---
|
|
64
64
|
|
|
@@ -250,31 +250,31 @@ export async function createProductAction(
|
|
|
250
250
|
|
|
251
251
|
## 6. `@3lineas/groovepack/api-toast`
|
|
252
252
|
|
|
253
|
-
Orchestrates async actions with **
|
|
253
|
+
Orchestrates async actions with **Shadcn v4 (`@base-ui/react/toast`)** loading, success, and error toasts, returning the resolved `ActionResponse<T>`. Throws an explicit error if Shadcn Toast (`@base-ui/react/toast`) is not installed or configured.
|
|
254
254
|
|
|
255
255
|
```typescript
|
|
256
|
-
import { apiToast,
|
|
256
|
+
import { apiToast, createApiToast } from "@3lineas/groovepack/api-toast";
|
|
257
|
+
import { toastManager } from "@/components/ui/toast";
|
|
257
258
|
|
|
258
|
-
//
|
|
259
|
-
const
|
|
259
|
+
// Using the shared toast manager from Shadcn v4 (@/components/ui/toast)
|
|
260
|
+
export const appToast = createApiToast({
|
|
261
|
+
toast: toastManager,
|
|
262
|
+
locale: "es",
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
const res = await appToast({
|
|
260
266
|
action: () => createProductAction(values),
|
|
261
267
|
loadingMessage: "Guardando producto...",
|
|
262
|
-
successMessage:
|
|
268
|
+
successMessage: "Producto creado correctamente",
|
|
263
269
|
onSuccess: () => navigate("/products"),
|
|
264
270
|
});
|
|
265
271
|
|
|
266
|
-
//
|
|
267
|
-
await
|
|
272
|
+
// Or passing the toast manager directly per call
|
|
273
|
+
await apiToast({
|
|
274
|
+
toast: toastManager,
|
|
268
275
|
action: () => deleteProductAction(id),
|
|
269
276
|
loadingMessage: "Eliminando...",
|
|
270
277
|
});
|
|
271
|
-
|
|
272
|
-
// Custom project-wide defaults (e.g., English-only app)
|
|
273
|
-
export const enToast = createApiToast({
|
|
274
|
-
defaultLoadingMessage: "Processing...",
|
|
275
|
-
defaultSuccessMessage: "Completed successfully.",
|
|
276
|
-
defaultErrorMessage: "Something went wrong.",
|
|
277
|
-
});
|
|
278
278
|
```
|
|
279
279
|
|
|
280
280
|
---
|
|
@@ -317,7 +317,7 @@ export const enToast = createApiToast({
|
|
|
317
317
|
1. Explicit message string passed to the call or factory (`defaultErrorMessage`, `loadingMessage`, `successMessage`, `errorMessage`).
|
|
318
318
|
2. Explicit `locale` option (`apiAction({ locale: "es", ... })`, `apiToast({ locale: "pt", ... })`, `createApiToast({ locale: "fr" })`).
|
|
319
319
|
3. Runtime locale configured via `setGroovepackLocale("es")` from `@3lineas/groovepack/i18n`.
|
|
320
|
-
4. Environment variable (`GROOVEPACK_LOCALE
|
|
320
|
+
4. Environment variable (`GROOVEPACK_LOCALE` or `NEXT_PUBLIC_GROOVEPACK_LOCALE` in Vinext).
|
|
321
321
|
5. Default fallback: `"en"`.
|
|
322
322
|
|
|
323
323
|
```ts
|
package/dist/api-action/index.js
CHANGED
|
@@ -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":";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AAI;AAAA,IAC/D,UAAU,CAAC,UAAU,eAAe,iBAAiB,KAAK;AAAA,IAC1D,aAAa,MAAM,kBAAkB,eAAe;AAAA,EACtD;AACF;;;ACtDA,SAAS,UAAU;AASZ,SAAS,iBACd,SAA0B,CAAC,GAC3B;AACA,QAAM;AAAA,IACJ,UAAU;AAAA,IACV,kBAAkB;AAAA,IAClB;AAAA,IACA;AAAA,IACA,UAAU;AAAA,EACZ,IAAI;AAEJ,SAAO,GAAS,SAAS;AAAA,IACvB,OAAO,OAAO,OAA0B,SAAuB;AAC7D,YAAM,aACJ,OAAO,aAAa,eAAe,MAAM,gBAAgB;AAC3D,YAAM,UAAU,MAAM;AAAA,QACpB;AAAA,QACA;AAAA,QACA;AAAA,QACA,MAAM;AAAA,QACN;AAAA,MACF;AAEA,aAAO,QAAQ,OAAO;AAAA,QACpB,GAAG;AAAA,QACH;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -1,12 +1,32 @@
|
|
|
1
1
|
import { A as ActionResponse } from '../action-response.type-XlzII9Lr.js';
|
|
2
2
|
import { G as GroovepackLocale } from '../groovepack-locale.type-CaXo9vLj.js';
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Toast payload accepted by `@base-ui/react/toast` (`Toast.createToastManager()`).
|
|
6
|
+
*/
|
|
7
|
+
interface BaseUiToastPayload {
|
|
8
|
+
title?: string;
|
|
9
|
+
description?: string;
|
|
10
|
+
type?: "loading" | "success" | "error" | "info" | "warning" | (string & {});
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Contract for `@base-ui/react/toast` manager (`Toast.createToastManager()`).
|
|
15
|
+
*/
|
|
16
|
+
interface BaseUiToastManager {
|
|
17
|
+
add: (options: BaseUiToastPayload) => string;
|
|
18
|
+
update: (id: string, updates: BaseUiToastPayload) => void;
|
|
19
|
+
close: (id: string) => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
4
22
|
/**
|
|
5
23
|
* Options for `apiToast`.
|
|
6
24
|
*/
|
|
7
25
|
interface ApiToastOptions<T = unknown> {
|
|
8
26
|
/** Async action returning an `ActionResponse<T>`. */
|
|
9
27
|
action: () => Promise<ActionResponse<T>>;
|
|
28
|
+
/** Optional `@base-ui/react/toast` manager instance from `@/components/ui/toast`. */
|
|
29
|
+
toast?: BaseUiToastManager;
|
|
10
30
|
/** Optional locale override (`"en" | "es" | "pt" | "it" | "fr"`). */
|
|
11
31
|
locale?: GroovepackLocale;
|
|
12
32
|
/** Message displayed while the action is pending. */
|
|
@@ -25,6 +45,8 @@ interface ApiToastOptions<T = unknown> {
|
|
|
25
45
|
* Default configuration for `createApiToast`.
|
|
26
46
|
*/
|
|
27
47
|
interface ApiToastDefaults {
|
|
48
|
+
/** Optional `@base-ui/react/toast` manager instance from `@/components/ui/toast`. */
|
|
49
|
+
toast?: BaseUiToastManager;
|
|
28
50
|
/** Optional locale override (`"en" | "es" | "pt" | "it" | "fr"`). */
|
|
29
51
|
locale?: GroovepackLocale;
|
|
30
52
|
/** Default loading message when not specified per call. */
|
|
@@ -36,6 +58,7 @@ interface ApiToastDefaults {
|
|
|
36
58
|
}
|
|
37
59
|
type ToastedOptions<T = unknown> = {
|
|
38
60
|
action: () => Promise<ActionResponse<T>>;
|
|
61
|
+
toast?: BaseUiToastManager;
|
|
39
62
|
locale?: GroovepackLocale;
|
|
40
63
|
loadingMessage?: string;
|
|
41
64
|
successMessage?: string;
|
|
@@ -45,14 +68,13 @@ type ToastedOptions<T = unknown> = {
|
|
|
45
68
|
};
|
|
46
69
|
|
|
47
70
|
/**
|
|
48
|
-
* Factory creating a pre-configured `apiToast` helper
|
|
49
|
-
* messages and/or locale.
|
|
71
|
+
* Factory creating a pre-configured `apiToast` helper backed by Shadcn v4 (`@base-ui/react/toast`).
|
|
50
72
|
*/
|
|
51
|
-
declare function createApiToast(defaults?: ApiToastDefaults): <T = unknown>({ action, locale, loadingMessage, successMessage, errorMessage, onSuccess, onError, }: ApiToastOptions<T>) => Promise<ActionResponse<T>>;
|
|
73
|
+
declare function createApiToast(defaults?: ApiToastDefaults): <T = unknown>({ action, toast, locale, loadingMessage, successMessage, errorMessage, onSuccess, onError, }: ApiToastOptions<T>) => Promise<ActionResponse<T>>;
|
|
52
74
|
|
|
53
75
|
/**
|
|
54
|
-
* Wraps an `ActionResponse<T>` promise with `
|
|
76
|
+
* Wraps an `ActionResponse<T>` promise with Shadcn v4 (`@base-ui/react/toast`) loading, success, and error states.
|
|
55
77
|
*/
|
|
56
|
-
declare const apiToast: <T = unknown>({ action, locale, loadingMessage, successMessage, errorMessage, onSuccess, onError, }: ApiToastOptions<T>) => Promise<ActionResponse<T>>;
|
|
78
|
+
declare const apiToast: <T = unknown>({ action, toast, locale, loadingMessage, successMessage, errorMessage, onSuccess, onError, }: ApiToastOptions<T>) => Promise<ActionResponse<T>>;
|
|
57
79
|
|
|
58
|
-
export { ActionResponse, type ApiToastDefaults, type ApiToastOptions, type ToastedOptions, apiToast, createApiToast };
|
|
80
|
+
export { ActionResponse, type ApiToastDefaults, type ApiToastOptions, type BaseUiToastManager, type BaseUiToastPayload, type ToastedOptions, apiToast, createApiToast };
|
package/dist/api-toast/index.js
CHANGED
|
@@ -1,12 +1,51 @@
|
|
|
1
1
|
import {
|
|
2
2
|
resolveLocaleMessages
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-3FQ5C44Y.js";
|
|
4
|
+
|
|
5
|
+
// src/api-toast/resolve-toast-manager.ts
|
|
6
|
+
var MISSING_SHADCN_TOAST_MESSAGE = '[@3lineas/groovepack/api-toast] Shadcn Toast (@base-ui/react/toast) is not installed or configured. Run "pnpm dlx shadcn@latest add toast" and ensure "@base-ui/react" is installed.';
|
|
7
|
+
var defaultToastManager;
|
|
8
|
+
function isValidToastManager(candidate) {
|
|
9
|
+
if (typeof candidate !== "object" || candidate === null) {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
const record = candidate;
|
|
13
|
+
return typeof record["add"] === "function" && typeof record["update"] === "function";
|
|
14
|
+
}
|
|
15
|
+
async function resolveToastManager(customToast) {
|
|
16
|
+
if (customToast !== void 0) {
|
|
17
|
+
if (!isValidToastManager(customToast)) {
|
|
18
|
+
console.error(MISSING_SHADCN_TOAST_MESSAGE);
|
|
19
|
+
throw new Error(MISSING_SHADCN_TOAST_MESSAGE);
|
|
20
|
+
}
|
|
21
|
+
return customToast;
|
|
22
|
+
}
|
|
23
|
+
if (defaultToastManager) {
|
|
24
|
+
return defaultToastManager;
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
const baseUiToastModule = await import("@base-ui/react/toast");
|
|
28
|
+
const factory = baseUiToastModule.Toast?.createToastManager ?? baseUiToastModule.createToastManager;
|
|
29
|
+
if (typeof factory !== "function") {
|
|
30
|
+
throw new Error(MISSING_SHADCN_TOAST_MESSAGE);
|
|
31
|
+
}
|
|
32
|
+
const created = factory();
|
|
33
|
+
if (!isValidToastManager(created)) {
|
|
34
|
+
throw new Error(MISSING_SHADCN_TOAST_MESSAGE);
|
|
35
|
+
}
|
|
36
|
+
defaultToastManager = created;
|
|
37
|
+
return defaultToastManager;
|
|
38
|
+
} catch {
|
|
39
|
+
console.error(MISSING_SHADCN_TOAST_MESSAGE);
|
|
40
|
+
throw new Error(MISSING_SHADCN_TOAST_MESSAGE);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
4
43
|
|
|
5
44
|
// src/api-toast/create-api-toast.ts
|
|
6
|
-
import { toast } from "sonner";
|
|
7
45
|
function createApiToast(defaults = {}) {
|
|
8
46
|
return async function configuredApiToast({
|
|
9
47
|
action,
|
|
48
|
+
toast = defaults.toast,
|
|
10
49
|
locale = defaults.locale,
|
|
11
50
|
loadingMessage,
|
|
12
51
|
successMessage,
|
|
@@ -14,26 +53,39 @@ function createApiToast(defaults = {}) {
|
|
|
14
53
|
onSuccess,
|
|
15
54
|
onError
|
|
16
55
|
}) {
|
|
56
|
+
const toastManager = await resolveToastManager(toast);
|
|
17
57
|
const messages = resolveLocaleMessages(locale);
|
|
18
58
|
const resolvedLoading = loadingMessage ?? defaults.defaultLoadingMessage ?? messages.loading;
|
|
19
59
|
const resolvedSuccess = successMessage ?? defaults.defaultSuccessMessage ?? messages.success;
|
|
20
60
|
const resolvedError = errorMessage ?? defaults.defaultErrorMessage ?? messages.operationFailed;
|
|
21
|
-
const toastId =
|
|
61
|
+
const toastId = toastManager.add({
|
|
62
|
+
title: resolvedLoading,
|
|
63
|
+
type: "loading"
|
|
64
|
+
});
|
|
22
65
|
try {
|
|
23
66
|
const actionResult = await action();
|
|
24
67
|
if (actionResult.success) {
|
|
25
68
|
const displayMessage = actionResult.message ?? resolvedSuccess;
|
|
26
|
-
|
|
69
|
+
toastManager.update(toastId, {
|
|
70
|
+
title: displayMessage,
|
|
71
|
+
type: "success"
|
|
72
|
+
});
|
|
27
73
|
onSuccess?.(actionResult.data, actionResult);
|
|
28
74
|
return actionResult;
|
|
29
75
|
}
|
|
30
76
|
const displayError = actionResult.error ?? actionResult.message ?? resolvedError;
|
|
31
|
-
|
|
77
|
+
toastManager.update(toastId, {
|
|
78
|
+
title: displayError,
|
|
79
|
+
type: "error"
|
|
80
|
+
});
|
|
32
81
|
onError?.(displayError, actionResult);
|
|
33
82
|
return actionResult;
|
|
34
83
|
} catch (caughtError) {
|
|
35
84
|
const fallbackError = caughtError instanceof Error ? caughtError.message : resolvedError;
|
|
36
|
-
|
|
85
|
+
toastManager.update(toastId, {
|
|
86
|
+
title: fallbackError,
|
|
87
|
+
type: "error"
|
|
88
|
+
});
|
|
37
89
|
onError?.(fallbackError);
|
|
38
90
|
return {
|
|
39
91
|
success: false,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/api-toast/create-api-toast.ts","../../src/api-toast/index.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../src/api-toast/resolve-toast-manager.ts","../../src/api-toast/create-api-toast.ts","../../src/api-toast/index.ts"],"sourcesContent":["import type { BaseUiToastManager } from \"@/types/api-toast/base-ui-toast-manager.type\";\n\nconst MISSING_SHADCN_TOAST_MESSAGE =\n '[@3lineas/groovepack/api-toast] Shadcn Toast (@base-ui/react/toast) is not installed or configured. Run \"pnpm dlx shadcn@latest add toast\" and ensure \"@base-ui/react\" is installed.';\n\nlet defaultToastManager: BaseUiToastManager | undefined;\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\n/**\n * Resolves the active `@base-ui/react/toast` manager or throws a descriptive\n * error when Shadcn Toast (`@base-ui/react/toast`) is not installed.\n */\nexport async function resolveToastManager(\n customToast?: BaseUiToastManager,\n): Promise<BaseUiToastManager> {\n if (customToast !== undefined) {\n if (!isValidToastManager(customToast)) {\n console.error(MISSING_SHADCN_TOAST_MESSAGE);\n throw new Error(MISSING_SHADCN_TOAST_MESSAGE);\n }\n\n return customToast;\n }\n\n if (defaultToastManager) {\n return defaultToastManager;\n }\n\n try {\n const baseUiToastModule = (await import(\"@base-ui/react/toast\")) as {\n Toast?: { createToastManager?: () => BaseUiToastManager };\n createToastManager?: () => BaseUiToastManager;\n };\n const factory =\n baseUiToastModule.Toast?.createToastManager ??\n baseUiToastModule.createToastManager;\n\n if (typeof factory !== \"function\") {\n throw new Error(MISSING_SHADCN_TOAST_MESSAGE);\n }\n\n const created = factory();\n if (!isValidToastManager(created)) {\n throw new Error(MISSING_SHADCN_TOAST_MESSAGE);\n }\n\n defaultToastManager = created;\n return defaultToastManager;\n } catch {\n console.error(MISSING_SHADCN_TOAST_MESSAGE);\n throw new Error(MISSING_SHADCN_TOAST_MESSAGE);\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 v4 (`@base-ui/react/toast`).\n */\nexport function createApiToast(defaults: ApiToastDefaults = {}) {\n return async function configuredApiToast<T = unknown>({\n action,\n toast = defaults.toast,\n locale = defaults.locale,\n loadingMessage,\n successMessage,\n errorMessage,\n onSuccess,\n onError,\n }: ApiToastOptions<T>): Promise<ActionResponse<T>> {\n const toastManager = await resolveToastManager(toast);\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 = 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":";;;;;AAEA,IAAM,+BACJ;AAEF,IAAI;AAEJ,SAAS,oBACP,WACiC;AACjC,MAAI,OAAO,cAAc,YAAY,cAAc,MAAM;AACvD,WAAO;AAAA,EACT;AAEA,QAAM,SAAS;AACf,SACE,OAAO,OAAO,KAAK,MAAM,cACzB,OAAO,OAAO,QAAQ,MAAM;AAEhC;AAMA,eAAsB,oBACpB,aAC6B;AAC7B,MAAI,gBAAgB,QAAW;AAC7B,QAAI,CAAC,oBAAoB,WAAW,GAAG;AACrC,cAAQ,MAAM,4BAA4B;AAC1C,YAAM,IAAI,MAAM,4BAA4B;AAAA,IAC9C;AAEA,WAAO;AAAA,EACT;AAEA,MAAI,qBAAqB;AACvB,WAAO;AAAA,EACT;AAEA,MAAI;AACF,UAAM,oBAAqB,MAAM,OAAO,sBAAsB;AAI9D,UAAM,UACJ,kBAAkB,OAAO,sBACzB,kBAAkB;AAEpB,QAAI,OAAO,YAAY,YAAY;AACjC,YAAM,IAAI,MAAM,4BAA4B;AAAA,IAC9C;AAEA,UAAM,UAAU,QAAQ;AACxB,QAAI,CAAC,oBAAoB,OAAO,GAAG;AACjC,YAAM,IAAI,MAAM,4BAA4B;AAAA,IAC9C;AAEA,0BAAsB;AACtB,WAAO;AAAA,EACT,QAAQ;AACN,YAAQ,MAAM,4BAA4B;AAC1C,UAAM,IAAI,MAAM,4BAA4B;AAAA,EAC9C;AACF;;;ACxDO,SAAS,eAAe,WAA6B,CAAC,GAAG;AAC9D,SAAO,eAAe,mBAAgC;AAAA,IACpD;AAAA,IACA,QAAQ,SAAS;AAAA,IACjB,SAAS,SAAS;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAAmD;AACjD,UAAM,eAAe,MAAM,oBAAoB,KAAK;AACpD,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,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;;;ACvDO,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,21 +30,24 @@ 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
|
|
@@ -127,4 +116,4 @@ export {
|
|
|
127
116
|
GROOVEPACK_MESSAGES,
|
|
128
117
|
resolveLocaleMessages
|
|
129
118
|
};
|
|
130
|
-
//# sourceMappingURL=chunk-
|
|
119
|
+
//# sourceMappingURL=chunk-3FQ5C44Y.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 { 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,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,YAAY,aAAa,MAAM;AACrD,WAAO;AAAA,EACT;AAEA,QAAM,SAAS;AACf,aAAW,OAAO,iBAAiB;AACjC,UAAM,aAAa,yBAAyB,OAAO,GAAG,CAAC;AACvD,QAAI,YAAY;AACd,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;AAEA,SAAS,2BAAyD;AAChE,MAAI;AACF,WACE,yBAAyB,YAAY,KAAK,iBAAiB,KAC3D,yBAAyB,YAAY,KAAK,6BAA6B;AAAA,EAE3E,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMO,SAAS,gBAA8C;AAC5D,SAAO,yBAAyB,KAAK,yBAAyB;AAChE;;;AC5CA,IAAI;AAOG,SAAS,oBAAoB,QAA4C;AAC9E,MAAI,WAAW,QAAW;AACxB,uBAAmB;AACnB;AAAA,EACF;AAEA,qBAAmB,yBAAyB,MAAM;AACpD;AASO,SAAS,oBACd,gBACkB;AAClB,SACE,yBAAyB,cAAc,KACvC,oBACA,cAAc,KACd;AAEJ;;;ACjCO,IAAM,sBAAsB;AAAA,EACjC,IAAI;AAAA,IACF,SAAS;AAAA,IACT,SAAS;AAAA,IACT,iBACE;AAAA,IACF,qBACE;AAAA,IACF,iBAAiB;AAAA,EACnB;AAAA,EACA,IAAI;AAAA,IACF,SAAS;AAAA,IACT,SAAS;AAAA,IACT,iBACE;AAAA,IACF,qBACE;AAAA,IACF,iBAAiB;AAAA,EACnB;AAAA,EACA,IAAI;AAAA,IACF,SAAS;AAAA,IACT,SAAS;AAAA,IACT,iBACE;AAAA,IACF,qBACE;AAAA,IACF,iBAAiB;AAAA,EACnB;AAAA,EACA,IAAI;AAAA,IACF,SAAS;AAAA,IACT,SAAS;AAAA,IACT,iBACE;AAAA,IACF,qBACE;AAAA,IACF,iBAAiB;AAAA,EACnB;AAAA,EACA,IAAI;AAAA,IACF,SAAS;AAAA,IACT,SAAS;AAAA,IACT,iBACE;AAAA,IACF,qBACE;AAAA,IACF,iBAAiB;AAAA,EACnB;AACF;;;ACxCO,SAAS,sBACd,gBAC0B;AAC1B,QAAM,eAAe,oBAAoB,cAAc;AACvD,SAAO,oBAAoB,YAAY;AACzC;","names":[]}
|
package/dist/i18n/index.d.ts
CHANGED
|
@@ -53,9 +53,8 @@ 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
|
|
package/dist/i18n/index.js
CHANGED
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;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,G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1.2.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,
|
|
@@ -56,21 +56,20 @@
|
|
|
56
56
|
"test": "tsx --test test/*.test.ts"
|
|
57
57
|
},
|
|
58
58
|
"peerDependencies": {
|
|
59
|
-
"
|
|
60
|
-
"
|
|
59
|
+
"@base-ui/react": ">=1.0.0",
|
|
60
|
+
"hono": ">=4.0.0"
|
|
61
61
|
},
|
|
62
62
|
"peerDependenciesMeta": {
|
|
63
|
-
"
|
|
63
|
+
"@base-ui/react": {
|
|
64
64
|
"optional": true
|
|
65
65
|
},
|
|
66
|
-
"
|
|
66
|
+
"hono": {
|
|
67
67
|
"optional": true
|
|
68
68
|
}
|
|
69
69
|
},
|
|
70
70
|
"devDependencies": {
|
|
71
71
|
"@types/node": "^22.10.1",
|
|
72
72
|
"hono": "^4.7.0",
|
|
73
|
-
"sonner": "^2.0.0",
|
|
74
73
|
"tsup": "^8.3.5",
|
|
75
74
|
"tsx": "^4.19.2",
|
|
76
75
|
"typescript": "^5.7.2"
|
|
@@ -83,7 +82,8 @@
|
|
|
83
82
|
"logger",
|
|
84
83
|
"api-client",
|
|
85
84
|
"api-action",
|
|
86
|
-
"
|
|
85
|
+
"base-ui",
|
|
86
|
+
"shadcn"
|
|
87
87
|
],
|
|
88
88
|
"author": "3lineas",
|
|
89
89
|
"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,WAC8B;AAC9B,MAAI,OAAO,cAAc,UAAU;AACjC,WAAO;AAAA,EACT;A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