@object-ui/react 0.5.0 → 2.0.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.
Files changed (65) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +13 -0
  3. package/dist/LazyPluginLoader.d.ts +44 -0
  4. package/dist/LazyPluginLoader.js +92 -3
  5. package/dist/components/form/FieldFactory.js +44 -40
  6. package/dist/components/form/FormRenderer.js +45 -3
  7. package/dist/context/ActionContext.d.ts +76 -0
  8. package/dist/context/ActionContext.js +139 -0
  9. package/dist/context/ThemeContext.d.ts +94 -0
  10. package/dist/context/ThemeContext.js +215 -0
  11. package/dist/context/index.d.ts +2 -0
  12. package/dist/context/index.js +2 -0
  13. package/dist/hooks/index.d.ts +5 -0
  14. package/dist/hooks/index.js +5 -0
  15. package/dist/hooks/useActionRunner.d.ts +21 -7
  16. package/dist/hooks/useActionRunner.js +27 -7
  17. package/dist/hooks/useDiscovery.d.ts +78 -0
  18. package/dist/hooks/useDiscovery.js +96 -0
  19. package/dist/hooks/useDynamicApp.d.ts +70 -0
  20. package/dist/hooks/useDynamicApp.js +92 -0
  21. package/dist/hooks/useNavigationOverlay.d.ts +78 -0
  22. package/dist/hooks/useNavigationOverlay.js +112 -0
  23. package/dist/hooks/usePageVariables.d.ts +67 -0
  24. package/dist/hooks/usePageVariables.js +109 -0
  25. package/dist/hooks/useViewData.d.ts +73 -0
  26. package/dist/hooks/useViewData.js +135 -0
  27. package/dist/index.d.ts +1 -0
  28. package/dist/index.js +2 -0
  29. package/dist/utils/i18n.d.ts +10 -0
  30. package/dist/utils/i18n.js +12 -0
  31. package/package.json +6 -4
  32. package/src/LazyPluginLoader.tsx +129 -7
  33. package/src/__tests__/LazyPluginLoader.test.tsx +97 -1
  34. package/src/__tests__/ThemeProvider.test.tsx +451 -0
  35. package/src/__tests__/useNavigationOverlay.test.ts +416 -0
  36. package/src/__tests__/usePageVariables.test.tsx +334 -0
  37. package/src/__tests__/useViewData.test.tsx +422 -0
  38. package/src/components/form/FieldFactory.tsx +51 -46
  39. package/src/components/form/FormRenderer.test.tsx +145 -0
  40. package/src/components/form/FormRenderer.tsx +52 -3
  41. package/src/context/ActionContext.tsx +213 -0
  42. package/src/context/ThemeContext.tsx +325 -0
  43. package/src/context/__tests__/ActionContext.test.tsx +174 -0
  44. package/src/context/index.ts +2 -0
  45. package/src/hooks/__tests__/useActionRunner.test.ts +153 -0
  46. package/src/hooks/__tests__/useDiscovery.test.tsx +149 -0
  47. package/src/hooks/__tests__/useDynamicApp.test.ts +161 -0
  48. package/src/hooks/__tests__/useExpression.test.ts +86 -0
  49. package/src/hooks/index.ts +5 -0
  50. package/src/hooks/useActionRunner.ts +49 -11
  51. package/src/hooks/useDiscovery.ts +141 -0
  52. package/src/hooks/useDynamicApp.ts +142 -0
  53. package/src/hooks/useNavigationOverlay.ts +180 -0
  54. package/src/hooks/usePageVariables.tsx +157 -0
  55. package/src/hooks/useViewData.ts +201 -0
  56. package/src/index.ts +21 -0
  57. package/src/utils/i18n.ts +10 -0
  58. package/tsconfig.json +1 -0
  59. package/tsconfig.tsbuildinfo +1 -1
  60. package/dist/__tests__/LazyPluginLoader.test.d.ts +0 -8
  61. package/dist/__tests__/LazyPluginLoader.test.js +0 -49
  62. package/dist/components/form/FormRenderer.test.d.ts +0 -8
  63. package/dist/components/form/FormRenderer.test.js +0 -534
  64. package/dist/index.test.d.ts +0 -8
  65. package/dist/index.test.js +0 -13
@@ -0,0 +1,73 @@
1
+ /**
2
+ * ObjectUI — useViewData
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ *
8
+ * A React hook that resolves a ViewData configuration into a DataSource
9
+ * and provides reactive data fetching with loading/error states.
10
+ */
11
+ import type { DataSource, ViewData, QueryParams } from '@object-ui/types';
12
+ import { type ResolveDataSourceOptions } from '@object-ui/core';
13
+ export interface UseViewDataOptions<T = any> {
14
+ /** The ViewData configuration from the schema */
15
+ viewData?: ViewData | null;
16
+ /** Resource name (object name, used for DataSource.find calls) */
17
+ resource?: string;
18
+ /** Initial query parameters */
19
+ params?: QueryParams;
20
+ /** Explicit data source override (bypasses context) */
21
+ dataSource?: DataSource<T> | null;
22
+ /** Options for adapter construction */
23
+ adapterOptions?: ResolveDataSourceOptions;
24
+ /** If true, skip the initial fetch (useful for forms in create mode) */
25
+ skip?: boolean;
26
+ }
27
+ export interface UseViewDataResult<T = any> {
28
+ /** Resolved data array */
29
+ data: T[];
30
+ /** Total number of records (from server or array length) */
31
+ totalCount: number;
32
+ /** Whether data is being fetched */
33
+ loading: boolean;
34
+ /** Error from the last fetch attempt */
35
+ error: Error | null;
36
+ /** The resolved DataSource instance (can be used for create/update/delete) */
37
+ dataSource: DataSource<T> | null;
38
+ /** Re-fetch data with current or new params */
39
+ refresh: (newParams?: QueryParams) => Promise<void>;
40
+ /** Fetch a single record by ID */
41
+ fetchOne: (id: string | number) => Promise<T | null>;
42
+ /** Whether more records are available */
43
+ hasMore: boolean;
44
+ }
45
+ /**
46
+ * useViewData — resolves ViewData into a DataSource and provides reactive data.
47
+ *
48
+ * This hook centralizes the data resolution pattern that was previously
49
+ * duplicated across plugins (ObjectGrid, ObjectView, etc.). It:
50
+ *
51
+ * 1. Resolves the ViewData config to the right DataSource adapter
52
+ * - `provider: 'object'` → context DataSource (ObjectStackAdapter)
53
+ * - `provider: 'api'` → ApiDataSource (raw HTTP)
54
+ * - `provider: 'value'` → ValueDataSource (in-memory)
55
+ * 2. Fetches data automatically on mount
56
+ * 3. Provides loading/error states and refresh capability
57
+ *
58
+ * @example
59
+ * ```tsx
60
+ * function MyGrid({ schema }) {
61
+ * const { data, loading, error, refresh, dataSource } = useViewData({
62
+ * viewData: schema.data,
63
+ * resource: schema.objectName,
64
+ * params: { $top: 50 },
65
+ * });
66
+ *
67
+ * if (loading) return <Spinner />;
68
+ * if (error) return <ErrorMessage error={error} />;
69
+ * return <Table data={data} />;
70
+ * }
71
+ * ```
72
+ */
73
+ export declare function useViewData<T = any>(options: UseViewDataOptions<T>): UseViewDataResult<T>;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * ObjectUI — useViewData
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ *
8
+ * A React hook that resolves a ViewData configuration into a DataSource
9
+ * and provides reactive data fetching with loading/error states.
10
+ */
11
+ import { useState, useEffect, useCallback, useMemo, useContext } from 'react';
12
+ import { resolveDataSource } from '@object-ui/core';
13
+ import { SchemaRendererContext } from '../context/SchemaRendererContext';
14
+ // ---------------------------------------------------------------------------
15
+ // Hook
16
+ // ---------------------------------------------------------------------------
17
+ /**
18
+ * useViewData — resolves ViewData into a DataSource and provides reactive data.
19
+ *
20
+ * This hook centralizes the data resolution pattern that was previously
21
+ * duplicated across plugins (ObjectGrid, ObjectView, etc.). It:
22
+ *
23
+ * 1. Resolves the ViewData config to the right DataSource adapter
24
+ * - `provider: 'object'` → context DataSource (ObjectStackAdapter)
25
+ * - `provider: 'api'` → ApiDataSource (raw HTTP)
26
+ * - `provider: 'value'` → ValueDataSource (in-memory)
27
+ * 2. Fetches data automatically on mount
28
+ * 3. Provides loading/error states and refresh capability
29
+ *
30
+ * @example
31
+ * ```tsx
32
+ * function MyGrid({ schema }) {
33
+ * const { data, loading, error, refresh, dataSource } = useViewData({
34
+ * viewData: schema.data,
35
+ * resource: schema.objectName,
36
+ * params: { $top: 50 },
37
+ * });
38
+ *
39
+ * if (loading) return <Spinner />;
40
+ * if (error) return <ErrorMessage error={error} />;
41
+ * return <Table data={data} />;
42
+ * }
43
+ * ```
44
+ */
45
+ export function useViewData(options) {
46
+ const { viewData, resource = '', params, dataSource: explicitDataSource, adapterOptions, skip = false, } = options;
47
+ // Get context DataSource
48
+ const context = useContext(SchemaRendererContext);
49
+ const contextDataSource = context?.dataSource ?? null;
50
+ // Resolve the DataSource — memoize to prevent re-creation on every render.
51
+ // We key on the viewData provider + config identity.
52
+ const resolvedDataSource = useMemo(() => {
53
+ if (explicitDataSource)
54
+ return explicitDataSource;
55
+ return resolveDataSource(viewData, contextDataSource, adapterOptions);
56
+ // eslint-disable-next-line react-hooks/exhaustive-deps
57
+ }, [
58
+ explicitDataSource,
59
+ viewData?.provider,
60
+ // For 'api' provider, key on read/write URLs
61
+ viewData?.provider === 'api' ? viewData.read?.url : undefined,
62
+ viewData?.provider === 'api' ? viewData.write?.url : undefined,
63
+ // For 'value' provider, key on items reference (or length as proxy)
64
+ viewData?.provider === 'value' ? viewData.items?.length : undefined,
65
+ contextDataSource,
66
+ ]);
67
+ // State
68
+ const [data, setData] = useState([]);
69
+ const [totalCount, setTotalCount] = useState(0);
70
+ const [loading, setLoading] = useState(!skip);
71
+ const [error, setError] = useState(null);
72
+ const [hasMore, setHasMore] = useState(false);
73
+ // Stable params reference
74
+ const paramsKey = useMemo(() => JSON.stringify(params ?? {}), [params]);
75
+ // Fetch function
76
+ const fetchData = useCallback(async (fetchParams) => {
77
+ if (!resolvedDataSource || !resource) {
78
+ setLoading(false);
79
+ return;
80
+ }
81
+ setLoading(true);
82
+ setError(null);
83
+ try {
84
+ const mergedParams = fetchParams ?? (params ? { ...params } : undefined);
85
+ const result = await resolvedDataSource.find(resource, mergedParams);
86
+ setData(result.data ?? []);
87
+ setTotalCount(result.total ?? result.data?.length ?? 0);
88
+ setHasMore(result.hasMore ?? false);
89
+ }
90
+ catch (err) {
91
+ setError(err instanceof Error ? err : new Error(String(err)));
92
+ setData([]);
93
+ setTotalCount(0);
94
+ }
95
+ finally {
96
+ setLoading(false);
97
+ }
98
+ }, [resolvedDataSource, resource, params]);
99
+ // Auto-fetch on mount / when deps change
100
+ useEffect(() => {
101
+ if (skip) {
102
+ setLoading(false);
103
+ return;
104
+ }
105
+ // For value provider, data is synchronous — still go through fetchData
106
+ // for consistency, but it resolves immediately.
107
+ fetchData();
108
+ // eslint-disable-next-line react-hooks/exhaustive-deps
109
+ }, [resolvedDataSource, resource, paramsKey, skip]);
110
+ // Refresh function (can accept new params)
111
+ const refresh = useCallback(async (newParams) => {
112
+ await fetchData(newParams);
113
+ }, [fetchData]);
114
+ // Fetch one record
115
+ const fetchOne = useCallback(async (id) => {
116
+ if (!resolvedDataSource)
117
+ return null;
118
+ try {
119
+ return await resolvedDataSource.findOne(resource, id);
120
+ }
121
+ catch {
122
+ return null;
123
+ }
124
+ }, [resolvedDataSource, resource]);
125
+ return {
126
+ data,
127
+ totalCount,
128
+ loading,
129
+ error,
130
+ dataSource: resolvedDataSource,
131
+ refresh,
132
+ fetchOne,
133
+ hasMore,
134
+ };
135
+ }
package/dist/index.d.ts CHANGED
@@ -10,3 +10,4 @@ export * from './hooks';
10
10
  export * from './context';
11
11
  export * from './components/form';
12
12
  export * from './LazyPluginLoader';
13
+ export { I18nProvider, useObjectTranslation, useI18nContext, createI18n, getDirection, getAvailableLanguages, formatDate, formatDateTime, formatRelativeTime, formatCurrency, formatNumber, type I18nConfig, type I18nProviderProps, type TranslationKeys, type DateFormatOptions, type CurrencyFormatOptions, type NumberFormatOptions, } from '@object-ui/i18n';
package/dist/index.js CHANGED
@@ -10,3 +10,5 @@ export * from './hooks'; // will be empty for now
10
10
  export * from './context'; // will be empty for now
11
11
  export * from './components/form';
12
12
  export * from './LazyPluginLoader';
13
+ // Built-in i18n support
14
+ export { I18nProvider, useObjectTranslation, useI18nContext, createI18n, getDirection, getAvailableLanguages, formatDate, formatDateTime, formatRelativeTime, formatCurrency, formatNumber, } from '@object-ui/i18n';
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Resolves an I18nLabel to a plain string.
3
+ * I18nLabel can be either a string or an object { key, defaultValue?, params? }.
4
+ * When it's an object, we return the defaultValue or the key as fallback.
5
+ */
6
+ export declare function resolveI18nLabel(label: string | {
7
+ key: string;
8
+ defaultValue?: string;
9
+ params?: Record<string, any>;
10
+ } | undefined): string | undefined;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Resolves an I18nLabel to a plain string.
3
+ * I18nLabel can be either a string or an object { key, defaultValue?, params? }.
4
+ * When it's an object, we return the defaultValue or the key as fallback.
5
+ */
6
+ export function resolveI18nLabel(label) {
7
+ if (label === undefined || label === null)
8
+ return undefined;
9
+ if (typeof label === 'string')
10
+ return label;
11
+ return label.defaultValue || label.key;
12
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@object-ui/react",
3
- "version": "0.5.0",
3
+ "version": "2.0.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "React bindings and SchemaRenderer component for Object UI",
@@ -23,16 +23,18 @@
23
23
  }
24
24
  },
25
25
  "dependencies": {
26
- "@objectstack/spec": "^0.9.1",
26
+ "@objectstack/spec": "^2.0.7",
27
27
  "react-hook-form": "^7.71.1",
28
- "@object-ui/core": "0.5.0"
28
+ "@object-ui/core": "2.0.0",
29
+ "@object-ui/i18n": "2.0.0",
30
+ "@object-ui/types": "2.0.0"
29
31
  },
30
32
  "peerDependencies": {
31
33
  "react": "^18.0.0 || ^19.0.0",
32
34
  "react-dom": "^18.0.0 || ^19.0.0"
33
35
  },
34
36
  "devDependencies": {
35
- "@types/react": "^19.2.10",
37
+ "@types/react": "^19.2.13",
36
38
  "@types/react-dom": "^19.2.3",
37
39
  "typescript": "^5.9.3"
38
40
  },
@@ -6,13 +6,83 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
 
9
- import React, { lazy, Suspense } from 'react';
9
+ import React, { lazy, Suspense, Component } from 'react';
10
10
 
11
11
  export interface LazyPluginOptions {
12
12
  /**
13
13
  * Fallback component to show while loading
14
14
  */
15
15
  fallback?: React.ReactNode;
16
+ /**
17
+ * Number of retry attempts on load failure (default: 2)
18
+ */
19
+ retries?: number;
20
+ /**
21
+ * Delay in ms between retries (default: 1000)
22
+ */
23
+ retryDelay?: number;
24
+ /**
25
+ * Custom error fallback component
26
+ */
27
+ errorFallback?: React.ComponentType<{ error: Error; retry: () => void }>;
28
+ }
29
+
30
+ /**
31
+ * Error boundary for lazy-loaded plugins
32
+ */
33
+ interface ErrorBoundaryState {
34
+ hasError: boolean;
35
+ error: Error | null;
36
+ }
37
+
38
+ class PluginErrorBoundary extends Component<
39
+ { fallback?: React.ComponentType<{ error: Error; retry: () => void }>; children: React.ReactNode },
40
+ ErrorBoundaryState
41
+ > {
42
+ state: ErrorBoundaryState = { hasError: false, error: null };
43
+
44
+ static getDerivedStateFromError(error: Error): ErrorBoundaryState {
45
+ return { hasError: true, error };
46
+ }
47
+
48
+ handleRetry = () => {
49
+ this.setState({ hasError: false, error: null });
50
+ };
51
+
52
+ render() {
53
+ if (this.state.hasError && this.state.error) {
54
+ const FallbackComponent = this.props.fallback;
55
+ if (FallbackComponent) {
56
+ return <FallbackComponent error={this.state.error} retry={this.handleRetry} />;
57
+ }
58
+ return null;
59
+ }
60
+ return this.props.children;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Create a lazy-loaded import function with retry support
66
+ */
67
+ function createRetryImport<P extends object>(
68
+ importFn: () => Promise<{ default: React.ComponentType<P> }>,
69
+ retries: number,
70
+ retryDelay: number,
71
+ ): () => Promise<{ default: React.ComponentType<P> }> {
72
+ return () => {
73
+ let attempt = 0;
74
+ const tryImport = (): Promise<{ default: React.ComponentType<P> }> =>
75
+ importFn().catch((err) => {
76
+ attempt++;
77
+ if (attempt <= retries) {
78
+ return new Promise((resolve) =>
79
+ setTimeout(() => resolve(tryImport()), retryDelay),
80
+ );
81
+ }
82
+ throw err;
83
+ });
84
+ return tryImport();
85
+ };
16
86
  }
17
87
 
18
88
  /**
@@ -34,19 +104,71 @@ export interface LazyPluginOptions {
34
104
  * () => import('@object-ui/plugin-grid'),
35
105
  * { fallback: <div>Loading grid...</div> }
36
106
  * );
107
+ *
108
+ * // With retry and error handling
109
+ * const ObjectGrid = createLazyPlugin(
110
+ * () => import('@object-ui/plugin-grid'),
111
+ * {
112
+ * retries: 3,
113
+ * errorFallback: ({ error, retry }) => (
114
+ * <div>
115
+ * <p>Failed to load: {error.message}</p>
116
+ * <button onClick={retry}>Retry</button>
117
+ * </div>
118
+ * ),
119
+ * }
120
+ * );
37
121
  * ```
38
122
  */
39
123
  export function createLazyPlugin<P extends object = any>(
40
124
  importFn: () => Promise<{ default: React.ComponentType<P> }>,
41
125
  options?: LazyPluginOptions
42
126
  ): React.ComponentType<P> {
43
- const LazyComponent = lazy(importFn);
127
+ const { retries = 2, retryDelay = 1000, errorFallback } = options || {};
128
+
129
+ const retryImport = retries > 0
130
+ ? createRetryImport(importFn, retries, retryDelay)
131
+ : importFn;
132
+
133
+ const LazyComponent = lazy(retryImport);
44
134
 
45
- const PluginWrapper: React.FC<P> = (props) => (
46
- <Suspense fallback={options?.fallback || null}>
47
- <LazyComponent {...props} />
48
- </Suspense>
49
- );
135
+ const PluginWrapper: React.FC<P> = (props) => {
136
+ const content = (
137
+ <Suspense fallback={options?.fallback || null}>
138
+ <LazyComponent {...props} />
139
+ </Suspense>
140
+ );
141
+
142
+ if (errorFallback) {
143
+ return (
144
+ <PluginErrorBoundary fallback={errorFallback}>
145
+ {content}
146
+ </PluginErrorBoundary>
147
+ );
148
+ }
149
+
150
+ return content;
151
+ };
50
152
 
51
153
  return PluginWrapper;
52
154
  }
155
+
156
+ /**
157
+ * Preload a plugin module without rendering it.
158
+ * Useful for preloading plugins that will be needed soon.
159
+ *
160
+ * @param importFn - Dynamic import function
161
+ * @returns Promise that resolves when the module is loaded
162
+ *
163
+ * @example
164
+ * ```tsx
165
+ * // Preload on hover
166
+ * const loadGrid = () => import('@object-ui/plugin-grid');
167
+ * <button onMouseEnter={() => preloadPlugin(loadGrid)}>Show Grid</button>
168
+ * ```
169
+ */
170
+ export function preloadPlugin<T = unknown>(
171
+ importFn: () => Promise<T>,
172
+ ): Promise<T> {
173
+ return importFn();
174
+ }
@@ -9,7 +9,7 @@
9
9
  import { describe, it, expect, vi } from 'vitest';
10
10
  import { render, screen, waitFor } from '@testing-library/react';
11
11
  import React from 'react';
12
- import { createLazyPlugin } from '../LazyPluginLoader';
12
+ import { createLazyPlugin, preloadPlugin } from '../LazyPluginLoader';
13
13
 
14
14
  describe('createLazyPlugin', () => {
15
15
  it('should create a lazy-loaded component', async () => {
@@ -77,4 +77,100 @@ describe('createLazyPlugin', () => {
77
77
  // Restore console.error
78
78
  console.error = originalError;
79
79
  });
80
+
81
+ it('should preload a plugin without rendering', async () => {
82
+ const TestComponent = () => <div>Preloaded</div>;
83
+ const importFn = vi.fn(() => Promise.resolve({ default: TestComponent }));
84
+
85
+ const result = await preloadPlugin(importFn);
86
+
87
+ expect(importFn).toHaveBeenCalledTimes(1);
88
+ expect(result).toEqual({ default: TestComponent });
89
+ });
90
+
91
+ it('should render errorFallback when component fails to load', async () => {
92
+ const originalError = console.error;
93
+ console.error = vi.fn();
94
+
95
+ const ErrorFallback = ({ error, retry }: { error: Error; retry: () => void }) => (
96
+ <div>
97
+ <span>Error: {error.message}</span>
98
+ <button onClick={retry}>Retry</button>
99
+ </div>
100
+ );
101
+
102
+ const LazyComponent = createLazyPlugin(
103
+ () => Promise.reject(new Error('chunk failed')),
104
+ { retries: 0, errorFallback: ErrorFallback }
105
+ );
106
+
107
+ render(<LazyComponent />);
108
+
109
+ await waitFor(() => {
110
+ expect(screen.getByText('Error: chunk failed')).toBeInTheDocument();
111
+ });
112
+
113
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();
114
+
115
+ console.error = originalError;
116
+ });
117
+
118
+ it('should not retry when retries=0', async () => {
119
+ const originalError = console.error;
120
+ console.error = vi.fn();
121
+
122
+ const importFn = vi.fn(() => Promise.reject(new Error('fail')));
123
+
124
+ const ErrorFallback = ({ error }: { error: Error; retry: () => void }) => (
125
+ <div>Error: {error.message}</div>
126
+ );
127
+
128
+ const LazyComponent = createLazyPlugin(importFn, {
129
+ retries: 0,
130
+ errorFallback: ErrorFallback,
131
+ });
132
+
133
+ render(<LazyComponent />);
134
+
135
+ await waitFor(() => {
136
+ expect(screen.getByText('Error: fail')).toBeInTheDocument();
137
+ });
138
+
139
+ // Called only once — no retries
140
+ expect(importFn).toHaveBeenCalledTimes(1);
141
+
142
+ console.error = originalError;
143
+ });
144
+
145
+ it('should retry on failure then succeed', async () => {
146
+ const originalError = console.error;
147
+ console.error = vi.fn();
148
+
149
+ const TestComponent = () => <div>Success after retry</div>;
150
+
151
+ let callCount = 0;
152
+ const importFn = vi.fn(() => {
153
+ callCount++;
154
+ if (callCount <= 2) {
155
+ return Promise.reject(new Error('transient error'));
156
+ }
157
+ return Promise.resolve({ default: TestComponent as React.ComponentType });
158
+ });
159
+
160
+ const LazyComponent = createLazyPlugin(importFn, {
161
+ retries: 3,
162
+ retryDelay: 10,
163
+ });
164
+
165
+ render(<LazyComponent />);
166
+
167
+ await waitFor(() => {
168
+ expect(screen.getByText('Success after retry')).toBeInTheDocument();
169
+ }, { timeout: 5000 });
170
+
171
+ // First call + 2 retries (fails) + 1 success = called 3 times
172
+ expect(importFn).toHaveBeenCalledTimes(3);
173
+
174
+ console.error = originalError;
175
+ });
80
176
  });