Skip to content

Commit e948782

Browse files
JOHNJOHN
authored andcommitted
Fix PubkyAPISDK window error with better error handling
- Add try-catch around @synonymdev/pubky import - Check window availability before and after import - Use console directly in error paths to avoid logger circular issues - Prevents 'window is not defined' errors in service worker contexts
1 parent e51dbbc commit e948782

File tree

1 file changed

+33
-7
lines changed

1 file changed

+33
-7
lines changed

src/utils/pubky-api-sdk.ts

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,20 +43,44 @@ class PubkyAPISDK {
4343
private async initializePubky() {
4444
if (!this.isClientContextAvailable()) {
4545
const error = new Error('Pubky Client requires window object (not available in service workers)');
46-
logger.warn('PubkyAPISDK', 'Cannot initialize Pubky Client in service worker context', error);
46+
// Use console directly to avoid logger issues
47+
console.warn('[PubkyAPISDK] Cannot initialize Pubky Client in service worker context', error);
4748
throw error;
4849
}
4950

5051
try {
51-
const { Client } = await import('@synonymdev/pubky');
52+
// Dynamic import with error handling - the package itself might access window
53+
const pubkyModule = await import('@synonymdev/pubky').catch((importError) => {
54+
// If import fails due to window issues, wrap the error
55+
if (importError.message?.includes('window') || !this.isClientContextAvailable()) {
56+
throw new Error('Pubky Client requires window object (not available in service workers)');
57+
}
58+
throw importError;
59+
});
60+
61+
const { Client } = pubkyModule;
62+
63+
// Check window again before creating Client (it might access window in constructor)
64+
if (!this.isClientContextAvailable()) {
65+
throw new Error('Pubky Client requires window object (not available in service workers)');
66+
}
67+
5268
this.pubky = new Client();
5369
logger.info('PubkyAPISDK', 'Pubky Client initialized');
5470
} catch (error) {
55-
ErrorHandler.handle(error, {
56-
context: 'PubkyAPISDK',
57-
data: { operation: 'initializePubky' },
58-
showNotification: false,
59-
});
71+
// Use console directly to avoid circular logger issues
72+
console.error('[PubkyAPISDK] Failed to initialize Pubky Client', error);
73+
74+
// Only use ErrorHandler if it won't cause issues
75+
try {
76+
ErrorHandler.handle(error as Error, {
77+
context: 'PubkyAPISDK',
78+
data: { operation: 'initializePubky' },
79+
showNotification: false,
80+
});
81+
} catch {
82+
// Ignore if ErrorHandler fails
83+
}
6084
throw error;
6185
}
6286
}
@@ -803,5 +827,7 @@ class PubkyAPISDK {
803827

804828
}
805829

830+
// Export singleton instance - constructor is now safe (doesn't initialize)
831+
// Methods that need window will check before using it
806832
export const pubkyAPISDK = PubkyAPISDK.getInstance();
807833

0 commit comments

Comments
 (0)