Compare commits
66 Commits
gifting-pe
...
sql-absurd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
981920dd7a | ||
|
|
d189c39062 | ||
|
|
8edddb1a57 | ||
|
|
9eb07b3258 | ||
|
|
e5dffc30ff | ||
|
|
0b4e885edd | ||
|
|
b6d9b29720 | ||
|
|
b5348e42a7 | ||
|
|
a4fb3eea2d | ||
|
|
5d12c76693 | ||
|
|
d426f9c4ac | ||
| 340a574325 | |||
|
|
98b3a35e3c | ||
|
|
409de21fc4 | ||
|
|
17c9d32f49 | ||
|
|
25e4db395a | ||
|
|
b6ee30892f | ||
|
|
b01a450733 | ||
|
|
596f3355bf | ||
|
|
e1f9a6fa08 | ||
|
|
340e718199 | ||
|
|
5d97c98ae8 | ||
|
|
ec74fff892 | ||
|
|
1e88c0e26f | ||
|
|
3ec2364394 | ||
|
|
8b215c909d | ||
|
|
91a1c05473 | ||
|
|
66929d9b14 | ||
|
|
1e63ddcb6e | ||
|
|
51f5755f5c | ||
|
|
e5a3d622b6 | ||
|
|
a6edcd6269 | ||
|
|
b7b6be5831 | ||
|
|
cbaca0304d | ||
| 59d711bd90 | |||
|
|
c355de6e33 | ||
|
|
28c114a2c7 | ||
| dabfe33fbe | |||
| d8f2587d1c | |||
|
|
3946a8a27a | ||
| 4c40b80718 | |||
| 74989c2b64 | |||
| 7e17b41444 | |||
| 83acb028c7 | |||
|
|
786f07e067 | ||
|
|
710cc1683c | ||
|
|
ebef5d6c8d | ||
|
|
43ea7ee610 | ||
|
|
57191df416 | ||
| 644593a5f4 | |||
|
|
900c2521c7 | ||
|
|
182cff2b16 | ||
|
|
3b4ef908f3 | ||
|
|
a5a9e15ece | ||
|
|
a6d8f0eb8a | ||
|
|
3997a88b44 | ||
| 5eeeae32c6 | |||
|
|
d9895086e6 | ||
|
|
fb8d1cb8b2 | ||
|
|
70c0edbed0 | ||
|
|
55cc08d675 | ||
|
|
688a5be76e | ||
|
|
014341f320 | ||
|
|
1d5e062c76 | ||
|
|
2c5c15108a | ||
|
|
26df0fb671 |
@@ -2,7 +2,7 @@
|
||||
|
||||
# iOS doesn't like spaces in the app title.
|
||||
TIME_SAFARI_APP_TITLE="TimeSafari_Dev"
|
||||
VITE_APP_SERVER=http://localhost:8080
|
||||
VITE_APP_SERVER=http://localhost:3000
|
||||
# This is the claim ID for actions in the BVC project, with the JWT ID on this environment (not production).
|
||||
VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F
|
||||
VITE_DEFAULT_ENDORSER_API_SERVER=http://localhost:3000
|
||||
|
||||
6
.gitignore
vendored
@@ -51,8 +51,6 @@ vendor/
|
||||
# Build logs
|
||||
build_logs/
|
||||
|
||||
# PWA icon files generated by capacitor-assets
|
||||
icons
|
||||
android/app/src/main/assets/public
|
||||
android/app/src/main/res
|
||||
|
||||
|
||||
android/app/src/main/res/
|
||||
100
BUILDING.md
@@ -9,6 +9,19 @@ For a quick dev environment setup, use [pkgx](https://pkgx.dev).
|
||||
- Node.js (LTS version recommended)
|
||||
- npm (comes with Node.js)
|
||||
- Git
|
||||
- For Android builds: Android Studio with SDK installed
|
||||
- For iOS builds: macOS with Xcode and ruby gems & bundle
|
||||
- `pkgx +rubygems.org sh`
|
||||
|
||||
- ... and you may have to fix these, especially with pkgx
|
||||
|
||||
```bash
|
||||
gem_path=$(which gem)
|
||||
shortened_path="${gem_path:h:h}"
|
||||
export GEM_HOME=$shortened_path
|
||||
export GEM_PATH=$shortened_path
|
||||
```
|
||||
|
||||
- For desktop builds: Additional build tools based on your OS
|
||||
|
||||
## Forks
|
||||
@@ -41,7 +54,6 @@ Install dependencies:
|
||||
1. Run the production build:
|
||||
|
||||
```bash
|
||||
rm -rf dist
|
||||
npm run build:web
|
||||
```
|
||||
|
||||
@@ -63,18 +75,16 @@ Install dependencies:
|
||||
|
||||
* Update the ClickUp tasks & CHANGELOG.md & the version in package.json, run `npm install`.
|
||||
|
||||
* Run a build to make sure package-lock version is updated, linting works, etc: `npm install && npm run build`
|
||||
|
||||
* Commit everything (since the commit hash is used the app).
|
||||
|
||||
* Put the commit hash in the changelog (which will help you remember to bump the version in the step later).
|
||||
* Put the commit hash in the changelog (which will help you remember to bump the version later).
|
||||
|
||||
* Tag with the new version, [online](https://gitea.anomalistdesign.com/trent_larson/crowd-funder-for-time-pwa/releases) or `git tag 1.0.2 && git push origin 1.0.2`.
|
||||
* Tag with the new version, [online](https://gitea.anomalistdesign.com/trent_larson/crowd-funder-for-time-pwa/releases) or `git tag 0.3.55 && git push origin 0.3.55`.
|
||||
|
||||
* For test, build the app (because test server is not yet set up to build):
|
||||
|
||||
```bash
|
||||
TIME_SAFARI_APP_TITLE="TimeSafari_Test" VITE_APP_SERVER=https://test.timesafari.app VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app VITE_DEFAULT_PARTNER_API_SERVER=https://test-partner-api.endorser.ch VITE_DEFAULT_PUSH_SERVER=https://test.timesafari.app VITE_PASSKEYS_ENABLED=true npm run build:web
|
||||
TIME_SAFARI_APP_TITLE="TimeSafari_Test" VITE_APP_SERVER=https://test.timesafari.app VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZYYPS272F VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app VITE_DEFAULT_PARTNER_API_SERVER=https://test-partner-api.endorser.ch VITE_DEFAULT_PUSH_SERVER=https://test.timesafari.app VITE_PASSKEYS_ENABLED=true npm run build
|
||||
```
|
||||
|
||||
... and transfer to the test server:
|
||||
@@ -93,13 +103,13 @@ TIME_SAFARI_APP_TITLE="TimeSafari_Test" VITE_APP_SERVER=https://test.timesafari.
|
||||
|
||||
* `pkgx +npm sh`
|
||||
|
||||
* `cd crowd-funder-for-time-pwa && git checkout master && git pull && git checkout 1.0.2 && npm install && npm run build:web && cd -`
|
||||
* `cd crowd-funder-for-time-pwa && git checkout master && git pull && git checkout 0.3.55 && npm install && npm run build && cd -`
|
||||
|
||||
(The plain `npm run build:web` uses the .env.production file.)
|
||||
(The plain `npm run build` uses the .env.production file.)
|
||||
|
||||
* Back up the time-safari/dist folder & deploy: `mv time-safari/dist time-safari-dist-prev-2 && mv crowd-funder-for-time-pwa/dist time-safari/`
|
||||
* Back up the time-safari/dist folder & deploy: `mv time-safari/dist time-safari-dist-prev.0 && mv crowd-funder-for-time-pwa/dist time-safari/`
|
||||
|
||||
* Record the new hash in the changelog. Edit package.json to increment version & add "-beta", `npm install`, commit, and push. Also record what version is on production.
|
||||
* Record the new hash in the changelog. Edit package.json to increment version & add "-beta", `npm install`, and commit. Also record what version is on production.
|
||||
|
||||
## Docker Deployment
|
||||
|
||||
@@ -316,33 +326,17 @@ npm run build:electron-prod && npm run electron:start
|
||||
|
||||
Prerequisites: macOS with Xcode installed
|
||||
|
||||
#### First-time iOS Configuration
|
||||
|
||||
- Generate certificates inside XCode.
|
||||
|
||||
- Right-click on App and under Signing & Capabilities set the Team.
|
||||
|
||||
#### Each Release
|
||||
|
||||
0. First time (or if dependencies change):
|
||||
|
||||
- `pkgx +rubygems.org sh`
|
||||
|
||||
- ... and you may have to fix these, especially with pkgx:
|
||||
|
||||
```bash
|
||||
gem_path=$(which gem)
|
||||
shortened_path="${gem_path:h:h}"
|
||||
export GEM_HOME=$shortened_path
|
||||
export GEM_PATH=$shortened_path
|
||||
```
|
||||
|
||||
1. Build the web assets & update ios:
|
||||
1. Build the web assets:
|
||||
|
||||
```bash
|
||||
rm -rf dist
|
||||
npm run build:web
|
||||
npm run build:capacitor
|
||||
```
|
||||
|
||||
2. Update iOS project with latest build:
|
||||
|
||||
```bash
|
||||
npx cap sync ios
|
||||
```
|
||||
|
||||
@@ -351,20 +345,20 @@ Prerequisites: macOS with Xcode installed
|
||||
3. Copy the assets:
|
||||
|
||||
```bash
|
||||
# It makes no sense why capacitor-assets will not run without these but it actually changes the contents.
|
||||
mkdir -p ios/App/App/Assets.xcassets/AppIcon.appiconset
|
||||
echo '{"images":[]}' > ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json
|
||||
mkdir -p ios/App/App/Assets.xcassets/Splash.imageset
|
||||
echo '{"images":[]}' > ios/App/App/Assets.xcassets/Splash.imageset/Contents.json
|
||||
npx capacitor-assets generate --ios
|
||||
```
|
||||
|
||||
4. Bump the version to match Android & package.json:
|
||||
4. Bump the version to match Android:
|
||||
|
||||
```
|
||||
cd ios/App && xcrun agvtool new-version 35 && perl -p -i -e "s/MARKETING_VERSION = .*;/MARKETING_VERSION = 1.0.2;/g" App.xcodeproj/project.pbxproj && cd -
|
||||
cd ios/App
|
||||
xcrun agvtool new-version 15
|
||||
# Unfortunately this edits Info.plist directly.
|
||||
#xcrun agvtool new-marketing-version 0.4.5
|
||||
cat App.xcodeproj/project.pbxproj | sed "s/MARKETING_VERSION = .*;/MARKETING_VERSION = 0.4.5;/g" > temp
|
||||
mv temp App.xcodeproj/project.pbxproj
|
||||
cd -
|
||||
```
|
||||
|
||||
5. Open the project in Xcode:
|
||||
@@ -375,25 +369,28 @@ Prerequisites: macOS with Xcode installed
|
||||
|
||||
6. Use Xcode to build and run on simulator or device.
|
||||
|
||||
* Select Product -> Destination with some Simulator version. Then click the run arrow.
|
||||
|
||||
7. Release
|
||||
|
||||
* Someday: Under "General" we want to rename a bunch of things to "Time Safari"
|
||||
* Choose Product -> Destination -> Any iOS Device
|
||||
* Under "General" renamed a bunch of things to "Time Safari"
|
||||
* Choose Product -> Destination -> Build Any iOS
|
||||
* Choose Product -> Archive
|
||||
* This will trigger a build and take time, needing user's "login" keychain password (user's login password), repeatedly.
|
||||
* This will trigger a build and take time, needing user's "login" keychain password which is just their login password, repeatedly.
|
||||
* If it fails with `building for 'iOS', but linking in dylib (.../.pkgx/zlib.net/v1.3.0/lib/libz.1.3.dylib) built for 'macOS'` then run XCode outside that terminal (ie. not with `npx cap open ios`).
|
||||
* Click Distribute -> App Store Connect
|
||||
* In AppStoreConnect, add the build to the distribution: remove the current build with the "-" when you hover over it, then "Add Build" with the new build.
|
||||
* May have to go to App Review, click Submission, then hover over the build and click "-".
|
||||
* It can take 15 minutes for the build to show up in the list of builds.
|
||||
* You'll probably have to "Manage" something about encryption, disallowed in France.
|
||||
* Then "Save" and "Add to Review" and "Resubmit to App Review".
|
||||
|
||||
#### First-time iOS Configuration
|
||||
|
||||
- Generate certificates inside XCode.
|
||||
|
||||
- Right-click on App and under Signing & Capabilities set the Team.
|
||||
|
||||
### Android Build
|
||||
|
||||
Prerequisites: Android Studio with Java SDK installed
|
||||
Prerequisites: Android Studio with SDK installed
|
||||
|
||||
1. Build the web assets:
|
||||
|
||||
@@ -415,7 +412,7 @@ Prerequisites: Android Studio with Java SDK installed
|
||||
npx capacitor-assets generate --android
|
||||
```
|
||||
|
||||
4. Bump version to match iOS & package.json: android/app/build.gradle
|
||||
4. Bump version to match iOS: android/app/build.gradle
|
||||
|
||||
5. Open the project in Android Studio:
|
||||
|
||||
@@ -432,6 +429,7 @@ Prerequisites: Android Studio with Java SDK installed
|
||||
./gradlew clean
|
||||
./gradlew build -Dlint.baselines.continue=true
|
||||
cd -
|
||||
npx cap run android
|
||||
```
|
||||
|
||||
... or, to create the `aab` file, `bundle` instead of `build`:
|
||||
@@ -447,9 +445,7 @@ Prerequisites: Android Studio with Java SDK installed
|
||||
* Then `bundleRelease`:
|
||||
|
||||
```bash
|
||||
cd android
|
||||
./gradlew bundleRelease -Dlint.baselines.continue=true
|
||||
cd -
|
||||
```
|
||||
|
||||
... and find your `aab` file at app/build/outputs/bundle/release
|
||||
@@ -462,10 +458,8 @@ At play.google.com/console:
|
||||
- Hit "Next".
|
||||
- Save, go to "Publishing Overview" as prompted, and click "Send changes for review".
|
||||
|
||||
- Note that if you add testers, you have to go to "Publishing Overview" and send those changes or your (closed) testers won't see it.
|
||||
|
||||
|
||||
## Android Configuration for deep links
|
||||
## First-time Android Configuration for deep links
|
||||
|
||||
You must add the following intent filter to the `android/app/src/main/AndroidManifest.xml` file:
|
||||
|
||||
@@ -476,6 +470,4 @@ You must add the following intent filter to the `android/app/src/main/AndroidMan
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="timesafari" />
|
||||
</intent-filter>
|
||||
```
|
||||
|
||||
... though when we tried that most recently it failed to 'build' the APK with: http(s) scheme and host attribute are missing, but are required for Android App Links [AppLinkUrlError]
|
||||
```
|
||||
29
CHANGELOG.md
@@ -6,35 +6,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
|
||||
## [1.0.2] - 2025.06.20 - 276e0a741bc327de3380c4e508cccb7fee58c06d
|
||||
### Added
|
||||
- Version on feed title
|
||||
|
||||
|
||||
## [1.0.1] - 2025.06.20
|
||||
### Added
|
||||
- Allow a user to block someone else's content from view
|
||||
|
||||
|
||||
## [1.0.0] - 2025.06.20 - 5aa693de6337e5dbb278bfddc6bd39094bc14f73
|
||||
### Added
|
||||
- Web-oriented migration from IndexedDB to SQLite
|
||||
|
||||
|
||||
## [0.5.8]
|
||||
### Added
|
||||
- /deep-link/ path for URLs that are shared with people
|
||||
### Changed
|
||||
- External links now go to /deep-link/...
|
||||
- Feed visuals now have arrow imagery from giver to receiver
|
||||
|
||||
|
||||
## [0.4.7]
|
||||
### Fixed
|
||||
- Cameras everywhere
|
||||
### Changed
|
||||
- IndexedDB -> SQLite
|
||||
|
||||
|
||||
## [0.4.5] - 2025.02.23
|
||||
### Added
|
||||
|
||||
47
README.md
@@ -3,32 +3,6 @@
|
||||
[Time Safari](https://timesafari.org/) allows people to ease into collaboration: start with expressions of gratitude
|
||||
and expand to crowd-fund with time & money, then record and see the impact of contributions.
|
||||
|
||||
## Database Migration Status
|
||||
|
||||
**Current Status**: The application is undergoing a migration from Dexie (IndexedDB) to SQLite using absurd-sql. This migration is in **Phase 2** with a well-defined migration fence in place.
|
||||
|
||||
### Migration Progress
|
||||
- ✅ **SQLite Database Service**: Fully implemented with absurd-sql
|
||||
- ✅ **Platform Service Layer**: Unified database interface across platforms
|
||||
- ✅ **Settings Migration**: Core user settings transferred
|
||||
- ✅ **Account Migration**: Identity and key management
|
||||
- 🔄 **Contact Migration**: User contact data (via import interface)
|
||||
- 📋 **Code Cleanup**: Remove unused Dexie imports
|
||||
|
||||
### Migration Fence
|
||||
The migration is controlled by a **migration fence** that separates legacy Dexie code from the new SQLite implementation. See [Migration Fence Definition](doc/migration-fence-definition.md) for complete details.
|
||||
|
||||
**Key Points**:
|
||||
- Legacy Dexie database is disabled by default (`USE_DEXIE_DB = false`)
|
||||
- All database operations go through `PlatformService`
|
||||
- Migration tools provide controlled access to both databases
|
||||
- Clear separation between legacy and new code
|
||||
|
||||
### Migration Documentation
|
||||
- [Migration Guide](doc/migration-to-wa-sqlite.md) - Complete migration process
|
||||
- [Migration Fence Definition](doc/migration-fence-definition.md) - Fence boundaries and rules
|
||||
- [Database Migration Guide](doc/database-migration-guide.md) - User-facing migration tools
|
||||
|
||||
## Roadmap
|
||||
|
||||
See [project.task.yaml](project.task.yaml) for current priorities.
|
||||
@@ -47,10 +21,16 @@ npm run dev
|
||||
|
||||
See [BUILDING.md](BUILDING.md) for more details.
|
||||
|
||||
|
||||
|
||||
|
||||
## Tests
|
||||
|
||||
See [TESTING.md](test-playwright/TESTING.md) for detailed test instructions.
|
||||
|
||||
|
||||
|
||||
|
||||
## Icons
|
||||
|
||||
Application icons are in the `assets` directory, processed by the `capacitor-assets` command.
|
||||
@@ -86,21 +66,6 @@ Key principles:
|
||||
- Common interfaces are shared through `common.ts`
|
||||
- Type definitions are generated from Zod schemas where possible
|
||||
|
||||
### Database Architecture
|
||||
|
||||
The application uses a platform-agnostic database layer:
|
||||
|
||||
* `src/services/PlatformService.ts` - Database interface definition
|
||||
* `src/services/PlatformServiceFactory.ts` - Platform-specific service factory
|
||||
* `src/services/AbsurdSqlDatabaseService.ts` - SQLite implementation
|
||||
* `src/db/` - Legacy Dexie database (migration in progress)
|
||||
|
||||
**Development Guidelines**:
|
||||
- Always use `PlatformService` for database operations
|
||||
- Never import Dexie directly in application code
|
||||
- Test with `USE_DEXIE_DB = false` for new features
|
||||
- Use migration tools for data transfer between systems
|
||||
|
||||
### Kudos
|
||||
|
||||
Gifts make the world go 'round!
|
||||
|
||||
@@ -31,8 +31,8 @@ android {
|
||||
applicationId "app.timesafari.app"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 35
|
||||
versionName "1.0.2"
|
||||
versionCode 18
|
||||
versionName "0.4.7"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
}
|
||||
},
|
||||
"ios": {
|
||||
"contentInset": "never",
|
||||
"contentInset": "always",
|
||||
"allowsLinkPreview": true,
|
||||
"scrollEnabled": true,
|
||||
"limitsNavigationsToAppBoundDomains": true,
|
||||
|
||||
@@ -2,7 +2,7 @@ package app.timesafari;
|
||||
|
||||
import android.os.Bundle;
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
//import com.getcapacitor.community.sqlite.SQLite;
|
||||
import com.getcapacitor.community.sqlite.SQLite;
|
||||
|
||||
public class MainActivity extends BridgeActivity {
|
||||
@Override
|
||||
@@ -10,6 +10,6 @@ public class MainActivity extends BridgeActivity {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
// Initialize SQLite
|
||||
//registerPlugin(SQLite.class);
|
||||
registerPlugin(SQLite.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package timesafari.app;
|
||||
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
|
||||
public class MainActivity extends BridgeActivity {}
|
||||
BIN
android/app/src/main/res/drawable-land-hdpi/splash.png
Normal file
|
After Width: | Height: | Size: 7.5 KiB |
BIN
android/app/src/main/res/drawable-land-mdpi/splash.png
Normal file
|
After Width: | Height: | Size: 3.9 KiB |
BIN
android/app/src/main/res/drawable-land-xhdpi/splash.png
Normal file
|
After Width: | Height: | Size: 9.0 KiB |
BIN
android/app/src/main/res/drawable-land-xxhdpi/splash.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
android/app/src/main/res/drawable-land-xxxhdpi/splash.png
Normal file
|
After Width: | Height: | Size: 17 KiB |
BIN
android/app/src/main/res/drawable-port-hdpi/splash.png
Normal file
|
After Width: | Height: | Size: 7.7 KiB |
BIN
android/app/src/main/res/drawable-port-mdpi/splash.png
Normal file
|
After Width: | Height: | Size: 4.0 KiB |
BIN
android/app/src/main/res/drawable-port-xhdpi/splash.png
Normal file
|
After Width: | Height: | Size: 9.6 KiB |
BIN
android/app/src/main/res/drawable-port-xxhdpi/splash.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
android/app/src/main/res/drawable-port-xxxhdpi/splash.png
Normal file
|
After Width: | Height: | Size: 17 KiB |
BIN
android/app/src/main/res/drawable/splash.png
Normal file
|
After Width: | Height: | Size: 3.9 KiB |
@@ -1,9 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background>
|
||||
<inset android:drawable="@mipmap/ic_launcher_background" android:inset="16.7%" />
|
||||
</background>
|
||||
<foreground>
|
||||
<inset android:drawable="@mipmap/ic_launcher_foreground" android:inset="16.7%" />
|
||||
</foreground>
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
@@ -1,9 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background>
|
||||
<inset android:drawable="@mipmap/ic_launcher_background" android:inset="16.7%" />
|
||||
</background>
|
||||
<foreground>
|
||||
<inset android:drawable="@mipmap/ic_launcher_foreground" android:inset="16.7%" />
|
||||
</foreground>
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
BIN
android/app/src/main/res/mipmap-hdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 4.6 KiB |
BIN
android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 3.4 KiB |
BIN
android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
Normal file
|
After Width: | Height: | Size: 7.3 KiB |
BIN
android/app/src/main/res/mipmap-mdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 2.1 KiB |
BIN
android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 2.1 KiB |
BIN
android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
Normal file
|
After Width: | Height: | Size: 4.3 KiB |
BIN
android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 6.9 KiB |
BIN
android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 4.9 KiB |
BIN
android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
BIN
android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
Normal file
|
After Width: | Height: | Size: 17 KiB |
BIN
android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 15 KiB |
BIN
android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
assets/icon-only.jpg
Normal file
|
After Width: | Height: | Size: 60 KiB |
BIN
assets/icon.png
|
Before Width: | Height: | Size: 279 KiB |
|
Before Width: | Height: | Size: 1.9 MiB |
|
Before Width: | Height: | Size: 1.9 MiB |
@@ -1,10 +1,11 @@
|
||||
{
|
||||
"appId": "app.timesafari",
|
||||
"appId": "com.timesafari.app",
|
||||
"appName": "TimeSafari",
|
||||
"webDir": "dist",
|
||||
"bundledWebRuntime": false,
|
||||
"server": {
|
||||
"cleartext": true
|
||||
"cleartext": true,
|
||||
"androidScheme": "https"
|
||||
},
|
||||
"plugins": {
|
||||
"App": {
|
||||
@@ -29,10 +30,16 @@
|
||||
"biometricAuth": true,
|
||||
"biometricTitle": "Biometric login for TimeSafari"
|
||||
}
|
||||
},
|
||||
"CapacitorSQLite": {
|
||||
"electronIsEncryption": false,
|
||||
"electronMacLocation": "~/Library/Application Support/TimeSafari",
|
||||
"electronWindowsLocation": "C:\\ProgramData\\TimeSafari",
|
||||
"electronLinuxLocation": "~/.local/share/TimeSafari"
|
||||
}
|
||||
},
|
||||
"ios": {
|
||||
"contentInset": "never",
|
||||
"contentInset": "always",
|
||||
"allowsLinkPreview": true,
|
||||
"scrollEnabled": true,
|
||||
"limitsNavigationsToAppBoundDomains": true,
|
||||
|
||||
@@ -100,7 +100,6 @@ try {
|
||||
- `src/interfaces/deepLinks.ts`: Type definitions and validation schemas
|
||||
- `src/services/deepLinks.ts`: Deep link processing service
|
||||
- `src/main.capacitor.ts`: Capacitor integration
|
||||
- `src/views/DeepLinkRedirectView.vue`: Page to handle links to both mobile and web
|
||||
|
||||
## Type Safety Examples
|
||||
|
||||
|
||||
@@ -1,295 +0,0 @@
|
||||
# Database Migration Guide
|
||||
|
||||
## Overview
|
||||
|
||||
The Database Migration feature allows you to compare and migrate data between Dexie (IndexedDB) and SQLite databases in the TimeSafari application. This is particularly useful during the transition from the old Dexie-based storage system to the new SQLite-based system.
|
||||
|
||||
## Features
|
||||
|
||||
### 1. Database Comparison
|
||||
|
||||
- Compare data between Dexie and SQLite databases
|
||||
- View detailed differences in contacts and settings
|
||||
- Identify added, modified, and missing records
|
||||
- Export comparison results for analysis
|
||||
|
||||
### 2. Data Migration
|
||||
|
||||
- Migrate contacts from Dexie to SQLite
|
||||
- Migrate settings from Dexie to SQLite
|
||||
- Option to overwrite existing records or skip them
|
||||
- Comprehensive error handling and reporting
|
||||
|
||||
### 3. User Interface
|
||||
|
||||
- Modern, responsive UI built with Tailwind CSS
|
||||
- Real-time loading states and progress indicators
|
||||
- Clear success and error messaging
|
||||
- Export functionality for comparison data
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### Enable Dexie Database
|
||||
|
||||
Before using the migration features, you must enable the Dexie database by setting:
|
||||
|
||||
```typescript
|
||||
// In constants/app.ts
|
||||
export const USE_DEXIE_DB = true;
|
||||
```
|
||||
|
||||
**Note**: This should only be enabled temporarily during migration. Remember to set it back to `false` after migration is complete.
|
||||
|
||||
## Accessing the Migration Interface
|
||||
|
||||
1. Navigate to the **Account** page in the TimeSafari app
|
||||
2. Scroll down to find the **Database Migration** link
|
||||
3. Click the link to open the migration interface
|
||||
|
||||
## Using the Migration Interface
|
||||
|
||||
### Step 1: Compare Databases
|
||||
|
||||
1. Click the **"Compare Databases"** button
|
||||
2. The system will retrieve data from both Dexie and SQLite databases
|
||||
3. Review the comparison results showing:
|
||||
- Summary counts for each database
|
||||
- Detailed differences (added, modified, missing records)
|
||||
- Specific records that need attention
|
||||
|
||||
### Step 2: Review Differences
|
||||
|
||||
The comparison results are displayed in several sections:
|
||||
|
||||
#### Summary Cards
|
||||
|
||||
- **Dexie Contacts**: Number of contacts in Dexie database
|
||||
- **SQLite Contacts**: Number of contacts in SQLite database
|
||||
- **Dexie Settings**: Number of settings in Dexie database
|
||||
- **SQLite Settings**: Number of settings in SQLite database
|
||||
|
||||
#### Contact Differences
|
||||
|
||||
- **Added**: Contacts in Dexie but not in SQLite
|
||||
- **Modified**: Contacts that differ between databases
|
||||
- **Missing**: Contacts in SQLite but not in Dexie
|
||||
|
||||
#### Settings Differences
|
||||
|
||||
- **Added**: Settings in Dexie but not in SQLite
|
||||
- **Modified**: Settings that differ between databases
|
||||
- **Missing**: Settings in SQLite but not in Dexie
|
||||
|
||||
### Step 3: Configure Migration Options
|
||||
|
||||
Before migrating data, configure the migration options:
|
||||
|
||||
- **Overwrite existing records**: When enabled, existing records in SQLite will be updated with data from Dexie. When disabled, existing records will be skipped.
|
||||
|
||||
### Step 4: Migrate Data
|
||||
|
||||
#### Migrate Contacts
|
||||
|
||||
1. Click the **"Migrate Contacts"** button
|
||||
2. The system will transfer contacts from Dexie to SQLite
|
||||
3. Review the migration results showing:
|
||||
- Number of contacts successfully migrated
|
||||
- Any warnings or errors encountered
|
||||
|
||||
#### Migrate Settings
|
||||
|
||||
1. Click the **"Migrate Settings"** button
|
||||
2. The system will transfer settings from Dexie to SQLite
|
||||
3. Review the migration results showing:
|
||||
- Number of settings successfully migrated
|
||||
- Any warnings or errors encountered
|
||||
|
||||
### Step 5: Export Comparison (Optional)
|
||||
|
||||
1. Click the **"Export Comparison"** button
|
||||
2. A JSON file will be downloaded containing the complete comparison data
|
||||
3. This file can be used for analysis or backup purposes
|
||||
|
||||
## Migration Process Details
|
||||
|
||||
### Contact Migration
|
||||
|
||||
The contact migration process:
|
||||
|
||||
1. **Retrieves** all contacts from Dexie database
|
||||
2. **Checks** for existing contacts in SQLite by DID
|
||||
3. **Inserts** new contacts or **updates** existing ones (if overwrite is enabled)
|
||||
4. **Handles** complex fields like `contactMethods` (JSON arrays)
|
||||
5. **Reports** success/failure for each contact
|
||||
|
||||
### Settings Migration
|
||||
|
||||
The settings migration process:
|
||||
|
||||
1. **Retrieves** all settings from Dexie database
|
||||
2. **Focuses** on key user-facing settings:
|
||||
- `firstName`
|
||||
- `isRegistered`
|
||||
- `profileImageUrl`
|
||||
- `showShortcutBvc`
|
||||
- `searchBoxes`
|
||||
3. **Preserves** other settings in SQLite
|
||||
4. **Reports** success/failure for each setting
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### Dexie Database Not Enabled
|
||||
|
||||
**Error**: "Dexie database is not enabled"
|
||||
**Solution**: Set `USE_DEXIE_DB = true` in `constants/app.ts`
|
||||
|
||||
#### Database Connection Issues
|
||||
|
||||
**Error**: "Failed to retrieve Dexie contacts"
|
||||
**Solution**: Check that the Dexie database is properly initialized and accessible
|
||||
|
||||
#### SQLite Query Errors
|
||||
|
||||
**Error**: "Failed to retrieve SQLite contacts"
|
||||
**Solution**: Verify that the SQLite database is properly set up and the platform service is working
|
||||
|
||||
#### Migration Failures
|
||||
|
||||
**Error**: "Migration failed: [specific error]"
|
||||
**Solution**: Review the error details and check data integrity in both databases
|
||||
|
||||
### Error Recovery
|
||||
|
||||
1. **Review** the error messages carefully
|
||||
2. **Check** the browser console for additional details
|
||||
3. **Verify** database connectivity and permissions
|
||||
4. **Retry** the operation if appropriate
|
||||
5. **Export** comparison data for manual review if needed
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Before Migration
|
||||
|
||||
1. **Backup** your data if possible
|
||||
2. **Test** the migration on a small dataset first
|
||||
3. **Verify** that both databases are accessible
|
||||
4. **Review** the comparison results before migrating
|
||||
|
||||
### During Migration
|
||||
|
||||
1. **Don't** interrupt the migration process
|
||||
2. **Monitor** the progress and error messages
|
||||
3. **Note** any warnings or skipped records
|
||||
4. **Export** comparison data for reference
|
||||
|
||||
### After Migration
|
||||
|
||||
1. **Verify** that data was migrated correctly
|
||||
2. **Test** the application functionality
|
||||
3. **Disable** Dexie database (`USE_DEXIE_DB = false`)
|
||||
4. **Clean up** any temporary files or exports
|
||||
|
||||
## Technical Details
|
||||
|
||||
### Database Schema
|
||||
|
||||
The migration handles the following data structures:
|
||||
|
||||
#### Contacts Table
|
||||
|
||||
```typescript
|
||||
interface Contact {
|
||||
did: string; // Decentralized Identifier
|
||||
name: string; // Contact name
|
||||
contactMethods: ContactMethod[]; // Array of contact methods
|
||||
nextPubKeyHashB64: string; // Next public key hash
|
||||
notes: string; // Contact notes
|
||||
profileImageUrl: string; // Profile image URL
|
||||
publicKeyBase64: string; // Public key in base64
|
||||
seesMe: boolean; // Visibility flag
|
||||
registered: boolean; // Registration status
|
||||
}
|
||||
```
|
||||
|
||||
#### Settings Table
|
||||
|
||||
```typescript
|
||||
interface Settings {
|
||||
id: number; // Settings ID
|
||||
accountDid: string; // Account DID
|
||||
activeDid: string; // Active DID
|
||||
firstName: string; // User's first name
|
||||
isRegistered: boolean; // Registration status
|
||||
profileImageUrl: string; // Profile image URL
|
||||
showShortcutBvc: boolean; // UI preference
|
||||
searchBoxes: any[]; // Search configuration
|
||||
// ... other fields
|
||||
}
|
||||
```
|
||||
|
||||
### Migration Logic
|
||||
|
||||
The migration service uses sophisticated comparison logic:
|
||||
|
||||
1. **Primary Key Matching**: Uses DID for contacts, ID for settings
|
||||
2. **Deep Comparison**: Compares all fields including complex objects
|
||||
3. **JSON Handling**: Properly handles JSON fields like `contactMethods` and `searchBoxes`
|
||||
4. **Conflict Resolution**: Provides options for handling existing records
|
||||
|
||||
### Performance Considerations
|
||||
|
||||
- **Batch Processing**: Processes records one by one for reliability
|
||||
- **Error Isolation**: Individual record failures don't stop the entire migration
|
||||
- **Memory Management**: Handles large datasets efficiently
|
||||
- **Progress Reporting**: Provides real-time feedback during migration
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Migration Stuck
|
||||
|
||||
If the migration appears to be stuck:
|
||||
|
||||
1. **Check** the browser console for errors
|
||||
2. **Refresh** the page and try again
|
||||
3. **Verify** database connectivity
|
||||
4. **Check** for large datasets that might take time
|
||||
|
||||
### Incomplete Migration
|
||||
|
||||
If migration doesn't complete:
|
||||
|
||||
1. **Review** error messages
|
||||
2. **Check** data integrity in both databases
|
||||
3. **Export** comparison data for manual review
|
||||
4. **Consider** migrating in smaller batches
|
||||
|
||||
### Data Inconsistencies
|
||||
|
||||
If you notice data inconsistencies:
|
||||
|
||||
1. **Export** comparison data
|
||||
2. **Review** the differences carefully
|
||||
3. **Manually** verify critical records
|
||||
4. **Consider** selective migration of specific records
|
||||
|
||||
## Support
|
||||
|
||||
For issues with the Database Migration feature:
|
||||
|
||||
1. **Check** this documentation first
|
||||
2. **Review** the browser console for error details
|
||||
3. **Export** comparison data for analysis
|
||||
4. **Contact** the development team with specific error details
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- **Data Privacy**: Migration data is processed locally and not sent to external servers
|
||||
- **Access Control**: Only users with access to the account can perform migration
|
||||
- **Data Integrity**: Migration preserves data integrity and handles conflicts gracefully
|
||||
- **Audit Trail**: Export functionality provides an audit trail of migration operations
|
||||
|
||||
---
|
||||
|
||||
**Note**: This migration tool is designed for the transition period between database systems. Once migration is complete and verified, the Dexie database should be disabled to avoid confusion and potential data conflicts.
|
||||
@@ -3,7 +3,6 @@
|
||||
## Schema Mapping
|
||||
|
||||
### Current Dexie Schema
|
||||
|
||||
```typescript
|
||||
// Current Dexie schema
|
||||
const db = new Dexie('TimeSafariDB');
|
||||
@@ -16,7 +15,6 @@ db.version(1).stores({
|
||||
```
|
||||
|
||||
### New SQLite Schema
|
||||
|
||||
```sql
|
||||
-- New SQLite schema
|
||||
CREATE TABLE accounts (
|
||||
@@ -52,7 +50,6 @@ CREATE INDEX idx_settings_updated_at ON settings(updated_at);
|
||||
### 1. Account Operations
|
||||
|
||||
#### Get Account by DID
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
const account = await db.accounts.get(did);
|
||||
@@ -65,7 +62,6 @@ const account = result[0]?.values[0];
|
||||
```
|
||||
|
||||
#### Get All Accounts
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
const accounts = await db.accounts.toArray();
|
||||
@@ -78,7 +74,6 @@ const accounts = result[0]?.values || [];
|
||||
```
|
||||
|
||||
#### Add Account
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.accounts.add({
|
||||
@@ -96,7 +91,6 @@ await db.run(`
|
||||
```
|
||||
|
||||
#### Update Account
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.accounts.update(did, {
|
||||
@@ -106,7 +100,7 @@ await db.accounts.update(did, {
|
||||
|
||||
// absurd-sql
|
||||
await db.run(`
|
||||
UPDATE accounts
|
||||
UPDATE accounts
|
||||
SET public_key_hex = ?, updated_at = ?
|
||||
WHERE did = ?
|
||||
`, [publicKeyHex, Date.now(), did]);
|
||||
@@ -115,7 +109,6 @@ await db.run(`
|
||||
### 2. Settings Operations
|
||||
|
||||
#### Get Setting
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
const setting = await db.settings.get(key);
|
||||
@@ -128,7 +121,6 @@ const setting = result[0]?.values[0];
|
||||
```
|
||||
|
||||
#### Set Setting
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.settings.put({
|
||||
@@ -150,7 +142,6 @@ await db.run(`
|
||||
### 3. Contact Operations
|
||||
|
||||
#### Get Contacts by Account
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
const contacts = await db.contacts
|
||||
@@ -160,7 +151,7 @@ const contacts = await db.contacts
|
||||
|
||||
// absurd-sql
|
||||
const result = await db.exec(`
|
||||
SELECT * FROM contacts
|
||||
SELECT * FROM contacts
|
||||
WHERE did = ?
|
||||
ORDER BY created_at DESC
|
||||
`, [accountDid]);
|
||||
@@ -168,7 +159,6 @@ const contacts = result[0]?.values || [];
|
||||
```
|
||||
|
||||
#### Add Contact
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.contacts.add({
|
||||
@@ -189,7 +179,6 @@ await db.run(`
|
||||
## Transaction Mapping
|
||||
|
||||
### Batch Operations
|
||||
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.transaction('rw', [db.accounts, db.contacts], async () => {
|
||||
@@ -221,11 +210,10 @@ try {
|
||||
## Migration Helper Functions
|
||||
|
||||
### 1. Data Export (Dexie to JSON)
|
||||
|
||||
```typescript
|
||||
async function exportDexieData(): Promise<MigrationData> {
|
||||
const db = new Dexie('TimeSafariDB');
|
||||
|
||||
|
||||
return {
|
||||
accounts: await db.accounts.toArray(),
|
||||
settings: await db.settings.toArray(),
|
||||
@@ -240,7 +228,6 @@ async function exportDexieData(): Promise<MigrationData> {
|
||||
```
|
||||
|
||||
### 2. Data Import (JSON to absurd-sql)
|
||||
|
||||
```typescript
|
||||
async function importToAbsurdSql(data: MigrationData): Promise<void> {
|
||||
await db.exec('BEGIN TRANSACTION;');
|
||||
@@ -252,7 +239,7 @@ async function importToAbsurdSql(data: MigrationData): Promise<void> {
|
||||
VALUES (?, ?, ?, ?)
|
||||
`, [account.did, account.publicKeyHex, account.createdAt, account.updatedAt]);
|
||||
}
|
||||
|
||||
|
||||
// Import settings
|
||||
for (const setting of data.settings) {
|
||||
await db.run(`
|
||||
@@ -260,7 +247,7 @@ async function importToAbsurdSql(data: MigrationData): Promise<void> {
|
||||
VALUES (?, ?, ?)
|
||||
`, [setting.key, setting.value, setting.updatedAt]);
|
||||
}
|
||||
|
||||
|
||||
// Import contacts
|
||||
for (const contact of data.contacts) {
|
||||
await db.run(`
|
||||
@@ -277,7 +264,6 @@ async function importToAbsurdSql(data: MigrationData): Promise<void> {
|
||||
```
|
||||
|
||||
### 3. Verification
|
||||
|
||||
```typescript
|
||||
async function verifyMigration(dexieData: MigrationData): Promise<boolean> {
|
||||
// Verify account count
|
||||
@@ -286,21 +272,21 @@ async function verifyMigration(dexieData: MigrationData): Promise<boolean> {
|
||||
if (accountCount !== dexieData.accounts.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Verify settings count
|
||||
const settingsResult = await db.exec('SELECT COUNT(*) as count FROM settings');
|
||||
const settingsCount = settingsResult[0].values[0][0];
|
||||
if (settingsCount !== dexieData.settings.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Verify contacts count
|
||||
const contactsResult = await db.exec('SELECT COUNT(*) as count FROM contacts');
|
||||
const contactsCount = contactsResult[0].values[0][0];
|
||||
if (contactsCount !== dexieData.contacts.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Verify data integrity
|
||||
for (const account of dexieData.accounts) {
|
||||
const result = await db.exec(
|
||||
@@ -308,12 +294,12 @@ async function verifyMigration(dexieData: MigrationData): Promise<boolean> {
|
||||
[account.did]
|
||||
);
|
||||
const migratedAccount = result[0]?.values[0];
|
||||
if (!migratedAccount ||
|
||||
if (!migratedAccount ||
|
||||
migratedAccount[1] !== account.publicKeyHex) { // public_key_hex is second column
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
@@ -321,21 +307,18 @@ async function verifyMigration(dexieData: MigrationData): Promise<boolean> {
|
||||
## Performance Considerations
|
||||
|
||||
### 1. Indexing
|
||||
|
||||
- Dexie automatically creates indexes based on the schema
|
||||
- absurd-sql requires explicit index creation
|
||||
- Added indexes for frequently queried fields
|
||||
- Use `PRAGMA journal_mode=MEMORY;` for better performance
|
||||
|
||||
### 2. Batch Operations
|
||||
|
||||
- Dexie has built-in bulk operations
|
||||
- absurd-sql uses transactions for batch operations
|
||||
- Consider chunking large datasets
|
||||
- Use prepared statements for repeated queries
|
||||
|
||||
### 3. Query Optimization
|
||||
|
||||
- Dexie uses IndexedDB's native indexing
|
||||
- absurd-sql requires explicit query optimization
|
||||
- Use prepared statements for repeated queries
|
||||
@@ -344,7 +327,6 @@ async function verifyMigration(dexieData: MigrationData): Promise<boolean> {
|
||||
## Error Handling
|
||||
|
||||
### 1. Common Errors
|
||||
|
||||
```typescript
|
||||
// Dexie errors
|
||||
try {
|
||||
@@ -369,7 +351,6 @@ try {
|
||||
```
|
||||
|
||||
### 2. Transaction Recovery
|
||||
|
||||
```typescript
|
||||
// Dexie transaction
|
||||
try {
|
||||
@@ -415,4 +396,4 @@ try {
|
||||
- Remove Dexie database
|
||||
- Clear IndexedDB storage
|
||||
- Update application code
|
||||
- Remove old dependencies
|
||||
- Remove old dependencies
|
||||
270
doc/electron-migration.md
Normal file
@@ -0,0 +1,270 @@
|
||||
# Electron App Migration Strategy
|
||||
|
||||
## Overview
|
||||
|
||||
This document outlines the migration strategy for the TimeSafari Electron app, focusing on the transition from web-based storage to native SQLite implementation while maintaining cross-platform compatibility.
|
||||
|
||||
## Current Architecture
|
||||
|
||||
### 1. Platform Services
|
||||
- `ElectronPlatformService`: Implements platform-specific features for desktop
|
||||
- Uses `@capacitor-community/sqlite` for database operations
|
||||
- Maintains compatibility with web/mobile platforms through shared interfaces
|
||||
|
||||
### 2. Database Implementation
|
||||
- SQLite with native Node.js backend
|
||||
- WAL journal mode for better concurrency
|
||||
- Connection pooling for performance
|
||||
- Migration system for schema updates
|
||||
- Secure file permissions (0o755)
|
||||
|
||||
### 3. Build Process
|
||||
```bash
|
||||
# Development
|
||||
npm run dev:electron
|
||||
|
||||
# Production Build
|
||||
npm run build:web
|
||||
npm run build:electron
|
||||
npm run electron:build-linux # or electron:build-mac
|
||||
```
|
||||
|
||||
## Migration Goals
|
||||
|
||||
1. **Data Integrity**
|
||||
- Preserve existing data during migration
|
||||
- Maintain data relationships
|
||||
- Ensure ACID compliance
|
||||
- Implement proper backup/restore
|
||||
|
||||
2. **Performance**
|
||||
- Optimize SQLite configuration
|
||||
- Implement connection pooling
|
||||
- Use WAL journal mode
|
||||
- Configure optimal PRAGMA settings
|
||||
|
||||
3. **Security**
|
||||
- Secure file permissions
|
||||
- Proper IPC communication
|
||||
- Context isolation
|
||||
- Safe preload scripts
|
||||
|
||||
4. **User Experience**
|
||||
- Zero data loss
|
||||
- Automatic migration
|
||||
- Progress indicators
|
||||
- Error recovery
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### 1. Database Initialization
|
||||
```typescript
|
||||
// electron/src/rt/sqlite-init.ts
|
||||
export async function initializeSQLite() {
|
||||
// Set up database path with proper permissions
|
||||
const dbPath = path.join(app.getPath('userData'), 'timesafari.db');
|
||||
|
||||
// Initialize SQLite plugin
|
||||
const sqlite = new CapacitorSQLite();
|
||||
|
||||
// Configure database
|
||||
await sqlite.createConnection({
|
||||
database: 'timesafari',
|
||||
path: dbPath,
|
||||
encrypted: false,
|
||||
mode: 'no-encryption'
|
||||
});
|
||||
|
||||
// Set optimal PRAGMA settings
|
||||
await sqlite.execute({
|
||||
database: 'timesafari',
|
||||
statements: [
|
||||
'PRAGMA journal_mode = WAL;',
|
||||
'PRAGMA synchronous = NORMAL;',
|
||||
'PRAGMA foreign_keys = ON;'
|
||||
]
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Migration System
|
||||
```typescript
|
||||
// electron/src/rt/sqlite-migrations.ts
|
||||
interface Migration {
|
||||
version: number;
|
||||
name: string;
|
||||
description: string;
|
||||
sql: string;
|
||||
rollback?: string;
|
||||
}
|
||||
|
||||
async function runMigrations(plugin: any, database: string) {
|
||||
// Track migration state
|
||||
const state = await getMigrationState(plugin, database);
|
||||
|
||||
// Execute migrations in transaction
|
||||
for (const migration of pendingMigrations) {
|
||||
await executeMigration(plugin, database, migration);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Platform Service Implementation
|
||||
```typescript
|
||||
// src/services/platforms/ElectronPlatformService.ts
|
||||
export class ElectronPlatformService implements PlatformService {
|
||||
private sqlite: any;
|
||||
|
||||
async dbQuery(sql: string, params: any[]): Promise<QueryExecResult> {
|
||||
return await this.sqlite.execute({
|
||||
database: 'timesafari',
|
||||
statements: [{ statement: sql, values: params }]
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Preload Script
|
||||
```typescript
|
||||
// electron/preload.ts
|
||||
contextBridge.exposeInMainWorld('electron', {
|
||||
sqlite: {
|
||||
isAvailable: () => ipcRenderer.invoke('sqlite:isAvailable'),
|
||||
execute: (method: string, ...args: unknown[]) =>
|
||||
ipcRenderer.invoke('sqlite:execute', method, ...args)
|
||||
},
|
||||
getPath: (pathType: string) => ipcRenderer.invoke('get-path', pathType),
|
||||
env: {
|
||||
platform: 'electron'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Build Configuration
|
||||
|
||||
### 1. Vite Configuration
|
||||
```typescript
|
||||
// vite.config.app.electron.mts
|
||||
export default defineConfig({
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true
|
||||
},
|
||||
define: {
|
||||
'process.env.VITE_PLATFORM': JSON.stringify('electron'),
|
||||
'process.env.VITE_PWA_ENABLED': JSON.stringify(false)
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### 2. Package Scripts
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"dev:electron": "vite build --watch --config vite.config.app.electron.mts",
|
||||
"build:electron": "vite build --config vite.config.app.electron.mts",
|
||||
"electron:build-linux": "electron-builder --linux",
|
||||
"electron:build-mac": "electron-builder --mac"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
1. **Unit Tests**
|
||||
- Database operations
|
||||
- Migration system
|
||||
- Platform service methods
|
||||
- IPC communication
|
||||
|
||||
2. **Integration Tests**
|
||||
- Full migration process
|
||||
- Data integrity verification
|
||||
- Cross-platform compatibility
|
||||
- Error recovery
|
||||
|
||||
3. **End-to-End Tests**
|
||||
- User workflows
|
||||
- Data persistence
|
||||
- UI interactions
|
||||
- Platform-specific features
|
||||
|
||||
## Error Handling
|
||||
|
||||
1. **Database Errors**
|
||||
- Connection failures
|
||||
- Migration errors
|
||||
- Query execution errors
|
||||
- Transaction failures
|
||||
|
||||
2. **Platform Errors**
|
||||
- File system errors
|
||||
- IPC communication errors
|
||||
- Permission issues
|
||||
- Resource constraints
|
||||
|
||||
3. **Recovery Mechanisms**
|
||||
- Automatic retry logic
|
||||
- Transaction rollback
|
||||
- State verification
|
||||
- User notifications
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **File System**
|
||||
- Secure file permissions
|
||||
- Path validation
|
||||
- Access control
|
||||
- Data encryption
|
||||
|
||||
2. **IPC Communication**
|
||||
- Context isolation
|
||||
- Channel validation
|
||||
- Data sanitization
|
||||
- Error handling
|
||||
|
||||
3. **Preload Scripts**
|
||||
- Minimal API exposure
|
||||
- Type safety
|
||||
- Input validation
|
||||
- Error boundaries
|
||||
|
||||
## Future Improvements
|
||||
|
||||
1. **Performance**
|
||||
- Query optimization
|
||||
- Index tuning
|
||||
- Connection management
|
||||
- Cache implementation
|
||||
|
||||
2. **Features**
|
||||
- Offline support
|
||||
- Sync capabilities
|
||||
- Backup/restore
|
||||
- Data export/import
|
||||
|
||||
3. **Security**
|
||||
- Database encryption
|
||||
- Secure storage
|
||||
- Access control
|
||||
- Audit logging
|
||||
|
||||
## Maintenance
|
||||
|
||||
1. **Regular Tasks**
|
||||
- Database optimization
|
||||
- Log rotation
|
||||
- Error monitoring
|
||||
- Performance tracking
|
||||
|
||||
2. **Updates**
|
||||
- Dependency updates
|
||||
- Security patches
|
||||
- Feature additions
|
||||
- Bug fixes
|
||||
|
||||
3. **Documentation**
|
||||
- API documentation
|
||||
- Migration guides
|
||||
- Troubleshooting
|
||||
- Best practices
|
||||
@@ -1,272 +0,0 @@
|
||||
# Migration Fence Definition: Dexie to SQLite
|
||||
|
||||
## Overview
|
||||
|
||||
This document defines the **migration fence** - the boundary between the legacy Dexie (IndexedDB) storage system and the new SQLite-based storage system in TimeSafari. The fence ensures controlled migration while maintaining data integrity and application stability.
|
||||
|
||||
## Current Migration Status
|
||||
|
||||
### ✅ Completed Components
|
||||
- **SQLite Database Service**: Fully implemented with absurd-sql
|
||||
- **Platform Service Layer**: Unified database interface across platforms
|
||||
- **Migration Tools**: Data comparison and transfer utilities
|
||||
- **Schema Migration**: Complete table structure migration
|
||||
- **Data Export/Import**: Backup and restore functionality
|
||||
|
||||
### 🔄 Active Migration Components
|
||||
- **Settings Migration**: Core user settings transferred
|
||||
- **Account Migration**: Identity and key management
|
||||
- **Contact Migration**: User contact data (via import interface)
|
||||
|
||||
### ❌ Legacy Components (Fence Boundary)
|
||||
- **Dexie Database**: Legacy IndexedDB storage (disabled by default)
|
||||
- **Dexie-Specific Code**: Direct database access patterns
|
||||
- **Legacy Migration Paths**: Old data transfer methods
|
||||
|
||||
## Migration Fence Definition
|
||||
|
||||
### 1. Configuration Boundary
|
||||
|
||||
```typescript
|
||||
// src/constants/app.ts
|
||||
export const USE_DEXIE_DB = false; // FENCE: Controls legacy database access
|
||||
```
|
||||
|
||||
**Fence Rule**: When `USE_DEXIE_DB = false`:
|
||||
- All new data operations use SQLite
|
||||
- Legacy Dexie database is not initialized
|
||||
- Migration tools are the only path to legacy data
|
||||
|
||||
**Fence Rule**: When `USE_DEXIE_DB = true`:
|
||||
- Legacy database is available for migration
|
||||
- Dual-write operations may be enabled
|
||||
- Migration tools can access both databases
|
||||
|
||||
### 2. Service Layer Boundary
|
||||
|
||||
```typescript
|
||||
// src/services/PlatformServiceFactory.ts
|
||||
export class PlatformServiceFactory {
|
||||
public static getInstance(): PlatformService {
|
||||
// FENCE: All database operations go through platform service
|
||||
// No direct Dexie access outside migration tools
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Fence Rule**: All database operations must use:
|
||||
- `PlatformService.dbQuery()` for read operations
|
||||
- `PlatformService.dbExec()` for write operations
|
||||
- No direct `db.` or `accountsDBPromise` access in application code
|
||||
|
||||
### 3. Data Access Patterns
|
||||
|
||||
#### ✅ Allowed (Inside Fence)
|
||||
```typescript
|
||||
// Use platform service for all database operations
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const contacts = await platformService.dbQuery(
|
||||
"SELECT * FROM contacts WHERE did = ?",
|
||||
[accountDid]
|
||||
);
|
||||
```
|
||||
|
||||
#### ❌ Forbidden (Outside Fence)
|
||||
```typescript
|
||||
// Direct Dexie access (legacy pattern)
|
||||
const contacts = await db.contacts.where('did').equals(accountDid).toArray();
|
||||
|
||||
// Direct database reference
|
||||
const result = await accountsDBPromise;
|
||||
```
|
||||
|
||||
### 4. Migration Tool Boundary
|
||||
|
||||
```typescript
|
||||
// src/services/indexedDBMigrationService.ts
|
||||
// FENCE: Only migration tools can access both databases
|
||||
export async function compareDatabases(): Promise<DataComparison> {
|
||||
// This is the ONLY place where both databases are accessed
|
||||
}
|
||||
```
|
||||
|
||||
**Fence Rule**: Migration tools are the exclusive interface between:
|
||||
- Legacy Dexie database
|
||||
- New SQLite database
|
||||
- Data comparison and transfer operations
|
||||
|
||||
## Migration Fence Guidelines
|
||||
|
||||
### 1. Code Development Rules
|
||||
|
||||
#### New Feature Development
|
||||
- **Always** use `PlatformService` for database operations
|
||||
- **Never** import or reference Dexie directly
|
||||
- **Always** test with `USE_DEXIE_DB = false`
|
||||
|
||||
#### Legacy Code Maintenance
|
||||
- **Only** modify Dexie code for migration purposes
|
||||
- **Always** add migration tests for schema changes
|
||||
- **Never** add new Dexie-specific features
|
||||
|
||||
### 2. Data Integrity Rules
|
||||
|
||||
#### Migration Safety
|
||||
- **Always** create backups before migration
|
||||
- **Always** verify data integrity after migration
|
||||
- **Never** delete legacy data until verified
|
||||
|
||||
#### Rollback Strategy
|
||||
- **Always** maintain ability to rollback to Dexie
|
||||
- **Always** preserve migration logs
|
||||
- **Never** assume migration is irreversible
|
||||
|
||||
### 3. Testing Requirements
|
||||
|
||||
#### Migration Testing
|
||||
```typescript
|
||||
// Required test pattern for migration
|
||||
describe('Database Migration', () => {
|
||||
it('should migrate data without loss', async () => {
|
||||
// 1. Enable Dexie
|
||||
// 2. Create test data
|
||||
// 3. Run migration
|
||||
// 4. Verify data integrity
|
||||
// 5. Disable Dexie
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
#### Application Testing
|
||||
```typescript
|
||||
// Required test pattern for application features
|
||||
describe('Feature with Database', () => {
|
||||
it('should work with SQLite only', async () => {
|
||||
// Test with USE_DEXIE_DB = false
|
||||
// Verify all operations use PlatformService
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Migration Fence Enforcement
|
||||
|
||||
### 1. Static Analysis
|
||||
|
||||
#### ESLint Rules
|
||||
```json
|
||||
{
|
||||
"rules": {
|
||||
"no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
"patterns": [
|
||||
{
|
||||
"group": ["../db/index"],
|
||||
"message": "Use PlatformService instead of direct Dexie access"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### TypeScript Rules
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"noImplicitAny": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Runtime Checks
|
||||
|
||||
#### Development Mode Validation
|
||||
```typescript
|
||||
// Development-only fence validation
|
||||
if (import.meta.env.DEV && USE_DEXIE_DB) {
|
||||
console.warn('⚠️ Dexie is enabled - migration mode active');
|
||||
}
|
||||
```
|
||||
|
||||
#### Production Safety
|
||||
```typescript
|
||||
// Production fence enforcement
|
||||
if (import.meta.env.PROD && USE_DEXIE_DB) {
|
||||
throw new Error('Dexie cannot be enabled in production');
|
||||
}
|
||||
```
|
||||
|
||||
## Migration Fence Timeline
|
||||
|
||||
### Phase 1: Fence Establishment ✅
|
||||
- [x] Define migration fence boundaries
|
||||
- [x] Implement PlatformService layer
|
||||
- [x] Create migration tools
|
||||
- [x] Set `USE_DEXIE_DB = false` by default
|
||||
|
||||
### Phase 2: Data Migration 🔄
|
||||
- [x] Migrate core settings
|
||||
- [x] Migrate account data
|
||||
- [ ] Complete contact migration
|
||||
- [ ] Verify all data integrity
|
||||
|
||||
### Phase 3: Code Cleanup 📋
|
||||
- [ ] Remove unused Dexie imports
|
||||
- [ ] Clean up legacy database code
|
||||
- [ ] Update all documentation
|
||||
- [ ] Remove migration tools
|
||||
|
||||
### Phase 4: Fence Removal 🎯
|
||||
- [ ] Remove `USE_DEXIE_DB` constant
|
||||
- [ ] Remove Dexie dependencies
|
||||
- [ ] Remove migration service
|
||||
- [ ] Finalize SQLite-only architecture
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### 1. Data Protection
|
||||
- **Encryption**: Maintain encryption standards across migration
|
||||
- **Access Control**: Preserve user privacy during migration
|
||||
- **Audit Trail**: Log all migration operations
|
||||
|
||||
### 2. Error Handling
|
||||
- **Graceful Degradation**: Handle migration failures gracefully
|
||||
- **User Communication**: Clear messaging about migration status
|
||||
- **Recovery Options**: Provide rollback mechanisms
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
### 1. Migration Performance
|
||||
- **Batch Operations**: Use transactions for bulk data transfer
|
||||
- **Progress Indicators**: Show migration progress to users
|
||||
- **Background Processing**: Non-blocking migration operations
|
||||
|
||||
### 2. Application Performance
|
||||
- **Query Optimization**: Optimize SQLite queries for performance
|
||||
- **Indexing Strategy**: Maintain proper database indexes
|
||||
- **Memory Management**: Efficient memory usage during migration
|
||||
|
||||
## Documentation Requirements
|
||||
|
||||
### 1. Code Documentation
|
||||
- **Migration Fence Comments**: Document fence boundaries in code
|
||||
- **API Documentation**: Update all database API documentation
|
||||
- **Migration Guides**: Comprehensive migration documentation
|
||||
|
||||
### 2. User Documentation
|
||||
- **Migration Instructions**: Clear user migration steps
|
||||
- **Troubleshooting**: Common migration issues and solutions
|
||||
- **Rollback Instructions**: How to revert if needed
|
||||
|
||||
## Conclusion
|
||||
|
||||
The migration fence provides a controlled boundary between legacy and new database systems, ensuring:
|
||||
- **Data Integrity**: No data loss during migration
|
||||
- **Application Stability**: Consistent behavior across platforms
|
||||
- **Development Clarity**: Clear guidelines for code development
|
||||
- **Migration Safety**: Controlled and reversible migration process
|
||||
|
||||
This fence will remain in place until all data is successfully migrated and verified, at which point the legacy system can be safely removed.
|
||||
@@ -1,355 +0,0 @@
|
||||
# Database Migration Security Audit Checklist
|
||||
|
||||
## Overview
|
||||
|
||||
This document provides a comprehensive security audit checklist for the Dexie to SQLite migration in TimeSafari. The checklist ensures that data protection, privacy, and security are maintained throughout the migration process.
|
||||
|
||||
## Pre-Migration Security Assessment
|
||||
|
||||
### 1. Data Classification and Sensitivity
|
||||
|
||||
- [ ] **Data Inventory**
|
||||
- [ ] Identify all sensitive data types (DIDs, private keys, personal information)
|
||||
- [ ] Document data retention requirements
|
||||
- [ ] Map data relationships and dependencies
|
||||
- [ ] Assess data sensitivity levels (public, internal, confidential, restricted)
|
||||
|
||||
- [ ] **Encryption Assessment**
|
||||
- [ ] Verify current encryption methods for sensitive data
|
||||
- [ ] Document encryption keys and their management
|
||||
- [ ] Assess encryption strength and compliance
|
||||
- [ ] Plan encryption migration strategy
|
||||
|
||||
### 2. Access Control Review
|
||||
|
||||
- [ ] **User Access Rights**
|
||||
- [ ] Audit current user permissions and roles
|
||||
- [ ] Document access control mechanisms
|
||||
- [ ] Verify principle of least privilege
|
||||
- [ ] Plan access control migration
|
||||
|
||||
- [ ] **System Access**
|
||||
- [ ] Review database access patterns
|
||||
- [ ] Document authentication mechanisms
|
||||
- [ ] Assess session management
|
||||
- [ ] Plan authentication migration
|
||||
|
||||
### 3. Compliance Requirements
|
||||
|
||||
- [ ] **Regulatory Compliance**
|
||||
- [ ] Identify applicable regulations (GDPR, CCPA, etc.)
|
||||
- [ ] Document data processing requirements
|
||||
- [ ] Assess privacy impact
|
||||
- [ ] Plan compliance verification
|
||||
|
||||
- [ ] **Industry Standards**
|
||||
- [ ] Review security standards compliance
|
||||
- [ ] Document security controls
|
||||
- [ ] Assess audit requirements
|
||||
- [ ] Plan standards compliance
|
||||
|
||||
## Migration Security Controls
|
||||
|
||||
### 1. Data Protection During Migration
|
||||
|
||||
- [ ] **Encryption in Transit**
|
||||
- [ ] Verify all data transfers are encrypted
|
||||
- [ ] Use secure communication protocols (TLS 1.3+)
|
||||
- [ ] Implement secure API endpoints
|
||||
- [ ] Monitor encryption status
|
||||
|
||||
- [ ] **Encryption at Rest**
|
||||
- [ ] Maintain encryption for stored data
|
||||
- [ ] Verify encryption key management
|
||||
- [ ] Test encryption/decryption processes
|
||||
- [ ] Document encryption procedures
|
||||
|
||||
### 2. Access Control During Migration
|
||||
|
||||
- [ ] **Authentication**
|
||||
- [ ] Maintain user authentication during migration
|
||||
- [ ] Verify session management
|
||||
- [ ] Implement secure token handling
|
||||
- [ ] Monitor authentication events
|
||||
|
||||
- [ ] **Authorization**
|
||||
- [ ] Preserve user permissions during migration
|
||||
- [ ] Verify role-based access control
|
||||
- [ ] Implement audit logging
|
||||
- [ ] Monitor access patterns
|
||||
|
||||
### 3. Data Integrity
|
||||
|
||||
- [ ] **Data Validation**
|
||||
- [ ] Implement input validation for all data
|
||||
- [ ] Verify data format consistency
|
||||
- [ ] Test data transformation processes
|
||||
- [ ] Document validation rules
|
||||
|
||||
- [ ] **Data Verification**
|
||||
- [ ] Implement checksums for data integrity
|
||||
- [ ] Verify data completeness after migration
|
||||
- [ ] Test data consistency checks
|
||||
- [ ] Document verification procedures
|
||||
|
||||
## Migration Process Security
|
||||
|
||||
### 1. Backup Security
|
||||
|
||||
- [ ] **Backup Creation**
|
||||
- [ ] Create encrypted backups before migration
|
||||
- [ ] Verify backup integrity
|
||||
- [ ] Store backups securely
|
||||
- [ ] Test backup restoration
|
||||
|
||||
- [ ] **Backup Access**
|
||||
- [ ] Limit backup access to authorized personnel
|
||||
- [ ] Implement backup access logging
|
||||
- [ ] Verify backup encryption
|
||||
- [ ] Document backup procedures
|
||||
|
||||
### 2. Migration Tool Security
|
||||
|
||||
- [ ] **Tool Authentication**
|
||||
- [ ] Implement secure authentication for migration tools
|
||||
- [ ] Verify tool access controls
|
||||
- [ ] Monitor tool usage
|
||||
- [ ] Document tool security
|
||||
|
||||
- [ ] **Tool Validation**
|
||||
- [ ] Verify migration tool integrity
|
||||
- [ ] Test tool security features
|
||||
- [ ] Validate tool outputs
|
||||
- [ ] Document tool validation
|
||||
|
||||
### 3. Error Handling
|
||||
|
||||
- [ ] **Error Security**
|
||||
- [ ] Implement secure error handling
|
||||
- [ ] Avoid information disclosure in errors
|
||||
- [ ] Log security-relevant errors
|
||||
- [ ] Document error procedures
|
||||
|
||||
- [ ] **Recovery Security**
|
||||
- [ ] Implement secure recovery procedures
|
||||
- [ ] Verify recovery data protection
|
||||
- [ ] Test recovery processes
|
||||
- [ ] Document recovery security
|
||||
|
||||
## Post-Migration Security
|
||||
|
||||
### 1. Data Verification
|
||||
|
||||
- [ ] **Data Completeness**
|
||||
- [ ] Verify all data was migrated successfully
|
||||
- [ ] Check for data corruption
|
||||
- [ ] Validate data relationships
|
||||
- [ ] Document verification results
|
||||
|
||||
- [ ] **Data Accuracy**
|
||||
- [ ] Verify data accuracy after migration
|
||||
- [ ] Test data consistency
|
||||
- [ ] Validate data integrity
|
||||
- [ ] Document accuracy checks
|
||||
|
||||
### 2. Access Control Verification
|
||||
|
||||
- [ ] **User Access**
|
||||
- [ ] Verify user access rights after migration
|
||||
- [ ] Test authentication mechanisms
|
||||
- [ ] Validate authorization rules
|
||||
- [ ] Document access verification
|
||||
|
||||
- [ ] **System Access**
|
||||
- [ ] Verify system access controls
|
||||
- [ ] Test API security
|
||||
- [ ] Validate session management
|
||||
- [ ] Document system security
|
||||
|
||||
### 3. Security Testing
|
||||
|
||||
- [ ] **Penetration Testing**
|
||||
- [ ] Conduct security penetration testing
|
||||
- [ ] Test for common vulnerabilities
|
||||
- [ ] Verify security controls
|
||||
- [ ] Document test results
|
||||
|
||||
- [ ] **Vulnerability Assessment**
|
||||
- [ ] Scan for security vulnerabilities
|
||||
- [ ] Assess security posture
|
||||
- [ ] Identify security gaps
|
||||
- [ ] Document assessment results
|
||||
|
||||
## Monitoring and Logging
|
||||
|
||||
### 1. Security Monitoring
|
||||
|
||||
- [ ] **Access Monitoring**
|
||||
- [ ] Monitor database access patterns
|
||||
- [ ] Track user authentication events
|
||||
- [ ] Monitor system access
|
||||
- [ ] Document monitoring procedures
|
||||
|
||||
- [ ] **Data Monitoring**
|
||||
- [ ] Monitor data access patterns
|
||||
- [ ] Track data modification events
|
||||
- [ ] Monitor data integrity
|
||||
- [ ] Document data monitoring
|
||||
|
||||
### 2. Security Logging
|
||||
|
||||
- [ ] **Audit Logging**
|
||||
- [ ] Implement comprehensive audit logging
|
||||
- [ ] Log all security-relevant events
|
||||
- [ ] Secure log storage and access
|
||||
- [ ] Document logging procedures
|
||||
|
||||
- [ ] **Log Analysis**
|
||||
- [ ] Implement log analysis tools
|
||||
- [ ] Monitor for security incidents
|
||||
- [ ] Analyze security trends
|
||||
- [ ] Document analysis procedures
|
||||
|
||||
## Incident Response
|
||||
|
||||
### 1. Security Incident Planning
|
||||
|
||||
- [ ] **Incident Response Plan**
|
||||
- [ ] Develop security incident response plan
|
||||
- [ ] Define incident response procedures
|
||||
- [ ] Train incident response team
|
||||
- [ ] Document response procedures
|
||||
|
||||
- [ ] **Incident Detection**
|
||||
- [ ] Implement incident detection mechanisms
|
||||
- [ ] Monitor for security incidents
|
||||
- [ ] Establish incident reporting procedures
|
||||
- [ ] Document detection procedures
|
||||
|
||||
### 2. Recovery Procedures
|
||||
|
||||
- [ ] **Data Recovery**
|
||||
- [ ] Develop data recovery procedures
|
||||
- [ ] Test recovery processes
|
||||
- [ ] Verify recovery data integrity
|
||||
- [ ] Document recovery procedures
|
||||
|
||||
- [ ] **System Recovery**
|
||||
- [ ] Develop system recovery procedures
|
||||
- [ ] Test system recovery
|
||||
- [ ] Verify system security after recovery
|
||||
- [ ] Document recovery procedures
|
||||
|
||||
## Compliance Verification
|
||||
|
||||
### 1. Regulatory Compliance
|
||||
|
||||
- [ ] **Privacy Compliance**
|
||||
- [ ] Verify GDPR compliance
|
||||
- [ ] Check CCPA compliance
|
||||
- [ ] Assess other privacy regulations
|
||||
- [ ] Document compliance status
|
||||
|
||||
- [ ] **Security Compliance**
|
||||
- [ ] Verify security standard compliance
|
||||
- [ ] Check industry requirements
|
||||
- [ ] Assess security certifications
|
||||
- [ ] Document compliance status
|
||||
|
||||
### 2. Audit Requirements
|
||||
|
||||
- [ ] **Audit Trail**
|
||||
- [ ] Maintain comprehensive audit trail
|
||||
- [ ] Verify audit log integrity
|
||||
- [ ] Test audit log accessibility
|
||||
- [ ] Document audit procedures
|
||||
|
||||
- [ ] **Audit Reporting**
|
||||
- [ ] Generate audit reports
|
||||
- [ ] Verify report accuracy
|
||||
- [ ] Distribute reports securely
|
||||
- [ ] Document reporting procedures
|
||||
|
||||
## Documentation and Training
|
||||
|
||||
### 1. Security Documentation
|
||||
|
||||
- [ ] **Security Procedures**
|
||||
- [ ] Document security procedures
|
||||
- [ ] Update security policies
|
||||
- [ ] Create security guidelines
|
||||
- [ ] Maintain documentation
|
||||
|
||||
- [ ] **Security Training**
|
||||
- [ ] Develop security training materials
|
||||
- [ ] Train staff on security procedures
|
||||
- [ ] Verify training effectiveness
|
||||
- [ ] Document training procedures
|
||||
|
||||
### 2. Ongoing Security
|
||||
|
||||
- [ ] **Security Maintenance**
|
||||
- [ ] Establish security maintenance procedures
|
||||
- [ ] Schedule security updates
|
||||
- [ ] Monitor security trends
|
||||
- [ ] Document maintenance procedures
|
||||
|
||||
- [ ] **Security Review**
|
||||
- [ ] Conduct regular security reviews
|
||||
- [ ] Update security controls
|
||||
- [ ] Assess security effectiveness
|
||||
- [ ] Document review procedures
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
### 1. Risk Identification
|
||||
|
||||
- [ ] **Security Risks**
|
||||
- [ ] Identify potential security risks
|
||||
- [ ] Assess risk likelihood and impact
|
||||
- [ ] Prioritize security risks
|
||||
- [ ] Document risk assessment
|
||||
|
||||
- [ ] **Mitigation Strategies**
|
||||
- [ ] Develop risk mitigation strategies
|
||||
- [ ] Implement risk controls
|
||||
- [ ] Monitor risk status
|
||||
- [ ] Document mitigation procedures
|
||||
|
||||
### 2. Risk Monitoring
|
||||
|
||||
- [ ] **Risk Tracking**
|
||||
- [ ] Track identified risks
|
||||
- [ ] Monitor risk status
|
||||
- [ ] Update risk assessments
|
||||
- [ ] Document risk tracking
|
||||
|
||||
- [ ] **Risk Reporting**
|
||||
- [ ] Generate risk reports
|
||||
- [ ] Distribute risk information
|
||||
- [ ] Update risk documentation
|
||||
- [ ] Document reporting procedures
|
||||
|
||||
## Conclusion
|
||||
|
||||
This security audit checklist ensures that the database migration maintains the highest standards of data protection, privacy, and security. Regular review and updates of this checklist are essential to maintain security throughout the migration process and beyond.
|
||||
|
||||
### Security Checklist Summary
|
||||
|
||||
- [ ] **Pre-Migration Assessment**: Complete
|
||||
- [ ] **Migration Controls**: Complete
|
||||
- [ ] **Process Security**: Complete
|
||||
- [ ] **Post-Migration Verification**: Complete
|
||||
- [ ] **Monitoring and Logging**: Complete
|
||||
- [ ] **Incident Response**: Complete
|
||||
- [ ] **Compliance Verification**: Complete
|
||||
- [ ] **Documentation and Training**: Complete
|
||||
- [ ] **Risk Assessment**: Complete
|
||||
|
||||
**Overall Security Status**: [ ] Secure [ ] Needs Attention [ ] Critical Issues
|
||||
|
||||
**Next Review Date**: _______________
|
||||
|
||||
**Reviewed By**: _______________
|
||||
|
||||
**Approved By**: _______________
|
||||
@@ -4,223 +4,610 @@
|
||||
|
||||
This document outlines the migration process from Dexie.js to absurd-sql for the TimeSafari app's storage implementation. The migration aims to provide a consistent SQLite-based storage solution across all platforms while maintaining data integrity and ensuring a smooth transition for users.
|
||||
|
||||
**Current Status**: The migration is in **Phase 2** with a well-defined migration fence in place. Core settings and account data have been migrated, with contact migration in progress. **ActiveDid migration has been implemented** to ensure user identity continuity.
|
||||
|
||||
## Migration Goals
|
||||
|
||||
1. **Data Integrity**
|
||||
- Preserve all existing data
|
||||
- Maintain data relationships
|
||||
- Ensure data consistency
|
||||
- **Preserve user's active identity**
|
||||
|
||||
2. **Performance**
|
||||
- Improve query performance
|
||||
- Reduce storage overhead
|
||||
- Optimize for platform-specific capabilities
|
||||
- Optimize for platform-specific features
|
||||
|
||||
3. **User Experience**
|
||||
- Seamless transition with no data loss
|
||||
- Maintain user's active identity and preferences
|
||||
- Preserve application state
|
||||
3. **Security**
|
||||
- Maintain or improve encryption
|
||||
- Preserve access controls
|
||||
- Enhance data protection
|
||||
|
||||
## Migration Architecture
|
||||
4. **User Experience**
|
||||
- Zero data loss
|
||||
- Minimal downtime
|
||||
- Automatic migration where possible
|
||||
|
||||
### Migration Fence
|
||||
The migration fence is defined by the `USE_DEXIE_DB` constant in `src/constants/app.ts`:
|
||||
- `USE_DEXIE_DB = false` (default): Uses SQLite database
|
||||
- `USE_DEXIE_DB = true`: Uses Dexie database (for migration purposes)
|
||||
## Prerequisites
|
||||
|
||||
### Migration Order
|
||||
The migration follows a specific order to maintain data integrity:
|
||||
1. **Backup Requirements**
|
||||
```typescript
|
||||
interface MigrationBackup {
|
||||
timestamp: number;
|
||||
accounts: Account[];
|
||||
settings: Setting[];
|
||||
contacts: Contact[];
|
||||
metadata: {
|
||||
version: string;
|
||||
platform: string;
|
||||
dexieVersion: string;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
1. **Accounts** (foundational - contains DIDs)
|
||||
2. **Settings** (references accountDid, activeDid)
|
||||
3. **ActiveDid** (depends on accounts and settings) ⭐ **NEW**
|
||||
4. **Contacts** (independent, but migrated after accounts for consistency)
|
||||
2. **Dependencies**
|
||||
```json
|
||||
{
|
||||
"@jlongster/sql.js": "^1.8.0",
|
||||
"absurd-sql": "^1.8.0"
|
||||
}
|
||||
```
|
||||
|
||||
## ActiveDid Migration ⭐ **NEW FEATURE**
|
||||
3. **Storage Requirements**
|
||||
- Sufficient IndexedDB quota
|
||||
- Available disk space for SQLite
|
||||
- Backup storage space
|
||||
|
||||
### Problem Solved
|
||||
Previously, the `activeDid` setting was not migrated from Dexie to SQLite, causing users to lose their active identity after migration.
|
||||
|
||||
### Solution Implemented
|
||||
The migration now includes a dedicated step for migrating the `activeDid`:
|
||||
|
||||
1. **Detection**: Identifies the `activeDid` from Dexie master settings
|
||||
2. **Validation**: Verifies the `activeDid` exists in SQLite accounts
|
||||
3. **Migration**: Updates SQLite master settings with the `activeDid`
|
||||
4. **Error Handling**: Graceful handling of missing accounts
|
||||
|
||||
### Implementation Details
|
||||
|
||||
#### New Function: `migrateActiveDid()`
|
||||
```typescript
|
||||
export async function migrateActiveDid(): Promise<MigrationResult> {
|
||||
// 1. Get Dexie settings to find the activeDid
|
||||
const dexieSettings = await getDexieSettings();
|
||||
const masterSettings = dexieSettings.find(setting => !setting.accountDid);
|
||||
|
||||
// 2. Verify the activeDid exists in SQLite accounts
|
||||
const accountExists = await platformService.dbQuery(
|
||||
"SELECT did FROM accounts WHERE did = ?",
|
||||
[dexieActiveDid],
|
||||
);
|
||||
|
||||
// 3. Update SQLite master settings
|
||||
await updateDefaultSettings({ activeDid: dexieActiveDid });
|
||||
}
|
||||
```
|
||||
|
||||
#### Enhanced `migrateSettings()` Function
|
||||
The settings migration now includes activeDid handling:
|
||||
- Extracts `activeDid` from Dexie master settings
|
||||
- Validates account existence in SQLite
|
||||
- Updates SQLite master settings with the `activeDid`
|
||||
|
||||
#### Updated `migrateAll()` Function
|
||||
The complete migration now includes a dedicated step for activeDid:
|
||||
```typescript
|
||||
// Step 3: Migrate ActiveDid (depends on accounts and settings)
|
||||
logger.info("[MigrationService] Step 3: Migrating activeDid...");
|
||||
const activeDidResult = await migrateActiveDid();
|
||||
```
|
||||
|
||||
### Benefits
|
||||
- ✅ **User Identity Preservation**: Users maintain their active identity
|
||||
- ✅ **Seamless Experience**: No need to manually select identity after migration
|
||||
- ✅ **Data Consistency**: Ensures all identity-related settings are preserved
|
||||
- ✅ **Error Resilience**: Graceful handling of edge cases
|
||||
4. **Platform Support**
|
||||
- Web: Modern browser with IndexedDB support
|
||||
- iOS: iOS 13+ with SQLite support
|
||||
- Android: Android 5+ with SQLite support
|
||||
- Electron: Latest version with SQLite support
|
||||
|
||||
## Migration Process
|
||||
|
||||
### Phase 1: Preparation ✅
|
||||
- [x] Enable Dexie database access
|
||||
- [x] Implement data comparison tools
|
||||
- [x] Create migration service structure
|
||||
### 1. Preparation
|
||||
|
||||
### Phase 2: Core Migration ✅
|
||||
- [x] Account migration with `importFromMnemonic`
|
||||
- [x] Settings migration (excluding activeDid)
|
||||
- [x] **ActiveDid migration** ⭐ **COMPLETED**
|
||||
- [x] Contact migration framework
|
||||
|
||||
### Phase 3: Validation and Cleanup 🔄
|
||||
- [ ] Comprehensive data validation
|
||||
- [ ] Performance testing
|
||||
- [ ] User acceptance testing
|
||||
- [ ] Dexie removal
|
||||
|
||||
## Usage
|
||||
|
||||
### Manual Migration
|
||||
```typescript
|
||||
import { migrateAll, migrateActiveDid } from '../services/indexedDBMigrationService';
|
||||
// src/services/storage/migration/MigrationService.ts
|
||||
import initSqlJs from '@jlongster/sql.js';
|
||||
import { SQLiteFS } from 'absurd-sql';
|
||||
import IndexedDBBackend from 'absurd-sql/dist/indexeddb-backend';
|
||||
|
||||
// Complete migration
|
||||
const result = await migrateAll();
|
||||
export class MigrationService {
|
||||
private static instance: MigrationService;
|
||||
private backup: MigrationBackup | null = null;
|
||||
private sql: any = null;
|
||||
private db: any = null;
|
||||
|
||||
// Or migrate just the activeDid
|
||||
const activeDidResult = await migrateActiveDid();
|
||||
async prepare(): Promise<void> {
|
||||
try {
|
||||
// 1. Check prerequisites
|
||||
await this.checkPrerequisites();
|
||||
|
||||
// 2. Create backup
|
||||
this.backup = await this.createBackup();
|
||||
|
||||
// 3. Verify backup integrity
|
||||
await this.verifyBackup();
|
||||
|
||||
// 4. Initialize absurd-sql
|
||||
await this.initializeAbsurdSql();
|
||||
} catch (error) {
|
||||
throw new StorageError(
|
||||
'Migration preparation failed',
|
||||
StorageErrorCodes.MIGRATION_FAILED,
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async initializeAbsurdSql(): Promise<void> {
|
||||
// Initialize SQL.js
|
||||
this.sql = await initSqlJs({
|
||||
locateFile: (file: string) => {
|
||||
return new URL(`/node_modules/@jlongster/sql.js/dist/${file}`, import.meta.url).href;
|
||||
}
|
||||
});
|
||||
|
||||
// Setup SQLiteFS with IndexedDB backend
|
||||
const sqlFS = new SQLiteFS(this.sql.FS, new IndexedDBBackend());
|
||||
this.sql.register_for_idb(sqlFS);
|
||||
|
||||
// Create and mount filesystem
|
||||
this.sql.FS.mkdir('/sql');
|
||||
this.sql.FS.mount(sqlFS, {}, '/sql');
|
||||
|
||||
// Open database
|
||||
const path = '/sql/db.sqlite';
|
||||
if (typeof SharedArrayBuffer === 'undefined') {
|
||||
let stream = this.sql.FS.open(path, 'a+');
|
||||
await stream.node.contents.readIfFallback();
|
||||
this.sql.FS.close(stream);
|
||||
}
|
||||
|
||||
this.db = new this.sql.Database(path, { filename: true });
|
||||
if (!this.db) {
|
||||
throw new StorageError(
|
||||
'Database initialization failed',
|
||||
StorageErrorCodes.INITIALIZATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
// Configure database
|
||||
await this.db.exec(`PRAGMA journal_mode=MEMORY;`);
|
||||
}
|
||||
|
||||
private async checkPrerequisites(): Promise<void> {
|
||||
// Check IndexedDB availability
|
||||
if (!window.indexedDB) {
|
||||
throw new StorageError(
|
||||
'IndexedDB not available',
|
||||
StorageErrorCodes.INITIALIZATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
// Check storage quota
|
||||
const quota = await navigator.storage.estimate();
|
||||
if (quota.quota && quota.usage && quota.usage > quota.quota * 0.9) {
|
||||
throw new StorageError(
|
||||
'Insufficient storage space',
|
||||
StorageErrorCodes.STORAGE_FULL
|
||||
);
|
||||
}
|
||||
|
||||
// Check platform support
|
||||
const capabilities = await PlatformDetection.getCapabilities();
|
||||
if (!capabilities.hasFileSystem) {
|
||||
throw new StorageError(
|
||||
'Platform does not support required features',
|
||||
StorageErrorCodes.INITIALIZATION_FAILED
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async createBackup(): Promise<MigrationBackup> {
|
||||
const dexieDB = new Dexie('TimeSafariDB');
|
||||
|
||||
return {
|
||||
timestamp: Date.now(),
|
||||
accounts: await dexieDB.accounts.toArray(),
|
||||
settings: await dexieDB.settings.toArray(),
|
||||
contacts: await dexieDB.contacts.toArray(),
|
||||
metadata: {
|
||||
version: '1.0.0',
|
||||
platform: await PlatformDetection.getPlatform(),
|
||||
dexieVersion: Dexie.version
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Migration Verification
|
||||
### 2. Data Migration
|
||||
|
||||
```typescript
|
||||
import { compareDatabases } from '../services/indexedDBMigrationService';
|
||||
// src/services/storage/migration/DataMigration.ts
|
||||
export class DataMigration {
|
||||
async migrate(backup: MigrationBackup): Promise<void> {
|
||||
try {
|
||||
// 1. Create new database schema
|
||||
await this.createSchema();
|
||||
|
||||
// 2. Migrate accounts
|
||||
await this.migrateAccounts(backup.accounts);
|
||||
|
||||
// 3. Migrate settings
|
||||
await this.migrateSettings(backup.settings);
|
||||
|
||||
// 4. Migrate contacts
|
||||
await this.migrateContacts(backup.contacts);
|
||||
|
||||
// 5. Verify migration
|
||||
await this.verifyMigration(backup);
|
||||
} catch (error) {
|
||||
// 6. Handle failure
|
||||
await this.handleMigrationFailure(error, backup);
|
||||
}
|
||||
}
|
||||
|
||||
const comparison = await compareDatabases();
|
||||
console.log('Migration differences:', comparison.differences);
|
||||
private async migrateAccounts(accounts: Account[]): Promise<void> {
|
||||
// Use transaction for atomicity
|
||||
await this.db.exec('BEGIN TRANSACTION;');
|
||||
try {
|
||||
for (const account of accounts) {
|
||||
await this.db.run(`
|
||||
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`, [
|
||||
account.did,
|
||||
account.publicKeyHex,
|
||||
account.createdAt,
|
||||
account.updatedAt
|
||||
]);
|
||||
}
|
||||
await this.db.exec('COMMIT;');
|
||||
} catch (error) {
|
||||
await this.db.exec('ROLLBACK;');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async verifyMigration(backup: MigrationBackup): Promise<void> {
|
||||
// Verify account count
|
||||
const result = await this.db.exec('SELECT COUNT(*) as count FROM accounts');
|
||||
const accountCount = result[0].values[0][0];
|
||||
|
||||
if (accountCount !== backup.accounts.length) {
|
||||
throw new StorageError(
|
||||
'Account count mismatch',
|
||||
StorageErrorCodes.VERIFICATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
// Verify data integrity
|
||||
await this.verifyDataIntegrity(backup);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
### 3. Rollback Strategy
|
||||
|
||||
### ActiveDid Migration Errors
|
||||
- **Missing Account**: If the `activeDid` from Dexie doesn't exist in SQLite accounts
|
||||
- **Database Errors**: Connection or query failures
|
||||
- **Settings Update Failures**: Issues updating SQLite master settings
|
||||
|
||||
### Recovery Strategies
|
||||
1. **Automatic Recovery**: Migration continues even if activeDid migration fails
|
||||
2. **Manual Recovery**: Users can manually select their identity after migration
|
||||
3. **Fallback**: System creates new identity if none exists
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Data Protection
|
||||
- All sensitive data (mnemonics, private keys) are encrypted
|
||||
- Migration preserves encryption standards
|
||||
- No plaintext data exposure during migration
|
||||
|
||||
### Identity Verification
|
||||
- ActiveDid migration validates account existence
|
||||
- Prevents setting non-existent identities as active
|
||||
- Maintains cryptographic integrity
|
||||
|
||||
## Testing
|
||||
|
||||
### Migration Testing
|
||||
```bash
|
||||
# Enable Dexie for testing
|
||||
# Set USE_DEXIE_DB = true in constants/app.ts
|
||||
|
||||
# Run migration
|
||||
npm run migrate
|
||||
|
||||
# Verify results
|
||||
npm run test:migration
|
||||
```
|
||||
|
||||
### ActiveDid Testing
|
||||
```typescript
|
||||
// Test activeDid migration specifically
|
||||
const result = await migrateActiveDid();
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.warnings).toContain('Successfully migrated activeDid');
|
||||
// src/services/storage/migration/RollbackService.ts
|
||||
export class RollbackService {
|
||||
async rollback(backup: MigrationBackup): Promise<void> {
|
||||
try {
|
||||
// 1. Stop all database operations
|
||||
await this.stopDatabaseOperations();
|
||||
|
||||
// 2. Restore from backup
|
||||
await this.restoreFromBackup(backup);
|
||||
|
||||
// 3. Verify restoration
|
||||
await this.verifyRestoration(backup);
|
||||
|
||||
// 4. Clean up absurd-sql
|
||||
await this.cleanupAbsurdSql();
|
||||
} catch (error) {
|
||||
throw new StorageError(
|
||||
'Rollback failed',
|
||||
StorageErrorCodes.ROLLBACK_FAILED,
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async restoreFromBackup(backup: MigrationBackup): Promise<void> {
|
||||
const dexieDB = new Dexie('TimeSafariDB');
|
||||
|
||||
// Restore accounts
|
||||
await dexieDB.accounts.bulkPut(backup.accounts);
|
||||
|
||||
// Restore settings
|
||||
await dexieDB.settings.bulkPut(backup.settings);
|
||||
|
||||
// Restore contacts
|
||||
await dexieDB.contacts.bulkPut(backup.contacts);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
## Migration UI
|
||||
|
||||
### Common Issues
|
||||
```vue
|
||||
<!-- src/components/MigrationProgress.vue -->
|
||||
<template>
|
||||
<div class="migration-progress">
|
||||
<h2>Database Migration</h2>
|
||||
|
||||
<div class="progress-container">
|
||||
<div class="progress-bar" :style="{ width: `${progress}%` }" />
|
||||
<div class="progress-text">{{ progress }}%</div>
|
||||
</div>
|
||||
|
||||
<div class="status-message">{{ statusMessage }}</div>
|
||||
|
||||
<div v-if="error" class="error-message">
|
||||
{{ error }}
|
||||
<button @click="retryMigration">Retry</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
1. **ActiveDid Not Found**
|
||||
- Ensure accounts were migrated before activeDid migration
|
||||
- Check that the Dexie activeDid exists in SQLite accounts
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { MigrationService } from '@/services/storage/migration/MigrationService';
|
||||
|
||||
2. **Migration Failures**
|
||||
- Verify Dexie database is accessible
|
||||
- Check SQLite database permissions
|
||||
- Review migration logs for specific errors
|
||||
const progress = ref(0);
|
||||
const statusMessage = ref('Preparing migration...');
|
||||
const error = ref<string | null>(null);
|
||||
|
||||
3. **Data Inconsistencies**
|
||||
- Use `compareDatabases()` to identify differences
|
||||
- Re-run migration if necessary
|
||||
- Check for duplicate or conflicting records
|
||||
const migrationService = MigrationService.getInstance();
|
||||
|
||||
### Debugging
|
||||
```typescript
|
||||
// Enable detailed logging
|
||||
logger.setLevel('debug');
|
||||
async function startMigration() {
|
||||
try {
|
||||
// 1. Preparation
|
||||
statusMessage.value = 'Creating backup...';
|
||||
await migrationService.prepare();
|
||||
progress.value = 20;
|
||||
|
||||
// 2. Data migration
|
||||
statusMessage.value = 'Migrating data...';
|
||||
await migrationService.migrate();
|
||||
progress.value = 80;
|
||||
|
||||
// 3. Verification
|
||||
statusMessage.value = 'Verifying migration...';
|
||||
await migrationService.verify();
|
||||
progress.value = 100;
|
||||
|
||||
statusMessage.value = 'Migration completed successfully!';
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : 'Migration failed';
|
||||
statusMessage.value = 'Migration failed';
|
||||
}
|
||||
}
|
||||
|
||||
// Check migration status
|
||||
const comparison = await compareDatabases();
|
||||
console.log('Settings differences:', comparison.differences.settings);
|
||||
async function retryMigration() {
|
||||
error.value = null;
|
||||
progress.value = 0;
|
||||
await startMigration();
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
startMigration();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.migration-progress {
|
||||
padding: 2rem;
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.progress-container {
|
||||
position: relative;
|
||||
height: 20px;
|
||||
background: #eee;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
position: absolute;
|
||||
height: 100%;
|
||||
background: #4CAF50;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
line-height: 20px;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
.status-message {
|
||||
text-align: center;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
color: #f44336;
|
||||
text-align: center;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
|
||||
button {
|
||||
margin-top: 1rem;
|
||||
padding: 0.5rem 1rem;
|
||||
background: #2196F3;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: #1976D2;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
## Future Enhancements
|
||||
## Testing Strategy
|
||||
|
||||
### Planned Improvements
|
||||
1. **Batch Processing**: Optimize for large datasets
|
||||
2. **Incremental Migration**: Support partial migrations
|
||||
3. **Rollback Capability**: Ability to revert migration
|
||||
4. **Progress Tracking**: Real-time migration progress
|
||||
1. **Unit Tests**
|
||||
```typescript
|
||||
// src/services/storage/migration/__tests__/MigrationService.spec.ts
|
||||
describe('MigrationService', () => {
|
||||
it('should initialize absurd-sql correctly', async () => {
|
||||
const service = MigrationService.getInstance();
|
||||
await service.initializeAbsurdSql();
|
||||
|
||||
expect(service.isInitialized()).toBe(true);
|
||||
expect(service.getDatabase()).toBeDefined();
|
||||
});
|
||||
|
||||
### Performance Optimizations
|
||||
1. **Parallel Processing**: Migrate independent data concurrently
|
||||
2. **Memory Management**: Optimize for large datasets
|
||||
3. **Transaction Batching**: Reduce database round trips
|
||||
it('should create valid backup', async () => {
|
||||
const service = MigrationService.getInstance();
|
||||
const backup = await service.createBackup();
|
||||
|
||||
expect(backup).toBeDefined();
|
||||
expect(backup.accounts).toBeInstanceOf(Array);
|
||||
expect(backup.settings).toBeInstanceOf(Array);
|
||||
expect(backup.contacts).toBeInstanceOf(Array);
|
||||
});
|
||||
|
||||
## Conclusion
|
||||
it('should migrate data correctly', async () => {
|
||||
const service = MigrationService.getInstance();
|
||||
const backup = await service.createBackup();
|
||||
|
||||
await service.migrate(backup);
|
||||
|
||||
// Verify migration
|
||||
const accounts = await service.getMigratedAccounts();
|
||||
expect(accounts).toHaveLength(backup.accounts.length);
|
||||
});
|
||||
|
||||
The Dexie to SQLite migration provides a robust, secure, and user-friendly transition path. The addition of activeDid migration ensures that users maintain their identity continuity throughout the migration process, significantly improving the user experience.
|
||||
it('should handle rollback correctly', async () => {
|
||||
const service = MigrationService.getInstance();
|
||||
const backup = await service.createBackup();
|
||||
|
||||
// Simulate failed migration
|
||||
await service.migrate(backup);
|
||||
await service.simulateFailure();
|
||||
|
||||
// Perform rollback
|
||||
await service.rollback(backup);
|
||||
|
||||
// Verify rollback
|
||||
const accounts = await service.getOriginalAccounts();
|
||||
expect(accounts).toHaveLength(backup.accounts.length);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
The migration fence architecture allows for controlled, reversible migration while maintaining application stability and data integrity.
|
||||
2. **Integration Tests**
|
||||
```typescript
|
||||
// src/services/storage/migration/__tests__/integration/Migration.spec.ts
|
||||
describe('Migration Integration', () => {
|
||||
it('should handle concurrent access during migration', async () => {
|
||||
const service = MigrationService.getInstance();
|
||||
|
||||
// Start migration
|
||||
const migrationPromise = service.migrate();
|
||||
|
||||
// Simulate concurrent access
|
||||
const accessPromises = Array(5).fill(null).map(() =>
|
||||
service.getAccount('did:test:123')
|
||||
);
|
||||
|
||||
// Wait for all operations
|
||||
const [migrationResult, ...accessResults] = await Promise.allSettled([
|
||||
migrationPromise,
|
||||
...accessPromises
|
||||
]);
|
||||
|
||||
// Verify results
|
||||
expect(migrationResult.status).toBe('fulfilled');
|
||||
expect(accessResults.some(r => r.status === 'rejected')).toBe(true);
|
||||
});
|
||||
|
||||
it('should maintain data integrity during platform transition', async () => {
|
||||
const service = MigrationService.getInstance();
|
||||
|
||||
// Simulate platform change
|
||||
await service.simulatePlatformChange();
|
||||
|
||||
// Verify data
|
||||
const accounts = await service.getAllAccounts();
|
||||
const settings = await service.getAllSettings();
|
||||
const contacts = await service.getAllContacts();
|
||||
|
||||
expect(accounts).toBeDefined();
|
||||
expect(settings).toBeDefined();
|
||||
expect(contacts).toBeDefined();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Success Criteria
|
||||
|
||||
1. **Data Integrity**
|
||||
- [ ] All accounts migrated successfully
|
||||
- [ ] All settings preserved
|
||||
- [ ] All contacts transferred
|
||||
- [ ] No data corruption
|
||||
|
||||
2. **Performance**
|
||||
- [ ] Migration completes within acceptable time
|
||||
- [ ] No significant performance degradation
|
||||
- [ ] Efficient storage usage
|
||||
- [ ] Smooth user experience
|
||||
|
||||
3. **Security**
|
||||
- [ ] Encrypted data remains secure
|
||||
- [ ] Access controls maintained
|
||||
- [ ] No sensitive data exposure
|
||||
- [ ] Secure backup process
|
||||
|
||||
4. **User Experience**
|
||||
- [ ] Clear migration progress
|
||||
- [ ] Informative error messages
|
||||
- [ ] Automatic recovery from failures
|
||||
- [ ] No data loss
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
1. **Automatic Rollback**
|
||||
- Triggered by migration failure
|
||||
- Restores from verified backup
|
||||
- Maintains data consistency
|
||||
- Logs rollback reason
|
||||
|
||||
2. **Manual Rollback**
|
||||
- Available through settings
|
||||
- Requires user confirmation
|
||||
- Preserves backup data
|
||||
- Provides rollback status
|
||||
|
||||
3. **Emergency Recovery**
|
||||
- Manual backup restoration
|
||||
- Database repair tools
|
||||
- Data recovery procedures
|
||||
- Support contact information
|
||||
|
||||
## Post-Migration
|
||||
|
||||
1. **Verification**
|
||||
- Data integrity checks
|
||||
- Performance monitoring
|
||||
- Error rate tracking
|
||||
- User feedback collection
|
||||
|
||||
2. **Cleanup**
|
||||
- Remove old database
|
||||
- Clear migration artifacts
|
||||
- Update application state
|
||||
- Archive backup data
|
||||
|
||||
3. **Monitoring**
|
||||
- Track migration success rate
|
||||
- Monitor performance metrics
|
||||
- Collect error reports
|
||||
- Gather user feedback
|
||||
|
||||
## Support
|
||||
|
||||
For assistance with migration:
|
||||
1. Check the troubleshooting guide
|
||||
2. Review error logs
|
||||
3. Contact support team
|
||||
4. Submit issue report
|
||||
|
||||
## Timeline
|
||||
|
||||
1. **Preparation Phase** (1 week)
|
||||
- Backup system implementation
|
||||
- Migration service development
|
||||
- Testing framework setup
|
||||
|
||||
2. **Testing Phase** (2 weeks)
|
||||
- Unit testing
|
||||
- Integration testing
|
||||
- Performance testing
|
||||
- Security testing
|
||||
|
||||
3. **Deployment Phase** (1 week)
|
||||
- Staged rollout
|
||||
- Monitoring
|
||||
- Support preparation
|
||||
- Documentation updates
|
||||
|
||||
4. **Post-Deployment** (2 weeks)
|
||||
- Monitoring
|
||||
- Bug fixes
|
||||
- Performance optimization
|
||||
- User feedback collection
|
||||
55
electron/.gitignore
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
# NPM renames .gitignore to .npmignore
|
||||
# In order to prevent that, we remove the initial "."
|
||||
# And the CLI then renames it
|
||||
app
|
||||
node_modules
|
||||
build
|
||||
dist
|
||||
logs
|
||||
# Node.js dependencies
|
||||
node_modules/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# Capacitor build outputs
|
||||
web/
|
||||
ios/
|
||||
android/
|
||||
electron/app/
|
||||
|
||||
# Capacitor SQLite plugin data (important!)
|
||||
capacitor-sqlite/
|
||||
|
||||
# TypeScript / build output
|
||||
dist/
|
||||
build/
|
||||
*.log
|
||||
|
||||
# Development / IDE files
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
# VS Code
|
||||
.vscode/
|
||||
!.vscode/extensions.json
|
||||
|
||||
# JetBrains IDEs (IntelliJ, WebStorm, etc.)
|
||||
.idea/
|
||||
*.iml
|
||||
*.iws
|
||||
|
||||
# macOS specific
|
||||
.DS_Store
|
||||
*.swp
|
||||
*~
|
||||
*.tmp
|
||||
|
||||
# Windows specific
|
||||
Thumbs.db
|
||||
ehthumbs.db
|
||||
Desktop.ini
|
||||
$RECYCLE.BIN/
|
||||
BIN
electron/assets/appIcon.ico
Normal file
|
After Width: | Height: | Size: 142 KiB |
BIN
electron/assets/appIcon.png
Normal file
|
After Width: | Height: | Size: 121 KiB |
BIN
electron/assets/splash.gif
Normal file
|
After Width: | Height: | Size: 159 KiB |
BIN
electron/assets/splash.png
Normal file
|
After Width: | Height: | Size: 12 KiB |
62
electron/capacitor.config.json
Normal file
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"appId": "com.timesafari.app",
|
||||
"appName": "TimeSafari",
|
||||
"webDir": "dist",
|
||||
"bundledWebRuntime": false,
|
||||
"server": {
|
||||
"cleartext": true,
|
||||
"androidScheme": "https"
|
||||
},
|
||||
"plugins": {
|
||||
"App": {
|
||||
"appUrlOpen": {
|
||||
"handlers": [
|
||||
{
|
||||
"url": "timesafari://*",
|
||||
"autoVerify": true
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"SQLite": {
|
||||
"iosDatabaseLocation": "Library/CapacitorDatabase",
|
||||
"iosIsEncryption": true,
|
||||
"iosBiometric": {
|
||||
"biometricAuth": true,
|
||||
"biometricTitle": "Biometric login for TimeSafari"
|
||||
},
|
||||
"androidIsEncryption": true,
|
||||
"androidBiometric": {
|
||||
"biometricAuth": true,
|
||||
"biometricTitle": "Biometric login for TimeSafari"
|
||||
}
|
||||
},
|
||||
"CapacitorSQLite": {
|
||||
"electronIsEncryption": false,
|
||||
"electronMacLocation": "~/Library/Application Support/TimeSafari",
|
||||
"electronWindowsLocation": "C:\\ProgramData\\TimeSafari"
|
||||
}
|
||||
},
|
||||
"ios": {
|
||||
"contentInset": "always",
|
||||
"allowsLinkPreview": true,
|
||||
"scrollEnabled": true,
|
||||
"limitsNavigationsToAppBoundDomains": true,
|
||||
"backgroundColor": "#ffffff",
|
||||
"allowNavigation": [
|
||||
"*.timesafari.app",
|
||||
"*.jsdelivr.net",
|
||||
"api.endorser.ch"
|
||||
]
|
||||
},
|
||||
"android": {
|
||||
"allowMixedContent": false,
|
||||
"captureInput": true,
|
||||
"webContentsDebuggingEnabled": false,
|
||||
"allowNavigation": [
|
||||
"*.timesafari.app",
|
||||
"*.jsdelivr.net",
|
||||
"api.endorser.ch"
|
||||
]
|
||||
}
|
||||
}
|
||||
28
electron/electron-builder.config.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"appId": "com.yourdoamnin.yourapp",
|
||||
"directories": {
|
||||
"buildResources": "resources"
|
||||
},
|
||||
"files": [
|
||||
"assets/**/*",
|
||||
"build/**/*",
|
||||
"capacitor.config.*",
|
||||
"app/**/*"
|
||||
],
|
||||
"publish": {
|
||||
"provider": "github"
|
||||
},
|
||||
"nsis": {
|
||||
"allowElevation": true,
|
||||
"oneClick": false,
|
||||
"allowToChangeInstallationDirectory": true
|
||||
},
|
||||
"win": {
|
||||
"target": "nsis",
|
||||
"icon": "assets/appIcon.ico"
|
||||
},
|
||||
"mac": {
|
||||
"category": "your.app.category.type",
|
||||
"target": "dmg"
|
||||
}
|
||||
}
|
||||
75
electron/live-runner.js
Normal file
@@ -0,0 +1,75 @@
|
||||
/* eslint-disable no-undef */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
const cp = require('child_process');
|
||||
const chokidar = require('chokidar');
|
||||
const electron = require('electron');
|
||||
|
||||
let child = null;
|
||||
const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
||||
const reloadWatcher = {
|
||||
debouncer: null,
|
||||
ready: false,
|
||||
watcher: null,
|
||||
restarting: false,
|
||||
};
|
||||
|
||||
///*
|
||||
function runBuild() {
|
||||
return new Promise((resolve, _reject) => {
|
||||
let tempChild = cp.spawn(npmCmd, ['run', 'build']);
|
||||
tempChild.once('exit', () => {
|
||||
resolve();
|
||||
});
|
||||
tempChild.stdout.pipe(process.stdout);
|
||||
});
|
||||
}
|
||||
//*/
|
||||
|
||||
async function spawnElectron() {
|
||||
if (child !== null) {
|
||||
child.stdin.pause();
|
||||
child.kill();
|
||||
child = null;
|
||||
await runBuild();
|
||||
}
|
||||
child = cp.spawn(electron, ['--inspect=5858', './']);
|
||||
child.on('exit', () => {
|
||||
if (!reloadWatcher.restarting) {
|
||||
process.exit(0);
|
||||
}
|
||||
});
|
||||
child.stdout.pipe(process.stdout);
|
||||
}
|
||||
|
||||
function setupReloadWatcher() {
|
||||
reloadWatcher.watcher = chokidar
|
||||
.watch('./src/**/*', {
|
||||
ignored: /[/\\]\./,
|
||||
persistent: true,
|
||||
})
|
||||
.on('ready', () => {
|
||||
reloadWatcher.ready = true;
|
||||
})
|
||||
.on('all', (_event, _path) => {
|
||||
if (reloadWatcher.ready) {
|
||||
clearTimeout(reloadWatcher.debouncer);
|
||||
reloadWatcher.debouncer = setTimeout(async () => {
|
||||
console.log('Restarting');
|
||||
reloadWatcher.restarting = true;
|
||||
await spawnElectron();
|
||||
reloadWatcher.restarting = false;
|
||||
reloadWatcher.ready = false;
|
||||
clearTimeout(reloadWatcher.debouncer);
|
||||
reloadWatcher.debouncer = null;
|
||||
reloadWatcher.watcher = null;
|
||||
setupReloadWatcher();
|
||||
}, 500);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
(async () => {
|
||||
await runBuild();
|
||||
await spawnElectron();
|
||||
setupReloadWatcher();
|
||||
})();
|
||||
5460
electron/package-lock.json
generated
Normal file
52
electron/package.json
Normal file
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "TimeSafari",
|
||||
"version": "1.0.0",
|
||||
"description": "TimeSafari Electron App",
|
||||
"author": {
|
||||
"name": "",
|
||||
"email": ""
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": ""
|
||||
},
|
||||
"license": "MIT",
|
||||
"main": "build/src/index.js",
|
||||
"scripts": {
|
||||
"build": "tsc && electron-rebuild",
|
||||
"electron:start-live": "node ./live-runner.js",
|
||||
"electron:start": "npm run build && electron --inspect=5858 ./",
|
||||
"electron:pack": "npm run build && electron-builder build --dir -c ./electron-builder.config.json",
|
||||
"electron:make": "npm run build && electron-builder build -c ./electron-builder.config.json -p always"
|
||||
},
|
||||
"dependencies": {
|
||||
"@capacitor-community/electron": "^5.0.0",
|
||||
"@capacitor-community/sqlite": "^6.0.2",
|
||||
"better-sqlite3-multiple-ciphers": "^11.10.0",
|
||||
"chokidar": "~3.5.3",
|
||||
"crypto": "^1.0.1",
|
||||
"crypto-js": "^4.2.0",
|
||||
"electron-is-dev": "~2.0.0",
|
||||
"electron-json-storage": "^4.6.0",
|
||||
"electron-serve": "~1.1.0",
|
||||
"electron-unhandled": "~4.0.1",
|
||||
"electron-updater": "^5.3.0",
|
||||
"electron-window-state": "^5.0.3",
|
||||
"jszip": "^3.10.1",
|
||||
"node-fetch": "^2.6.7",
|
||||
"winston": "^3.17.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/crypto-js": "^4.2.2",
|
||||
"@types/electron-json-storage": "^4.5.4",
|
||||
"electron": "^26.2.2",
|
||||
"electron-builder": "~23.6.0",
|
||||
"source-map-support": "^0.5.21",
|
||||
"typescript": "^5.0.4"
|
||||
},
|
||||
"keywords": [
|
||||
"capacitor",
|
||||
"electron"
|
||||
]
|
||||
}
|
||||
10
electron/resources/electron-publisher-custom.js
Normal file
@@ -0,0 +1,10 @@
|
||||
/* eslint-disable no-undef */
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
const electronPublish = require('electron-publish');
|
||||
|
||||
class Publisher extends electronPublish.Publisher {
|
||||
async upload(task) {
|
||||
console.log('electron-publisher-custom', task.file);
|
||||
}
|
||||
}
|
||||
module.exports = Publisher;
|
||||
140
electron/src/index.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import type { CapacitorElectronConfig } from '@capacitor-community/electron';
|
||||
import { getCapacitorElectronConfig, setupElectronDeepLinking } from '@capacitor-community/electron';
|
||||
import type { MenuItemConstructorOptions } from 'electron';
|
||||
import { app, MenuItem } from 'electron';
|
||||
import electronIsDev from 'electron-is-dev';
|
||||
import unhandled from 'electron-unhandled';
|
||||
import { autoUpdater } from 'electron-updater';
|
||||
|
||||
import { ElectronCapacitorApp, setupContentSecurityPolicy, setupReloadWatcher } from './setup';
|
||||
import { initializeSQLite, setupSQLiteHandlers } from './rt/sqlite-init';
|
||||
|
||||
// Graceful handling of unhandled errors.
|
||||
unhandled();
|
||||
|
||||
// Define our menu templates (these are optional)
|
||||
const trayMenuTemplate: (MenuItemConstructorOptions | MenuItem)[] = [new MenuItem({ label: 'Quit App', role: 'quit' })];
|
||||
const appMenuBarMenuTemplate: (MenuItemConstructorOptions | MenuItem)[] = [
|
||||
{ role: process.platform === 'darwin' ? 'appMenu' : 'fileMenu' },
|
||||
{ role: 'viewMenu' },
|
||||
];
|
||||
|
||||
// Get Config options from capacitor.config
|
||||
const capacitorFileConfig: CapacitorElectronConfig = getCapacitorElectronConfig();
|
||||
|
||||
// Initialize our app. You can pass menu templates into the app here.
|
||||
const myCapacitorApp = new ElectronCapacitorApp(capacitorFileConfig, trayMenuTemplate, appMenuBarMenuTemplate);
|
||||
|
||||
// If deeplinking is enabled then we will set it up here.
|
||||
if (capacitorFileConfig.electron?.deepLinkingEnabled) {
|
||||
setupElectronDeepLinking(myCapacitorApp, {
|
||||
customProtocol: capacitorFileConfig.electron.deepLinkingCustomProtocol ?? 'mycapacitorapp',
|
||||
});
|
||||
}
|
||||
|
||||
// If we are in Dev mode, use the file watcher components.
|
||||
if (electronIsDev) {
|
||||
setupReloadWatcher(myCapacitorApp);
|
||||
}
|
||||
|
||||
// Run Application
|
||||
(async () => {
|
||||
try {
|
||||
// Wait for electron app to be ready first
|
||||
await app.whenReady();
|
||||
console.log('[Electron Main Process] App is ready');
|
||||
|
||||
// Initialize SQLite plugin and handlers BEFORE creating any windows
|
||||
console.log('[Electron Main Process] Initializing SQLite...');
|
||||
setupSQLiteHandlers();
|
||||
await initializeSQLite();
|
||||
console.log('[Electron Main Process] SQLite initialization complete');
|
||||
|
||||
// Security - Set Content-Security-Policy
|
||||
setupContentSecurityPolicy(myCapacitorApp.getCustomURLScheme());
|
||||
|
||||
// Initialize our app and create window
|
||||
console.log('[Electron Main Process] Starting app initialization...');
|
||||
await myCapacitorApp.init();
|
||||
console.log('[Electron Main Process] App initialization complete');
|
||||
|
||||
// Get the main window
|
||||
const mainWindow = myCapacitorApp.getMainWindow();
|
||||
if (!mainWindow) {
|
||||
throw new Error('Main window not available after app initialization');
|
||||
}
|
||||
|
||||
// Wait for window to be ready and loaded
|
||||
await new Promise<void>((resolve) => {
|
||||
const handleReady = () => {
|
||||
console.log('[Electron Main Process] Window ready to show');
|
||||
mainWindow.show();
|
||||
|
||||
// Wait for window to finish loading
|
||||
mainWindow.webContents.once('did-finish-load', () => {
|
||||
console.log('[Electron Main Process] Window finished loading');
|
||||
|
||||
// Send SQLite ready signal after window is fully loaded
|
||||
if (!mainWindow.isDestroyed()) {
|
||||
mainWindow.webContents.send('sqlite-ready');
|
||||
console.log('[Electron Main Process] Sent SQLite ready signal to renderer');
|
||||
} else {
|
||||
console.warn('[Electron Main Process] Window was destroyed before sending SQLite ready signal');
|
||||
}
|
||||
|
||||
resolve();
|
||||
});
|
||||
};
|
||||
|
||||
// Always use the event since isReadyToShow is not reliable
|
||||
mainWindow.once('ready-to-show', handleReady);
|
||||
});
|
||||
|
||||
// Check for updates if we are in a packaged app
|
||||
if (!electronIsDev) {
|
||||
console.log('[Electron Main Process] Checking for updates...');
|
||||
autoUpdater.checkForUpdatesAndNotify();
|
||||
}
|
||||
|
||||
// Handle window close
|
||||
mainWindow.on('closed', () => {
|
||||
console.log('[Electron Main Process] Main window closed');
|
||||
});
|
||||
|
||||
// Handle window close request
|
||||
mainWindow.on('close', (event) => {
|
||||
console.log('[Electron Main Process] Window close requested');
|
||||
if (mainWindow.webContents.isLoading()) {
|
||||
event.preventDefault();
|
||||
console.log('[Electron Main Process] Deferring window close due to loading state');
|
||||
mainWindow.webContents.once('did-finish-load', () => {
|
||||
mainWindow.close();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('[Electron Main Process] Fatal error during initialization:', error);
|
||||
app.quit();
|
||||
}
|
||||
})();
|
||||
|
||||
// Handle when all of our windows are close (platforms have their own expectations).
|
||||
app.on('window-all-closed', function () {
|
||||
// On OS X it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
// When the dock icon is clicked.
|
||||
app.on('activate', async function () {
|
||||
// On OS X it's common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (myCapacitorApp.getMainWindow().isDestroyed()) {
|
||||
await myCapacitorApp.init();
|
||||
}
|
||||
});
|
||||
|
||||
// Place all ipc or other electron api calls and custom functionality under this line
|
||||
303
electron/src/preload.ts
Normal file
@@ -0,0 +1,303 @@
|
||||
/**
|
||||
* Preload script for Electron
|
||||
* Sets up secure IPC communication between renderer and main process
|
||||
*
|
||||
* @author Matthew Raymer
|
||||
*/
|
||||
|
||||
import { contextBridge, ipcRenderer } from 'electron';
|
||||
|
||||
// Enhanced logger for preload script that forwards to main process
|
||||
const logger = {
|
||||
log: (...args: unknown[]) => {
|
||||
console.log('[Preload]', ...args);
|
||||
ipcRenderer.send('renderer-log', { level: 'log', args });
|
||||
},
|
||||
error: (...args: unknown[]) => {
|
||||
console.error('[Preload]', ...args);
|
||||
ipcRenderer.send('renderer-log', { level: 'error', args });
|
||||
},
|
||||
info: (...args: unknown[]) => {
|
||||
console.info('[Preload]', ...args);
|
||||
ipcRenderer.send('renderer-log', { level: 'info', args });
|
||||
},
|
||||
warn: (...args: unknown[]) => {
|
||||
console.warn('[Preload]', ...args);
|
||||
ipcRenderer.send('renderer-log', { level: 'warn', args });
|
||||
},
|
||||
debug: (...args: unknown[]) => {
|
||||
console.debug('[Preload]', ...args);
|
||||
ipcRenderer.send('renderer-log', { level: 'debug', args });
|
||||
},
|
||||
sqlite: {
|
||||
log: (operation: string, ...args: unknown[]) => {
|
||||
const message = ['[Preload][SQLite]', operation, ...args];
|
||||
console.log(...message);
|
||||
ipcRenderer.send('renderer-log', {
|
||||
level: 'log',
|
||||
args: message,
|
||||
source: 'sqlite',
|
||||
operation
|
||||
});
|
||||
},
|
||||
error: (operation: string, error: unknown) => {
|
||||
const message = ['[Preload][SQLite]', operation, 'failed:', error];
|
||||
console.error(...message);
|
||||
ipcRenderer.send('renderer-log', {
|
||||
level: 'error',
|
||||
args: message,
|
||||
source: 'sqlite',
|
||||
operation,
|
||||
error: error instanceof Error ? {
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
stack: error.stack
|
||||
} : error
|
||||
});
|
||||
},
|
||||
debug: (operation: string, ...args: unknown[]) => {
|
||||
const message = ['[Preload][SQLite]', operation, ...args];
|
||||
console.debug(...message);
|
||||
ipcRenderer.send('renderer-log', {
|
||||
level: 'debug',
|
||||
args: message,
|
||||
source: 'sqlite',
|
||||
operation
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Types for SQLite connection options
|
||||
interface SQLiteConnectionOptions {
|
||||
database: string;
|
||||
version?: number;
|
||||
readOnly?: boolean;
|
||||
readonly?: boolean; // Handle both cases
|
||||
encryption?: string;
|
||||
mode?: string;
|
||||
useNative?: boolean;
|
||||
[key: string]: unknown; // Allow other properties
|
||||
}
|
||||
|
||||
// Define valid channels for security
|
||||
const VALID_CHANNELS = {
|
||||
send: ['toMain'] as const,
|
||||
receive: ['fromMain', 'sqlite-ready', 'database-status'] as const,
|
||||
invoke: [
|
||||
'sqlite-is-available',
|
||||
'sqlite-echo',
|
||||
'sqlite-create-connection',
|
||||
'sqlite-execute',
|
||||
'sqlite-query',
|
||||
'sqlite-run',
|
||||
'sqlite-close-connection',
|
||||
'sqlite-open',
|
||||
'sqlite-close',
|
||||
'sqlite-is-db-open',
|
||||
'sqlite-status',
|
||||
'get-path',
|
||||
'get-base-path'
|
||||
] as const
|
||||
};
|
||||
|
||||
type ValidSendChannel = typeof VALID_CHANNELS.send[number];
|
||||
type ValidReceiveChannel = typeof VALID_CHANNELS.receive[number];
|
||||
type ValidInvokeChannel = typeof VALID_CHANNELS.invoke[number];
|
||||
|
||||
// Create a secure IPC bridge
|
||||
const createSecureIPCBridge = () => {
|
||||
return {
|
||||
send: (channel: string, data: unknown) => {
|
||||
if (VALID_CHANNELS.send.includes(channel as ValidSendChannel)) {
|
||||
logger.debug('IPC Send:', channel, data);
|
||||
ipcRenderer.send(channel, data);
|
||||
} else {
|
||||
logger.warn(`[Preload] Attempted to send on invalid channel: ${channel}`);
|
||||
}
|
||||
},
|
||||
|
||||
receive: (channel: string, func: (...args: unknown[]) => void) => {
|
||||
if (VALID_CHANNELS.receive.includes(channel as ValidReceiveChannel)) {
|
||||
logger.debug('IPC Receive:', channel);
|
||||
ipcRenderer.on(channel, (_event, ...args) => {
|
||||
logger.debug('IPC Received:', channel, args);
|
||||
func(...args);
|
||||
});
|
||||
} else {
|
||||
logger.warn(`[Preload] Attempted to receive on invalid channel: ${channel}`);
|
||||
}
|
||||
},
|
||||
|
||||
once: (channel: string, func: (...args: unknown[]) => void) => {
|
||||
if (VALID_CHANNELS.receive.includes(channel as ValidReceiveChannel)) {
|
||||
logger.debug('IPC Once:', channel);
|
||||
ipcRenderer.once(channel, (_event, ...args) => {
|
||||
logger.debug('IPC Received Once:', channel, args);
|
||||
func(...args);
|
||||
});
|
||||
} else {
|
||||
logger.warn(`[Preload] Attempted to receive once on invalid channel: ${channel}`);
|
||||
}
|
||||
},
|
||||
|
||||
invoke: async (channel: string, ...args: unknown[]) => {
|
||||
if (VALID_CHANNELS.invoke.includes(channel as ValidInvokeChannel)) {
|
||||
logger.debug('IPC Invoke:', channel, args);
|
||||
try {
|
||||
const result = await ipcRenderer.invoke(channel, ...args);
|
||||
logger.debug('IPC Invoke Result:', channel, result);
|
||||
return result;
|
||||
} catch (error) {
|
||||
logger.error('IPC Invoke Error:', channel, error);
|
||||
throw error;
|
||||
}
|
||||
} else {
|
||||
logger.warn(`[Preload] Attempted to invoke on invalid channel: ${channel}`);
|
||||
throw new Error(`Invalid channel: ${channel}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Create SQLite proxy with retry logic
|
||||
const createSQLiteProxy = () => {
|
||||
const MAX_RETRIES = 3;
|
||||
const RETRY_DELAY = 1000;
|
||||
|
||||
const withRetry = async <T>(operation: string, ...args: unknown[]): Promise<T> => {
|
||||
let lastError: Error | undefined;
|
||||
const operationId = `${operation}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||
const startTime = Date.now();
|
||||
|
||||
logger.sqlite.debug(operation, 'starting with args:', {
|
||||
operationId,
|
||||
args,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
logger.sqlite.debug(operation, `attempt ${attempt}/${MAX_RETRIES}`, {
|
||||
operationId,
|
||||
attempt,
|
||||
args,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
// Log the exact IPC call
|
||||
logger.sqlite.debug(operation, 'invoking IPC', {
|
||||
operationId,
|
||||
channel: `sqlite-${operation}`,
|
||||
args,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
const result = await ipcRenderer.invoke(`sqlite-${operation}`, ...args);
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
logger.sqlite.log(operation, 'success', {
|
||||
operationId,
|
||||
attempt,
|
||||
result,
|
||||
duration: `${duration}ms`,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
return result as T;
|
||||
} catch (error) {
|
||||
const duration = Date.now() - startTime;
|
||||
lastError = error instanceof Error ? error : new Error(String(error));
|
||||
|
||||
logger.sqlite.error(operation, {
|
||||
operationId,
|
||||
attempt,
|
||||
error: {
|
||||
name: lastError.name,
|
||||
message: lastError.message,
|
||||
stack: lastError.stack
|
||||
},
|
||||
args,
|
||||
duration: `${duration}ms`,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
if (attempt < MAX_RETRIES) {
|
||||
const backoffDelay = RETRY_DELAY * Math.pow(2, attempt - 1);
|
||||
logger.warn(`[Preload] SQLite ${operation} failed (attempt ${attempt}/${MAX_RETRIES}), retrying in ${backoffDelay}ms...`, {
|
||||
operationId,
|
||||
error: lastError,
|
||||
args,
|
||||
nextAttemptIn: `${backoffDelay}ms`,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
await new Promise(resolve => setTimeout(resolve, backoffDelay));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const finalError = new Error(
|
||||
`SQLite ${operation} failed after ${MAX_RETRIES} attempts: ${lastError?.message || "Unknown error"}`
|
||||
);
|
||||
|
||||
logger.error('[Preload] SQLite operation failed permanently:', {
|
||||
operation,
|
||||
operationId,
|
||||
error: {
|
||||
name: finalError.name,
|
||||
message: finalError.message,
|
||||
stack: finalError.stack,
|
||||
originalError: lastError
|
||||
},
|
||||
args,
|
||||
attempts: MAX_RETRIES,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
throw finalError;
|
||||
};
|
||||
|
||||
return {
|
||||
isAvailable: () => withRetry('is-available'),
|
||||
echo: (value: string) => withRetry('echo', { value }),
|
||||
createConnection: (options: SQLiteConnectionOptions) => withRetry('create-connection', options),
|
||||
closeConnection: (options: { database: string }) => withRetry('close-connection', options),
|
||||
query: (options: { statement: string; values?: unknown[] }) => withRetry('query', options),
|
||||
run: (options: { statement: string; values?: unknown[] }) => withRetry('run', options),
|
||||
execute: (options: { statements: { statement: string; values?: unknown[] }[] }) => withRetry('execute', options),
|
||||
getPlatform: () => Promise.resolve('electron')
|
||||
};
|
||||
};
|
||||
|
||||
try {
|
||||
// Expose the secure IPC bridge and SQLite proxy
|
||||
const electronAPI = {
|
||||
ipcRenderer: createSecureIPCBridge(),
|
||||
sqlite: createSQLiteProxy(),
|
||||
env: {
|
||||
platform: 'electron',
|
||||
isDev: process.env.NODE_ENV === 'development'
|
||||
}
|
||||
};
|
||||
|
||||
// Log the exposed API for debugging
|
||||
logger.debug('Exposing Electron API:', {
|
||||
hasIpcRenderer: !!electronAPI.ipcRenderer,
|
||||
hasSqlite: !!electronAPI.sqlite,
|
||||
sqliteMethods: Object.keys(electronAPI.sqlite),
|
||||
env: electronAPI.env
|
||||
});
|
||||
|
||||
contextBridge.exposeInMainWorld('electron', electronAPI);
|
||||
logger.info('[Preload] IPC bridge and SQLite proxy initialized successfully');
|
||||
} catch (error) {
|
||||
logger.error('[Preload] Failed to initialize IPC bridge:', error);
|
||||
}
|
||||
|
||||
// Log startup
|
||||
logger.log('[CapacitorSQLite] Preload script starting...');
|
||||
|
||||
// Handle window load
|
||||
window.addEventListener('load', () => {
|
||||
logger.log('[CapacitorSQLite] Preload script complete');
|
||||
});
|
||||
6
electron/src/rt/electron-plugins.js
Normal file
@@ -0,0 +1,6 @@
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
const CapacitorCommunitySqlite = require('../../../node_modules/@capacitor-community/sqlite/electron/dist/plugin.js');
|
||||
|
||||
module.exports = {
|
||||
CapacitorCommunitySqlite,
|
||||
}
|
||||
88
electron/src/rt/electron-rt.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import { randomBytes } from 'crypto';
|
||||
import { ipcRenderer, contextBridge } from 'electron';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const plugins = require('./electron-plugins');
|
||||
|
||||
const randomId = (length = 5) => randomBytes(length).toString('hex');
|
||||
|
||||
const contextApi: {
|
||||
[plugin: string]: { [functionName: string]: () => Promise<any> };
|
||||
} = {};
|
||||
|
||||
Object.keys(plugins).forEach((pluginKey) => {
|
||||
Object.keys(plugins[pluginKey])
|
||||
.filter((className) => className !== 'default')
|
||||
.forEach((classKey) => {
|
||||
const functionList = Object.getOwnPropertyNames(plugins[pluginKey][classKey].prototype).filter(
|
||||
(v) => v !== 'constructor'
|
||||
);
|
||||
|
||||
if (!contextApi[classKey]) {
|
||||
contextApi[classKey] = {};
|
||||
}
|
||||
|
||||
functionList.forEach((functionName) => {
|
||||
if (!contextApi[classKey][functionName]) {
|
||||
contextApi[classKey][functionName] = (...args) => ipcRenderer.invoke(`${classKey}-${functionName}`, ...args);
|
||||
}
|
||||
});
|
||||
|
||||
// Events
|
||||
if (plugins[pluginKey][classKey].prototype instanceof EventEmitter) {
|
||||
const listeners: { [key: string]: { type: string; listener: (...args: any[]) => void } } = {};
|
||||
const listenersOfTypeExist = (type) =>
|
||||
!!Object.values(listeners).find((listenerObj) => listenerObj.type === type);
|
||||
|
||||
Object.assign(contextApi[classKey], {
|
||||
addListener(type: string, callback: (...args) => void) {
|
||||
const id = randomId();
|
||||
|
||||
// Deduplicate events
|
||||
if (!listenersOfTypeExist(type)) {
|
||||
ipcRenderer.send(`event-add-${classKey}`, type);
|
||||
}
|
||||
|
||||
const eventHandler = (_, ...args) => callback(...args);
|
||||
|
||||
ipcRenderer.addListener(`event-${classKey}-${type}`, eventHandler);
|
||||
listeners[id] = { type, listener: eventHandler };
|
||||
|
||||
return id;
|
||||
},
|
||||
removeListener(id: string) {
|
||||
if (!listeners[id]) {
|
||||
throw new Error('Invalid id');
|
||||
}
|
||||
|
||||
const { type, listener } = listeners[id];
|
||||
|
||||
ipcRenderer.removeListener(`event-${classKey}-${type}`, listener);
|
||||
|
||||
delete listeners[id];
|
||||
|
||||
if (!listenersOfTypeExist(type)) {
|
||||
ipcRenderer.send(`event-remove-${classKey}-${type}`);
|
||||
}
|
||||
},
|
||||
removeAllListeners(type: string) {
|
||||
Object.entries(listeners).forEach(([id, listenerObj]) => {
|
||||
if (!type || listenerObj.type === type) {
|
||||
ipcRenderer.removeListener(`event-${classKey}-${listenerObj.type}`, listenerObj.listener);
|
||||
ipcRenderer.send(`event-remove-${classKey}-${listenerObj.type}`);
|
||||
delete listeners[id];
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
contextBridge.exposeInMainWorld('CapacitorCustomPlatform', {
|
||||
name: 'electron',
|
||||
plugins: contextApi,
|
||||
});
|
||||
////////////////////////////////////////////////////////
|
||||
188
electron/src/rt/logger.ts
Normal file
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* Enhanced logging system for TimeSafari Electron
|
||||
* Provides structured logging with proper levels and formatting
|
||||
* Supports both console and file output with different verbosity levels
|
||||
*
|
||||
* @author Matthew Raymer
|
||||
*/
|
||||
|
||||
import { app, ipcMain } from 'electron';
|
||||
import winston from 'winston';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import fs from 'fs';
|
||||
|
||||
// Extend Winston Logger type with our custom loggers
|
||||
declare module 'winston' {
|
||||
interface Logger {
|
||||
sqlite: {
|
||||
debug: (message: string, ...args: unknown[]) => void;
|
||||
info: (message: string, ...args: unknown[]) => void;
|
||||
warn: (message: string, ...args: unknown[]) => void;
|
||||
error: (message: string, ...args: unknown[]) => void;
|
||||
};
|
||||
migration: {
|
||||
debug: (message: string, ...args: unknown[]) => void;
|
||||
info: (message: string, ...args: unknown[]) => void;
|
||||
warn: (message: string, ...args: unknown[]) => void;
|
||||
error: (message: string, ...args: unknown[]) => void;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Create logs directory if it doesn't exist
|
||||
const logsDir = path.join(app.getPath('userData'), 'logs');
|
||||
if (!fs.existsSync(logsDir)) {
|
||||
fs.mkdirSync(logsDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Custom format for console output with migration filtering
|
||||
const consoleFormat = winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.colorize(),
|
||||
winston.format.printf(({ level, message, timestamp, ...metadata }) => {
|
||||
// Skip migration logs unless DEBUG_MIGRATIONS is set
|
||||
if (level === 'info' &&
|
||||
typeof message === 'string' &&
|
||||
message.includes('[Migration]') &&
|
||||
!process.env.DEBUG_MIGRATIONS) {
|
||||
return '';
|
||||
}
|
||||
|
||||
let msg = `${timestamp} [${level}] ${message}`;
|
||||
if (Object.keys(metadata).length > 0) {
|
||||
msg += ` ${JSON.stringify(metadata, null, 2)}`;
|
||||
}
|
||||
return msg;
|
||||
})
|
||||
);
|
||||
|
||||
// Custom format for file output
|
||||
const fileFormat = winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.json()
|
||||
);
|
||||
|
||||
// Create logger instance
|
||||
const logger = winston.createLogger({
|
||||
level: process.env.NODE_ENV === 'development' ? 'debug' : 'info',
|
||||
format: fileFormat,
|
||||
defaultMeta: { service: 'timesafari-electron' },
|
||||
transports: [
|
||||
// Console transport with custom format and migration filtering
|
||||
new winston.transports.Console({
|
||||
format: consoleFormat,
|
||||
level: process.env.NODE_ENV === 'development' ? 'debug' : 'info',
|
||||
silent: false // Ensure we can still see non-migration logs
|
||||
}),
|
||||
// File transport for all logs
|
||||
new winston.transports.File({
|
||||
filename: path.join(logsDir, 'error.log'),
|
||||
level: 'error',
|
||||
maxsize: 5242880, // 5MB
|
||||
maxFiles: 5
|
||||
}),
|
||||
// File transport for all logs including debug
|
||||
new winston.transports.File({
|
||||
filename: path.join(logsDir, 'combined.log'),
|
||||
maxsize: 5242880, // 5MB
|
||||
maxFiles: 5
|
||||
})
|
||||
]
|
||||
}) as winston.Logger & {
|
||||
sqlite: {
|
||||
debug: (message: string, ...args: unknown[]) => void;
|
||||
info: (message: string, ...args: unknown[]) => void;
|
||||
warn: (message: string, ...args: unknown[]) => void;
|
||||
error: (message: string, ...args: unknown[]) => void;
|
||||
};
|
||||
migration: {
|
||||
debug: (message: string, ...args: unknown[]) => void;
|
||||
info: (message: string, ...args: unknown[]) => void;
|
||||
warn: (message: string, ...args: unknown[]) => void;
|
||||
error: (message: string, ...args: unknown[]) => void;
|
||||
};
|
||||
};
|
||||
|
||||
// Add SQLite specific logger
|
||||
logger.sqlite = {
|
||||
debug: (message: string, ...args: unknown[]) => {
|
||||
logger.debug(`[SQLite] ${message}`, ...args);
|
||||
},
|
||||
info: (message: string, ...args: unknown[]) => {
|
||||
logger.info(`[SQLite] ${message}`, ...args);
|
||||
},
|
||||
warn: (message: string, ...args: unknown[]) => {
|
||||
logger.warn(`[SQLite] ${message}`, ...args);
|
||||
},
|
||||
error: (message: string, ...args: unknown[]) => {
|
||||
logger.error(`[SQLite] ${message}`, ...args);
|
||||
}
|
||||
};
|
||||
|
||||
// Add migration specific logger with debug filtering
|
||||
logger.migration = {
|
||||
debug: (message: string, ...args: unknown[]) => {
|
||||
if (process.env.DEBUG_MIGRATIONS) {
|
||||
//logger.debug(`[Migration] ${message}`, ...args);
|
||||
}
|
||||
},
|
||||
info: (message: string, ...args: unknown[]) => {
|
||||
// Always log to file, but only log to console if DEBUG_MIGRATIONS is set
|
||||
if (process.env.DEBUG_MIGRATIONS) {
|
||||
//logger.info(`[Migration] ${message}`, ...args);
|
||||
} else {
|
||||
// Use a separate transport for migration logs to file only
|
||||
const metadata = args[0] as Record<string, unknown>;
|
||||
logger.write({
|
||||
level: 'info',
|
||||
message: `[Migration] ${message}`,
|
||||
...(metadata || {})
|
||||
});
|
||||
}
|
||||
},
|
||||
warn: (message: string, ...args: unknown[]) => {
|
||||
// Always log warnings to both console and file
|
||||
//logger.warn(`[Migration] ${message}`, ...args);
|
||||
},
|
||||
error: (message: string, ...args: unknown[]) => {
|
||||
// Always log errors to both console and file
|
||||
//logger.error(`[Migration] ${message}`, ...args);
|
||||
}
|
||||
};
|
||||
|
||||
// Add renderer log handler
|
||||
ipcMain.on('renderer-log', (_event, { level, args, source, operation, error }) => {
|
||||
const message = args.map((arg: unknown) =>
|
||||
typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
|
||||
).join(' ');
|
||||
|
||||
const meta = {
|
||||
source: source || 'renderer',
|
||||
...(operation && { operation }),
|
||||
...(error && { error })
|
||||
};
|
||||
|
||||
switch (level) {
|
||||
case 'error':
|
||||
logger.error(message, meta);
|
||||
break;
|
||||
case 'warn':
|
||||
logger.warn(message, meta);
|
||||
break;
|
||||
case 'info':
|
||||
logger.info(message, meta);
|
||||
break;
|
||||
case 'debug':
|
||||
logger.debug(message, meta);
|
||||
break;
|
||||
default:
|
||||
logger.log(level, message, meta);
|
||||
}
|
||||
});
|
||||
|
||||
// Export logger instance
|
||||
export { logger };
|
||||
|
||||
// Export a function to get the logs directory
|
||||
export const getLogsDirectory = () => logsDir;
|
||||
14
electron/src/rt/sqlite-error.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Custom error class for SQLite operations
|
||||
* Provides additional context and error tracking for SQLite operations
|
||||
*/
|
||||
export class SQLiteError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public operation: string,
|
||||
public cause?: unknown
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'SQLiteError';
|
||||
}
|
||||
}
|
||||
1147
electron/src/rt/sqlite-init.ts
Normal file
1261
electron/src/rt/sqlite-migrations.ts
Normal file
442
electron/src/setup.ts
Normal file
@@ -0,0 +1,442 @@
|
||||
import type { CapacitorElectronConfig } from '@capacitor-community/electron';
|
||||
import {
|
||||
CapElectronEventEmitter,
|
||||
CapacitorSplashScreen,
|
||||
setupCapacitorElectronPlugins,
|
||||
} from '@capacitor-community/electron';
|
||||
import chokidar from 'chokidar';
|
||||
import type { MenuItemConstructorOptions } from 'electron';
|
||||
import { app, BrowserWindow, Menu, MenuItem, nativeImage, Tray, session } from 'electron';
|
||||
import electronIsDev from 'electron-is-dev';
|
||||
import electronServe from 'electron-serve';
|
||||
import windowStateKeeper from 'electron-window-state';
|
||||
import { join } from 'path';
|
||||
|
||||
/**
|
||||
* Reload watcher configuration and state management
|
||||
* Prevents infinite reload loops and implements rate limiting
|
||||
* Also prevents reloads during critical database operations
|
||||
*
|
||||
* @author Matthew Raymer
|
||||
*/
|
||||
const RELOAD_CONFIG = {
|
||||
DEBOUNCE_MS: 1500,
|
||||
COOLDOWN_MS: 5000,
|
||||
MAX_RELOADS_PER_MINUTE: 10,
|
||||
MAX_RELOADS_PER_SESSION: 100,
|
||||
DATABASE_OPERATION_TIMEOUT_MS: 10000 // 10 second timeout for database operations
|
||||
};
|
||||
|
||||
// Track database operation state
|
||||
let isDatabaseOperationInProgress = false;
|
||||
let lastDatabaseOperationTime = 0;
|
||||
|
||||
/**
|
||||
* Checks if a database operation is in progress or recently completed
|
||||
* @returns {boolean} Whether a database operation is active
|
||||
*/
|
||||
const isDatabaseOperationActive = (): boolean => {
|
||||
const now = Date.now();
|
||||
return isDatabaseOperationInProgress ||
|
||||
(now - lastDatabaseOperationTime < RELOAD_CONFIG.DATABASE_OPERATION_TIMEOUT_MS);
|
||||
};
|
||||
|
||||
/**
|
||||
* Marks the start of a database operation
|
||||
*/
|
||||
export const startDatabaseOperation = (): void => {
|
||||
isDatabaseOperationInProgress = true;
|
||||
lastDatabaseOperationTime = Date.now();
|
||||
};
|
||||
|
||||
/**
|
||||
* Marks the end of a database operation
|
||||
*/
|
||||
export const endDatabaseOperation = (): void => {
|
||||
isDatabaseOperationInProgress = false;
|
||||
lastDatabaseOperationTime = Date.now();
|
||||
};
|
||||
|
||||
const reloadWatcher = {
|
||||
debouncer: null as NodeJS.Timeout | null,
|
||||
ready: false,
|
||||
watcher: null as chokidar.FSWatcher | null,
|
||||
lastReloadTime: 0,
|
||||
reloadCount: 0,
|
||||
sessionReloadCount: 0,
|
||||
resetTimeout: null as NodeJS.Timeout | null,
|
||||
isReloading: false
|
||||
};
|
||||
|
||||
/**
|
||||
* Resets the reload counter after one minute
|
||||
*/
|
||||
const resetReloadCounter = () => {
|
||||
reloadWatcher.reloadCount = 0;
|
||||
reloadWatcher.resetTimeout = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if a reload is allowed based on rate limits, cooldown, and database state
|
||||
* @returns {boolean} Whether a reload is allowed
|
||||
*/
|
||||
const canReload = (): boolean => {
|
||||
const now = Date.now();
|
||||
|
||||
// Check if database operation is active
|
||||
if (isDatabaseOperationActive()) {
|
||||
console.warn('[Reload Watcher] Skipping reload - database operation in progress');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check cooldown period
|
||||
if (now - reloadWatcher.lastReloadTime < RELOAD_CONFIG.COOLDOWN_MS) {
|
||||
console.warn('[Reload Watcher] Skipping reload - cooldown period active');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check per-minute limit
|
||||
if (reloadWatcher.reloadCount >= RELOAD_CONFIG.MAX_RELOADS_PER_MINUTE) {
|
||||
console.warn('[Reload Watcher] Skipping reload - maximum reloads per minute reached');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check session limit
|
||||
if (reloadWatcher.sessionReloadCount >= RELOAD_CONFIG.MAX_RELOADS_PER_SESSION) {
|
||||
console.error('[Reload Watcher] Maximum reloads per session reached. Please restart the application.');
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Cleans up the current watcher instance
|
||||
*/
|
||||
const cleanupWatcher = () => {
|
||||
if (reloadWatcher.watcher) {
|
||||
reloadWatcher.watcher.close();
|
||||
reloadWatcher.watcher = null;
|
||||
}
|
||||
if (reloadWatcher.debouncer) {
|
||||
clearTimeout(reloadWatcher.debouncer);
|
||||
reloadWatcher.debouncer = null;
|
||||
}
|
||||
if (reloadWatcher.resetTimeout) {
|
||||
clearTimeout(reloadWatcher.resetTimeout);
|
||||
reloadWatcher.resetTimeout = null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets up the file watcher for development mode reloading
|
||||
* Implements rate limiting and prevents infinite reload loops
|
||||
*
|
||||
* @param electronCapacitorApp - The Electron Capacitor app instance
|
||||
*/
|
||||
export function setupReloadWatcher(electronCapacitorApp: ElectronCapacitorApp): void {
|
||||
// Cleanup any existing watcher
|
||||
cleanupWatcher();
|
||||
|
||||
// Reset state
|
||||
reloadWatcher.ready = false;
|
||||
reloadWatcher.isReloading = false;
|
||||
|
||||
reloadWatcher.watcher = chokidar
|
||||
.watch(join(app.getAppPath(), 'app'), {
|
||||
ignored: /[/\\]\./,
|
||||
persistent: true,
|
||||
awaitWriteFinish: {
|
||||
stabilityThreshold: 1000,
|
||||
pollInterval: 100
|
||||
}
|
||||
})
|
||||
.on('ready', () => {
|
||||
reloadWatcher.ready = true;
|
||||
console.log('[Reload Watcher] Ready to watch for changes');
|
||||
})
|
||||
.on('all', (_event, _path) => {
|
||||
if (!reloadWatcher.ready || reloadWatcher.isReloading) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear existing debouncer
|
||||
if (reloadWatcher.debouncer) {
|
||||
clearTimeout(reloadWatcher.debouncer);
|
||||
}
|
||||
|
||||
// Set up new debouncer
|
||||
reloadWatcher.debouncer = setTimeout(async () => {
|
||||
if (!canReload()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
reloadWatcher.isReloading = true;
|
||||
|
||||
// Update reload counters
|
||||
reloadWatcher.lastReloadTime = Date.now();
|
||||
reloadWatcher.reloadCount++;
|
||||
reloadWatcher.sessionReloadCount++;
|
||||
|
||||
// Set up reset timeout for per-minute counter
|
||||
if (!reloadWatcher.resetTimeout) {
|
||||
reloadWatcher.resetTimeout = setTimeout(resetReloadCounter, 60000);
|
||||
}
|
||||
|
||||
// Perform reload
|
||||
console.log('[Reload Watcher] Reloading window...');
|
||||
await electronCapacitorApp.getMainWindow().webContents.reload();
|
||||
|
||||
// Reset state after reload
|
||||
reloadWatcher.ready = false;
|
||||
reloadWatcher.isReloading = false;
|
||||
|
||||
// Re-setup watcher after successful reload
|
||||
setupReloadWatcher(electronCapacitorApp);
|
||||
|
||||
} catch (error) {
|
||||
console.error('[Reload Watcher] Error during reload:', error);
|
||||
reloadWatcher.isReloading = false;
|
||||
reloadWatcher.ready = true;
|
||||
}
|
||||
}, RELOAD_CONFIG.DEBOUNCE_MS);
|
||||
})
|
||||
.on('error', (error) => {
|
||||
console.error('[Reload Watcher] Error:', error);
|
||||
cleanupWatcher();
|
||||
});
|
||||
}
|
||||
|
||||
// Define our class to manage our app.
|
||||
export class ElectronCapacitorApp {
|
||||
private MainWindow: BrowserWindow | null = null;
|
||||
private SplashScreen: CapacitorSplashScreen | null = null;
|
||||
private TrayIcon: Tray | null = null;
|
||||
private CapacitorFileConfig: CapacitorElectronConfig;
|
||||
private TrayMenuTemplate: (MenuItem | MenuItemConstructorOptions)[] = [
|
||||
new MenuItem({ label: 'Quit App', role: 'quit' }),
|
||||
];
|
||||
private AppMenuBarMenuTemplate: (MenuItem | MenuItemConstructorOptions)[] = [
|
||||
{ role: process.platform === 'darwin' ? 'appMenu' : 'fileMenu' },
|
||||
{ role: 'viewMenu' },
|
||||
];
|
||||
private mainWindowState;
|
||||
private loadWebApp;
|
||||
private customScheme: string;
|
||||
|
||||
constructor(
|
||||
capacitorFileConfig: CapacitorElectronConfig,
|
||||
trayMenuTemplate?: (MenuItemConstructorOptions | MenuItem)[],
|
||||
appMenuBarMenuTemplate?: (MenuItemConstructorOptions | MenuItem)[]
|
||||
) {
|
||||
this.CapacitorFileConfig = capacitorFileConfig;
|
||||
|
||||
this.customScheme = this.CapacitorFileConfig.electron?.customUrlScheme ?? 'capacitor-electron';
|
||||
|
||||
if (trayMenuTemplate) {
|
||||
this.TrayMenuTemplate = trayMenuTemplate;
|
||||
}
|
||||
|
||||
if (appMenuBarMenuTemplate) {
|
||||
this.AppMenuBarMenuTemplate = appMenuBarMenuTemplate;
|
||||
}
|
||||
|
||||
// Setup our web app loader, this lets us load apps like react, vue, and angular without changing their build chains.
|
||||
this.loadWebApp = electronServe({
|
||||
directory: join(app.getAppPath(), 'app'),
|
||||
scheme: this.customScheme,
|
||||
});
|
||||
}
|
||||
|
||||
// Helper function to load in the app.
|
||||
private async loadMainWindow(thisRef: any) {
|
||||
await thisRef.loadWebApp(thisRef.MainWindow);
|
||||
}
|
||||
|
||||
// Expose the mainWindow ref for use outside of the class.
|
||||
getMainWindow(): BrowserWindow {
|
||||
return this.MainWindow;
|
||||
}
|
||||
|
||||
getCustomURLScheme(): string {
|
||||
return this.customScheme;
|
||||
}
|
||||
|
||||
async init(): Promise<void> {
|
||||
const icon = nativeImage.createFromPath(
|
||||
join(app.getAppPath(), 'assets', process.platform === 'win32' ? 'appIcon.ico' : 'appIcon.png')
|
||||
);
|
||||
this.mainWindowState = windowStateKeeper({
|
||||
defaultWidth: 1000,
|
||||
defaultHeight: 800,
|
||||
});
|
||||
|
||||
// Setup preload script path based on environment
|
||||
const preloadPath = app.isPackaged
|
||||
? join(process.resourcesPath, 'preload.js')
|
||||
: join(__dirname, 'preload.js');
|
||||
|
||||
console.log('[Electron Main Process] Preload path:', preloadPath);
|
||||
console.log('[Electron Main Process] Preload exists:', require('fs').existsSync(preloadPath));
|
||||
|
||||
this.MainWindow = new BrowserWindow({
|
||||
icon,
|
||||
show: false,
|
||||
x: this.mainWindowState.x,
|
||||
y: this.mainWindowState.y,
|
||||
width: this.mainWindowState.width,
|
||||
height: this.mainWindowState.height,
|
||||
webPreferences: {
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
sandbox: false,
|
||||
preload: preloadPath,
|
||||
webSecurity: true,
|
||||
allowRunningInsecureContent: false,
|
||||
},
|
||||
});
|
||||
this.mainWindowState.manage(this.MainWindow);
|
||||
|
||||
if (this.CapacitorFileConfig.backgroundColor) {
|
||||
this.MainWindow.setBackgroundColor(this.CapacitorFileConfig.electron.backgroundColor);
|
||||
}
|
||||
|
||||
// If we close the main window with the splashscreen enabled we need to destory the ref.
|
||||
this.MainWindow.on('closed', () => {
|
||||
if (this.SplashScreen?.getSplashWindow() && !this.SplashScreen.getSplashWindow().isDestroyed()) {
|
||||
this.SplashScreen.getSplashWindow().close();
|
||||
}
|
||||
});
|
||||
|
||||
// When the tray icon is enabled, setup the options.
|
||||
if (this.CapacitorFileConfig.electron?.trayIconAndMenuEnabled) {
|
||||
this.TrayIcon = new Tray(icon);
|
||||
this.TrayIcon.on('double-click', () => {
|
||||
if (this.MainWindow) {
|
||||
if (this.MainWindow.isVisible()) {
|
||||
this.MainWindow.hide();
|
||||
} else {
|
||||
this.MainWindow.show();
|
||||
this.MainWindow.focus();
|
||||
}
|
||||
}
|
||||
});
|
||||
this.TrayIcon.on('click', () => {
|
||||
if (this.MainWindow) {
|
||||
if (this.MainWindow.isVisible()) {
|
||||
this.MainWindow.hide();
|
||||
} else {
|
||||
this.MainWindow.show();
|
||||
this.MainWindow.focus();
|
||||
}
|
||||
}
|
||||
});
|
||||
this.TrayIcon.setToolTip(app.getName());
|
||||
this.TrayIcon.setContextMenu(Menu.buildFromTemplate(this.TrayMenuTemplate));
|
||||
}
|
||||
|
||||
// Setup the main manu bar at the top of our window.
|
||||
Menu.setApplicationMenu(Menu.buildFromTemplate(this.AppMenuBarMenuTemplate));
|
||||
|
||||
// If the splashscreen is enabled, show it first while the main window loads then switch it out for the main window, or just load the main window from the start.
|
||||
if (this.CapacitorFileConfig.electron?.splashScreenEnabled) {
|
||||
this.SplashScreen = new CapacitorSplashScreen({
|
||||
imageFilePath: join(
|
||||
app.getAppPath(),
|
||||
'assets',
|
||||
this.CapacitorFileConfig.electron?.splashScreenImageName ?? 'splash.png'
|
||||
),
|
||||
windowWidth: 400,
|
||||
windowHeight: 400,
|
||||
});
|
||||
this.SplashScreen.init(this.loadMainWindow, this);
|
||||
} else {
|
||||
this.loadMainWindow(this);
|
||||
}
|
||||
|
||||
// Security
|
||||
this.MainWindow.webContents.setWindowOpenHandler((details) => {
|
||||
if (!details.url.includes(this.customScheme)) {
|
||||
return { action: 'deny' };
|
||||
} else {
|
||||
return { action: 'allow' };
|
||||
}
|
||||
});
|
||||
this.MainWindow.webContents.on('will-navigate', (event, _newURL) => {
|
||||
if (!this.MainWindow.webContents.getURL().includes(this.customScheme)) {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
// Link electron plugins into the system.
|
||||
setupCapacitorElectronPlugins();
|
||||
|
||||
// When the web app is loaded we hide the splashscreen if needed and show the mainwindow.
|
||||
this.MainWindow.webContents.on('dom-ready', () => {
|
||||
if (this.CapacitorFileConfig.electron?.splashScreenEnabled) {
|
||||
this.SplashScreen.getSplashWindow().hide();
|
||||
}
|
||||
if (!this.CapacitorFileConfig.electron?.hideMainWindowOnLaunch) {
|
||||
this.MainWindow.show();
|
||||
}
|
||||
|
||||
// Re-register SQLite handlers after reload
|
||||
if (electronIsDev) {
|
||||
console.log('[Electron Main Process] Re-registering SQLite handlers after reload');
|
||||
const { setupSQLiteHandlers } = require('./rt/sqlite-init');
|
||||
setupSQLiteHandlers();
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
if (electronIsDev) {
|
||||
this.MainWindow.webContents.openDevTools();
|
||||
}
|
||||
CapElectronEventEmitter.emit('CAPELECTRON_DeeplinkListenerInitialized', '');
|
||||
}, 400);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Set a CSP up for our application based on the custom scheme
|
||||
export function setupContentSecurityPolicy(customScheme: string): void {
|
||||
session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
|
||||
callback({
|
||||
responseHeaders: {
|
||||
...details.responseHeaders,
|
||||
'Content-Security-Policy': [
|
||||
// Base CSP for both dev and prod
|
||||
`default-src ${customScheme}://*;`,
|
||||
// Script sources
|
||||
`script-src ${customScheme}://* 'self' 'unsafe-inline'${electronIsDev ? " 'unsafe-eval'" : ''};`,
|
||||
// Style sources
|
||||
`style-src ${customScheme}://* 'self' 'unsafe-inline' https://fonts.googleapis.com;`,
|
||||
// Font sources
|
||||
`font-src ${customScheme}://* 'self' https://fonts.gstatic.com;`,
|
||||
// Image sources
|
||||
`img-src ${customScheme}://* 'self' data: https:;`,
|
||||
// Connect sources (for API calls)
|
||||
`connect-src ${customScheme}://* 'self' https:;`,
|
||||
// Worker sources
|
||||
`worker-src ${customScheme}://* 'self' blob:;`,
|
||||
// Frame sources
|
||||
`frame-src ${customScheme}://* 'self';`,
|
||||
// Media sources
|
||||
`media-src ${customScheme}://* 'self' data:;`,
|
||||
// Object sources
|
||||
`object-src 'none';`,
|
||||
// Base URI
|
||||
`base-uri 'self';`,
|
||||
// Form action
|
||||
`form-action ${customScheme}://* 'self';`,
|
||||
// Frame ancestors
|
||||
`frame-ancestors 'none';`,
|
||||
// Upgrade insecure requests
|
||||
'upgrade-insecure-requests;',
|
||||
// Block mixed content
|
||||
'block-all-mixed-content;'
|
||||
].join(' ')
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
18
electron/tsconfig.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compileOnSave": true,
|
||||
"include": ["./src/**/*", "./capacitor.config.ts", "./capacitor.config.js"],
|
||||
"compilerOptions": {
|
||||
"outDir": "./build",
|
||||
"importHelpers": true,
|
||||
"target": "ES2020",
|
||||
"module": "CommonJS",
|
||||
"moduleResolution": "node",
|
||||
"esModuleInterop": true,
|
||||
"typeRoots": ["./node_modules/@types"],
|
||||
"allowJs": true,
|
||||
"rootDir": ".",
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true
|
||||
}
|
||||
}
|
||||
|
||||
155
experiment.sh
Executable file
@@ -0,0 +1,155 @@
|
||||
#!/bin/bash
|
||||
# experiment.sh
|
||||
# Author: Matthew Raymer
|
||||
# Description: Build script for TimeSafari Electron application
|
||||
# This script handles the complete build process for the TimeSafari Electron app,
|
||||
# including web asset compilation and Capacitor sync.
|
||||
#
|
||||
# Build Process:
|
||||
# 1. Environment setup and dependency checks
|
||||
# 2. Web asset compilation (Vite)
|
||||
# 3. Capacitor sync
|
||||
# 4. Electron start
|
||||
#
|
||||
# Dependencies:
|
||||
# - Node.js and npm
|
||||
# - TypeScript
|
||||
# - Vite
|
||||
# - @capacitor-community/electron
|
||||
#
|
||||
# Usage: ./experiment.sh
|
||||
#
|
||||
# Exit Codes:
|
||||
# 1 - Required command not found
|
||||
# 2 - TypeScript installation failed
|
||||
# 3 - Build process failed
|
||||
# 4 - Capacitor sync failed
|
||||
# 5 - Electron start failed
|
||||
|
||||
# Exit on any error
|
||||
set -e
|
||||
|
||||
# ANSI color codes for better output formatting
|
||||
readonly RED='\033[0;31m'
|
||||
readonly GREEN='\033[0;32m'
|
||||
readonly YELLOW='\033[1;33m'
|
||||
readonly BLUE='\033[0;34m'
|
||||
readonly NC='\033[0m' # No Color
|
||||
|
||||
# Logging functions
|
||||
log_info() {
|
||||
echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')] [INFO]${NC} $1"
|
||||
}
|
||||
|
||||
log_success() {
|
||||
echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] [SUCCESS]${NC} $1"
|
||||
}
|
||||
|
||||
log_warn() {
|
||||
echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] [WARN]${NC} $1"
|
||||
}
|
||||
|
||||
log_error() {
|
||||
echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] [ERROR]${NC} $1"
|
||||
}
|
||||
|
||||
# Function to check if a command exists
|
||||
check_command() {
|
||||
if ! command -v "$1" &> /dev/null; then
|
||||
log_error "$1 is required but not installed."
|
||||
exit 1
|
||||
fi
|
||||
log_info "Found $1: $(command -v "$1")"
|
||||
}
|
||||
|
||||
# Function to measure and log execution time
|
||||
measure_time() {
|
||||
local start_time=$(date +%s)
|
||||
"$@"
|
||||
local end_time=$(date +%s)
|
||||
local duration=$((end_time - start_time))
|
||||
log_success "Completed in ${duration} seconds"
|
||||
}
|
||||
|
||||
# Print build header
|
||||
echo -e "\n${BLUE}=== TimeSafari Electron Build Process ===${NC}\n"
|
||||
log_info "Starting build process at $(date)"
|
||||
|
||||
# Check required commands
|
||||
log_info "Checking required dependencies..."
|
||||
check_command node
|
||||
check_command npm
|
||||
check_command git
|
||||
|
||||
# Create application data directory
|
||||
log_info "Setting up application directories..."
|
||||
mkdir -p ~/.local/share/TimeSafari/timesafari
|
||||
|
||||
# Clean up previous builds
|
||||
log_info "Cleaning previous builds..."
|
||||
rm -rf dist* || log_warn "No previous builds to clean"
|
||||
|
||||
# Set environment variables for the build
|
||||
log_info "Configuring build environment..."
|
||||
export VITE_PLATFORM=electron
|
||||
export VITE_PWA_ENABLED=false
|
||||
export VITE_DISABLE_PWA=true
|
||||
export DEBUG_MIGRATIONS=0
|
||||
|
||||
# Ensure TypeScript is installed
|
||||
log_info "Verifying TypeScript installation..."
|
||||
if [ ! -f "./node_modules/.bin/tsc" ]; then
|
||||
log_info "Installing TypeScript..."
|
||||
if ! npm install --save-dev typescript@~5.2.2; then
|
||||
log_error "TypeScript installation failed!"
|
||||
exit 2
|
||||
fi
|
||||
# Verify installation
|
||||
if [ ! -f "./node_modules/.bin/tsc" ]; then
|
||||
log_error "TypeScript installation verification failed!"
|
||||
exit 2
|
||||
fi
|
||||
log_success "TypeScript installed successfully"
|
||||
else
|
||||
log_info "TypeScript already installed"
|
||||
fi
|
||||
|
||||
# Get git hash for versioning
|
||||
GIT_HASH=$(git log -1 --pretty=format:%h)
|
||||
log_info "Using git hash: ${GIT_HASH}"
|
||||
|
||||
# Build web assets
|
||||
log_info "Building web assets with Vite..."
|
||||
if ! measure_time env VITE_GIT_HASH="$GIT_HASH" npx vite build --config vite.config.app.electron.mts --mode electron; then
|
||||
log_error "Web asset build failed!"
|
||||
exit 3
|
||||
fi
|
||||
|
||||
# Sync with Capacitor
|
||||
log_info "Syncing with Capacitor..."
|
||||
if ! measure_time npx cap sync electron; then
|
||||
log_error "Capacitor sync failed!"
|
||||
exit 4
|
||||
fi
|
||||
|
||||
# Restore capacitor config
|
||||
log_info "Restoring capacitor config..."
|
||||
if ! git checkout electron/capacitor.config.json; then
|
||||
log_error "Failed to restore capacitor config!"
|
||||
exit 4
|
||||
fi
|
||||
|
||||
# Start Electron
|
||||
log_info "Starting Electron..."
|
||||
cd electron/
|
||||
if ! measure_time npm run electron:start; then
|
||||
log_error "Electron start failed!"
|
||||
exit 5
|
||||
fi
|
||||
|
||||
# Print build summary
|
||||
log_success "Build and start completed successfully!"
|
||||
echo -e "\n${GREEN}=== End of Build Process ===${NC}\n"
|
||||
|
||||
# Exit with success
|
||||
exit 0
|
||||
13
ios/.gitignore
vendored
@@ -11,16 +11,3 @@ capacitor-cordova-ios-plugins
|
||||
# Generated Config files
|
||||
App/App/capacitor.config.json
|
||||
App/App/config.xml
|
||||
|
||||
# User-specific Xcode files
|
||||
App/App.xcodeproj/xcuserdata/*.xcuserdatad/
|
||||
App/App.xcodeproj/*.xcuserstate
|
||||
|
||||
fastlane/report.xml
|
||||
fastlane/Preview.html
|
||||
fastlane/screenshots
|
||||
fastlane/test_output
|
||||
|
||||
# Generated Icons from capacitor-assets (also Contents.json which is confusing; see BUILDING.md)
|
||||
App/App/Assets.xcassets/AppIcon.appiconset
|
||||
App/App/Assets.xcassets/Splash.imageset
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
504EC30F1FED79650016851F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 504EC30E1FED79650016851F /* Assets.xcassets */; };
|
||||
504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; };
|
||||
50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; };
|
||||
97EF2DC6FD76C3643D680B8D /* Pods_App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 90DCAFB4D8948F7A50C13800 /* Pods_App.framework */; };
|
||||
A084ECDBA7D38E1E42DFC39D /* Pods_App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
@@ -27,9 +27,9 @@
|
||||
504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
504EC3131FED79650016851F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
50B271D01FEDC1A000F3C39B /* public */ = {isa = PBXFileReference; lastKnownFileType = folder; path = public; sourceTree = "<group>"; };
|
||||
90DCAFB4D8948F7A50C13800 /* Pods_App.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_App.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
E2E9297D5D02C549106C77F9 /* Pods-App.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.release.xcconfig"; path = "Target Support Files/Pods-App/Pods-App.release.xcconfig"; sourceTree = "<group>"; };
|
||||
EAEC6436E595F7CD3A1C9E96 /* Pods-App.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.debug.xcconfig"; path = "Target Support Files/Pods-App/Pods-App.debug.xcconfig"; sourceTree = "<group>"; };
|
||||
AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_App.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.release.xcconfig"; path = "Pods/Target Support Files/Pods-App/Pods-App.release.xcconfig"; sourceTree = "<group>"; };
|
||||
FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-App.debug.xcconfig"; path = "Pods/Target Support Files/Pods-App/Pods-App.debug.xcconfig"; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -37,17 +37,17 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
97EF2DC6FD76C3643D680B8D /* Pods_App.framework in Frameworks */,
|
||||
A084ECDBA7D38E1E42DFC39D /* Pods_App.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
4B546315E668C7A13939F417 /* Frameworks */ = {
|
||||
27E2DDA53C4D2A4D1A88CE4A /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
90DCAFB4D8948F7A50C13800 /* Pods_App.framework */,
|
||||
AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */,
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
@@ -57,8 +57,8 @@
|
||||
children = (
|
||||
504EC3061FED79650016851F /* App */,
|
||||
504EC3051FED79650016851F /* Products */,
|
||||
BA325FFCDCE8D334E5C7AEBE /* Pods */,
|
||||
4B546315E668C7A13939F417 /* Frameworks */,
|
||||
7F8756D8B27F46E3366F6CEA /* Pods */,
|
||||
27E2DDA53C4D2A4D1A88CE4A /* Frameworks */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
@@ -85,13 +85,13 @@
|
||||
path = App;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
BA325FFCDCE8D334E5C7AEBE /* Pods */ = {
|
||||
7F8756D8B27F46E3366F6CEA /* Pods */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
EAEC6436E595F7CD3A1C9E96 /* Pods-App.debug.xcconfig */,
|
||||
E2E9297D5D02C549106C77F9 /* Pods-App.release.xcconfig */,
|
||||
FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */,
|
||||
AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */,
|
||||
);
|
||||
path = Pods;
|
||||
name = Pods;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
@@ -101,13 +101,12 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */;
|
||||
buildPhases = (
|
||||
92977BEA1068CC097A57FC77 /* [CP] Check Pods Manifest.lock */,
|
||||
6634F4EFEBD30273BCE97C65 /* [CP] Check Pods Manifest.lock */,
|
||||
504EC3001FED79650016851F /* Sources */,
|
||||
504EC3011FED79650016851F /* Frameworks */,
|
||||
504EC3021FED79650016851F /* Resources */,
|
||||
9592DBEFFC6D2A0C8D5DEB22 /* [CP] Embed Pods Frameworks */,
|
||||
012076E8FFE4BF260A79B034 /* Fix Privacy Manifest */,
|
||||
3525031ED1C96EF4CF6E9959 /* [CP] Embed Pods Frameworks */,
|
||||
96A7EF592DF3366D00084D51 /* Fix Privacy Manifest */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
@@ -187,10 +186,28 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "\"${PROJECT_DIR}/app_privacy_manifest_fixer/fixer.sh\" \n";
|
||||
shellScript = "\"${PROJECT_DIR}/app_privacy_manifest_fixer/fixer.sh\" ";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
3525031ED1C96EF4CF6E9959 /* [CP] Embed Pods Frameworks */ = {
|
||||
6634F4EFEBD30273BCE97C65 /* [CP] Check Pods Manifest.lock */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
inputPaths = (
|
||||
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
|
||||
"${PODS_ROOT}/Manifest.lock",
|
||||
);
|
||||
name = "[CP] Check Pods Manifest.lock";
|
||||
outputPaths = (
|
||||
"$(DERIVED_FILE_DIR)/Pods-App-checkManifestLockResult.txt",
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
9592DBEFFC6D2A0C8D5DEB22 /* [CP] Embed Pods Frameworks */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
@@ -205,47 +222,6 @@
|
||||
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-App/Pods-App-frameworks.sh\"\n";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
92977BEA1068CC097A57FC77 /* [CP] Check Pods Manifest.lock */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
inputFileListPaths = (
|
||||
);
|
||||
inputPaths = (
|
||||
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
|
||||
"${PODS_ROOT}/Manifest.lock",
|
||||
);
|
||||
name = "[CP] Check Pods Manifest.lock";
|
||||
outputFileListPaths = (
|
||||
);
|
||||
outputPaths = (
|
||||
"$(DERIVED_FILE_DIR)/Pods-App-checkManifestLockResult.txt",
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
96A7EF592DF3366D00084D51 /* Fix Privacy Manifest */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
inputFileListPaths = (
|
||||
);
|
||||
inputPaths = (
|
||||
);
|
||||
name = "Fix Privacy Manifest";
|
||||
outputFileListPaths = (
|
||||
);
|
||||
outputPaths = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "$PROJECT_DIR/app_privacy_manifest_fixer/fixer.sh\n";
|
||||
};
|
||||
/* End PBXShellScriptBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
@@ -399,12 +375,11 @@
|
||||
};
|
||||
504EC3171FED79650016851F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = EAEC6436E595F7CD3A1C9E96 /* Pods-App.debug.xcconfig */;
|
||||
baseConfigurationReference = FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 35;
|
||||
DEVELOPMENT_TEAM = GM3FS5JQPH;
|
||||
CURRENT_PROJECT_VERSION = 18;
|
||||
ENABLE_APP_SANDBOX = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
INFOPLIST_FILE = App/Info.plist;
|
||||
@@ -413,7 +388,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.0.2;
|
||||
MARKETING_VERSION = 0.4.7;
|
||||
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
@@ -426,12 +401,11 @@
|
||||
};
|
||||
504EC3181FED79650016851F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = E2E9297D5D02C549106C77F9 /* Pods-App.release.xcconfig */;
|
||||
baseConfigurationReference = AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 35;
|
||||
DEVELOPMENT_TEAM = GM3FS5JQPH;
|
||||
CURRENT_PROJECT_VERSION = 18;
|
||||
ENABLE_APP_SANDBOX = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
INFOPLIST_FILE = App/Info.plist;
|
||||
@@ -440,7 +414,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.0.2;
|
||||
MARKETING_VERSION = 0.4.7;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";
|
||||
|
||||
@@ -9,8 +9,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
|
||||
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
|
||||
// Initialize SQLite
|
||||
//let sqlite = SQLite()
|
||||
//sqlite.initialize()
|
||||
let sqlite = SQLite()
|
||||
sqlite.initialize()
|
||||
|
||||
// Override point for customization after application launch.
|
||||
return true
|
||||
|
||||
|
After Width: | Height: | Size: 116 KiB |
14
ios/App/App/Assets.xcassets/AppIcon.appiconset/Contents.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"images": [
|
||||
{
|
||||
"idiom": "universal",
|
||||
"size": "1024x1024",
|
||||
"filename": "AppIcon-512@2x.png",
|
||||
"platform": "ios"
|
||||
}
|
||||
],
|
||||
"info": {
|
||||
"author": "xcode",
|
||||
"version": 1
|
||||
}
|
||||
}
|
||||
23
ios/App/App/Assets.xcassets/Splash.imageset/Contents.json
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"filename" : "splash-2732x2732-2.png",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"filename" : "splash-2732x2732-1.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"filename" : "splash-2732x2732.png",
|
||||
"scale" : "3x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
}
|
||||
}
|
||||
BIN
ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-1.png
vendored
Normal file
|
After Width: | Height: | Size: 40 KiB |
BIN
ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732-2.png
vendored
Normal file
|
After Width: | Height: | Size: 40 KiB |
BIN
ios/App/App/Assets.xcassets/Splash.imageset/splash-2732x2732.png
vendored
Normal file
|
After Width: | Height: | Size: 40 KiB |
@@ -49,16 +49,5 @@
|
||||
</array>
|
||||
<key>UIViewControllerBasedStatusBarAppearance</key>
|
||||
<true/>
|
||||
<key>CFBundleURLTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>app.timesafari</string>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>timesafari</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -27,9 +27,4 @@ end
|
||||
|
||||
post_install do |installer|
|
||||
assertDeploymentTarget(installer)
|
||||
installer.pods_project.targets.each do |target|
|
||||
target.build_configurations.each do |config|
|
||||
config.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64'
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -5,10 +5,6 @@ PODS:
|
||||
- Capacitor
|
||||
- CapacitorCamera (6.1.2):
|
||||
- Capacitor
|
||||
- CapacitorCommunitySqlite (6.0.2):
|
||||
- Capacitor
|
||||
- SQLCipher
|
||||
- ZIPFoundation
|
||||
- CapacitorCordova (6.2.1)
|
||||
- CapacitorFilesystem (6.0.3):
|
||||
- Capacitor
|
||||
@@ -77,18 +73,11 @@ PODS:
|
||||
- nanopb/decode (2.30910.0)
|
||||
- nanopb/encode (2.30910.0)
|
||||
- PromisesObjC (2.4.0)
|
||||
- SQLCipher (4.9.0):
|
||||
- SQLCipher/standard (= 4.9.0)
|
||||
- SQLCipher/common (4.9.0)
|
||||
- SQLCipher/standard (4.9.0):
|
||||
- SQLCipher/common
|
||||
- ZIPFoundation (0.9.19)
|
||||
|
||||
DEPENDENCIES:
|
||||
- "Capacitor (from `../../node_modules/@capacitor/ios`)"
|
||||
- "CapacitorApp (from `../../node_modules/@capacitor/app`)"
|
||||
- "CapacitorCamera (from `../../node_modules/@capacitor/camera`)"
|
||||
- "CapacitorCommunitySqlite (from `../../node_modules/@capacitor-community/sqlite`)"
|
||||
- "CapacitorCordova (from `../../node_modules/@capacitor/ios`)"
|
||||
- "CapacitorFilesystem (from `../../node_modules/@capacitor/filesystem`)"
|
||||
- "CapacitorMlkitBarcodeScanning (from `../../node_modules/@capacitor-mlkit/barcode-scanning`)"
|
||||
@@ -109,8 +98,6 @@ SPEC REPOS:
|
||||
- MLKitVision
|
||||
- nanopb
|
||||
- PromisesObjC
|
||||
- SQLCipher
|
||||
- ZIPFoundation
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
Capacitor:
|
||||
@@ -119,8 +106,6 @@ EXTERNAL SOURCES:
|
||||
:path: "../../node_modules/@capacitor/app"
|
||||
CapacitorCamera:
|
||||
:path: "../../node_modules/@capacitor/camera"
|
||||
CapacitorCommunitySqlite:
|
||||
:path: "../../node_modules/@capacitor-community/sqlite"
|
||||
CapacitorCordova:
|
||||
:path: "../../node_modules/@capacitor/ios"
|
||||
CapacitorFilesystem:
|
||||
@@ -136,7 +121,6 @@ SPEC CHECKSUMS:
|
||||
Capacitor: c95400d761e376be9da6be5a05f226c0e865cebf
|
||||
CapacitorApp: e1e6b7d05e444d593ca16fd6d76f2b7c48b5aea7
|
||||
CapacitorCamera: 9bc7b005d0e6f1d5f525b8137045b60cffffce79
|
||||
CapacitorCommunitySqlite: 0299d20f4b00c2e6aa485a1d8932656753937b9b
|
||||
CapacitorCordova: 8d93e14982f440181be7304aa9559ca631d77fff
|
||||
CapacitorFilesystem: 59270a63c60836248812671aa3b15df673fbaf74
|
||||
CapacitorMlkitBarcodeScanning: 7652be9c7922f39203a361de735d340ae37e134e
|
||||
@@ -154,9 +138,7 @@ SPEC CHECKSUMS:
|
||||
MLKitVision: 90922bca854014a856f8b649d1f1f04f63fd9c79
|
||||
nanopb: 438bc412db1928dac798aa6fd75726007be04262
|
||||
PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47
|
||||
SQLCipher: 31878d8ebd27e5c96db0b7cb695c96e9f8ad77da
|
||||
ZIPFoundation: b8c29ea7ae353b309bc810586181fd073cb3312c
|
||||
|
||||
PODFILE CHECKSUM: f987510f7383b04a1b09ea8472bdadcd88b6c924
|
||||
PODFILE CHECKSUM: 7e7e09e6937de7f015393aecf2cf7823645689b3
|
||||
|
||||
COCOAPODS: 1.16.2
|
||||
|
||||
1482
package-lock.json
generated
53
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "timesafari",
|
||||
"version": "1.0.3-beta",
|
||||
"version": "0.4.6",
|
||||
"description": "Time Safari Application",
|
||||
"author": {
|
||||
"name": "Time Safari Team"
|
||||
@@ -11,7 +11,7 @@
|
||||
"build": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.mts",
|
||||
"lint": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src",
|
||||
"lint-fix": "eslint --ext .js,.ts,.vue --ignore-path .gitignore --fix src",
|
||||
"prebuild": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src && node sw_combine.js && node scripts/copy-wasm.js",
|
||||
"prebuild": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src && node sw_combine.cjs && node scripts/copy-wasm.cjs",
|
||||
"test:all": "npm run test:prerequisites && npm run build && npm run test:web && npm run test:mobile",
|
||||
"test:prerequisites": "node scripts/check-prerequisites.js",
|
||||
"test:web": "npx playwright test -c playwright.config-local.ts --trace on",
|
||||
@@ -22,14 +22,15 @@
|
||||
"check:ios-device": "xcrun xctrace list devices 2>&1 | grep -w 'Booted' || (echo 'No iOS simulator running' && exit 1)",
|
||||
"clean:electron": "rimraf dist-electron",
|
||||
"build:pywebview": "vite build --config vite.config.pywebview.mts",
|
||||
"build:electron": "npm run clean:electron && tsc -p tsconfig.electron.json && vite build --config vite.config.electron.mts && node scripts/build-electron.js",
|
||||
"build:capacitor": "vite build --mode capacitor --config vite.config.capacitor.mts",
|
||||
"build:web": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.web.mts",
|
||||
"build:web:electron": "VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.web.mts && VITE_GIT_HASH=`git log -1 --pretty=format:%h` vite build --config vite.config.electron.mts --mode electron",
|
||||
"build:electron": "npm run clean:electron && npm run build:web:electron && tsc -p tsconfig.electron.json && vite build --config vite.config.electron.mts && node scripts/build-electron.cjs",
|
||||
"build:capacitor": "vite build --mode capacitor --config vite.config.capacitor.mts",
|
||||
"electron:dev": "npm run build && electron .",
|
||||
"electron:start": "electron .",
|
||||
"clean:android": "adb uninstall app.timesafari.app || true",
|
||||
"build:android": "npm run clean:android && rm -rf dist && npm run build:web && npm run build:capacitor && cd android && ./gradlew clean && ./gradlew assembleDebug && cd .. && npx cap sync android && npx capacitor-assets generate --android && npx cap open android",
|
||||
"electron:build-linux": "npm run build:electron && electron-builder --linux AppImage",
|
||||
"electron:build-linux": "electron-builder --linux AppImage",
|
||||
"electron:build-linux-deb": "npm run build:electron && electron-builder --linux deb",
|
||||
"electron:build-linux-prod": "NODE_ENV=production npm run build:electron && electron-builder --linux AppImage",
|
||||
"build:electron-prod": "NODE_ENV=production npm run build:electron",
|
||||
@@ -46,7 +47,7 @@
|
||||
"electron:build-mac-universal": "npm run build:electron-prod && electron-builder --mac --universal"
|
||||
},
|
||||
"dependencies": {
|
||||
"@capacitor-community/sqlite": "6.0.2",
|
||||
"@capacitor-community/sqlite": "^6.0.2",
|
||||
"@capacitor-mlkit/barcode-scanning": "^6.0.0",
|
||||
"@capacitor/android": "^6.2.0",
|
||||
"@capacitor/app": "^6.0.0",
|
||||
@@ -57,8 +58,8 @@
|
||||
"@capacitor/ios": "^6.2.0",
|
||||
"@capacitor/share": "^6.0.3",
|
||||
"@capawesome/capacitor-file-picker": "^6.2.0",
|
||||
"@dicebear/collection": "^5.4.1",
|
||||
"@dicebear/core": "^5.4.1",
|
||||
"@dicebear/collection": "^5.4.3",
|
||||
"@dicebear/core": "^5.4.3",
|
||||
"@ethersproject/hdnode": "^5.7.0",
|
||||
"@ethersproject/wallet": "^5.8.0",
|
||||
"@fortawesome/fontawesome-svg-core": "^6.5.1",
|
||||
@@ -69,7 +70,7 @@
|
||||
"@peculiar/asn1-schema": "^2.3.8",
|
||||
"@pvermeer/dexie-encrypted-addon": "^3.0.0",
|
||||
"@simplewebauthn/browser": "^10.0.0",
|
||||
"@simplewebauthn/server": "^10.0.0",
|
||||
"@simplewebauthn/server": "^10.0.1",
|
||||
"@tweenjs/tween.js": "^21.1.1",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
"@veramo/core": "^5.6.0",
|
||||
@@ -86,6 +87,7 @@
|
||||
"absurd-sql": "^0.0.54",
|
||||
"asn1-ber": "^1.2.2",
|
||||
"axios": "^1.6.8",
|
||||
"better-sqlite3-multiple-ciphers": "^11.10.0",
|
||||
"cbor-x": "^1.5.9",
|
||||
"class-transformer": "^0.5.1",
|
||||
"dexie": "^3.2.7",
|
||||
@@ -93,22 +95,23 @@
|
||||
"did-jwt": "^7.4.7",
|
||||
"did-resolver": "^4.1.0",
|
||||
"dotenv": "^16.0.3",
|
||||
"ethereum-cryptography": "^2.1.3",
|
||||
"electron-json-storage": "^4.6.0",
|
||||
"ethereum-cryptography": "^2.2.1",
|
||||
"ethereumjs-util": "^7.1.5",
|
||||
"jdenticon": "^3.2.0",
|
||||
"jdenticon": "^3.3.0",
|
||||
"js-generate-password": "^0.1.9",
|
||||
"js-yaml": "^4.1.0",
|
||||
"jsqr": "^1.4.0",
|
||||
"leaflet": "^1.9.4",
|
||||
"localstorage-slim": "^2.7.0",
|
||||
"lru-cache": "^10.2.0",
|
||||
"lru-cache": "^10.4.3",
|
||||
"luxon": "^3.4.4",
|
||||
"merkletreejs": "^0.3.11",
|
||||
"nostr-tools": "^2.10.4",
|
||||
"nostr-tools": "^2.13.1",
|
||||
"notiwind": "^2.0.2",
|
||||
"papaparse": "^5.4.1",
|
||||
"pina": "^0.20.2204228",
|
||||
"pinia-plugin-persistedstate": "^3.2.1",
|
||||
"pinia-plugin-persistedstate": "^3.2.3",
|
||||
"qr-code-generator-vue3": "^1.4.21",
|
||||
"qrcode": "^1.5.4",
|
||||
"ramda": "^0.29.1",
|
||||
@@ -124,12 +127,13 @@
|
||||
"vue-axios": "^3.5.2",
|
||||
"vue-facing-decorator": "^3.0.4",
|
||||
"vue-picture-cropper": "^0.7.0",
|
||||
"vue-qrcode-reader": "^5.5.3",
|
||||
"vue-qrcode-reader": "^5.7.2",
|
||||
"vue-router": "^4.5.0",
|
||||
"web-did-resolver": "^2.0.27",
|
||||
"web-did-resolver": "^2.0.30",
|
||||
"zod": "^3.24.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@capacitor-community/electron": "^5.0.1",
|
||||
"@capacitor/assets": "^3.0.5",
|
||||
"@playwright/test": "^1.45.2",
|
||||
"@types/dom-webcodecs": "^0.1.7",
|
||||
@@ -144,7 +148,7 @@
|
||||
"@types/ua-parser-js": "^0.7.39",
|
||||
"@typescript-eslint/eslint-plugin": "^6.21.0",
|
||||
"@typescript-eslint/parser": "^6.21.0",
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"@vitejs/plugin-vue": "^5.2.4",
|
||||
"@vue/eslint-config-typescript": "^11.0.3",
|
||||
"autoprefixer": "^10.4.19",
|
||||
"browserify-fs": "^1.0.0",
|
||||
@@ -164,26 +168,32 @@
|
||||
"postcss": "^8.4.38",
|
||||
"prettier": "^3.2.5",
|
||||
"rimraf": "^6.0.1",
|
||||
"source-map-support": "^0.5.21",
|
||||
"tailwindcss": "^3.4.1",
|
||||
"typescript": "~5.2.2",
|
||||
"vite": "^5.2.0",
|
||||
"vite-plugin-pwa": "^1.0.0"
|
||||
},
|
||||
"main": "./dist-electron/main.js",
|
||||
"main": "./dist-electron/main.mjs",
|
||||
"build": {
|
||||
"appId": "app.timesafari.app",
|
||||
"appId": "app.timesafari",
|
||||
"productName": "TimeSafari",
|
||||
"directories": {
|
||||
"output": "dist-electron-packages"
|
||||
},
|
||||
"files": [
|
||||
"dist-electron/**/*",
|
||||
"dist/**/*"
|
||||
"dist/**/*",
|
||||
"capacitor.config.json"
|
||||
],
|
||||
"extraResources": [
|
||||
{
|
||||
"from": "dist-electron/www",
|
||||
"to": "www"
|
||||
},
|
||||
{
|
||||
"from": "dist-electron/resources/preload.js",
|
||||
"to": "preload.js"
|
||||
}
|
||||
],
|
||||
"linux": {
|
||||
@@ -221,5 +231,6 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"type": "module"
|
||||
}
|
||||
|
||||
@@ -2,6 +2,5 @@ dependencies:
|
||||
- gradle
|
||||
- java
|
||||
- pod
|
||||
- rubygems.org
|
||||
|
||||
# other dependencies are discovered via package.json & requirements.txt & Gemfile (I'm guessing).
|
||||
|
||||
96
scripts/build-electron.cjs
Normal file
@@ -0,0 +1,96 @@
|
||||
const fs = require("fs");
|
||||
const fse = require("fs-extra");
|
||||
const path = require("path");
|
||||
const { execSync } = require('child_process');
|
||||
|
||||
console.log("Starting Electron build finalization...");
|
||||
|
||||
// Define paths
|
||||
const distPath = path.join(__dirname, "..", "dist");
|
||||
const electronDistPath = path.join(__dirname, "..", "dist-electron");
|
||||
const wwwPath = path.join(electronDistPath, "www");
|
||||
const builtIndexPath = path.join(distPath, "index.html");
|
||||
const finalIndexPath = path.join(wwwPath, "index.html");
|
||||
|
||||
// Ensure target directory exists
|
||||
if (!fs.existsSync(wwwPath)) {
|
||||
fs.mkdirSync(wwwPath, { recursive: true });
|
||||
}
|
||||
|
||||
// Copy assets directory
|
||||
const assetsSrc = path.join(distPath, "assets");
|
||||
const assetsDest = path.join(wwwPath, "assets");
|
||||
if (fs.existsSync(assetsSrc)) {
|
||||
fse.copySync(assetsSrc, assetsDest, { overwrite: true });
|
||||
}
|
||||
|
||||
// Copy favicon.ico
|
||||
const faviconSrc = path.join(distPath, "favicon.ico");
|
||||
if (fs.existsSync(faviconSrc)) {
|
||||
fs.copyFileSync(faviconSrc, path.join(wwwPath, "favicon.ico"));
|
||||
}
|
||||
|
||||
// Copy manifest.webmanifest
|
||||
const manifestSrc = path.join(distPath, "manifest.webmanifest");
|
||||
if (fs.existsSync(manifestSrc)) {
|
||||
fs.copyFileSync(manifestSrc, path.join(wwwPath, "manifest.webmanifest"));
|
||||
}
|
||||
|
||||
// Load and modify index.html from Vite output
|
||||
let indexContent = fs.readFileSync(builtIndexPath, "utf-8");
|
||||
|
||||
// Inject the window.process shim after the first <script> block
|
||||
indexContent = indexContent.replace(
|
||||
/<script[^>]*type="module"[^>]*>/,
|
||||
match => `${match}\n window.process = { env: { VITE_PLATFORM: 'electron' } };`
|
||||
);
|
||||
|
||||
// Write the modified index.html to dist-electron/www
|
||||
fs.writeFileSync(finalIndexPath, indexContent);
|
||||
|
||||
// Copy preload script to resources
|
||||
const preloadSrc = path.join(electronDistPath, "preload.mjs");
|
||||
const preloadDest = path.join(electronDistPath, "resources", "preload.js");
|
||||
|
||||
// Ensure resources directory exists
|
||||
const resourcesDir = path.join(electronDistPath, "resources");
|
||||
if (!fs.existsSync(resourcesDir)) {
|
||||
fs.mkdirSync(resourcesDir, { recursive: true });
|
||||
}
|
||||
|
||||
if (fs.existsSync(preloadSrc)) {
|
||||
// Read the preload script
|
||||
let preloadContent = fs.readFileSync(preloadSrc, 'utf-8');
|
||||
|
||||
// Convert ESM to CommonJS if needed
|
||||
preloadContent = preloadContent
|
||||
.replace(/import\s*{\s*([^}]+)\s*}\s*from\s*['"]electron['"];?/g, 'const { $1 } = require("electron");')
|
||||
.replace(/export\s*{([^}]+)};?/g, '')
|
||||
.replace(/export\s+default\s+([^;]+);?/g, 'module.exports = $1;');
|
||||
|
||||
// Write the modified preload script
|
||||
fs.writeFileSync(preloadDest, preloadContent);
|
||||
console.log("Preload script copied and converted to resources directory");
|
||||
} else {
|
||||
console.error("Preload script not found at:", preloadSrc);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Copy capacitor.config.json to dist-electron
|
||||
try {
|
||||
console.log("Copying capacitor.config.json to dist-electron...");
|
||||
const configPath = path.join(process.cwd(), 'capacitor.config.json');
|
||||
const targetPath = path.join(process.cwd(), 'dist-electron', 'capacitor.config.json');
|
||||
|
||||
if (!fs.existsSync(configPath)) {
|
||||
throw new Error('capacitor.config.json not found in project root');
|
||||
}
|
||||
|
||||
fs.copyFileSync(configPath, targetPath);
|
||||
console.log("Successfully copied capacitor.config.json");
|
||||
} catch (error) {
|
||||
console.error("Failed to copy capacitor.config.json:", error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
console.log("Electron index.html copied and patched for Electron context.");
|
||||
@@ -1,165 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
console.log('Starting electron build process...');
|
||||
|
||||
// Define paths
|
||||
const electronDistPath = path.join(__dirname, '..', 'dist-electron');
|
||||
const wwwPath = path.join(electronDistPath, 'www');
|
||||
|
||||
// Create www directory if it doesn't exist
|
||||
if (!fs.existsSync(wwwPath)) {
|
||||
fs.mkdirSync(wwwPath, { recursive: true });
|
||||
}
|
||||
|
||||
// Create a platform-specific index.html for Electron
|
||||
const initialIndexContent = `<!DOCTYPE html>
|
||||
<html lang="">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1.0,viewport-fit=cover">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<title>TimeSafari</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>
|
||||
<strong>We're sorry but TimeSafari doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
|
||||
</noscript>
|
||||
<div id="app"></div>
|
||||
<script type="module">
|
||||
// Force electron platform
|
||||
window.process = { env: { VITE_PLATFORM: 'electron' } };
|
||||
import('./src/main.electron.ts');
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
// Write the Electron-specific index.html
|
||||
fs.writeFileSync(path.join(wwwPath, 'index.html'), initialIndexContent);
|
||||
|
||||
// Copy only necessary assets from web build
|
||||
const webDistPath = path.join(__dirname, '..', 'dist');
|
||||
if (fs.existsSync(webDistPath)) {
|
||||
// Copy assets directory
|
||||
const assetsSrc = path.join(webDistPath, 'assets');
|
||||
const assetsDest = path.join(wwwPath, 'assets');
|
||||
if (fs.existsSync(assetsSrc)) {
|
||||
fs.cpSync(assetsSrc, assetsDest, { recursive: true });
|
||||
}
|
||||
|
||||
// Copy favicon
|
||||
const faviconSrc = path.join(webDistPath, 'favicon.ico');
|
||||
if (fs.existsSync(faviconSrc)) {
|
||||
fs.copyFileSync(faviconSrc, path.join(wwwPath, 'favicon.ico'));
|
||||
}
|
||||
}
|
||||
|
||||
// Remove service worker files
|
||||
const swFilesToRemove = [
|
||||
'sw.js',
|
||||
'sw.js.map',
|
||||
'workbox-*.js',
|
||||
'workbox-*.js.map',
|
||||
'registerSW.js',
|
||||
'manifest.webmanifest',
|
||||
'**/workbox-*.js',
|
||||
'**/workbox-*.js.map',
|
||||
'**/sw.js',
|
||||
'**/sw.js.map',
|
||||
'**/registerSW.js',
|
||||
'**/manifest.webmanifest'
|
||||
];
|
||||
|
||||
console.log('Removing service worker files...');
|
||||
swFilesToRemove.forEach(pattern => {
|
||||
const files = fs.readdirSync(wwwPath).filter(file =>
|
||||
file.match(new RegExp(pattern.replace(/\*/g, '.*')))
|
||||
);
|
||||
files.forEach(file => {
|
||||
const filePath = path.join(wwwPath, file);
|
||||
console.log(`Removing ${filePath}`);
|
||||
try {
|
||||
fs.unlinkSync(filePath);
|
||||
} catch (err) {
|
||||
console.warn(`Could not remove ${filePath}:`, err.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Also check and remove from assets directory
|
||||
const assetsPath = path.join(wwwPath, 'assets');
|
||||
if (fs.existsSync(assetsPath)) {
|
||||
swFilesToRemove.forEach(pattern => {
|
||||
const files = fs.readdirSync(assetsPath).filter(file =>
|
||||
file.match(new RegExp(pattern.replace(/\*/g, '.*')))
|
||||
);
|
||||
files.forEach(file => {
|
||||
const filePath = path.join(assetsPath, file);
|
||||
console.log(`Removing ${filePath}`);
|
||||
try {
|
||||
fs.unlinkSync(filePath);
|
||||
} catch (err) {
|
||||
console.warn(`Could not remove ${filePath}:`, err.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Modify index.html to remove service worker registration
|
||||
const indexPath = path.join(wwwPath, 'index.html');
|
||||
if (fs.existsSync(indexPath)) {
|
||||
console.log('Modifying index.html to remove service worker registration...');
|
||||
let indexContent = fs.readFileSync(indexPath, 'utf8');
|
||||
|
||||
// Remove service worker registration script
|
||||
indexContent = indexContent
|
||||
.replace(/<script[^>]*id="vite-plugin-pwa:register-sw"[^>]*><\/script>/g, '')
|
||||
.replace(/<script[^>]*registerServiceWorker[^>]*><\/script>/g, '')
|
||||
.replace(/<link[^>]*rel="manifest"[^>]*>/g, '')
|
||||
.replace(/<link[^>]*rel="serviceworker"[^>]*>/g, '')
|
||||
.replace(/navigator\.serviceWorker\.register\([^)]*\)/g, '')
|
||||
.replace(/if\s*\(\s*['"]serviceWorker['"]\s*in\s*navigator\s*\)\s*{[^}]*}/g, '');
|
||||
|
||||
fs.writeFileSync(indexPath, indexContent);
|
||||
console.log('Successfully modified index.html');
|
||||
}
|
||||
|
||||
// Fix asset paths
|
||||
console.log('Fixing asset paths in index.html...');
|
||||
let modifiedIndexContent = fs.readFileSync(indexPath, 'utf8');
|
||||
modifiedIndexContent = modifiedIndexContent
|
||||
.replace(/\/assets\//g, './assets/')
|
||||
.replace(/href="\//g, 'href="./')
|
||||
.replace(/src="\//g, 'src="./');
|
||||
|
||||
fs.writeFileSync(indexPath, modifiedIndexContent);
|
||||
|
||||
// Verify no service worker references remain
|
||||
const finalContent = fs.readFileSync(indexPath, 'utf8');
|
||||
if (finalContent.includes('serviceWorker') || finalContent.includes('workbox')) {
|
||||
console.warn('Warning: Service worker references may still exist in index.html');
|
||||
}
|
||||
|
||||
// Check for remaining /assets/ paths
|
||||
console.log('After path fixing, checking for remaining /assets/ paths:', finalContent.includes('/assets/'));
|
||||
console.log('Sample of fixed content:', finalContent.substring(0, 500));
|
||||
|
||||
console.log('Copied and fixed web files in:', wwwPath);
|
||||
|
||||
// Copy main process files
|
||||
console.log('Copying main process files...');
|
||||
|
||||
// Copy the main process file instead of creating a template
|
||||
const mainSrcPath = path.join(__dirname, '..', 'dist-electron', 'main.js');
|
||||
const mainDestPath = path.join(electronDistPath, 'main.js');
|
||||
|
||||
if (fs.existsSync(mainSrcPath)) {
|
||||
fs.copyFileSync(mainSrcPath, mainDestPath);
|
||||
console.log('Copied main process file successfully');
|
||||
} else {
|
||||
console.error('Main process file not found at:', mainSrcPath);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log('Electron build process completed successfully');
|
||||
@@ -51,7 +51,7 @@ const { existsSync } = require('fs');
|
||||
*/
|
||||
function checkCommand(command, errorMessage) {
|
||||
try {
|
||||
execSync(command, { stdio: 'ignore' });
|
||||
execSync(command + ' --version', { stdio: 'ignore' });
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error(`❌ ${errorMessage}`);
|
||||
@@ -164,10 +164,10 @@ function main() {
|
||||
|
||||
// Check required command line tools
|
||||
// These are essential for building and testing the application
|
||||
success &= checkCommand('node --version', 'Node.js is required');
|
||||
success &= checkCommand('npm --version', 'npm is required');
|
||||
success &= checkCommand('gradle --version', 'Gradle is required for Android builds');
|
||||
success &= checkCommand('xcodebuild --help', 'Xcode is required for iOS builds');
|
||||
success &= checkCommand('node', 'Node.js is required');
|
||||
success &= checkCommand('npm', 'npm is required');
|
||||
success &= checkCommand('gradle', 'Gradle is required for Android builds');
|
||||
success &= checkCommand('xcodebuild', 'Xcode is required for iOS builds');
|
||||
|
||||
// Check platform-specific development environments
|
||||
success &= checkAndroidSetup();
|
||||
|
||||
@@ -170,7 +170,7 @@ const executeDeeplink = async (url, description, log) => {
|
||||
|
||||
try {
|
||||
// Stop the app before executing the deep link
|
||||
execSync('adb shell am force-stop app.timesafari.app');
|
||||
execSync('adb shell am force-stop app.timesafari');
|
||||
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1s
|
||||
|
||||
execSync(`adb shell am start -W -a android.intent.action.VIEW -d "${url}" -c android.intent.category.BROWSABLE`);
|
||||
|
||||
19
src/App.vue
@@ -4,7 +4,7 @@
|
||||
<!-- Messages in the upper-right - https://github.com/emmanuelsw/notiwind -->
|
||||
<NotificationGroup group="alert">
|
||||
<div
|
||||
class="fixed z-[90] top-[max(1rem,env(safe-area-inset-top))] right-4 left-4 sm:left-auto sm:w-full sm:max-w-sm flex flex-col items-start justify-end"
|
||||
class="fixed top-[calc(env(safe-area-inset-top)+1rem)] right-4 left-4 sm:left-auto sm:w-full sm:max-w-sm flex flex-col items-start justify-end"
|
||||
>
|
||||
<Notification
|
||||
v-slot="{ notifications, close }"
|
||||
@@ -459,9 +459,10 @@ export default class App extends Vue {
|
||||
return true;
|
||||
}
|
||||
|
||||
const serverSubscription = {
|
||||
...subscription,
|
||||
};
|
||||
const serverSubscription =
|
||||
typeof subscription === "object" && subscription !== null
|
||||
? { ...subscription }
|
||||
: {};
|
||||
if (!allGoingOff) {
|
||||
serverSubscription["notifyType"] = notification.title;
|
||||
logger.log(
|
||||
@@ -548,13 +549,13 @@ export default class App extends Vue {
|
||||
|
||||
<style>
|
||||
#Content {
|
||||
padding-left: max(1.5rem, env(safe-area-inset-left));
|
||||
padding-right: max(1.5rem, env(safe-area-inset-right));
|
||||
padding-top: max(1.5rem, env(safe-area-inset-top));
|
||||
padding-bottom: max(1.5rem, env(safe-area-inset-bottom));
|
||||
padding-left: 1.5rem;
|
||||
padding-right: 1.5rem;
|
||||
padding-top: calc(env(safe-area-inset-top) + 1.5rem);
|
||||
padding-bottom: calc(env(safe-area-inset-bottom) + 1.5rem);
|
||||
}
|
||||
|
||||
#QuickNav ~ #Content {
|
||||
padding-bottom: calc(env(safe-area-inset-bottom) + 6.333rem);
|
||||
padding-bottom: calc(env(safe-area-inset-bottom) + 6rem);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
{
|
||||
"warning": {
|
||||
"fillRule": "evenodd",
|
||||
"d": "M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z",
|
||||
"clipRule": "evenodd"
|
||||
},
|
||||
"spinner": {
|
||||
"d": "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
||||
},
|
||||
"chart": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
|
||||
},
|
||||
"plus": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M12 4v16m8-8H4"
|
||||
},
|
||||
"settings": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
|
||||
},
|
||||
"settingsDot": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M15 12a3 3 0 11-6 0 3 3 0 016 0z"
|
||||
},
|
||||
"lock": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
|
||||
},
|
||||
"download": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
|
||||
},
|
||||
"check": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
},
|
||||
"edit": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
|
||||
},
|
||||
"trash": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
|
||||
},
|
||||
"plusCircle": {
|
||||
"strokeLinecap": "round",
|
||||
"strokeLinejoin": "round",
|
||||
"strokeWidth": "2",
|
||||
"d": "M12 6v6m0 0v6m0-6h6m-6 0H6"
|
||||
},
|
||||
"info": {
|
||||
"fillRule": "evenodd",
|
||||
"d": "M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z",
|
||||
"clipRule": "evenodd"
|
||||
}
|
||||
}
|
||||
@@ -14,34 +14,22 @@
|
||||
class="flex items-center justify-between gap-2 text-lg bg-slate-200 border border-slate-300 border-b-0 rounded-t-md px-3 sm:px-4 py-1 sm:py-2"
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
<router-link
|
||||
v-if="record.issuerDid && !isHiddenDid(record.issuerDid)"
|
||||
:to="{
|
||||
path: '/did/' + encodeURIComponent(record.issuerDid),
|
||||
}"
|
||||
title="More details about this person"
|
||||
>
|
||||
<div v-if="record.issuerDid">
|
||||
<EntityIcon
|
||||
:entity-id="record.issuerDid"
|
||||
class="rounded-full bg-white overflow-hidden !size-[2rem] object-cover"
|
||||
/>
|
||||
</router-link>
|
||||
<font-awesome
|
||||
v-else-if="isHiddenDid(record.issuerDid)"
|
||||
icon="eye-slash"
|
||||
class="text-slate-400 !size-[2rem] cursor-pointer"
|
||||
@click="notifyHiddenPerson"
|
||||
/>
|
||||
<font-awesome
|
||||
v-else
|
||||
icon="person-circle-question"
|
||||
class="text-slate-400 !size-[2rem] cursor-pointer"
|
||||
@click="notifyUnknownPerson"
|
||||
/>
|
||||
</div>
|
||||
<div v-else>
|
||||
<font-awesome
|
||||
icon="person-circle-question"
|
||||
class="text-slate-300 text-[2rem]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 v-if="record.issuer.known" class="font-semibold leading-tight">
|
||||
{{ record.issuer.displayName }}
|
||||
<h3 class="font-semibold">
|
||||
{{ record.issuer.known ? record.issuer.displayName : "" }}
|
||||
</h3>
|
||||
<p class="ms-auto text-xs text-slate-500 italic">
|
||||
{{ friendlyDate }}
|
||||
@@ -49,11 +37,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a
|
||||
class="cursor-pointer"
|
||||
data-testid="circle-info-link"
|
||||
@click="$emit('loadClaim', record.jwtId)"
|
||||
>
|
||||
<a class="cursor-pointer" @click="$emit('loadClaim', record.jwtId)">
|
||||
<font-awesome icon="circle-info" class="fa-fw text-slate-500" />
|
||||
</a>
|
||||
</div>
|
||||
@@ -62,7 +46,7 @@
|
||||
<!-- Record Image -->
|
||||
<div
|
||||
v-if="record.image"
|
||||
class="bg-cover mb-2 -mt-3 sm:-mt-4 -mx-3 sm:-mx-4"
|
||||
class="bg-cover mb-6 -mt-3 sm:-mt-4 -mx-3 sm:-mx-4"
|
||||
:style="`background-image: url(${record.image});`"
|
||||
>
|
||||
<a
|
||||
@@ -78,59 +62,29 @@
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- Description -->
|
||||
<p class="font-medium">
|
||||
<a class="cursor-pointer" @click="$emit('loadClaim', record.jwtId)">
|
||||
{{ description }}
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<div
|
||||
class="relative flex justify-between gap-4 max-w-[40rem] mx-auto mt-4"
|
||||
class="relative flex justify-between gap-4 max-w-[40rem] mx-auto mb-5"
|
||||
>
|
||||
<!-- Source -->
|
||||
<div
|
||||
class="w-[7rem] sm:w-[12rem] text-center bg-white border border-slate-200 rounded p-2 sm:p-3"
|
||||
class="w-[8rem] sm:w-[12rem] text-center bg-white border border-slate-200 rounded p-2 sm:p-3"
|
||||
>
|
||||
<div class="relative w-fit mx-auto">
|
||||
<div>
|
||||
<!-- Project Icon -->
|
||||
<div v-if="record.providerPlanName">
|
||||
<router-link
|
||||
:to="{
|
||||
path:
|
||||
'/project/' +
|
||||
encodeURIComponent(record.providerPlanHandleId || ''),
|
||||
}"
|
||||
title="View project details"
|
||||
>
|
||||
<ProjectIcon
|
||||
:entity-id="record.providerPlanHandleId || ''"
|
||||
:icon-size="48"
|
||||
class="rounded size-[3rem] sm:size-[4rem] *:w-full *:h-full"
|
||||
/>
|
||||
</router-link>
|
||||
<ProjectIcon
|
||||
:entity-id="record.providerPlanName"
|
||||
:icon-size="48"
|
||||
class="rounded size-[3rem] sm:size-[4rem] *:w-full *:h-full"
|
||||
/>
|
||||
</div>
|
||||
<!-- Identicon for DIDs -->
|
||||
<div v-else-if="record.agentDid">
|
||||
<router-link
|
||||
v-if="!isHiddenDid(record.agentDid)"
|
||||
:to="{
|
||||
path: '/did/' + encodeURIComponent(record.agentDid),
|
||||
}"
|
||||
title="More details about this person"
|
||||
>
|
||||
<EntityIcon
|
||||
:entity-id="record.agentDid"
|
||||
:profile-image-url="record.issuer.profileImageUrl"
|
||||
class="rounded-full bg-slate-100 overflow-hidden !size-[3rem] sm:!size-[4rem]"
|
||||
/>
|
||||
</router-link>
|
||||
<font-awesome
|
||||
v-else
|
||||
icon="eye-slash"
|
||||
class="text-slate-300 !size-[3rem] sm:!size-[4rem]"
|
||||
@click="notifyHiddenPerson"
|
||||
<EntityIcon
|
||||
:entity-id="record.agentDid"
|
||||
:profile-image-url="record.issuer.profileImageUrl"
|
||||
class="rounded-full bg-slate-100 overflow-hidden !size-[3rem] sm:!size-[4rem]"
|
||||
/>
|
||||
</div>
|
||||
<!-- Unknown Person -->
|
||||
@@ -138,7 +92,6 @@
|
||||
<font-awesome
|
||||
icon="person-circle-question"
|
||||
class="text-slate-300 text-[3rem] sm:text-[4rem]"
|
||||
@click="notifyUnknownPerson"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -157,11 +110,9 @@
|
||||
|
||||
<!-- Arrow -->
|
||||
<div
|
||||
class="absolute inset-x-[7rem] sm:inset-x-[12rem] mx-2 top-1/2 -translate-y-1/2"
|
||||
class="absolute inset-x-[8rem] sm:inset-x-[12rem] mx-2 top-1/2 -translate-y-1/2"
|
||||
>
|
||||
<div
|
||||
class="text-sm text-center leading-none font-semibold pe-2 sm:pe-4"
|
||||
>
|
||||
<div class="text-sm text-center leading-none font-semibold pe-[15px]">
|
||||
{{ fetchAmount }}
|
||||
</div>
|
||||
|
||||
@@ -178,47 +129,24 @@
|
||||
|
||||
<!-- Destination -->
|
||||
<div
|
||||
class="w-[7rem] sm:w-[12rem] text-center bg-white border border-slate-200 rounded p-2 sm:p-3"
|
||||
class="w-[8rem] sm:w-[12rem] text-center bg-white border border-slate-200 rounded p-2 sm:p-3"
|
||||
>
|
||||
<div class="relative w-fit mx-auto">
|
||||
<div>
|
||||
<!-- Project Icon -->
|
||||
<div v-if="record.recipientProjectName">
|
||||
<router-link
|
||||
:to="{
|
||||
path:
|
||||
'/project/' +
|
||||
encodeURIComponent(record.fulfillsPlanHandleId || ''),
|
||||
}"
|
||||
title="View project details"
|
||||
>
|
||||
<ProjectIcon
|
||||
:entity-id="record.fulfillsPlanHandleId || ''"
|
||||
:icon-size="48"
|
||||
class="rounded size-[3rem] sm:size-[4rem] *:w-full *:h-full"
|
||||
/>
|
||||
</router-link>
|
||||
<ProjectIcon
|
||||
:entity-id="record.recipientProjectName"
|
||||
:icon-size="48"
|
||||
class="rounded size-[3rem] sm:size-[4rem] *:w-full *:h-full"
|
||||
/>
|
||||
</div>
|
||||
<!-- Identicon for DIDs -->
|
||||
<div v-else-if="record.recipientDid">
|
||||
<router-link
|
||||
v-if="!isHiddenDid(record.recipientDid)"
|
||||
:to="{
|
||||
path: '/did/' + encodeURIComponent(record.recipientDid),
|
||||
}"
|
||||
title="More details about this person"
|
||||
>
|
||||
<EntityIcon
|
||||
:entity-id="record.recipientDid"
|
||||
:profile-image-url="record.receiver.profileImageUrl"
|
||||
class="rounded-full bg-slate-100 overflow-hidden !size-[3rem] sm:!size-[4rem]"
|
||||
/>
|
||||
</router-link>
|
||||
<font-awesome
|
||||
v-else
|
||||
icon="eye-slash"
|
||||
class="text-slate-300 !size-[3rem] sm:!size-[4rem]"
|
||||
@click="notifyHiddenPerson"
|
||||
<EntityIcon
|
||||
:entity-id="record.recipientDid"
|
||||
:profile-image-url="record.receiver.profileImageUrl"
|
||||
class="rounded-full bg-slate-100 overflow-hidden !size-[3rem] sm:!size-[4rem]"
|
||||
/>
|
||||
</div>
|
||||
<!-- Unknown Person -->
|
||||
@@ -226,7 +154,6 @@
|
||||
<font-awesome
|
||||
icon="person-circle-question"
|
||||
class="text-slate-300 text-[3rem] sm:text-[4rem]"
|
||||
@click="notifyUnknownPerson"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -243,6 +170,13 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Description -->
|
||||
<p class="font-medium">
|
||||
<a class="cursor-pointer" @click="$emit('loadClaim', record.jwtId)">
|
||||
{{ description }}
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
</template>
|
||||
@@ -252,9 +186,8 @@ import { Component, Prop, Vue, Emit } from "vue-facing-decorator";
|
||||
import { GiveRecordWithContactInfo } from "../types";
|
||||
import EntityIcon from "./EntityIcon.vue";
|
||||
import { isGiveClaimType, notifyWhyCannotConfirm } from "../libs/util";
|
||||
import { containsHiddenDid, isHiddenDid } from "../libs/endorserServer";
|
||||
import { containsHiddenDid } from "../libs/endorserServer";
|
||||
import ProjectIcon from "./ProjectIcon.vue";
|
||||
import { NotificationIface } from "../constants/app";
|
||||
|
||||
@Component({
|
||||
components: {
|
||||
@@ -269,33 +202,6 @@ export default class ActivityListItem extends Vue {
|
||||
@Prop() activeDid!: string;
|
||||
@Prop() confirmerIdList?: string[];
|
||||
|
||||
isHiddenDid = isHiddenDid;
|
||||
$notify!: (notification: NotificationIface, timeout?: number) => void;
|
||||
|
||||
notifyHiddenPerson() {
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "warning",
|
||||
title: "Person Outside Your Network",
|
||||
text: "This person is not visible to you.",
|
||||
},
|
||||
3000,
|
||||
);
|
||||
}
|
||||
|
||||
notifyUnknownPerson() {
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "warning",
|
||||
title: "Unidentified Person",
|
||||
text: "Nobody specific was recognized.",
|
||||
},
|
||||
3000,
|
||||
);
|
||||
}
|
||||
|
||||
@Emit()
|
||||
cacheImage(image: string) {
|
||||
return image;
|
||||
@@ -316,7 +222,7 @@ export default class ActivityListItem extends Vue {
|
||||
const claim =
|
||||
(this.record.fullClaim as unknown).claim || this.record.fullClaim;
|
||||
|
||||
return `${claim?.description || ""}`;
|
||||
return `${claim.description}`;
|
||||
}
|
||||
|
||||
private displayAmount(code: string, amt: number) {
|
||||
|
||||
@@ -24,7 +24,9 @@ backup and database export, with platform-specific download instructions. * *
|
||||
class="block w-full text-center text-md bg-gradient-to-b from-blue-400 to-blue-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-1.5 py-2 rounded-md"
|
||||
@click="exportDatabase()"
|
||||
>
|
||||
Download Contacts
|
||||
Download Settings & Contacts
|
||||
<br />
|
||||
(excluding Identifier Data)
|
||||
</button>
|
||||
<a
|
||||
ref="downloadLink"
|
||||
@@ -60,18 +62,14 @@ backup and database export, with platform-specific download instructions. * *
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue } from "vue-facing-decorator";
|
||||
import { AppString, NotificationIface } from "../constants/app";
|
||||
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
|
||||
import { AppString, NotificationIface, USE_DEXIE_DB } from "../constants/app";
|
||||
import { db } from "../db/index";
|
||||
import { logger } from "../utils/logger";
|
||||
import { PlatformServiceFactory } from "../services/PlatformServiceFactory";
|
||||
import {
|
||||
PlatformService,
|
||||
PlatformCapabilities,
|
||||
} from "../services/PlatformService";
|
||||
import { contactsToExportJson } from "../libs/util";
|
||||
|
||||
/**
|
||||
* @vue-component
|
||||
@@ -133,25 +131,24 @@ export default class DataExportSection extends Vue {
|
||||
*/
|
||||
public async exportDatabase() {
|
||||
try {
|
||||
let allContacts: Contact[] = [];
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const result = await platformService.dbQuery(`SELECT * FROM contacts`);
|
||||
if (result) {
|
||||
allContacts = databaseUtil.mapQueryResultToValues(
|
||||
result,
|
||||
) as unknown as Contact[];
|
||||
if (!USE_DEXIE_DB) {
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
// if (USE_DEXIE_DB) {
|
||||
// await db.open();
|
||||
// allContacts = await db.contacts.toArray();
|
||||
// }
|
||||
|
||||
// Convert contacts to export format
|
||||
const exportData = contactsToExportJson(allContacts);
|
||||
const jsonStr = JSON.stringify(exportData, null, 2);
|
||||
const blob = new Blob([jsonStr], { type: "application/json" });
|
||||
|
||||
const fileName = `${AppString.APP_NAME_NO_SPACES}-backup-contacts.json`;
|
||||
const blob = await db.export({
|
||||
prettyJson: true,
|
||||
transform: (table, value, key) => {
|
||||
if (table === "contacts") {
|
||||
// Dexie inserts a number 0 when some are undefined, so we need to totally remove them.
|
||||
Object.keys(value).forEach((prop) => {
|
||||
if (value[prop] === undefined) {
|
||||
delete value[prop];
|
||||
}
|
||||
});
|
||||
}
|
||||
return { value, key };
|
||||
},
|
||||
});
|
||||
const fileName = `${AppString.APP_NAME_NO_SPACES}-backup.json`;
|
||||
|
||||
if (this.platformCapabilities.hasFileDownload) {
|
||||
// Web platform: Use download link
|
||||
@@ -163,7 +160,8 @@ export default class DataExportSection extends Vue {
|
||||
setTimeout(() => URL.revokeObjectURL(this.downloadUrl), 1000);
|
||||
} else if (this.platformCapabilities.hasFileSystem) {
|
||||
// Native platform: Write to app directory
|
||||
await this.platformService.writeAndShareFile(fileName, jsonStr);
|
||||
const content = await blob.text();
|
||||
await this.platformService.writeAndShareFile(fileName, content);
|
||||
} else {
|
||||
throw new Error("This platform does not support file downloads.");
|
||||
}
|
||||
@@ -174,10 +172,10 @@ export default class DataExportSection extends Vue {
|
||||
type: "success",
|
||||
title: "Export Successful",
|
||||
text: this.platformCapabilities.hasFileDownload
|
||||
? "See your downloads directory for the backup."
|
||||
: "The backup file has been saved.",
|
||||
? "See your downloads directory for the backup. It is in the Dexie format."
|
||||
: "You should have been prompted to save your backup file.",
|
||||
},
|
||||
3000,
|
||||
-1,
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error("Export Error:", error);
|
||||
|
||||
@@ -104,6 +104,7 @@ import { USE_DEXIE_DB } from "@/constants/app";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import { MASTER_SETTINGS_KEY } from "../db/tables/settings";
|
||||
import { db, retrieveSettingsForActiveAccount } from "../db/index";
|
||||
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
|
||||
|
||||
@Component({
|
||||
components: {
|
||||
@@ -142,23 +143,19 @@ export default class FeedFilters extends Vue {
|
||||
async toggleHasVisibleDid() {
|
||||
this.settingChanged = true;
|
||||
this.hasVisibleDid = !this.hasVisibleDid;
|
||||
await databaseUtil.updateDefaultSettings({
|
||||
await db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
filterFeedByVisible: this.hasVisibleDid,
|
||||
});
|
||||
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
filterFeedByVisible: this.hasVisibleDid,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async toggleNearby() {
|
||||
this.settingChanged = true;
|
||||
this.isNearby = !this.isNearby;
|
||||
await databaseUtil.updateDefaultSettings({
|
||||
filterFeedByNearby: this.isNearby,
|
||||
});
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
await platformService.dbExec(
|
||||
`UPDATE settings SET filterFeedByNearby = ? WHERE id = ?`,
|
||||
[this.isNearby, MASTER_SETTINGS_KEY],
|
||||
);
|
||||
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
@@ -172,10 +169,11 @@ export default class FeedFilters extends Vue {
|
||||
this.settingChanged = true;
|
||||
}
|
||||
|
||||
await databaseUtil.updateDefaultSettings({
|
||||
filterFeedByNearby: false,
|
||||
filterFeedByVisible: false,
|
||||
});
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
await platformService.dbExec(
|
||||
`UPDATE settings SET filterFeedByNearby = ? AND filterFeedByVisible = ? WHERE id = ?`,
|
||||
[false, false, MASTER_SETTINGS_KEY],
|
||||
);
|
||||
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
@@ -193,10 +191,11 @@ export default class FeedFilters extends Vue {
|
||||
this.settingChanged = true;
|
||||
}
|
||||
|
||||
await databaseUtil.updateDefaultSettings({
|
||||
filterFeedByNearby: true,
|
||||
filterFeedByVisible: true,
|
||||
});
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
await platformService.dbExec(
|
||||
`UPDATE settings SET filterFeedByNearby = ? AND filterFeedByVisible = ? WHERE id = ?`,
|
||||
[true, true, MASTER_SETTINGS_KEY],
|
||||
);
|
||||
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
|
||||
@@ -1,534 +1,99 @@
|
||||
<template>
|
||||
<div v-if="visible" class="dialog-overlay">
|
||||
<div class="dialog">
|
||||
<!-- Step 1: Giver -->
|
||||
<div v-show="firstStep" id="sectionGiftedGiver">
|
||||
<label class="block font-bold mb-4">
|
||||
{{
|
||||
stepType === "recipient"
|
||||
? "Choose who received the gift:"
|
||||
: showProjects
|
||||
? "Choose a project benefitted from:"
|
||||
: "Choose a person received from:"
|
||||
}}
|
||||
</label>
|
||||
|
||||
<!-- Unified Quick-pick grid for People and Projects -->
|
||||
<ul
|
||||
:class="
|
||||
shouldShowProjects
|
||||
? 'grid grid-cols-3 md:grid-cols-4 gap-x-2 gap-y-4 text-center mb-4'
|
||||
: 'grid grid-cols-4 sm:grid-cols-5 md:grid-cols-6 gap-x-2 gap-y-4 text-center mb-4'
|
||||
"
|
||||
<h1 class="text-xl font-bold text-center mb-4">
|
||||
{{ customTitle }}
|
||||
</h1>
|
||||
<input
|
||||
v-model="description"
|
||||
type="text"
|
||||
class="block w-full rounded border border-slate-400 mb-2 px-3 py-2"
|
||||
:placeholder="prompt || 'What was given?'"
|
||||
/>
|
||||
<div class="flex flex-row justify-center">
|
||||
<span
|
||||
class="rounded-l border border-r-0 border-slate-400 bg-slate-200 text-center text-blue-500 px-2 py-2 w-20"
|
||||
@click="changeUnitCode()"
|
||||
>
|
||||
<template v-if="shouldShowProjects">
|
||||
<!-- show projects -->
|
||||
<li
|
||||
v-for="project in projects.slice(0, 7)"
|
||||
:key="project.handleId"
|
||||
class="cursor-pointer"
|
||||
@click="
|
||||
stepType === 'recipient'
|
||||
? selectRecipientProject(project)
|
||||
: selectProject(project)
|
||||
"
|
||||
>
|
||||
<div class="relative w-fit mx-auto mb-1">
|
||||
<ProjectIcon
|
||||
:entity-id="project.handleId"
|
||||
:icon-size="48"
|
||||
:image-url="project.image"
|
||||
class="!size-[3rem] mx-auto border border-slate-300 bg-white overflow-hidden rounded-full"
|
||||
/>
|
||||
</div>
|
||||
<h3
|
||||
class="text-xs font-medium text-ellipsis whitespace-nowrap overflow-hidden"
|
||||
>
|
||||
{{ project.name }}
|
||||
</h3>
|
||||
<div class="text-xs text-slate-500 truncate">
|
||||
<font-awesome icon="user" class="fa-fw text-slate-400" />
|
||||
{{
|
||||
didInfo(project.issuerDid, activeDid, allMyDids, allContacts)
|
||||
}}
|
||||
</div>
|
||||
</li>
|
||||
<li
|
||||
v-if="projects.length === 0"
|
||||
class="text-xs text-slate-500 italic col-span-full"
|
||||
>
|
||||
(No projects found.)
|
||||
</li>
|
||||
<li v-if="projects.length > 0">
|
||||
<router-link :to="{ name: 'discover' }" class="cursor-pointer">
|
||||
<font-awesome
|
||||
icon="circle-right"
|
||||
class="text-blue-500 text-5xl mb-1"
|
||||
/>
|
||||
<h3
|
||||
class="text-xs text-slate-400 font-medium italic text-ellipsis whitespace-nowrap overflow-hidden"
|
||||
>
|
||||
Show All
|
||||
</h3>
|
||||
</router-link>
|
||||
</li>
|
||||
</template>
|
||||
<template v-else>
|
||||
<!-- show people (contacts) -->
|
||||
<li
|
||||
v-if="
|
||||
stepType === 'recipient' ||
|
||||
(stepType === 'giver' && isFromProjectView)
|
||||
"
|
||||
:class="{
|
||||
'cursor-pointer': !wouldCreateConflict(activeDid),
|
||||
'cursor-not-allowed opacity-50': wouldCreateConflict(activeDid)
|
||||
}"
|
||||
@click="
|
||||
!wouldCreateConflict(activeDid) &&
|
||||
(stepType === 'recipient'
|
||||
? selectRecipient({ did: activeDid, name: 'You' })
|
||||
: selectGiver({ did: activeDid, name: 'You' }))
|
||||
"
|
||||
>
|
||||
<font-awesome
|
||||
:class="{
|
||||
'text-blue-500 text-5xl mb-1': !wouldCreateConflict(activeDid),
|
||||
'text-slate-400 text-5xl mb-1': wouldCreateConflict(activeDid)
|
||||
}"
|
||||
icon="hand"
|
||||
/>
|
||||
<h3
|
||||
:class="{
|
||||
'text-xs text-blue-500 font-medium text-ellipsis whitespace-nowrap overflow-hidden': !wouldCreateConflict(activeDid),
|
||||
'text-xs text-slate-400 font-medium text-ellipsis whitespace-nowrap overflow-hidden': wouldCreateConflict(activeDid)
|
||||
}"
|
||||
>
|
||||
You
|
||||
</h3>
|
||||
</li>
|
||||
<li
|
||||
class="cursor-pointer"
|
||||
@click="
|
||||
stepType === 'recipient' ? selectRecipient() : selectGiver()
|
||||
"
|
||||
>
|
||||
<font-awesome
|
||||
icon="circle-question"
|
||||
class="text-slate-400 text-5xl mb-1"
|
||||
/>
|
||||
<h3
|
||||
class="text-xs text-slate-400 font-medium italic text-ellipsis whitespace-nowrap overflow-hidden"
|
||||
>
|
||||
(Unnamed)
|
||||
</h3>
|
||||
</li>
|
||||
<li
|
||||
v-if="allContacts.length === 0"
|
||||
class="text-xs text-slate-500 italic col-span-full"
|
||||
>
|
||||
(Add friends to see more people worthy of recognition.)
|
||||
</li>
|
||||
<li
|
||||
v-for="contact in allContacts.slice(0, 10)"
|
||||
:key="contact.did"
|
||||
:class="{
|
||||
'cursor-pointer': !wouldCreateConflict(contact.did),
|
||||
'cursor-not-allowed opacity-50': wouldCreateConflict(contact.did)
|
||||
}"
|
||||
@click="
|
||||
!wouldCreateConflict(contact.did) &&
|
||||
(stepType === 'recipient'
|
||||
? selectRecipient(contact)
|
||||
: selectGiver(contact))
|
||||
"
|
||||
>
|
||||
<div class="relative w-fit mx-auto mb-1">
|
||||
<EntityIcon
|
||||
:contact="contact"
|
||||
class="!size-[3rem] mx-auto border border-slate-300 bg-white overflow-hidden rounded-full"
|
||||
/>
|
||||
<div
|
||||
class="rounded-full bg-slate-400 absolute bottom-0 right-0 p-1 translate-x-1/3"
|
||||
>
|
||||
<font-awesome
|
||||
icon="clock"
|
||||
class="block text-white text-xs w-[1em]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<h3
|
||||
:class="{
|
||||
'text-xs font-medium text-ellipsis whitespace-nowrap overflow-hidden': !wouldCreateConflict(contact.did) && contact.name,
|
||||
'text-xs font-medium text-ellipsis whitespace-nowrap overflow-hidden text-slate-400 italic': !contact.name,
|
||||
'text-xs font-medium text-ellipsis whitespace-nowrap overflow-hidden text-slate-400': wouldCreateConflict(contact.did) && contact.name
|
||||
}"
|
||||
>
|
||||
{{ contact.name || "(No name)" }}
|
||||
</h3>
|
||||
</li>
|
||||
<li v-if="allContacts.length > 0" class="cursor-pointer">
|
||||
<router-link
|
||||
:to="{
|
||||
name: 'contact-gift',
|
||||
query: {
|
||||
stepType: stepType,
|
||||
giverEntityType: giverEntityType,
|
||||
recipientEntityType: recipientEntityType,
|
||||
...(stepType === 'giver'
|
||||
? {
|
||||
recipientProjectId: toProjectId,
|
||||
recipientProjectName: receiver?.name,
|
||||
recipientProjectImage: receiver?.image,
|
||||
recipientProjectHandleId: receiver?.handleId,
|
||||
recipientDid: receiver?.did,
|
||||
}
|
||||
: {
|
||||
giverProjectId: fromProjectId,
|
||||
giverProjectName: giver?.name,
|
||||
giverProjectImage: giver?.image,
|
||||
giverProjectHandleId: giver?.handleId,
|
||||
giverDid: giver?.did,
|
||||
}),
|
||||
fromProjectId: fromProjectId,
|
||||
toProjectId: toProjectId,
|
||||
showProjects: (showProjects || false).toString(),
|
||||
isFromProjectView: (isFromProjectView || false).toString(),
|
||||
},
|
||||
}"
|
||||
>
|
||||
<font-awesome
|
||||
icon="circle-right"
|
||||
class="text-blue-500 text-5xl mb-1"
|
||||
/>
|
||||
<h3
|
||||
class="text-xs text-slate-400 font-medium italic text-ellipsis whitespace-nowrap overflow-hidden"
|
||||
>
|
||||
Show All
|
||||
</h3>
|
||||
</router-link>
|
||||
</li>
|
||||
</template>
|
||||
</ul>
|
||||
|
||||
{{ libsUtil.UNIT_SHORT[unitCode] || unitCode }}
|
||||
</span>
|
||||
<div
|
||||
class="border border-r-0 border-slate-400 bg-slate-200 px-4 py-2"
|
||||
@click="amountInput === '0' ? null : decrement()"
|
||||
>
|
||||
<font-awesome icon="chevron-left" />
|
||||
</div>
|
||||
<input
|
||||
id="inputGivenAmount"
|
||||
v-model="amountInput"
|
||||
type="number"
|
||||
class="border border-r-0 border-slate-400 px-2 py-2 text-center w-20"
|
||||
/>
|
||||
<div
|
||||
class="rounded-r border border-slate-400 bg-slate-200 px-4 py-2"
|
||||
@click="increment()"
|
||||
>
|
||||
<font-awesome icon="chevron-right" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-4 flex justify-center">
|
||||
<span>
|
||||
<router-link
|
||||
:to="{
|
||||
name: 'gifted-details',
|
||||
query: {
|
||||
amountInput,
|
||||
description,
|
||||
giverDid: giver?.did,
|
||||
giverName: giver?.name,
|
||||
offerId,
|
||||
fulfillsProjectId: toProjectId,
|
||||
providerProjectId: fromProjectId,
|
||||
recipientDid: receiver?.did,
|
||||
recipientName: receiver?.name,
|
||||
unitCode,
|
||||
},
|
||||
}"
|
||||
class="text-blue-500"
|
||||
>
|
||||
Photo & more options ...
|
||||
</router-link>
|
||||
</span>
|
||||
</div>
|
||||
<p class="text-center mb-2 mt-6 italic">
|
||||
Sign & Send to publish to the world
|
||||
<font-awesome
|
||||
icon="circle-info"
|
||||
class="pl-2 text-blue-500 cursor-pointer"
|
||||
@click="explainData()"
|
||||
/>
|
||||
</p>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||
<button
|
||||
class="block w-full text-center text-md uppercase bg-gradient-to-b from-slate-400 to-slate-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-1.5 py-2 rounded-lg"
|
||||
class="block w-full text-center text-lg font-bold uppercase bg-gradient-to-b from-blue-400 to-blue-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-2 py-3 rounded-md"
|
||||
@click="confirm"
|
||||
>
|
||||
Sign & Send
|
||||
</button>
|
||||
<button
|
||||
class="block w-full text-center text-md uppercase bg-gradient-to-b from-slate-400 to-slate-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-1.5 py-2 rounded-md"
|
||||
@click="cancel"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Gift -->
|
||||
<div v-show="!firstStep" id="sectionGiftedGift">
|
||||
<div class="grid grid-cols-2 gap-2 mb-4">
|
||||
<!-- Giver Button -->
|
||||
<button
|
||||
v-if="
|
||||
(giverEntityType === 'person' || giverEntityType === 'project') &&
|
||||
!(isFromProjectView && giverEntityType === 'project')
|
||||
"
|
||||
class="flex-1 flex items-center gap-2 bg-slate-100 border border-slate-300 rounded-md p-2"
|
||||
@click="goBackToStep1('giver')"
|
||||
>
|
||||
<div>
|
||||
<template v-if="giverEntityType === 'project'">
|
||||
<ProjectIcon
|
||||
v-if="giver?.handleId"
|
||||
:entity-id="giver.handleId"
|
||||
:icon-size="32"
|
||||
:image-url="giver.image"
|
||||
class="rounded-full bg-white overflow-hidden !size-[2rem] object-cover"
|
||||
/>
|
||||
</template>
|
||||
<template v-else>
|
||||
<EntityIcon
|
||||
v-if="giver?.did"
|
||||
:contact="giver"
|
||||
class="rounded-full bg-white overflow-hidden !size-[2rem] object-cover"
|
||||
/>
|
||||
<font-awesome
|
||||
v-else
|
||||
icon="circle-question"
|
||||
class="text-slate-400 text-3xl"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="text-start min-w-0">
|
||||
<p class="text-xs text-slate-500 leading-1 -mb-1 uppercase">
|
||||
{{
|
||||
giverEntityType === "project"
|
||||
? "Benefited from:"
|
||||
: "Received from:"
|
||||
}}
|
||||
</p>
|
||||
<h3
|
||||
v-if="giver?.name && giver.name !== giver.did"
|
||||
class="font-semibold truncate"
|
||||
>
|
||||
{{ giver.name }}
|
||||
</h3>
|
||||
<h3
|
||||
v-if="giver?.name && giver.name === giver.did"
|
||||
class="font-semibold truncate text-slate-400 italic"
|
||||
>
|
||||
(No name)
|
||||
</h3>
|
||||
<h3
|
||||
v-else-if="!giver?.name"
|
||||
class="font-semibold truncate text-slate-400 italic"
|
||||
>
|
||||
(Unnamed)
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<p class="ms-auto text-sm text-blue-500 pe-1">
|
||||
<font-awesome icon="pen" title="Change" />
|
||||
</p>
|
||||
</button>
|
||||
<div
|
||||
v-else
|
||||
class="flex-1 flex items-center gap-2 bg-slate-100 border border-slate-300 rounded-md p-2"
|
||||
>
|
||||
<div>
|
||||
<template v-if="giverEntityType === 'project'">
|
||||
<ProjectIcon
|
||||
v-if="giver?.handleId"
|
||||
:entity-id="giver.handleId"
|
||||
:icon-size="32"
|
||||
:image-url="giver.image"
|
||||
class="rounded-full bg-white overflow-hidden !size-[2rem] object-cover"
|
||||
/>
|
||||
</template>
|
||||
<template v-else>
|
||||
<EntityIcon
|
||||
v-if="giver?.did"
|
||||
:contact="giver"
|
||||
class="rounded-full bg-white overflow-hidden !size-[2rem] object-cover"
|
||||
/>
|
||||
<font-awesome
|
||||
v-else
|
||||
icon="circle-question"
|
||||
class="text-slate-400 text-3xl"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="text-start min-w-0">
|
||||
<p class="text-xs text-slate-500 leading-1 -mb-1 uppercase">
|
||||
{{
|
||||
giverEntityType === "project"
|
||||
? "Benefited from:"
|
||||
: "Received from:"
|
||||
}}
|
||||
</p>
|
||||
<h3
|
||||
v-if="giver?.name && giver.name !== giver.did"
|
||||
class="font-semibold truncate"
|
||||
>
|
||||
{{ giver.name }}
|
||||
</h3>
|
||||
<h3
|
||||
v-if="giver?.name && giver.name === giver.did"
|
||||
class="font-semibold truncate text-slate-400 italic"
|
||||
>
|
||||
(No name)
|
||||
</h3>
|
||||
<h3
|
||||
v-else-if="!giver?.name"
|
||||
class="font-semibold truncate text-slate-400 italic"
|
||||
>
|
||||
(Unnamed)
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<p class="ms-auto text-sm text-slate-400 pe-1">
|
||||
<font-awesome icon="lock" title="Can't be changed" />
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Recipient Button -->
|
||||
<button
|
||||
v-if="recipientEntityType === 'person'"
|
||||
class="flex-1 flex items-center gap-2 bg-slate-100 border border-slate-300 rounded-md p-2"
|
||||
@click="goBackToStep1('recipient')"
|
||||
>
|
||||
<div>
|
||||
<EntityIcon
|
||||
v-if="receiver?.did"
|
||||
:contact="receiver"
|
||||
class="rounded-full bg-white overflow-hidden !size-[2rem] object-cover"
|
||||
/>
|
||||
<font-awesome
|
||||
v-else
|
||||
icon="circle-question"
|
||||
class="text-slate-400 text-3xl"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="text-start min-w-0">
|
||||
<p class="text-xs text-slate-500 leading-1 -mb-1 uppercase">
|
||||
Given to:
|
||||
</p>
|
||||
<h3
|
||||
v-if="receiver?.name && receiver.name !== receiver.did"
|
||||
class="font-semibold truncate"
|
||||
>
|
||||
{{ receiver.name }}
|
||||
</h3>
|
||||
<h3
|
||||
v-if="receiver?.name && receiver.name === receiver.did"
|
||||
class="font-semibold truncate text-slate-400 italic"
|
||||
>
|
||||
(No name)
|
||||
</h3>
|
||||
<h3
|
||||
v-else-if="!receiver?.name"
|
||||
class="font-semibold truncate text-slate-400 italic"
|
||||
>
|
||||
(Unnamed)
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<p class="ms-auto text-sm text-blue-500 pe-1">
|
||||
<font-awesome icon="pen" title="Change" />
|
||||
</p>
|
||||
</button>
|
||||
<div
|
||||
v-else-if="recipientEntityType === 'project'"
|
||||
class="flex-1 flex items-center gap-2 bg-slate-100 border border-slate-300 rounded-md p-2"
|
||||
>
|
||||
<div>
|
||||
<ProjectIcon
|
||||
v-if="receiver?.handleId"
|
||||
:entity-id="receiver.handleId"
|
||||
:icon-size="32"
|
||||
:image-url="receiver.image"
|
||||
class="rounded-full bg-white overflow-hidden !size-[2rem] object-cover"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="text-start min-w-0">
|
||||
<p class="text-xs text-slate-500 leading-1 -mb-1 uppercase">
|
||||
Given to project:
|
||||
</p>
|
||||
<h3
|
||||
v-if="receiver?.name"
|
||||
class="font-semibold truncate"
|
||||
>
|
||||
{{ receiver.name }}
|
||||
</h3>
|
||||
<h3
|
||||
v-else
|
||||
class="font-semibold truncate text-slate-400 italic"
|
||||
>
|
||||
(Unnamed)
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<p class="ms-auto text-sm text-slate-400 pe-1">
|
||||
<font-awesome icon="lock" title="Can't be changed" />
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
v-model="description"
|
||||
type="text"
|
||||
class="block w-full rounded border border-slate-400 px-3 py-2 mb-4 placeholder:italic"
|
||||
:placeholder="prompt || 'What was given?'"
|
||||
/>
|
||||
<div class="flex mb-4">
|
||||
<button
|
||||
class="rounded-s border border-e-0 border-slate-400 bg-slate-200 px-4 py-2"
|
||||
@click="amountInput === '0' ? null : decrement()"
|
||||
>
|
||||
<font-awesome icon="chevron-left" />
|
||||
</button>
|
||||
<input
|
||||
id="inputGivenAmount"
|
||||
v-model="amountInput"
|
||||
type="number"
|
||||
class="flex-1 border border-e-0 border-slate-400 px-2 py-2 text-center w-[1px]"
|
||||
/>
|
||||
<button
|
||||
class="rounded-e border border-slate-400 bg-slate-200 px-4 py-2"
|
||||
@click="increment()"
|
||||
>
|
||||
<font-awesome icon="chevron-right" />
|
||||
</button>
|
||||
|
||||
<select
|
||||
v-model="unitCode"
|
||||
class="flex-1 rounded border border-slate-400 ms-2 px-3 py-2"
|
||||
>
|
||||
<option
|
||||
v-for="(displayName, code) in unitOptions"
|
||||
:key="code"
|
||||
:value="code"
|
||||
>
|
||||
{{ displayName }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<router-link
|
||||
:to="{
|
||||
name: 'gifted-details',
|
||||
query: giftedDetailsQuery,
|
||||
}"
|
||||
class="block w-full text-center text-md uppercase bg-gradient-to-b from-slate-400 to-slate-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-1.5 py-2 rounded-lg mb-4"
|
||||
>
|
||||
Photo & more options…
|
||||
</router-link>
|
||||
<p class="text-center text-sm mb-4">
|
||||
<b class="font-medium">Sign & Send</b> to publish to the world
|
||||
<font-awesome
|
||||
icon="circle-info"
|
||||
class="fa-fw text-blue-500 text-base cursor-pointer"
|
||||
@click="explainData()"
|
||||
/>
|
||||
</p>
|
||||
|
||||
<!-- Conflict warning -->
|
||||
<div v-if="hasPersonConflict" class="mb-4 p-3 bg-red-50 border border-red-200 rounded-md">
|
||||
<p class="text-red-700 text-sm text-center">
|
||||
<font-awesome icon="exclamation-triangle" class="fa-fw mr-1" />
|
||||
Cannot record: Same person selected as both giver and recipient
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||
<button
|
||||
:disabled="hasPersonConflict"
|
||||
:class="{
|
||||
'block w-full text-center text-md uppercase font-bold bg-gradient-to-b from-blue-400 to-blue-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-1.5 py-2 rounded-lg': !hasPersonConflict,
|
||||
'block w-full text-center text-md uppercase font-bold bg-gradient-to-b from-slate-300 to-slate-500 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-slate-400 px-1.5 py-2 rounded-lg cursor-not-allowed': hasPersonConflict
|
||||
}"
|
||||
@click="confirm"
|
||||
>
|
||||
Sign & Send
|
||||
</button>
|
||||
<button
|
||||
class="block w-full text-center text-md uppercase bg-gradient-to-b from-slate-400 to-slate-700 shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.5)] text-white px-1.5 py-2 rounded-lg"
|
||||
@click="cancel"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Vue, Component, Prop, Watch } from "vue-facing-decorator";
|
||||
import { Vue, Component, Prop } from "vue-facing-decorator";
|
||||
|
||||
import { NotificationIface, USE_DEXIE_DB } from "../constants/app";
|
||||
import {
|
||||
createAndSubmitGive,
|
||||
didInfo,
|
||||
serverMessageForUser,
|
||||
getHeaders,
|
||||
} from "../libs/endorserServer";
|
||||
import * as libsUtil from "../libs/util";
|
||||
import { db, retrieveSettingsForActiveAccount } from "../db/index";
|
||||
@@ -537,38 +102,13 @@ import * as databaseUtil from "../db/databaseUtil";
|
||||
import { retrieveAccountDids } from "../libs/util";
|
||||
import { logger } from "../utils/logger";
|
||||
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
|
||||
import EntityIcon from "../components/EntityIcon.vue";
|
||||
import ProjectIcon from "../components/ProjectIcon.vue";
|
||||
import { PlanData } from "../interfaces/records";
|
||||
|
||||
@Component({
|
||||
components: {
|
||||
EntityIcon,
|
||||
ProjectIcon,
|
||||
},
|
||||
})
|
||||
@Component
|
||||
export default class GiftedDialog extends Vue {
|
||||
$notify!: (notification: NotificationIface, timeout?: number) => void;
|
||||
|
||||
@Prop() fromProjectId = "";
|
||||
@Prop() toProjectId = "";
|
||||
@Prop({ default: false }) showProjects = false;
|
||||
@Prop() isFromProjectView = false;
|
||||
|
||||
@Watch("showProjects")
|
||||
onShowProjectsChange() {
|
||||
this.updateEntityTypes();
|
||||
}
|
||||
|
||||
@Watch("fromProjectId")
|
||||
onFromProjectIdChange() {
|
||||
this.updateEntityTypes();
|
||||
}
|
||||
|
||||
@Watch("toProjectId")
|
||||
onToProjectIdChange() {
|
||||
this.updateEntityTypes();
|
||||
}
|
||||
|
||||
activeDid = "";
|
||||
allContacts: Array<Contact> = [];
|
||||
@@ -579,7 +119,6 @@ export default class GiftedDialog extends Vue {
|
||||
callbackOnSuccess?: (amount: number) => void = () => {};
|
||||
customTitle?: string;
|
||||
description = "";
|
||||
firstStep = true; // true = Step 1 (giver/recipient selection), false = Step 2 (amount/description)
|
||||
giver?: libsUtil.GiverReceiverInputInfo; // undefined means no identified giver agent
|
||||
offerId = "";
|
||||
prompt = "";
|
||||
@@ -589,80 +128,6 @@ export default class GiftedDialog extends Vue {
|
||||
|
||||
libsUtil = libsUtil;
|
||||
|
||||
projects: PlanData[] = [];
|
||||
|
||||
didInfo = didInfo;
|
||||
|
||||
// Computed property to help debug template logic
|
||||
get shouldShowProjects() {
|
||||
const result =
|
||||
(this.stepType === "giver" && this.giverEntityType === "project") ||
|
||||
(this.stepType === "recipient" && this.recipientEntityType === "project");
|
||||
return result;
|
||||
}
|
||||
|
||||
// Computed property to check if current selection would create a conflict
|
||||
get hasPersonConflict() {
|
||||
// Only check for conflicts when both entities are persons
|
||||
if (this.giverEntityType !== "person" || this.recipientEntityType !== "person") {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if giver and recipient are the same person
|
||||
if (this.giver?.did && this.receiver?.did && this.giver.did === this.receiver.did) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Computed property to check if a contact would create a conflict when selected
|
||||
wouldCreateConflict(contactDid: string) {
|
||||
// Only check for conflicts when both entities are persons
|
||||
if (this.giverEntityType !== "person" || this.recipientEntityType !== "person") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.stepType === "giver") {
|
||||
// If selecting as giver, check if it conflicts with current recipient
|
||||
return this.receiver?.did === contactDid;
|
||||
} else if (this.stepType === "recipient") {
|
||||
// If selecting as recipient, check if it conflicts with current giver
|
||||
return this.giver?.did === contactDid;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
stepType = "giver";
|
||||
giverEntityType = "person" as "person" | "project";
|
||||
recipientEntityType = "person" as "person" | "project";
|
||||
|
||||
updateEntityTypes() {
|
||||
// Reset and set entity types based on current context
|
||||
this.giverEntityType = "person";
|
||||
this.recipientEntityType = "person";
|
||||
|
||||
// Determine entity types based on current context
|
||||
if (this.showProjects) {
|
||||
// HomeView "Project" button or ProjectViewView "Given by This"
|
||||
this.giverEntityType = "project";
|
||||
this.recipientEntityType = "person";
|
||||
} else if (this.fromProjectId) {
|
||||
// ProjectViewView "Given by This" button (project is giver)
|
||||
this.giverEntityType = "project";
|
||||
this.recipientEntityType = "person";
|
||||
} else if (this.toProjectId) {
|
||||
// ProjectViewView "Given to This" button (project is recipient)
|
||||
this.giverEntityType = "person";
|
||||
this.recipientEntityType = "project";
|
||||
} else {
|
||||
// HomeView "Person" button
|
||||
this.giverEntityType = "person";
|
||||
this.recipientEntityType = "person";
|
||||
}
|
||||
}
|
||||
|
||||
async open(
|
||||
giver?: libsUtil.GiverReceiverInputInfo,
|
||||
receiver?: libsUtil.GiverReceiverInputInfo,
|
||||
@@ -675,14 +140,10 @@ export default class GiftedDialog extends Vue {
|
||||
this.giver = giver;
|
||||
this.prompt = prompt || "";
|
||||
this.receiver = receiver;
|
||||
// if we show "given to user" selection, default checkbox to true
|
||||
this.amountInput = "0";
|
||||
this.callbackOnSuccess = callbackOnSuccess;
|
||||
this.offerId = offerId || "";
|
||||
this.firstStep = !giver;
|
||||
this.stepType = "giver";
|
||||
|
||||
// Update entity types based on current props
|
||||
this.updateEntityTypes();
|
||||
|
||||
try {
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
@@ -713,16 +174,7 @@ export default class GiftedDialog extends Vue {
|
||||
this.allContacts,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
this.giverEntityType === "project" ||
|
||||
this.recipientEntityType === "project"
|
||||
) {
|
||||
await this.loadProjects();
|
||||
} else {
|
||||
// Clear projects array when not needed
|
||||
this.projects = [];
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (err: any) {
|
||||
logger.error("Error retrieving settings from database:", err);
|
||||
this.$notify(
|
||||
@@ -772,7 +224,6 @@ export default class GiftedDialog extends Vue {
|
||||
this.amountInput = "0";
|
||||
this.prompt = "";
|
||||
this.unitCode = "HUR";
|
||||
this.firstStep = true;
|
||||
}
|
||||
|
||||
async confirm() {
|
||||
@@ -814,20 +265,6 @@ export default class GiftedDialog extends Vue {
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for person conflict
|
||||
if (this.hasPersonConflict) {
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Error",
|
||||
text: "You cannot select the same person as both giver and recipient.",
|
||||
},
|
||||
3000,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.close();
|
||||
this.$notify(
|
||||
@@ -867,56 +304,24 @@ export default class GiftedDialog extends Vue {
|
||||
unitCode: string = "HUR",
|
||||
) {
|
||||
try {
|
||||
// Determine the correct parameters based on entity types
|
||||
let fromDid: string | undefined;
|
||||
let toDid: string | undefined;
|
||||
let fulfillsProjectHandleId: string | undefined;
|
||||
let providerPlanHandleId: string | undefined;
|
||||
|
||||
if (this.giverEntityType === "project" && this.recipientEntityType === "person") {
|
||||
// Project-to-person gift
|
||||
fromDid = undefined; // No person giver
|
||||
toDid = recipientDid as string; // Person recipient
|
||||
fulfillsProjectHandleId = undefined; // No project recipient
|
||||
providerPlanHandleId = this.giver?.handleId; // Project giver
|
||||
} else if (this.giverEntityType === "person" && this.recipientEntityType === "project") {
|
||||
// Person-to-project gift
|
||||
fromDid = giverDid as string; // Person giver
|
||||
toDid = undefined; // No person recipient
|
||||
fulfillsProjectHandleId = this.toProjectId; // Project recipient
|
||||
providerPlanHandleId = undefined; // No project giver
|
||||
} else if (this.giverEntityType === "project" && this.recipientEntityType === "project") {
|
||||
// Project-to-project gift
|
||||
fromDid = undefined; // No person giver
|
||||
toDid = undefined; // No person recipient
|
||||
fulfillsProjectHandleId = this.toProjectId; // Project recipient
|
||||
providerPlanHandleId = this.giver?.handleId; // Project giver
|
||||
} else {
|
||||
// Person-to-person gift
|
||||
fromDid = giverDid as string;
|
||||
toDid = recipientDid as string;
|
||||
fulfillsProjectHandleId = undefined;
|
||||
providerPlanHandleId = undefined;
|
||||
}
|
||||
|
||||
const result = await createAndSubmitGive(
|
||||
this.axios,
|
||||
this.apiServer,
|
||||
this.activeDid,
|
||||
fromDid,
|
||||
toDid,
|
||||
giverDid as string,
|
||||
recipientDid as string,
|
||||
description,
|
||||
amount,
|
||||
unitCode,
|
||||
fulfillsProjectHandleId,
|
||||
this.toProjectId,
|
||||
this.offerId,
|
||||
false,
|
||||
undefined,
|
||||
providerPlanHandleId,
|
||||
this.fromProjectId,
|
||||
);
|
||||
|
||||
if (!result.success) {
|
||||
const errorMessage = result.error;
|
||||
const errorMessage = this.getGiveCreationErrorMessage(result);
|
||||
logger.error("Error with give creation result:", result);
|
||||
this.$notify(
|
||||
{
|
||||
@@ -962,6 +367,19 @@ export default class GiftedDialog extends Vue {
|
||||
|
||||
// Helper functions for readability
|
||||
|
||||
/**
|
||||
* @param result direct response eg. ErrorResult or SuccessResult (potentially with embedded "data")
|
||||
* @returns best guess at an error message
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
getGiveCreationErrorMessage(result: any) {
|
||||
return (
|
||||
result.error?.userMessage ||
|
||||
result.error?.error ||
|
||||
result.response?.data?.error?.message
|
||||
);
|
||||
}
|
||||
|
||||
explainData() {
|
||||
this.$notify(
|
||||
{
|
||||
@@ -973,118 +391,6 @@ export default class GiftedDialog extends Vue {
|
||||
-1,
|
||||
);
|
||||
}
|
||||
|
||||
selectGiver(contact?: Contact) {
|
||||
if (contact) {
|
||||
this.giver = {
|
||||
did: contact.did,
|
||||
name: contact.name || contact.did,
|
||||
};
|
||||
} else {
|
||||
this.giver = {
|
||||
did: "",
|
||||
name: "",
|
||||
};
|
||||
}
|
||||
this.firstStep = false;
|
||||
}
|
||||
|
||||
goBackToStep1(step: string) {
|
||||
this.stepType = step;
|
||||
this.firstStep = true;
|
||||
}
|
||||
|
||||
async loadProjects() {
|
||||
try {
|
||||
const response = await fetch(this.apiServer + "/api/v2/report/plans", {
|
||||
method: "GET",
|
||||
headers: await getHeaders(this.activeDid),
|
||||
});
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new Error("Failed to load projects");
|
||||
}
|
||||
|
||||
const results = await response.json();
|
||||
if (results.data) {
|
||||
this.projects = results.data;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("Error loading projects:", error);
|
||||
this.$notify(
|
||||
{
|
||||
group: "alert",
|
||||
type: "danger",
|
||||
title: "Error",
|
||||
text: "Failed to load projects",
|
||||
},
|
||||
3000,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
selectProject(project: PlanData) {
|
||||
this.giver = {
|
||||
name: project.name,
|
||||
image: project.image,
|
||||
handleId: project.handleId,
|
||||
};
|
||||
this.receiver = {
|
||||
did: this.activeDid,
|
||||
name: "You",
|
||||
};
|
||||
this.firstStep = false;
|
||||
}
|
||||
|
||||
selectRecipient(contact?: Contact) {
|
||||
if (contact) {
|
||||
this.receiver = {
|
||||
did: contact.did,
|
||||
name: contact.name || contact.did,
|
||||
};
|
||||
} else {
|
||||
this.receiver = {
|
||||
did: "",
|
||||
name: "",
|
||||
};
|
||||
}
|
||||
this.firstStep = false;
|
||||
}
|
||||
|
||||
selectRecipientProject(project: PlanData) {
|
||||
this.receiver = {
|
||||
// no did, because it's a project
|
||||
name: project.name,
|
||||
image: project.image,
|
||||
handleId: project.handleId,
|
||||
};
|
||||
this.firstStep = false;
|
||||
}
|
||||
|
||||
// Computed property for the query parameters
|
||||
get giftedDetailsQuery() {
|
||||
return {
|
||||
amountInput: this.amountInput,
|
||||
description: this.description,
|
||||
giverDid: this.giverEntityType === "person" ? this.giver?.did : undefined,
|
||||
giverName: this.giver?.name,
|
||||
offerId: this.offerId,
|
||||
fulfillsProjectId: this.giverEntityType === "person" && this.recipientEntityType === "project"
|
||||
? this.toProjectId
|
||||
: undefined,
|
||||
providerProjectId: this.giverEntityType === "project" && this.recipientEntityType === "person"
|
||||
? this.giver?.handleId
|
||||
: this.fromProjectId,
|
||||
recipientDid: this.receiver?.did,
|
||||
recipientName: this.receiver?.name,
|
||||
unitCode: this.unitCode,
|
||||
};
|
||||
}
|
||||
|
||||
// Computed property to get unit options
|
||||
get unitOptions() {
|
||||
return this.libsUtil.UNIT_SHORT;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -227,7 +227,6 @@ export default class GivenPrompts extends Vue {
|
||||
|
||||
let someContactDbIndex = Math.floor(Math.random() * this.numContacts);
|
||||
let count = 0;
|
||||
|
||||
// as long as the index has an entry, loop
|
||||
while (
|
||||
this.shownContactDbIndices[someContactDbIndex] != null &&
|
||||
@@ -246,8 +245,9 @@ export default class GivenPrompts extends Vue {
|
||||
[someContactDbIndex],
|
||||
);
|
||||
if (result) {
|
||||
const mappedContacts = databaseUtil.mapQueryResultToValues(result);
|
||||
this.currentContact = mappedContacts[0] as unknown as Contact;
|
||||
this.currentContact = databaseUtil.mapQueryResultToValues(result)[
|
||||
someContactDbIndex
|
||||
] as unknown as Contact;
|
||||
}
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.open();
|
||||
|
||||