refactor: improve build configuration and code organization

- Add build scripts for Android and iOS platforms
- Remove duplicate web implementation (src/web.ts)
- Add proper TypeScript configuration
- Add module documentation to index.ts
- Clean up package.json scripts

This commit improves the project structure and build process by:
1. Adding dedicated build scripts for native platforms
2. Removing redundant web implementation
3. Adding proper TypeScript configuration with strict mode
4. Improving code documentation
5. Organizing package.json scripts

The changes maintain backward compatibility while improving
the development experience and code quality.
This commit is contained in:
Matthew Raymer
2025-03-25 13:13:55 +00:00
parent e946767cba
commit 71e0f297ff
92 changed files with 11523 additions and 69 deletions

510
README.md Normal file
View File

@@ -0,0 +1,510 @@
# Daily Notification Plugin for Capacitor
A powerful Capacitor plugin for scheduling and managing daily notifications with advanced features like timezone support, offline capabilities, and retry logic.
## Features
- Schedule daily notifications at specific times
- Support for multiple notification schedules
- Timezone-aware scheduling
- Offline support with content caching
- Retry logic with exponential backoff
- Custom notification content handlers
- Event-based notification handling
- Comprehensive settings management
- TypeScript support with full type definitions
## Installation
```bash
npm install @timesafari/daily-notification-plugin
```
## Usage
### Basic Usage
```typescript
import { DailyNotification } from '@timesafari/daily-notification-plugin';
const plugin = new DailyNotification();
// Schedule a daily notification
await plugin.scheduleDailyNotification({
url: 'https://api.example.com/updates',
time: '09:00',
title: 'Daily Update',
body: 'Your daily content is ready!',
sound: true,
priority: 'high'
});
// Get notification status
const status = await plugin.getNotificationStatus();
console.log('Next notification:', status.nextNotificationTime);
// Handle notification events
plugin.on('notification', (event) => {
console.log('Notification received:', event.detail);
});
```
### Advanced Usage
```typescript
// Multiple schedules with different timezones
const schedules = [
{
url: 'https://api.example.com/morning',
time: '09:00',
timezone: 'America/New_York',
title: 'Morning Update'
},
{
url: 'https://api.example.com/evening',
time: '18:00',
timezone: 'Europe/London',
title: 'Evening Update'
}
];
for (const schedule of schedules) {
await plugin.scheduleDailyNotification(schedule);
}
// Offline support with caching
await plugin.scheduleDailyNotification({
url: 'https://api.example.com/updates',
time: '10:00',
offlineFallback: true,
cacheDuration: 3600, // 1 hour
contentHandler: async (response) => {
const data = await response.json();
return {
title: data.title,
body: data.content,
data: data.metadata
};
}
});
// Update settings
await plugin.updateSettings({
time: '11:00',
sound: true,
priority: 'high',
timezone: 'America/Chicago'
});
```
## API Reference
### Methods
#### `scheduleDailyNotification(options: NotificationOptions): Promise<void>`
Schedules a daily notification with the specified options.
```typescript
interface NotificationOptions {
url: string;
time: string; // "HH:mm" format
title?: string;
body?: string;
sound?: boolean;
vibrate?: boolean;
priority?: 'low' | 'normal' | 'high';
retryCount?: number;
retryInterval?: number;
cacheDuration?: number;
headers?: Record<string, string>;
offlineFallback?: boolean;
timezone?: string;
contentHandler?: (response: Response) => Promise<{
title: string;
body: string;
data?: any;
}>;
}
```
#### `getLastNotification(): Promise<NotificationResponse | null>`
Retrieves the last notification that was delivered.
#### `cancelAllNotifications(): Promise<void>`
Cancels all scheduled notifications.
#### `getNotificationStatus(): Promise<NotificationStatus>`
Gets the current status of notifications.
#### `updateSettings(settings: NotificationSettings): Promise<void>`
Updates notification settings.
```typescript
interface NotificationSettings {
time?: string;
sound?: boolean;
vibrate?: boolean;
priority?: 'low' | 'normal' | 'high';
timezone?: string;
}
```
### Events
The plugin emits the following events:
- `notification`: Fired when a notification is received or interacted with
```typescript
interface NotificationEvent extends Event {
detail: {
id: string;
action: string;
data?: any;
};
}
```
## Testing
The plugin includes comprehensive tests covering:
- Basic functionality
- Multiple schedules
- Timezone handling
- Offline support
- Retry logic
- Event handling
- Settings management
Run tests with:
```bash
npm test
```
## Security Considerations
- All network requests use HTTPS
- Content is validated before display
- Sensitive data is not stored in logs
- Permissions are properly managed
- Input validation is performed on all methods
## Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Author
Matthew Raymer
## Platform-Specific Implementation
### Android Implementation
- Uses `WorkManager` for periodic data fetching
- Implements `AlarmManager` for precise notification scheduling
- Stores data in `SharedPreferences`
- Handles Doze mode and battery optimizations
### iOS
- Utilizes `BGTaskScheduler` for background fetches
- Implements `UNUserNotificationCenter` for notifications
- Stores data in `UserDefaults`
- Respects system background execution limits
## Permissions
### Android Permissions
Required permissions in `AndroidManifest.xml`:
```xml
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
```
### iOS Implementation
- Notification permissions (requested at runtime)
- Background App Refresh capability (enabled in Xcode)
## Error Handling
The plugin implements comprehensive error handling:
- Network failure retry logic with exponential backoff
- Fallback to cached content when fetching fails
- Detailed error logging and reporting
- Graceful degradation when permissions are denied
## Best Practices
### Content Management
- Keep notification content concise and actionable
- Use clear, engaging titles under 50 characters
- Limit notification body to 2-3 lines
- Include a clear call-to-action when appropriate
### Network Optimization
- Implement proper caching headers on your API
- Use compression for network responses
- Keep payload size under 4KB for optimal performance
- Implement rate limiting on your API endpoints
### Battery Considerations
- Schedule notifications during active hours
- Avoid excessive background fetches
- Use appropriate fetch intervals (minimum 15 minutes)
- Implement smart retry strategies
### User Experience
- Request notification permissions at an appropriate time
- Provide clear value proposition for notifications
- Allow users to customize notification timing
- Implement proper error messaging for users
### Security
- Always use HTTPS for API endpoints
- Implement proper API authentication
- Sanitize notification content
- Follow platform-specific security guidelines
### Testing
- Test notifications in various app states
- Verify behavior with different network conditions
- Test on multiple device types and OS versions
- Implement proper error logging for debugging
## Development Setup
### Prerequisites
1. Node.js 14 or higher
2. Java 11 or higher
3. Android Studio and Android SDK
4. Xcode (for iOS development, macOS only)
5. CocoaPods (for iOS development)
### Environment Setup
1. Clone the repository:
```bash
git clone https://github.com/yourusername/capacitor-daily-notification.git
cd capacitor-daily-notification
```
2. Install dependencies:
```bash
npm install
```
This will:
- Install Node.js dependencies
- Check your development environment
- Set up native build environments
- Install platform-specific dependencies
### Building the Plugin
#### TypeScript Build
```bash
# Build TypeScript code
npm run build
# Watch mode for development
npm run watch
```
#### Android Build
```bash
# Build Android library
npm run build:android
# Run Android tests
npm run test:android
```
The Android build will:
1. Compile the TypeScript code
2. Build the Android library
3. Generate an AAR file in `android/build/outputs/aar/`
#### iOS Build
```bash
# Build iOS library
npm run build:ios
# Run iOS tests
npm run test:ios
```
The iOS build will:
1. Compile the TypeScript code
2. Install CocoaPods dependencies
3. Build the iOS framework
### Using in a Capacitor App
1. Install the plugin in your Capacitor app:
```bash
npm install capacitor-daily-notification
```
2. Add to your Android app's `android/app/build.gradle`:
```gradle
dependencies {
implementation project(':daily-notification')
}
```
3. Add to your iOS app's `ios/App/Podfile`:
```ruby
pod 'CapacitorDailyNotification', :path => '../node_modules/capacitor-daily-notification'
```
4. Sync native projects:
```bash
npx cap sync
```
### Troubleshooting
#### Android Issues
1. Gradle Sync Failed
```bash
cd android
./gradlew clean
./gradlew --refresh-dependencies
```
2. Missing Android SDK
- Set ANDROID_HOME environment variable
- Install required SDK components via Android Studio
3. Build Errors
- Check Android Studio for detailed error messages
- Ensure all required SDK components are installed
- Verify Gradle version compatibility
#### iOS Issues
1. Pod Install Failed
```bash
cd ios
pod deintegrate
pod cache clean --all
pod install
```
2. Xcode Build Errors
- Open Xcode project in Xcode
- Check build settings
- Verify deployment target matches requirements
3. Missing Dependencies
- Ensure CocoaPods is installed
- Run `pod setup` to update CocoaPods repos
### Development Workflow
1. Make changes to TypeScript code
2. Run `npm run build` to compile
3. Run `npm run build:native` to build native code
4. Test changes:
- Android: `npm run test:android`
- iOS: `npm run test:ios`
5. Run full validation:
- Android: `npm run validate`
- iOS: `npm run validate:ios`
### Continuous Integration
The plugin includes pre-commit hooks and CI configurations:
1. Pre-commit checks:
- TypeScript compilation
- Linting
- Native build verification
2. CI pipeline:
- Environment validation
- TypeScript build
- Native builds
- Unit tests
- Integration tests
## Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Author
Matthew Raymer
## Plugin Security
This plugin follows security best practices:
- Secure storage of sensitive data
- HTTPS-only network requests
- Permission-based access control
- Regular security audits
- No sensitive data in logs
## Support
For support, please open an issue in the GitHub repository or contact the maintainers.
## Changelog
See [CHANGELOG.md](CHANGELOG.md) for a list of changes and version history.