@3lineas/groovepack 0.1.4 → 1.1.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 +261 -138
- package/dist/action-response.type-XlzII9Lr.d.ts +11 -0
- package/dist/api-action/index.d.ts +44 -0
- package/dist/api-action/index.js +105 -0
- package/dist/api-action/index.js.map +1 -0
- package/dist/api-client/index.d.ts +46 -0
- package/dist/api-client/index.js +142 -0
- package/dist/api-client/index.js.map +1 -0
- package/dist/api-toast/index.d.ts +58 -0
- package/dist/api-toast/index.js +52 -0
- package/dist/api-toast/index.js.map +1 -0
- package/dist/batch-capable-db.type-Cyybxkjc.d.ts +8 -0
- package/dist/chunk-PDWE3D4J.js +130 -0
- package/dist/chunk-PDWE3D4J.js.map +1 -0
- package/dist/groovepack-locale.type-CaXo9vLj.d.ts +3 -0
- package/dist/i18n/index.d.ts +83 -0
- package/dist/i18n/index.js +17 -0
- package/dist/i18n/index.js.map +1 -0
- package/dist/logger/index.d.ts +19 -0
- package/dist/logger/index.js +92 -0
- package/dist/logger/index.js.map +1 -0
- package/dist/pipeline/pipeline.d.ts +41 -0
- package/dist/pipeline/pipeline.js +64 -0
- package/dist/pipeline/pipeline.js.map +1 -0
- package/dist/pipeline/with-d1-transaction.d.ts +16 -0
- package/dist/pipeline/with-d1-transaction.js +17 -0
- package/dist/pipeline/with-d1-transaction.js.map +1 -0
- package/package.json +55 -16
- package/dist/index.js +0 -468
- package/dist/index.js.map +0 -1
- package/registry/common/api-client/files/README.md.template +0 -64
- package/registry/common/api-client/files/index.ts.template +0 -296
- package/registry/common/logger/files/README.md.template +0 -55
- package/registry/common/logger/files/index.ts.template +0 -194
- package/registry/react/api-action/files/README.md.template +0 -61
- package/registry/react/api-action/files/index.ts.template +0 -291
- package/registry/react/api-toast/files/README.md.template +0 -51
- package/registry/react/api-toast/files/index.ts.template +0 -169
- package/registry/server/pipeline/files/README.md.template +0 -205
- package/registry/server/pipeline/files/pipeline.ts.template +0 -134
- package/registry/server/pipeline/files/types.ts.template +0 -35
- package/registry/server/pipeline/files/with-d1-transaction.ts.template +0 -50
package/README.md
CHANGED
|
@@ -1,204 +1,327 @@
|
|
|
1
|
-
|
|
1
|
+
# `@3lineas/groovepack`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Zero-dependency & modular infrastructure primitives for **TypeScript**, **Cloudflare Workers (D1, Hono)**, **React**, and **Astro**.
|
|
4
4
|
|
|
5
|
-
|
|
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 Sonner toast orchestration — exposed via **Subpath Exports** with `sideEffects: false` and **optional peer dependencies**.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
---
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
[](https://www.typescriptlang.org/)
|
|
11
|
-
[](https://github.com/natemoo-re/clack)
|
|
12
|
-
[](#)
|
|
9
|
+
## Table of Contents
|
|
13
10
|
|
|
14
|
-
|
|
11
|
+
- [Why Subpath Exports?](#why-subpath-exports)
|
|
12
|
+
- [Installation](#installation)
|
|
13
|
+
- [Available Modules](#available-modules)
|
|
14
|
+
- [1. `@3lineas/groovepack/logger`](#1-3lineasgroovepacklogger)
|
|
15
|
+
- [2. `@3lineas/groovepack/pipeline`](#2-3lineasgroovepackpipeline)
|
|
16
|
+
- [3. `@3lineas/groovepack/pipeline/with-d1-transaction`](#3-3lineasgroovepackpipelinewith-d1-transaction)
|
|
17
|
+
- [4. `@3lineas/groovepack/api-client`](#4-3lineasgroovepackapi-client)
|
|
18
|
+
- [5. `@3lineas/groovepack/api-action`](#5-3lineasgroovepackapi-action)
|
|
19
|
+
- [6. `@3lineas/groovepack/api-toast`](#6-3lineasgroovepackapi-toast)
|
|
20
|
+
- [End-to-End Architecture Example](#end-to-end-architecture-example)
|
|
21
|
+
- [Migrating from v0.x (CLI Copy-Paste)](#migrating-from-v0x-cli-copy-paste)
|
|
15
22
|
|
|
16
23
|
---
|
|
17
24
|
|
|
18
|
-
##
|
|
25
|
+
## Why Subpath Exports?
|
|
26
|
+
|
|
27
|
+
- **Zero Dead Weight**: Backend workers importing `/logger` and `/pipeline` never bundle `sonner` or frontend code. Frontend apps importing `/api-toast` never bundle server utilities.
|
|
28
|
+
- **No Barrel Files**: Every module has its own dedicated entry point for optimal tree-shaking.
|
|
29
|
+
- **Immutable Infrastructure**: Lives in `node_modules` with SemVer guarantees, preventing accidental local drift across monorepo apps.
|
|
19
30
|
|
|
20
|
-
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
21
34
|
|
|
22
35
|
```bash
|
|
23
|
-
|
|
36
|
+
pnpm add @3lineas/groovepack
|
|
24
37
|
```
|
|
25
38
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
39
|
+
### Optional Peer Dependencies
|
|
40
|
+
|
|
41
|
+
Install only what your app actually uses:
|
|
42
|
+
|
|
43
|
+
| Subpath | Required Peer Dependency | Target Environment |
|
|
44
|
+
| :--- | :--- | :--- |
|
|
45
|
+
| `/logger` | *None (0 deps)* | Node, Cloudflare Workers, Browser |
|
|
46
|
+
| `/pipeline` | *None (0 deps)* | Cloudflare Workers, Node |
|
|
47
|
+
| `/pipeline/with-d1-transaction` | *None (0 deps)* | Cloudflare Workers (D1 / Drizzle) |
|
|
48
|
+
| `/api-action` | *None (0 deps)* | React, Astro, Next.js, Node |
|
|
49
|
+
| `/api-client` | `hono >= 4.0.0` *(only if using `createHonoClient`)* | Frontend / Edge |
|
|
50
|
+
| `/api-toast` | `sonner >= 1.0.0` | React / Browser |
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## Available Modules
|
|
55
|
+
|
|
56
|
+
1. `@3lineas/groovepack/logger` — Structured Logger (ANSI in dev, JSON in prod).
|
|
57
|
+
2. `@3lineas/groovepack/pipeline` — Laravel-inspired sequential `Pipeline` with D1 batching.
|
|
58
|
+
3. `@3lineas/groovepack/pipeline/with-d1-transaction` — Standalone `withD1Transaction` wrapper.
|
|
59
|
+
4. `@3lineas/groovepack/api-client` — `createApiClient` (REST) & `createHonoClient` (Hono RPC).
|
|
60
|
+
5. `@3lineas/groovepack/api-action` — Polymorphic `apiAction` wrapper returning `ActionResponse<T>`.
|
|
61
|
+
6. `@3lineas/groovepack/api-toast` — `apiToast`, `toasted`, and `createApiToast` for Sonner.
|
|
31
62
|
|
|
32
63
|
---
|
|
33
64
|
|
|
34
|
-
##
|
|
65
|
+
## 1. `@3lineas/groovepack/logger`
|
|
35
66
|
|
|
36
|
-
|
|
37
|
-
-
|
|
38
|
-
-
|
|
39
|
-
- Overhead in CI/CD pipelines.
|
|
67
|
+
Universal structured logger that automatically adapts to the runtime:
|
|
68
|
+
- **Development / Test** (`NODE_ENV === "development"` or `"test"`): Outputs readable, ANSI-colored console logs.
|
|
69
|
+
- **Production / Cloudflare Workers**: Outputs single-line structured JSON for log indexing.
|
|
40
70
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
71
|
+
```typescript
|
|
72
|
+
import { Logger, type LogContext } from "@3lineas/groovepack/logger";
|
|
73
|
+
|
|
74
|
+
const logger = new Logger("API:Sales");
|
|
75
|
+
|
|
76
|
+
logger.debug("Validating cart items", { itemCount: 3 });
|
|
77
|
+
logger.info("Sale completed", { saleId: "sal_123", totalCents: 4500 });
|
|
78
|
+
logger.warn("Low inventory", { productId: "prod_9", remaining: 2 });
|
|
79
|
+
|
|
80
|
+
try {
|
|
81
|
+
await processPayment();
|
|
82
|
+
} catch (error) {
|
|
83
|
+
logger.error("Payment gateway timeout", { file: "checkout.ts", line: 42 }, error);
|
|
84
|
+
}
|
|
85
|
+
```
|
|
46
86
|
|
|
47
87
|
---
|
|
48
88
|
|
|
49
|
-
##
|
|
89
|
+
## 2. `@3lineas/groovepack/pipeline`
|
|
50
90
|
|
|
51
|
-
|
|
91
|
+
Sequential multi-action processor inspired by Laravel's `Pipeline`.
|
|
92
|
+
Each step is an isolated atomic function `(context: TContext) => Promise<TContext> | TContext`.
|
|
52
93
|
|
|
53
|
-
|
|
54
|
-
Universal structured logger designed for seamless local development and production observability.
|
|
55
|
-
- **Local Development**: Human-readable ANSI color-coded terminal output with `[file:line]` context tracing.
|
|
56
|
-
- **Production / Cloudflare Workers**: Fast, structured JSON serialization compatible with log aggregators (Datadog, Cloudflare Logpush, Axiom).
|
|
57
|
-
- **Default Target**: `src/lib/logger`
|
|
94
|
+
### Basic Usage
|
|
58
95
|
|
|
59
96
|
```typescript
|
|
60
|
-
import {
|
|
97
|
+
import { Pipeline, type PipeAction } from "@3lineas/groovepack/pipeline";
|
|
61
98
|
|
|
62
|
-
|
|
99
|
+
interface OrderContext {
|
|
100
|
+
items: Array<{ id: string; price: number }>;
|
|
101
|
+
total: number;
|
|
102
|
+
}
|
|
63
103
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
104
|
+
const calculateTotal: PipeAction<OrderContext> = (ctx) => ({
|
|
105
|
+
...ctx,
|
|
106
|
+
total: ctx.items.reduce((acc, item) => acc + item.price, 0),
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
const result = await Pipeline.send<OrderContext>({ items: [{ id: "1", price: 500 }], total: 0 })
|
|
110
|
+
.through([calculateTotal])
|
|
111
|
+
.thenReturn();
|
|
67
112
|
```
|
|
68
113
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
-
|
|
73
|
-
-
|
|
74
|
-
- **
|
|
114
|
+
### Transactional Mode with Cloudflare D1 / Drizzle ORM
|
|
115
|
+
|
|
116
|
+
Calling `.transactional(db)` injects `tx: D1TransactionContext` into `context.tx`.
|
|
117
|
+
- Mutations staged via `context.tx.stage(...)` are held in memory.
|
|
118
|
+
- When `.thenReturn()` or `.then()` finishes, all staged statements are committed atomically via `db.batch()`.
|
|
119
|
+
- **Preventive In-Memory Rollback**: If any pipe throws an error, `db.batch()` is **never called** — zero mutations reach D1.
|
|
75
120
|
|
|
76
121
|
```typescript
|
|
77
|
-
import {
|
|
78
|
-
import type { AppType } from "api";
|
|
122
|
+
import { Pipeline, type D1TransactionContext, type PipeAction } from "@3lineas/groovepack/pipeline";
|
|
79
123
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
124
|
+
interface CreateSaleContext {
|
|
125
|
+
input: { productId: string; quantity: number };
|
|
126
|
+
tx?: D1TransactionContext<D1Database, D1PreparedStatement>;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const validateStock: PipeAction<CreateSaleContext> = async (ctx) => {
|
|
130
|
+
const row = await ctx.tx!.db
|
|
131
|
+
.prepare("SELECT stock FROM products WHERE id = ?")
|
|
132
|
+
.bind(ctx.input.productId)
|
|
133
|
+
.first<{ stock: number }>();
|
|
134
|
+
|
|
135
|
+
if (!row || row.stock < ctx.input.quantity) {
|
|
136
|
+
throw new Error("Insufficient stock");
|
|
137
|
+
}
|
|
138
|
+
return ctx;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const stageSale: PipeAction<CreateSaleContext> = (ctx) => {
|
|
142
|
+
ctx.tx!.stage(
|
|
143
|
+
ctx.tx!.db
|
|
144
|
+
.prepare("UPDATE products SET stock = stock - ? WHERE id = ?")
|
|
145
|
+
.bind(ctx.input.quantity, ctx.input.productId),
|
|
146
|
+
ctx.tx!.db
|
|
147
|
+
.prepare("INSERT INTO sales (product_id, quantity) VALUES (?, ?)")
|
|
148
|
+
.bind(ctx.input.productId, ctx.input.quantity),
|
|
149
|
+
);
|
|
150
|
+
return ctx;
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
await Pipeline.send<CreateSaleContext>({ input: { productId: "p1", quantity: 2 } })
|
|
154
|
+
.transactional(env.DB)
|
|
155
|
+
.through([validateStock, stageSale])
|
|
156
|
+
.thenReturn();
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
## 3. `@3lineas/groovepack/pipeline/with-d1-transaction`
|
|
162
|
+
|
|
163
|
+
Standalone transactional helper for workflows that don't need the full `Pipeline` class:
|
|
164
|
+
|
|
165
|
+
```typescript
|
|
166
|
+
import { withD1Transaction } from "@3lineas/groovepack/pipeline/with-d1-transaction";
|
|
167
|
+
|
|
168
|
+
const saleId = await withD1Transaction(env.DB, async (tx) => {
|
|
169
|
+
const user = await tx.db.prepare("SELECT id FROM users WHERE id = ?").bind(userId).first();
|
|
170
|
+
if (!user) throw new Error("User not found");
|
|
171
|
+
|
|
172
|
+
tx.stage(
|
|
173
|
+
tx.db.prepare("INSERT INTO sales (id, user_id) VALUES (?, ?)").bind("s_1", userId),
|
|
174
|
+
tx.db.prepare("UPDATE users SET last_sale_at = ? WHERE id = ?").bind(Date.now(), userId),
|
|
175
|
+
);
|
|
176
|
+
|
|
177
|
+
return "s_1";
|
|
84
178
|
});
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
---
|
|
182
|
+
|
|
183
|
+
## 4. `@3lineas/groovepack/api-client`
|
|
184
|
+
|
|
185
|
+
Unified factory for both **REST** (`createApiClient`) and **Hono RPC** (`createHonoClient`), with automatic `Authorization: Bearer <token>` injection and `BigInt`-safe JSON serialization.
|
|
85
186
|
|
|
86
|
-
|
|
187
|
+
### Hono RPC Client
|
|
188
|
+
|
|
189
|
+
```typescript
|
|
190
|
+
import { createHonoClient } from "@3lineas/groovepack/api-client";
|
|
191
|
+
import type { AppType } from "api";
|
|
87
192
|
|
|
88
|
-
// 2. Hono RPC Client (Optional)
|
|
89
193
|
export const rpc = createHonoClient<AppType>({
|
|
90
|
-
baseUrl:
|
|
194
|
+
baseUrl: import.meta.env.VITE_API_URL,
|
|
195
|
+
getToken: () => localStorage.getItem("auth_token"),
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
// Full end-to-end type inference
|
|
199
|
+
const res = await rpc.v1.products.$get();
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
### REST Client & Token Helpers
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
import {
|
|
206
|
+
createApiClient,
|
|
207
|
+
getStoredToken,
|
|
208
|
+
setStoredToken,
|
|
209
|
+
removeStoredToken,
|
|
210
|
+
} from "@3lineas/groovepack/api-client";
|
|
211
|
+
|
|
212
|
+
export const api = createApiClient({
|
|
213
|
+
baseUrl: "https://api.example.com/v1",
|
|
214
|
+
tokenStorageKey: "auth_token",
|
|
215
|
+
headers: { "X-App-Version": "1.0.0" },
|
|
91
216
|
});
|
|
92
|
-
|
|
217
|
+
|
|
218
|
+
const response = await api.post("/orders", { total: BigInt(1500) });
|
|
93
219
|
```
|
|
94
220
|
|
|
95
221
|
---
|
|
96
222
|
|
|
97
|
-
|
|
223
|
+
## 5. `@3lineas/groovepack/api-action`
|
|
98
224
|
|
|
99
|
-
|
|
100
|
-
Universal async operation and API wrapper for React components, Server Actions, and custom hooks.
|
|
101
|
-
- **Polymorphic Compatibility**: Natively accepts Hono RPC responses, standard `fetch` (`Response`), structured `ActionResponse<T>`, or raw promises.
|
|
102
|
-
- **Strict Error-Only Logging**: Only logs on actual failures (`!response.ok`, `!result.success`, or unexpected runtime crashes). Does not pollute console logs on successful operations.
|
|
103
|
-
- **Default Target**: `src/lib/api-action`
|
|
225
|
+
Polymorphic wrapper that normalizes Hono RPC responses, standard `fetch` responses, `ActionResponse<T>`, or raw promises into a predictable `ActionResponse<T>` contract. Logs **exclusively on errors**.
|
|
104
226
|
|
|
105
227
|
```typescript
|
|
106
|
-
import { apiAction } from "
|
|
107
|
-
import {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
228
|
+
import { apiAction, type ActionResponse } from "@3lineas/groovepack/api-action";
|
|
229
|
+
import { Logger } from "@3lineas/groovepack/logger";
|
|
230
|
+
import { rpc } from "@/lib/rpc";
|
|
231
|
+
|
|
232
|
+
const logger = new Logger("Web:Products");
|
|
233
|
+
|
|
234
|
+
export async function createProductAction(
|
|
235
|
+
input: { name: string; price: number },
|
|
236
|
+
): Promise<ActionResponse<Product>> {
|
|
237
|
+
return apiAction<Product>({
|
|
238
|
+
actionName: "createProduct",
|
|
239
|
+
logger,
|
|
240
|
+
defaultErrorMessage: "Could not create product. Please try again.",
|
|
241
|
+
apiCall: () => rpc.v1.products.$post({ json: input }),
|
|
242
|
+
onSuccess: (product) => {
|
|
243
|
+
console.log("Created:", product.id);
|
|
115
244
|
},
|
|
116
245
|
});
|
|
117
246
|
}
|
|
118
247
|
```
|
|
119
248
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
- **Default Target**: `src/lib/api-toast`
|
|
249
|
+
---
|
|
250
|
+
|
|
251
|
+
## 6. `@3lineas/groovepack/api-toast`
|
|
252
|
+
|
|
253
|
+
Orchestrates async actions with **Sonner** loading, success, and error toasts, returning the resolved `ActionResponse<T>`.
|
|
126
254
|
|
|
127
255
|
```typescript
|
|
128
|
-
import { apiToast } from "
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
const
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
onError: (err) => console.error("Login failed:", err),
|
|
138
|
-
});
|
|
256
|
+
import { apiToast, toasted, createApiToast } from "@3lineas/groovepack/api-toast";
|
|
257
|
+
|
|
258
|
+
// Standard usage (Spanish defaults)
|
|
259
|
+
const res = await apiToast({
|
|
260
|
+
action: () => createProductAction(values),
|
|
261
|
+
loadingMessage: "Guardando producto...",
|
|
262
|
+
successMessage: (r) => `Producto "${r.data?.name}" creado`,
|
|
263
|
+
onSuccess: () => navigate("/products"),
|
|
264
|
+
});
|
|
139
265
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
266
|
+
// Backward-compatible alias
|
|
267
|
+
await toasted({
|
|
268
|
+
action: () => deleteProductAction(id),
|
|
269
|
+
loadingMessage: "Eliminando...",
|
|
270
|
+
});
|
|
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
|
+
});
|
|
144
278
|
```
|
|
145
279
|
|
|
146
280
|
---
|
|
147
281
|
|
|
148
|
-
|
|
282
|
+
## End-to-End Architecture Example
|
|
149
283
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
```typescript
|
|
159
|
-
import { Pipeline } from "@/lib/pipeline/pipeline";
|
|
160
|
-
import type { D1TransactionContext } from "@/lib/pipeline/types";
|
|
284
|
+
```text
|
|
285
|
+
[React Form]
|
|
286
|
+
└─> apiToast({ action: () => createSaleAction(data) }) (@3lineas/groovepack/api-toast)
|
|
287
|
+
└─> apiAction({ apiCall: () => rpc.v1.sales.$post() }) (@3lineas/groovepack/api-action)
|
|
288
|
+
└─> createHonoClient<AppType>() (@3lineas/groovepack/api-client)
|
|
289
|
+
└─> [Hono API Worker]
|
|
290
|
+
└─> Pipeline.send(ctx).transactional(db).through([...]) (@3lineas/groovepack/pipeline)
|
|
291
|
+
```
|
|
161
292
|
|
|
162
|
-
|
|
163
|
-
const result = await Pipeline.send<UserContext>({ db: env.DB, input })
|
|
164
|
-
.transactional(env.DB)
|
|
165
|
-
.through([
|
|
166
|
-
async (ctx) => {
|
|
167
|
-
// Immediate read
|
|
168
|
-
const existing = await ctx.tx!.db.prepare("SELECT id FROM users WHERE email = ?").bind(ctx.input.email).first();
|
|
169
|
-
if (existing) throw new Error("Email already registered");
|
|
170
|
-
|
|
171
|
-
// Stage atomic mutation
|
|
172
|
-
ctx.tx!.stage(
|
|
173
|
-
ctx.tx!.db.prepare("INSERT INTO users (id, email) VALUES (?, ?)").bind(newId, ctx.input.email)
|
|
174
|
-
);
|
|
175
|
-
return ctx;
|
|
176
|
-
}
|
|
177
|
-
])
|
|
178
|
-
.thenReturn();
|
|
293
|
+
---
|
|
179
294
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
```
|
|
295
|
+
## Migrating from v0.x (CLI Copy-Paste)
|
|
296
|
+
|
|
297
|
+
1. Install the package:
|
|
298
|
+
```bash
|
|
299
|
+
pnpm add @3lineas/groovepack
|
|
300
|
+
```
|
|
301
|
+
2. Replace local `@/lib/*` imports with package subpath imports:
|
|
302
|
+
- `@/lib/logger` $\rightarrow$ `@3lineas/groovepack/logger`
|
|
303
|
+
- `@/lib/pipeline/pipeline` $\rightarrow$ `@3lineas/groovepack/pipeline`
|
|
304
|
+
- `@/lib/pipeline/with-d1-transaction` $\rightarrow$ `@3lineas/groovepack/pipeline/with-d1-transaction`
|
|
305
|
+
- `@/lib/api-client` $\rightarrow$ `@3lineas/groovepack/api-client`
|
|
306
|
+
- `@/lib/api-action` $\rightarrow$ `@3lineas/groovepack/api-action`
|
|
307
|
+
- `@/lib/api-toast` $\rightarrow$ `@3lineas/groovepack/api-toast`
|
|
308
|
+
3. Remove the copied files from `src/lib/` once imports are updated.
|
|
186
309
|
|
|
187
310
|
---
|
|
188
311
|
|
|
189
|
-
##
|
|
312
|
+
## Internationalization (`@3lineas/groovepack/i18n`)
|
|
190
313
|
|
|
191
|
-
|
|
192
|
-
1. Tracks all filesystem operations and directories created during the transaction.
|
|
193
|
-
2. Backs up pre-existing destination files in memory before applying changes.
|
|
194
|
-
3. If an error occurs (such as permission denials, path errors, or disk write failures):
|
|
195
|
-
- Restores original file contents.
|
|
196
|
-
- Removes newly written files.
|
|
197
|
-
- Cleans up empty directory segments.
|
|
198
|
-
- Reports the exact failure cause in the terminal **without crashing or interrupting the installation of other selected packages**.
|
|
314
|
+
`apiAction` and `apiToast` ship with a zero-dependency **5-language dictionary** (`en`, `es`, `pt`, `it`, `fr`) defaulting to **English (`"en"`)**.
|
|
199
315
|
|
|
200
|
-
|
|
316
|
+
### Resolution Precedence (Highest to Lowest)
|
|
317
|
+
1. Explicit message string passed to the call or factory (`defaultErrorMessage`, `loadingMessage`, `successMessage`, `errorMessage`).
|
|
318
|
+
2. Explicit `locale` option (`apiAction({ locale: "es", ... })`, `apiToast({ locale: "pt", ... })`, `createApiToast({ locale: "fr" })`).
|
|
319
|
+
3. Runtime locale configured via `setGroovepackLocale("es")` from `@3lineas/groovepack/i18n`.
|
|
320
|
+
4. Environment variable (`GROOVEPACK_LOCALE`, `NEXT_PUBLIC_GROOVEPACK_LOCALE`, `VITE_GROOVEPACK_LOCALE`, `PUBLIC_GROOVEPACK_LOCALE`).
|
|
321
|
+
5. Default fallback: `"en"`.
|
|
201
322
|
|
|
202
|
-
|
|
323
|
+
```ts
|
|
324
|
+
import { setGroovepackLocale } from "@3lineas/groovepack/i18n";
|
|
203
325
|
|
|
204
|
-
|
|
326
|
+
setGroovepackLocale("es");
|
|
327
|
+
```
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { A as ActionResponse } from '../action-response.type-XlzII9Lr.js';
|
|
2
|
+
import { G as GroovepackLocale } from '../groovepack-locale.type-CaXo9vLj.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Minimal `Response`-like contract compatible with `fetch`, Hono `ClientResponse`,
|
|
6
|
+
* and custom test mocks.
|
|
7
|
+
*/
|
|
8
|
+
interface MinimalResponse {
|
|
9
|
+
ok: boolean;
|
|
10
|
+
status: number;
|
|
11
|
+
json: () => Promise<unknown>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Supported return types from an `apiCall` passed to `apiAction`.
|
|
16
|
+
*/
|
|
17
|
+
type ApiCallResult<T> = MinimalResponse | ActionResponse<T>;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Optional error logger callback invoked when `apiAction` catches an unexpected error.
|
|
21
|
+
*/
|
|
22
|
+
type ErrorLogger = (message: string, context?: Record<string, unknown>) => void;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Options for `apiAction`.
|
|
26
|
+
*/
|
|
27
|
+
interface ApiActionOptions<T = unknown> {
|
|
28
|
+
/** Async call returning either a `Response`/`ClientResponse` or an `ActionResponse<T>`. */
|
|
29
|
+
apiCall: () => Promise<ApiCallResult<T>>;
|
|
30
|
+
/** Optional locale override (`"en" | "es" | "pt" | "it" | "fr"`). */
|
|
31
|
+
locale?: GroovepackLocale;
|
|
32
|
+
/** Default fallback error message when the server does not provide one. */
|
|
33
|
+
defaultErrorMessage?: string;
|
|
34
|
+
/** Optional logger for unexpected exceptions or malformed payloads. */
|
|
35
|
+
onError?: ErrorLogger;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Universal wrapper for API calls (Hono RPC, `fetch`, or Server Actions)
|
|
40
|
+
* guaranteeing a standardized `ActionResponse<T>` without throwing uncaught errors.
|
|
41
|
+
*/
|
|
42
|
+
declare function apiAction<T = unknown>({ apiCall, locale, defaultErrorMessage, onError, }: ApiActionOptions<T>): Promise<ActionResponse<T>>;
|
|
43
|
+
|
|
44
|
+
export { ActionResponse, type ApiActionOptions, type ApiCallResult, type ErrorLogger, type MinimalResponse, apiAction };
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import {
|
|
2
|
+
resolveLocaleMessages
|
|
3
|
+
} from "../chunk-PDWE3D4J.js";
|
|
4
|
+
|
|
5
|
+
// src/api-action/default-error-logger.ts
|
|
6
|
+
var defaultErrorLogger = (message, context) => {
|
|
7
|
+
if (context) {
|
|
8
|
+
console.error(`[apiAction] ${message}`, context);
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
console.error(`[apiAction] ${message}`);
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
// src/api-action/is-minimal-response.ts
|
|
15
|
+
function isMinimalResponse(candidateValue) {
|
|
16
|
+
return typeof candidateValue === "object" && candidateValue !== null && "ok" in candidateValue && typeof candidateValue.ok === "boolean" && "status" in candidateValue && typeof candidateValue.status === "number" && "json" in candidateValue && typeof candidateValue.json === "function";
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// src/api-action/is-action-response.ts
|
|
20
|
+
function isActionResponse(candidateValue) {
|
|
21
|
+
return typeof candidateValue === "object" && candidateValue !== null && "success" in candidateValue && typeof candidateValue.success === "boolean";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// src/api-action/try-parse-json.ts
|
|
25
|
+
async function tryParseJson(response) {
|
|
26
|
+
try {
|
|
27
|
+
const parsed = await response.json();
|
|
28
|
+
if (typeof parsed === "object" && parsed !== null) {
|
|
29
|
+
return parsed;
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
} catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/api-action/handle-http-response.ts
|
|
38
|
+
async function handleHttpResponse(response, fallbackErrorMessage, serverRequestFailedMessage, logError) {
|
|
39
|
+
const payload = await tryParseJson(response);
|
|
40
|
+
if (!response.ok) {
|
|
41
|
+
const serverError = payload && typeof payload["error"] === "string" ? payload["error"] : void 0;
|
|
42
|
+
const serverMessage = payload && typeof payload["message"] === "string" ? payload["message"] : void 0;
|
|
43
|
+
return {
|
|
44
|
+
success: false,
|
|
45
|
+
error: serverError ?? serverMessage ?? fallbackErrorMessage
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
if (isActionResponse(payload)) {
|
|
49
|
+
return payload;
|
|
50
|
+
}
|
|
51
|
+
if (payload !== null) {
|
|
52
|
+
return {
|
|
53
|
+
success: true,
|
|
54
|
+
data: payload
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
logError("Received non-JSON 2xx response from server", {
|
|
58
|
+
status: response.status
|
|
59
|
+
});
|
|
60
|
+
return {
|
|
61
|
+
success: false,
|
|
62
|
+
error: serverRequestFailedMessage
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// src/api-action/index.ts
|
|
67
|
+
async function apiAction({
|
|
68
|
+
apiCall,
|
|
69
|
+
locale,
|
|
70
|
+
defaultErrorMessage,
|
|
71
|
+
onError = defaultErrorLogger
|
|
72
|
+
}) {
|
|
73
|
+
const messages = resolveLocaleMessages(locale);
|
|
74
|
+
const resolvedDefaultError = defaultErrorMessage ?? messages.unexpectedError;
|
|
75
|
+
try {
|
|
76
|
+
const actionResult = await apiCall();
|
|
77
|
+
if (isMinimalResponse(actionResult)) {
|
|
78
|
+
return await handleHttpResponse(
|
|
79
|
+
actionResult,
|
|
80
|
+
resolvedDefaultError,
|
|
81
|
+
messages.serverRequestFailed,
|
|
82
|
+
onError
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
if (isActionResponse(actionResult)) {
|
|
86
|
+
return actionResult;
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
success: true,
|
|
90
|
+
data: actionResult
|
|
91
|
+
};
|
|
92
|
+
} catch (caughtError) {
|
|
93
|
+
onError("Unexpected error in apiAction", {
|
|
94
|
+
error: caughtError instanceof Error ? caughtError.message : String(caughtError)
|
|
95
|
+
});
|
|
96
|
+
return {
|
|
97
|
+
success: false,
|
|
98
|
+
error: resolvedDefaultError
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
export {
|
|
103
|
+
apiAction
|
|
104
|
+
};
|
|
105
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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 locale,\n defaultErrorMessage,\n onError = defaultErrorLogger,\n}: ApiActionOptions<T>): Promise<ActionResponse<T>> {\n const messages = resolveLocaleMessages(locale);\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;AAAA,EACA,UAAU;AACZ,GAAoD;AAClD,QAAM,WAAW,sBAAsB,MAAM;AAC7C,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":[]}
|