@buildbase/sdk 0.0.11 → 0.0.13
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 +34 -13
- package/dist/index.d.ts +896 -134
- package/dist/index.esm.js +5 -11
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +5 -11
- package/dist/index.js.map +1 -1
- package/dist/saas-os.css +1 -1
- package/dist/types/components/ErrorBoundary.d.ts +49 -2
- package/dist/types/components/dropdowns/country/selectCountry.d.ts +2 -2
- package/dist/types/components/dropdowns/currency/selectCurrency.d.ts +2 -2
- package/dist/types/components/dropdowns/language/selectLanguage.d.ts +2 -2
- package/dist/types/components/dropdowns/timezone/selectTimeZone.d.ts +2 -2
- package/dist/types/components/features/index.d.ts +109 -0
- package/dist/types/components/ui/command-select.d.ts +13 -0
- package/dist/types/components/ui/command.d.ts +2 -2
- package/dist/types/components/user/auth.d.ts +64 -0
- package/dist/types/components/user/role.d.ts +70 -0
- package/dist/types/contexts/WorkspaceContext/actions.d.ts +1 -1
- package/dist/types/contexts/WorkspaceContext/types.d.ts +3 -3
- package/dist/types/contexts/shared/useSelectWithEquality.d.ts +10 -0
- package/dist/types/index.d.ts +1 -3
- package/dist/types/lib/api-utils.d.ts +182 -0
- package/dist/types/lib/error-handler.d.ts +58 -0
- package/dist/types/lib/logger.d.ts +27 -0
- package/dist/types/lib/useAsyncEffect.d.ts +29 -0
- package/dist/types/lib/utils.d.ts +5 -0
- package/dist/types/providers/auth/hooks.d.ts +61 -0
- package/dist/types/providers/auth/types.d.ts +12 -0
- package/dist/types/providers/auth/utils.d.ts +7 -2
- package/dist/types/providers/constants.d.ts +1 -0
- package/dist/types/providers/os/hooks.d.ts +40 -1
- package/dist/types/providers/user/hooks.d.ts +71 -0
- package/dist/types/providers/workspace/hooks.d.ts +112 -4
- package/dist/types/providers/workspace/provider.d.ts +0 -1
- package/dist/types/providers/workspace/subscription-hooks.d.ts +351 -29
- package/dist/types/providers/workspace/types.d.ts +1 -1
- package/package.json +14 -12
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* API utility functions for consistent error handling and request management
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* Check if an error is from AbortController (request was cancelled).
|
|
6
|
+
* Useful for ignoring abort errors when components unmount or requests are cancelled.
|
|
7
|
+
*
|
|
8
|
+
* @param error - The error to check
|
|
9
|
+
* @returns True if the error is an AbortError, false otherwise
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```tsx
|
|
13
|
+
* try {
|
|
14
|
+
* await safeFetch(url, { signal });
|
|
15
|
+
* } catch (error) {
|
|
16
|
+
* if (isAbortError(error)) {
|
|
17
|
+
* // Request was cancelled, ignore
|
|
18
|
+
* return;
|
|
19
|
+
* }
|
|
20
|
+
* // Handle other errors
|
|
21
|
+
* console.error('Request failed:', error);
|
|
22
|
+
* }
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
export declare function isAbortError(error: unknown): boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Safely execute a fetch request with network error handling.
|
|
28
|
+
* Wraps native fetch to provide better error messages for network failures.
|
|
29
|
+
* Supports AbortSignal - when aborted, throws with name 'AbortError' (caller can use isAbortError()).
|
|
30
|
+
* In development mode, automatically logs request/response for debugging (prefixed with [SDK API]).
|
|
31
|
+
* Sensitive data (tokens, passwords) is automatically redacted from logs.
|
|
32
|
+
*
|
|
33
|
+
* @param url - The URL to fetch
|
|
34
|
+
* @param options - Optional fetch options (RequestInit), including AbortSignal
|
|
35
|
+
* @returns Promise resolving to Response object
|
|
36
|
+
* @throws {Error} Network errors with descriptive messages, or AbortError if request was aborted
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```tsx
|
|
40
|
+
* // Basic usage
|
|
41
|
+
* const response = await safeFetch('/api/users');
|
|
42
|
+
* ```
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```tsx
|
|
46
|
+
* // With abort signal
|
|
47
|
+
* const controller = new AbortController();
|
|
48
|
+
* const response = await safeFetch('/api/users', {
|
|
49
|
+
* signal: controller.signal,
|
|
50
|
+
* method: 'POST',
|
|
51
|
+
* body: JSON.stringify({ name: 'John' }),
|
|
52
|
+
* });
|
|
53
|
+
*
|
|
54
|
+
* // Cancel request
|
|
55
|
+
* controller.abort();
|
|
56
|
+
* ```
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```tsx
|
|
60
|
+
* // Handle network errors
|
|
61
|
+
* try {
|
|
62
|
+
* const response = await safeFetch('/api/users');
|
|
63
|
+
* } catch (error) {
|
|
64
|
+
* if (isAbortError(error)) {
|
|
65
|
+
* // Request was cancelled
|
|
66
|
+
* return;
|
|
67
|
+
* }
|
|
68
|
+
* // Network error: "Network error: Please check your internet connection"
|
|
69
|
+
* console.error(error.message);
|
|
70
|
+
* }
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
export declare function safeFetch(url: string, options?: RequestInit): Promise<Response>;
|
|
74
|
+
/**
|
|
75
|
+
* Extract error message from a failed response.
|
|
76
|
+
* Parses JSON body and returns message/error field, or defaultMsg if not available.
|
|
77
|
+
*
|
|
78
|
+
* @param response - The Response object (typically from a failed request)
|
|
79
|
+
* @param defaultMsg - Default message if parsing fails or no message in body
|
|
80
|
+
* @returns Promise resolving to the error message string
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```tsx
|
|
84
|
+
* const response = await safeFetch('/api/users');
|
|
85
|
+
* if (!response.ok) {
|
|
86
|
+
* const msg = await getErrorMessage(response, 'Failed to fetch users');
|
|
87
|
+
* throw new Error(msg);
|
|
88
|
+
* }
|
|
89
|
+
* ```
|
|
90
|
+
*/
|
|
91
|
+
export declare function getErrorMessage(response: Response, defaultMsg: string): Promise<string>;
|
|
92
|
+
/**
|
|
93
|
+
* Parse JSON response with error handling.
|
|
94
|
+
* Provides better error messages if response is not valid JSON.
|
|
95
|
+
*
|
|
96
|
+
* @param response - The Response object to parse
|
|
97
|
+
* @returns Promise resolving to parsed JSON data
|
|
98
|
+
* @throws {Error} If response body is empty or not valid JSON
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```tsx
|
|
102
|
+
* const response = await safeFetch('/api/users');
|
|
103
|
+
* const users = await parseJsonResponse<User[]>(response);
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
export declare function parseJsonResponse<T>(response: Response): Promise<T>;
|
|
107
|
+
/**
|
|
108
|
+
* Create a standardized API error from a response.
|
|
109
|
+
* Provides user-friendly error messages based on HTTP status codes.
|
|
110
|
+
*
|
|
111
|
+
* @param response - The Response object with error status
|
|
112
|
+
* @param defaultMessage - Default error message if status-specific message not available
|
|
113
|
+
* @returns Error instance with descriptive message
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```tsx
|
|
117
|
+
* const response = await safeFetch('/api/users');
|
|
118
|
+
* if (!response.ok) {
|
|
119
|
+
* throw createApiError(response, 'Failed to fetch users');
|
|
120
|
+
* // Error message: "Failed to fetch users (401: Unauthorized - Please check your session)"
|
|
121
|
+
* }
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
export declare function createApiError(response: Response, defaultMessage: string): Error;
|
|
125
|
+
/**
|
|
126
|
+
* Handle API response with consistent error handling.
|
|
127
|
+
* Checks response status, parses JSON, and provides standardized error messages.
|
|
128
|
+
* This is the recommended way to handle API responses in the SDK.
|
|
129
|
+
*
|
|
130
|
+
* @param response - The Response object to handle
|
|
131
|
+
* @param defaultErrorMessage - Default error message if response is not ok
|
|
132
|
+
* @returns Promise resolving to parsed JSON data
|
|
133
|
+
* @throws {Error} If response is not ok or JSON parsing fails
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* ```tsx
|
|
137
|
+
* const response = await safeFetch('/api/users');
|
|
138
|
+
* const users = await handleApiResponse<User[]>(response, 'Failed to fetch users');
|
|
139
|
+
* ```
|
|
140
|
+
*
|
|
141
|
+
* @example
|
|
142
|
+
* ```tsx
|
|
143
|
+
* // With error handling
|
|
144
|
+
* try {
|
|
145
|
+
* const response = await safeFetch('/api/users');
|
|
146
|
+
* const users = await handleApiResponse<User[]>(response);
|
|
147
|
+
* } catch (error) {
|
|
148
|
+
* // Error message includes status code and descriptive text
|
|
149
|
+
* console.error(error.message);
|
|
150
|
+
* }
|
|
151
|
+
* ```
|
|
152
|
+
*/
|
|
153
|
+
export declare function handleApiResponse<T>(response: Response, defaultErrorMessage?: string): Promise<T>;
|
|
154
|
+
/**
|
|
155
|
+
* Fetch with timeout support.
|
|
156
|
+
* Automatically cancels request if it takes longer than specified timeout.
|
|
157
|
+
*
|
|
158
|
+
* @param url - The URL to fetch
|
|
159
|
+
* @param options - Optional fetch options (RequestInit)
|
|
160
|
+
* @param timeout - Timeout in milliseconds (default: 10000ms / 10 seconds)
|
|
161
|
+
* @returns Promise resolving to Response object
|
|
162
|
+
* @throws {Error} If request times out: "Request timeout after {timeout}ms"
|
|
163
|
+
*
|
|
164
|
+
* @example
|
|
165
|
+
* ```tsx
|
|
166
|
+
* // 5 second timeout
|
|
167
|
+
* const response = await fetchWithTimeout('/api/users', {}, 5000);
|
|
168
|
+
* ```
|
|
169
|
+
*
|
|
170
|
+
* @example
|
|
171
|
+
* ```tsx
|
|
172
|
+
* // Handle timeout
|
|
173
|
+
* try {
|
|
174
|
+
* const response = await fetchWithTimeout('/api/users', {}, 5000);
|
|
175
|
+
* } catch (error) {
|
|
176
|
+
* if (error.message.includes('timeout')) {
|
|
177
|
+
* console.error('Request took too long');
|
|
178
|
+
* }
|
|
179
|
+
* }
|
|
180
|
+
* ```
|
|
181
|
+
*/
|
|
182
|
+
export declare function fetchWithTimeout(url: string, options?: RequestInit, timeout?: number): Promise<Response>;
|
|
@@ -55,6 +55,64 @@ declare class ErrorHandler {
|
|
|
55
55
|
wrapSync<T extends (...args: any[]) => any>(fn: T, context: SDKErrorContext): T;
|
|
56
56
|
}
|
|
57
57
|
export declare const errorHandler: ErrorHandler;
|
|
58
|
+
/**
|
|
59
|
+
* Convenience function to handle an error with context.
|
|
60
|
+
* Uses the global error handler instance.
|
|
61
|
+
*
|
|
62
|
+
* @param error - The error to handle (Error instance, string, or unknown)
|
|
63
|
+
* @param context - Optional context about where the error occurred
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```tsx
|
|
67
|
+
* try {
|
|
68
|
+
* await someOperation();
|
|
69
|
+
* } catch (error) {
|
|
70
|
+
* handleError(error, {
|
|
71
|
+
* component: 'MyComponent',
|
|
72
|
+
* action: 'someOperation',
|
|
73
|
+
* metadata: { userId: '123' },
|
|
74
|
+
* });
|
|
75
|
+
* }
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
58
78
|
export declare function handleError(error: Error | unknown, context?: SDKErrorContext): void;
|
|
79
|
+
/**
|
|
80
|
+
* Handle an error only if it is not an AbortError.
|
|
81
|
+
* Convenience for async code that uses AbortSignal - call this in catch and abort errors are ignored.
|
|
82
|
+
*
|
|
83
|
+
* @param error - The error that occurred
|
|
84
|
+
* @param context - Optional context about where the error occurred
|
|
85
|
+
* @returns true if error was handled, false if it was an abort error (ignored)
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```tsx
|
|
89
|
+
* try {
|
|
90
|
+
* await safeFetch(url, { signal });
|
|
91
|
+
* } catch (error) {
|
|
92
|
+
* handleErrorUnlessAborted(error, { component: 'MyComponent', action: 'fetch' });
|
|
93
|
+
* }
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
export declare function handleErrorUnlessAborted(error: Error | unknown, context?: SDKErrorContext): boolean;
|
|
97
|
+
/**
|
|
98
|
+
* Creates a new SDKError instance with optional code and context.
|
|
99
|
+
* Useful for creating standardized errors throughout the SDK.
|
|
100
|
+
*
|
|
101
|
+
* @param message - Error message
|
|
102
|
+
* @param code - Optional error code (e.g., 'AUTH_FAILED', 'NETWORK_ERROR')
|
|
103
|
+
* @param context - Optional context about where the error occurred
|
|
104
|
+
* @param originalError - Optional original error that caused this error
|
|
105
|
+
* @returns A new SDKError instance
|
|
106
|
+
*
|
|
107
|
+
* @example
|
|
108
|
+
* ```tsx
|
|
109
|
+
* throw createSDKError(
|
|
110
|
+
* 'Failed to authenticate user',
|
|
111
|
+
* 'AUTH_FAILED',
|
|
112
|
+
* { component: 'AuthProvider', action: 'signIn' },
|
|
113
|
+
* originalError
|
|
114
|
+
* );
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
59
117
|
export declare function createSDKError(message: string, code?: string, context?: SDKErrorContext, originalError?: Error): SDKError;
|
|
60
118
|
export {};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Centralized logger for SDK
|
|
3
|
+
* All console output should go through this for consistency and configurable behavior
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Configure the SDK logger
|
|
7
|
+
*/
|
|
8
|
+
export declare function configureLogger(config: {
|
|
9
|
+
enableLogging?: boolean;
|
|
10
|
+
}): void;
|
|
11
|
+
/**
|
|
12
|
+
* Log info (dev only, respects enableLogging)
|
|
13
|
+
*/
|
|
14
|
+
export declare function sdkLog(message: string, ...args: unknown[]): void;
|
|
15
|
+
/**
|
|
16
|
+
* Log warning (dev only, respects enableLogging)
|
|
17
|
+
*/
|
|
18
|
+
export declare function sdkWarn(message: string, ...args: unknown[]): void;
|
|
19
|
+
/**
|
|
20
|
+
* Log error (dev only, respects enableLogging)
|
|
21
|
+
*/
|
|
22
|
+
export declare function sdkLogError(message: string, ...args: unknown[]): void;
|
|
23
|
+
/**
|
|
24
|
+
* Log internal/critical error - always logs.
|
|
25
|
+
* Use when the error handling system itself fails (e.g. user's onError callback throws).
|
|
26
|
+
*/
|
|
27
|
+
export declare function sdkError(message: string, ...args: unknown[]): void;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { DependencyList } from 'react';
|
|
2
|
+
export interface UseAsyncEffectOptions {
|
|
3
|
+
/**
|
|
4
|
+
* Called when the effect promise rejects (except for AbortError which is ignored).
|
|
5
|
+
*/
|
|
6
|
+
onError?: (err: unknown) => void;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Encapsulates the AbortController + async effect pattern.
|
|
10
|
+
* Provides cancellation on cleanup and optional error handling.
|
|
11
|
+
*
|
|
12
|
+
* @param effect - Async function that receives AbortSignal for cancellation
|
|
13
|
+
* @param deps - Dependency array (same as useEffect)
|
|
14
|
+
* @param options - Optional onError callback for unhandled rejections
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```tsx
|
|
18
|
+
* useAsyncEffect(
|
|
19
|
+
* async (signal) => {
|
|
20
|
+
* const response = await safeFetch(url, { signal });
|
|
21
|
+
* const data = await response.json();
|
|
22
|
+
* setData(data);
|
|
23
|
+
* },
|
|
24
|
+
* [url],
|
|
25
|
+
* { onError: (err) => handleError(err, { component: 'MyComponent', action: 'fetch' }) }
|
|
26
|
+
* );
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export declare function useAsyncEffect(effect: (signal: AbortSignal) => Promise<void>, deps: DependencyList, options?: UseAsyncEffectOptions): void;
|
|
@@ -1,2 +1,7 @@
|
|
|
1
1
|
import { type ClassValue } from 'clsx';
|
|
2
|
+
/**
|
|
3
|
+
* Check if running in development mode.
|
|
4
|
+
* Safe for browser bundles where process may be undefined.
|
|
5
|
+
*/
|
|
6
|
+
export declare function isDevelopment(): boolean;
|
|
2
7
|
export declare function cn(...inputs: ClassValue[]): string;
|
|
@@ -1,3 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Main authentication hook for the SDK.
|
|
3
|
+
* Provides authentication state, user session, and auth actions.
|
|
4
|
+
*
|
|
5
|
+
* @returns An object containing:
|
|
6
|
+
* - `user`: Current authenticated user object (null if not authenticated)
|
|
7
|
+
* - `session`: Full session object with user and token (null if not authenticated)
|
|
8
|
+
* - `status`: Current authentication status (loading, redirecting, authenticating, authenticated, unauthenticated)
|
|
9
|
+
* - `isLoading`: Boolean indicating if auth state is being determined
|
|
10
|
+
* - `isAuthenticated`: Boolean indicating if user is authenticated
|
|
11
|
+
* - `isRedirecting`: Boolean indicating if redirecting to OAuth provider
|
|
12
|
+
* - `signIn()`: Function to initiate OAuth sign-in flow
|
|
13
|
+
* - `signOut()`: Function to sign out the current user
|
|
14
|
+
* - `openWorkspaceSettings(section?)`: Function to open workspace settings dialog
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```tsx
|
|
18
|
+
* function MyComponent() {
|
|
19
|
+
* const { user, isAuthenticated, signIn, signOut } = useSaaSAuth();
|
|
20
|
+
*
|
|
21
|
+
* if (!isAuthenticated) {
|
|
22
|
+
* return <button onClick={signIn}>Sign In</button>;
|
|
23
|
+
* }
|
|
24
|
+
*
|
|
25
|
+
* return (
|
|
26
|
+
* <div>
|
|
27
|
+
* <p>Welcome, {user?.name}</p>
|
|
28
|
+
* <button onClick={signOut}>Sign Out</button>
|
|
29
|
+
* </div>
|
|
30
|
+
* );
|
|
31
|
+
* }
|
|
32
|
+
* ```
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```tsx
|
|
36
|
+
* // Handle loading state
|
|
37
|
+
* function App() {
|
|
38
|
+
* const { status, isLoading } = useSaaSAuth();
|
|
39
|
+
*
|
|
40
|
+
* if (isLoading) {
|
|
41
|
+
* return <LoadingSpinner />;
|
|
42
|
+
* }
|
|
43
|
+
*
|
|
44
|
+
* return <MainContent />;
|
|
45
|
+
* }
|
|
46
|
+
* ```
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```tsx
|
|
50
|
+
* // Open workspace settings
|
|
51
|
+
* function SettingsButton() {
|
|
52
|
+
* const { openWorkspaceSettings } = useSaaSAuth();
|
|
53
|
+
*
|
|
54
|
+
* return (
|
|
55
|
+
* <button onClick={() => openWorkspaceSettings('general')}>
|
|
56
|
+
* Open Settings
|
|
57
|
+
* </button>
|
|
58
|
+
* );
|
|
59
|
+
* }
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
1
62
|
export declare function useSaaSAuth(): {
|
|
2
63
|
signIn: () => Promise<void>;
|
|
3
64
|
signOut: () => Promise<void>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { EventData, EventType } from '../events/types';
|
|
2
|
+
import type { IWorkspace } from '../workspace/types';
|
|
2
3
|
export declare enum AuthStatus {
|
|
3
4
|
loading = "loading",
|
|
4
5
|
redirecting = "redirecting",
|
|
@@ -47,4 +48,15 @@ export interface IAuthCallbacks {
|
|
|
47
48
|
* @param data - The event data (type varies based on eventType)
|
|
48
49
|
*/
|
|
49
50
|
handleEvent?: (eventType: EventType, data: EventData) => void | Promise<void>;
|
|
51
|
+
/**
|
|
52
|
+
* Called before switching workspace (e.g. generate token, save state).
|
|
53
|
+
* Used when user clicks "Switch to" and when restoring from storage on page refresh.
|
|
54
|
+
* Switch proceeds only when this resolves; reject to abort.
|
|
55
|
+
*/
|
|
56
|
+
onWorkspaceChange?: (params: OnWorkspaceChangeParams) => Promise<void>;
|
|
57
|
+
}
|
|
58
|
+
export interface OnWorkspaceChangeParams {
|
|
59
|
+
workspace: IWorkspace;
|
|
60
|
+
user: AuthUser | null;
|
|
61
|
+
role: string | null;
|
|
50
62
|
}
|
|
@@ -1,5 +1,10 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { AuthUser } from './types';
|
|
1
|
+
import { IUser } from '../../api/types';
|
|
2
|
+
import type { AuthSession, AuthUser } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* Map IUser from API to AuthUser for session
|
|
5
|
+
* @throws Error if user data is missing required ID or email fields
|
|
6
|
+
*/
|
|
7
|
+
export declare function mapIUserToAuthUser(userData: IUser, orgId: string, clientId: string): AuthUser;
|
|
3
8
|
/**
|
|
4
9
|
* Centralized Session Management
|
|
5
10
|
* Only stores sessionId in localStorage - user data is kept in context only
|
|
@@ -1,5 +1,44 @@
|
|
|
1
1
|
import type { ISettings } from '../types';
|
|
2
|
+
/**
|
|
3
|
+
* Hook to access organization settings from the OS context.
|
|
4
|
+
* Automatically fetches settings when OS config is ready.
|
|
5
|
+
*
|
|
6
|
+
* @returns An object containing:
|
|
7
|
+
* - `settings`: Organization settings object (null if not loaded)
|
|
8
|
+
* - `getSettings(signal?)`: Function to manually fetch settings (supports AbortSignal)
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```tsx
|
|
12
|
+
* function SettingsDisplay() {
|
|
13
|
+
* const { settings } = useSaaSSettings();
|
|
14
|
+
*
|
|
15
|
+
* if (!settings) return <Loading />;
|
|
16
|
+
*
|
|
17
|
+
* return (
|
|
18
|
+
* <div>
|
|
19
|
+
* <p>Organization: {settings.name}</p>
|
|
20
|
+
* <p>Theme: {settings.theme}</p>
|
|
21
|
+
* </div>
|
|
22
|
+
* );
|
|
23
|
+
* }
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```tsx
|
|
28
|
+
* // Manual fetch with abort signal
|
|
29
|
+
* function SettingsLoader() {
|
|
30
|
+
* const { getSettings } = useSaaSSettings();
|
|
31
|
+
*
|
|
32
|
+
* useEffect(() => {
|
|
33
|
+
* const controller = new AbortController();
|
|
34
|
+
* getSettings(controller.signal);
|
|
35
|
+
*
|
|
36
|
+
* return () => controller.abort();
|
|
37
|
+
* }, [getSettings]);
|
|
38
|
+
* }
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
2
41
|
export declare function useSaaSSettings(): {
|
|
3
42
|
settings: ISettings | null | undefined;
|
|
4
|
-
getSettings: () => Promise<ISettings | null>;
|
|
43
|
+
getSettings: (signal?: AbortSignal) => Promise<ISettings | null>;
|
|
5
44
|
};
|
|
@@ -1,4 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hook to access user attributes from the UserProvider.
|
|
3
|
+
* Must be used within a UserProvider component.
|
|
4
|
+
*
|
|
5
|
+
* @returns User context object containing:
|
|
6
|
+
* - `attributes`: Record of user attribute key-value pairs
|
|
7
|
+
* - `isLoading`: Boolean indicating if attributes are being loaded
|
|
8
|
+
* - `error`: Error message string (null if no error)
|
|
9
|
+
* - `refreshAttributes()`: Function to manually refresh attributes
|
|
10
|
+
*
|
|
11
|
+
* @throws {Error} If used outside of UserProvider
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```tsx
|
|
15
|
+
* function UserProfile() {
|
|
16
|
+
* const { attributes, isLoading } = useUserAttributes();
|
|
17
|
+
*
|
|
18
|
+
* if (isLoading) return <Loading />;
|
|
19
|
+
*
|
|
20
|
+
* return (
|
|
21
|
+
* <div>
|
|
22
|
+
* <p>Plan: {attributes?.plan}</p>
|
|
23
|
+
* <p>Company: {attributes?.company}</p>
|
|
24
|
+
* </div>
|
|
25
|
+
* );
|
|
26
|
+
* }
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
1
29
|
export declare function useUserAttributes(): import("./provider").UserContextValue;
|
|
30
|
+
/**
|
|
31
|
+
* Hook to access user feature flags from the UserProvider.
|
|
32
|
+
* Must be used within a UserProvider component.
|
|
33
|
+
*
|
|
34
|
+
* @returns An object containing:
|
|
35
|
+
* - `features`: Record of feature flag key-value pairs (boolean values)
|
|
36
|
+
* - `isLoading`: Boolean indicating if features are being loaded
|
|
37
|
+
* - `error`: Error message string (null if no error)
|
|
38
|
+
* - `refreshFeatures()`: Function to manually refresh features
|
|
39
|
+
* - `isFeatureEnabled(featureId)`: Function to check if a specific feature is enabled
|
|
40
|
+
*
|
|
41
|
+
* @throws {Error} If used outside of UserProvider
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```tsx
|
|
45
|
+
* function FeatureContent() {
|
|
46
|
+
* const { isFeatureEnabled, isLoading } = useUserFeatures();
|
|
47
|
+
*
|
|
48
|
+
* if (isLoading) return <Loading />;
|
|
49
|
+
*
|
|
50
|
+
* if (isFeatureEnabled('premium-feature')) {
|
|
51
|
+
* return <PremiumFeature />;
|
|
52
|
+
* }
|
|
53
|
+
*
|
|
54
|
+
* return <BasicFeature />;
|
|
55
|
+
* }
|
|
56
|
+
* ```
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```tsx
|
|
60
|
+
* // Check multiple features
|
|
61
|
+
* function Dashboard() {
|
|
62
|
+
* const { isFeatureEnabled } = useUserFeatures();
|
|
63
|
+
*
|
|
64
|
+
* return (
|
|
65
|
+
* <div>
|
|
66
|
+
* {isFeatureEnabled('analytics') && <Analytics />}
|
|
67
|
+
* {isFeatureEnabled('reports') && <Reports />}
|
|
68
|
+
* </div>
|
|
69
|
+
* );
|
|
70
|
+
* }
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
2
73
|
export declare function useUserFeatures(): {
|
|
3
74
|
features: Record<string, boolean>;
|
|
4
75
|
isLoading: boolean;
|
|
@@ -1,6 +1,110 @@
|
|
|
1
1
|
import { IUser } from '../../api/types';
|
|
2
|
-
import { WorkspaceSwitcher } from './provider';
|
|
3
2
|
import { IWorkspace, IWorkspaceUser } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* Main workspace management hook for the SDK.
|
|
5
|
+
* Provides workspace state, CRUD operations, and user management.
|
|
6
|
+
*
|
|
7
|
+
* @returns An object containing:
|
|
8
|
+
* - `workspaces`: Array of all workspaces the user has access to
|
|
9
|
+
* - `currentWorkspace`: Currently selected workspace (null if none selected)
|
|
10
|
+
* - `loading`: Boolean indicating if workspaces are being fetched
|
|
11
|
+
* - `error`: Error message string (null if no error)
|
|
12
|
+
* - `refreshing`: Boolean indicating if workspaces are being refreshed in background
|
|
13
|
+
* - `switching`: Boolean - true when a workspace switch is in progress
|
|
14
|
+
* - `fetchWorkspaces()`: Function to fetch all workspaces
|
|
15
|
+
* - `refreshWorkspaces()`: Function to refresh workspaces in background (non-blocking)
|
|
16
|
+
* - `setCurrentWorkspace(workspace)`: Function to set the current workspace (direct, no callback)
|
|
17
|
+
* - `switchToWorkspace(workspace)`: Centralized switch - calls onWorkspaceChange first, then sets workspace
|
|
18
|
+
* - `resetCurrentWorkspace()`: Function to clear the current workspace
|
|
19
|
+
* - `createWorkspace(name, image?)`: Function to create a new workspace
|
|
20
|
+
* - `updateWorkspace(workspace, data)`: Function to update a workspace
|
|
21
|
+
* - `deleteWorkspace(workspaceId)`: Function to delete a workspace (owner only)
|
|
22
|
+
* - `getWorkspace(workspaceId)`: Function to fetch a specific workspace
|
|
23
|
+
* - `getUsers(workspaceId)`: Function to fetch users in a workspace
|
|
24
|
+
* - `addUser(workspaceId, email, role)`: Function to add a user to a workspace
|
|
25
|
+
* - `removeUser(workspaceId, userId)`: Function to remove a user from a workspace
|
|
26
|
+
* - `updateUser(workspaceId, userId, config)`: Function to update a user in a workspace
|
|
27
|
+
* - `getProfile()`: Function to fetch current user profile
|
|
28
|
+
* - `updateUserProfile(config)`: Function to update current user profile
|
|
29
|
+
* - `allFeatures`: Array of all available feature flags
|
|
30
|
+
* - `getFeatures()`: Function to fetch all available features
|
|
31
|
+
* - `updateFeature(workspaceId, key, value)`: Function to update a feature flag
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```tsx
|
|
35
|
+
* function WorkspaceList() {
|
|
36
|
+
* const { workspaces, loading, fetchWorkspaces } = useSaaSWorkspaces();
|
|
37
|
+
*
|
|
38
|
+
* useEffect(() => {
|
|
39
|
+
* fetchWorkspaces();
|
|
40
|
+
* }, [fetchWorkspaces]);
|
|
41
|
+
*
|
|
42
|
+
* if (loading) return <Loading />;
|
|
43
|
+
*
|
|
44
|
+
* return (
|
|
45
|
+
* <ul>
|
|
46
|
+
* {workspaces.map(ws => (
|
|
47
|
+
* <li key={ws._id}>{ws.name}</li>
|
|
48
|
+
* ))}
|
|
49
|
+
* </ul>
|
|
50
|
+
* );
|
|
51
|
+
* }
|
|
52
|
+
* ```
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```tsx
|
|
56
|
+
* // Create a new workspace
|
|
57
|
+
* function CreateWorkspace() {
|
|
58
|
+
* const { createWorkspace } = useSaaSWorkspaces();
|
|
59
|
+
*
|
|
60
|
+
* const handleCreate = async () => {
|
|
61
|
+
* try {
|
|
62
|
+
* await createWorkspace('My Workspace', 'https://example.com/logo.png');
|
|
63
|
+
* } catch (error) {
|
|
64
|
+
* console.error('Failed to create workspace:', error);
|
|
65
|
+
* }
|
|
66
|
+
* };
|
|
67
|
+
*
|
|
68
|
+
* return <button onClick={handleCreate}>Create Workspace</button>;
|
|
69
|
+
* }
|
|
70
|
+
* ```
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* ```tsx
|
|
74
|
+
* // Delete workspace (owner only)
|
|
75
|
+
* function DeleteWorkspaceButton({ workspaceId }) {
|
|
76
|
+
* const { deleteWorkspace } = useSaaSWorkspaces();
|
|
77
|
+
*
|
|
78
|
+
* const handleDelete = async () => {
|
|
79
|
+
* if (!confirm('Are you sure?')) return;
|
|
80
|
+
* try {
|
|
81
|
+
* await deleteWorkspace(workspaceId);
|
|
82
|
+
* } catch (error) {
|
|
83
|
+
* // Error: "Only the workspace creator can delete the workspace"
|
|
84
|
+
* alert(error.message);
|
|
85
|
+
* }
|
|
86
|
+
* };
|
|
87
|
+
*
|
|
88
|
+
* return <button onClick={handleDelete}>Delete</button>;
|
|
89
|
+
* }
|
|
90
|
+
* ```
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```tsx
|
|
94
|
+
* // Edge case: Workspace removed from user's access
|
|
95
|
+
* function WorkspaceContent() {
|
|
96
|
+
* const { currentWorkspace, workspaces } = useSaaSWorkspaces();
|
|
97
|
+
*
|
|
98
|
+
* // If current workspace is not in the list, it was removed
|
|
99
|
+
* // The hook automatically switches to first available workspace
|
|
100
|
+
* if (!currentWorkspace) {
|
|
101
|
+
* return <p>No workspace selected</p>;
|
|
102
|
+
* }
|
|
103
|
+
*
|
|
104
|
+
* return <div>{currentWorkspace.name}</div>;
|
|
105
|
+
* }
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
4
108
|
export declare const useSaaSWorkspaces: () => {
|
|
5
109
|
workspaces: IWorkspace[];
|
|
6
110
|
loading: boolean;
|
|
@@ -8,16 +112,19 @@ export declare const useSaaSWorkspaces: () => {
|
|
|
8
112
|
fetchWorkspaces: () => Promise<void>;
|
|
9
113
|
refreshWorkspaces: () => Promise<void>;
|
|
10
114
|
refreshing: boolean;
|
|
11
|
-
WorkspaceSwitcher: typeof WorkspaceSwitcher;
|
|
12
115
|
currentWorkspace: IWorkspace | null;
|
|
13
|
-
setCurrentWorkspace: (ws: IWorkspace
|
|
116
|
+
setCurrentWorkspace: (ws: IWorkspace, options?: {
|
|
117
|
+
forceEmit?: boolean;
|
|
118
|
+
}) => void;
|
|
119
|
+
switchToWorkspace: (ws: IWorkspace, options?: {
|
|
120
|
+
forceEmit?: boolean;
|
|
121
|
+
}) => Promise<void>;
|
|
14
122
|
resetCurrentWorkspace: () => void;
|
|
15
123
|
createWorkspace: (name: string, image: string) => Promise<void>;
|
|
16
124
|
allFeatures: import("./types").IWorkspaceFeature[];
|
|
17
125
|
getFeatures: () => Promise<import("./types").IWorkspaceFeature[] | null>;
|
|
18
126
|
updateFeature: (workspaceId: string, key: string, value: boolean) => Promise<IWorkspace>;
|
|
19
127
|
getWorkspace: (workspaceId: string) => Promise<IWorkspace>;
|
|
20
|
-
switching: boolean;
|
|
21
128
|
updateWorkspace: (ws: IWorkspace, _data: Partial<IWorkspace>) => Promise<void>;
|
|
22
129
|
getUsers: (workspaceId: string) => Promise<IWorkspaceUser[]>;
|
|
23
130
|
addUser: (workspaceId: string, email: string, role: string) => Promise<{
|
|
@@ -40,4 +147,5 @@ export declare const useSaaSWorkspaces: () => {
|
|
|
40
147
|
deleteWorkspace: (workspaceId: string) => Promise<{
|
|
41
148
|
success: boolean;
|
|
42
149
|
}>;
|
|
150
|
+
switching: boolean;
|
|
43
151
|
};
|
|
@@ -5,5 +5,4 @@ export declare const WorkspaceProvider: ({ children }: {
|
|
|
5
5
|
}) => import("react/jsx-runtime").JSX.Element;
|
|
6
6
|
export declare function WorkspaceSwitcher(props: {
|
|
7
7
|
trigger: (isLoading: boolean, currentWorkspace: IWorkspace | null) => ReactNode;
|
|
8
|
-
onWorkspaceChange: (workspace: IWorkspace) => Promise<void>;
|
|
9
8
|
}): import("react/jsx-runtime").JSX.Element;
|