Skip to content

Commit 7e44460

Browse files
committed
chore: update comments
1 parent c80adf1 commit 7e44460

22 files changed

+199
-108
lines changed

CLAUDE.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,54 @@ For multi-step tasks, state a brief plan:
5555
```
5656

5757
Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.
58+
59+
## 5. Comment Style
60+
61+
**Consistent, purposeful comments. Not noise.**
62+
63+
### JSDoc for public APIs
64+
Every exported function, interface, and type gets JSDoc documentation:
65+
```typescript
66+
/**
67+
* Brief description of what it does
68+
*
69+
* @param foo - Description of parameter
70+
* @returns Description of return value
71+
*/
72+
export function myFunction(foo: string): number { ... }
73+
```
74+
75+
### Section markers inside functions
76+
Use `/** SECTION NAME */` to mark logical sections within complex functions:
77+
```typescript
78+
function complexFunction() {
79+
/** PARSE OPTIONS */
80+
const { foo, bar } = options;
81+
82+
/** VALIDATE INPUT */
83+
if (!foo) throw new Error('foo required');
84+
85+
/** EXECUTE MAIN LOGIC */
86+
const result = doSomething(foo, bar);
87+
88+
/** CLEANUP */
89+
return result;
90+
}
91+
```
92+
93+
Common section names: `STATE`, `REFS`, `GUARDS`, `HELPERS`, `CLEANUP`, `EFFECT 1: ...`, `HANDLE ERROR`
94+
95+
### Inline explanations
96+
Use `// comment` for explaining specific logic:
97+
```typescript
98+
// Only sync if auto-sync is not explicitly disabled
99+
const shouldAutoSync = options?.autoSync !== false;
100+
101+
// On Android, the native call blocks for ~10-15s if offline
102+
if (Platform.OS === 'android') { ... }
103+
```
104+
105+
### What NOT to comment
106+
- Obvious code (`// increment counter` before `count++`)
107+
- Code that's already clear from good naming
108+
- Every single line - only where it adds value

src/core/background/backgroundSyncConfig.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export interface BackgroundSyncConfig {
1414
debug?: boolean;
1515
}
1616

17-
// Storage key for persisted config
17+
/** STORAGE KEY */
1818
const CONFIG_STORAGE_KEY = 'sqlite_sync_background_config';
1919

2020
/**
@@ -44,13 +44,15 @@ export async function persistConfig(
4444
): Promise<void> {
4545
const logger = createLogger(config.debug ?? false);
4646

47+
/** GUARD: SECURE STORE REQUIRED */
4748
if (!ExpoSecureStore) {
4849
logger.warn(
4950
'⚠️ expo-secure-store not found. Background/terminated sync will not work.'
5051
);
5152
return;
5253
}
5354

55+
/** SAVE CONFIG */
5456
try {
5557
const configJson = JSON.stringify(config);
5658
await ExpoSecureStore.setItemAsync(CONFIG_STORAGE_KEY, configJson);

src/core/background/backgroundSyncRegistry.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,19 @@ export async function registerBackgroundSync(
1919
): Promise<void> {
2020
const logger = createLogger(config.debug ?? false);
2121

22+
/** GUARD: DEPENDENCIES REQUIRED */
2223
if (!isBackgroundSyncAvailable()) {
2324
logger.warn(
2425
'⚠️ Background sync dependencies not available (expo-notifications, expo-task-manager, expo-secure-store)'
2526
);
2627
return;
2728
}
2829

29-
// Persist config for background/terminated task execution
30+
/** PERSIST CONFIG */
31+
// Config is needed for background/terminated task execution
3032
await persistConfig(config);
3133

32-
// Register the task to handle background notifications
34+
/** REGISTER TASK */
3335
await ExpoNotifications.registerTaskAsync(BACKGROUND_SYNC_TASK_NAME);
3436
logger.info('📲 Background sync task registered');
3537
}

src/core/background/executeBackgroundSync.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,11 @@ export async function executeBackgroundSync(
2121
try {
2222
logger.info('📲 Starting background sync...');
2323

24-
// Open database connection
24+
/** OPEN DATABASE */
2525
db = await createDatabase(config.databaseName, 'write');
2626
logger.info('✅ Database connection opened');
2727

28-
// Initialize sync extension
28+
/** INITIALIZE SYNC EXTENSION */
2929
await initializeSyncExtension(
3030
db,
3131
{
@@ -37,7 +37,7 @@ export async function executeBackgroundSync(
3737
logger
3838
);
3939

40-
// Set up updateHook to capture changes during sync
40+
/** REGISTER UPDATE HOOK */
4141
const callback = getBackgroundSyncCallback();
4242
if (callback) {
4343
db.updateHook(({ operation, table, rowId }) => {
@@ -50,6 +50,7 @@ export async function executeBackgroundSync(
5050
logger.info('📲 Update hook registered for change tracking');
5151
}
5252

53+
/** EXECUTE SYNC */
5354
await executeSync(db, logger, {
5455
useNativeRetry: true,
5556
maxAttempts: 3,
@@ -58,7 +59,7 @@ export async function executeBackgroundSync(
5859

5960
logger.info('✅ Background sync completed successfully');
6061

61-
// Call the callback with changes (before closing db so callback can query)
62+
/** INVOKE USER CALLBACK */
6263
if (callback && db) {
6364
logger.info(
6465
`📲 Calling background sync callback with ${changes.length} changes`
@@ -76,10 +77,9 @@ export async function executeBackgroundSync(
7677
logger.error('❌ Background sync failed:', error);
7778
throw error;
7879
} finally {
79-
// Always close database connection
80+
/** CLEANUP */
8081
if (db) {
8182
try {
82-
// Ensure hook is removed
8383
db.updateHook(null);
8484
db.close();
8585
logger.info('✅ Database connection closed');

src/core/common/logger.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,18 @@
33
* Only logs when debug mode is enabled, except for errors which always log
44
*/
55

6+
/** CONSTANTS */
67
const PREFIX = '[SQLiteSync]';
78

9+
/** HELPERS */
810
const getTimestamp = () => new Date().toISOString();
911

12+
/**
13+
* Create a logger instance with debug mode control
14+
*
15+
* @param debug - Enable debug logging (info/warn messages)
16+
* @returns Logger instance with info, warn, and error methods
17+
*/
1018
export const createLogger = (debug: boolean = false) => ({
1119
/**
1220
* Log informational messages (only in debug mode)
@@ -34,4 +42,5 @@ export const createLogger = (debug: boolean = false) => ({
3442
},
3543
});
3644

45+
/** TYPE EXPORT */
3746
export type Logger = ReturnType<typeof createLogger>;

src/core/common/optionalDependencies.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,50 +3,50 @@
33
* Loaded once at module initialization
44
*/
55

6-
// Module references
6+
/** MODULE REFERENCES */
77
export let ExpoNotifications: any = null;
88
export let ExpoTaskManager: any = null;
99
export let ExpoSecureStore: any = null;
1010
export let ExpoConstants: any = null;
11+
export let ExpoApplication: any = null;
1112

12-
// Load expo-notifications
13+
/** LOAD EXPO-NOTIFICATIONS */
1314
try {
1415
ExpoNotifications = require('expo-notifications');
1516
} catch {
1617
// Not available
1718
}
1819

19-
// Load expo-task-manager
20+
/** LOAD EXPO-TASK-MANAGER */
2021
try {
2122
ExpoTaskManager = require('expo-task-manager');
2223
} catch {
2324
// Not available
2425
}
2526

26-
// Load expo-secure-store
27+
/** LOAD EXPO-SECURE-STORE */
2728
try {
2829
ExpoSecureStore = require('expo-secure-store');
2930
} catch {
3031
// Not available
3132
}
3233

33-
// Load expo-constants
34+
/** LOAD EXPO-CONSTANTS */
3435
try {
3536
const constantsModule = require('expo-constants');
3637
ExpoConstants = constantsModule.default || constantsModule;
3738
} catch {
3839
// Not available
3940
}
4041

41-
// Load expo-application
42-
export let ExpoApplication: any = null;
42+
/** LOAD EXPO-APPLICATION */
4343
try {
4444
ExpoApplication = require('expo-application');
4545
} catch {
4646
// Not available
4747
}
4848

49-
// Compound availability check
49+
/** COMPOUND AVAILABILITY CHECK */
5050
export const isBackgroundSyncAvailable = () =>
5151
ExpoNotifications !== null &&
5252
ExpoTaskManager !== null &&

src/core/database/createDatabase.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,18 @@ export async function createDatabase(
1717
name: string,
1818
mode: 'write' | 'read'
1919
): Promise<DB> {
20+
/** OPEN DATABASE */
2021
const db = open({ name });
2122

22-
// Configure WAL mode for both connections
23+
/** CONFIGURE WAL MODE */
24+
// WAL mode enables concurrent reads and writes
2325
await db.execute('PRAGMA journal_mode = WAL');
2426

27+
/** CONFIGURE CONNECTION MODE */
2528
if (mode === 'write') {
26-
// Write connection configuration
2729
await db.execute('PRAGMA synchronous = NORMAL');
2830
await db.execute('PRAGMA locking_mode = NORMAL');
2931
} else {
30-
// Read connection configuration
3132
await db.execute('PRAGMA query_only = true');
3233
}
3334

src/core/polling/calculateAdaptiveSyncInterval.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,21 +63,21 @@ export function calculateAdaptiveSyncInterval(
6363
errorBackoffMultiplier,
6464
} = config;
6565

66-
// Priority 1: Error backoff (exponential)
66+
/** PRIORITY 1: ERROR BACKOFF */
6767
if (errors > 0) {
6868
const errorInterval =
6969
baseInterval * Math.pow(errorBackoffMultiplier, errors);
7070
return Math.min(errorInterval, maxInterval);
7171
}
7272

73-
// Priority 2: Idle backoff (exponential)
73+
/** PRIORITY 2: IDLE BACKOFF */
7474
if (emptySyncs >= emptyThreshold) {
7575
const backoffPower = emptySyncs - emptyThreshold + 1;
7676
const idleInterval =
7777
baseInterval * Math.pow(idleBackoffMultiplier, backoffPower);
7878
return Math.min(idleInterval, maxInterval);
7979
}
8080

81-
// Default: base interval
81+
/** DEFAULT: BASE INTERVAL */
8282
return baseInterval;
8383
}

src/core/polling/useAdaptivePollingSync.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -65,13 +65,12 @@ export function useAdaptivePollingSync(params: AdaptivePollingParams): void {
6565
syncMode,
6666
} = params;
6767

68-
/** REFS */
6968
const syncTimerRef = useRef<NodeJS.Timeout | null>(null);
7069
const isPollingActiveRef = useRef<boolean>(false);
7170

72-
/** ADAPTIVE SYNC POLLING - Dynamic interval with foreground/background awareness */
71+
/** ADAPTIVE SYNC POLLING EFFECT */
7372
useEffect(() => {
74-
// Only enable polling when syncMode is 'polling'
73+
/** GUARD: POLLING MODE ONLY */
7574
if (
7675
!isSyncReady ||
7776
syncMode !== 'polling' ||
@@ -81,7 +80,7 @@ export function useAdaptivePollingSync(params: AdaptivePollingParams): void {
8180
return;
8281
}
8382

84-
// Pause polling if app is in background
83+
/** GUARD: PAUSE WHEN BACKGROUNDED */
8584
if (appState !== 'active') {
8685
if (syncTimerRef.current !== null) {
8786
clearTimeout(syncTimerRef.current);
@@ -91,14 +90,14 @@ export function useAdaptivePollingSync(params: AdaptivePollingParams): void {
9190
return;
9291
}
9392

94-
// Prevent multiple polling loops from starting
93+
/** GUARD: PREVENT MULTIPLE LOOPS */
9594
if (isPollingActiveRef.current) {
9695
return;
9796
}
9897

9998
isPollingActiveRef.current = true;
10099

101-
// Schedule next sync with recursive setTimeout
100+
/** RECURSIVE POLLING LOOP */
102101
const scheduleNextSync = () => {
103102
if (syncTimerRef.current !== null) {
104103
clearTimeout(syncTimerRef.current);
@@ -123,6 +122,7 @@ export function useAdaptivePollingSync(params: AdaptivePollingParams): void {
123122

124123
scheduleNextSync();
125124

125+
/** CLEANUP */
126126
return () => {
127127
if (syncTimerRef.current !== null) {
128128
clearTimeout(syncTimerRef.current);

src/core/pushNotifications/isSqliteCloudNotification.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/** SQLITE CLOUD ARTIFACT URI */
12
const ARTIFACT_URI = 'https://sqlite.ai';
23

34
/**
@@ -22,12 +23,12 @@ export const isForegroundSqliteCloudNotification = (
2223
export const isSqliteCloudNotification = (notification: any): boolean => {
2324
const body = notification?.data?.body;
2425

25-
// iOS background
26+
/** CHECK IOS BACKGROUND FORMAT */
2627
if (body && typeof body === 'object' && body.artifactURI === ARTIFACT_URI) {
2728
return true;
2829
}
2930

30-
// Android background
31+
/** CHECK ANDROID BACKGROUND FORMAT */
3132
const bodyString =
3233
typeof body === 'string' ? body : notification?.data?.dataString;
3334
if (typeof bodyString === 'string') {
@@ -41,6 +42,6 @@ export const isSqliteCloudNotification = (notification: any): boolean => {
4142
}
4243
}
4344

44-
// Foreground notification structure (fallback)
45+
/** CHECK FOREGROUND FORMAT */
4546
return isForegroundSqliteCloudNotification(notification);
4647
};

0 commit comments

Comments
 (0)