@larose-ui/data 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 laRose contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,98 @@
1
+ import { ApiError, AsyncState } from '@larose-ui/core';
2
+ import * as react from 'react';
3
+ import { ReactNode } from 'react';
4
+
5
+ interface ApiFetchOptions extends RequestInit {
6
+ baseUrl?: string;
7
+ }
8
+ declare class ApiRequestError extends Error {
9
+ readonly apiError: ApiError;
10
+ constructor(apiError: ApiError);
11
+ }
12
+ declare function apiFetch<T>(url: string, options?: ApiFetchOptions): Promise<T>;
13
+ declare function isApiError(error: unknown): error is ApiRequestError;
14
+ declare function getRetryDelay(retryCount: number, baseMs?: number): number;
15
+
16
+ type QueryStatus = 'idle' | 'loading' | 'success' | 'error' | 'unauthorized';
17
+ interface QueryState<T> {
18
+ status: QueryStatus;
19
+ data: T | null;
20
+ error: ApiError | null;
21
+ retryCount: number;
22
+ }
23
+ interface UseQueryOptions<T> extends ApiFetchOptions {
24
+ enabled?: boolean;
25
+ permission?: string;
26
+ resource?: string;
27
+ initialData?: T;
28
+ }
29
+ interface UseQueryResult<T> extends QueryState<T> {
30
+ refetch: () => Promise<void>;
31
+ retry: () => Promise<void>;
32
+ isEmpty: boolean;
33
+ }
34
+ declare function useQuery<T>(url: string | null, options?: UseQueryOptions<T>): UseQueryResult<T>;
35
+
36
+ interface UseMutationOptions<TData, TVariables> extends ApiFetchOptions {
37
+ url: string;
38
+ method?: string;
39
+ onSuccess?: (data: TData, variables: TVariables) => void;
40
+ onError?: (error: ApiError, variables: TVariables) => void;
41
+ }
42
+ interface UseMutationResult<TData, TVariables> {
43
+ status: AsyncState;
44
+ data: TData | null;
45
+ error: ApiError | null;
46
+ mutate: (variables: TVariables) => Promise<TData | undefined>;
47
+ reset: () => void;
48
+ }
49
+ declare function useMutation<TData = unknown, TVariables = unknown>(options: UseMutationOptions<TData, TVariables>): UseMutationResult<TData, TVariables>;
50
+
51
+ interface SelfHealingErrorProps {
52
+ error: ApiError;
53
+ onRetry?: () => void;
54
+ retryCount?: number;
55
+ }
56
+ declare function SelfHealingError({ error, onRetry, retryCount, }: SelfHealingErrorProps): react.JSX.Element;
57
+ interface DataViewProps<T> extends UseQueryOptions<T> {
58
+ url: string;
59
+ children: (data: T) => ReactNode;
60
+ empty?: ReactNode;
61
+ loading?: ReactNode;
62
+ unauthorized?: ReactNode;
63
+ }
64
+ declare function DataView<T>({ url, children, empty, loading, unauthorized, ...queryOptions }: DataViewProps<T>): string | number | bigint | boolean | react.JSX.Element | Iterable<ReactNode> | Promise<string | number | bigint | boolean | react.ReactPortal | react.ReactElement<unknown, string | react.JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | null;
65
+ interface ResourceProps<T> extends UseQueryOptions<T> {
66
+ url: string;
67
+ children: (resource: {
68
+ data: T;
69
+ refetch: () => Promise<void>;
70
+ }) => ReactNode;
71
+ }
72
+ declare function Resource<T>({ url, children, ...options }: ResourceProps<T>): react.JSX.Element;
73
+
74
+ interface UndoAction<T = unknown> {
75
+ id: string;
76
+ label: string;
77
+ data: T;
78
+ undo: () => void | Promise<void>;
79
+ expiresAt: number;
80
+ }
81
+ interface UseUndoOptions {
82
+ timeoutMs?: number;
83
+ }
84
+ declare function useUndo(options?: UseUndoOptions): {
85
+ actions: UndoAction<unknown>[];
86
+ register: <T>(label: string, data: T, undoFn: () => void | Promise<void>) => string;
87
+ executeUndo: (id: string) => Promise<void>;
88
+ dismiss: (id: string) => void;
89
+ };
90
+
91
+ interface UndoToastProps {
92
+ actions: UndoAction[];
93
+ onUndo: (id: string) => void;
94
+ onDismiss: (id: string) => void;
95
+ }
96
+ declare function UndoToast({ actions, onUndo, onDismiss }: UndoToastProps): react.JSX.Element | null;
97
+
98
+ export { type ApiFetchOptions, ApiRequestError, DataView, type DataViewProps, type QueryStatus, Resource, type ResourceProps, SelfHealingError, type SelfHealingErrorProps, type UndoAction, UndoToast, type UndoToastProps, type UseMutationOptions, type UseMutationResult, type UseQueryOptions, type UseQueryResult, type UseUndoOptions, apiFetch, getRetryDelay, isApiError, useMutation, useQuery, useUndo };
package/dist/index.js ADDED
@@ -0,0 +1,392 @@
1
+ // src/client.ts
2
+ import { classifyHttpError } from "@larose-ui/core";
3
+ var ApiRequestError = class extends Error {
4
+ constructor(apiError) {
5
+ super(apiError.message);
6
+ this.apiError = apiError;
7
+ this.name = "ApiRequestError";
8
+ }
9
+ apiError;
10
+ };
11
+ async function apiFetch(url, options = {}) {
12
+ const { baseUrl = "", ...init } = options;
13
+ const fullUrl = url.startsWith("http") ? url : `${baseUrl}${url}`;
14
+ let response;
15
+ const method = init.method ?? "GET";
16
+ notifyApiRequest(fullUrl, method);
17
+ try {
18
+ response = await fetch(fullUrl, {
19
+ headers: { "Content-Type": "application/json", ...init.headers },
20
+ ...init
21
+ });
22
+ } catch {
23
+ notifyNetworkFailure();
24
+ notifyApiResponse(fullUrl, method, 0, false);
25
+ throw new ApiRequestError({
26
+ code: 503,
27
+ message: "Network request failed. Check your connection.",
28
+ retryable: true
29
+ });
30
+ }
31
+ notifyApiResponse(fullUrl, method, response.status, response.ok);
32
+ if (!response.ok) {
33
+ notifyNetworkFailure();
34
+ let message;
35
+ try {
36
+ const body = await response.json();
37
+ message = body.message;
38
+ } catch {
39
+ }
40
+ const apiError = classifyHttpError(response.status, message);
41
+ if (response.status === 401 && typeof window !== "undefined") {
42
+ window.dispatchEvent(
43
+ new CustomEvent("larose:session-expired", { detail: { code: 401 } })
44
+ );
45
+ }
46
+ throw new ApiRequestError(apiError);
47
+ }
48
+ if (response.status === 204) {
49
+ notifyNetworkSuccess();
50
+ return void 0;
51
+ }
52
+ notifyNetworkSuccess();
53
+ return response.json();
54
+ }
55
+ function notifyNetworkFailure() {
56
+ if (typeof window !== "undefined") {
57
+ window.dispatchEvent(new CustomEvent("larose:network-failure"));
58
+ }
59
+ }
60
+ function notifyNetworkSuccess() {
61
+ if (typeof window !== "undefined") {
62
+ window.dispatchEvent(new CustomEvent("larose:network-success"));
63
+ }
64
+ }
65
+ function notifyApiRequest(url, method) {
66
+ if (typeof window !== "undefined") {
67
+ window.dispatchEvent(
68
+ new CustomEvent("larose:api-request", { detail: { url, method } })
69
+ );
70
+ }
71
+ }
72
+ function notifyApiResponse(url, method, status, ok) {
73
+ if (typeof window !== "undefined") {
74
+ window.dispatchEvent(
75
+ new CustomEvent("larose:api-response", { detail: { url, method, status, ok } })
76
+ );
77
+ }
78
+ }
79
+ function isApiError(error) {
80
+ return error instanceof ApiRequestError;
81
+ }
82
+ function getRetryDelay(retryCount, baseMs = 1e3) {
83
+ return Math.min(baseMs * 2 ** retryCount, 3e4);
84
+ }
85
+
86
+ // src/useQuery.ts
87
+ import { useCallback, useEffect, useReducer, useRef } from "react";
88
+ import { usePermissions } from "@larose-ui/permissions";
89
+ function queryReducer(state, action) {
90
+ switch (action.type) {
91
+ case "LOAD":
92
+ return { ...state, status: "loading", error: null };
93
+ case "SUCCESS":
94
+ return { status: "success", data: action.data, error: null, retryCount: state.retryCount };
95
+ case "ERROR":
96
+ return { ...state, status: "error", error: action.error };
97
+ case "UNAUTHORIZED":
98
+ return { ...state, status: "unauthorized", error: { code: 403, message: "Unauthorized", retryable: false } };
99
+ case "RETRY":
100
+ return { ...state, retryCount: state.retryCount + 1, status: "loading" };
101
+ default:
102
+ return state;
103
+ }
104
+ }
105
+ function useQuery(url, options = {}) {
106
+ const { enabled = true, permission, resource, initialData, ...fetchOptions } = options;
107
+ const { check } = usePermissions();
108
+ const perm = permission ? check(permission, resource) : { allowed: true };
109
+ const [state, dispatch] = useReducer(queryReducer, {
110
+ status: "idle",
111
+ data: initialData ?? null,
112
+ error: null,
113
+ retryCount: 0
114
+ });
115
+ const fetchOptionsRef = useRef(fetchOptions);
116
+ fetchOptionsRef.current = fetchOptions;
117
+ const execute = useCallback(async () => {
118
+ if (!url) return;
119
+ if (perm && !perm.allowed) {
120
+ dispatch({ type: "UNAUTHORIZED" });
121
+ return;
122
+ }
123
+ dispatch({ type: "LOAD" });
124
+ try {
125
+ const data = await apiFetch(url, fetchOptionsRef.current);
126
+ dispatch({ type: "SUCCESS", data });
127
+ } catch (err) {
128
+ if (isApiError(err)) {
129
+ if (err.apiError.code === 401 || err.apiError.code === 403) {
130
+ dispatch({ type: "UNAUTHORIZED" });
131
+ } else {
132
+ dispatch({ type: "ERROR", error: err.apiError });
133
+ }
134
+ } else {
135
+ dispatch({
136
+ type: "ERROR",
137
+ error: { code: 500, message: "Unknown error", retryable: true }
138
+ });
139
+ }
140
+ }
141
+ }, [url, perm]);
142
+ useEffect(() => {
143
+ if (enabled && url) void execute();
144
+ }, [enabled, url, execute, state.retryCount]);
145
+ const retry = useCallback(async () => {
146
+ dispatch({ type: "RETRY" });
147
+ }, []);
148
+ const isEmpty = state.status === "success" && (state.data === null || state.data === void 0 || Array.isArray(state.data) && state.data.length === 0);
149
+ return {
150
+ ...state,
151
+ refetch: execute,
152
+ retry,
153
+ isEmpty
154
+ };
155
+ }
156
+
157
+ // src/useMutation.ts
158
+ import { useCallback as useCallback2, useReducer as useReducer2 } from "react";
159
+ function mutationReducer(state, action) {
160
+ switch (action.type) {
161
+ case "SUBMIT":
162
+ return { ...state, status: "submitting", error: null, variables: action.variables };
163
+ case "SUCCESS":
164
+ return { status: "success", data: action.data, error: null, variables: state.variables };
165
+ case "ERROR":
166
+ return { ...state, status: "error", error: action.error };
167
+ case "RESET":
168
+ return { status: "idle", data: null, error: null, variables: null };
169
+ default:
170
+ return state;
171
+ }
172
+ }
173
+ function useMutation(options) {
174
+ const { url, method = "POST", onSuccess, onError, ...fetchOptions } = options;
175
+ const [state, dispatch] = useReducer2(mutationReducer, {
176
+ status: "idle",
177
+ data: null,
178
+ error: null,
179
+ variables: null
180
+ });
181
+ const mutate = useCallback2(
182
+ async (variables) => {
183
+ dispatch({ type: "SUBMIT", variables });
184
+ try {
185
+ const data = await apiFetch(url, {
186
+ method,
187
+ body: JSON.stringify(variables),
188
+ ...fetchOptions
189
+ });
190
+ dispatch({ type: "SUCCESS", data });
191
+ onSuccess?.(data, variables);
192
+ return data;
193
+ } catch (err) {
194
+ const apiError = isApiError(err) ? err.apiError : { code: 500, message: "Unknown error", retryable: true };
195
+ dispatch({ type: "ERROR", error: apiError });
196
+ onError?.(apiError, variables);
197
+ return void 0;
198
+ }
199
+ },
200
+ [url, method, fetchOptions, onSuccess, onError]
201
+ );
202
+ const reset = useCallback2(() => dispatch({ type: "RESET" }), []);
203
+ return {
204
+ status: state.status,
205
+ data: state.data,
206
+ error: state.error,
207
+ mutate,
208
+ reset
209
+ };
210
+ }
211
+
212
+ // src/DataView.tsx
213
+ import { useEffect as useEffect2, useState } from "react";
214
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
215
+ function SelfHealingError({
216
+ error,
217
+ onRetry,
218
+ retryCount = 0
219
+ }) {
220
+ const [countdown, setCountdown] = useState(null);
221
+ useEffect2(() => {
222
+ if (error.code === 429 && error.retryable && onRetry) {
223
+ const delay = Math.ceil(getRetryDelay(retryCount, 2e3) / 1e3);
224
+ setCountdown(delay);
225
+ const timer = setInterval(() => {
226
+ setCountdown((c) => {
227
+ if (c === null || c <= 1) {
228
+ clearInterval(timer);
229
+ onRetry();
230
+ return null;
231
+ }
232
+ return c - 1;
233
+ });
234
+ }, 1e3);
235
+ return () => clearInterval(timer);
236
+ }
237
+ }, [error, onRetry, retryCount]);
238
+ return /* @__PURE__ */ jsxs("div", { role: "alert", "data-lr-error": error.code, style: { textAlign: "center", padding: "var(--lr-space-4)" }, children: [
239
+ /* @__PURE__ */ jsx("p", { style: { color: "var(--lr-color-error)", marginBottom: "var(--lr-space-2)" }, children: error.message }),
240
+ error.retryable && onRetry && error.code !== 429 && /* @__PURE__ */ jsx(
241
+ "button",
242
+ {
243
+ type: "button",
244
+ onClick: onRetry,
245
+ style: {
246
+ padding: "var(--lr-space-2) var(--lr-space-4)",
247
+ borderRadius: "var(--lr-radius-md)",
248
+ border: "1px solid var(--lr-color-border)",
249
+ background: "var(--lr-color-surface)",
250
+ cursor: "pointer"
251
+ },
252
+ children: "Retry"
253
+ }
254
+ ),
255
+ countdown !== null && /* @__PURE__ */ jsxs("p", { style: { fontSize: "var(--lr-font-size-sm)", color: "var(--lr-color-text-muted)" }, children: [
256
+ "Retrying in ",
257
+ countdown,
258
+ "s..."
259
+ ] })
260
+ ] });
261
+ }
262
+ function DataView({
263
+ url,
264
+ children,
265
+ empty,
266
+ loading,
267
+ unauthorized,
268
+ ...queryOptions
269
+ }) {
270
+ const query = useQuery(url, queryOptions);
271
+ if (query.status === "loading" || query.status === "idle") {
272
+ return loading ?? /* @__PURE__ */ jsx("div", { role: "status", "aria-busy": "true", style: { padding: "var(--lr-space-4)" }, children: "Loading..." });
273
+ }
274
+ if (query.status === "unauthorized") {
275
+ return unauthorized ?? /* @__PURE__ */ jsx("div", { role: "alert", style: { padding: "var(--lr-space-4)", color: "var(--lr-color-error)" }, children: "You do not have permission to view this data." });
276
+ }
277
+ if (query.status === "error" && query.error) {
278
+ return /* @__PURE__ */ jsx(
279
+ SelfHealingError,
280
+ {
281
+ error: query.error,
282
+ onRetry: () => void query.retry(),
283
+ retryCount: query.retryCount
284
+ }
285
+ );
286
+ }
287
+ if (query.isEmpty) {
288
+ return empty ?? /* @__PURE__ */ jsx("div", { role: "status", style: { padding: "var(--lr-space-4)", color: "var(--lr-color-text-muted)" }, children: "No data found" });
289
+ }
290
+ if (query.data !== null) {
291
+ return /* @__PURE__ */ jsx(Fragment, { children: children(query.data) });
292
+ }
293
+ return null;
294
+ }
295
+ function Resource({ url, children, ...options }) {
296
+ const query = useQuery(url, options);
297
+ if (query.status !== "success" || query.data === null) {
298
+ return /* @__PURE__ */ jsx(DataView, { url, ...options, children: (data) => children({ data, refetch: query.refetch }) });
299
+ }
300
+ return /* @__PURE__ */ jsx(Fragment, { children: children({ data: query.data, refetch: query.refetch }) });
301
+ }
302
+
303
+ // src/useUndo.ts
304
+ import { useCallback as useCallback3, useState as useState2 } from "react";
305
+ function useUndo(options = {}) {
306
+ const { timeoutMs = 8e3 } = options;
307
+ const [actions, setActions] = useState2([]);
308
+ const register = useCallback3(
309
+ (label, data, undoFn) => {
310
+ const id = `undo-${Date.now()}`;
311
+ const action = {
312
+ id,
313
+ label,
314
+ data,
315
+ undo: undoFn,
316
+ expiresAt: Date.now() + timeoutMs
317
+ };
318
+ setActions((prev) => [...prev, action]);
319
+ setTimeout(() => {
320
+ setActions((prev) => prev.filter((a) => a.id !== id));
321
+ }, timeoutMs);
322
+ return id;
323
+ },
324
+ [timeoutMs]
325
+ );
326
+ const executeUndo = useCallback3(async (id) => {
327
+ const action = actions.find((a) => a.id === id);
328
+ if (action) {
329
+ await action.undo();
330
+ setActions((prev) => prev.filter((a) => a.id !== id));
331
+ }
332
+ }, [actions]);
333
+ const dismiss = useCallback3((id) => {
334
+ setActions((prev) => prev.filter((a) => a.id !== id));
335
+ }, []);
336
+ return { actions, register, executeUndo, dismiss };
337
+ }
338
+
339
+ // src/UndoToast.tsx
340
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
341
+ function UndoToast({ actions, onUndo, onDismiss }) {
342
+ if (actions.length === 0) return null;
343
+ return /* @__PURE__ */ jsx2(
344
+ "div",
345
+ {
346
+ style: {
347
+ position: "fixed",
348
+ bottom: "var(--lr-space-6)",
349
+ right: "var(--lr-space-6)",
350
+ display: "flex",
351
+ flexDirection: "column",
352
+ gap: "var(--lr-space-2)",
353
+ zIndex: 1100
354
+ },
355
+ children: actions.map((action) => /* @__PURE__ */ jsxs2(
356
+ "div",
357
+ {
358
+ role: "status",
359
+ style: {
360
+ display: "flex",
361
+ alignItems: "center",
362
+ gap: "var(--lr-space-3)",
363
+ padding: "var(--lr-space-3) var(--lr-space-4)",
364
+ background: "var(--lr-color-surface-elevated)",
365
+ border: "1px solid var(--lr-color-border)",
366
+ borderRadius: "var(--lr-radius-md)",
367
+ boxShadow: "var(--lr-shadow-md)"
368
+ },
369
+ children: [
370
+ /* @__PURE__ */ jsx2("span", { style: { fontSize: "var(--lr-font-size-sm)" }, children: action.label }),
371
+ /* @__PURE__ */ jsx2("button", { type: "button", onClick: () => onUndo(action.id), style: { fontWeight: 600 }, children: "Undo" }),
372
+ /* @__PURE__ */ jsx2("button", { type: "button", onClick: () => onDismiss(action.id), "aria-label": "Dismiss", children: "\xD7" })
373
+ ]
374
+ },
375
+ action.id
376
+ ))
377
+ }
378
+ );
379
+ }
380
+ export {
381
+ ApiRequestError,
382
+ DataView,
383
+ Resource,
384
+ SelfHealingError,
385
+ UndoToast,
386
+ apiFetch,
387
+ getRetryDelay,
388
+ isApiError,
389
+ useMutation,
390
+ useQuery,
391
+ useUndo
392
+ };
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@larose-ui/data",
3
+ "version": "0.1.0",
4
+ "description": "Backend-aware data layer for laRose UI platform",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "dependencies": {
19
+ "@larose-ui/core": "0.1.0",
20
+ "@larose-ui/permissions": "0.1.0"
21
+ },
22
+ "peerDependencies": {
23
+ "react": ">=18"
24
+ },
25
+ "devDependencies": {
26
+ "@testing-library/jest-dom": "^6.6.3",
27
+ "@testing-library/react": "^16.1.0",
28
+ "@vitejs/plugin-react": "^4.3.4",
29
+ "jsdom": "^25.0.1",
30
+ "react": "^19.0.0",
31
+ "react-dom": "^19.0.0",
32
+ "tsup": "^8.3.5",
33
+ "typescript": "^5.7.2",
34
+ "vitest": "^2.1.8"
35
+ },
36
+ "license": "MIT",
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "https://github.com/larose-ui/larose.git",
43
+ "directory": "packages/data"
44
+ },
45
+ "keywords": [
46
+ "larose",
47
+ "react",
48
+ "ui-platform",
49
+ "design-system",
50
+ "saas"
51
+ ],
52
+ "scripts": {
53
+ "build": "tsup",
54
+ "dev": "tsup --watch",
55
+ "test": "vitest run",
56
+ "typecheck": "tsc --noEmit",
57
+ "clean": "rm -rf dist"
58
+ }
59
+ }