@buildbase/sdk 0.0.12 → 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 CHANGED
@@ -95,6 +95,11 @@ export default function SaaSProvider(props: { children: React.ReactNode }) {
95
95
  // Handle SDK events (user created, workspace changed, etc.)
96
96
  console.log('SDK Event:', eventType, data);
97
97
  },
98
+ onWorkspaceChange: async ({ workspace, user, role }) => {
99
+ // Called before switching workspace (e.g. generate token). Used on "Switch to" and page refresh/restore.
100
+ // Switch proceeds only when this resolves; reject to abort.
101
+ console.log('Switching to workspace:', workspace.name, 'as', role);
102
+ },
98
103
  },
99
104
  }}
100
105
  >
@@ -124,7 +129,7 @@ export default App;
124
129
 
125
130
  ### 4. Workspace Management
126
131
 
127
- The WorkspaceSwitcher component uses a render prop pattern, giving you full control over the UI:
132
+ The WorkspaceSwitcher component uses a render prop pattern, giving you full control over the UI. Configure `onWorkspaceChange` in `auth.callbacks` (SaaSOSProvider) to handle workspace switches—used when clicking "Switch to" and when restoring from storage on page refresh. The callback receives `{ workspace, user, role }` so you don't need to look up the user's role:
128
133
 
129
134
  ```tsx
130
135
  import React from 'react';
@@ -160,10 +165,6 @@ function WorkspaceExample() {
160
165
  </div>
161
166
  );
162
167
  }}
163
- onWorkspaceChange={async workspace => {
164
- // Handle workspace change
165
- console.log('Workspace changed to:', workspace);
166
- }}
167
168
  />
168
169
  );
169
170
  }
@@ -372,10 +373,12 @@ function WorkspaceManager() {
372
373
  currentWorkspace, // Currently selected workspace
373
374
  loading, // Loading state
374
375
  refreshing, // Refreshing state
376
+ switching, // True when a workspace switch is in progress
375
377
  error, // Error message
376
378
  fetchWorkspaces, // Fetch all workspaces
377
379
  refreshWorkspaces, // Background refresh
378
- setCurrentWorkspace, // Switch workspace
380
+ setCurrentWorkspace, // Direct workspace set (bypasses onWorkspaceChange)
381
+ switchToWorkspace, // Full switch flow: onWorkspaceChange first, then set workspace
379
382
  createWorkspace, // Create new workspace
380
383
  updateWorkspace, // Update workspace
381
384
  deleteWorkspace, // Delete workspace
@@ -460,7 +463,7 @@ import { SaaSOSProvider, eventEmitter } from '@buildbase/sdk';
460
463
 
461
464
  - `user:created` - User account created
462
465
  - `user:updated` - User profile updated
463
- - `workspace:changed` - Workspace switched
466
+ - `workspace:changed` - Workspace switched (fires after switch completes; use `onWorkspaceChange` for prep before switch)
464
467
  - `workspace:created` - New workspace created
465
468
  - `workspace:updated` - Workspace updated
466
469
  - `workspace:deleted` - Workspace deleted
@@ -557,8 +560,15 @@ interface IAuthConfig {
557
560
  handleAuthentication: (code: string) => Promise<{ sessionId: string }>;
558
561
  onSignOut?: () => Promise<void>;
559
562
  handleEvent?: (eventType: EventType, data: EventData) => void | Promise<void>;
563
+ onWorkspaceChange?: (params: OnWorkspaceChangeParams) => Promise<void>;
560
564
  };
561
565
  }
566
+
567
+ interface OnWorkspaceChangeParams {
568
+ workspace: IWorkspace;
569
+ user: AuthUser | null;
570
+ role: string | null; // User's role in this workspace
571
+ }
562
572
  ```
563
573
 
564
574
  ### Validation Requirements
@@ -683,7 +693,7 @@ import { useSaaSWorkspaces } from '@buildbase/sdk';
683
693
  import { useEffect } from 'react';
684
694
 
685
695
  function App() {
686
- const { currentWorkspace, setCurrentWorkspace } = useSaaSWorkspaces();
696
+ const { currentWorkspace, switching } = useSaaSWorkspaces();
687
697
 
688
698
  useEffect(() => {
689
699
  if (currentWorkspace) {
@@ -693,10 +703,15 @@ function App() {
693
703
  }
694
704
  }, [currentWorkspace]);
695
705
 
706
+ // Show loading during switch (switchingToId !== null)
707
+ if (switching) return <LoadingOverlay />;
708
+
696
709
  return <YourApp />;
697
710
  }
698
711
  ```
699
712
 
713
+ For token generation or prep before switching, configure `onWorkspaceChange` in auth callbacks (see Quick Start)—it receives `{ workspace, user, role }`.
714
+
700
715
  ### Pattern 6: Error Boundary with Custom Fallback
701
716
 
702
717
  ```tsx
@@ -863,7 +878,7 @@ A: Yes, as long as you're using React 19+.
863
878
  A: Use the `trigger` render prop to fully customize the UI.
864
879
 
865
880
  **Q: Can I use multiple workspaces simultaneously?**
866
- A: No, the SDK manages one current workspace at a time. Switch between workspaces using `setCurrentWorkspace()`.
881
+ A: No, the SDK manages one current workspace at a time. Use `switchToWorkspace()` (runs `onWorkspaceChange` first) or `setCurrentWorkspace()` (direct set, bypasses callback).
867
882
 
868
883
  **Q: How do I handle offline scenarios?**
869
884
  A: The SDK stores session data in localStorage. Handle offline scenarios in your `handleAuthentication` callback.
@@ -933,9 +948,13 @@ try {
933
948
 
934
949
  ```tsx
935
950
  // ✅ Good
936
- const { currentWorkspace, setCurrentWorkspace } = useSaaSWorkspaces();
951
+ const { currentWorkspace, switchToWorkspace, switching } = useSaaSWorkspaces();
952
+ // switchToWorkspace: runs onWorkspaceChange first (token gen, etc.)
953
+ // switching: true when switch is in progress
937
954
  ```
938
955
 
956
+ ✅ **Do**: Configure `onWorkspaceChange` in auth callbacks for token generation—receives `{ workspace, user, role }`.
957
+
939
958
  ❌ **Don't**: Manually manage workspace state.
940
959
 
941
960
  ```tsx
@@ -987,17 +1006,19 @@ const { signIn, status } = useSaaSAuth();
987
1006
 
988
1007
  ### 6. Event Handling
989
1008
 
990
- ✅ **Do**: Handle events in your provider configuration.
1009
+ ✅ **Do**: Handle events in your provider configuration. Use `onWorkspaceChange` for prep before switch (e.g. generate token), and `handleEvent` for post-switch notifications.
991
1010
 
992
1011
  ```tsx
993
1012
  // ✅ Good
994
1013
  <SaaSOSProvider
995
1014
  auth={{
996
1015
  callbacks: {
1016
+ onWorkspaceChange: async ({ workspace, user, role }) => {
1017
+ await generateTokenForWorkspace(workspace._id, user?.id, role);
1018
+ },
997
1019
  handleEvent: async (eventType, data) => {
998
- // Handle events
999
1020
  if (eventType === 'workspace:changed') {
1000
- // Update your app state
1021
+ // Workspace already switched; update app state
1001
1022
  }
1002
1023
  },
1003
1024
  },
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as react from 'react';
2
- import react__default, { ReactNode, Component } from 'react';
2
+ import react__default, { ReactNode } from 'react';
3
3
  import * as react_jsx_runtime from 'react/jsx-runtime';
4
4
 
5
5
  interface IDocument {
@@ -355,6 +355,17 @@ interface IAuthCallbacks {
355
355
  * @param data - The event data (type varies based on eventType)
356
356
  */
357
357
  handleEvent?: (eventType: EventType, data: EventData) => void | Promise<void>;
358
+ /**
359
+ * Called before switching workspace (e.g. generate token, save state).
360
+ * Used when user clicks "Switch to" and when restoring from storage on page refresh.
361
+ * Switch proceeds only when this resolves; reject to abort.
362
+ */
363
+ onWorkspaceChange?: (params: OnWorkspaceChangeParams) => Promise<void>;
364
+ }
365
+ interface OnWorkspaceChangeParams {
366
+ workspace: IWorkspace;
367
+ user: AuthUser | null;
368
+ role: string | null;
358
369
  }
359
370
 
360
371
  interface ISettings {
@@ -885,11 +896,6 @@ declare function useUserFeatures(): {
885
896
  isFeatureEnabled: (featureId: string) => boolean;
886
897
  };
887
898
 
888
- declare function WorkspaceSwitcher(props: {
889
- trigger: (isLoading: boolean, currentWorkspace: IWorkspace | null) => ReactNode;
890
- onWorkspaceChange: (workspace: IWorkspace) => Promise<void>;
891
- }): react_jsx_runtime.JSX.Element;
892
-
893
899
  /**
894
900
  * Main workspace management hook for the SDK.
895
901
  * Provides workspace state, CRUD operations, and user management.
@@ -900,11 +906,11 @@ declare function WorkspaceSwitcher(props: {
900
906
  * - `loading`: Boolean indicating if workspaces are being fetched
901
907
  * - `error`: Error message string (null if no error)
902
908
  * - `refreshing`: Boolean indicating if workspaces are being refreshed in background
903
- * - `switching`: Boolean indicating if workspace is being switched
904
- * - `WorkspaceSwitcher`: Component for switching between workspaces
909
+ * - `switching`: Boolean - true when a workspace switch is in progress
905
910
  * - `fetchWorkspaces()`: Function to fetch all workspaces
906
911
  * - `refreshWorkspaces()`: Function to refresh workspaces in background (non-blocking)
907
- * - `setCurrentWorkspace(workspace)`: Function to set the current workspace
912
+ * - `setCurrentWorkspace(workspace)`: Function to set the current workspace (direct, no callback)
913
+ * - `switchToWorkspace(workspace)`: Centralized switch - calls onWorkspaceChange first, then sets workspace
908
914
  * - `resetCurrentWorkspace()`: Function to clear the current workspace
909
915
  * - `createWorkspace(name, image?)`: Function to create a new workspace
910
916
  * - `updateWorkspace(workspace, data)`: Function to update a workspace
@@ -1002,16 +1008,19 @@ declare const useSaaSWorkspaces: () => {
1002
1008
  fetchWorkspaces: () => Promise<void>;
1003
1009
  refreshWorkspaces: () => Promise<void>;
1004
1010
  refreshing: boolean;
1005
- WorkspaceSwitcher: typeof WorkspaceSwitcher;
1006
1011
  currentWorkspace: IWorkspace | null;
1007
- setCurrentWorkspace: (ws: IWorkspace) => void;
1012
+ setCurrentWorkspace: (ws: IWorkspace, options?: {
1013
+ forceEmit?: boolean;
1014
+ }) => void;
1015
+ switchToWorkspace: (ws: IWorkspace, options?: {
1016
+ forceEmit?: boolean;
1017
+ }) => Promise<void>;
1008
1018
  resetCurrentWorkspace: () => void;
1009
1019
  createWorkspace: (name: string, image: string) => Promise<void>;
1010
1020
  allFeatures: IWorkspaceFeature[];
1011
1021
  getFeatures: () => Promise<IWorkspaceFeature[] | null>;
1012
1022
  updateFeature: (workspaceId: string, key: string, value: boolean) => Promise<IWorkspace>;
1013
1023
  getWorkspace: (workspaceId: string) => Promise<IWorkspace>;
1014
- switching: boolean;
1015
1024
  updateWorkspace: (ws: IWorkspace, _data: Partial<IWorkspace>) => Promise<void>;
1016
1025
  getUsers: (workspaceId: string) => Promise<IWorkspaceUser[]>;
1017
1026
  addUser: (workspaceId: string, email: string, role: string) => Promise<{
@@ -1034,8 +1043,13 @@ declare const useSaaSWorkspaces: () => {
1034
1043
  deleteWorkspace: (workspaceId: string) => Promise<{
1035
1044
  success: boolean;
1036
1045
  }>;
1046
+ switching: boolean;
1037
1047
  };
1038
1048
 
1049
+ declare function WorkspaceSwitcher(props: {
1050
+ trigger: (isLoading: boolean, currentWorkspace: IWorkspace | null) => ReactNode;
1051
+ }): react_jsx_runtime.JSX.Element;
1052
+
1039
1053
  /**
1040
1054
  * Hook to get and manage the current subscription for a workspace.
1041
1055
  * Automatically fetches subscription when workspaceId changes.
@@ -1544,185 +1558,5 @@ declare class EventEmitter {
1544
1558
  }
1545
1559
  declare const eventEmitter: EventEmitter;
1546
1560
 
1547
- interface ErrorBoundaryProps {
1548
- children: ReactNode;
1549
- /**
1550
- * Fallback UI to render when an error occurs
1551
- */
1552
- fallback?: ReactNode | ((error: Error, resetError: () => void) => ReactNode);
1553
- /**
1554
- * Called when an error is caught
1555
- */
1556
- onError?: (error: Error, errorInfo: react__default.ErrorInfo) => void;
1557
- /**
1558
- * Whether to reset error state when children change
1559
- * @default true
1560
- */
1561
- resetOnPropsChange?: boolean;
1562
- }
1563
- interface ErrorBoundaryState {
1564
- hasError: boolean;
1565
- error: Error | null;
1566
- }
1567
- /**
1568
- * Error Boundary component for catching React component errors.
1569
- * Wraps SDK components to prevent crashes from propagating to the entire app.
1570
- * Automatically logs errors using the SDK error handler.
1571
- *
1572
- * @example
1573
- * ```tsx
1574
- * function App() {
1575
- * return (
1576
- * <SDKErrorBoundary
1577
- * fallback={(error, reset) => (
1578
- * <div>
1579
- * <p>Error: {error.message}</p>
1580
- * <button onClick={reset}>Try Again</button>
1581
- * </div>
1582
- * )}
1583
- * onError={(error, errorInfo) => {
1584
- * // Custom error reporting
1585
- * reportError(error, errorInfo);
1586
- * }}
1587
- * >
1588
- * <YourApp />
1589
- * </SDKErrorBoundary>
1590
- * );
1591
- * }
1592
- * ```
1593
- *
1594
- * @example
1595
- * ```tsx
1596
- * // Simple usage with default fallback
1597
- * function App() {
1598
- * return (
1599
- * <SDKErrorBoundary>
1600
- * <YourApp />
1601
- * </SDKErrorBoundary>
1602
- * );
1603
- * }
1604
- * ```
1605
- *
1606
- * @example
1607
- * ```tsx
1608
- * // Disable auto-reset on props change
1609
- * function App() {
1610
- * return (
1611
- * <SDKErrorBoundary resetOnPropsChange={false}>
1612
- * <YourApp />
1613
- * </SDKErrorBoundary>
1614
- * );
1615
- * }
1616
- * ```
1617
- */
1618
- declare class SDKErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
1619
- constructor(props: ErrorBoundaryProps);
1620
- static getDerivedStateFromError(error: Error): ErrorBoundaryState;
1621
- componentDidCatch(error: Error, errorInfo: react__default.ErrorInfo): void;
1622
- componentDidUpdate(prevProps: ErrorBoundaryProps): void;
1623
- resetError: () => void;
1624
- render(): ReactNode;
1625
- }
1626
-
1627
- /**
1628
- * Centralized Error Handler for SDK
1629
- * Provides consistent error handling, logging, and user-facing error management
1630
- */
1631
- interface SDKErrorContext {
1632
- component?: string;
1633
- action?: string;
1634
- metadata?: Record<string, unknown>;
1635
- }
1636
- declare class SDKError extends Error {
1637
- readonly code?: string | undefined;
1638
- readonly context?: SDKErrorContext | undefined;
1639
- readonly originalError?: Error | undefined;
1640
- constructor(message: string, code?: string | undefined, context?: SDKErrorContext | undefined, originalError?: Error | undefined);
1641
- }
1642
- interface ErrorHandlerConfig {
1643
- /**
1644
- * Custom error callback for handling errors
1645
- * @param error - The error that occurred
1646
- * @param context - Additional context about where the error occurred
1647
- */
1648
- onError?: (error: Error, context: SDKErrorContext) => void;
1649
- /**
1650
- * Whether to log errors to console in development
1651
- * @default true
1652
- */
1653
- enableConsoleLogging?: boolean;
1654
- /**
1655
- * Whether to show user-facing error notifications
1656
- * @default false
1657
- */
1658
- showUserNotifications?: boolean;
1659
- }
1660
- declare class ErrorHandler {
1661
- private config;
1662
- /**
1663
- * Configure the error handler
1664
- */
1665
- configure(config: Partial<ErrorHandlerConfig>): void;
1666
- /**
1667
- * Handle an error with context
1668
- */
1669
- handleError(error: Error | unknown, context?: SDKErrorContext): void;
1670
- /**
1671
- * Notify user of error (placeholder for notification system)
1672
- */
1673
- private notifyUser;
1674
- /**
1675
- * Create a safe error handler wrapper for async functions
1676
- */
1677
- wrapAsync<T extends (...args: any[]) => Promise<any>>(fn: T, context: SDKErrorContext): T;
1678
- /**
1679
- * Create a safe error handler wrapper for sync functions
1680
- */
1681
- wrapSync<T extends (...args: any[]) => any>(fn: T, context: SDKErrorContext): T;
1682
- }
1683
- declare const errorHandler: ErrorHandler;
1684
- /**
1685
- * Convenience function to handle an error with context.
1686
- * Uses the global error handler instance.
1687
- *
1688
- * @param error - The error to handle (Error instance, string, or unknown)
1689
- * @param context - Optional context about where the error occurred
1690
- *
1691
- * @example
1692
- * ```tsx
1693
- * try {
1694
- * await someOperation();
1695
- * } catch (error) {
1696
- * handleError(error, {
1697
- * component: 'MyComponent',
1698
- * action: 'someOperation',
1699
- * metadata: { userId: '123' },
1700
- * });
1701
- * }
1702
- * ```
1703
- */
1704
- declare function handleError(error: Error | unknown, context?: SDKErrorContext): void;
1705
- /**
1706
- * Creates a new SDKError instance with optional code and context.
1707
- * Useful for creating standardized errors throughout the SDK.
1708
- *
1709
- * @param message - Error message
1710
- * @param code - Optional error code (e.g., 'AUTH_FAILED', 'NETWORK_ERROR')
1711
- * @param context - Optional context about where the error occurred
1712
- * @param originalError - Optional original error that caused this error
1713
- * @returns A new SDKError instance
1714
- *
1715
- * @example
1716
- * ```tsx
1717
- * throw createSDKError(
1718
- * 'Failed to authenticate user',
1719
- * 'AUTH_FAILED',
1720
- * { component: 'AuthProvider', action: 'signIn' },
1721
- * originalError
1722
- * );
1723
- * ```
1724
- */
1725
- declare function createSDKError(message: string, code?: string, context?: SDKErrorContext, originalError?: Error): SDKError;
1726
-
1727
- export { ApiVersion, AuthStatus, BetaForm, SDKErrorBoundary as ErrorBoundary, SDKError, SDKErrorBoundary, SaaSOSProvider, WhenAuthenticated, WhenRoles, WhenUnauthenticated, WhenUserFeatureDisabled, WhenUserFeatureEnabled, WhenWorkspaceFeatureDisabled, WhenWorkspaceFeatureEnabled, WhenWorkspaceRoles, WorkspaceSwitcher, createSDKError, errorHandler, eventEmitter, handleError, useCreateCheckoutSession, useInvoice, useInvoices, usePlanGroup, usePlanGroupVersions, useSaaSAuth, useSaaSSettings, useSaaSWorkspaces, useSubscription, useSubscriptionManagement, useUpdateSubscription, useUserAttributes, useUserFeatures };
1728
- export type { BillingInterval, ErrorHandlerConfig, EventData, EventType, IBasePricing, ICheckoutSessionRequest, ICheckoutSessionResponse, IEventCallbacks, IInvoice, IInvoiceListResponse, IInvoiceResponse, IPlan, IPlanGroup, IPlanGroupLatestVersion, IPlanGroupResponse, IPlanGroupVersion, IPlanGroupVersionWithPlans, IPlanGroupVersionsResponse, IPlanVersion, IPlanVersionWithPlan, IQuotaValue, ISubscription, ISubscriptionItem, ISubscriptionResponse, ISubscriptionUpdateRequest, ISubscriptionUpdateResponse, InvoiceStatus, SDKErrorContext, UserCreatedEventData, UserUpdatedEventData, WorkspaceChangedEventData, WorkspaceCreatedEventData, WorkspaceDeletedEventData, WorkspaceUpdatedEventData, WorkspaceUserAddedEventData, WorkspaceUserRemovedEventData, WorkspaceUserRoleChangedEventData };
1561
+ export { ApiVersion, AuthStatus, BetaForm, SaaSOSProvider, WhenAuthenticated, WhenRoles, WhenUnauthenticated, WhenUserFeatureDisabled, WhenUserFeatureEnabled, WhenWorkspaceFeatureDisabled, WhenWorkspaceFeatureEnabled, WhenWorkspaceRoles, WorkspaceSwitcher, eventEmitter, useCreateCheckoutSession, useInvoice, useInvoices, usePlanGroup, usePlanGroupVersions, useSaaSAuth, useSaaSSettings, useSaaSWorkspaces, useSubscription, useSubscriptionManagement, useUpdateSubscription, useUserAttributes, useUserFeatures };
1562
+ export type { BillingInterval, EventData, EventType, IBasePricing, ICheckoutSessionRequest, ICheckoutSessionResponse, IEventCallbacks, IInvoice, IInvoiceListResponse, IInvoiceResponse, IPlan, IPlanGroup, IPlanGroupLatestVersion, IPlanGroupResponse, IPlanGroupVersion, IPlanGroupVersionWithPlans, IPlanGroupVersionsResponse, IPlanVersion, IPlanVersionWithPlan, IQuotaValue, ISubscription, ISubscriptionItem, ISubscriptionResponse, ISubscriptionUpdateRequest, ISubscriptionUpdateResponse, InvoiceStatus, OnWorkspaceChangeParams, UserCreatedEventData, UserUpdatedEventData, WorkspaceChangedEventData, WorkspaceCreatedEventData, WorkspaceDeletedEventData, WorkspaceUpdatedEventData, WorkspaceUserAddedEventData, WorkspaceUserRemovedEventData, WorkspaceUserRoleChangedEventData };