Compare commits
162 Commits
search-map
...
matthew-sc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
46814ebf5d | ||
|
|
19d189bc6e | ||
|
|
2c71b0a827 | ||
|
|
4745cf8536 | ||
|
|
f4856f48aa | ||
|
|
cc45d9d92e | ||
|
|
d9b168bf2a | ||
|
|
42adfd8174 | ||
|
|
b3cad2cfa1 | ||
|
|
60aa137dab | ||
|
|
e5b622f575 | ||
|
|
a559fd3318 | ||
|
|
4e7dc36ecc | ||
|
|
41142397ec | ||
|
|
fcac13eb7e | ||
|
|
a16f88743a | ||
| 0e6a9c4f89 | |||
|
|
ca22161f12 | ||
|
|
d3b80fbe47 | ||
|
|
0342c872f4 | ||
|
|
a7e65b3b49 | ||
|
|
eb7605991c | ||
| fa21660fd1 | |||
|
|
df1c1f0186 | ||
|
|
3daf1c8a5c | ||
|
|
7eefee1ea5 | ||
|
|
140c36a416 | ||
| f255ea389b | |||
| 0d343b9877 | |||
| df06100c32 | |||
|
|
ac5ddfc6f2 | ||
|
|
89b3f30466 | ||
|
|
3cb5cc096b | ||
|
|
5df560154f | ||
|
|
c1aa522e6c | ||
| a082469a01 | |||
|
|
3544d7278d | ||
|
|
d3110506ea | ||
| 8609f8458d | |||
| 8f5c34bc5f | |||
| b0d61b95ea | |||
| af7bd236a3 | |||
| d719338bcc | |||
| 6ddf2d1012 | |||
|
|
1b2d4b623a | ||
|
|
16d5c917d2 | ||
| 5976a4995e | |||
| dcd0cc4c20 | |||
| b3ca6c9d91 | |||
| e9d800f601 | |||
| b939a5e592 | |||
| aa62037fae | |||
| 722020ea86 | |||
| 96aa3f4a54 | |||
| c0c5f9842b | |||
| be27ca1855 | |||
| 92e4570672 | |||
| 820ae727ed | |||
| dbeb1c6b4b | |||
| 573e4b206a | |||
| abc05d426e | |||
| 2ea7479d75 | |||
| 9ac9713172 | |||
| 41dad3254d | |||
| 485eac59a0 | |||
|
|
73fc32b75d | ||
|
|
3d8e40e92b | ||
| 38e67f3533 | |||
| 7f63ee7c80 | |||
| 6a47f0d3e7 | |||
| fc50a9d4c6 | |||
|
|
c1f2c3951a | ||
| 9d4f726c31 | |||
| 1d7f626645 | |||
| c5228ba7ec | |||
| 6e1fcd8dee | |||
| 5bb563d694 | |||
| a3951c9d66 | |||
| aa177a9b8c | |||
| 03cb4720b8 | |||
| 297c5a2dbb | |||
|
|
92b9c9334c | ||
|
|
706182ca0c | ||
| ef3bfcdbd2 | |||
| ec1f27bab1 | |||
| 01c33069c4 | |||
| c637d39dc9 | |||
| 3e90bafbd1 | |||
|
|
d2c3e5db05 | ||
|
|
e824fcce2e | ||
|
|
f2c49872a6 | ||
|
|
229d9184b2 | ||
|
|
29908b77e3 | ||
|
|
16cad04e5c | ||
|
|
e4f859a116 | ||
|
|
7f17a3d9c7 | ||
|
|
2d4d9691ca | ||
|
|
63575b36ed | ||
|
|
2eb46367bc | ||
|
|
cea0456148 | ||
|
|
6f5db13a49 | ||
|
|
068662625d | ||
|
|
23627835f9 | ||
|
|
f1ba6f9231 | ||
|
|
137fce3e30 | ||
|
|
7166dadbc0 | ||
|
|
bc274bdf7f | ||
|
|
082f8c0126 | ||
|
|
fd09c7e426 | ||
|
|
be40643379 | ||
|
|
835a270e65 | ||
|
|
13682a1930 | ||
|
|
669a66c24c | ||
|
|
13505b539e | ||
|
|
07ac340733 | ||
|
|
ba2b2fc543 | ||
| 21184e7625 | |||
| 8d1511e38f | |||
|
|
b18112b869 | ||
|
|
a228a9b1c0 | ||
|
|
1560ff0829 | ||
| 7de4125eb7 | |||
|
|
81d4f0c762 | ||
| 4c1b4fe651 | |||
|
|
e63541ef53 | ||
| 0bfc18c385 | |||
|
|
35f5df6b6b | ||
|
|
0f1ac2b230 | ||
| 3c0bdeaed3 | |||
| 11f2527b04 | |||
| 5d8175aeeb | |||
| b6b95cb0d0 | |||
| 655c5188a4 | |||
| 8b7451330f | |||
| b8fbc3f7a6 | |||
| 92dadba1cb | |||
| 3a6f585de0 | |||
| 2647c5a77d | |||
|
|
682fceb1c6 | ||
|
|
e0013008b4 | ||
| 0674d98670 | |||
|
|
ee441d1aea | ||
|
|
75f6e99200 | ||
|
|
52c9e57ef4 | ||
| 603823d808 | |||
| 5f24f4975d | |||
| 5057d7d07f | |||
| 946e88d903 | |||
|
|
cbfb1ebf57 | ||
| a38934e38d | |||
| a3bdcfd168 | |||
| 83771caee1 | |||
| da35b225cd | |||
| 8c3920e108 | |||
| 54f269054f | |||
|
|
574520d9b3 | ||
| 6556eb55a3 | |||
| 634e2bb2fb | |||
|
|
988244b7ae | ||
|
|
4b355a5448 | ||
|
|
b511f9cd24 | ||
|
|
579cecbe6e |
153
.cursor/rules/absurd-sql.mdc
Normal file
153
.cursor/rules/absurd-sql.mdc
Normal file
@@ -0,0 +1,153 @@
|
||||
---
|
||||
description:
|
||||
globs:
|
||||
alwaysApply: true
|
||||
---
|
||||
# Absurd SQL - Cursor Development Guide
|
||||
|
||||
## Project Overview
|
||||
Absurd SQL is a backend implementation for sql.js that enables persistent SQLite databases in the browser by using IndexedDB as a block storage system. This guide provides rules and best practices for developing with this project in Cursor.
|
||||
|
||||
## Project Structure
|
||||
```
|
||||
absurd-sql/
|
||||
├── src/ # Source code
|
||||
├── dist/ # Built files
|
||||
├── package.json # Dependencies and scripts
|
||||
├── rollup.config.js # Build configuration
|
||||
└── jest.config.js # Test configuration
|
||||
```
|
||||
|
||||
## Development Rules
|
||||
|
||||
### 1. Worker Thread Requirements
|
||||
- All SQL operations MUST be performed in a worker thread
|
||||
- Main thread should only handle worker initialization and communication
|
||||
- Never block the main thread with database operations
|
||||
|
||||
### 2. Code Organization
|
||||
- Keep worker code in separate files (e.g., `*.worker.js`)
|
||||
- Use ES modules for imports/exports
|
||||
- Follow the project's existing module structure
|
||||
|
||||
### 3. Required Headers
|
||||
When developing locally or deploying, ensure these headers are set:
|
||||
```
|
||||
Cross-Origin-Opener-Policy: same-origin
|
||||
Cross-Origin-Embedder-Policy: require-corp
|
||||
```
|
||||
|
||||
### 4. Browser Compatibility
|
||||
- Primary target: Modern browsers with SharedArrayBuffer support
|
||||
- Fallback mode: Safari (with limitations)
|
||||
- Always test in both modes
|
||||
|
||||
### 5. Database Configuration
|
||||
Recommended database settings:
|
||||
```sql
|
||||
PRAGMA journal_mode=MEMORY;
|
||||
PRAGMA page_size=8192; -- Optional, but recommended
|
||||
```
|
||||
|
||||
### 6. Development Workflow
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
yarn add @jlongster/sql.js absurd-sql
|
||||
```
|
||||
|
||||
2. Development commands:
|
||||
- `yarn build` - Build the project
|
||||
- `yarn jest` - Run tests
|
||||
- `yarn serve` - Start development server
|
||||
|
||||
### 7. Testing Guidelines
|
||||
- Write tests for both SharedArrayBuffer and fallback modes
|
||||
- Use Jest for testing
|
||||
- Include performance benchmarks for critical operations
|
||||
|
||||
### 8. Performance Considerations
|
||||
- Use bulk operations when possible
|
||||
- Monitor read/write performance
|
||||
- Consider using transactions for multiple operations
|
||||
- Avoid unnecessary database connections
|
||||
|
||||
### 9. Error Handling
|
||||
- Implement proper error handling for:
|
||||
- Worker initialization failures
|
||||
- Database connection issues
|
||||
- Concurrent access conflicts (in fallback mode)
|
||||
- Storage quota exceeded scenarios
|
||||
|
||||
### 10. Security Best Practices
|
||||
- Never expose database operations directly to the client
|
||||
- Validate all SQL queries
|
||||
- Implement proper access controls
|
||||
- Handle sensitive data appropriately
|
||||
|
||||
### 11. Code Style
|
||||
- Follow ESLint configuration
|
||||
- Use async/await for asynchronous operations
|
||||
- Document complex database operations
|
||||
- Include comments for non-obvious optimizations
|
||||
|
||||
### 12. Debugging
|
||||
- Use `jest-debug` for debugging tests
|
||||
- Monitor IndexedDB usage in browser dev tools
|
||||
- Check worker communication in console
|
||||
- Use performance monitoring tools
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Worker Initialization
|
||||
```javascript
|
||||
// Main thread
|
||||
import { initBackend } from 'absurd-sql/dist/indexeddb-main-thread';
|
||||
|
||||
function init() {
|
||||
let worker = new Worker(new URL('./index.worker.js', import.meta.url));
|
||||
initBackend(worker);
|
||||
}
|
||||
```
|
||||
|
||||
### Database Setup
|
||||
```javascript
|
||||
// Worker thread
|
||||
import initSqlJs from '@jlongster/sql.js';
|
||||
import { SQLiteFS } from 'absurd-sql';
|
||||
import IndexedDBBackend from 'absurd-sql/dist/indexeddb-backend';
|
||||
|
||||
async function setupDatabase() {
|
||||
let SQL = await initSqlJs({ locateFile: file => file });
|
||||
let sqlFS = new SQLiteFS(SQL.FS, new IndexedDBBackend());
|
||||
SQL.register_for_idb(sqlFS);
|
||||
|
||||
SQL.FS.mkdir('/sql');
|
||||
SQL.FS.mount(sqlFS, {}, '/sql');
|
||||
|
||||
return new SQL.Database('/sql/db.sqlite', { filename: true });
|
||||
}
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
1. SharedArrayBuffer not available
|
||||
- Check COOP/COEP headers
|
||||
- Verify browser support
|
||||
- Test fallback mode
|
||||
|
||||
2. Worker initialization failures
|
||||
- Check file paths
|
||||
- Verify module imports
|
||||
- Check browser console for errors
|
||||
|
||||
3. Performance issues
|
||||
- Monitor IndexedDB usage
|
||||
- Check for unnecessary operations
|
||||
- Verify transaction usage
|
||||
|
||||
## Resources
|
||||
- [Project Demo](https://priceless-keller-d097e5.netlify.app/)
|
||||
- [Example Project](https://github.com/jlongster/absurd-example-project)
|
||||
- [Blog Post](https://jlongster.com/future-sql-web)
|
||||
- [SQL.js Documentation](https://github.com/sql-js/sql.js/)
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
description:
|
||||
globs:
|
||||
alwaysApply: true
|
||||
alwaysApply: false
|
||||
---
|
||||
# Camera Implementation Documentation
|
||||
|
||||
|
||||
6
.cursor/rules/development_aids.mdc
Normal file
6
.cursor/rules/development_aids.mdc
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
description:
|
||||
globs:
|
||||
alwaysApply: true
|
||||
---
|
||||
use the system date function to understand the proper date and time for all interactions.
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
# iOS doesn't like spaces in the app title.
|
||||
TIME_SAFARI_APP_TITLE="TimeSafari_Dev"
|
||||
VITE_APP_SERVER=http://localhost:3000
|
||||
VITE_APP_SERVER=http://localhost:8080
|
||||
# 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
|
||||
# Using shared server by default to ease setup, which works for shared test users.
|
||||
VITE_DEFAULT_IMAGE_API_SERVER=https://test-image-api.timesafari.app
|
||||
VITE_DEFAULT_PARTNER_API_SERVER=http://localhost:3000
|
||||
#VITE_DEFAULT_PUSH_SERVER... can't be set up with localhost domain
|
||||
VITE_PASSKEYS_ENABLED=true
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
# Admin DID credentials
|
||||
ADMIN_DID=did:ethr:0x0000694B58C2cC69658993A90D3840C560f2F51F
|
||||
ADMIN_PRIVATE_KEY=2b6472c026ec2aa2c4235c994a63868fc9212d18b58f6cbfe861b52e71330f5b
|
||||
|
||||
# API Configuration
|
||||
ENDORSER_API_URL=https://test-api.endorser.ch/api/v2/claim
|
||||
@@ -9,3 +9,4 @@ VITE_DEFAULT_ENDORSER_API_SERVER=https://api.endorser.ch
|
||||
|
||||
VITE_DEFAULT_IMAGE_API_SERVER=https://image-api.timesafari.app
|
||||
VITE_DEFAULT_PARTNER_API_SERVER=https://partner-api.endorser.ch
|
||||
VITE_DEFAULT_PUSH_SERVER=https://timesafari.app
|
||||
|
||||
@@ -9,4 +9,5 @@ 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
|
||||
|
||||
@@ -4,6 +4,12 @@ module.exports = {
|
||||
node: true,
|
||||
es2022: true,
|
||||
},
|
||||
ignorePatterns: [
|
||||
'node_modules/',
|
||||
'dist/',
|
||||
'dist-electron/',
|
||||
'*.d.ts'
|
||||
],
|
||||
extends: [
|
||||
"plugin:vue/vue3-recommended",
|
||||
"eslint:recommended",
|
||||
|
||||
71
BUILDING.md
71
BUILDING.md
@@ -9,19 +9,6 @@ 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
|
||||
@@ -84,7 +71,7 @@ Install dependencies:
|
||||
* 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_PASSKEYS_ENABLED=true npm run build
|
||||
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:
|
||||
@@ -241,7 +228,9 @@ docker run -d \
|
||||
1. Build the electron app in production mode:
|
||||
|
||||
```bash
|
||||
npm run build:electron-prod
|
||||
npm run build:web
|
||||
npm run build:electron
|
||||
npm run electron:build-mac
|
||||
```
|
||||
|
||||
2. Package the Electron app for macOS:
|
||||
@@ -324,6 +313,32 @@ 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 XCode 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
|
||||
```
|
||||
|
||||
```bash
|
||||
cd ios/App
|
||||
pod install
|
||||
```
|
||||
|
||||
1. Build the web assets:
|
||||
|
||||
```bash
|
||||
@@ -332,6 +347,7 @@ Prerequisites: macOS with Xcode installed
|
||||
npm run build:capacitor
|
||||
```
|
||||
|
||||
|
||||
2. Update iOS project with latest build:
|
||||
|
||||
```bash
|
||||
@@ -355,10 +371,10 @@ Prerequisites: macOS with Xcode installed
|
||||
|
||||
```
|
||||
cd ios/App
|
||||
xcrun agvtool new-version 15
|
||||
xcrun agvtool new-version 25
|
||||
# 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
|
||||
cat App.xcodeproj/project.pbxproj | sed "s/MARKETING_VERSION = .*;/MARKETING_VERSION = 0.5.1;/g" > temp
|
||||
mv temp App.xcodeproj/project.pbxproj
|
||||
cd -
|
||||
```
|
||||
@@ -371,28 +387,25 @@ 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
|
||||
|
||||
* Under "General" renamed a bunch of things to "Time Safari"
|
||||
* Choose Product -> Destination -> Build Any iOS
|
||||
* Someday: Under "General" we want to rename a bunch of things to "Time Safari"
|
||||
* Choose Product -> Destination -> Any iOS Device
|
||||
* Choose Product -> Archive
|
||||
* This will trigger a build and take time, needing user's "login" keychain password which is just their login password, repeatedly.
|
||||
* This will trigger a build and take time, needing user's "login" keychain password (user's 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 SDK installed
|
||||
Prerequisites: Android Studio with Java SDK installed
|
||||
|
||||
1. Build the web assets:
|
||||
|
||||
@@ -447,7 +460,9 @@ Prerequisites: Android Studio with 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
|
||||
@@ -460,6 +475,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.
|
||||
|
||||
|
||||
## First-time Android Configuration for deep links
|
||||
|
||||
|
||||
538
CEFPython-Survey.md
Normal file
538
CEFPython-Survey.md
Normal file
@@ -0,0 +1,538 @@
|
||||
# CEFPython Implementation Survey for TimeSafari
|
||||
|
||||
**Author:** Matthew Raymer
|
||||
**Date:** December 2025
|
||||
**Project:** TimeSafari Cross-Platform Desktop Implementation
|
||||
|
||||
## Executive Summary
|
||||
|
||||
This survey evaluates implementing CEFPython as an additional desktop platform for TimeSafari, with full integration into the existing migration system used by Capacitor and native web platforms.
|
||||
|
||||
### Key Findings
|
||||
|
||||
**Feasibility:** ✅ **Highly Feasible** - CEFPython can integrate seamlessly with TimeSafari's existing architecture
|
||||
|
||||
**Migration System Compatibility:** ✅ **Full Compatibility** - Can use the exact same `migration.ts` system as Capacitor and web
|
||||
|
||||
**Performance:** ✅ **Excellent** - Native Python backend with Chromium rendering engine
|
||||
|
||||
**Security:** ✅ **Strong** - Chromium's security model with Python backend isolation
|
||||
|
||||
---
|
||||
|
||||
## 1. Architecture Overview
|
||||
|
||||
### 1.1 Current Platform Architecture
|
||||
|
||||
TimeSafari uses a sophisticated cross-platform architecture with shared codebase and platform-specific implementations:
|
||||
|
||||
```typescript
|
||||
src/
|
||||
├── main.common.ts # Shared initialization
|
||||
├── main.web.ts # Web/PWA entry point
|
||||
├── main.capacitor.ts # Mobile entry point
|
||||
├── main.electron.ts # Electron entry point
|
||||
├── main.pywebview.ts # PyWebView entry point
|
||||
├── main.cefpython.ts # NEW: CEFPython entry point
|
||||
├── services/
|
||||
│ ├── PlatformService.ts # Platform abstraction interface
|
||||
│ ├── PlatformServiceFactory.ts
|
||||
│ └── platforms/
|
||||
│ ├── WebPlatformService.ts
|
||||
│ ├── CapacitorPlatformService.ts
|
||||
│ ├── ElectronPlatformService.ts
|
||||
│ ├── PyWebViewPlatformService.ts
|
||||
│ └── CEFPythonPlatformService.ts # NEW
|
||||
└── cefpython/ # NEW: CEFPython backend
|
||||
├── main.py
|
||||
├── handlers/
|
||||
│ ├── database.py # SQLite with migration support
|
||||
│ ├── crypto.py # Cryptographic operations
|
||||
│ └── api.py # API server integration
|
||||
└── bridge/
|
||||
└── javascript_bridge.py # JS-Python communication
|
||||
```
|
||||
|
||||
### 1.2 Migration System Integration
|
||||
|
||||
**Key Insight:** CEFPython can use the exact same migration system as Capacitor and web platforms:
|
||||
|
||||
```typescript
|
||||
// src/main.cefpython.ts - CEFPython entry point
|
||||
import { initializeApp } from "./main.common";
|
||||
import { runMigrations } from "./db-sql/migration";
|
||||
import { CEFPythonPlatformService } from "./services/platforms/CEFPythonPlatformService";
|
||||
|
||||
const app = initializeApp();
|
||||
|
||||
// Initialize CEFPython platform service
|
||||
const platformService = new CEFPythonPlatformService();
|
||||
|
||||
// Run migrations using the same system as Capacitor
|
||||
async function initializeDatabase() {
|
||||
const sqlExec = (sql: string) => platformService.dbExecute(sql);
|
||||
const sqlQuery = (sql: string) => platformService.dbQuery(sql);
|
||||
const extractMigrationNames = (result: any) => {
|
||||
const names = result.values?.map((row: any) => row.name) || [];
|
||||
return new Set(names);
|
||||
};
|
||||
|
||||
await runMigrations(sqlExec, sqlQuery, extractMigrationNames);
|
||||
}
|
||||
|
||||
// Initialize database before mounting app
|
||||
initializeDatabase().then(() => {
|
||||
app.mount("#app");
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Python Backend Implementation
|
||||
|
||||
### 2.1 Database Handler with Migration Support
|
||||
|
||||
```python
|
||||
# src/cefpython/handlers/database.py
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Any
|
||||
|
||||
class DatabaseHandler:
|
||||
def __init__(self):
|
||||
self.db_path = self._get_db_path()
|
||||
self.connection = sqlite3.connect(str(self.db_path))
|
||||
self.connection.row_factory = sqlite3.Row
|
||||
|
||||
# Configure for better performance
|
||||
self.connection.execute("PRAGMA journal_mode=WAL;")
|
||||
self.connection.execute("PRAGMA synchronous=NORMAL;")
|
||||
|
||||
def query(self, sql: str, params: List[Any] = None) -> Dict[str, Any]:
|
||||
"""Execute SQL query and return results in Capacitor-compatible format"""
|
||||
cursor = self.connection.cursor()
|
||||
|
||||
if params:
|
||||
cursor.execute(sql, params)
|
||||
else:
|
||||
cursor.execute(sql)
|
||||
|
||||
if sql.strip().upper().startswith('SELECT'):
|
||||
columns = [description[0] for description in cursor.description]
|
||||
rows = []
|
||||
for row in cursor.fetchall():
|
||||
rows.append(dict(zip(columns, row)))
|
||||
return {'values': rows} # Match Capacitor format
|
||||
else:
|
||||
self.connection.commit()
|
||||
return {'affected_rows': cursor.rowcount}
|
||||
|
||||
def execute(self, sql: string, params: List[Any] = None) -> Dict[str, Any]:
|
||||
"""Execute SQL statement (for INSERT, UPDATE, DELETE, CREATE)"""
|
||||
cursor = self.connection.cursor()
|
||||
|
||||
if params:
|
||||
cursor.execute(sql, params)
|
||||
else:
|
||||
cursor.execute(sql)
|
||||
|
||||
self.connection.commit()
|
||||
|
||||
return {
|
||||
'changes': {
|
||||
'changes': cursor.rowcount,
|
||||
'lastId': cursor.lastrowid
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2.2 Platform Service Implementation
|
||||
|
||||
```typescript
|
||||
// src/services/platforms/CEFPythonPlatformService.ts
|
||||
import { PlatformService } from '../PlatformService';
|
||||
import { runMigrations } from '@/db-sql/migration';
|
||||
|
||||
export class CEFPythonPlatformService implements PlatformService {
|
||||
private bridge: any;
|
||||
|
||||
constructor() {
|
||||
this.bridge = (window as any).cefBridge;
|
||||
if (!this.bridge) {
|
||||
throw new Error('CEFPython bridge not available');
|
||||
}
|
||||
}
|
||||
|
||||
// Database operations using the same interface as Capacitor
|
||||
async dbQuery(sql: string, params?: any[]): Promise<any> {
|
||||
const result = await this.bridge.call('database', 'query', sql, params || []);
|
||||
return result;
|
||||
}
|
||||
|
||||
async dbExecute(sql: string, params?: any[]): Promise<any> {
|
||||
const result = await this.bridge.call('database', 'execute', sql, params || []);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Migration system integration
|
||||
async runMigrations(): Promise<void> {
|
||||
const sqlExec: (sql: string) => Promise<any> = this.dbExecute.bind(this);
|
||||
const sqlQuery: (sql: string) => Promise<any> = this.dbQuery.bind(this);
|
||||
const extractMigrationNames: (result: any) => Set<string> = (result) => {
|
||||
const names = result.values?.map((row: any) => row.name) || [];
|
||||
return new Set(names);
|
||||
};
|
||||
|
||||
await runMigrations(sqlExec, sqlQuery, extractMigrationNames);
|
||||
}
|
||||
|
||||
// Platform detection
|
||||
isCEFPython(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
getCapabilities(): PlatformCapabilities {
|
||||
return {
|
||||
hasCamera: true,
|
||||
hasFileSystem: true,
|
||||
hasNotifications: true,
|
||||
hasSQLite: true,
|
||||
hasCrypto: true
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Migration System Compatibility
|
||||
|
||||
### 3.1 Key Advantage
|
||||
|
||||
**CEFPython can use the exact same migration system as Capacitor:**
|
||||
|
||||
```typescript
|
||||
// Both Capacitor and CEFPython use the same migration.ts
|
||||
import { runMigrations } from '@/db-sql/migration';
|
||||
|
||||
// Capacitor implementation
|
||||
const sqlExec: (sql: string) => Promise<capSQLiteChanges> = this.db.execute.bind(this.db);
|
||||
const sqlQuery: (sql: string) => Promise<DBSQLiteValues> = this.db.query.bind(this.db);
|
||||
|
||||
// CEFPython implementation
|
||||
const sqlExec: (sql: string) => Promise<any> = this.dbExecute.bind(this);
|
||||
const sqlQuery: (sql: string) => Promise<any> = this.dbQuery.bind(this);
|
||||
|
||||
// Both use the same migration runner
|
||||
await runMigrations(sqlExec, sqlQuery, extractMigrationNames);
|
||||
```
|
||||
|
||||
### 3.2 Database Format Compatibility
|
||||
|
||||
The Python database handler returns data in the same format as Capacitor:
|
||||
|
||||
```python
|
||||
# Python returns Capacitor-compatible format
|
||||
def query(self, sql: str, params: List[Any] = None) -> Dict[str, Any]:
|
||||
# ... execute query ...
|
||||
return {
|
||||
'values': [
|
||||
{'name': '001_initial', 'executed_at': '2025-01-01'},
|
||||
{'name': '002_add_contacts', 'executed_at': '2025-01-02'}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
This matches the Capacitor format:
|
||||
```typescript
|
||||
// Capacitor returns same format
|
||||
const result = await this.db.query("SELECT name FROM migrations");
|
||||
// result = { values: [{ name: '001_initial' }, { name: '002_add_contacts' }] }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Build Configuration
|
||||
|
||||
### 4.1 Vite Configuration
|
||||
|
||||
```typescript
|
||||
// vite.config.cefpython.mts
|
||||
import { defineConfig } from 'vite';
|
||||
import { createBuildConfig } from './vite.config.common.mts';
|
||||
|
||||
export default defineConfig({
|
||||
...createBuildConfig('cefpython'),
|
||||
|
||||
define: {
|
||||
'process.env.VITE_PLATFORM': JSON.stringify('cefpython'),
|
||||
'process.env.VITE_PWA_ENABLED': JSON.stringify(false),
|
||||
__IS_MOBILE__: JSON.stringify(false),
|
||||
__USE_QR_READER__: JSON.stringify(true)
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### 4.2 Package.json Scripts
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"build:cefpython": "vite build --config vite.config.cefpython.mts",
|
||||
"dev:cefpython": "concurrently \"npm run dev:web\" \"python src/cefpython/main.py --dev\"",
|
||||
"test:cefpython": "python -m pytest tests/cefpython/"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4.3 Python Requirements
|
||||
|
||||
```txt
|
||||
# requirements-cefpython.txt
|
||||
cefpython3>=66.1
|
||||
cryptography>=3.4.0
|
||||
requests>=2.25.0
|
||||
pyinstaller>=4.0
|
||||
pytest>=6.0.0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Platform Service Factory Integration
|
||||
|
||||
### 5.1 Updated Factory
|
||||
|
||||
```typescript
|
||||
// src/services/PlatformServiceFactory.ts
|
||||
import { CEFPythonPlatformService } from './platforms/CEFPythonPlatformService';
|
||||
|
||||
export function createPlatformService(platform: string): PlatformService {
|
||||
switch (platform) {
|
||||
case 'web':
|
||||
return new WebPlatformService();
|
||||
case 'capacitor':
|
||||
return new CapacitorPlatformService();
|
||||
case 'electron':
|
||||
return new ElectronPlatformService();
|
||||
case 'pywebview':
|
||||
return new PyWebViewPlatformService();
|
||||
case 'cefpython':
|
||||
return new CEFPythonPlatformService(); // NEW
|
||||
default:
|
||||
throw new Error(`Unsupported platform: ${platform}`);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Performance and Security Analysis
|
||||
|
||||
### 6.1 Performance Comparison
|
||||
|
||||
| Metric | Electron | PyWebView | CEFPython | Notes |
|
||||
|--------|----------|-----------|-----------|-------|
|
||||
| **Memory Usage** | 150-200MB | 80-120MB | 100-150MB | CEFPython more efficient than Electron |
|
||||
| **Startup Time** | 3-5s | 2-3s | 2-4s | Similar to PyWebView |
|
||||
| **Database Performance** | Good | Good | Excellent | Native SQLite |
|
||||
| **Crypto Performance** | Good | Good | Excellent | Native Python crypto |
|
||||
| **Bundle Size** | 120-150MB | 50-80MB | 80-120MB | Smaller than Electron |
|
||||
|
||||
### 6.2 Security Features
|
||||
|
||||
```python
|
||||
# src/cefpython/utils/security.py
|
||||
class SecurityManager:
|
||||
def __init__(self):
|
||||
self.blocked_domains = set(['malicious-site.com'])
|
||||
self.allowed_schemes = {'https', 'http', 'file'}
|
||||
|
||||
def validate_network_access(self, url: str) -> bool:
|
||||
"""Validate if network access is allowed"""
|
||||
from urllib.parse import urlparse
|
||||
parsed = urlparse(url)
|
||||
|
||||
# Check blocked domains
|
||||
if parsed.hostname in self.blocked_domains:
|
||||
return False
|
||||
|
||||
# Allow HTTPS only for external domains
|
||||
if parsed.scheme != 'https' and parsed.hostname != 'localhost':
|
||||
return False
|
||||
|
||||
return True
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Migration Strategy
|
||||
|
||||
### 7.1 Phase 1: Foundation (Week 1-2)
|
||||
|
||||
**Objectives:**
|
||||
- Set up CEFPython development environment
|
||||
- Create basic application structure
|
||||
- Implement database handler with migration support
|
||||
- Establish JavaScript-Python bridge
|
||||
|
||||
**Deliverables:**
|
||||
- [ ] Basic CEFPython application that loads TimeSafari web app
|
||||
- [ ] Database handler with SQLite integration
|
||||
- [ ] Migration system integration
|
||||
- [ ] JavaScript bridge for communication
|
||||
|
||||
### 7.2 Phase 2: Platform Integration (Week 3-4)
|
||||
|
||||
**Objectives:**
|
||||
- Implement CEFPython platform service
|
||||
- Integrate with existing migration system
|
||||
- Test database operations with real data
|
||||
- Validate migration compatibility
|
||||
|
||||
**Deliverables:**
|
||||
- [ ] CEFPython platform service implementation
|
||||
- [ ] Migration system integration
|
||||
- [ ] Database compatibility testing
|
||||
- [ ] Performance benchmarking
|
||||
|
||||
### 7.3 Phase 3: Feature Integration (Week 5-6)
|
||||
|
||||
**Objectives:**
|
||||
- Integrate with existing platform features
|
||||
- Implement API server integration
|
||||
- Add security features
|
||||
- Test with real user workflows
|
||||
|
||||
**Deliverables:**
|
||||
- [ ] Full feature compatibility
|
||||
- [ ] API integration
|
||||
- [ ] Security implementation
|
||||
- [ ] User workflow testing
|
||||
|
||||
### 7.4 Phase 4: Polish and Distribution (Week 7-8)
|
||||
|
||||
**Objectives:**
|
||||
- Optimize performance
|
||||
- Add build and distribution scripts
|
||||
- Create documentation
|
||||
- Prepare for release
|
||||
|
||||
**Deliverables:**
|
||||
- [ ] Performance optimization
|
||||
- [ ] Build automation
|
||||
- [ ] Documentation
|
||||
- [ ] Release-ready application
|
||||
|
||||
---
|
||||
|
||||
## 8. Risk Assessment
|
||||
|
||||
### 8.1 Technical Risks
|
||||
|
||||
| Risk | Probability | Impact | Mitigation |
|
||||
|------|-------------|--------|------------|
|
||||
| **CEFPython compatibility issues** | Medium | High | Use stable CEFPython version, test thoroughly |
|
||||
| **Migration system integration** | Low | High | Follow existing patterns, extensive testing |
|
||||
| **Performance issues** | Low | Medium | Benchmark early, optimize as needed |
|
||||
| **Security vulnerabilities** | Low | High | Implement security manager, regular audits |
|
||||
|
||||
### 8.2 Development Risks
|
||||
|
||||
| Risk | Probability | Impact | Mitigation |
|
||||
|------|-------------|--------|------------|
|
||||
| **Python/CEF knowledge gap** | Medium | Medium | Training, documentation, pair programming |
|
||||
| **Integration complexity** | Medium | Medium | Incremental development, extensive testing |
|
||||
| **Build system complexity** | Low | Medium | Automated build scripts, CI/CD |
|
||||
|
||||
---
|
||||
|
||||
## 9. Success Metrics
|
||||
|
||||
### 9.1 Technical Metrics
|
||||
|
||||
- [ ] **Migration Compatibility:** 100% compatibility with existing migration system
|
||||
- [ ] **Performance:** < 150MB memory usage, < 4s startup time
|
||||
- [ ] **Security:** Pass security audit, no critical vulnerabilities
|
||||
- [ ] **Reliability:** 99%+ uptime, < 1% error rate
|
||||
|
||||
### 9.2 Development Metrics
|
||||
|
||||
- [ ] **Code Quality:** 90%+ test coverage, < 5% code duplication
|
||||
- [ ] **Documentation:** Complete API documentation, user guides
|
||||
- [ ] **Build Automation:** Automated builds, CI/CD pipeline
|
||||
- [ ] **Release Readiness:** Production-ready application
|
||||
|
||||
---
|
||||
|
||||
## 10. Conclusion
|
||||
|
||||
### 10.1 Recommendation
|
||||
|
||||
**✅ PROCEED WITH IMPLEMENTATION**
|
||||
|
||||
CEFPython provides an excellent opportunity to add a robust desktop platform to TimeSafari with:
|
||||
|
||||
1. **Full Migration System Compatibility:** Can use the exact same migration system as Capacitor and web
|
||||
2. **Native Performance:** Python backend with Chromium rendering
|
||||
3. **Security:** Chromium's security model with Python backend isolation
|
||||
4. **Development Efficiency:** Follows established patterns and architecture
|
||||
|
||||
### 10.2 Implementation Priority
|
||||
|
||||
**High Priority:**
|
||||
- Database handler with migration support
|
||||
- JavaScript-Python bridge
|
||||
- Platform service integration
|
||||
- Basic application structure
|
||||
|
||||
**Medium Priority:**
|
||||
- Crypto handler integration
|
||||
- API server integration
|
||||
- Security features
|
||||
- Performance optimization
|
||||
|
||||
**Low Priority:**
|
||||
- Advanced features
|
||||
- Build automation
|
||||
- Documentation
|
||||
- Distribution packaging
|
||||
|
||||
### 10.3 Timeline
|
||||
|
||||
**Total Duration:** 8 weeks (2 months)
|
||||
**Team Size:** 1-2 developers
|
||||
**Risk Level:** Medium
|
||||
**Confidence:** 85%
|
||||
|
||||
The implementation leverages TimeSafari's existing architecture and migration system, making it a natural addition to the platform ecosystem while providing users with a high-performance desktop option.
|
||||
|
||||
---
|
||||
|
||||
## 11. Next Steps
|
||||
|
||||
1. **Immediate Actions:**
|
||||
- Set up development environment
|
||||
- Create basic CEFPython application structure
|
||||
- Implement database handler with migration support
|
||||
|
||||
2. **Week 1-2:**
|
||||
- Complete foundation implementation
|
||||
- Test migration system integration
|
||||
- Validate database operations
|
||||
|
||||
3. **Week 3-4:**
|
||||
- Implement platform service
|
||||
- Integrate with existing features
|
||||
- Begin performance testing
|
||||
|
||||
4. **Week 5-6:**
|
||||
- Complete feature integration
|
||||
- Security implementation
|
||||
- User workflow testing
|
||||
|
||||
5. **Week 7-8:**
|
||||
- Performance optimization
|
||||
- Build automation
|
||||
- Documentation and release preparation
|
||||
|
||||
This implementation will provide TimeSafari users with a robust, secure, and high-performance desktop application that seamlessly integrates with the existing ecosystem.
|
||||
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
|
||||
|
||||
## [0.4.7]
|
||||
### Fixed
|
||||
- Cameras everywhere
|
||||
### Changed
|
||||
- IndexedDB -> SQLite
|
||||
|
||||
|
||||
## [0.4.5] - 2025.02.23
|
||||
### Added
|
||||
- Total amounts of gives on project page
|
||||
|
||||
1456
GiftedDialog-Complete-Documentation.md
Normal file
1456
GiftedDialog-Complete-Documentation.md
Normal file
File diff suppressed because it is too large
Load Diff
469
GiftedDialog-Decomposition-Plan.md
Normal file
469
GiftedDialog-Decomposition-Plan.md
Normal file
@@ -0,0 +1,469 @@
|
||||
# GiftedDialog Component Decomposition Plan
|
||||
|
||||
## Overview
|
||||
|
||||
This document outlines a comprehensive plan to refactor the GiftedDialog component by breaking it into smaller, more manageable sub-components. This approach will improve maintainability, testability, and reusability while preparing the codebase for future Pinia integration.
|
||||
|
||||
## Current State Analysis
|
||||
|
||||
The GiftedDialog component (1060 lines) is a complex Vue component that handles:
|
||||
|
||||
- **Two-step wizard UI**: Entity selection → Gift details
|
||||
- **Multiple entity types**: Person/Project as giver/recipient
|
||||
- **Complex conditional rendering**: Based on context and entity types
|
||||
- **Form validation and submission**: Gift recording with API integration
|
||||
- **State management**: UI flow, entity selection, form data
|
||||
|
||||
### Key Challenges
|
||||
|
||||
1. **Large single file**: Difficult to navigate and maintain
|
||||
2. **Mixed concerns**: UI logic, business logic, and API calls in one place
|
||||
3. **Complex state**: Multiple interconnected reactive properties
|
||||
4. **Testing difficulty**: Hard to test individual features in isolation
|
||||
5. **Reusability**: Components like entity grids could be reused elsewhere
|
||||
|
||||
## Decomposition Strategy
|
||||
|
||||
### Phase 1: Extract Display Components (✅ COMPLETED)
|
||||
|
||||
These components handle pure presentation with minimal business logic:
|
||||
|
||||
#### 1. PersonCard.vue ✅
|
||||
|
||||
- **Purpose**: Display individual person entities with selection capability
|
||||
- **Features**:
|
||||
- Person avatar using EntityIcon
|
||||
- Selection states (selectable, conflicted, disabled)
|
||||
- Time icon overlay for contacts
|
||||
- Click event handling
|
||||
- **Props**: `person`, `selectable`, `conflicted`, `showTimeIcon`
|
||||
- **Emits**: `person-selected`
|
||||
|
||||
#### 2. ProjectCard.vue ✅
|
||||
|
||||
- **Purpose**: Display individual project entities with selection capability
|
||||
- **Features**:
|
||||
- Project icon using ProjectIcon
|
||||
- Project name and issuer information
|
||||
- Click event handling
|
||||
- **Props**: `project`, `activeDid`, `allMyDids`, `allContacts`
|
||||
- **Emits**: `project-selected`
|
||||
|
||||
#### 3. EntitySummaryButton.vue ✅
|
||||
|
||||
- **Purpose**: Display selected entity with edit capability in step 2
|
||||
- **Features**:
|
||||
- Entity avatar (person or project)
|
||||
- Entity name and role label
|
||||
- Editable vs locked states
|
||||
- Edit button functionality
|
||||
- **Props**: `entity`, `entityType`, `label`, `editable`
|
||||
- **Emits**: `edit-requested`
|
||||
|
||||
#### 4. AmountInput.vue ✅
|
||||
|
||||
- **Purpose**: Specialized numeric input with increment/decrement controls
|
||||
- **Features**:
|
||||
- Increment/decrement buttons with validation
|
||||
- Configurable min/max values and step size
|
||||
- Input validation and formatting
|
||||
- v-model compatibility
|
||||
- **Props**: `value`, `min`, `max`, `step`, `inputId`
|
||||
- **Emits**: `update:value`
|
||||
|
||||
### Phase 2: Extract Layout Components (✅ COMPLETED)
|
||||
|
||||
These components handle layout and entity organization:
|
||||
|
||||
#### 5. EntityGrid.vue ✅
|
||||
|
||||
- **Purpose**: Unified grid layout for displaying people or projects
|
||||
- **Features**:
|
||||
- Responsive grid layout for people/projects
|
||||
- Special entity integration (You, Unnamed)
|
||||
- Conflict detection integration
|
||||
- Empty state messaging
|
||||
- Show All navigation
|
||||
- Event delegation for entity selection
|
||||
- **Props**: `entityType`, `entities`, `maxItems`, `activeDid`, `allMyDids`, `allContacts`, `conflictChecker`, `showYouEntity`, `youSelectable`, `showAllRoute`, `showAllQueryParams`
|
||||
- **Emits**: `entity-selected`
|
||||
|
||||
#### 6. SpecialEntityCard.vue ✅
|
||||
|
||||
- **Purpose**: Handle special entities like "You" and "Unnamed"
|
||||
- **Features**:
|
||||
- Special icon display (hand, question mark)
|
||||
- Conflict state handling
|
||||
- Configurable styling based on entity type
|
||||
- Click event handling
|
||||
- **Props**: `entityType`, `label`, `icon`, `selectable`, `conflicted`, `entityData`
|
||||
- **Emits**: `entity-selected`
|
||||
|
||||
#### 7. ShowAllCard.vue ✅
|
||||
|
||||
- **Purpose**: Handle "Show All" navigation functionality
|
||||
- **Features**:
|
||||
- Router-link integration
|
||||
- Query parameter passing
|
||||
- Consistent visual styling
|
||||
- Hover effects
|
||||
- **Props**: `entityType`, `routeName`, `queryParams`
|
||||
- **Emits**: None (uses router-link)
|
||||
|
||||
### Phase 3: Extract Step Components (✅ COMPLETED)
|
||||
|
||||
These components handle major UI sections:
|
||||
|
||||
#### 8. EntitySelectionStep.vue ✅
|
||||
|
||||
- **Purpose**: Complete step 1 entity selection interface
|
||||
- **Features**:
|
||||
- Dynamic step labeling based on context
|
||||
- EntityGrid integration for unified entity display
|
||||
- Conflict detection and prevention
|
||||
- Special entity handling (You, Unnamed)
|
||||
- Show All navigation with context preservation
|
||||
- Cancel functionality
|
||||
- Event delegation for entity selection
|
||||
- **Props**: `stepType`, `giverEntityType`, `recipientEntityType`, `showProjects`, `isFromProjectView`, `projects`, `allContacts`, `activeDid`, `allMyDids`, `conflictChecker`, `fromProjectId`, `toProjectId`, `giver`, `receiver`
|
||||
- **Emits**: `entity-selected`, `cancel`
|
||||
|
||||
#### 9. GiftDetailsStep.vue ✅
|
||||
|
||||
- **Purpose**: Complete step 2 gift details form interface
|
||||
- **Features**:
|
||||
- Entity summary display with edit capability
|
||||
- Gift description input with placeholder support
|
||||
- Amount input with increment/decrement controls
|
||||
- Unit code selection (HUR, USD, BTC, etc.)
|
||||
- Photo & more options navigation
|
||||
- Conflict detection and warning display
|
||||
- Form validation and submission
|
||||
- Cancel functionality
|
||||
- **Props**: `giver`, `receiver`, `giverEntityType`, `recipientEntityType`, `description`, `amount`, `unitCode`, `prompt`, `isFromProjectView`, `hasConflict`, `offerId`, `fromProjectId`, `toProjectId`
|
||||
- **Emits**: `update:description`, `update:amount`, `update:unitCode`, `edit-entity`, `explain-data`, `submit`, `cancel`
|
||||
|
||||
### Phase 4: Refactor Main Component (FINAL)
|
||||
|
||||
#### 9. GiftedDialog.vue (PLANNED REFACTOR)
|
||||
|
||||
- **Purpose**: Orchestrate sub-components and manage overall state
|
||||
- **Responsibilities**:
|
||||
- Step navigation logic
|
||||
- Entity conflict detection
|
||||
- API integration for gift recording
|
||||
- Success/error handling
|
||||
- Dialog visibility management
|
||||
|
||||
## Implementation Progress
|
||||
|
||||
### ✅ Completed Components
|
||||
|
||||
**Phase 1: Display Components**
|
||||
|
||||
1. **PersonCard.vue** - Individual person display with selection
|
||||
2. **ProjectCard.vue** - Individual project display with selection
|
||||
3. **EntitySummaryButton.vue** - Selected entity display with edit capability
|
||||
4. **AmountInput.vue** - Numeric input with increment/decrement controls
|
||||
|
||||
**Phase 2: Layout Components**
|
||||
5. **EntityGrid.vue** - Unified grid layout for entity selection
|
||||
6. **SpecialEntityCard.vue** - Special entities (You, Unnamed) with conflict handling
|
||||
7. **ShowAllCard.vue** - Show All navigation with router integration
|
||||
|
||||
**Phase 3: Step Components**
|
||||
8. **EntitySelectionStep.vue** - Complete step 1 entity selection interface
|
||||
9. **GiftDetailsStep.vue** - Complete step 2 gift details form interface
|
||||
|
||||
### 🔄 Next Steps
|
||||
|
||||
1. **Update GiftedDialog.vue** - Integrate all Phase 1-3 components
|
||||
2. **Test integration** - Ensure functionality remains intact
|
||||
3. **Create unit tests** - For all new components
|
||||
4. **Performance validation** - Ensure no regression
|
||||
5. **Phase 4 planning** - Refactor main component to orchestration only
|
||||
|
||||
### 📋 Future Phases
|
||||
|
||||
1. **Extract EntitySelectionStep.vue** - Complete step 1 logic
|
||||
2. **Extract GiftDetailsStep.vue** - Complete step 2 logic
|
||||
3. **Refactor main component** - Minimal orchestration logic
|
||||
4. **Add comprehensive tests** - Unit tests for each component
|
||||
5. **Prepare for Pinia** - State management migration
|
||||
|
||||
## Benefits of This Approach
|
||||
|
||||
### 1. Incremental Refactoring
|
||||
|
||||
- Each phase can be implemented and tested independently
|
||||
- Reduces risk of breaking existing functionality
|
||||
- Allows for gradual improvement over time
|
||||
|
||||
### 2. Improved Maintainability
|
||||
- Smaller, focused components are easier to understand
|
||||
- Clear separation of concerns
|
||||
- Easier to locate and fix bugs
|
||||
|
||||
### 3. Enhanced Testability
|
||||
- Individual components can be unit tested in isolation
|
||||
- Easier to mock dependencies
|
||||
- Better test coverage possible
|
||||
|
||||
### 4. Better Reusability
|
||||
- Components like EntityGrid can be used in other views
|
||||
- PersonCard and ProjectCard can be used throughout the app
|
||||
- AmountInput can be reused for other numeric inputs
|
||||
|
||||
### 5. Pinia Preparation
|
||||
- Smaller components make state management migration easier
|
||||
- Clear data flow patterns emerge
|
||||
- Easier to identify what state should be global vs local
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### Using PersonCard in EntityGrid
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<ul class="grid grid-cols-4 sm:grid-cols-5 md:grid-cols-6 gap-x-2 gap-y-4">
|
||||
<PersonCard
|
||||
v-for="person in people"
|
||||
:key="person.did"
|
||||
:person="person"
|
||||
:conflicted="wouldCreateConflict(person.did)"
|
||||
@person-selected="handlePersonSelected"
|
||||
/>
|
||||
</ul>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Using AmountInput in GiftDetailsStep
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<AmountInput
|
||||
:value="amount"
|
||||
:min="0"
|
||||
:max="1000"
|
||||
input-id="gift-amount"
|
||||
@update:value="amount = $event"
|
||||
/>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Using EntitySummaryButton in GiftDetailsStep
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<EntitySummaryButton
|
||||
:entity="giver"
|
||||
entity-type="person"
|
||||
label="Received from:"
|
||||
:editable="canEditGiver"
|
||||
@edit-requested="handleEditGiver"
|
||||
/>
|
||||
<EntitySummaryButton
|
||||
:entity="receiver"
|
||||
entity-type="person"
|
||||
label="Given to:"
|
||||
:editable="canEditReceiver"
|
||||
@edit-requested="handleEditReceiver"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Using EntityGrid in EntitySelectionStep
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div>
|
||||
<label class="block font-bold mb-4">
|
||||
{{ stepLabel }}
|
||||
</label>
|
||||
|
||||
<EntityGrid
|
||||
:entity-type="shouldShowProjects ? 'projects' : 'people'"
|
||||
:entities="shouldShowProjects ? projects : allContacts"
|
||||
:max-items="10"
|
||||
:active-did="activeDid"
|
||||
:all-my-dids="allMyDids"
|
||||
:all-contacts="allContacts"
|
||||
:conflict-checker="wouldCreateConflict"
|
||||
:show-you-entity="showYouEntity"
|
||||
:you-selectable="youSelectable"
|
||||
:show-all-route="showAllRoute"
|
||||
:show-all-query-params="showAllQueryParams"
|
||||
@entity-selected="handleEntitySelected"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Using SpecialEntityCard Standalone
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<ul class="grid grid-cols-4 gap-2">
|
||||
<SpecialEntityCard
|
||||
entity-type="you"
|
||||
label="You"
|
||||
icon="hand"
|
||||
:conflicted="wouldCreateConflict(activeDid)"
|
||||
:entity-data="{ did: activeDid, name: 'You' }"
|
||||
@entity-selected="handleYouSelected"
|
||||
/>
|
||||
|
||||
<SpecialEntityCard
|
||||
entity-type="unnamed"
|
||||
label="Unnamed"
|
||||
icon="circle-question"
|
||||
:entity-data="{ did: '', name: 'Unnamed' }"
|
||||
@entity-selected="handleUnnamedSelected"
|
||||
/>
|
||||
</ul>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Using EntitySelectionStep in GiftedDialog
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div v-show="currentStep === 1">
|
||||
<EntitySelectionStep
|
||||
:step-type="stepType"
|
||||
:giver-entity-type="giverEntityType"
|
||||
:recipient-entity-type="recipientEntityType"
|
||||
:show-projects="showProjects"
|
||||
:is-from-project-view="isFromProjectView"
|
||||
:projects="projects"
|
||||
:all-contacts="allContacts"
|
||||
:active-did="activeDid"
|
||||
:all-my-dids="allMyDids"
|
||||
:conflict-checker="wouldCreateConflict"
|
||||
:from-project-id="fromProjectId"
|
||||
:to-project-id="toProjectId"
|
||||
:giver="giver"
|
||||
:receiver="receiver"
|
||||
@entity-selected="handleEntitySelected"
|
||||
@cancel="cancel"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Using GiftDetailsStep in GiftedDialog
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div v-show="currentStep === 2">
|
||||
<GiftDetailsStep
|
||||
:giver="giver"
|
||||
:receiver="receiver"
|
||||
:giver-entity-type="giverEntityType"
|
||||
:recipient-entity-type="recipientEntityType"
|
||||
:description="description"
|
||||
:amount="parseFloat(amountInput)"
|
||||
:unit-code="unitCode"
|
||||
:prompt="prompt"
|
||||
:is-from-project-view="isFromProjectView"
|
||||
:has-conflict="hasPersonConflict"
|
||||
:offer-id="offerId"
|
||||
:from-project-id="fromProjectId"
|
||||
:to-project-id="toProjectId"
|
||||
@update:description="description = $event"
|
||||
@update:amount="amountInput = $event.toString()"
|
||||
@update:unit-code="unitCode = $event"
|
||||
@edit-entity="handleEditEntity"
|
||||
@explain-data="explainData"
|
||||
@submit="handleSubmit"
|
||||
@cancel="cancel"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
```
|
||||
|
||||
## Migration Strategy
|
||||
|
||||
### Backward Compatibility
|
||||
- Maintain existing API and prop interfaces
|
||||
- Ensure all existing functionality works unchanged
|
||||
- Preserve all event emissions and callbacks
|
||||
|
||||
### Testing Strategy
|
||||
- Create unit tests for each new component
|
||||
- Maintain existing integration tests
|
||||
- Add visual regression tests for UI components
|
||||
|
||||
### Performance Considerations
|
||||
- Monitor bundle size impact
|
||||
- Ensure no performance regression
|
||||
- Optimize component loading if needed
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Input Validation
|
||||
- AmountInput includes proper numeric validation
|
||||
- All user inputs are validated before processing
|
||||
- XSS prevention through proper Vue templating
|
||||
|
||||
### Data Handling
|
||||
- No sensitive data stored in component state
|
||||
- Proper prop validation and type checking
|
||||
- Secure API communication maintained
|
||||
|
||||
## Conclusion
|
||||
|
||||
This decomposition plan provides a structured approach to refactoring the GiftedDialog component while maintaining functionality and preparing for future enhancements. The incremental approach reduces risk and allows for continuous improvement of the codebase.
|
||||
|
||||
The completed Phase 1 components (PersonCard, ProjectCard, EntitySummaryButton, AmountInput) provide a solid foundation for the remaining phases and demonstrate the benefits of component decomposition in terms of maintainability, testability, and reusability.
|
||||
|
||||
---
|
||||
|
||||
## Final Integration Results
|
||||
|
||||
### ✅ **INTEGRATION COMPLETE**
|
||||
|
||||
**Completed on**: 2025-01-28
|
||||
|
||||
**Results:**
|
||||
- **Main GiftedDialog template**: Reduced from ~200 lines to ~20 lines
|
||||
- **Components created**: 9 focused, reusable components
|
||||
- **Lines of code**: ~2,000 lines of well-structured component code
|
||||
- **Backward compatibility**: 100% maintained
|
||||
- **Build status**: ✅ Passing
|
||||
- **Runtime status**: ✅ Working
|
||||
|
||||
**Components Successfully Integrated:**
|
||||
|
||||
1. **PersonCard.vue** - Individual person display with conflict detection
|
||||
2. **ProjectCard.vue** - Individual project display with issuer info
|
||||
3. **EntitySummaryButton.vue** - Selected entity display with edit capability
|
||||
4. **AmountInput.vue** - Numeric input with validation and controls
|
||||
5. **SpecialEntityCard.vue** - "You" and "Unnamed" entity handling
|
||||
6. **ShowAllCard.vue** - Navigation with router integration
|
||||
7. **EntityGrid.vue** - Unified grid layout orchestration
|
||||
8. **EntitySelectionStep.vue** - Complete Step 1 interface
|
||||
9. **GiftDetailsStep.vue** - Complete Step 2 interface
|
||||
|
||||
**Integration Benefits Achieved:**
|
||||
- ✅ **Maintainability**: Each component has single responsibility
|
||||
- ✅ **Testability**: Components can be unit tested in isolation
|
||||
- ✅ **Reusability**: Components can be used across the application
|
||||
- ✅ **Readability**: Clear separation of concerns and focused logic
|
||||
- ✅ **Debugging**: Easier to identify and fix issues
|
||||
- ✅ **Performance**: No performance regression, improved code splitting
|
||||
|
||||
**Next Steps:**
|
||||
1. **Pinia State Management**: Ready for state management migration
|
||||
2. **Component Testing**: Add comprehensive unit tests
|
||||
3. **Visual Testing**: Add Playwright component tests
|
||||
4. **Documentation**: Update component documentation
|
||||
5. **Optimization**: Fine-tune performance if needed
|
||||
|
||||
---
|
||||
|
||||
**Author**: Matthew Raymer
|
||||
**Last Updated**: 2025-01-28
|
||||
**Status**: ✅ **INTEGRATION COMPLETE - READY FOR PRODUCTION**
|
||||
4508
GiftedDialog-Logic-Flow.md
Normal file
4508
GiftedDialog-Logic-Flow.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -31,8 +31,8 @@ android {
|
||||
applicationId "app.timesafari.app"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 18
|
||||
versionName "0.4.7"
|
||||
versionCode 26
|
||||
versionName "0.5.1"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
@@ -91,6 +91,8 @@ dependencies {
|
||||
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
|
||||
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
|
||||
implementation project(':capacitor-android')
|
||||
implementation project(':capacitor-community-sqlite')
|
||||
implementation "androidx.biometric:biometric:1.2.0-alpha05"
|
||||
testImplementation "junit:junit:$junitVersion"
|
||||
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
|
||||
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
|
||||
|
||||
@@ -9,6 +9,7 @@ android {
|
||||
|
||||
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
|
||||
dependencies {
|
||||
implementation project(':capacitor-community-sqlite')
|
||||
implementation project(':capacitor-mlkit-barcode-scanning')
|
||||
implementation project(':capacitor-app')
|
||||
implementation project(':capacitor-camera')
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"appId": "app.timesafari.app",
|
||||
"appId": "app.timesafari",
|
||||
"appName": "TimeSafari",
|
||||
"webDir": "dist",
|
||||
"bundledWebRuntime": false,
|
||||
@@ -16,6 +16,41 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"SQLite": {
|
||||
"iosDatabaseLocation": "Library/CapacitorDatabase",
|
||||
"iosIsEncryption": true,
|
||||
"iosBiometric": {
|
||||
"biometricAuth": true,
|
||||
"biometricTitle": "Biometric login for TimeSafari"
|
||||
},
|
||||
"androidIsEncryption": true,
|
||||
"androidBiometric": {
|
||||
"biometricAuth": true,
|
||||
"biometricTitle": "Biometric login for TimeSafari"
|
||||
}
|
||||
}
|
||||
},
|
||||
"ios": {
|
||||
"contentInset": "never",
|
||||
"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"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
[
|
||||
{
|
||||
"pkg": "@capacitor-community/sqlite",
|
||||
"classpath": "com.getcapacitor.community.database.sqlite.CapacitorSQLitePlugin"
|
||||
},
|
||||
{
|
||||
"pkg": "@capacitor-mlkit/barcode-scanning",
|
||||
"classpath": "io.capawesome.capacitorjs.plugins.mlkit.barcodescanning.BarcodeScannerPlugin"
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
package app.timesafari;
|
||||
|
||||
import android.os.Bundle;
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
//import com.getcapacitor.community.sqlite.SQLite;
|
||||
|
||||
public class MainActivity extends BridgeActivity {
|
||||
// ... existing code ...
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
// Initialize SQLite
|
||||
//registerPlugin(SQLite.class);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package timesafari.app;
|
||||
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
|
||||
public class MainActivity extends BridgeActivity {}
|
||||
@@ -2,6 +2,9 @@
|
||||
include ':capacitor-android'
|
||||
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
|
||||
|
||||
include ':capacitor-community-sqlite'
|
||||
project(':capacitor-community-sqlite').projectDir = new File('../node_modules/@capacitor-community/sqlite/android')
|
||||
|
||||
include ':capacitor-mlkit-barcode-scanning'
|
||||
project(':capacitor-mlkit-barcode-scanning').projectDir = new File('../node_modules/@capacitor-mlkit/barcode-scanning/android')
|
||||
|
||||
|
||||
@@ -16,6 +16,41 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"SQLite": {
|
||||
"iosDatabaseLocation": "Library/CapacitorDatabase",
|
||||
"iosIsEncryption": true,
|
||||
"iosBiometric": {
|
||||
"biometricAuth": true,
|
||||
"biometricTitle": "Biometric login for TimeSafari"
|
||||
},
|
||||
"androidIsEncryption": true,
|
||||
"androidBiometric": {
|
||||
"biometricAuth": true,
|
||||
"biometricTitle": "Biometric login for TimeSafari"
|
||||
}
|
||||
}
|
||||
},
|
||||
"ios": {
|
||||
"contentInset": "never",
|
||||
"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"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
224
doc/GiftedDialog-Complete-Documentation.md
Normal file
224
doc/GiftedDialog-Complete-Documentation.md
Normal file
@@ -0,0 +1,224 @@
|
||||
# GiftedDialog Complete Documentation
|
||||
|
||||
## Overview
|
||||
|
||||
The GiftedDialog system is a sophisticated multi-step dialog for recording gifts between people and projects in the TimeSafari application. It consists of a main orchestrating component and 9 specialized child components that handle different aspects of the gift recording workflow.
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Two-Step Workflow**: Entity selection → Gift details
|
||||
- **Multi-Entity Support**: People, projects, and special entities
|
||||
- **Conflict Detection**: Prevents invalid gift combinations
|
||||
- **Responsive Design**: Works across all device sizes
|
||||
- **Accessibility**: Full keyboard navigation and screen reader support
|
||||
- **Validation**: Comprehensive form validation and error handling
|
||||
- **Flexible Integration**: Can be embedded in any view with different contexts
|
||||
|
||||
## Component Architecture
|
||||
|
||||
### Main Component
|
||||
- **GiftedDialog.vue** - Main orchestrating component that manages dialog state, step navigation, and API integration
|
||||
|
||||
### Step Components
|
||||
- **EntitySelectionStep.vue** - Step 1 controller with dynamic labeling and context awareness
|
||||
- **GiftDetailsStep.vue** - Step 2 controller with form validation and entity summaries
|
||||
|
||||
### Layout Components
|
||||
- **EntityGrid.vue** - Unified entity grid layout with responsive design
|
||||
- **EntitySummaryButton.vue** - Selected entity display with edit capability
|
||||
|
||||
### Display Components
|
||||
- **PersonCard.vue** - Individual person display with avatar and selection states
|
||||
- **ProjectCard.vue** - Individual project display with icons and issuer information
|
||||
- **SpecialEntityCard.vue** - Special entities (You, Unnamed) with conflict detection
|
||||
- **ShowAllCard.vue** - Navigation component with router integration
|
||||
|
||||
### Input Components
|
||||
- **AmountInput.vue** - Numeric input with increment/decrement controls and validation
|
||||
|
||||
## Data Flow
|
||||
|
||||
### Step 1: Entity Selection
|
||||
1. User opens dialog → GiftedDialog renders EntitySelectionStep
|
||||
2. EntitySelectionStep renders EntityGrid with entities and configuration
|
||||
3. EntityGrid renders PersonCard/ProjectCard/SpecialEntityCard components
|
||||
4. User clicks entity → Card emits to Grid → Grid emits to Step → Step emits to Dialog
|
||||
5. GiftedDialog updates state and advances to step 2
|
||||
|
||||
### Step 2: Gift Details
|
||||
1. GiftedDialog renders GiftDetailsStep with selected entities
|
||||
2. GiftDetailsStep renders EntitySummaryButton and AmountInput components
|
||||
3. User fills form and clicks submit → Step emits to Dialog
|
||||
4. GiftedDialog processes submission via API and handles success/error
|
||||
|
||||
## Key Props and Configuration
|
||||
|
||||
### GiftedDialog Props
|
||||
```typescript
|
||||
interface GiftedDialogProps {
|
||||
fromProjectId?: string; // Project ID when project is giver
|
||||
toProjectId?: string; // Project ID when project is recipient
|
||||
showProjects?: boolean; // Whether to show projects
|
||||
isFromProjectView?: boolean; // Context flag for project views
|
||||
}
|
||||
```
|
||||
|
||||
### Opening the Dialog
|
||||
```typescript
|
||||
// Basic usage
|
||||
giftedDialog.open();
|
||||
|
||||
// With pre-selected entities and context
|
||||
giftedDialog.open(
|
||||
giverEntity, // Pre-selected giver
|
||||
receiverEntity, // Pre-selected receiver
|
||||
offerId, // Offer context
|
||||
customTitle, // Custom dialog title
|
||||
prompt, // Custom input prompt
|
||||
successCallback // Success handler
|
||||
);
|
||||
```
|
||||
|
||||
## Integration Patterns
|
||||
|
||||
### Basic Integration
|
||||
```vue
|
||||
<template>
|
||||
<div>
|
||||
<button @click="openGiftDialog">Record Gift</button>
|
||||
<GiftedDialog ref="giftedDialog" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
export default class Example extends Vue {
|
||||
openGiftDialog() {
|
||||
const dialog = this.$refs.giftedDialog as GiftedDialog;
|
||||
dialog.open();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
### Project Context Integration
|
||||
```typescript
|
||||
// Gift from project
|
||||
dialog.open(
|
||||
projectEntity, // Project as giver
|
||||
undefined, // User selects receiver
|
||||
undefined, // No offer
|
||||
"Gift from Project",
|
||||
"What did this project provide?"
|
||||
);
|
||||
|
||||
// Gift to project
|
||||
dialog.open(
|
||||
undefined, // User selects giver
|
||||
projectEntity, // Project as receiver
|
||||
undefined, // No offer
|
||||
"Gift to Project",
|
||||
"What was contributed to this project?"
|
||||
);
|
||||
```
|
||||
|
||||
## State Management
|
||||
|
||||
The dialog manages internal state through a reactive system:
|
||||
|
||||
- **Step Navigation**: Controls progression from entity selection to gift details
|
||||
- **Entity Selection**: Tracks selected giver and receiver entities
|
||||
- **Conflict Detection**: Prevents selecting same person for both roles
|
||||
- **Form Validation**: Ensures required fields are completed
|
||||
- **API Integration**: Handles gift submission and response processing
|
||||
|
||||
## Conflict Detection Logic
|
||||
|
||||
```typescript
|
||||
function wouldCreateConflict(selectedDid: string): boolean {
|
||||
// Only applies to person-to-person gifts
|
||||
if (giverEntityType !== "person" || recipientEntityType !== "person") {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if selecting same person for both roles
|
||||
if (stepType === "giver") {
|
||||
return receiver?.did === selectedDid;
|
||||
} else if (stepType === "recipient") {
|
||||
return giver?.did === selectedDid;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
```
|
||||
|
||||
## AmountInput Component Fix
|
||||
|
||||
The AmountInput component was recently fixed to resolve an issue where increment/decrement buttons weren't updating the displayed value:
|
||||
|
||||
### Problem
|
||||
- Input field used `:value="displayValue"` (one-way binding)
|
||||
- Programmatic updates to `displayValue` weren't reflected in DOM
|
||||
|
||||
### Solution
|
||||
- Changed to `v-model="displayValue"` (two-way binding)
|
||||
- Now properly synchronizes programmatic and user input changes
|
||||
|
||||
### Usage
|
||||
```vue
|
||||
<AmountInput
|
||||
:value="amount"
|
||||
:min="0"
|
||||
:max="1000"
|
||||
:step="1"
|
||||
@update:value="handleAmountChange"
|
||||
/>
|
||||
```
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Testing
|
||||
- Individual component behavior
|
||||
- Props validation
|
||||
- Event emission
|
||||
- Computed property calculations
|
||||
|
||||
### Integration Testing
|
||||
- Multi-component workflows
|
||||
- State management
|
||||
- API integration
|
||||
- Error handling
|
||||
|
||||
### End-to-End Testing
|
||||
- Complete user workflows
|
||||
- Cross-browser compatibility
|
||||
- Accessibility compliance
|
||||
- Performance validation
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- **Input Validation**: All user inputs are sanitized and validated
|
||||
- **DID Privacy**: User identifiers only shared with authorized contacts
|
||||
- **API Security**: Requests are cryptographically signed
|
||||
- **XSS Prevention**: Template sanitization and CSP headers
|
||||
|
||||
## Performance Optimizations
|
||||
|
||||
- **Lazy Loading**: Components loaded only when needed
|
||||
- **Virtual Scrolling**: For large entity lists
|
||||
- **Debounced Input**: Prevents excessive API calls
|
||||
- **Computed Properties**: Efficient reactive calculations
|
||||
- **Memory Management**: Proper cleanup on component destruction
|
||||
|
||||
## Accessibility Features
|
||||
|
||||
- **Keyboard Navigation**: Full tab order and keyboard shortcuts
|
||||
- **Screen Reader Support**: ARIA labels and semantic HTML
|
||||
- **Focus Management**: Proper focus handling on open/close
|
||||
- **High Contrast**: Supports high contrast themes
|
||||
- **Responsive Design**: Works on all screen sizes
|
||||
|
||||
---
|
||||
|
||||
**Author**: Matthew Raymer
|
||||
**Last Updated**: 2025-06-30
|
||||
**Version**: 1.0.0
|
||||
399
doc/dexie-to-sqlite-mapping.md
Normal file
399
doc/dexie-to-sqlite-mapping.md
Normal file
@@ -0,0 +1,399 @@
|
||||
# Dexie to absurd-sql Mapping Guide
|
||||
|
||||
## Schema Mapping
|
||||
|
||||
### Current Dexie Schema
|
||||
```typescript
|
||||
// Current Dexie schema
|
||||
const db = new Dexie('TimeSafariDB');
|
||||
|
||||
db.version(1).stores({
|
||||
accounts: 'did, publicKeyHex, createdAt, updatedAt',
|
||||
settings: 'key, value, updatedAt',
|
||||
contacts: 'id, did, name, createdAt, updatedAt'
|
||||
});
|
||||
```
|
||||
|
||||
### New SQLite Schema
|
||||
```sql
|
||||
-- New SQLite schema
|
||||
CREATE TABLE accounts (
|
||||
did TEXT PRIMARY KEY,
|
||||
public_key_hex TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE contacts (
|
||||
id TEXT PRIMARY KEY,
|
||||
did TEXT NOT NULL,
|
||||
name TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
FOREIGN KEY (did) REFERENCES accounts(did)
|
||||
);
|
||||
|
||||
-- Indexes for performance
|
||||
CREATE INDEX idx_accounts_created_at ON accounts(created_at);
|
||||
CREATE INDEX idx_contacts_did ON contacts(did);
|
||||
CREATE INDEX idx_settings_updated_at ON settings(updated_at);
|
||||
```
|
||||
|
||||
## Query Mapping
|
||||
|
||||
### 1. Account Operations
|
||||
|
||||
#### Get Account by DID
|
||||
```typescript
|
||||
// Dexie
|
||||
const account = await db.accounts.get(did);
|
||||
|
||||
// absurd-sql
|
||||
const result = await db.exec(`
|
||||
SELECT * FROM accounts WHERE did = ?
|
||||
`, [did]);
|
||||
const account = result[0]?.values[0];
|
||||
```
|
||||
|
||||
#### Get All Accounts
|
||||
```typescript
|
||||
// Dexie
|
||||
const accounts = await db.accounts.toArray();
|
||||
|
||||
// absurd-sql
|
||||
const result = await db.exec(`
|
||||
SELECT * FROM accounts ORDER BY created_at DESC
|
||||
`);
|
||||
const accounts = result[0]?.values || [];
|
||||
```
|
||||
|
||||
#### Add Account
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.accounts.add({
|
||||
did,
|
||||
publicKeyHex,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now()
|
||||
});
|
||||
|
||||
// absurd-sql
|
||||
await db.run(`
|
||||
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`, [did, publicKeyHex, Date.now(), Date.now()]);
|
||||
```
|
||||
|
||||
#### Update Account
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.accounts.update(did, {
|
||||
publicKeyHex,
|
||||
updatedAt: Date.now()
|
||||
});
|
||||
|
||||
// absurd-sql
|
||||
await db.run(`
|
||||
UPDATE accounts
|
||||
SET public_key_hex = ?, updated_at = ?
|
||||
WHERE did = ?
|
||||
`, [publicKeyHex, Date.now(), did]);
|
||||
```
|
||||
|
||||
### 2. Settings Operations
|
||||
|
||||
#### Get Setting
|
||||
```typescript
|
||||
// Dexie
|
||||
const setting = await db.settings.get(key);
|
||||
|
||||
// absurd-sql
|
||||
const result = await db.exec(`
|
||||
SELECT * FROM settings WHERE key = ?
|
||||
`, [key]);
|
||||
const setting = result[0]?.values[0];
|
||||
```
|
||||
|
||||
#### Set Setting
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.settings.put({
|
||||
key,
|
||||
value,
|
||||
updatedAt: Date.now()
|
||||
});
|
||||
|
||||
// absurd-sql
|
||||
await db.run(`
|
||||
INSERT INTO settings (key, value, updated_at)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET
|
||||
value = excluded.value,
|
||||
updated_at = excluded.updated_at
|
||||
`, [key, value, Date.now()]);
|
||||
```
|
||||
|
||||
### 3. Contact Operations
|
||||
|
||||
#### Get Contacts by Account
|
||||
```typescript
|
||||
// Dexie
|
||||
const contacts = await db.contacts
|
||||
.where('did')
|
||||
.equals(accountDid)
|
||||
.toArray();
|
||||
|
||||
// absurd-sql
|
||||
const result = await db.exec(`
|
||||
SELECT * FROM contacts
|
||||
WHERE did = ?
|
||||
ORDER BY created_at DESC
|
||||
`, [accountDid]);
|
||||
const contacts = result[0]?.values || [];
|
||||
```
|
||||
|
||||
#### Add Contact
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.contacts.add({
|
||||
id: generateId(),
|
||||
did: accountDid,
|
||||
name,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now()
|
||||
});
|
||||
|
||||
// absurd-sql
|
||||
await db.run(`
|
||||
INSERT INTO contacts (id, did, name, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`, [generateId(), accountDid, name, Date.now(), Date.now()]);
|
||||
```
|
||||
|
||||
## Transaction Mapping
|
||||
|
||||
### Batch Operations
|
||||
```typescript
|
||||
// Dexie
|
||||
await db.transaction('rw', [db.accounts, db.contacts], async () => {
|
||||
await db.accounts.add(account);
|
||||
await db.contacts.bulkAdd(contacts);
|
||||
});
|
||||
|
||||
// absurd-sql
|
||||
await db.exec('BEGIN TRANSACTION;');
|
||||
try {
|
||||
await db.run(`
|
||||
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`, [account.did, account.publicKeyHex, account.createdAt, account.updatedAt]);
|
||||
|
||||
for (const contact of contacts) {
|
||||
await db.run(`
|
||||
INSERT INTO contacts (id, did, name, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`, [contact.id, contact.did, contact.name, contact.createdAt, contact.updatedAt]);
|
||||
}
|
||||
await db.exec('COMMIT;');
|
||||
} catch (error) {
|
||||
await db.exec('ROLLBACK;');
|
||||
throw error;
|
||||
}
|
||||
```
|
||||
|
||||
## 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(),
|
||||
contacts: await db.contacts.toArray(),
|
||||
metadata: {
|
||||
version: '1.0.0',
|
||||
timestamp: Date.now(),
|
||||
dexieVersion: Dexie.version
|
||||
}
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Data Import (JSON to absurd-sql)
|
||||
```typescript
|
||||
async function importToAbsurdSql(data: MigrationData): Promise<void> {
|
||||
await db.exec('BEGIN TRANSACTION;');
|
||||
try {
|
||||
// Import accounts
|
||||
for (const account of data.accounts) {
|
||||
await db.run(`
|
||||
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`, [account.did, account.publicKeyHex, account.createdAt, account.updatedAt]);
|
||||
}
|
||||
|
||||
// Import settings
|
||||
for (const setting of data.settings) {
|
||||
await db.run(`
|
||||
INSERT INTO settings (key, value, updated_at)
|
||||
VALUES (?, ?, ?)
|
||||
`, [setting.key, setting.value, setting.updatedAt]);
|
||||
}
|
||||
|
||||
// Import contacts
|
||||
for (const contact of data.contacts) {
|
||||
await db.run(`
|
||||
INSERT INTO contacts (id, did, name, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`, [contact.id, contact.did, contact.name, contact.createdAt, contact.updatedAt]);
|
||||
}
|
||||
await db.exec('COMMIT;');
|
||||
} catch (error) {
|
||||
await db.exec('ROLLBACK;');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Verification
|
||||
```typescript
|
||||
async function verifyMigration(dexieData: MigrationData): Promise<boolean> {
|
||||
// Verify account count
|
||||
const accountResult = await db.exec('SELECT COUNT(*) as count FROM accounts');
|
||||
const accountCount = accountResult[0].values[0][0];
|
||||
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(
|
||||
'SELECT * FROM accounts WHERE did = ?',
|
||||
[account.did]
|
||||
);
|
||||
const migratedAccount = result[0]?.values[0];
|
||||
if (!migratedAccount ||
|
||||
migratedAccount[1] !== account.publicKeyHex) { // public_key_hex is second column
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
## 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
|
||||
- Consider using `PRAGMA synchronous=NORMAL;` for better performance
|
||||
|
||||
## Error Handling
|
||||
|
||||
### 1. Common Errors
|
||||
```typescript
|
||||
// Dexie errors
|
||||
try {
|
||||
await db.accounts.add(account);
|
||||
} catch (error) {
|
||||
if (error instanceof Dexie.ConstraintError) {
|
||||
// Handle duplicate key
|
||||
}
|
||||
}
|
||||
|
||||
// absurd-sql errors
|
||||
try {
|
||||
await db.run(`
|
||||
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`, [account.did, account.publicKeyHex, account.createdAt, account.updatedAt]);
|
||||
} catch (error) {
|
||||
if (error.message.includes('UNIQUE constraint failed')) {
|
||||
// Handle duplicate key
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Transaction Recovery
|
||||
```typescript
|
||||
// Dexie transaction
|
||||
try {
|
||||
await db.transaction('rw', db.accounts, async () => {
|
||||
// Operations
|
||||
});
|
||||
} catch (error) {
|
||||
// Dexie automatically rolls back
|
||||
}
|
||||
|
||||
// absurd-sql transaction
|
||||
try {
|
||||
await db.exec('BEGIN TRANSACTION;');
|
||||
// Operations
|
||||
await db.exec('COMMIT;');
|
||||
} catch (error) {
|
||||
await db.exec('ROLLBACK;');
|
||||
throw error;
|
||||
}
|
||||
```
|
||||
|
||||
## Migration Strategy
|
||||
|
||||
1. **Preparation**
|
||||
- Export all Dexie data
|
||||
- Verify data integrity
|
||||
- Create SQLite schema
|
||||
- Setup indexes
|
||||
|
||||
2. **Migration**
|
||||
- Import data in transactions
|
||||
- Verify each batch
|
||||
- Handle errors gracefully
|
||||
- Maintain backup
|
||||
|
||||
3. **Verification**
|
||||
- Compare record counts
|
||||
- Verify data integrity
|
||||
- Test common queries
|
||||
- Validate relationships
|
||||
|
||||
4. **Cleanup**
|
||||
- Remove Dexie database
|
||||
- Clear IndexedDB storage
|
||||
- Update application code
|
||||
- Remove old dependencies
|
||||
@@ -1,8 +1,8 @@
|
||||
# Migration Guide: Dexie to wa-sqlite
|
||||
# Migration Guide: Dexie to absurd-sql
|
||||
|
||||
## Overview
|
||||
|
||||
This document outlines the migration process from Dexie.js to wa-sqlite 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.
|
||||
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.
|
||||
|
||||
## Migration Goals
|
||||
|
||||
@@ -43,12 +43,20 @@ This document outlines the migration process from Dexie.js to wa-sqlite for the
|
||||
}
|
||||
```
|
||||
|
||||
2. **Storage Requirements**
|
||||
2. **Dependencies**
|
||||
```json
|
||||
{
|
||||
"@jlongster/sql.js": "^1.8.0",
|
||||
"absurd-sql": "^1.8.0"
|
||||
}
|
||||
```
|
||||
|
||||
3. **Storage Requirements**
|
||||
- Sufficient IndexedDB quota
|
||||
- Available disk space for SQLite
|
||||
- Backup storage space
|
||||
|
||||
3. **Platform Support**
|
||||
4. **Platform Support**
|
||||
- Web: Modern browser with IndexedDB support
|
||||
- iOS: iOS 13+ with SQLite support
|
||||
- Android: Android 5+ with SQLite support
|
||||
@@ -60,9 +68,15 @@ This document outlines the migration process from Dexie.js to wa-sqlite for the
|
||||
|
||||
```typescript
|
||||
// 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';
|
||||
|
||||
export class MigrationService {
|
||||
private static instance: MigrationService;
|
||||
private backup: MigrationBackup | null = null;
|
||||
private sql: any = null;
|
||||
private db: any = null;
|
||||
|
||||
async prepare(): Promise<void> {
|
||||
try {
|
||||
@@ -75,8 +89,8 @@ export class MigrationService {
|
||||
// 3. Verify backup integrity
|
||||
await this.verifyBackup();
|
||||
|
||||
// 4. Initialize wa-sqlite
|
||||
await this.initializeWaSqlite();
|
||||
// 4. Initialize absurd-sql
|
||||
await this.initializeAbsurdSql();
|
||||
} catch (error) {
|
||||
throw new StorageError(
|
||||
'Migration preparation failed',
|
||||
@@ -86,6 +100,42 @@ export class MigrationService {
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -160,12 +210,11 @@ export class DataMigration {
|
||||
}
|
||||
|
||||
private async migrateAccounts(accounts: Account[]): Promise<void> {
|
||||
const db = await this.getWaSqliteConnection();
|
||||
|
||||
// Use transaction for atomicity
|
||||
await db.transaction(async (tx) => {
|
||||
await this.db.exec('BEGIN TRANSACTION;');
|
||||
try {
|
||||
for (const account of accounts) {
|
||||
await tx.execute(`
|
||||
await this.db.run(`
|
||||
INSERT INTO accounts (did, public_key_hex, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`, [
|
||||
@@ -175,16 +224,18 @@ export class DataMigration {
|
||||
account.updatedAt
|
||||
]);
|
||||
}
|
||||
});
|
||||
await this.db.exec('COMMIT;');
|
||||
} catch (error) {
|
||||
await this.db.exec('ROLLBACK;');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async verifyMigration(backup: MigrationBackup): Promise<void> {
|
||||
const db = await this.getWaSqliteConnection();
|
||||
|
||||
// Verify account count
|
||||
const accountCount = await db.selectValue(
|
||||
'SELECT COUNT(*) FROM accounts'
|
||||
);
|
||||
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',
|
||||
@@ -214,8 +265,8 @@ export class RollbackService {
|
||||
// 3. Verify restoration
|
||||
await this.verifyRestoration(backup);
|
||||
|
||||
// 4. Clean up wa-sqlite
|
||||
await this.cleanupWaSqlite();
|
||||
// 4. Clean up absurd-sql
|
||||
await this.cleanupAbsurdSql();
|
||||
} catch (error) {
|
||||
throw new StorageError(
|
||||
'Rollback failed',
|
||||
@@ -371,6 +422,14 @@ button:hover {
|
||||
```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();
|
||||
});
|
||||
|
||||
it('should create valid backup', async () => {
|
||||
const service = MigrationService.getInstance();
|
||||
const backup = await service.createBackup();
|
||||
339
doc/secure-storage-implementation.md
Normal file
339
doc/secure-storage-implementation.md
Normal file
@@ -0,0 +1,339 @@
|
||||
# Secure Storage Implementation Guide for TimeSafari App
|
||||
|
||||
## Overview
|
||||
|
||||
This document outlines the implementation of secure storage for the TimeSafari app. The implementation focuses on:
|
||||
|
||||
1. **Platform-Specific Storage Solutions**:
|
||||
- Web: SQLite with IndexedDB backend (absurd-sql)
|
||||
- Electron: SQLite with Node.js backend
|
||||
- Native: (Planned) SQLCipher with platform-specific secure storage
|
||||
|
||||
2. **Key Features**:
|
||||
- SQLite-based storage using absurd-sql for web
|
||||
- Platform-specific service factory pattern
|
||||
- Consistent API across platforms
|
||||
- Migration support from Dexie.js
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Installation
|
||||
|
||||
```bash
|
||||
# Core dependencies
|
||||
npm install @jlongster/sql.js
|
||||
npm install absurd-sql
|
||||
|
||||
# Platform-specific dependencies (for future native support)
|
||||
npm install @capacitor/preferences
|
||||
npm install @capacitor-community/biometric-auth
|
||||
```
|
||||
|
||||
### 2. Basic Usage
|
||||
|
||||
```typescript
|
||||
// Using the platform service
|
||||
import { PlatformServiceFactory } from '../services/PlatformServiceFactory';
|
||||
|
||||
// Get platform-specific service instance
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
|
||||
// Example database operations
|
||||
async function example() {
|
||||
try {
|
||||
// Query example
|
||||
const result = await platformService.dbQuery(
|
||||
"SELECT * FROM accounts WHERE did = ?",
|
||||
[did]
|
||||
);
|
||||
|
||||
// Execute example
|
||||
await platformService.dbExec(
|
||||
"INSERT INTO accounts (did, public_key_hex) VALUES (?, ?)",
|
||||
[did, publicKeyHex]
|
||||
);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Database operation failed:', error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Platform Detection
|
||||
|
||||
```typescript
|
||||
// src/services/PlatformServiceFactory.ts
|
||||
export class PlatformServiceFactory {
|
||||
static getInstance(): PlatformService {
|
||||
if (process.env.ELECTRON) {
|
||||
// Electron platform
|
||||
return new ElectronPlatformService();
|
||||
} else {
|
||||
// Web platform (default)
|
||||
return new AbsurdSqlDatabaseService();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Current Implementation Details
|
||||
|
||||
#### Web Platform (AbsurdSqlDatabaseService)
|
||||
|
||||
The web platform uses absurd-sql with IndexedDB backend:
|
||||
|
||||
```typescript
|
||||
// src/services/AbsurdSqlDatabaseService.ts
|
||||
export class AbsurdSqlDatabaseService implements PlatformService {
|
||||
private static instance: AbsurdSqlDatabaseService | null = null;
|
||||
private db: AbsurdSqlDatabase | null = null;
|
||||
private initialized: boolean = false;
|
||||
|
||||
// Singleton pattern
|
||||
static getInstance(): AbsurdSqlDatabaseService {
|
||||
if (!AbsurdSqlDatabaseService.instance) {
|
||||
AbsurdSqlDatabaseService.instance = new AbsurdSqlDatabaseService();
|
||||
}
|
||||
return AbsurdSqlDatabaseService.instance;
|
||||
}
|
||||
|
||||
// Database operations
|
||||
async dbQuery(sql: string, params: unknown[] = []): Promise<QueryExecResult[]> {
|
||||
await this.waitForInitialization();
|
||||
return this.queueOperation<QueryExecResult[]>("query", sql, params);
|
||||
}
|
||||
|
||||
async dbExec(sql: string, params: unknown[] = []): Promise<void> {
|
||||
await this.waitForInitialization();
|
||||
await this.queueOperation<void>("run", sql, params);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Key features:
|
||||
- Uses absurd-sql for SQLite in the browser
|
||||
- Implements operation queuing for thread safety
|
||||
- Handles initialization and connection management
|
||||
- Provides consistent API across platforms
|
||||
|
||||
### 5. Migration from Dexie.js
|
||||
|
||||
The current implementation supports gradual migration from Dexie.js:
|
||||
|
||||
```typescript
|
||||
// Example of dual-storage pattern
|
||||
async function getAccount(did: string): Promise<Account | undefined> {
|
||||
// Try SQLite first
|
||||
const platform = PlatformServiceFactory.getInstance();
|
||||
let account = await platform.dbQuery(
|
||||
"SELECT * FROM accounts WHERE did = ?",
|
||||
[did]
|
||||
);
|
||||
|
||||
// Fallback to Dexie if needed
|
||||
if (USE_DEXIE_DB) {
|
||||
account = await db.accounts.get(did);
|
||||
}
|
||||
|
||||
return account;
|
||||
}
|
||||
```
|
||||
|
||||
#### A. Modifying Code
|
||||
|
||||
When converting from Dexie.js to SQL-based implementation, follow these patterns:
|
||||
|
||||
1. **Database Access Pattern**
|
||||
```typescript
|
||||
// Before (Dexie)
|
||||
const result = await db.table.where("field").equals(value).first();
|
||||
|
||||
// After (SQL)
|
||||
const platform = PlatformServiceFactory.getInstance();
|
||||
let result = await platform.dbQuery(
|
||||
"SELECT * FROM table WHERE field = ?",
|
||||
[value]
|
||||
);
|
||||
result = databaseUtil.mapQueryResultToValues(result);
|
||||
|
||||
// Fallback to Dexie if needed
|
||||
if (USE_DEXIE_DB) {
|
||||
result = await db.table.where("field").equals(value).first();
|
||||
}
|
||||
```
|
||||
|
||||
2. **Update Operations**
|
||||
```typescript
|
||||
// Before (Dexie)
|
||||
await db.table.where("id").equals(id).modify(changes);
|
||||
|
||||
// After (SQL)
|
||||
// For settings updates, use the utility methods:
|
||||
await databaseUtil.updateDefaultSettings(changes);
|
||||
// OR
|
||||
await databaseUtil.updateAccountSettings(did, changes);
|
||||
|
||||
// For other tables, use direct SQL:
|
||||
const platform = PlatformServiceFactory.getInstance();
|
||||
await platform.dbExec(
|
||||
"UPDATE table SET field1 = ?, field2 = ? WHERE id = ?",
|
||||
[changes.field1, changes.field2, id]
|
||||
);
|
||||
|
||||
// Fallback to Dexie if needed
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.table.where("id").equals(id).modify(changes);
|
||||
}
|
||||
```
|
||||
|
||||
3. **Insert Operations**
|
||||
```typescript
|
||||
// Before (Dexie)
|
||||
await db.table.add(item);
|
||||
|
||||
// After (SQL)
|
||||
const platform = PlatformServiceFactory.getInstance();
|
||||
const columns = Object.keys(item);
|
||||
const values = Object.values(item);
|
||||
const placeholders = values.map(() => '?').join(', ');
|
||||
const sql = `INSERT INTO table (${columns.join(', ')}) VALUES (${placeholders})`;
|
||||
await platform.dbExec(sql, values);
|
||||
|
||||
// Fallback to Dexie if needed
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.table.add(item);
|
||||
}
|
||||
```
|
||||
|
||||
4. **Delete Operations**
|
||||
```typescript
|
||||
// Before (Dexie)
|
||||
await db.table.where("id").equals(id).delete();
|
||||
|
||||
// After (SQL)
|
||||
const platform = PlatformServiceFactory.getInstance();
|
||||
await platform.dbExec("DELETE FROM table WHERE id = ?", [id]);
|
||||
|
||||
// Fallback to Dexie if needed
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.table.where("id").equals(id).delete();
|
||||
}
|
||||
```
|
||||
|
||||
5. **Result Processing**
|
||||
```typescript
|
||||
// Before (Dexie)
|
||||
const items = await db.table.toArray();
|
||||
|
||||
// After (SQL)
|
||||
const platform = PlatformServiceFactory.getInstance();
|
||||
let items = await platform.dbQuery("SELECT * FROM table");
|
||||
items = databaseUtil.mapQueryResultToValues(items);
|
||||
|
||||
// Fallback to Dexie if needed
|
||||
if (USE_DEXIE_DB) {
|
||||
items = await db.table.toArray();
|
||||
}
|
||||
```
|
||||
|
||||
6. **Using Utility Methods**
|
||||
|
||||
When working with settings or other common operations, use the utility methods in `db/index.ts`:
|
||||
|
||||
```typescript
|
||||
// Settings operations
|
||||
await databaseUtil.updateDefaultSettings(settings);
|
||||
await databaseUtil.updateAccountSettings(did, settings);
|
||||
const settings = await databaseUtil.retrieveSettingsForDefaultAccount();
|
||||
const settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
|
||||
// Logging operations
|
||||
await databaseUtil.logToDb(message);
|
||||
await databaseUtil.logConsoleAndDb(message, showInConsole);
|
||||
```
|
||||
|
||||
Key Considerations:
|
||||
- Always use `databaseUtil.mapQueryResultToValues()` to process SQL query results
|
||||
- Use utility methods from `db/index.ts` when available instead of direct SQL
|
||||
- Keep Dexie fallbacks wrapped in `if (USE_DEXIE_DB)` checks
|
||||
- For queries that return results, use `let` variables to allow Dexie fallback to override
|
||||
- For updates/inserts/deletes, execute both SQL and Dexie operations when `USE_DEXIE_DB` is true
|
||||
|
||||
Example Migration:
|
||||
```typescript
|
||||
// Before (Dexie)
|
||||
export async function updateSettings(settings: Settings): Promise<void> {
|
||||
await db.settings.put(settings);
|
||||
}
|
||||
|
||||
// After (SQL)
|
||||
export async function updateSettings(settings: Settings): Promise<void> {
|
||||
const platform = PlatformServiceFactory.getInstance();
|
||||
const { sql, params } = generateUpdateStatement(
|
||||
settings,
|
||||
"settings",
|
||||
"id = ?",
|
||||
[settings.id]
|
||||
);
|
||||
await platform.dbExec(sql, params);
|
||||
}
|
||||
```
|
||||
|
||||
Remember to:
|
||||
- Create database access code to use the platform service, putting it in front of the Dexie version
|
||||
- Instead of removing Dexie-specific code, keep it.
|
||||
|
||||
- For creates & updates & deletes, the duplicate code is fine.
|
||||
|
||||
- For queries where we use the results, make the setting from SQL into a 'let' variable, then wrap the Dexie code in a check for USE_DEXIE_DB from app.ts and if
|
||||
it's true then use that result instead of the SQL code's result.
|
||||
|
||||
- Consider data migration needs, and warn if there are any potential migration problems
|
||||
|
||||
## Success Criteria
|
||||
|
||||
1. **Functionality**
|
||||
- [x] Basic CRUD operations work correctly
|
||||
- [x] Platform service factory pattern implemented
|
||||
- [x] Error handling in place
|
||||
- [ ] Native platform support (planned)
|
||||
|
||||
2. **Performance**
|
||||
- [x] Database operations complete within acceptable time
|
||||
- [x] Operation queuing for thread safety
|
||||
- [x] Proper initialization handling
|
||||
- [ ] Performance monitoring (planned)
|
||||
|
||||
3. **Security**
|
||||
- [x] Basic data integrity
|
||||
- [ ] Encryption (planned for native platforms)
|
||||
- [ ] Secure key storage (planned)
|
||||
- [ ] Platform-specific security features (planned)
|
||||
|
||||
4. **Testing**
|
||||
- [x] Basic unit tests
|
||||
- [ ] Comprehensive integration tests (planned)
|
||||
- [ ] Platform-specific tests (planned)
|
||||
- [ ] Migration tests (planned)
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. **Native Platform Support**
|
||||
- Implement SQLCipher for iOS/Android
|
||||
- Add platform-specific secure storage
|
||||
- Implement biometric authentication
|
||||
|
||||
2. **Enhanced Security**
|
||||
- Add encryption for sensitive data
|
||||
- Implement secure key storage
|
||||
- Add platform-specific security features
|
||||
|
||||
3. **Testing and Monitoring**
|
||||
- Add comprehensive test coverage
|
||||
- Implement performance monitoring
|
||||
- Add error tracking and analytics
|
||||
|
||||
4. **Documentation**
|
||||
- Add API documentation
|
||||
- Create migration guides
|
||||
- Document security measures
|
||||
329
doc/storage-implementation-checklist.md
Normal file
329
doc/storage-implementation-checklist.md
Normal file
@@ -0,0 +1,329 @@
|
||||
# Storage Implementation Checklist
|
||||
|
||||
## Core Services
|
||||
|
||||
### 1. Storage Service Layer
|
||||
- [x] Create base `PlatformService` interface
|
||||
- [x] Define common methods for all platforms
|
||||
- [x] Add platform-specific method signatures
|
||||
- [x] Include error handling types
|
||||
- [x] Add migration support methods
|
||||
|
||||
- [x] Implement platform-specific services
|
||||
- [x] `AbsurdSqlDatabaseService` (web)
|
||||
- [x] Database initialization
|
||||
- [x] VFS setup with IndexedDB backend
|
||||
- [x] Connection management
|
||||
- [x] Operation queuing
|
||||
- [ ] `NativeSQLiteService` (iOS/Android) (planned)
|
||||
- [ ] SQLCipher integration
|
||||
- [ ] Native bridge setup
|
||||
- [ ] File system access
|
||||
- [ ] `ElectronSQLiteService` (planned)
|
||||
- [ ] Node SQLite integration
|
||||
- [ ] IPC communication
|
||||
- [ ] File system access
|
||||
|
||||
### 2. Migration Services
|
||||
- [x] Implement basic migration support
|
||||
- [x] Dual-storage pattern (SQLite + Dexie)
|
||||
- [x] Basic data verification
|
||||
- [ ] Rollback procedures (planned)
|
||||
- [ ] Progress tracking (planned)
|
||||
- [ ] Create `MigrationUI` components (planned)
|
||||
- [ ] Progress indicators
|
||||
- [ ] Error handling
|
||||
- [ ] User notifications
|
||||
- [ ] Manual triggers
|
||||
|
||||
### 3. Security Layer
|
||||
- [x] Basic data integrity
|
||||
- [ ] Implement `EncryptionService` (planned)
|
||||
- [ ] Key management
|
||||
- [ ] Encryption/decryption
|
||||
- [ ] Secure storage
|
||||
- [ ] Add `BiometricService` (planned)
|
||||
- [ ] Platform detection
|
||||
- [ ] Authentication flow
|
||||
- [ ] Fallback mechanisms
|
||||
|
||||
## Platform-Specific Implementation
|
||||
|
||||
### Web Platform
|
||||
- [x] Setup absurd-sql
|
||||
- [x] Install dependencies
|
||||
```json
|
||||
{
|
||||
"@jlongster/sql.js": "^1.8.0",
|
||||
"absurd-sql": "^1.8.0"
|
||||
}
|
||||
```
|
||||
- [x] Configure VFS with IndexedDB backend
|
||||
- [x] Setup worker threads
|
||||
- [x] Implement operation queuing
|
||||
- [x] Configure database pragmas
|
||||
|
||||
```sql
|
||||
PRAGMA journal_mode=MEMORY;
|
||||
PRAGMA synchronous=NORMAL;
|
||||
PRAGMA foreign_keys=ON;
|
||||
PRAGMA busy_timeout=5000;
|
||||
```
|
||||
|
||||
- [x] Update build configuration
|
||||
- [x] Modify `vite.config.ts`
|
||||
- [x] Add worker configuration
|
||||
- [x] Update chunk splitting
|
||||
- [x] Configure asset handling
|
||||
|
||||
- [x] Implement IndexedDB backend
|
||||
- [x] Create database service
|
||||
- [x] Add operation queuing
|
||||
- [x] Handle initialization
|
||||
- [x] Implement atomic operations
|
||||
|
||||
### iOS Platform (Planned)
|
||||
- [ ] Setup SQLCipher
|
||||
- [ ] Install pod dependencies
|
||||
- [ ] Configure encryption
|
||||
- [ ] Setup keychain access
|
||||
- [ ] Implement secure storage
|
||||
|
||||
- [ ] Update Capacitor config
|
||||
- [ ] Modify `capacitor.config.ts`
|
||||
- [ ] Add iOS permissions
|
||||
- [ ] Configure backup
|
||||
- [ ] Setup app groups
|
||||
|
||||
### Android Platform (Planned)
|
||||
- [ ] Setup SQLCipher
|
||||
- [ ] Add Gradle dependencies
|
||||
- [ ] Configure encryption
|
||||
- [ ] Setup keystore
|
||||
- [ ] Implement secure storage
|
||||
|
||||
- [ ] Update Capacitor config
|
||||
- [ ] Modify `capacitor.config.ts`
|
||||
- [ ] Add Android permissions
|
||||
- [ ] Configure backup
|
||||
- [ ] Setup file provider
|
||||
|
||||
### Electron Platform (Planned)
|
||||
- [ ] Setup Node SQLite
|
||||
- [ ] Install dependencies
|
||||
- [ ] Configure IPC
|
||||
- [ ] Setup file system access
|
||||
- [ ] Implement secure storage
|
||||
|
||||
- [ ] Update Electron config
|
||||
- [ ] Modify `electron.config.ts`
|
||||
- [ ] Add security policies
|
||||
- [ ] Configure file access
|
||||
- [ ] Setup auto-updates
|
||||
|
||||
## Data Models and Types
|
||||
|
||||
### 1. Database Schema
|
||||
- [x] Define tables
|
||||
|
||||
```sql
|
||||
-- Accounts table
|
||||
CREATE TABLE accounts (
|
||||
did TEXT PRIMARY KEY,
|
||||
public_key_hex TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
-- Settings table
|
||||
CREATE TABLE settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
-- Contacts table
|
||||
CREATE TABLE contacts (
|
||||
id TEXT PRIMARY KEY,
|
||||
did TEXT NOT NULL,
|
||||
name TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
FOREIGN KEY (did) REFERENCES accounts(did)
|
||||
);
|
||||
|
||||
-- Indexes for performance
|
||||
CREATE INDEX idx_accounts_created_at ON accounts(created_at);
|
||||
CREATE INDEX idx_contacts_did ON contacts(did);
|
||||
CREATE INDEX idx_settings_updated_at ON settings(updated_at);
|
||||
```
|
||||
|
||||
- [x] Create indexes
|
||||
- [x] Define constraints
|
||||
- [ ] Add triggers (planned)
|
||||
- [ ] Setup migrations (planned)
|
||||
|
||||
### 2. Type Definitions
|
||||
|
||||
- [x] Create interfaces
|
||||
```typescript
|
||||
interface Account {
|
||||
did: string;
|
||||
publicKeyHex: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
interface Setting {
|
||||
key: string;
|
||||
value: string;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
interface Contact {
|
||||
id: string;
|
||||
did: string;
|
||||
name?: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
```
|
||||
|
||||
- [x] Add validation
|
||||
- [x] Create DTOs
|
||||
- [x] Define enums
|
||||
- [x] Add type guards
|
||||
|
||||
## UI Components
|
||||
|
||||
### 1. Migration UI (Planned)
|
||||
- [ ] Create components
|
||||
- [ ] `MigrationProgress.vue`
|
||||
- [ ] `MigrationError.vue`
|
||||
- [ ] `MigrationSettings.vue`
|
||||
- [ ] `MigrationStatus.vue`
|
||||
|
||||
### 2. Settings UI (Planned)
|
||||
- [ ] Update components
|
||||
- [ ] Add storage settings
|
||||
- [ ] Add migration controls
|
||||
- [ ] Add backup options
|
||||
- [ ] Add security settings
|
||||
|
||||
### 3. Error Handling UI (Planned)
|
||||
- [ ] Create components
|
||||
- [ ] `StorageError.vue`
|
||||
- [ ] `QuotaExceeded.vue`
|
||||
- [ ] `MigrationFailed.vue`
|
||||
- [ ] `RecoveryOptions.vue`
|
||||
|
||||
## Testing
|
||||
|
||||
### 1. Unit Tests
|
||||
- [x] Basic service tests
|
||||
- [x] Platform service tests
|
||||
- [x] Database operation tests
|
||||
- [ ] Security service tests (planned)
|
||||
- [ ] Platform detection tests (planned)
|
||||
|
||||
### 2. Integration Tests (Planned)
|
||||
- [ ] Test migrations
|
||||
- [ ] Web platform tests
|
||||
- [ ] iOS platform tests
|
||||
- [ ] Android platform tests
|
||||
- [ ] Electron platform tests
|
||||
|
||||
### 3. E2E Tests (Planned)
|
||||
- [ ] Test workflows
|
||||
- [ ] Account management
|
||||
- [ ] Settings management
|
||||
- [ ] Contact management
|
||||
- [ ] Migration process
|
||||
|
||||
## Documentation
|
||||
|
||||
### 1. Technical Documentation
|
||||
- [x] Update architecture docs
|
||||
- [x] Add API documentation
|
||||
- [ ] Create migration guides (planned)
|
||||
- [ ] Document security measures (planned)
|
||||
|
||||
### 2. User Documentation (Planned)
|
||||
- [ ] Update user guides
|
||||
- [ ] Add troubleshooting guides
|
||||
- [ ] Create FAQ
|
||||
- [ ] Document new features
|
||||
|
||||
## Deployment
|
||||
|
||||
### 1. Build Process
|
||||
- [x] Update build scripts
|
||||
- [x] Add platform-specific builds
|
||||
- [ ] Configure CI/CD (planned)
|
||||
- [ ] Setup automated testing (planned)
|
||||
|
||||
### 2. Release Process (Planned)
|
||||
- [ ] Create release checklist
|
||||
- [ ] Add version management
|
||||
- [ ] Setup rollback procedures
|
||||
- [ ] Configure monitoring
|
||||
|
||||
## Monitoring and Analytics (Planned)
|
||||
|
||||
### 1. Error Tracking
|
||||
- [ ] Setup error logging
|
||||
- [ ] Add performance monitoring
|
||||
- [ ] Configure alerts
|
||||
- [ ] Create dashboards
|
||||
|
||||
### 2. Usage Analytics
|
||||
- [ ] Add storage metrics
|
||||
- [ ] Track migration success
|
||||
- [ ] Monitor performance
|
||||
- [ ] Collect user feedback
|
||||
|
||||
## Security Audit (Planned)
|
||||
|
||||
### 1. Code Review
|
||||
- [ ] Review encryption
|
||||
- [ ] Check access controls
|
||||
- [ ] Verify data handling
|
||||
- [ ] Audit dependencies
|
||||
|
||||
### 2. Penetration Testing
|
||||
- [ ] Test data access
|
||||
- [ ] Verify encryption
|
||||
- [ ] Check authentication
|
||||
- [ ] Review permissions
|
||||
|
||||
## Success Criteria
|
||||
|
||||
### 1. Performance
|
||||
- [x] Query response time < 100ms
|
||||
- [x] Operation queuing for thread safety
|
||||
- [x] Proper initialization handling
|
||||
- [ ] Migration time < 5s per 1000 records (planned)
|
||||
- [ ] Storage overhead < 10% (planned)
|
||||
- [ ] Memory usage < 50MB (planned)
|
||||
|
||||
### 2. Reliability
|
||||
- [x] Basic data integrity
|
||||
- [x] Operation queuing
|
||||
- [ ] Automatic recovery (planned)
|
||||
- [ ] Backup verification (planned)
|
||||
- [ ] Transaction atomicity (planned)
|
||||
- [ ] Data consistency (planned)
|
||||
|
||||
### 3. Security
|
||||
- [x] Basic data integrity
|
||||
- [ ] AES-256 encryption (planned)
|
||||
- [ ] Secure key storage (planned)
|
||||
- [ ] Access control (planned)
|
||||
- [ ] Audit logging (planned)
|
||||
|
||||
### 4. User Experience
|
||||
- [x] Basic database operations
|
||||
- [ ] Smooth migration (planned)
|
||||
- [ ] Clear error messages (planned)
|
||||
- [ ] Progress indicators (planned)
|
||||
- [ ] Recovery options (planned)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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 */; };
|
||||
A084ECDBA7D38E1E42DFC39D /* Pods_App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */; };
|
||||
97EF2DC6FD76C3643D680B8D /* Pods_App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 90DCAFB4D8948F7A50C13800 /* 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>"; };
|
||||
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>"; };
|
||||
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>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -37,17 +37,17 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
A084ECDBA7D38E1E42DFC39D /* Pods_App.framework in Frameworks */,
|
||||
97EF2DC6FD76C3643D680B8D /* Pods_App.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
27E2DDA53C4D2A4D1A88CE4A /* Frameworks */ = {
|
||||
4B546315E668C7A13939F417 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */,
|
||||
90DCAFB4D8948F7A50C13800 /* Pods_App.framework */,
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
@@ -57,8 +57,8 @@
|
||||
children = (
|
||||
504EC3061FED79650016851F /* App */,
|
||||
504EC3051FED79650016851F /* Products */,
|
||||
7F8756D8B27F46E3366F6CEA /* Pods */,
|
||||
27E2DDA53C4D2A4D1A88CE4A /* Frameworks */,
|
||||
BA325FFCDCE8D334E5C7AEBE /* Pods */,
|
||||
4B546315E668C7A13939F417 /* Frameworks */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
@@ -85,13 +85,13 @@
|
||||
path = App;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
7F8756D8B27F46E3366F6CEA /* Pods */ = {
|
||||
BA325FFCDCE8D334E5C7AEBE /* Pods */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */,
|
||||
AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */,
|
||||
EAEC6436E595F7CD3A1C9E96 /* Pods-App.debug.xcconfig */,
|
||||
E2E9297D5D02C549106C77F9 /* Pods-App.release.xcconfig */,
|
||||
);
|
||||
name = Pods;
|
||||
path = Pods;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
@@ -101,12 +101,13 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 504EC3161FED79650016851F /* Build configuration list for PBXNativeTarget "App" */;
|
||||
buildPhases = (
|
||||
6634F4EFEBD30273BCE97C65 /* [CP] Check Pods Manifest.lock */,
|
||||
92977BEA1068CC097A57FC77 /* [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 = (
|
||||
);
|
||||
@@ -186,28 +187,10 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "\"${PROJECT_DIR}/app_privacy_manifest_fixer/fixer.sh\" ";
|
||||
shellScript = "\"${PROJECT_DIR}/app_privacy_manifest_fixer/fixer.sh\" \n";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
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 */ = {
|
||||
3525031ED1C96EF4CF6E9959 /* [CP] Embed Pods Frameworks */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
@@ -222,6 +205,47 @@
|
||||
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 */
|
||||
@@ -375,11 +399,11 @@
|
||||
};
|
||||
504EC3171FED79650016851F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = FC68EB0AF532CFC21C3344DD /* Pods-App.debug.xcconfig */;
|
||||
baseConfigurationReference = EAEC6436E595F7CD3A1C9E96 /* Pods-App.debug.xcconfig */;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 18;
|
||||
CURRENT_PROJECT_VERSION = 26;
|
||||
DEVELOPMENT_TEAM = GM3FS5JQPH;
|
||||
ENABLE_APP_SANDBOX = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
@@ -389,7 +413,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 0.4.7;
|
||||
MARKETING_VERSION = 0.5.1;
|
||||
OTHER_SWIFT_FLAGS = "$(inherited) \"-D\" \"COCOAPODS\" \"-DDEBUG\"";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
@@ -402,11 +426,11 @@
|
||||
};
|
||||
504EC3181FED79650016851F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
baseConfigurationReference = AF51FD2D460BCFE21FA515B2 /* Pods-App.release.xcconfig */;
|
||||
baseConfigurationReference = E2E9297D5D02C549106C77F9 /* Pods-App.release.xcconfig */;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 18;
|
||||
CURRENT_PROJECT_VERSION = 26;
|
||||
DEVELOPMENT_TEAM = GM3FS5JQPH;
|
||||
ENABLE_APP_SANDBOX = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
@@ -416,7 +440,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 0.4.7;
|
||||
MARKETING_VERSION = 0.5.1;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = app.timesafari;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import UIKit
|
||||
import Capacitor
|
||||
import CapacitorCommunitySqlite
|
||||
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
@@ -7,6 +8,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
var window: UIWindow?
|
||||
|
||||
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
|
||||
// Initialize SQLite
|
||||
//let sqlite = SQLite()
|
||||
//sqlite.initialize()
|
||||
|
||||
// Override point for customization after application launch.
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ install! 'cocoapods', :disable_input_output_paths => true
|
||||
def capacitor_pods
|
||||
pod 'Capacitor', :path => '../../node_modules/@capacitor/ios'
|
||||
pod 'CapacitorCordova', :path => '../../node_modules/@capacitor/ios'
|
||||
pod 'CapacitorCommunitySqlite', :path => '../../node_modules/@capacitor-community/sqlite'
|
||||
pod 'CapacitorMlkitBarcodeScanning', :path => '../../node_modules/@capacitor-mlkit/barcode-scanning'
|
||||
pod 'CapacitorApp', :path => '../../node_modules/@capacitor/app'
|
||||
pod 'CapacitorCamera', :path => '../../node_modules/@capacitor/camera'
|
||||
@@ -26,4 +27,9 @@ 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,6 +5,10 @@ PODS:
|
||||
- Capacitor
|
||||
- CapacitorCamera (6.1.2):
|
||||
- Capacitor
|
||||
- CapacitorCommunitySqlite (6.0.2):
|
||||
- Capacitor
|
||||
- SQLCipher
|
||||
- ZIPFoundation
|
||||
- CapacitorCordova (6.2.1)
|
||||
- CapacitorFilesystem (6.0.3):
|
||||
- Capacitor
|
||||
@@ -73,11 +77,18 @@ 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`)"
|
||||
@@ -98,6 +109,8 @@ SPEC REPOS:
|
||||
- MLKitVision
|
||||
- nanopb
|
||||
- PromisesObjC
|
||||
- SQLCipher
|
||||
- ZIPFoundation
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
Capacitor:
|
||||
@@ -106,6 +119,8 @@ 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:
|
||||
@@ -121,6 +136,7 @@ SPEC CHECKSUMS:
|
||||
Capacitor: c95400d761e376be9da6be5a05f226c0e865cebf
|
||||
CapacitorApp: e1e6b7d05e444d593ca16fd6d76f2b7c48b5aea7
|
||||
CapacitorCamera: 9bc7b005d0e6f1d5f525b8137045b60cffffce79
|
||||
CapacitorCommunitySqlite: 0299d20f4b00c2e6aa485a1d8932656753937b9b
|
||||
CapacitorCordova: 8d93e14982f440181be7304aa9559ca631d77fff
|
||||
CapacitorFilesystem: 59270a63c60836248812671aa3b15df673fbaf74
|
||||
CapacitorMlkitBarcodeScanning: 7652be9c7922f39203a361de735d340ae37e134e
|
||||
@@ -138,7 +154,9 @@ SPEC CHECKSUMS:
|
||||
MLKitVision: 90922bca854014a856f8b649d1f1f04f63fd9c79
|
||||
nanopb: 438bc412db1928dac798aa6fd75726007be04262
|
||||
PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47
|
||||
SQLCipher: 31878d8ebd27e5c96db0b7cb695c96e9f8ad77da
|
||||
ZIPFoundation: b8c29ea7ae353b309bc810586181fd073cb3312c
|
||||
|
||||
PODFILE CHECKSUM: 7e7e09e6937de7f015393aecf2cf7823645689b3
|
||||
PODFILE CHECKSUM: f987510f7383b04a1b09ea8472bdadcd88b6c924
|
||||
|
||||
COCOAPODS: 1.16.2
|
||||
|
||||
29
main.js
29
main.js
@@ -1,29 +0,0 @@
|
||||
const { app, BrowserWindow } = require('electron');
|
||||
const path = require('path');
|
||||
|
||||
function createWindow() {
|
||||
const win = new BrowserWindow({
|
||||
width: 1200,
|
||||
height: 800,
|
||||
webPreferences: {
|
||||
nodeIntegration: true,
|
||||
contextIsolation: false
|
||||
}
|
||||
});
|
||||
|
||||
win.loadFile(path.join(__dirname, 'dist-electron/www/index.html'));
|
||||
}
|
||||
|
||||
app.whenReady().then(createWindow);
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
5873
package-lock.json
generated
5873
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
14
package.json
14
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "timesafari",
|
||||
"version": "0.4.6",
|
||||
"version": "0.5.1",
|
||||
"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",
|
||||
"prebuild": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src && node sw_combine.js && node scripts/copy-wasm.js",
|
||||
"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",
|
||||
@@ -46,6 +46,7 @@
|
||||
"electron:build-mac-universal": "npm run build:electron-prod && electron-builder --mac --universal"
|
||||
},
|
||||
"dependencies": {
|
||||
"@capacitor-community/sqlite": "6.0.2",
|
||||
"@capacitor-mlkit/barcode-scanning": "^6.0.0",
|
||||
"@capacitor/android": "^6.2.0",
|
||||
"@capacitor/app": "^6.0.0",
|
||||
@@ -63,6 +64,7 @@
|
||||
"@fortawesome/fontawesome-svg-core": "^6.5.1",
|
||||
"@fortawesome/free-solid-svg-icons": "^6.5.1",
|
||||
"@fortawesome/vue-fontawesome": "^3.0.6",
|
||||
"@jlongster/sql.js": "^1.6.7",
|
||||
"@peculiar/asn1-ecc": "^2.3.8",
|
||||
"@peculiar/asn1-schema": "^2.3.8",
|
||||
"@pvermeer/dexie-encrypted-addon": "^3.0.0",
|
||||
@@ -81,6 +83,7 @@
|
||||
"@vue-leaflet/vue-leaflet": "^0.10.1",
|
||||
"@vueuse/core": "^12.3.0",
|
||||
"@zxing/text-encoding": "^0.9.0",
|
||||
"absurd-sql": "^0.0.54",
|
||||
"asn1-ber": "^1.2.2",
|
||||
"axios": "^1.6.8",
|
||||
"cbor-x": "^1.5.9",
|
||||
@@ -144,7 +147,9 @@
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"@vue/eslint-config-typescript": "^11.0.3",
|
||||
"autoprefixer": "^10.4.19",
|
||||
"browserify-fs": "^1.0.0",
|
||||
"concurrently": "^8.2.2",
|
||||
"crypto-browserify": "^3.12.1",
|
||||
"electron": "^33.2.1",
|
||||
"electron-builder": "^25.1.8",
|
||||
"eslint": "^8.57.0",
|
||||
@@ -155,13 +160,14 @@
|
||||
"markdownlint": "^0.37.4",
|
||||
"markdownlint-cli": "^0.44.0",
|
||||
"npm-check-updates": "^17.1.13",
|
||||
"path-browserify": "^1.0.1",
|
||||
"postcss": "^8.4.38",
|
||||
"prettier": "^3.2.5",
|
||||
"rimraf": "^6.0.1",
|
||||
"tailwindcss": "^3.4.1",
|
||||
"typescript": "~5.2.2",
|
||||
"vite": "^5.2.0",
|
||||
"vite-plugin-pwa": "^0.19.8"
|
||||
"vite-plugin-pwa": "^1.0.0"
|
||||
},
|
||||
"main": "./dist-electron/main.js",
|
||||
"build": {
|
||||
@@ -176,7 +182,7 @@
|
||||
],
|
||||
"extraResources": [
|
||||
{
|
||||
"from": "dist",
|
||||
"from": "dist-electron/www",
|
||||
"to": "www"
|
||||
}
|
||||
],
|
||||
|
||||
@@ -2,5 +2,6 @@ dependencies:
|
||||
- gradle
|
||||
- java
|
||||
- pod
|
||||
- rubygems.org
|
||||
|
||||
# other dependencies are discovered via package.json & requirements.txt & Gemfile (I'm guessing).
|
||||
|
||||
BIN
public/wasm/sql-wasm.wasm
Executable file
BIN
public/wasm/sql-wasm.wasm
Executable file
Binary file not shown.
@@ -1,5 +1,6 @@
|
||||
eth_keys
|
||||
pywebview
|
||||
pyinstaller>=6.12.0
|
||||
setuptools>=69.0.0 # Required for distutils for electron-builder on macOS
|
||||
# For development
|
||||
watchdog>=3.0.0 # For file watching support
|
||||
@@ -1,10 +1,9 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
console.log('Starting electron build process...');
|
||||
console.log('Starting electron build process...');
|
||||
|
||||
// Copy web files
|
||||
const webDistPath = path.join(__dirname, '..', 'dist');
|
||||
// Define paths
|
||||
const electronDistPath = path.join(__dirname, '..', 'dist-electron');
|
||||
const wwwPath = path.join(electronDistPath, 'www');
|
||||
|
||||
@@ -13,231 +12,154 @@ if (!fs.existsSync(wwwPath)) {
|
||||
fs.mkdirSync(wwwPath, { recursive: true });
|
||||
}
|
||||
|
||||
// Copy web files to www directory
|
||||
fs.cpSync(webDistPath, 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>`;
|
||||
|
||||
// Fix asset paths in index.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');
|
||||
let indexContent = fs.readFileSync(indexPath, 'utf8');
|
||||
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
|
||||
indexContent = indexContent
|
||||
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, indexContent);
|
||||
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:', indexContent.includes('/assets/'));
|
||||
console.log('Sample of fixed content:', indexContent.substring(0, 500));
|
||||
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 main process files
|
||||
console.log('Copying main process files...');
|
||||
|
||||
// Create the main process file with inlined logger
|
||||
const mainContent = `const { app, BrowserWindow } = require("electron");
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
// 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');
|
||||
|
||||
// Inline logger implementation
|
||||
const logger = {
|
||||
log: (...args) => console.log(...args),
|
||||
error: (...args) => console.error(...args),
|
||||
info: (...args) => console.info(...args),
|
||||
warn: (...args) => console.warn(...args),
|
||||
debug: (...args) => console.debug(...args),
|
||||
};
|
||||
|
||||
// Check if running in dev mode
|
||||
const isDev = process.argv.includes("--inspect");
|
||||
|
||||
function createWindow() {
|
||||
// Add before createWindow function
|
||||
const preloadPath = path.join(__dirname, "preload.js");
|
||||
logger.log("Checking preload path:", preloadPath);
|
||||
logger.log("Preload exists:", fs.existsSync(preloadPath));
|
||||
|
||||
// Create the browser window.
|
||||
const mainWindow = new BrowserWindow({
|
||||
width: 1200,
|
||||
height: 800,
|
||||
webPreferences: {
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
webSecurity: true,
|
||||
allowRunningInsecureContent: false,
|
||||
preload: path.join(__dirname, "preload.js"),
|
||||
},
|
||||
});
|
||||
|
||||
// Always open DevTools for now
|
||||
mainWindow.webContents.openDevTools();
|
||||
|
||||
// Intercept requests to fix asset paths
|
||||
mainWindow.webContents.session.webRequest.onBeforeRequest(
|
||||
{
|
||||
urls: [
|
||||
"file://*/*/assets/*",
|
||||
"file://*/assets/*",
|
||||
"file:///assets/*", // Catch absolute paths
|
||||
"<all_urls>", // Catch all URLs as a fallback
|
||||
],
|
||||
},
|
||||
(details, callback) => {
|
||||
let url = details.url;
|
||||
|
||||
// Handle paths that don't start with file://
|
||||
if (!url.startsWith("file://") && url.includes("/assets/")) {
|
||||
url = \`file://\${path.join(__dirname, "www", url)}\`;
|
||||
}
|
||||
|
||||
// Handle absolute paths starting with /assets/
|
||||
if (url.includes("/assets/") && !url.includes("/www/assets/")) {
|
||||
const baseDir = url.includes("dist-electron")
|
||||
? url.substring(
|
||||
0,
|
||||
url.indexOf("/dist-electron") + "/dist-electron".length,
|
||||
)
|
||||
: \`file://\${__dirname}\`;
|
||||
const assetPath = url.split("/assets/")[1];
|
||||
const newUrl = \`\${baseDir}/www/assets/\${assetPath}\`;
|
||||
callback({ redirectURL: newUrl });
|
||||
return;
|
||||
}
|
||||
|
||||
callback({}); // No redirect for other URLs
|
||||
},
|
||||
);
|
||||
|
||||
if (isDev) {
|
||||
// Debug info
|
||||
logger.log("Debug Info:");
|
||||
logger.log("Running in dev mode:", isDev);
|
||||
logger.log("App is packaged:", app.isPackaged);
|
||||
logger.log("Process resource path:", process.resourcesPath);
|
||||
logger.log("App path:", app.getAppPath());
|
||||
logger.log("__dirname:", __dirname);
|
||||
logger.log("process.cwd():", process.cwd());
|
||||
}
|
||||
|
||||
const indexPath = path.join(__dirname, "www", "index.html");
|
||||
|
||||
if (isDev) {
|
||||
logger.log("Loading index from:", indexPath);
|
||||
logger.log("www path:", path.join(__dirname, "www"));
|
||||
logger.log("www assets path:", path.join(__dirname, "www", "assets"));
|
||||
}
|
||||
|
||||
if (!fs.existsSync(indexPath)) {
|
||||
logger.error(\`Index file not found at: \${indexPath}\`);
|
||||
throw new Error("Index file not found");
|
||||
}
|
||||
|
||||
// Add CSP headers to allow API connections, Google Fonts, and zxing-wasm
|
||||
mainWindow.webContents.session.webRequest.onHeadersReceived(
|
||||
(details, callback) => {
|
||||
callback({
|
||||
responseHeaders: {
|
||||
...details.responseHeaders,
|
||||
"Content-Security-Policy": [
|
||||
"default-src 'self';" +
|
||||
"connect-src 'self' https://api.endorser.ch https://*.timesafari.app https://*.jsdelivr.net;" +
|
||||
"img-src 'self' data: https: blob:;" +
|
||||
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://*.jsdelivr.net;" +
|
||||
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;" +
|
||||
"font-src 'self' data: https://fonts.gstatic.com;" +
|
||||
"style-src-elem 'self' 'unsafe-inline' https://fonts.googleapis.com;" +
|
||||
"worker-src 'self' blob:;",
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Load the index.html
|
||||
mainWindow
|
||||
.loadFile(indexPath)
|
||||
.then(() => {
|
||||
logger.log("Successfully loaded index.html");
|
||||
if (isDev) {
|
||||
mainWindow.webContents.openDevTools();
|
||||
logger.log("DevTools opened - running in dev mode");
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
logger.error("Failed to load index.html:", err);
|
||||
logger.error("Attempted path:", indexPath);
|
||||
});
|
||||
|
||||
// Listen for console messages from the renderer
|
||||
mainWindow.webContents.on("console-message", (_event, _level, message) => {
|
||||
logger.log("Renderer Console:", message);
|
||||
});
|
||||
|
||||
// Add right after creating the BrowserWindow
|
||||
mainWindow.webContents.on(
|
||||
"did-fail-load",
|
||||
(_event, errorCode, errorDescription) => {
|
||||
logger.error("Page failed to load:", errorCode, errorDescription);
|
||||
},
|
||||
);
|
||||
|
||||
mainWindow.webContents.on("preload-error", (_event, preloadPath, error) => {
|
||||
logger.error("Preload script error:", preloadPath, error);
|
||||
});
|
||||
|
||||
mainWindow.webContents.on(
|
||||
"console-message",
|
||||
(_event, _level, message, line, sourceId) => {
|
||||
logger.log("Renderer Console:", line, sourceId, message);
|
||||
},
|
||||
);
|
||||
|
||||
// Enable remote debugging when in dev mode
|
||||
if (isDev) {
|
||||
mainWindow.webContents.openDevTools();
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
// Handle app ready
|
||||
app.whenReady().then(createWindow);
|
||||
|
||||
// Handle all windows closed
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin") {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
|
||||
// Handle any errors
|
||||
process.on("uncaughtException", (error) => {
|
||||
logger.error("Uncaught Exception:", error);
|
||||
});
|
||||
`;
|
||||
|
||||
// Write the main process file
|
||||
const mainDest = path.join(electronDistPath, 'main.js');
|
||||
fs.writeFileSync(mainDest, mainContent);
|
||||
|
||||
// Copy preload script if it exists
|
||||
const preloadSrc = path.join(__dirname, '..', 'src', 'electron', 'preload.js');
|
||||
const preloadDest = path.join(electronDistPath, 'preload.js');
|
||||
if (fs.existsSync(preloadSrc)) {
|
||||
console.log(`Copying ${preloadSrc} to ${preloadDest}`);
|
||||
fs.copyFileSync(preloadSrc, preloadDest);
|
||||
}
|
||||
|
||||
// Verify build structure
|
||||
console.log('\nVerifying build structure:');
|
||||
console.log('Files in dist-electron:', fs.readdirSync(electronDistPath));
|
||||
|
||||
console.log('Build completed successfully!');
|
||||
console.log('Electron build process completed successfully');
|
||||
15
scripts/copy-wasm.js
Normal file
15
scripts/copy-wasm.js
Normal file
@@ -0,0 +1,15 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// Create public/wasm directory if it doesn't exist
|
||||
const wasmDir = path.join(__dirname, '../public/wasm');
|
||||
if (!fs.existsSync(wasmDir)) {
|
||||
fs.mkdirSync(wasmDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Copy the WASM file from node_modules to public/wasm
|
||||
const sourceFile = path.join(__dirname, '../node_modules/@jlongster/sql.js/dist/sql-wasm.wasm');
|
||||
const targetFile = path.join(wasmDir, 'sql-wasm.wasm');
|
||||
|
||||
fs.copyFileSync(sourceFile, targetFile);
|
||||
console.log('WASM file copied successfully!');
|
||||
13
src/App.vue
13
src/App.vue
@@ -330,8 +330,11 @@
|
||||
|
||||
<script lang="ts">
|
||||
import { Vue, Component } from "vue-facing-decorator";
|
||||
import { logConsoleAndDb, retrieveSettingsForActiveAccount } from "./db/index";
|
||||
import { NotificationIface } from "./constants/app";
|
||||
|
||||
import { NotificationIface, USE_DEXIE_DB } from "./constants/app";
|
||||
import * as databaseUtil from "./db/databaseUtil";
|
||||
import { retrieveSettingsForActiveAccount } from "./db/index";
|
||||
import { logConsoleAndDb } from "./db/databaseUtil";
|
||||
import { logger } from "./utils/logger";
|
||||
|
||||
interface Settings {
|
||||
@@ -396,7 +399,11 @@ export default class App extends Vue {
|
||||
|
||||
try {
|
||||
logger.log("Retrieving settings for the active account...");
|
||||
const settings: Settings = await retrieveSettingsForActiveAccount();
|
||||
let settings: Settings =
|
||||
await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
logger.log("Retrieved settings:", settings);
|
||||
|
||||
const notifyingNewActivity = !!settings?.notifyingNewActivityTime;
|
||||
|
||||
@@ -14,22 +14,34 @@
|
||||
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">
|
||||
<div v-if="record.issuerDid">
|
||||
<router-link
|
||||
v-if="record.issuerDid && !isHiddenDid(record.issuerDid)"
|
||||
:to="{
|
||||
path: '/did/' + encodeURIComponent(record.issuerDid),
|
||||
}"
|
||||
title="More details about this person"
|
||||
>
|
||||
<EntityIcon
|
||||
:entity-id="record.issuerDid"
|
||||
class="rounded-full bg-white overflow-hidden !size-[2rem] object-cover"
|
||||
/>
|
||||
</div>
|
||||
<div v-else>
|
||||
<font-awesome
|
||||
icon="person-circle-question"
|
||||
class="text-slate-300 text-[2rem]"
|
||||
/>
|
||||
</div>
|
||||
</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>
|
||||
<h3 class="font-semibold">
|
||||
{{ record.issuer.known ? record.issuer.displayName : "" }}
|
||||
<h3 v-if="record.issuer.known" class="font-semibold leading-tight">
|
||||
{{ record.issuer.displayName }}
|
||||
</h3>
|
||||
<p class="ms-auto text-xs text-slate-500 italic">
|
||||
{{ friendlyDate }}
|
||||
@@ -37,7 +49,11 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a class="cursor-pointer" @click="$emit('loadClaim', record.jwtId)">
|
||||
<a
|
||||
class="cursor-pointer"
|
||||
data-testid="circle-info-link"
|
||||
@click="$emit('loadClaim', record.jwtId)"
|
||||
>
|
||||
<font-awesome icon="circle-info" class="fa-fw text-slate-500" />
|
||||
</a>
|
||||
</div>
|
||||
@@ -46,7 +62,7 @@
|
||||
<!-- Record Image -->
|
||||
<div
|
||||
v-if="record.image"
|
||||
class="bg-cover mb-6 -mt-3 sm:-mt-4 -mx-3 sm:-mx-4"
|
||||
class="bg-cover mb-2 -mt-3 sm:-mt-4 -mx-3 sm:-mx-4"
|
||||
:style="`background-image: url(${record.image});`"
|
||||
>
|
||||
<a
|
||||
@@ -62,29 +78,59 @@
|
||||
</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 mb-5"
|
||||
class="relative flex justify-between gap-4 max-w-[40rem] mx-auto mt-4"
|
||||
>
|
||||
<!-- Source -->
|
||||
<div
|
||||
class="w-[8rem] sm:w-[12rem] text-center bg-white border border-slate-200 rounded p-2 sm:p-3"
|
||||
class="w-[7rem] 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">
|
||||
<ProjectIcon
|
||||
:entity-id="record.providerPlanName"
|
||||
:icon-size="48"
|
||||
class="rounded size-[3rem] sm:size-[4rem] *:w-full *:h-full"
|
||||
/>
|
||||
<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>
|
||||
</div>
|
||||
<!-- Identicon for DIDs -->
|
||||
<div v-else-if="record.agentDid">
|
||||
<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
|
||||
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"
|
||||
/>
|
||||
</div>
|
||||
<!-- Unknown Person -->
|
||||
@@ -92,6 +138,7 @@
|
||||
<font-awesome
|
||||
icon="person-circle-question"
|
||||
class="text-slate-300 text-[3rem] sm:text-[4rem]"
|
||||
@click="notifyUnknownPerson"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -110,9 +157,11 @@
|
||||
|
||||
<!-- Arrow -->
|
||||
<div
|
||||
class="absolute inset-x-[8rem] sm:inset-x-[12rem] mx-2 top-1/2 -translate-y-1/2"
|
||||
class="absolute inset-x-[7rem] sm:inset-x-[12rem] mx-2 top-1/2 -translate-y-1/2"
|
||||
>
|
||||
<div class="text-sm text-center leading-none font-semibold pe-[15px]">
|
||||
<div
|
||||
class="text-sm text-center leading-none font-semibold pe-2 sm:pe-4"
|
||||
>
|
||||
{{ fetchAmount }}
|
||||
</div>
|
||||
|
||||
@@ -129,24 +178,47 @@
|
||||
|
||||
<!-- Destination -->
|
||||
<div
|
||||
class="w-[8rem] sm:w-[12rem] text-center bg-white border border-slate-200 rounded p-2 sm:p-3"
|
||||
class="w-[7rem] 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">
|
||||
<ProjectIcon
|
||||
:entity-id="record.recipientProjectName"
|
||||
:icon-size="48"
|
||||
class="rounded size-[3rem] sm:size-[4rem] *:w-full *:h-full"
|
||||
/>
|
||||
<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>
|
||||
</div>
|
||||
<!-- Identicon for DIDs -->
|
||||
<div v-else-if="record.recipientDid">
|
||||
<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
|
||||
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"
|
||||
/>
|
||||
</div>
|
||||
<!-- Unknown Person -->
|
||||
@@ -154,6 +226,7 @@
|
||||
<font-awesome
|
||||
icon="person-circle-question"
|
||||
class="text-slate-300 text-[3rem] sm:text-[4rem]"
|
||||
@click="notifyUnknownPerson"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -170,13 +243,6 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Description -->
|
||||
<p class="font-medium">
|
||||
<a class="cursor-pointer" @click="$emit('loadClaim', record.jwtId)">
|
||||
{{ description }}
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
</template>
|
||||
@@ -186,8 +252,9 @@ 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 } from "../libs/endorserServer";
|
||||
import { containsHiddenDid, isHiddenDid } from "../libs/endorserServer";
|
||||
import ProjectIcon from "./ProjectIcon.vue";
|
||||
import { NotificationIface } from "../constants/app";
|
||||
|
||||
@Component({
|
||||
components: {
|
||||
@@ -202,6 +269,33 @@ 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;
|
||||
@@ -222,7 +316,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) {
|
||||
|
||||
207
src/components/AmountInput.vue
Normal file
207
src/components/AmountInput.vue
Normal file
@@ -0,0 +1,207 @@
|
||||
/** * AmountInput.vue - Specialized amount input with increment/decrement
|
||||
controls * * Extracted from GiftedDialog.vue to handle numeric amount input *
|
||||
with increment/decrement buttons and validation. * * @author Matthew Raymer */
|
||||
<template>
|
||||
<div class="flex flex-grow">
|
||||
<button
|
||||
class="rounded-s border border-e-0 border-slate-400 bg-slate-200 px-4 py-2"
|
||||
:disabled="isAtMinimum"
|
||||
type="button"
|
||||
@click.prevent="decrement"
|
||||
>
|
||||
<font-awesome icon="chevron-left" />
|
||||
</button>
|
||||
|
||||
<input
|
||||
:id="inputId"
|
||||
v-model="displayValue"
|
||||
type="number"
|
||||
:min="min"
|
||||
:max="max"
|
||||
:step="step"
|
||||
class="flex-1 border border-e-0 border-slate-400 px-2 py-2 text-center w-[1px]"
|
||||
@input="handleInput"
|
||||
@blur="handleBlur"
|
||||
/>
|
||||
|
||||
<button
|
||||
class="rounded-e border border-slate-400 bg-slate-200 px-4 py-2"
|
||||
:disabled="isAtMaximum"
|
||||
type="button"
|
||||
@click.prevent="increment"
|
||||
>
|
||||
<font-awesome icon="chevron-right" />
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Watch, Emit } from "vue-facing-decorator";
|
||||
|
||||
/**
|
||||
* AmountInput - Numeric input with increment/decrement controls
|
||||
*
|
||||
* Features:
|
||||
* - Increment/decrement buttons with validation
|
||||
* - Configurable min/max values and step size
|
||||
* - Input validation and formatting
|
||||
* - Disabled state handling for boundary values
|
||||
* - Emits update events for v-model compatibility
|
||||
*/
|
||||
@Component
|
||||
export default class AmountInput extends Vue {
|
||||
/** Current numeric value */
|
||||
@Prop({ required: true })
|
||||
value!: number;
|
||||
|
||||
/** Minimum allowed value */
|
||||
@Prop({ default: 0 })
|
||||
min!: number;
|
||||
|
||||
/** Maximum allowed value */
|
||||
@Prop({ default: Number.MAX_SAFE_INTEGER })
|
||||
max!: number;
|
||||
|
||||
/** Step size for increment/decrement */
|
||||
@Prop({ default: 1 })
|
||||
step!: number;
|
||||
|
||||
/** Input element ID for accessibility */
|
||||
@Prop({ default: "amount-input" })
|
||||
inputId!: string;
|
||||
|
||||
/** Internal display value for input field */
|
||||
private displayValue: string = "0";
|
||||
|
||||
/**
|
||||
* Initialize display value from prop
|
||||
*/
|
||||
mounted(): void {
|
||||
console.log(
|
||||
`[AmountInput] mounted() - initial value: ${this.value}, min: ${this.min}, max: ${this.max}, step: ${this.step}`,
|
||||
);
|
||||
this.displayValue = this.value.toString();
|
||||
console.log(
|
||||
`[AmountInput] mounted() - displayValue set to: ${this.displayValue}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Watch for external value changes
|
||||
*/
|
||||
@Watch("value")
|
||||
onValueChange(newValue: number): void {
|
||||
this.displayValue = newValue.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if current value is at minimum
|
||||
*/
|
||||
get isAtMinimum(): boolean {
|
||||
const result = this.value <= this.min;
|
||||
console.log(
|
||||
`[AmountInput] isAtMinimum - value: ${this.value}, min: ${this.min}, result: ${result}`,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if current value is at maximum
|
||||
*/
|
||||
get isAtMaximum(): boolean {
|
||||
const result = this.value >= this.max;
|
||||
console.log(
|
||||
`[AmountInput] isAtMaximum - value: ${this.value}, max: ${this.max}, result: ${result}`,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment the value by step size
|
||||
*/
|
||||
increment(): void {
|
||||
console.log(
|
||||
`[AmountInput] increment() called - current value: ${this.value}, step: ${this.step}`,
|
||||
);
|
||||
const newValue = Math.min(this.value + this.step, this.max);
|
||||
console.log(`[AmountInput] increment() calculated newValue: ${newValue}`);
|
||||
this.updateValue(newValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrement the value by step size
|
||||
*/
|
||||
decrement(): void {
|
||||
console.log(
|
||||
`[AmountInput] decrement() called - current value: ${this.value}, step: ${this.step}`,
|
||||
);
|
||||
const newValue = Math.max(this.value - this.step, this.min);
|
||||
console.log(`[AmountInput] decrement() calculated newValue: ${newValue}`);
|
||||
this.updateValue(newValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle direct input changes
|
||||
*/
|
||||
handleInput(): void {
|
||||
const numericValue = parseFloat(this.displayValue);
|
||||
if (!isNaN(numericValue)) {
|
||||
const clampedValue = Math.max(this.min, Math.min(numericValue, this.max));
|
||||
this.updateValue(clampedValue);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle input blur - ensure display value matches actual value
|
||||
*/
|
||||
handleBlur(): void {
|
||||
this.displayValue = this.value.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the value and emit change event
|
||||
*/
|
||||
private updateValue(newValue: number): void {
|
||||
console.log(
|
||||
`[AmountInput] updateValue() called - oldValue: ${this.value}, newValue: ${newValue}`,
|
||||
);
|
||||
if (newValue !== this.value) {
|
||||
console.log(
|
||||
`[AmountInput] updateValue() - values different, updating and emitting`,
|
||||
);
|
||||
this.displayValue = newValue.toString();
|
||||
this.emitUpdateValue(newValue);
|
||||
} else {
|
||||
console.log(`[AmountInput] updateValue() - values same, skipping update`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit update:value event
|
||||
*/
|
||||
@Emit("update:value")
|
||||
emitUpdateValue(value: number): number {
|
||||
console.log(`[AmountInput] emitUpdateValue() - emitting value: ${value}`);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* Remove spinner arrows from number input */
|
||||
input[type="number"]::-webkit-outer-spin-button,
|
||||
input[type="number"]::-webkit-inner-spin-button {
|
||||
-webkit-appearance: none;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
input[type="number"] {
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
|
||||
/* Disabled button styles */
|
||||
button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
</style>
|
||||
@@ -24,9 +24,7 @@ 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 Settings & Contacts
|
||||
<br />
|
||||
(excluding Identifier Data)
|
||||
Download Contacts
|
||||
</button>
|
||||
<a
|
||||
ref="downloadLink"
|
||||
@@ -62,14 +60,18 @@ backup and database export, with platform-specific download instructions. * *
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue } from "vue-facing-decorator";
|
||||
import { NotificationIface } from "../constants/app";
|
||||
import { db } from "../db/index";
|
||||
import { AppString, NotificationIface } from "../constants/app";
|
||||
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
|
||||
import { logger } from "../utils/logger";
|
||||
import { PlatformServiceFactory } from "../services/PlatformServiceFactory";
|
||||
import {
|
||||
PlatformService,
|
||||
PlatformCapabilities,
|
||||
} from "../services/PlatformService";
|
||||
import { contactsToExportJson } from "../libs/util";
|
||||
|
||||
/**
|
||||
* @vue-component
|
||||
@@ -131,21 +133,25 @@ export default class DataExportSection extends Vue {
|
||||
*/
|
||||
public async exportDatabase() {
|
||||
try {
|
||||
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 = `${db.name}-backup.json`;
|
||||
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) {
|
||||
// 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`;
|
||||
|
||||
if (this.platformCapabilities.hasFileDownload) {
|
||||
// Web platform: Use download link
|
||||
@@ -157,8 +163,9 @@ export default class DataExportSection extends Vue {
|
||||
setTimeout(() => URL.revokeObjectURL(this.downloadUrl), 1000);
|
||||
} else if (this.platformCapabilities.hasFileSystem) {
|
||||
// Native platform: Write to app directory
|
||||
const content = await blob.text();
|
||||
await this.platformService.writeAndShareFile(fileName, content);
|
||||
await this.platformService.writeAndShareFile(fileName, jsonStr);
|
||||
} else {
|
||||
throw new Error("This platform does not support file downloads.");
|
||||
}
|
||||
|
||||
this.$notify(
|
||||
@@ -167,10 +174,10 @@ export default class DataExportSection extends Vue {
|
||||
type: "success",
|
||||
title: "Export Successful",
|
||||
text: this.platformCapabilities.hasFileDownload
|
||||
? "See your downloads directory for the backup. It is in the Dexie format."
|
||||
: "You should have been prompted to save your backup file.",
|
||||
? "See your downloads directory for the backup."
|
||||
: "The backup file has been saved.",
|
||||
},
|
||||
-1,
|
||||
3000,
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error("Export Error:", error);
|
||||
|
||||
264
src/components/EntityGrid.vue
Normal file
264
src/components/EntityGrid.vue
Normal file
@@ -0,0 +1,264 @@
|
||||
/** * EntityGrid.vue - Unified entity grid layout component * * Extracted from
|
||||
GiftedDialog.vue to provide a reusable grid layout * for displaying people,
|
||||
projects, and special entities with selection. * * @author Matthew Raymer */
|
||||
<template>
|
||||
<ul :class="gridClasses">
|
||||
<!-- Special entities (You, Unnamed) for people grids -->
|
||||
<template v-if="entityType === 'people'">
|
||||
<!-- "You" entity -->
|
||||
<SpecialEntityCard
|
||||
v-if="showYouEntity"
|
||||
entity-type="you"
|
||||
label="You"
|
||||
icon="hand"
|
||||
:selectable="youSelectable"
|
||||
:conflicted="youConflicted"
|
||||
:entity-data="youEntityData"
|
||||
@entity-selected="handleEntitySelected"
|
||||
/>
|
||||
|
||||
<!-- "Unnamed" entity -->
|
||||
<SpecialEntityCard
|
||||
entity-type="unnamed"
|
||||
label="Unnamed"
|
||||
icon="circle-question"
|
||||
:entity-data="unnamedEntityData"
|
||||
@entity-selected="handleEntitySelected"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<!-- Empty state message -->
|
||||
<li
|
||||
v-if="entities.length === 0"
|
||||
class="text-xs text-slate-500 italic col-span-full"
|
||||
>
|
||||
{{ emptyStateMessage }}
|
||||
</li>
|
||||
|
||||
<!-- Entity cards (people or projects) -->
|
||||
<template v-if="entityType === 'people'">
|
||||
<PersonCard
|
||||
v-for="person in displayedEntities"
|
||||
:key="person.did"
|
||||
:person="person"
|
||||
:conflicted="isPersonConflicted(person.did)"
|
||||
:show-time-icon="true"
|
||||
@person-selected="handlePersonSelected"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else-if="entityType === 'projects'">
|
||||
<ProjectCard
|
||||
v-for="project in displayedEntities"
|
||||
:key="project.handleId"
|
||||
:project="project"
|
||||
:active-did="activeDid"
|
||||
:all-my-dids="allMyDids"
|
||||
:all-contacts="allContacts"
|
||||
@project-selected="handleProjectSelected"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<!-- Show All navigation -->
|
||||
<ShowAllCard
|
||||
v-if="shouldShowAll"
|
||||
:entity-type="entityType"
|
||||
:route-name="showAllRoute"
|
||||
:query-params="showAllQueryParams"
|
||||
/>
|
||||
</ul>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Emit } from "vue-facing-decorator";
|
||||
import PersonCard from "./PersonCard.vue";
|
||||
import ProjectCard from "./ProjectCard.vue";
|
||||
import SpecialEntityCard from "./SpecialEntityCard.vue";
|
||||
import ShowAllCard from "./ShowAllCard.vue";
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
import { PlanData } from "../interfaces/records";
|
||||
|
||||
/**
|
||||
* EntityGrid - Unified grid layout for displaying people or projects
|
||||
*
|
||||
* Features:
|
||||
* - Responsive grid layout for people/projects
|
||||
* - Special entity integration (You, Unnamed)
|
||||
* - Conflict detection integration
|
||||
* - Empty state messaging
|
||||
* - Show All navigation
|
||||
* - Event delegation for entity selection
|
||||
*/
|
||||
@Component({
|
||||
components: {
|
||||
PersonCard,
|
||||
ProjectCard,
|
||||
SpecialEntityCard,
|
||||
ShowAllCard,
|
||||
},
|
||||
})
|
||||
export default class EntityGrid extends Vue {
|
||||
/** Type of entities to display */
|
||||
@Prop({ required: true })
|
||||
entityType!: "people" | "projects";
|
||||
|
||||
/** Array of entities to display */
|
||||
@Prop({ required: true })
|
||||
entities!: Contact[] | PlanData[];
|
||||
|
||||
/** Maximum number of entities to display */
|
||||
@Prop({ default: 10 })
|
||||
maxItems!: number;
|
||||
|
||||
/** Active user's DID */
|
||||
@Prop({ required: true })
|
||||
activeDid!: string;
|
||||
|
||||
/** All user's DIDs */
|
||||
@Prop({ required: true })
|
||||
allMyDids!: string[];
|
||||
|
||||
/** All contacts */
|
||||
@Prop({ required: true })
|
||||
allContacts!: Contact[];
|
||||
|
||||
/** Function to check if a person DID would create a conflict */
|
||||
@Prop({ required: true })
|
||||
conflictChecker!: (did: string) => boolean;
|
||||
|
||||
/** Whether to show the "You" entity for people grids */
|
||||
@Prop({ default: true })
|
||||
showYouEntity!: boolean;
|
||||
|
||||
/** Whether the "You" entity is selectable */
|
||||
@Prop({ default: true })
|
||||
youSelectable!: boolean;
|
||||
|
||||
/** Route name for "Show All" navigation */
|
||||
@Prop({ default: "" })
|
||||
showAllRoute!: string;
|
||||
|
||||
/** Query parameters for "Show All" navigation */
|
||||
@Prop({ default: () => ({}) })
|
||||
showAllQueryParams!: Record<string, any>;
|
||||
|
||||
/**
|
||||
* Computed CSS classes for the grid layout
|
||||
*/
|
||||
get gridClasses(): string {
|
||||
const baseClasses = "grid gap-x-2 gap-y-4 text-center mb-4";
|
||||
|
||||
if (this.entityType === "projects") {
|
||||
return `${baseClasses} grid-cols-3 md:grid-cols-4`;
|
||||
} else {
|
||||
return `${baseClasses} grid-cols-4 sm:grid-cols-5 md:grid-cols-6`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computed entities to display (limited by maxItems)
|
||||
*/
|
||||
get displayedEntities(): Contact[] | PlanData[] {
|
||||
const maxDisplay = this.entityType === "projects" ? 7 : this.maxItems;
|
||||
return this.entities.slice(0, maxDisplay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Computed empty state message based on entity type
|
||||
*/
|
||||
get emptyStateMessage(): string {
|
||||
if (this.entityType === "projects") {
|
||||
return "(No projects found.)";
|
||||
} else {
|
||||
return "(Add friends to see more people worthy of recognition.)";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to show the "Show All" navigation
|
||||
*/
|
||||
get shouldShowAll(): boolean {
|
||||
return this.entities.length > 0 && this.showAllRoute !== "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the "You" entity is conflicted
|
||||
*/
|
||||
get youConflicted(): boolean {
|
||||
return this.conflictChecker(this.activeDid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Entity data for the "You" special entity
|
||||
*/
|
||||
get youEntityData(): { did: string; name: string } {
|
||||
return {
|
||||
did: this.activeDid,
|
||||
name: "You",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Entity data for the "Unnamed" special entity
|
||||
*/
|
||||
get unnamedEntityData(): { did: string; name: string } {
|
||||
return {
|
||||
did: "",
|
||||
name: "Unnamed",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a person DID is conflicted
|
||||
*/
|
||||
isPersonConflicted(did: string): boolean {
|
||||
return this.conflictChecker(did);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle person selection from PersonCard
|
||||
*/
|
||||
handlePersonSelected(person: Contact): void {
|
||||
this.emitEntitySelected({
|
||||
type: "person",
|
||||
data: person,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle project selection from ProjectCard
|
||||
*/
|
||||
handleProjectSelected(project: PlanData): void {
|
||||
this.emitEntitySelected({
|
||||
type: "project",
|
||||
data: project,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle special entity selection from SpecialEntityCard
|
||||
*/
|
||||
handleEntitySelected(event: {
|
||||
type: string;
|
||||
entityType: string;
|
||||
data: any;
|
||||
}): void {
|
||||
this.emitEntitySelected({
|
||||
type: "special",
|
||||
entityType: event.entityType,
|
||||
data: event.data,
|
||||
});
|
||||
}
|
||||
|
||||
// Emit methods using @Emit decorator
|
||||
|
||||
@Emit("entity-selected")
|
||||
emitEntitySelected(data: any): any {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* Grid-specific styles if needed */
|
||||
</style>
|
||||
242
src/components/EntitySelectionStep.vue
Normal file
242
src/components/EntitySelectionStep.vue
Normal file
@@ -0,0 +1,242 @@
|
||||
/** * EntitySelectionStep.vue - Entity selection step component * * Extracted
|
||||
from GiftedDialog.vue to handle the complete step 1 * entity selection interface
|
||||
with dynamic labeling and grid display. * * @author Matthew Raymer */
|
||||
<template>
|
||||
<div id="sectionGiftedGiver">
|
||||
<label class="block font-bold mb-4">
|
||||
{{ stepLabel }}
|
||||
</label>
|
||||
|
||||
<EntityGrid
|
||||
:entity-type="shouldShowProjects ? 'projects' : 'people'"
|
||||
:entities="shouldShowProjects ? projects : allContacts"
|
||||
:max-items="10"
|
||||
:active-did="activeDid"
|
||||
:all-my-dids="allMyDids"
|
||||
:all-contacts="allContacts"
|
||||
:conflict-checker="conflictChecker"
|
||||
:show-you-entity="shouldShowYouEntity"
|
||||
:you-selectable="youSelectable"
|
||||
:show-all-route="showAllRoute"
|
||||
:show-all-query-params="showAllQueryParams"
|
||||
@entity-selected="handleEntitySelected"
|
||||
/>
|
||||
|
||||
<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="handleCancel"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Emit } from "vue-facing-decorator";
|
||||
import EntityGrid from "./EntityGrid.vue";
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
import { PlanData } from "../interfaces/records";
|
||||
|
||||
/**
|
||||
* Entity selection event data structure
|
||||
*/
|
||||
interface EntitySelectionEvent {
|
||||
type: "person" | "project" | "special";
|
||||
entityType?: string;
|
||||
data: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* EntitySelectionStep - Complete step 1 entity selection interface
|
||||
*
|
||||
* Features:
|
||||
* - Dynamic step labeling based on context
|
||||
* - EntityGrid integration for unified entity display
|
||||
* - Conflict detection and prevention
|
||||
* - Special entity handling (You, Unnamed)
|
||||
* - Show All navigation with context preservation
|
||||
* - Cancel functionality
|
||||
* - Event delegation for entity selection
|
||||
*/
|
||||
@Component({
|
||||
components: {
|
||||
EntityGrid,
|
||||
},
|
||||
})
|
||||
export default class EntitySelectionStep extends Vue {
|
||||
/** Type of step: 'giver' or 'recipient' */
|
||||
@Prop({ required: true })
|
||||
stepType!: "giver" | "recipient";
|
||||
|
||||
/** Type of giver entity: 'person' or 'project' */
|
||||
@Prop({ required: true })
|
||||
giverEntityType!: "person" | "project";
|
||||
|
||||
/** Type of recipient entity: 'person' or 'project' */
|
||||
@Prop({ required: true })
|
||||
recipientEntityType!: "person" | "project";
|
||||
|
||||
/** Whether to show projects instead of people */
|
||||
@Prop({ default: false })
|
||||
showProjects!: boolean;
|
||||
|
||||
/** Whether this is from a project view */
|
||||
@Prop({ default: false })
|
||||
isFromProjectView!: boolean;
|
||||
|
||||
/** Array of available projects */
|
||||
@Prop({ required: true })
|
||||
projects!: PlanData[];
|
||||
|
||||
/** Array of available contacts */
|
||||
@Prop({ required: true })
|
||||
allContacts!: Contact[];
|
||||
|
||||
/** Active user's DID */
|
||||
@Prop({ required: true })
|
||||
activeDid!: string;
|
||||
|
||||
/** All user's DIDs */
|
||||
@Prop({ required: true })
|
||||
allMyDids!: string[];
|
||||
|
||||
/** Function to check if a DID would create a conflict */
|
||||
@Prop({ required: true })
|
||||
conflictChecker!: (did: string) => boolean;
|
||||
|
||||
/** Project ID for context (giver) */
|
||||
@Prop({ default: "" })
|
||||
fromProjectId!: string;
|
||||
|
||||
/** Project ID for context (recipient) */
|
||||
@Prop({ default: "" })
|
||||
toProjectId!: string;
|
||||
|
||||
/** Current giver entity for context */
|
||||
@Prop()
|
||||
giver?: any;
|
||||
|
||||
/** Current receiver entity for context */
|
||||
@Prop()
|
||||
receiver?: any;
|
||||
|
||||
/**
|
||||
* Computed step label based on context
|
||||
*/
|
||||
get stepLabel(): string {
|
||||
if (this.stepType === "recipient") {
|
||||
return "Choose who received the gift:";
|
||||
} else if (this.showProjects) {
|
||||
return "Choose a project benefitted from:";
|
||||
} else {
|
||||
return "Choose a person received from:";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to show projects in the grid
|
||||
*/
|
||||
get shouldShowProjects(): boolean {
|
||||
return (
|
||||
(this.stepType === "giver" && this.giverEntityType === "project") ||
|
||||
(this.stepType === "recipient" && this.recipientEntityType === "project")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to show the "You" entity
|
||||
*/
|
||||
get shouldShowYouEntity(): boolean {
|
||||
return (
|
||||
this.stepType === "recipient" ||
|
||||
(this.stepType === "giver" && this.isFromProjectView)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the "You" entity is selectable
|
||||
*/
|
||||
get youSelectable(): boolean {
|
||||
return !this.conflictChecker(this.activeDid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Route name for "Show All" navigation
|
||||
*/
|
||||
get showAllRoute(): string {
|
||||
if (this.shouldShowProjects) {
|
||||
return "discover";
|
||||
} else if (this.allContacts.length > 0) {
|
||||
return "contact-gift";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Query parameters for "Show All" navigation
|
||||
*/
|
||||
get showAllQueryParams(): Record<string, any> {
|
||||
if (this.shouldShowProjects) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
stepType: this.stepType,
|
||||
giverEntityType: this.giverEntityType,
|
||||
recipientEntityType: this.recipientEntityType,
|
||||
...(this.stepType === "giver"
|
||||
? {
|
||||
recipientProjectId: this.toProjectId,
|
||||
recipientProjectName: this.receiver?.name,
|
||||
recipientProjectImage: this.receiver?.image,
|
||||
recipientProjectHandleId: this.receiver?.handleId,
|
||||
recipientDid: this.receiver?.did,
|
||||
}
|
||||
: {
|
||||
giverProjectId: this.fromProjectId,
|
||||
giverProjectName: this.giver?.name,
|
||||
giverProjectImage: this.giver?.image,
|
||||
giverProjectHandleId: this.giver?.handleId,
|
||||
giverDid: this.giver?.did,
|
||||
}),
|
||||
fromProjectId: this.fromProjectId,
|
||||
toProjectId: this.toProjectId,
|
||||
showProjects: this.showProjects.toString(),
|
||||
isFromProjectView: this.isFromProjectView.toString(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle entity selection from EntityGrid
|
||||
*/
|
||||
handleEntitySelected(event: EntitySelectionEvent): void {
|
||||
this.emitEntitySelected({
|
||||
stepType: this.stepType,
|
||||
...event,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle cancel button click
|
||||
*/
|
||||
handleCancel(): void {
|
||||
this.emitCancel();
|
||||
}
|
||||
|
||||
// Emit methods using @Emit decorator
|
||||
|
||||
@Emit("entity-selected")
|
||||
emitEntitySelected(data: any): any {
|
||||
return data;
|
||||
}
|
||||
|
||||
@Emit("cancel")
|
||||
emitCancel(): void {
|
||||
// No return value needed
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* Component-specific styles if needed */
|
||||
</style>
|
||||
145
src/components/EntitySummaryButton.vue
Normal file
145
src/components/EntitySummaryButton.vue
Normal file
@@ -0,0 +1,145 @@
|
||||
/** * EntitySummaryButton.vue - Displays selected entity with edit capability *
|
||||
* Extracted from GiftedDialog.vue to handle entity summary display * in the gift
|
||||
details step with edit functionality. * * @author Matthew Raymer */
|
||||
<template>
|
||||
<component
|
||||
:is="editable ? 'button' : 'div'"
|
||||
class="flex-1 flex items-center gap-2 bg-slate-100 border border-slate-300 rounded-md p-2"
|
||||
@click="handleClick"
|
||||
>
|
||||
<!-- Entity Icon/Avatar -->
|
||||
<div>
|
||||
<template v-if="entityType === 'project'">
|
||||
<ProjectIcon
|
||||
v-if="entity?.handleId"
|
||||
:entity-id="entity.handleId"
|
||||
:icon-size="32"
|
||||
:image-url="entity.image"
|
||||
class="rounded-full bg-white overflow-hidden !size-[2rem] object-cover"
|
||||
/>
|
||||
</template>
|
||||
<template v-else>
|
||||
<EntityIcon
|
||||
v-if="entity?.did"
|
||||
:contact="entity"
|
||||
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>
|
||||
|
||||
<!-- Entity Information -->
|
||||
<div class="text-start min-w-0">
|
||||
<p class="text-xs text-slate-500 leading-1 -mb-1 uppercase">
|
||||
{{ label }}
|
||||
</p>
|
||||
<h3 class="font-semibold truncate">
|
||||
{{ entity?.name || "Unnamed" }}
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<!-- Edit/Lock Icon -->
|
||||
<p class="ms-auto text-sm pe-1" :class="iconClasses">
|
||||
<font-awesome
|
||||
:icon="editable ? 'pen' : 'lock'"
|
||||
:title="editable ? 'Change' : 'Can\'t be changed'"
|
||||
/>
|
||||
</p>
|
||||
</component>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Emit } from "vue-facing-decorator";
|
||||
import EntityIcon from "./EntityIcon.vue";
|
||||
import ProjectIcon from "./ProjectIcon.vue";
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
|
||||
/**
|
||||
* Entity interface for both person and project entities
|
||||
*/
|
||||
interface EntityData {
|
||||
did?: string;
|
||||
handleId?: string;
|
||||
name?: string;
|
||||
image?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* EntitySummaryButton - Displays selected entity with optional edit capability
|
||||
*
|
||||
* Features:
|
||||
* - Shows entity avatar (person or project)
|
||||
* - Displays entity name and role label
|
||||
* - Handles editable vs locked states
|
||||
* - Emits edit events when clicked and editable
|
||||
* - Supports both person and project entity types
|
||||
*/
|
||||
@Component({
|
||||
components: {
|
||||
EntityIcon,
|
||||
ProjectIcon,
|
||||
},
|
||||
})
|
||||
export default class EntitySummaryButton extends Vue {
|
||||
/** Entity data to display */
|
||||
@Prop({ required: true })
|
||||
entity!: EntityData | Contact | null;
|
||||
|
||||
/** Type of entity: 'person' or 'project' */
|
||||
@Prop({ required: true })
|
||||
entityType!: "person" | "project";
|
||||
|
||||
/** Display label for the entity role */
|
||||
@Prop({ required: true })
|
||||
label!: string;
|
||||
|
||||
/** Whether the entity can be edited */
|
||||
@Prop({ default: true })
|
||||
editable!: boolean;
|
||||
|
||||
/**
|
||||
* Computed CSS classes for the edit/lock icon
|
||||
*/
|
||||
get iconClasses(): string {
|
||||
return this.editable ? "text-blue-500" : "text-slate-400";
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle click event - only emit if editable
|
||||
*/
|
||||
handleClick(): void {
|
||||
if (this.editable) {
|
||||
this.emitEditRequested({
|
||||
entityType: this.entityType,
|
||||
entity: this.entity,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Emit methods using @Emit decorator
|
||||
|
||||
@Emit("edit-requested")
|
||||
emitEditRequested(data: any): any {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* Ensure button styling is consistent */
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background-color: #f1f5f9; /* hover:bg-slate-100 */
|
||||
}
|
||||
|
||||
div {
|
||||
cursor: default;
|
||||
}
|
||||
</style>
|
||||
@@ -99,6 +99,9 @@ import {
|
||||
LTileLayer,
|
||||
} from "@vue-leaflet/vue-leaflet";
|
||||
import { Router } from "vue-router";
|
||||
|
||||
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";
|
||||
|
||||
@@ -122,7 +125,10 @@ export default class FeedFilters extends Vue {
|
||||
async open(onCloseIfChanged: () => void) {
|
||||
this.onCloseIfChanged = onCloseIfChanged;
|
||||
|
||||
const settings = await retrieveSettingsForActiveAccount();
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
this.hasVisibleDid = !!settings.filterFeedByVisible;
|
||||
this.isNearby = !!settings.filterFeedByNearby;
|
||||
if (settings.searchBoxes && settings.searchBoxes.length > 0) {
|
||||
@@ -136,17 +142,29 @@ export default class FeedFilters extends Vue {
|
||||
async toggleHasVisibleDid() {
|
||||
this.settingChanged = true;
|
||||
this.hasVisibleDid = !this.hasVisibleDid;
|
||||
await db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
await databaseUtil.updateDefaultSettings({
|
||||
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 db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
await databaseUtil.updateDefaultSettings({
|
||||
filterFeedByNearby: this.isNearby,
|
||||
});
|
||||
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
filterFeedByNearby: this.isNearby,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async clearAll() {
|
||||
@@ -154,11 +172,18 @@ export default class FeedFilters extends Vue {
|
||||
this.settingChanged = true;
|
||||
}
|
||||
|
||||
await db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
await databaseUtil.updateDefaultSettings({
|
||||
filterFeedByNearby: false,
|
||||
filterFeedByVisible: false,
|
||||
});
|
||||
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
filterFeedByNearby: false,
|
||||
filterFeedByVisible: false,
|
||||
});
|
||||
}
|
||||
|
||||
this.hasVisibleDid = false;
|
||||
this.isNearby = false;
|
||||
}
|
||||
@@ -168,11 +193,18 @@ export default class FeedFilters extends Vue {
|
||||
this.settingChanged = true;
|
||||
}
|
||||
|
||||
await db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
await databaseUtil.updateDefaultSettings({
|
||||
filterFeedByNearby: true,
|
||||
filterFeedByVisible: true,
|
||||
});
|
||||
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
filterFeedByNearby: true,
|
||||
filterFeedByVisible: true,
|
||||
});
|
||||
}
|
||||
|
||||
this.hasVisibleDid = true;
|
||||
this.isNearby = true;
|
||||
}
|
||||
|
||||
414
src/components/GiftDetailsStep.vue
Normal file
414
src/components/GiftDetailsStep.vue
Normal file
@@ -0,0 +1,414 @@
|
||||
/** * GiftDetailsStep.vue - Gift details step component * * Extracted from
|
||||
GiftedDialog.vue to handle the complete step 2 * gift details form interface
|
||||
with entity summaries and validation. * * @author Matthew Raymer */
|
||||
<template>
|
||||
<div id="sectionGiftedGift">
|
||||
<!-- Entity Summary Buttons -->
|
||||
<div class="grid grid-cols-2 gap-2 mb-4">
|
||||
<!-- Giver Button -->
|
||||
<EntitySummaryButton
|
||||
:entity="giver"
|
||||
:entity-type="giverEntityType"
|
||||
:label="giverLabel"
|
||||
:editable="canEditGiver"
|
||||
@edit-requested="handleEditGiver"
|
||||
/>
|
||||
|
||||
<!-- Recipient Button -->
|
||||
<EntitySummaryButton
|
||||
:entity="receiver"
|
||||
:entity-type="recipientEntityType"
|
||||
:label="recipientLabel"
|
||||
:editable="canEditRecipient"
|
||||
@edit-requested="handleEditRecipient"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Gift Description Input -->
|
||||
<input
|
||||
v-model="localDescription"
|
||||
type="text"
|
||||
class="block w-full rounded border border-slate-400 px-3 py-2 mb-4 placeholder:italic"
|
||||
:placeholder="prompt || 'What was given?'"
|
||||
@input="handleDescriptionChange"
|
||||
/>
|
||||
|
||||
<!-- Amount Input and Unit Selection -->
|
||||
<div class="flex mb-4">
|
||||
<AmountInput
|
||||
:value="localAmount"
|
||||
:min="0"
|
||||
input-id="inputGivenAmount"
|
||||
@update:value="handleAmountChange"
|
||||
/>
|
||||
|
||||
<select
|
||||
v-model="localUnitCode"
|
||||
class="flex-1 rounded border border-slate-400 ms-2 px-3 py-2"
|
||||
@change="handleUnitCodeChange"
|
||||
>
|
||||
<option value="HUR">Hours</option>
|
||||
<option value="USD">US $</option>
|
||||
<option value="BTC">BTC</option>
|
||||
<option value="BX">BX</option>
|
||||
<option value="ETH">ETH</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Photo & More Options Link -->
|
||||
<router-link
|
||||
:to="photoOptionsRoute"
|
||||
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>
|
||||
|
||||
<!-- Sign & Send Info -->
|
||||
<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="handleExplainData"
|
||||
/>
|
||||
</p>
|
||||
|
||||
<!-- Conflict Warning -->
|
||||
<div
|
||||
v-if="hasConflict"
|
||||
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>
|
||||
|
||||
<!-- Action Buttons -->
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||
<button
|
||||
:disabled="hasConflict"
|
||||
:class="submitButtonClasses"
|
||||
@click="handleSubmit"
|
||||
>
|
||||
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="handleCancel"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Watch, Emit } from "vue-facing-decorator";
|
||||
import EntitySummaryButton from "./EntitySummaryButton.vue";
|
||||
import AmountInput from "./AmountInput.vue";
|
||||
import { RouteLocationRaw } from "vue-router";
|
||||
|
||||
/**
|
||||
* Entity data interface for giver/receiver
|
||||
*/
|
||||
interface EntityData {
|
||||
did?: string;
|
||||
handleId?: string;
|
||||
name?: string;
|
||||
image?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* GiftDetailsStep - Complete step 2 gift details form interface
|
||||
*
|
||||
* Features:
|
||||
* - Entity summary display with edit capability
|
||||
* - Gift description input with placeholder support
|
||||
* - Amount input with increment/decrement controls
|
||||
* - Unit code selection (HUR, USD, BTC, etc.)
|
||||
* - Photo & more options navigation
|
||||
* - Conflict detection and warning display
|
||||
* - Form validation and submission
|
||||
* - Cancel functionality
|
||||
*/
|
||||
@Component({
|
||||
components: {
|
||||
EntitySummaryButton,
|
||||
AmountInput,
|
||||
},
|
||||
})
|
||||
export default class GiftDetailsStep extends Vue {
|
||||
/** Giver entity data */
|
||||
@Prop({ required: true })
|
||||
giver!: EntityData | null;
|
||||
|
||||
/** Receiver entity data */
|
||||
@Prop({ required: true })
|
||||
receiver!: EntityData | null;
|
||||
|
||||
/** Type of giver entity: 'person' or 'project' */
|
||||
@Prop({ required: true })
|
||||
giverEntityType!: "person" | "project";
|
||||
|
||||
/** Type of recipient entity: 'person' or 'project' */
|
||||
@Prop({ required: true })
|
||||
recipientEntityType!: "person" | "project";
|
||||
|
||||
/** Gift description */
|
||||
@Prop({ default: "" })
|
||||
description!: string;
|
||||
|
||||
/** Gift amount */
|
||||
@Prop({ default: 0 })
|
||||
amount!: number;
|
||||
|
||||
/** Unit code (HUR, USD, etc.) */
|
||||
@Prop({ default: "HUR" })
|
||||
unitCode!: string;
|
||||
|
||||
/** Input placeholder text */
|
||||
@Prop({ default: "" })
|
||||
prompt!: string;
|
||||
|
||||
/** Whether this is from a project view */
|
||||
@Prop({ default: false })
|
||||
isFromProjectView!: boolean;
|
||||
|
||||
/** Whether there's a conflict between giver and receiver */
|
||||
@Prop({ default: false })
|
||||
hasConflict!: boolean;
|
||||
|
||||
/** Offer ID for context */
|
||||
@Prop({ default: "" })
|
||||
offerId!: string;
|
||||
|
||||
/** Project ID for context (giver) */
|
||||
@Prop({ default: "" })
|
||||
fromProjectId!: string;
|
||||
|
||||
/** Project ID for context (recipient) */
|
||||
@Prop({ default: "" })
|
||||
toProjectId!: string;
|
||||
|
||||
/** Local reactive copies of props for v-model */
|
||||
private localDescription: string = "";
|
||||
private localAmount: number = 0;
|
||||
private localUnitCode: string = "HUR";
|
||||
|
||||
/**
|
||||
* Initialize local values from props
|
||||
*/
|
||||
mounted(): void {
|
||||
this.localDescription = this.description;
|
||||
this.localAmount = this.amount;
|
||||
this.localUnitCode = this.unitCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Watch for external prop changes
|
||||
*/
|
||||
@Watch("description")
|
||||
onDescriptionChange(newValue: string): void {
|
||||
this.localDescription = newValue;
|
||||
}
|
||||
|
||||
@Watch("amount")
|
||||
onAmountChange(newValue: number): void {
|
||||
this.localAmount = newValue;
|
||||
}
|
||||
|
||||
@Watch("unitCode")
|
||||
onUnitCodeChange(newValue: string): void {
|
||||
this.localUnitCode = newValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computed label for giver entity
|
||||
*/
|
||||
get giverLabel(): string {
|
||||
return this.giverEntityType === "project"
|
||||
? "Benefited from:"
|
||||
: "Received from:";
|
||||
}
|
||||
|
||||
/**
|
||||
* Computed label for recipient entity
|
||||
*/
|
||||
get recipientLabel(): string {
|
||||
return this.recipientEntityType === "project"
|
||||
? "Given to project:"
|
||||
: "Given to:";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the giver can be edited
|
||||
*/
|
||||
get canEditGiver(): boolean {
|
||||
return !(this.isFromProjectView && this.giverEntityType === "project");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the recipient can be edited
|
||||
*/
|
||||
get canEditRecipient(): boolean {
|
||||
return this.recipientEntityType === "person";
|
||||
}
|
||||
|
||||
/**
|
||||
* Computed CSS classes for submit button
|
||||
*/
|
||||
get submitButtonClasses(): string {
|
||||
if (this.hasConflict) {
|
||||
return "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";
|
||||
}
|
||||
return "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";
|
||||
}
|
||||
|
||||
/**
|
||||
* Computed route for photo & more options
|
||||
*/
|
||||
get photoOptionsRoute(): RouteLocationRaw {
|
||||
return {
|
||||
name: "gifted-details",
|
||||
query: {
|
||||
amountInput: this.localAmount.toString(),
|
||||
description: this.localDescription,
|
||||
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.localUnitCode,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle description input changes
|
||||
*/
|
||||
handleDescriptionChange(): void {
|
||||
this.emitUpdateDescription(this.localDescription);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle amount input changes
|
||||
*/
|
||||
handleAmountChange(newAmount: number): void {
|
||||
console.log(
|
||||
`[GiftDetailsStep] handleAmountChange() called - oldAmount: ${this.localAmount}, newAmount: ${newAmount}`,
|
||||
);
|
||||
this.localAmount = newAmount;
|
||||
this.emitUpdateAmount(newAmount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle unit code selection changes
|
||||
*/
|
||||
handleUnitCodeChange(): void {
|
||||
this.emitUpdateUnitCode(this.localUnitCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle giver edit request
|
||||
*/
|
||||
handleEditGiver(): void {
|
||||
this.emitEditEntity({
|
||||
entityType: "giver",
|
||||
currentEntity: this.giver,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle recipient edit request
|
||||
*/
|
||||
handleEditRecipient(): void {
|
||||
this.emitEditEntity({
|
||||
entityType: "recipient",
|
||||
currentEntity: this.receiver,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle explain data info click
|
||||
*/
|
||||
handleExplainData(): void {
|
||||
this.emitExplainData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle form submission
|
||||
*/
|
||||
handleSubmit(): void {
|
||||
if (!this.hasConflict) {
|
||||
this.emitSubmit({
|
||||
description: this.localDescription,
|
||||
amount: this.localAmount,
|
||||
unitCode: this.localUnitCode,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle cancel button click
|
||||
*/
|
||||
handleCancel(): void {
|
||||
this.emitCancel();
|
||||
}
|
||||
|
||||
// Emit methods using @Emit decorator
|
||||
|
||||
@Emit("update:description")
|
||||
emitUpdateDescription(description: string): string {
|
||||
return description;
|
||||
}
|
||||
|
||||
@Emit("update:amount")
|
||||
emitUpdateAmount(amount: number): number {
|
||||
console.log(
|
||||
`[GiftDetailsStep] emitUpdateAmount() - emitting amount: ${amount}`,
|
||||
);
|
||||
return amount;
|
||||
}
|
||||
|
||||
@Emit("update:unitCode")
|
||||
emitUpdateUnitCode(unitCode: string): string {
|
||||
return unitCode;
|
||||
}
|
||||
|
||||
@Emit("edit-entity")
|
||||
emitEditEntity(data: any): any {
|
||||
return data;
|
||||
}
|
||||
|
||||
@Emit("explain-data")
|
||||
emitExplainData(): void {
|
||||
// No return value needed
|
||||
}
|
||||
|
||||
@Emit("submit")
|
||||
emitSubmit(data: any): any {
|
||||
return data;
|
||||
}
|
||||
|
||||
@Emit("cancel")
|
||||
emitCancel(): void {
|
||||
// No return value needed
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* Component-specific styles if needed */
|
||||
</style>
|
||||
@@ -1,112 +1,108 @@
|
||||
<template>
|
||||
<div v-if="visible" class="dialog-overlay">
|
||||
<div class="dialog">
|
||||
<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?'"
|
||||
<!-- Step 1: Entity Selection -->
|
||||
<EntitySelectionStep
|
||||
v-show="currentStep === 1"
|
||||
:step-type="stepType"
|
||||
:giver-entity-type="giverEntityType"
|
||||
:recipient-entity-type="recipientEntityType"
|
||||
:show-projects="showProjects"
|
||||
:is-from-project-view="isFromProjectView"
|
||||
:projects="projects"
|
||||
:all-contacts="allContacts"
|
||||
:active-did="activeDid"
|
||||
:all-my-dids="allMyDids"
|
||||
:conflict-checker="wouldCreateConflict"
|
||||
:from-project-id="fromProjectId"
|
||||
:to-project-id="toProjectId"
|
||||
:giver="giver"
|
||||
:receiver="receiver"
|
||||
@entity-selected="handleEntitySelected"
|
||||
@cancel="cancel"
|
||||
/>
|
||||
|
||||
<!-- Step 2: Gift Details -->
|
||||
<GiftDetailsStep
|
||||
v-show="currentStep === 2"
|
||||
:giver="giver"
|
||||
:receiver="receiver"
|
||||
:giver-entity-type="giverEntityType"
|
||||
:recipient-entity-type="recipientEntityType"
|
||||
:description="description"
|
||||
:amount="parseFloat(amountInput) || 0"
|
||||
:unit-code="unitCode"
|
||||
:prompt="prompt"
|
||||
:is-from-project-view="isFromProjectView"
|
||||
:has-conflict="hasPersonConflict"
|
||||
:offer-id="offerId"
|
||||
:from-project-id="fromProjectId"
|
||||
:to-project-id="toProjectId"
|
||||
@update:description="description = $event"
|
||||
@update:amount="handleAmountUpdate"
|
||||
@update:unit-code="unitCode = $event"
|
||||
@edit-entity="handleEditEntity"
|
||||
@explain-data="explainData"
|
||||
@submit="handleSubmit"
|
||||
@cancel="cancel"
|
||||
/>
|
||||
<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()"
|
||||
>
|
||||
{{ 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-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>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Vue, Component, Prop } from "vue-facing-decorator";
|
||||
import { Vue, Component, Prop, Watch } from "vue-facing-decorator";
|
||||
|
||||
import { NotificationIface } from "../constants/app";
|
||||
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";
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
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 EntitySelectionStep from "../components/EntitySelectionStep.vue";
|
||||
import GiftDetailsStep from "../components/GiftDetailsStep.vue";
|
||||
import { PlanData } from "../interfaces/records";
|
||||
|
||||
@Component
|
||||
@Component({
|
||||
components: {
|
||||
EntityIcon,
|
||||
ProjectIcon,
|
||||
EntitySelectionStep,
|
||||
GiftDetailsStep,
|
||||
},
|
||||
})
|
||||
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> = [];
|
||||
@@ -123,9 +119,94 @@ export default class GiftedDialog extends Vue {
|
||||
receiver?: libsUtil.GiverReceiverInputInfo;
|
||||
unitCode = "HUR";
|
||||
visible = false;
|
||||
currentStep = 1;
|
||||
|
||||
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,
|
||||
@@ -138,17 +219,33 @@ 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.currentStep = giver ? 2 : 1;
|
||||
this.stepType = "giver";
|
||||
|
||||
// Update entity types based on current props
|
||||
this.updateEntityTypes();
|
||||
|
||||
try {
|
||||
const settings = await retrieveSettingsForActiveAccount();
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
this.apiServer = settings.apiServer || "";
|
||||
this.activeDid = settings.activeDid || "";
|
||||
|
||||
this.allContacts = await db.contacts.toArray();
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const result = await platformService.dbQuery(`SELECT * FROM contacts`);
|
||||
if (result) {
|
||||
this.allContacts = databaseUtil.mapQueryResultToValues(
|
||||
result,
|
||||
) as unknown as Contact[];
|
||||
}
|
||||
if (USE_DEXIE_DB) {
|
||||
this.allContacts = await db.contacts.toArray();
|
||||
}
|
||||
|
||||
this.allMyDids = await retrieveAccountDids();
|
||||
|
||||
@@ -160,7 +257,16 @@ export default class GiftedDialog extends Vue {
|
||||
this.allContacts,
|
||||
);
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
|
||||
if (
|
||||
this.giverEntityType === "project" ||
|
||||
this.recipientEntityType === "project"
|
||||
) {
|
||||
await this.loadProjects();
|
||||
} else {
|
||||
// Clear projects array when not needed
|
||||
this.projects = [];
|
||||
}
|
||||
} catch (err: any) {
|
||||
logger.error("Error retrieving settings from database:", err);
|
||||
this.$notify(
|
||||
@@ -210,6 +316,7 @@ export default class GiftedDialog extends Vue {
|
||||
this.amountInput = "0";
|
||||
this.prompt = "";
|
||||
this.unitCode = "HUR";
|
||||
this.currentStep = 1;
|
||||
}
|
||||
|
||||
async confirm() {
|
||||
@@ -252,6 +359,20 @@ 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(
|
||||
{
|
||||
@@ -290,26 +411,55 @@ 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 {
|
||||
// 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,
|
||||
giverDid as string,
|
||||
recipientDid as string,
|
||||
fromDid,
|
||||
toDid,
|
||||
description,
|
||||
amount,
|
||||
unitCode,
|
||||
this.toProjectId,
|
||||
fulfillsProjectHandleId,
|
||||
this.offerId,
|
||||
false,
|
||||
undefined,
|
||||
this.fromProjectId,
|
||||
providerPlanHandleId,
|
||||
);
|
||||
|
||||
if (
|
||||
result.type === "error" ||
|
||||
this.isGiveCreationError(result.response)
|
||||
) {
|
||||
if (!result.success) {
|
||||
const errorMessage = this.getGiveCreationErrorMessage(result);
|
||||
logger.error("Error with give creation result:", result);
|
||||
this.$notify(
|
||||
@@ -356,15 +506,6 @@ export default class GiftedDialog extends Vue {
|
||||
|
||||
// Helper functions for readability
|
||||
|
||||
/**
|
||||
* @param result response "data" from the server
|
||||
* @returns true if the result indicates an error
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
isGiveCreationError(result: any) {
|
||||
return result.status !== 201 || result.data?.error;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param result direct response eg. ErrorResult or SuccessResult (potentially with embedded "data")
|
||||
* @returns best guess at an error message
|
||||
@@ -389,6 +530,173 @@ 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: "Unnamed",
|
||||
};
|
||||
}
|
||||
this.currentStep = 2;
|
||||
}
|
||||
|
||||
goBackToStep1(step: string) {
|
||||
this.stepType = step;
|
||||
this.currentStep = 1;
|
||||
}
|
||||
|
||||
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 = {
|
||||
did: project.handleId,
|
||||
name: project.name,
|
||||
image: project.image,
|
||||
handleId: project.handleId,
|
||||
};
|
||||
this.receiver = {
|
||||
did: this.activeDid,
|
||||
name: "You",
|
||||
};
|
||||
this.currentStep = 2;
|
||||
}
|
||||
|
||||
selectRecipient(contact?: Contact) {
|
||||
if (contact) {
|
||||
this.receiver = {
|
||||
did: contact.did,
|
||||
name: contact.name || contact.did,
|
||||
};
|
||||
} else {
|
||||
this.receiver = {
|
||||
did: "",
|
||||
name: "Unnamed",
|
||||
};
|
||||
}
|
||||
this.currentStep = 2;
|
||||
}
|
||||
|
||||
selectRecipientProject(project: PlanData) {
|
||||
this.receiver = {
|
||||
did: project.handleId,
|
||||
name: project.name,
|
||||
image: project.image,
|
||||
handleId: project.handleId,
|
||||
};
|
||||
this.currentStep = 2;
|
||||
}
|
||||
|
||||
// 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,
|
||||
};
|
||||
}
|
||||
|
||||
// New event handlers for component integration
|
||||
|
||||
/**
|
||||
* Handle entity selection from EntitySelectionStep
|
||||
* @param entity - The selected entity (person or project)
|
||||
*/
|
||||
handleEntitySelected(entity: {
|
||||
type: "person" | "project";
|
||||
data: Contact | PlanData;
|
||||
}) {
|
||||
if (entity.type === "person") {
|
||||
const contact = entity.data as Contact;
|
||||
if (this.stepType === "giver") {
|
||||
this.selectGiver(contact);
|
||||
} else {
|
||||
this.selectRecipient(contact);
|
||||
}
|
||||
} else {
|
||||
const project = entity.data as PlanData;
|
||||
if (this.stepType === "giver") {
|
||||
this.selectProject(project);
|
||||
} else {
|
||||
this.selectRecipientProject(project);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle edit entity request from GiftDetailsStep
|
||||
* @param entityType - 'giver' or 'recipient'
|
||||
*/
|
||||
handleEditEntity(entityType: "giver" | "recipient") {
|
||||
this.goBackToStep1(entityType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle form submission from GiftDetailsStep
|
||||
*/
|
||||
handleSubmit() {
|
||||
this.confirm();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle amount update from GiftDetailsStep
|
||||
*/
|
||||
handleAmountUpdate(newAmount: number) {
|
||||
console.log(
|
||||
`[GiftedDialog] handleAmountUpdate() called - oldAmount: ${this.amountInput}, newAmount: ${newAmount}`,
|
||||
);
|
||||
this.amountInput = newAmount.toString();
|
||||
console.log(
|
||||
`[GiftedDialog] handleAmountUpdate() - amountInput updated to: ${this.amountInput}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -74,10 +74,12 @@
|
||||
import { Vue, Component } from "vue-facing-decorator";
|
||||
import { Router } from "vue-router";
|
||||
|
||||
import { AppString, NotificationIface } from "../constants/app";
|
||||
import { AppString, NotificationIface, USE_DEXIE_DB } from "../constants/app";
|
||||
import { db } from "../db/index";
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import { GiverReceiverInputInfo } from "../libs/util";
|
||||
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
|
||||
|
||||
@Component
|
||||
export default class GivenPrompts extends Vue {
|
||||
@@ -127,8 +129,16 @@ export default class GivenPrompts extends Vue {
|
||||
this.visible = true;
|
||||
this.callbackOnFullGiftInfo = callbackOnFullGiftInfo;
|
||||
|
||||
await db.open();
|
||||
this.numContacts = await db.contacts.count();
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const result = await platformService.dbQuery(
|
||||
"SELECT COUNT(*) FROM contacts",
|
||||
);
|
||||
if (result) {
|
||||
this.numContacts = result.values[0][0] as number;
|
||||
}
|
||||
if (USE_DEXIE_DB) {
|
||||
this.numContacts = await db.contacts.count();
|
||||
}
|
||||
this.shownContactDbIndices = new Array<boolean>(this.numContacts); // all undefined to start
|
||||
}
|
||||
|
||||
@@ -217,6 +227,7 @@ 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 &&
|
||||
@@ -229,10 +240,21 @@ export default class GivenPrompts extends Vue {
|
||||
this.nextIdeaPastContacts();
|
||||
} else {
|
||||
// get the contact at that offset
|
||||
await db.open();
|
||||
this.currentContact = await db.contacts
|
||||
.offset(someContactDbIndex)
|
||||
.first();
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const result = await platformService.dbQuery(
|
||||
"SELECT * FROM contacts LIMIT 1 OFFSET ?",
|
||||
[someContactDbIndex],
|
||||
);
|
||||
if (result) {
|
||||
const mappedContacts = databaseUtil.mapQueryResultToValues(result);
|
||||
this.currentContact = mappedContacts[0] as unknown as Contact;
|
||||
}
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.open();
|
||||
this.currentContact = await db.contacts
|
||||
.offset(someContactDbIndex)
|
||||
.first();
|
||||
}
|
||||
this.shownContactDbIndices[someContactDbIndex] = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,11 +48,7 @@
|
||||
<span>
|
||||
{{ didInfo(visDid) }}
|
||||
<span v-if="!serverUtil.isEmptyOrHiddenDid(visDid)">
|
||||
<a
|
||||
:href="`/did/${visDid}`"
|
||||
target="_blank"
|
||||
class="text-blue-500"
|
||||
>
|
||||
<a :href="`/did/${visDid}`" class="text-blue-500">
|
||||
<font-awesome
|
||||
icon="arrow-up-right-from-square"
|
||||
class="fa-fw"
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
<div class="text-lg text-center font-bold relative">
|
||||
<h1 id="ViewHeading" class="text-center font-bold">
|
||||
<span v-if="uploading">Uploading Image…</span>
|
||||
<span v-else-if="blob">{{ crop ? 'Crop Image' : 'Preview Image' }}</span>
|
||||
<span v-else-if="blob">{{
|
||||
crop ? "Crop Image" : "Preview Image"
|
||||
}}</span>
|
||||
<span v-else-if="showCameraPreview">Upload Image</span>
|
||||
<span v-else>Add Photo</span>
|
||||
</h1>
|
||||
@@ -119,7 +121,9 @@
|
||||
playsinline
|
||||
muted
|
||||
></video>
|
||||
<div class="absolute bottom-4 inset-x-0 flex items-center justify-center gap-4">
|
||||
<div
|
||||
class="absolute bottom-4 inset-x-0 flex items-center justify-center gap-4"
|
||||
>
|
||||
<button
|
||||
class="bg-white text-slate-800 p-3 rounded-full text-2xl leading-none"
|
||||
@click="capturePhoto"
|
||||
@@ -238,12 +242,12 @@
|
||||
<p class="mb-2">
|
||||
Before you can upload a photo, a friend needs to register you.
|
||||
</p>
|
||||
<router-link
|
||||
:to="{ name: 'contact-qr' }"
|
||||
<button
|
||||
class="inline-block text-md 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-4 py-2 rounded-md"
|
||||
@click="handleQRCodeClick"
|
||||
>
|
||||
Share Your Info
|
||||
</router-link>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
@@ -256,11 +260,17 @@ import axios from "axios";
|
||||
import { ref } from "vue";
|
||||
import { Component, Vue } from "vue-facing-decorator";
|
||||
import VuePictureCropper, { cropper } from "vue-picture-cropper";
|
||||
import { DEFAULT_IMAGE_API_SERVER, NotificationIface } from "../constants/app";
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
import {
|
||||
DEFAULT_IMAGE_API_SERVER,
|
||||
NotificationIface,
|
||||
USE_DEXIE_DB,
|
||||
} from "../constants/app";
|
||||
import { retrieveSettingsForActiveAccount } from "../db/index";
|
||||
import { accessToken } from "../libs/crypto";
|
||||
import { logger } from "../utils/logger";
|
||||
import { PlatformServiceFactory } from "../services/PlatformServiceFactory";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
|
||||
const inputImageFileNameRef = ref<Blob>();
|
||||
|
||||
@@ -273,9 +283,9 @@ const inputImageFileNameRef = ref<Blob>();
|
||||
},
|
||||
defaultCameraMode: {
|
||||
type: String,
|
||||
default: 'environment',
|
||||
validator: (value: string) => ['environment', 'user'].includes(value)
|
||||
}
|
||||
default: "environment",
|
||||
validator: (value: string) => ["environment", "user"].includes(value),
|
||||
},
|
||||
},
|
||||
})
|
||||
export default class ImageMethodDialog extends Vue {
|
||||
@@ -318,7 +328,7 @@ export default class ImageMethodDialog extends Vue {
|
||||
private cameraStream: MediaStream | null = null;
|
||||
|
||||
/** Current camera facing mode */
|
||||
private currentFacingMode: 'environment' | 'user' = 'environment';
|
||||
private currentFacingMode: "environment" | "user" = "environment";
|
||||
|
||||
private platformService = PlatformServiceFactory.getInstance();
|
||||
URL = window.URL || window.webkitURL;
|
||||
@@ -350,9 +360,11 @@ export default class ImageMethodDialog extends Vue {
|
||||
* @throws {Error} When settings retrieval fails
|
||||
*/
|
||||
async mounted() {
|
||||
logger.log("ImageMethodDialog mounted");
|
||||
try {
|
||||
const settings = await retrieveSettingsForActiveAccount();
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
this.activeDid = settings.activeDid || "";
|
||||
} catch (error: unknown) {
|
||||
logger.error("Error retrieving settings from database:", error);
|
||||
@@ -384,7 +396,7 @@ export default class ImageMethodDialog extends Vue {
|
||||
this.crop = !!crop;
|
||||
this.imageCallback = setImageFn;
|
||||
this.visible = true;
|
||||
this.currentFacingMode = this.defaultCameraMode as 'environment' | 'user';
|
||||
this.currentFacingMode = this.defaultCameraMode as "environment" | "user";
|
||||
|
||||
// Start camera preview immediately
|
||||
logger.debug("Starting camera preview from open()");
|
||||
@@ -458,7 +470,10 @@ export default class ImageMethodDialog extends Vue {
|
||||
logger.debug("Current showCameraPreview state:", this.showCameraPreview);
|
||||
logger.debug("Platform capabilities:", this.platformCapabilities);
|
||||
logger.debug("MediaDevices available:", !!navigator.mediaDevices);
|
||||
logger.debug("getUserMedia available:", !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia));
|
||||
logger.debug(
|
||||
"getUserMedia available:",
|
||||
!!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),
|
||||
);
|
||||
|
||||
try {
|
||||
this.cameraState = "initializing";
|
||||
@@ -485,13 +500,16 @@ export default class ImageMethodDialog extends Vue {
|
||||
videoElement.srcObject = stream;
|
||||
await new Promise((resolve) => {
|
||||
videoElement.onloadedmetadata = () => {
|
||||
videoElement.play().then(() => {
|
||||
logger.debug("Video element started playing");
|
||||
resolve(true);
|
||||
}).catch(error => {
|
||||
logger.error("Error playing video:", error);
|
||||
throw error;
|
||||
});
|
||||
videoElement
|
||||
.play()
|
||||
.then(() => {
|
||||
logger.debug("Video element started playing");
|
||||
resolve(true);
|
||||
})
|
||||
.catch((error) => {
|
||||
logger.error("Error playing video:", error);
|
||||
throw error;
|
||||
});
|
||||
};
|
||||
});
|
||||
} else {
|
||||
@@ -503,17 +521,16 @@ export default class ImageMethodDialog extends Vue {
|
||||
let errorMessage =
|
||||
error instanceof Error ? error.message : "Failed to access camera";
|
||||
if (
|
||||
error instanceof Error && (
|
||||
error.name === "NotReadableError" ||
|
||||
error.name === "TrackStartError"
|
||||
)) {
|
||||
error instanceof Error &&
|
||||
(error.name === "NotReadableError" || error.name === "TrackStartError")
|
||||
) {
|
||||
errorMessage =
|
||||
"Camera is in use by another application. Please close any other apps or browser tabs using the camera and try again.";
|
||||
} else if (
|
||||
error instanceof Error && (
|
||||
error.name === "NotAllowedError" ||
|
||||
error.name === "PermissionDeniedError"
|
||||
)) {
|
||||
error instanceof Error &&
|
||||
(error.name === "NotAllowedError" ||
|
||||
error.name === "PermissionDeniedError")
|
||||
) {
|
||||
errorMessage =
|
||||
"Camera access was denied. Please allow camera access in your browser settings.";
|
||||
}
|
||||
@@ -583,11 +600,12 @@ export default class ImageMethodDialog extends Vue {
|
||||
|
||||
async rotateCamera() {
|
||||
// Toggle between front and back cameras
|
||||
this.currentFacingMode = this.currentFacingMode === 'environment' ? 'user' : 'environment';
|
||||
|
||||
this.currentFacingMode =
|
||||
this.currentFacingMode === "environment" ? "user" : "environment";
|
||||
|
||||
// Stop current stream
|
||||
if (this.cameraStream) {
|
||||
this.cameraStream.getTracks().forEach(track => track.stop());
|
||||
this.cameraStream.getTracks().forEach((track) => track.stop());
|
||||
this.cameraStream = null;
|
||||
}
|
||||
|
||||
@@ -692,6 +710,14 @@ export default class ImageMethodDialog extends Vue {
|
||||
toggleDiagnostics() {
|
||||
this.showDiagnostics = !this.showDiagnostics;
|
||||
}
|
||||
|
||||
private handleQRCodeClick() {
|
||||
if (Capacitor.isNativePlatform()) {
|
||||
this.$router.push({ name: "contact-qr-scan-full" });
|
||||
} else {
|
||||
this.$router.push({ name: "contact-qr" });
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -172,8 +172,10 @@ import {
|
||||
} from "../libs/endorserServer";
|
||||
import { decryptMessage } from "../libs/crypto";
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import * as libsUtil from "../libs/util";
|
||||
import { NotificationIface } from "../constants/app";
|
||||
import { NotificationIface, USE_DEXIE_DB } from "../constants/app";
|
||||
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
|
||||
|
||||
interface Member {
|
||||
admitted: boolean;
|
||||
@@ -209,7 +211,10 @@ export default class MembersList extends Vue {
|
||||
contacts: Array<Contact> = [];
|
||||
|
||||
async created() {
|
||||
const settings = await retrieveSettingsForActiveAccount();
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
this.activeDid = settings.activeDid || "";
|
||||
this.apiServer = settings.apiServer || "";
|
||||
this.firstName = settings.firstName || "";
|
||||
@@ -355,7 +360,16 @@ export default class MembersList extends Vue {
|
||||
}
|
||||
|
||||
async loadContacts() {
|
||||
this.contacts = await db.contacts.toArray();
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const result = await platformService.dbQuery("SELECT * FROM contacts");
|
||||
if (result) {
|
||||
this.contacts = databaseUtil.mapQueryResultToValues(
|
||||
result,
|
||||
) as unknown as Contact[];
|
||||
}
|
||||
if (USE_DEXIE_DB) {
|
||||
this.contacts = await db.contacts.toArray();
|
||||
}
|
||||
}
|
||||
|
||||
getContactFor(did: string): Contact | undefined {
|
||||
@@ -439,7 +453,14 @@ export default class MembersList extends Vue {
|
||||
if (result.success) {
|
||||
decrMember.isRegistered = true;
|
||||
if (oldContact) {
|
||||
await db.contacts.update(decrMember.did, { registered: true });
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
await platformService.dbExec(
|
||||
"UPDATE contacts SET registered = ? WHERE did = ?",
|
||||
[true, decrMember.did],
|
||||
);
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.contacts.update(decrMember.did, { registered: true });
|
||||
}
|
||||
oldContact.registered = true;
|
||||
}
|
||||
this.$notify(
|
||||
@@ -492,7 +513,14 @@ export default class MembersList extends Vue {
|
||||
name: member.name,
|
||||
};
|
||||
|
||||
await db.contacts.add(newContact);
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
await platformService.dbExec(
|
||||
"INSERT INTO contacts (did, name) VALUES (?, ?)",
|
||||
[member.did, member.name],
|
||||
);
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.contacts.add(newContact);
|
||||
}
|
||||
this.contacts.push(newContact);
|
||||
|
||||
this.$notify(
|
||||
|
||||
@@ -82,12 +82,13 @@
|
||||
<script lang="ts">
|
||||
import { Vue, Component, Prop } from "vue-facing-decorator";
|
||||
|
||||
import { NotificationIface } from "../constants/app";
|
||||
import { NotificationIface, USE_DEXIE_DB } from "../constants/app";
|
||||
import {
|
||||
createAndSubmitOffer,
|
||||
serverMessageForUser,
|
||||
} from "../libs/endorserServer";
|
||||
import * as libsUtil from "../libs/util";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import { retrieveSettingsForActiveAccount } from "../db/index";
|
||||
import { logger } from "../utils/logger";
|
||||
|
||||
@@ -116,7 +117,10 @@ export default class OfferDialog extends Vue {
|
||||
this.recipientDid = recipientDid;
|
||||
this.recipientName = recipientName;
|
||||
|
||||
const settings = await retrieveSettingsForActiveAccount();
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
this.apiServer = settings.apiServer || "";
|
||||
this.activeDid = settings.activeDid || "";
|
||||
|
||||
@@ -245,10 +249,7 @@ export default class OfferDialog extends Vue {
|
||||
this.projectId,
|
||||
);
|
||||
|
||||
if (
|
||||
result.type === "error" ||
|
||||
this.isOfferCreationError(result.response)
|
||||
) {
|
||||
if (!result.success) {
|
||||
const errorMessage = this.getOfferCreationErrorMessage(result);
|
||||
logger.error("Error with offer creation result:", result);
|
||||
this.$notify(
|
||||
@@ -292,15 +293,6 @@ export default class OfferDialog extends Vue {
|
||||
|
||||
// Helper functions for readability
|
||||
|
||||
/**
|
||||
* @param result response "data" from the server
|
||||
* @returns true if the result indicates an error
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
isOfferCreationError(result: any) {
|
||||
return result.status !== 201 || result.data?.error;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param result direct response eg. ErrorResult or SuccessResult (potentially with embedded "data")
|
||||
* @returns best guess at an error message
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<h1 class="text-xl font-bold text-center mb-4 relative">
|
||||
Welcome to Time Safari
|
||||
<br />
|
||||
- Showcasing Gratitude & Magnifying Time
|
||||
- Showcase Impact & Magnify Time
|
||||
<div
|
||||
class="text-lg text-center leading-none absolute right-0 -top-1"
|
||||
@click="onClickClose(true)"
|
||||
@@ -14,6 +14,9 @@
|
||||
</div>
|
||||
</h1>
|
||||
|
||||
The feed underneath this pop-up shows the latest contributions, some from
|
||||
people and some from projects.
|
||||
|
||||
<p v-if="isRegistered" class="mt-4">
|
||||
You can now log things that you've seen:
|
||||
<span v-if="numContacts > 0">
|
||||
@@ -23,14 +26,10 @@
|
||||
<span class="bg-green-600 text-white rounded-full">
|
||||
<font-awesome icon="plus" class="fa-fw" />
|
||||
</span>
|
||||
button to express your appreciation for... whatever -- maybe thanks for
|
||||
showing you all these fascinating stories of
|
||||
<em>gratitude</em>.
|
||||
button to express your appreciation for... whatever.
|
||||
</p>
|
||||
<p v-else class="mt-4">
|
||||
The feed underneath this pop-up shows the latest gifts that others have
|
||||
recognized. Once someone registers you, you can log your appreciation,
|
||||
too.
|
||||
<p class="mt-4">
|
||||
Once someone registers you, you can log your appreciation, too.
|
||||
</p>
|
||||
|
||||
<p class="mt-4">
|
||||
@@ -201,13 +200,16 @@
|
||||
import { Component, Vue } from "vue-facing-decorator";
|
||||
import { Router } from "vue-router";
|
||||
|
||||
import { NotificationIface } from "../constants/app";
|
||||
import { NotificationIface, USE_DEXIE_DB } from "../constants/app";
|
||||
import {
|
||||
db,
|
||||
retrieveSettingsForActiveAccount,
|
||||
updateAccountSettings,
|
||||
} from "../db/index";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import { OnboardPage } from "../libs/util";
|
||||
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
|
||||
import { Contact } from "@/db/tables/contacts";
|
||||
|
||||
@Component({
|
||||
computed: {
|
||||
@@ -222,7 +224,7 @@ export default class OnboardingDialog extends Vue {
|
||||
$router!: Router;
|
||||
|
||||
activeDid = "";
|
||||
firstContactName = null;
|
||||
firstContactName = "";
|
||||
givenName = "";
|
||||
isRegistered = false;
|
||||
numContacts = 0;
|
||||
@@ -231,29 +233,54 @@ export default class OnboardingDialog extends Vue {
|
||||
|
||||
async open(page: OnboardPage) {
|
||||
this.page = page;
|
||||
const settings = await retrieveSettingsForActiveAccount();
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
this.activeDid = settings.activeDid || "";
|
||||
this.isRegistered = !!settings.isRegistered;
|
||||
const contacts = await db.contacts.toArray();
|
||||
this.numContacts = contacts.length;
|
||||
if (this.numContacts > 0) {
|
||||
this.firstContactName = contacts[0].name;
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const dbContacts = await platformService.dbQuery("SELECT * FROM contacts");
|
||||
if (dbContacts) {
|
||||
this.numContacts = dbContacts.values.length;
|
||||
const firstContact = dbContacts.values[0];
|
||||
const fullContact = databaseUtil.mapColumnsToValues(dbContacts.columns, [
|
||||
firstContact,
|
||||
]) as unknown as Contact;
|
||||
this.firstContactName = fullContact.name || "";
|
||||
}
|
||||
if (USE_DEXIE_DB) {
|
||||
const contacts = await db.contacts.toArray();
|
||||
this.numContacts = contacts.length;
|
||||
if (this.numContacts > 0) {
|
||||
this.firstContactName = contacts[0].name || "";
|
||||
}
|
||||
}
|
||||
this.visible = true;
|
||||
if (this.page === OnboardPage.Create) {
|
||||
// we'll assume that they've been through all the other pages
|
||||
await updateAccountSettings(this.activeDid, {
|
||||
await databaseUtil.updateDidSpecificSettings(this.activeDid, {
|
||||
finishedOnboarding: true,
|
||||
});
|
||||
if (USE_DEXIE_DB) {
|
||||
await updateAccountSettings(this.activeDid, {
|
||||
finishedOnboarding: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async onClickClose(done?: boolean, goHome?: boolean) {
|
||||
this.visible = false;
|
||||
if (done) {
|
||||
await updateAccountSettings(this.activeDid, {
|
||||
await databaseUtil.updateDidSpecificSettings(this.activeDid, {
|
||||
finishedOnboarding: true,
|
||||
});
|
||||
if (USE_DEXIE_DB) {
|
||||
await updateAccountSettings(this.activeDid, {
|
||||
finishedOnboarding: true,
|
||||
});
|
||||
}
|
||||
if (goHome) {
|
||||
this.$router.push({ name: "home" });
|
||||
}
|
||||
|
||||
114
src/components/PersonCard.vue
Normal file
114
src/components/PersonCard.vue
Normal file
@@ -0,0 +1,114 @@
|
||||
/** * PersonCard.vue - Individual person display component * * Extracted from
|
||||
GiftedDialog.vue to handle person entity display * with selection states and
|
||||
conflict detection. * * @author Matthew Raymer */
|
||||
<template>
|
||||
<li :class="cardClasses" @click="handleClick">
|
||||
<div class="relative w-fit mx-auto">
|
||||
<EntityIcon
|
||||
v-if="person.did"
|
||||
:contact="person"
|
||||
class="!size-[3rem] mx-auto border border-slate-300 bg-white overflow-hidden rounded-full mb-1"
|
||||
/>
|
||||
<font-awesome
|
||||
v-else
|
||||
icon="circle-question"
|
||||
class="text-slate-400 text-5xl mb-1"
|
||||
/>
|
||||
|
||||
<!-- Time icon overlay for contacts -->
|
||||
<div
|
||||
v-if="person.did && showTimeIcon"
|
||||
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="nameClasses">
|
||||
{{ person.name || person.did || "Unnamed" }}
|
||||
</h3>
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Emit } from "vue-facing-decorator";
|
||||
import EntityIcon from "./EntityIcon.vue";
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
|
||||
/**
|
||||
* PersonCard - Individual person display with selection capability
|
||||
*
|
||||
* Features:
|
||||
* - Person avatar using EntityIcon
|
||||
* - Selection states (selectable, conflicted, disabled)
|
||||
* - Time icon overlay for contacts
|
||||
* - Click event handling
|
||||
* - Emits click events for parent handling
|
||||
*/
|
||||
@Component({
|
||||
components: {
|
||||
EntityIcon,
|
||||
},
|
||||
})
|
||||
export default class PersonCard extends Vue {
|
||||
/** Contact data to display */
|
||||
@Prop({ required: true })
|
||||
person!: Contact;
|
||||
|
||||
/** Whether this person can be selected */
|
||||
@Prop({ default: true })
|
||||
selectable!: boolean;
|
||||
|
||||
/** Whether this person would create a conflict if selected */
|
||||
@Prop({ default: false })
|
||||
conflicted!: boolean;
|
||||
|
||||
/** Whether to show time icon overlay */
|
||||
@Prop({ default: false })
|
||||
showTimeIcon!: boolean;
|
||||
|
||||
/**
|
||||
* Computed CSS classes for the card
|
||||
*/
|
||||
get cardClasses(): string {
|
||||
if (!this.selectable || this.conflicted) {
|
||||
return "opacity-50 cursor-not-allowed";
|
||||
}
|
||||
return "cursor-pointer hover:bg-slate-50";
|
||||
}
|
||||
|
||||
/**
|
||||
* Computed CSS classes for the person name
|
||||
*/
|
||||
get nameClasses(): string {
|
||||
const baseClasses =
|
||||
"text-xs font-medium text-ellipsis whitespace-nowrap overflow-hidden";
|
||||
|
||||
if (this.conflicted) {
|
||||
return `${baseClasses} text-slate-400`;
|
||||
}
|
||||
|
||||
return baseClasses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle card click - only emit if selectable and not conflicted
|
||||
*/
|
||||
handleClick(): void {
|
||||
if (this.selectable && !this.conflicted) {
|
||||
this.emitPersonSelected(this.person);
|
||||
}
|
||||
}
|
||||
|
||||
// Emit methods using @Emit decorator
|
||||
|
||||
@Emit("person-selected")
|
||||
emitPersonSelected(person: Contact): Contact {
|
||||
return person;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* Component-specific styles if needed */
|
||||
</style>
|
||||
@@ -119,7 +119,12 @@ PhotoDialog.vue */
|
||||
import axios from "axios";
|
||||
import { Component, Vue } from "vue-facing-decorator";
|
||||
import VuePictureCropper, { cropper } from "vue-picture-cropper";
|
||||
import { DEFAULT_IMAGE_API_SERVER, NotificationIface } from "../constants/app";
|
||||
import {
|
||||
DEFAULT_IMAGE_API_SERVER,
|
||||
NotificationIface,
|
||||
USE_DEXIE_DB,
|
||||
} from "../constants/app";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import { retrieveSettingsForActiveAccount } from "../db/index";
|
||||
import { accessToken } from "../libs/crypto";
|
||||
import { logger } from "../utils/logger";
|
||||
@@ -173,9 +178,12 @@ export default class PhotoDialog extends Vue {
|
||||
* @throws {Error} When settings retrieval fails
|
||||
*/
|
||||
async mounted() {
|
||||
logger.log("PhotoDialog mounted");
|
||||
// logger.log("PhotoDialog mounted");
|
||||
try {
|
||||
const settings = await retrieveSettingsForActiveAccount();
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
this.activeDid = settings.activeDid || "";
|
||||
this.isRegistered = !!settings.isRegistered;
|
||||
logger.log("isRegistered:", this.isRegistered);
|
||||
|
||||
96
src/components/ProjectCard.vue
Normal file
96
src/components/ProjectCard.vue
Normal file
@@ -0,0 +1,96 @@
|
||||
/** * ProjectCard.vue - Individual project display component * * Extracted from
|
||||
GiftedDialog.vue to handle project entity display * with selection states and
|
||||
issuer information. * * @author Matthew Raymer */
|
||||
<template>
|
||||
<li class="cursor-pointer" @click="handleClick">
|
||||
<div class="relative w-fit mx-auto">
|
||||
<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 mb-1"
|
||||
/>
|
||||
</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" />
|
||||
{{ issuerDisplayName }}
|
||||
</div>
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue, Emit } from "vue-facing-decorator";
|
||||
import ProjectIcon from "./ProjectIcon.vue";
|
||||
import { PlanData } from "../interfaces/records";
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
import { didInfo } from "../libs/endorserServer";
|
||||
|
||||
/**
|
||||
* ProjectCard - Displays a project entity with selection capability
|
||||
*
|
||||
* Features:
|
||||
* - Shows project icon using ProjectIcon
|
||||
* - Displays project name and issuer information
|
||||
* - Handles click events for selection
|
||||
* - Shows issuer name using didInfo utility
|
||||
*/
|
||||
@Component({
|
||||
components: {
|
||||
ProjectIcon,
|
||||
},
|
||||
})
|
||||
export default class ProjectCard extends Vue {
|
||||
/** Project entity to display */
|
||||
@Prop({ required: true })
|
||||
project!: PlanData;
|
||||
|
||||
/** Active user's DID for issuer display */
|
||||
@Prop({ required: true })
|
||||
activeDid!: string;
|
||||
|
||||
/** All user's DIDs for issuer display */
|
||||
@Prop({ required: true })
|
||||
allMyDids!: string[];
|
||||
|
||||
/** All contacts for issuer display */
|
||||
@Prop({ required: true })
|
||||
allContacts!: Contact[];
|
||||
|
||||
/**
|
||||
* Computed display name for the project issuer
|
||||
*/
|
||||
get issuerDisplayName(): string {
|
||||
return didInfo(
|
||||
this.project.issuerDid,
|
||||
this.activeDid,
|
||||
this.allMyDids,
|
||||
this.allContacts,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle card click - emit project selection
|
||||
*/
|
||||
handleClick(): void {
|
||||
this.emitProjectSelected(this.project);
|
||||
}
|
||||
|
||||
// Emit methods using @Emit decorator
|
||||
|
||||
@Emit("project-selected")
|
||||
emitProjectSelected(project: PlanData): PlanData {
|
||||
return project;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* Component-specific styles if needed */
|
||||
</style>
|
||||
@@ -1,18 +1,14 @@
|
||||
<!-- eslint-disable vue/no-v-html -->
|
||||
<template>
|
||||
<a
|
||||
v-if="linkToFull && imageUrl"
|
||||
v-if="linkToFullImage && imageUrl"
|
||||
:href="imageUrl"
|
||||
target="_blank"
|
||||
class="h-full w-full object-contain"
|
||||
>
|
||||
<div class="h-full w-full object-contain" v-html="generateIdenticon()" />
|
||||
<div class="h-full w-full object-contain" v-html="generateIcon()" />
|
||||
</a>
|
||||
<div
|
||||
v-else
|
||||
class="h-full w-full object-contain"
|
||||
v-html="generateIdenticon()"
|
||||
/>
|
||||
<div v-else class="h-full w-full object-contain" v-html="generateIcon()" />
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { toSvg } from "jdenticon";
|
||||
@@ -35,9 +31,9 @@ export default class ProjectIcon extends Vue {
|
||||
@Prop entityId = "";
|
||||
@Prop iconSize = 0;
|
||||
@Prop imageUrl = "";
|
||||
@Prop linkToFull = false;
|
||||
@Prop linkToFullImage = false;
|
||||
|
||||
generateIdenticon() {
|
||||
generateIcon() {
|
||||
if (this.imageUrl) {
|
||||
return `<img src="${this.imageUrl}" class="w-full h-full object-contain" />`;
|
||||
} else {
|
||||
|
||||
@@ -102,7 +102,12 @@
|
||||
<script lang="ts">
|
||||
import { Component, Vue } from "vue-facing-decorator";
|
||||
|
||||
import { DEFAULT_PUSH_SERVER, NotificationIface } from "../constants/app";
|
||||
import {
|
||||
DEFAULT_PUSH_SERVER,
|
||||
NotificationIface,
|
||||
USE_DEXIE_DB,
|
||||
} from "../constants/app";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import {
|
||||
logConsoleAndDb,
|
||||
retrieveSettingsForActiveAccount,
|
||||
@@ -169,7 +174,10 @@ export default class PushNotificationPermission extends Vue {
|
||||
this.isVisible = true;
|
||||
this.pushType = pushType;
|
||||
try {
|
||||
const settings = await retrieveSettingsForActiveAccount();
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
let pushUrl = DEFAULT_PUSH_SERVER;
|
||||
if (settings?.webPushServer) {
|
||||
pushUrl = settings.webPushServer;
|
||||
|
||||
66
src/components/ShowAllCard.vue
Normal file
66
src/components/ShowAllCard.vue
Normal file
@@ -0,0 +1,66 @@
|
||||
/** * ShowAllCard.vue - Show All navigation card component * * Extracted from
|
||||
GiftedDialog.vue to handle "Show All" navigation * for both people and projects
|
||||
entity types. * * @author Matthew Raymer */
|
||||
<template>
|
||||
<li class="cursor-pointer">
|
||||
<router-link :to="navigationRoute" class="block text-center">
|
||||
<font-awesome icon="circle-right" class="text-blue-500 text-5xl mb-1" />
|
||||
<h3
|
||||
class="text-xs text-slate-500 font-medium italic text-ellipsis whitespace-nowrap overflow-hidden"
|
||||
>
|
||||
Show All
|
||||
</h3>
|
||||
</router-link>
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue } from "vue-facing-decorator";
|
||||
import { RouteLocationRaw } from "vue-router";
|
||||
|
||||
/**
|
||||
* ShowAllCard - Displays "Show All" navigation for entity grids
|
||||
*
|
||||
* Features:
|
||||
* - Provides navigation to full entity listings
|
||||
* - Supports different routes based on entity type
|
||||
* - Maintains context through query parameters
|
||||
* - Consistent visual styling with other cards
|
||||
*/
|
||||
@Component
|
||||
export default class ShowAllCard extends Vue {
|
||||
/** Type of entities being shown */
|
||||
@Prop({ required: true })
|
||||
entityType!: "people" | "projects";
|
||||
|
||||
/** Route name to navigate to */
|
||||
@Prop({ required: true })
|
||||
routeName!: string;
|
||||
|
||||
/** Query parameters to pass to the route */
|
||||
@Prop({ default: () => ({}) })
|
||||
queryParams!: Record<string, any>;
|
||||
|
||||
/**
|
||||
* Computed navigation route with query parameters
|
||||
*/
|
||||
get navigationRoute(): RouteLocationRaw {
|
||||
return {
|
||||
name: this.routeName,
|
||||
query: this.queryParams,
|
||||
};
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* Ensure router-link styling is consistent */
|
||||
a {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a:hover .fa-circle-right {
|
||||
transform: scale(1.1);
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
</style>
|
||||
135
src/components/SpecialEntityCard.vue
Normal file
135
src/components/SpecialEntityCard.vue
Normal file
@@ -0,0 +1,135 @@
|
||||
/** * SpecialEntityCard.vue - Special entity display component * * Extracted
|
||||
from GiftedDialog.vue to handle special entities like "You" * and "Unnamed" with
|
||||
conflict detection and selection capability. * * @author Matthew Raymer */
|
||||
<template>
|
||||
<li :class="cardClasses" @click="handleClick">
|
||||
<font-awesome :icon="icon" :class="iconClasses" />
|
||||
<h3 :class="nameClasses">
|
||||
{{ label }}
|
||||
</h3>
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Prop, Vue } from "vue-facing-decorator";
|
||||
import { Emit } from "vue-facing-decorator";
|
||||
|
||||
/**
|
||||
* SpecialEntityCard - Displays special entities with selection capability
|
||||
*
|
||||
* Features:
|
||||
* - Displays special entities like "You" and "Unnamed"
|
||||
* - Shows appropriate FontAwesome icons
|
||||
* - Handles conflict states and selection
|
||||
* - Emits selection events with entity data
|
||||
* - Configurable styling based on entity type
|
||||
*/
|
||||
@Component({
|
||||
emits: ["entity-selected"],
|
||||
})
|
||||
export default class SpecialEntityCard extends Vue {
|
||||
/** Type of special entity */
|
||||
@Prop({ required: true })
|
||||
entityType!: "you" | "unnamed";
|
||||
|
||||
/** Display label for the entity */
|
||||
@Prop({ required: true })
|
||||
label!: string;
|
||||
|
||||
/** FontAwesome icon name */
|
||||
@Prop({ required: true })
|
||||
icon!: string;
|
||||
|
||||
/** Whether this entity can be selected */
|
||||
@Prop({ default: true })
|
||||
selectable!: boolean;
|
||||
|
||||
/** Whether selecting this entity would create a conflict */
|
||||
@Prop({ default: false })
|
||||
conflicted!: boolean;
|
||||
|
||||
/** Entity data to emit when selected */
|
||||
@Prop({ required: true })
|
||||
entityData!: { did?: string; name: string };
|
||||
|
||||
/**
|
||||
* Computed CSS classes for the card container
|
||||
*/
|
||||
get cardClasses(): string {
|
||||
const baseClasses = "block";
|
||||
|
||||
if (!this.selectable || this.conflicted) {
|
||||
return `${baseClasses} cursor-not-allowed opacity-50`;
|
||||
}
|
||||
|
||||
return `${baseClasses} cursor-pointer`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computed CSS classes for the icon
|
||||
*/
|
||||
get iconClasses(): string {
|
||||
const baseClasses = "text-5xl mb-1";
|
||||
|
||||
if (this.conflicted) {
|
||||
return `${baseClasses} text-slate-400`;
|
||||
}
|
||||
|
||||
// Different colors for different entity types
|
||||
switch (this.entityType) {
|
||||
case "you":
|
||||
return `${baseClasses} text-blue-500`;
|
||||
case "unnamed":
|
||||
return `${baseClasses} text-slate-400`;
|
||||
default:
|
||||
return `${baseClasses} text-slate-400`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computed CSS classes for the entity name/label
|
||||
*/
|
||||
get nameClasses(): string {
|
||||
const baseClasses =
|
||||
"text-xs font-medium text-ellipsis whitespace-nowrap overflow-hidden";
|
||||
|
||||
if (this.conflicted) {
|
||||
return `${baseClasses} text-slate-400`;
|
||||
}
|
||||
|
||||
// Different colors for different entity types
|
||||
switch (this.entityType) {
|
||||
case "you":
|
||||
return `${baseClasses} text-blue-500`;
|
||||
case "unnamed":
|
||||
return `${baseClasses} text-slate-500 italic`;
|
||||
default:
|
||||
return `${baseClasses} text-slate-500`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle card click - only emit if selectable and not conflicted
|
||||
*/
|
||||
handleClick(): void {
|
||||
if (this.selectable && !this.conflicted) {
|
||||
this.emitEntitySelected({
|
||||
type: "special",
|
||||
entityType: this.entityType,
|
||||
data: this.entityData,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Emit methods using @Emit decorator
|
||||
|
||||
@Emit("entity-selected")
|
||||
emitEntitySelected(data: any): any {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* Component-specific styles if needed */
|
||||
</style>
|
||||
@@ -15,7 +15,8 @@
|
||||
<script lang="ts">
|
||||
import { Component, Vue, Prop } from "vue-facing-decorator";
|
||||
|
||||
import { AppString, NotificationIface } from "../constants/app";
|
||||
import { AppString, NotificationIface, USE_DEXIE_DB } from "../constants/app";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import { retrieveSettingsForActiveAccount } from "../db/index";
|
||||
|
||||
@Component
|
||||
@@ -28,7 +29,10 @@ export default class TopMessage extends Vue {
|
||||
|
||||
async mounted() {
|
||||
try {
|
||||
const settings = await retrieveSettingsForActiveAccount();
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
if (
|
||||
settings.warnIfTestServer &&
|
||||
settings.apiServer !== AppString.PROD_ENDORSER_API_SERVER
|
||||
|
||||
@@ -37,9 +37,11 @@
|
||||
<script lang="ts">
|
||||
import { Vue, Component, Prop } from "vue-facing-decorator";
|
||||
|
||||
import { NotificationIface } from "../constants/app";
|
||||
import { NotificationIface, USE_DEXIE_DB } from "../constants/app";
|
||||
import { db, retrieveSettingsForActiveAccount } from "../db/index";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import { MASTER_SETTINGS_KEY } from "../db/tables/settings";
|
||||
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
|
||||
|
||||
@Component
|
||||
export default class UserNameDialog extends Vue {
|
||||
@@ -61,15 +63,25 @@ export default class UserNameDialog extends Vue {
|
||||
*/
|
||||
async open(aCallback?: (name?: string) => void) {
|
||||
this.callback = aCallback || this.callback;
|
||||
const settings = await retrieveSettingsForActiveAccount();
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
this.givenName = settings.firstName || "";
|
||||
this.visible = true;
|
||||
}
|
||||
|
||||
async onClickSaveChanges() {
|
||||
await db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
firstName: this.givenName,
|
||||
});
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
await platformService.dbExec(
|
||||
"UPDATE settings SET firstName = ? WHERE id = ?",
|
||||
[this.givenName, MASTER_SETTINGS_KEY],
|
||||
);
|
||||
if (USE_DEXIE_DB) {
|
||||
await db.settings.update(MASTER_SETTINGS_KEY, {
|
||||
firstName: this.givenName,
|
||||
});
|
||||
}
|
||||
this.visible = false;
|
||||
this.callback(this.givenName);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ import * as THREE from "three";
|
||||
import { GLTFLoader } from "three/addons/loaders/GLTFLoader";
|
||||
import * as SkeletonUtils from "three/addons/utils/SkeletonUtils";
|
||||
import * as TWEEN from "@tweenjs/tween.js";
|
||||
import { USE_DEXIE_DB } from "../../../../constants/app";
|
||||
import * as databaseUtil from "../../../../db/databaseUtil";
|
||||
import { retrieveSettingsForActiveAccount } from "../../../../db";
|
||||
import { getHeaders } from "../../../../libs/endorserServer";
|
||||
import { logger } from "../../../../utils/logger";
|
||||
@@ -14,7 +16,10 @@ export async function loadLandmarks(vue, world, scene, loop) {
|
||||
vue.setWorldProperty("animationDurationSeconds", ANIMATION_DURATION_SECS);
|
||||
|
||||
try {
|
||||
const settings = await retrieveSettingsForActiveAccount();
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
const activeDid = settings.activeDid || "";
|
||||
const apiServer = settings.apiServer;
|
||||
const headers = await getHeaders(activeDid);
|
||||
|
||||
@@ -7,6 +7,7 @@ export enum AppString {
|
||||
// This is used in titles and verbiage inside the app.
|
||||
// There is also an app name without spaces, for packaging in the package.json file used in the manifest.
|
||||
APP_NAME = "Time Safari",
|
||||
APP_NAME_NO_SPACES = "TimeSafari",
|
||||
|
||||
PROD_ENDORSER_API_SERVER = "https://api.endorser.ch",
|
||||
TEST_ENDORSER_API_SERVER = "https://test-api.endorser.ch",
|
||||
@@ -32,24 +33,26 @@ export const APP_SERVER =
|
||||
|
||||
export const DEFAULT_ENDORSER_API_SERVER =
|
||||
import.meta.env.VITE_DEFAULT_ENDORSER_API_SERVER ||
|
||||
AppString.TEST_ENDORSER_API_SERVER;
|
||||
AppString.PROD_ENDORSER_API_SERVER;
|
||||
|
||||
export const DEFAULT_IMAGE_API_SERVER =
|
||||
import.meta.env.VITE_DEFAULT_IMAGE_API_SERVER ||
|
||||
AppString.TEST_IMAGE_API_SERVER;
|
||||
AppString.PROD_IMAGE_API_SERVER;
|
||||
|
||||
export const DEFAULT_PARTNER_API_SERVER =
|
||||
import.meta.env.VITE_DEFAULT_PARTNER_API_SERVER ||
|
||||
AppString.TEST_PARTNER_API_SERVER;
|
||||
AppString.PROD_PARTNER_API_SERVER;
|
||||
|
||||
export const DEFAULT_PUSH_SERVER =
|
||||
window.location.protocol + "//" + window.location.host;
|
||||
import.meta.env.VITE_DEFAULT_PUSH_SERVER || AppString.PROD_PUSH_SERVER;
|
||||
|
||||
export const IMAGE_TYPE_PROFILE = "profile";
|
||||
|
||||
export const PASSKEYS_ENABLED =
|
||||
!!import.meta.env.VITE_PASSKEYS_ENABLED || false;
|
||||
|
||||
export const USE_DEXIE_DB = false;
|
||||
|
||||
/**
|
||||
* The possible values for "group" and "type" are in App.vue.
|
||||
* Some of this comes from the notiwind package, some is custom.
|
||||
|
||||
138
src/db-sql/migration.ts
Normal file
138
src/db-sql/migration.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import migrationService from "../services/migrationService";
|
||||
import { DEFAULT_ENDORSER_API_SERVER } from "@/constants/app";
|
||||
import { arrayBufferToBase64 } from "@/libs/crypto";
|
||||
|
||||
// Generate a random secret for the secret table
|
||||
|
||||
// It's not really secure to maintain the secret next to the user's data.
|
||||
// However, until we have better hooks into a real wallet or reliable secure
|
||||
// storage, we'll do this for user convenience. As they sign more records
|
||||
// and integrate with more people, they'll value it more and want to be more
|
||||
// secure, so we'll prompt them to take steps to back it up, properly encrypt,
|
||||
// etc. At the beginning, we'll prompt for a password, then we'll prompt for a
|
||||
// PWA so it's not in a browser... and then we hope to be integrated with a
|
||||
// real wallet or something else more secure.
|
||||
|
||||
// One might ask: why encrypt at all? We figure a basic encryption is better
|
||||
// than none. Plus, we expect to support their own password or keystore or
|
||||
// external wallet as better signing options in the future, so it's gonna be
|
||||
// important to have the structure where each account access might require
|
||||
// user action.
|
||||
|
||||
// (Once upon a time we stored the secret in localStorage, but it frequently
|
||||
// got erased, even though the IndexedDB still had the identity data. This
|
||||
// ended up throwing lots of errors to the user... and they'd end up in a state
|
||||
// where they couldn't take action because they couldn't unlock that identity.)
|
||||
|
||||
const randomBytes = crypto.getRandomValues(new Uint8Array(32));
|
||||
const secretBase64 = arrayBufferToBase64(randomBytes);
|
||||
|
||||
// Each migration can include multiple SQL statements (with semicolons)
|
||||
const MIGRATIONS = [
|
||||
{
|
||||
name: "001_initial",
|
||||
// see ../db/tables files for explanations of the fields
|
||||
sql: `
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
dateCreated TEXT NOT NULL,
|
||||
derivationPath TEXT,
|
||||
did TEXT NOT NULL,
|
||||
identityEncrBase64 TEXT, -- encrypted & base64-encoded
|
||||
mnemonicEncrBase64 TEXT, -- encrypted & base64-encoded
|
||||
passkeyCredIdHex TEXT,
|
||||
publicKeyHex TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_accounts_did ON accounts(did);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS secret (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
secretBase64 TEXT NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO secret (id, secretBase64) VALUES (1, '${secretBase64}');
|
||||
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
accountDid TEXT,
|
||||
activeDid TEXT,
|
||||
apiServer TEXT,
|
||||
filterFeedByNearby BOOLEAN,
|
||||
filterFeedByVisible BOOLEAN,
|
||||
finishedOnboarding BOOLEAN,
|
||||
firstName TEXT,
|
||||
hideRegisterPromptOnNewContact BOOLEAN,
|
||||
isRegistered BOOLEAN,
|
||||
lastName TEXT,
|
||||
lastAckedOfferToUserJwtId TEXT,
|
||||
lastAckedOfferToUserProjectsJwtId TEXT,
|
||||
lastNotifiedClaimId TEXT,
|
||||
lastViewedClaimId TEXT,
|
||||
notifyingNewActivityTime TEXT,
|
||||
notifyingReminderMessage TEXT,
|
||||
notifyingReminderTime TEXT,
|
||||
partnerApiServer TEXT,
|
||||
passkeyExpirationMinutes INTEGER,
|
||||
profileImageUrl TEXT,
|
||||
searchBoxes TEXT, -- Stored as JSON string
|
||||
showContactGivesInline BOOLEAN,
|
||||
showGeneralAdvanced BOOLEAN,
|
||||
showShortcutBvc BOOLEAN,
|
||||
vapid TEXT,
|
||||
warnIfProdServer BOOLEAN,
|
||||
warnIfTestServer BOOLEAN,
|
||||
webPushServer TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_settings_accountDid ON settings(accountDid);
|
||||
|
||||
INSERT INTO settings (id, apiServer) VALUES (1, '${DEFAULT_ENDORSER_API_SERVER}');
|
||||
|
||||
CREATE TABLE IF NOT EXISTS contacts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
did TEXT NOT NULL,
|
||||
name TEXT,
|
||||
contactMethods TEXT, -- Stored as JSON string
|
||||
nextPubKeyHashB64 TEXT,
|
||||
notes TEXT,
|
||||
profileImageUrl TEXT,
|
||||
publicKeyBase64 TEXT,
|
||||
seesMe BOOLEAN,
|
||||
registered BOOLEAN
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_contacts_did ON contacts(did);
|
||||
CREATE INDEX IF NOT EXISTS idx_contacts_name ON contacts(name);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS logs (
|
||||
date TEXT NOT NULL,
|
||||
message TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS temp (
|
||||
id TEXT PRIMARY KEY,
|
||||
blobB64 TEXT
|
||||
);
|
||||
`,
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* @param sqlExec - A function that executes a SQL statement and returns the result
|
||||
* @param extractMigrationNames - A function that extracts the names (string array) from "select name from migrations"
|
||||
*/
|
||||
export async function runMigrations<T>(
|
||||
sqlExec: (sql: string) => Promise<unknown>,
|
||||
sqlQuery: (sql: string) => Promise<T>,
|
||||
extractMigrationNames: (result: T) => Set<string>,
|
||||
): Promise<void> {
|
||||
for (const migration of MIGRATIONS) {
|
||||
migrationService.registerMigration(migration);
|
||||
}
|
||||
await migrationService.runMigrations(
|
||||
sqlExec,
|
||||
sqlQuery,
|
||||
extractMigrationNames,
|
||||
);
|
||||
}
|
||||
426
src/db/databaseUtil.ts
Normal file
426
src/db/databaseUtil.ts
Normal file
@@ -0,0 +1,426 @@
|
||||
/**
|
||||
* This file is the SQL replacement of the index.ts file in the db directory.
|
||||
* That file will eventually be deleted.
|
||||
*/
|
||||
|
||||
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
|
||||
import { MASTER_SETTINGS_KEY, Settings } from "./tables/settings";
|
||||
import { logger } from "@/utils/logger";
|
||||
import { DEFAULT_ENDORSER_API_SERVER } from "@/constants/app";
|
||||
import { QueryExecResult } from "@/interfaces/database";
|
||||
|
||||
export async function updateDefaultSettings(
|
||||
settingsChanges: Settings,
|
||||
): Promise<boolean> {
|
||||
delete settingsChanges.accountDid; // just in case
|
||||
// ensure there is no "id" that would override the key
|
||||
delete settingsChanges.id;
|
||||
try {
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const { sql, params } = generateUpdateStatement(
|
||||
settingsChanges,
|
||||
"settings",
|
||||
"id = ?",
|
||||
[MASTER_SETTINGS_KEY],
|
||||
);
|
||||
const result = await platformService.dbExec(sql, params);
|
||||
return result.changes === 1;
|
||||
} catch (error) {
|
||||
logger.error("Error updating default settings:", error);
|
||||
if (error instanceof Error) {
|
||||
throw error; // Re-throw if it's already an Error with a message
|
||||
} else {
|
||||
throw new Error(
|
||||
`Failed to update settings. We recommend you try again or restart the app.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function insertDidSpecificSettings(
|
||||
did: string,
|
||||
settings: Partial<Settings> = {},
|
||||
): Promise<boolean> {
|
||||
const platform = PlatformServiceFactory.getInstance();
|
||||
const { sql, params } = generateInsertStatement(
|
||||
{ ...settings, accountDid: did }, // make sure accountDid is set to the given value
|
||||
"settings",
|
||||
);
|
||||
const result = await platform.dbExec(sql, params);
|
||||
return result.changes === 1;
|
||||
}
|
||||
|
||||
export async function updateDidSpecificSettings(
|
||||
accountDid: string,
|
||||
settingsChanges: Settings,
|
||||
): Promise<boolean> {
|
||||
settingsChanges.accountDid = accountDid;
|
||||
delete settingsChanges.id; // key off account, not ID
|
||||
|
||||
const platform = PlatformServiceFactory.getInstance();
|
||||
|
||||
// First try to update existing record
|
||||
const { sql: updateSql, params: updateParams } = generateUpdateStatement(
|
||||
settingsChanges,
|
||||
"settings",
|
||||
"accountDid = ?",
|
||||
[accountDid],
|
||||
);
|
||||
|
||||
const updateResult = await platform.dbExec(updateSql, updateParams);
|
||||
return updateResult.changes === 1;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: Settings = {
|
||||
id: MASTER_SETTINGS_KEY,
|
||||
activeDid: undefined,
|
||||
apiServer: DEFAULT_ENDORSER_API_SERVER,
|
||||
};
|
||||
|
||||
// retrieves default settings
|
||||
export async function retrieveSettingsForDefaultAccount(): Promise<Settings> {
|
||||
const platform = PlatformServiceFactory.getInstance();
|
||||
const sql = "SELECT * FROM settings WHERE id = ?";
|
||||
const result = await platform.dbQuery(sql, [MASTER_SETTINGS_KEY]);
|
||||
if (!result) {
|
||||
return DEFAULT_SETTINGS;
|
||||
} else {
|
||||
const settings = mapColumnsToValues(
|
||||
result.columns,
|
||||
result.values,
|
||||
)[0] as Settings;
|
||||
if (settings.searchBoxes) {
|
||||
// @ts-expect-error - the searchBoxes field is a string in the DB
|
||||
settings.searchBoxes = JSON.parse(settings.searchBoxes);
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves settings for the active account, merging with default settings
|
||||
*
|
||||
* @returns Promise<Settings> Combined settings with account-specific overrides
|
||||
* @throws Will log specific errors for debugging but returns default settings on failure
|
||||
*/
|
||||
export async function retrieveSettingsForActiveAccount(): Promise<Settings> {
|
||||
try {
|
||||
// Get default settings first
|
||||
const defaultSettings = await retrieveSettingsForDefaultAccount();
|
||||
// If no active DID, return defaults
|
||||
if (!defaultSettings.activeDid) {
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
// Get account-specific settings
|
||||
try {
|
||||
const platform = PlatformServiceFactory.getInstance();
|
||||
const result = await platform.dbQuery(
|
||||
"SELECT * FROM settings WHERE accountDid = ?",
|
||||
[defaultSettings.activeDid],
|
||||
);
|
||||
|
||||
if (!result?.values?.length) {
|
||||
// we created DID-specific settings when generated or imported, so this shouldn't happen
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
// Map and filter settings
|
||||
const overrideSettings = mapColumnsToValues(
|
||||
result.columns,
|
||||
result.values,
|
||||
)[0] as Settings;
|
||||
|
||||
const overrideSettingsFiltered = Object.fromEntries(
|
||||
Object.entries(overrideSettings).filter(([_, v]) => v !== null),
|
||||
);
|
||||
|
||||
// Merge settings
|
||||
const settings = { ...defaultSettings, ...overrideSettingsFiltered };
|
||||
|
||||
// Handle searchBoxes parsing
|
||||
if (settings.searchBoxes) {
|
||||
settings.searchBoxes = parseJsonField(settings.searchBoxes, []);
|
||||
}
|
||||
|
||||
return settings;
|
||||
} catch (error) {
|
||||
logConsoleAndDb(
|
||||
`[databaseUtil] Failed to retrieve account settings for ${defaultSettings.activeDid}: ${error}`,
|
||||
true,
|
||||
);
|
||||
// Return defaults on error
|
||||
return defaultSettings;
|
||||
}
|
||||
} catch (error) {
|
||||
logConsoleAndDb(
|
||||
`[databaseUtil] Failed to retrieve default settings: ${error}`,
|
||||
true,
|
||||
);
|
||||
// Return minimal default settings on complete failure
|
||||
return {
|
||||
id: MASTER_SETTINGS_KEY,
|
||||
activeDid: undefined,
|
||||
apiServer: DEFAULT_ENDORSER_API_SERVER,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let lastCleanupDate: string | null = null;
|
||||
export let memoryLogs: string[] = [];
|
||||
|
||||
/**
|
||||
* Logs a message to the database with proper handling of concurrent writes
|
||||
* @param message - The message to log
|
||||
* @author Matthew Raymer
|
||||
*/
|
||||
export async function logToDb(message: string): Promise<void> {
|
||||
const platform = PlatformServiceFactory.getInstance();
|
||||
const todayKey = new Date().toDateString();
|
||||
const nowKey = new Date().toISOString();
|
||||
|
||||
try {
|
||||
memoryLogs.push(`${new Date().toISOString()} ${message}`);
|
||||
// Try to insert first, if it fails due to UNIQUE constraint, update instead
|
||||
await platform.dbExec("INSERT INTO logs (date, message) VALUES (?, ?)", [
|
||||
nowKey,
|
||||
message,
|
||||
]);
|
||||
|
||||
// Clean up old logs (keep only last 7 days) - do this less frequently
|
||||
// Only clean up if the date is different from the last cleanup
|
||||
if (!lastCleanupDate || lastCleanupDate !== todayKey) {
|
||||
const sevenDaysAgo = new Date(
|
||||
new Date().getTime() - 7 * 24 * 60 * 60 * 1000,
|
||||
);
|
||||
memoryLogs = memoryLogs.filter(
|
||||
(log) => log.split(" ")[0] > sevenDaysAgo.toDateString(),
|
||||
);
|
||||
await platform.dbExec("DELETE FROM logs WHERE date < ?", [
|
||||
sevenDaysAgo.toDateString(),
|
||||
]);
|
||||
lastCleanupDate = todayKey;
|
||||
}
|
||||
} catch (error) {
|
||||
// Log to console as fallback
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(
|
||||
"Error logging to database:",
|
||||
error,
|
||||
" ... for original message:",
|
||||
message,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// similar method is in the sw_scripts/additional-scripts.js file
|
||||
export async function logConsoleAndDb(
|
||||
message: string,
|
||||
isError = false,
|
||||
): Promise<void> {
|
||||
if (isError) {
|
||||
logger.error(`${new Date().toISOString()} ${message}`);
|
||||
} else {
|
||||
logger.log(`${new Date().toISOString()} ${message}`);
|
||||
}
|
||||
await logToDb(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates an SQL INSERT statement and parameters from a model object.
|
||||
* @param model The model object containing fields to update
|
||||
* @param tableName The name of the table to update
|
||||
* @returns Object containing the SQL statement and parameters array
|
||||
*/
|
||||
export function generateInsertStatement(
|
||||
model: Record<string, unknown>,
|
||||
tableName: string,
|
||||
): { sql: string; params: unknown[] } {
|
||||
const columns = Object.keys(model).filter((key) => model[key] !== undefined);
|
||||
const values = Object.values(model).filter((value) => value !== undefined);
|
||||
const placeholders = values.map(() => "?").join(", ");
|
||||
const insertSql = `INSERT INTO ${tableName} (${columns.join(", ")}) VALUES (${placeholders})`;
|
||||
|
||||
return {
|
||||
sql: insertSql,
|
||||
params: values,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates an SQL UPDATE statement and parameters from a model object.
|
||||
* @param model The model object containing fields to update
|
||||
* @param tableName The name of the table to update
|
||||
* @param whereClause The WHERE clause for the update (e.g. "id = ?")
|
||||
* @param whereParams Parameters for the WHERE clause
|
||||
* @returns Object containing the SQL statement and parameters array
|
||||
*/
|
||||
export function generateUpdateStatement(
|
||||
model: Record<string, unknown>,
|
||||
tableName: string,
|
||||
whereClause: string,
|
||||
whereParams: unknown[] = [],
|
||||
): { sql: string; params: unknown[] } {
|
||||
// Filter out undefined/null values and create SET clause
|
||||
const setClauses: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
|
||||
Object.entries(model).forEach(([key, value]) => {
|
||||
setClauses.push(`${key} = ?`);
|
||||
params.push(value ?? null);
|
||||
});
|
||||
|
||||
if (setClauses.length === 0) {
|
||||
throw new Error("No valid fields to update");
|
||||
}
|
||||
|
||||
const sql = `UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE ${whereClause}`;
|
||||
|
||||
return {
|
||||
sql,
|
||||
params: [...params, ...whereParams],
|
||||
};
|
||||
}
|
||||
|
||||
export function mapQueryResultToValues(
|
||||
record: QueryExecResult | undefined,
|
||||
): Array<Record<string, unknown>> {
|
||||
if (!record) {
|
||||
return [];
|
||||
}
|
||||
return mapColumnsToValues(record.columns, record.values) as Array<
|
||||
Record<string, unknown>
|
||||
>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps an array of column names to an array of value arrays, creating objects where each column name
|
||||
* is mapped to its corresponding value.
|
||||
* @param columns Array of column names to use as object keys
|
||||
* @param values Array of value arrays, where each inner array corresponds to one row of data
|
||||
* @returns Array of objects where each object maps column names to their corresponding values
|
||||
*/
|
||||
export function mapColumnsToValues(
|
||||
columns: string[],
|
||||
values: unknown[][],
|
||||
): Array<Record<string, unknown>> {
|
||||
return values.map((row) => {
|
||||
const obj: Record<string, unknown> = {};
|
||||
columns.forEach((column, index) => {
|
||||
obj[column] = row[index];
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug function to inspect raw settings data in the database
|
||||
* This helps diagnose issues with data corruption or malformed JSON
|
||||
* @param did Optional DID to inspect specific account settings
|
||||
* @author Matthew Raymer
|
||||
*/
|
||||
export async function debugSettingsData(did?: string): Promise<void> {
|
||||
try {
|
||||
const platform = PlatformServiceFactory.getInstance();
|
||||
|
||||
// Get all settings records
|
||||
const allSettings = await platform.dbQuery("SELECT * FROM settings");
|
||||
|
||||
logConsoleAndDb(
|
||||
`[DEBUG] Total settings records: ${allSettings?.values?.length || 0}`,
|
||||
false,
|
||||
);
|
||||
|
||||
if (allSettings?.values?.length) {
|
||||
allSettings.values.forEach((row, index) => {
|
||||
const settings = mapColumnsToValues(allSettings.columns, [row])[0];
|
||||
logConsoleAndDb(`[DEBUG] Settings record ${index + 1}:`, false);
|
||||
logConsoleAndDb(`[DEBUG] - ID: ${settings.id}`, false);
|
||||
logConsoleAndDb(`[DEBUG] - accountDid: ${settings.accountDid}`, false);
|
||||
logConsoleAndDb(`[DEBUG] - activeDid: ${settings.activeDid}`, false);
|
||||
|
||||
if (settings.searchBoxes) {
|
||||
logConsoleAndDb(
|
||||
`[DEBUG] - searchBoxes type: ${typeof settings.searchBoxes}`,
|
||||
false,
|
||||
);
|
||||
logConsoleAndDb(
|
||||
`[DEBUG] - searchBoxes value: ${String(settings.searchBoxes)}`,
|
||||
false,
|
||||
);
|
||||
|
||||
// Try to parse it
|
||||
try {
|
||||
const parsed = JSON.parse(String(settings.searchBoxes));
|
||||
logConsoleAndDb(
|
||||
`[DEBUG] - searchBoxes parsed successfully: ${JSON.stringify(parsed)}`,
|
||||
false,
|
||||
);
|
||||
} catch (parseError) {
|
||||
logConsoleAndDb(
|
||||
`[DEBUG] - searchBoxes parse error: ${parseError}`,
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
logConsoleAndDb(
|
||||
`[DEBUG] - Full record: ${JSON.stringify(settings, null, 2)}`,
|
||||
false,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// If specific DID provided, also check accounts table
|
||||
if (did) {
|
||||
const account = await platform.dbQuery(
|
||||
"SELECT * FROM accounts WHERE did = ?",
|
||||
[did],
|
||||
);
|
||||
logConsoleAndDb(
|
||||
`[DEBUG] Account for ${did}: ${JSON.stringify(account, null, 2)}`,
|
||||
false,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
logConsoleAndDb(`[DEBUG] Error inspecting settings data: ${error}`, true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Platform-agnostic JSON parsing utility
|
||||
* Handles different SQLite implementations:
|
||||
* - Web SQLite (wa-sqlite/absurd-sql): Auto-parses JSON strings to objects
|
||||
* - Capacitor SQLite: Returns raw strings that need manual parsing
|
||||
*
|
||||
* @param value The value to parse (could be string or already parsed object)
|
||||
* @param defaultValue Default value if parsing fails
|
||||
* @returns Parsed object or default value
|
||||
* @author Matthew Raymer
|
||||
*/
|
||||
export function parseJsonField<T>(value: unknown, defaultValue: T): T {
|
||||
try {
|
||||
// If already an object (web SQLite auto-parsed), return as-is
|
||||
if (typeof value === "object" && value !== null) {
|
||||
return value as T;
|
||||
}
|
||||
|
||||
// If it's a string (Capacitor SQLite or fallback), parse it
|
||||
if (typeof value === "string") {
|
||||
return JSON.parse(value) as T;
|
||||
}
|
||||
|
||||
// If it's null/undefined, return default
|
||||
if (value === null || value === undefined) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
return defaultValue;
|
||||
} catch (error) {
|
||||
logConsoleAndDb(
|
||||
`[databaseUtil] Failed to parse JSON field: ${error}`,
|
||||
true,
|
||||
);
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,9 @@
|
||||
/**
|
||||
* This is the original IndexedDB version of the database.
|
||||
* It will eventually be replaced fully by the SQL version in databaseUtil.ts.
|
||||
* Turn this on or off with the USE_DEXIE_DB constant in constants/app.ts.
|
||||
*/
|
||||
|
||||
import BaseDexie, { Table } from "dexie";
|
||||
import { encrypted, Encryption } from "@pvermeer/dexie-encrypted-addon";
|
||||
import * as R from "ramda";
|
||||
@@ -26,8 +32,8 @@ type NonsensitiveTables = {
|
||||
};
|
||||
|
||||
// Using 'unknown' instead of 'any' for stricter typing and to avoid TypeScript warnings
|
||||
export type SecretDexie<T extends unknown = SecretTable> = BaseDexie & T;
|
||||
export type SensitiveDexie<T extends unknown = SensitiveTables> = BaseDexie & T;
|
||||
type SecretDexie<T extends unknown = SecretTable> = BaseDexie & T;
|
||||
type SensitiveDexie<T extends unknown = SensitiveTables> = BaseDexie & T;
|
||||
export type NonsensitiveDexie<T extends unknown = NonsensitiveTables> =
|
||||
BaseDexie & T;
|
||||
|
||||
@@ -90,21 +96,18 @@ db.on("populate", async () => {
|
||||
try {
|
||||
await db.settings.add(DEFAULT_SETTINGS);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Error populating the database with default settings:",
|
||||
error,
|
||||
);
|
||||
logger.error("Error populating the database with default settings:", error);
|
||||
}
|
||||
});
|
||||
|
||||
// Helper function to safely open the database with retries
|
||||
async function safeOpenDatabase(retries = 1, delay = 500): Promise<void> {
|
||||
// console.log("Starting safeOpenDatabase with retries:", retries);
|
||||
// logger.log("Starting safeOpenDatabase with retries:", retries);
|
||||
for (let i = 0; i < retries; i++) {
|
||||
try {
|
||||
// console.log(`Attempt ${i + 1}: Checking if database is open...`);
|
||||
// logger.log(`Attempt ${i + 1}: Checking if database is open...`);
|
||||
if (!db.isOpen()) {
|
||||
// console.log(`Attempt ${i + 1}: Database is closed, attempting to open...`);
|
||||
// logger.log(`Attempt ${i + 1}: Database is closed, attempting to open...`);
|
||||
|
||||
// Create a promise that rejects after 5 seconds
|
||||
const timeoutPromise = new Promise((_, reject) => {
|
||||
@@ -113,19 +116,19 @@ async function safeOpenDatabase(retries = 1, delay = 500): Promise<void> {
|
||||
|
||||
// Race between the open operation and the timeout
|
||||
const openPromise = db.open();
|
||||
// console.log(`Attempt ${i + 1}: Waiting for db.open() promise...`);
|
||||
// logger.log(`Attempt ${i + 1}: Waiting for db.open() promise...`);
|
||||
await Promise.race([openPromise, timeoutPromise]);
|
||||
|
||||
// If we get here, the open succeeded
|
||||
// console.log(`Attempt ${i + 1}: Database opened successfully`);
|
||||
// logger.log(`Attempt ${i + 1}: Database opened successfully`);
|
||||
return;
|
||||
}
|
||||
// console.log(`Attempt ${i + 1}: Database was already open`);
|
||||
// logger.log(`Attempt ${i + 1}: Database was already open`);
|
||||
return;
|
||||
} catch (error) {
|
||||
console.error(`Attempt ${i + 1}: Database open failed:`, error);
|
||||
logger.error(`Attempt ${i + 1}: Database open failed:`, error);
|
||||
if (i < retries - 1) {
|
||||
console.log(`Attempt ${i + 1}: Waiting ${delay}ms before retry...`);
|
||||
logger.log(`Attempt ${i + 1}: Waiting ${delay}ms before retry...`);
|
||||
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||
} else {
|
||||
throw error;
|
||||
@@ -142,16 +145,14 @@ export async function updateDefaultSettings(
|
||||
delete settingsChanges.id;
|
||||
try {
|
||||
try {
|
||||
// console.log("Database state before open:", db.isOpen() ? "open" : "closed");
|
||||
// console.log("Database name:", db.name);
|
||||
// console.log("Database version:", db.verno);
|
||||
// logger.log("Database state before open:", db.isOpen() ? "open" : "closed");
|
||||
// logger.log("Database name:", db.name);
|
||||
// logger.log("Database version:", db.verno);
|
||||
await safeOpenDatabase();
|
||||
} catch (openError: unknown) {
|
||||
console.error("Failed to open database:", openError);
|
||||
const errorMessage =
|
||||
openError instanceof Error ? openError.message : String(openError);
|
||||
logger.error("Failed to open database:", openError, String(openError));
|
||||
throw new Error(
|
||||
`Database connection failed: ${errorMessage}. Please try again or restart the app.`,
|
||||
`The database connection failed. We recommend you try again or restart the app.`,
|
||||
);
|
||||
}
|
||||
const result = await db.settings.update(
|
||||
@@ -160,11 +161,13 @@ export async function updateDefaultSettings(
|
||||
);
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error("Error updating default settings:", error);
|
||||
logger.error("Error updating default settings:", error);
|
||||
if (error instanceof Error) {
|
||||
throw error; // Re-throw if it's already an Error with a message
|
||||
} else {
|
||||
throw new Error(`Failed to update settings: ${error}`);
|
||||
throw new Error(
|
||||
`Failed to update settings. We recommend you try again or restart the app.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,12 @@ export type Account = {
|
||||
publicKeyHex: string;
|
||||
};
|
||||
|
||||
// When finished with USE_DEXIE_DB, move these fields to Account and move identity and mnemonic here.
|
||||
export type AccountEncrypted = Account & {
|
||||
identityEncrBase64: string;
|
||||
mnemonicEncrBase64: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Schema for the accounts table in the database.
|
||||
* Fields starting with a $ character are encrypted.
|
||||
|
||||
@@ -25,6 +25,25 @@ function createWindow(): void {
|
||||
logger.log("Checking preload path:", preloadPath);
|
||||
logger.log("Preload exists:", fs.existsSync(preloadPath));
|
||||
|
||||
// Log environment and paths
|
||||
logger.log("process.cwd():", process.cwd());
|
||||
logger.log("__dirname:", __dirname);
|
||||
logger.log("app.getAppPath():", app.getAppPath());
|
||||
logger.log("app.isPackaged:", app.isPackaged);
|
||||
|
||||
// List files in __dirname and __dirname/www
|
||||
try {
|
||||
logger.log("Files in __dirname:", fs.readdirSync(__dirname));
|
||||
const wwwDir = path.join(__dirname, "www");
|
||||
if (fs.existsSync(wwwDir)) {
|
||||
logger.log("Files in www:", fs.readdirSync(wwwDir));
|
||||
} else {
|
||||
logger.log("www directory does not exist in __dirname");
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error("Error reading directories:", e);
|
||||
}
|
||||
|
||||
// Create the browser window.
|
||||
const mainWindow = new BrowserWindow({
|
||||
width: 1200,
|
||||
@@ -88,7 +107,16 @@ function createWindow(): void {
|
||||
logger.log("process.cwd():", process.cwd());
|
||||
}
|
||||
|
||||
const indexPath = path.join(__dirname, "www", "index.html");
|
||||
let indexPath = path.resolve(__dirname, "dist-electron", "www", "index.html");
|
||||
if (!fs.existsSync(indexPath)) {
|
||||
// Fallback for dev mode
|
||||
indexPath = path.resolve(
|
||||
process.cwd(),
|
||||
"dist-electron",
|
||||
"www",
|
||||
"index.html",
|
||||
);
|
||||
}
|
||||
|
||||
if (isDev) {
|
||||
logger.log("Loading index from:", indexPath);
|
||||
|
||||
@@ -2,24 +2,33 @@ const { contextBridge, ipcRenderer } = require("electron");
|
||||
|
||||
const logger = {
|
||||
log: (message, ...args) => {
|
||||
// Always log in development, log with context in production
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
/* eslint-disable no-console */
|
||||
console.log(message, ...args);
|
||||
console.log(`[Preload] ${message}`, ...args);
|
||||
/* eslint-enable no-console */
|
||||
}
|
||||
},
|
||||
warn: (message, ...args) => {
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
/* eslint-disable no-console */
|
||||
console.warn(message, ...args);
|
||||
/* eslint-enable no-console */
|
||||
}
|
||||
// Always log warnings
|
||||
/* eslint-disable no-console */
|
||||
console.warn(`[Preload] ${message}`, ...args);
|
||||
/* eslint-enable no-console */
|
||||
},
|
||||
error: (message, ...args) => {
|
||||
// Always log errors
|
||||
/* eslint-disable no-console */
|
||||
console.error(message, ...args); // Errors should always be logged
|
||||
console.error(`[Preload] ${message}`, ...args);
|
||||
/* eslint-enable no-console */
|
||||
},
|
||||
info: (message, ...args) => {
|
||||
// Always log info in development, log with context in production
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
/* eslint-disable no-console */
|
||||
console.info(`[Preload] ${message}`, ...args);
|
||||
/* eslint-enable no-console */
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// Use a more direct path resolution approach
|
||||
@@ -41,7 +50,10 @@ const getPath = (pathType) => {
|
||||
}
|
||||
};
|
||||
|
||||
logger.log("Preload script starting...");
|
||||
logger.info("Preload script starting...");
|
||||
|
||||
// Force electron platform in the renderer process
|
||||
window.process = { env: { VITE_PLATFORM: "electron" } };
|
||||
|
||||
try {
|
||||
contextBridge.exposeInMainWorld("electronAPI", {
|
||||
@@ -65,6 +77,7 @@ try {
|
||||
env: {
|
||||
isElectron: true,
|
||||
isDev: process.env.NODE_ENV === "development",
|
||||
platform: "electron", // Explicitly set platform
|
||||
},
|
||||
// Path utilities
|
||||
getBasePath: () => {
|
||||
@@ -72,7 +85,7 @@ try {
|
||||
},
|
||||
});
|
||||
|
||||
logger.log("Preload script completed successfully");
|
||||
logger.info("Preload script completed successfully");
|
||||
} catch (error) {
|
||||
logger.error("Error in preload script:", error);
|
||||
}
|
||||
|
||||
59
src/interfaces/absurd-sql.d.ts
vendored
Normal file
59
src/interfaces/absurd-sql.d.ts
vendored
Normal file
@@ -0,0 +1,59 @@
|
||||
import type { QueryExecResult, SqlValue } from "./database";
|
||||
|
||||
declare module "@jlongster/sql.js" {
|
||||
interface SQL {
|
||||
Database: new (path: string, options?: { filename: boolean }) => AbsurdSqlDatabase;
|
||||
FS: {
|
||||
mkdir: (path: string) => void;
|
||||
mount: (fs: any, options: any, path: string) => void;
|
||||
open: (path: string, flags: string) => any;
|
||||
close: (stream: any) => void;
|
||||
};
|
||||
register_for_idb: (fs: any) => void;
|
||||
}
|
||||
|
||||
interface AbsurdSqlDatabase {
|
||||
exec: (sql: string, params?: unknown[]) => Promise<QueryExecResult[]>;
|
||||
run: (
|
||||
sql: string,
|
||||
params?: unknown[],
|
||||
) => Promise<{ changes: number; lastId?: number }>;
|
||||
}
|
||||
|
||||
const initSqlJs: (options?: {
|
||||
locateFile?: (file: string) => string;
|
||||
}) => Promise<SQL>;
|
||||
|
||||
export default initSqlJs;
|
||||
}
|
||||
|
||||
declare module "absurd-sql" {
|
||||
import type { SQL } from "@jlongster/sql.js";
|
||||
|
||||
export class SQLiteFS {
|
||||
constructor(fs: any, backend: any);
|
||||
}
|
||||
}
|
||||
|
||||
declare module "absurd-sql/dist/indexeddb-backend" {
|
||||
export default class IndexedDBBackend {
|
||||
constructor();
|
||||
}
|
||||
}
|
||||
|
||||
declare module "absurd-sql/dist/indexeddb-main-thread" {
|
||||
export interface SQLiteOptions {
|
||||
filename?: string;
|
||||
autoLoad?: boolean;
|
||||
debug?: boolean;
|
||||
}
|
||||
|
||||
export interface SQLiteDatabase {
|
||||
exec: (sql: string, params?: unknown[]) => Promise<QueryExecResult[]>;
|
||||
close: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function initSqlJs(options?: any): Promise<any>;
|
||||
export function createDatabase(options?: SQLiteOptions): Promise<SQLiteDatabase>;
|
||||
export function openDatabase(options?: SQLiteOptions): Promise<SQLiteDatabase>;
|
||||
}
|
||||
@@ -1,15 +1,24 @@
|
||||
import { GenericVerifiableCredential } from "./common";
|
||||
/**
|
||||
* Types of Claims
|
||||
*
|
||||
* Note that these are for the claims that get signed.
|
||||
* Records that are the latest edited entities are in the records.ts file.
|
||||
*
|
||||
*/
|
||||
|
||||
export interface AgreeVerifiableCredential {
|
||||
"@context": string;
|
||||
import { ClaimObject } from "./common";
|
||||
|
||||
export interface AgreeActionClaim extends ClaimObject {
|
||||
"@context": "https://schema.org";
|
||||
"@type": string;
|
||||
object: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// Note that previous VCs may have additional fields.
|
||||
// https://endorser.ch/doc/html/transactions.html#id4
|
||||
export interface GiveVerifiableCredential extends GenericVerifiableCredential {
|
||||
"@context"?: string;
|
||||
export interface GiveActionClaim extends ClaimObject {
|
||||
// context is optional because it might be embedded in another claim, eg. an AgreeAction
|
||||
"@context"?: "https://schema.org";
|
||||
"@type": "GiveAction";
|
||||
agent?: { identifier: string };
|
||||
description?: string;
|
||||
@@ -17,16 +26,25 @@ export interface GiveVerifiableCredential extends GenericVerifiableCredential {
|
||||
identifier?: string;
|
||||
image?: string;
|
||||
object?: { amountOfThisGood: number; unitCode: string };
|
||||
provider?: GenericVerifiableCredential;
|
||||
provider?: ClaimObject;
|
||||
recipient?: { identifier: string };
|
||||
}
|
||||
|
||||
export interface JoinActionClaim extends ClaimObject {
|
||||
agent?: { identifier: string };
|
||||
event?: { organizer?: { name: string }; name?: string; startTime?: string };
|
||||
}
|
||||
|
||||
// Note that previous VCs may have additional fields.
|
||||
// https://endorser.ch/doc/html/transactions.html#id8
|
||||
export interface OfferVerifiableCredential extends GenericVerifiableCredential {
|
||||
"@context"?: string;
|
||||
export interface OfferClaim extends ClaimObject {
|
||||
"@context": "https://schema.org";
|
||||
"@type": "Offer";
|
||||
agent?: { identifier: string };
|
||||
description?: string;
|
||||
fulfills?: { "@type": string; identifier?: string; lastClaimId?: string }[];
|
||||
identifier?: string;
|
||||
image?: string;
|
||||
includesObject?: { amountOfThisGood: number; unitCode: string };
|
||||
itemOffered?: {
|
||||
description?: string;
|
||||
@@ -37,14 +55,18 @@ export interface OfferVerifiableCredential extends GenericVerifiableCredential {
|
||||
name?: string;
|
||||
};
|
||||
};
|
||||
offeredBy?: { identifier: string };
|
||||
offeredBy?: {
|
||||
type?: "Person";
|
||||
identifier: string;
|
||||
};
|
||||
provider?: ClaimObject;
|
||||
recipient?: { identifier: string };
|
||||
validThrough?: string;
|
||||
}
|
||||
|
||||
// Note that previous VCs may have additional fields.
|
||||
// https://endorser.ch/doc/html/transactions.html#id7
|
||||
export interface PlanVerifiableCredential extends GenericVerifiableCredential {
|
||||
export interface PlanActionClaim extends ClaimObject {
|
||||
"@context": "https://schema.org";
|
||||
"@type": "PlanAction";
|
||||
name: string;
|
||||
@@ -58,11 +80,18 @@ export interface PlanVerifiableCredential extends GenericVerifiableCredential {
|
||||
}
|
||||
|
||||
// AKA Registration & RegisterAction
|
||||
export interface RegisterVerifiableCredential {
|
||||
"@context": string;
|
||||
export interface RegisterActionClaim extends ClaimObject {
|
||||
"@context": "https://schema.org";
|
||||
"@type": "RegisterAction";
|
||||
agent: { identifier: string };
|
||||
identifier?: string;
|
||||
object: string;
|
||||
object?: string;
|
||||
participant?: { identifier: string };
|
||||
}
|
||||
|
||||
export interface TenureClaim extends ClaimObject {
|
||||
"@context": "https://endorser.ch";
|
||||
"@type": "Tenure";
|
||||
party?: { identifier: string };
|
||||
spatialUnit?: { geo?: { polygon?: string } };
|
||||
}
|
||||
|
||||
@@ -34,3 +34,77 @@ export interface ErrorResult extends ResultWithType {
|
||||
type: "error";
|
||||
error: InternalError;
|
||||
}
|
||||
|
||||
export interface KeyMeta {
|
||||
did: string;
|
||||
publicKeyHex: string;
|
||||
derivationPath?: string;
|
||||
passkeyCredIdHex?: string; // The Webauthn credential ID in hex, if this is from a passkey
|
||||
}
|
||||
|
||||
export interface KeyMetaMaybeWithPrivate extends KeyMeta {
|
||||
mnemonic?: string; // 12 or 24 words encoding the seed
|
||||
identity?: string; // Stringified IIdentifier object from Veramo
|
||||
}
|
||||
|
||||
export interface KeyMetaWithPrivate extends KeyMeta {
|
||||
mnemonic: string; // 12 or 24 words encoding the seed
|
||||
identity: string; // Stringified IIdentifier object from Veramo
|
||||
}
|
||||
|
||||
export interface QuantitativeValue extends GenericVerifiableCredential {
|
||||
"@type": "QuantitativeValue";
|
||||
"@context"?: string;
|
||||
amountOfThisGood: number;
|
||||
unitCode: string;
|
||||
}
|
||||
|
||||
export interface AxiosErrorResponse {
|
||||
message?: string;
|
||||
response?: {
|
||||
data?: {
|
||||
error?: {
|
||||
message?: string;
|
||||
};
|
||||
[key: string]: unknown;
|
||||
};
|
||||
status?: number;
|
||||
config?: unknown;
|
||||
};
|
||||
config?: unknown;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface UserInfo {
|
||||
did: string;
|
||||
name: string;
|
||||
publicEncKey: string;
|
||||
registered: boolean;
|
||||
profileImageUrl?: string;
|
||||
nextPublicEncKeyHash?: string;
|
||||
}
|
||||
|
||||
export interface CreateAndSubmitClaimResult {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
handleId?: string;
|
||||
}
|
||||
|
||||
export interface Agent {
|
||||
identifier?: string;
|
||||
did?: string;
|
||||
}
|
||||
|
||||
export interface ClaimObject {
|
||||
"@type": string;
|
||||
"@context"?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface VerifiableCredentialClaim {
|
||||
"@context"?: string;
|
||||
"@type": string;
|
||||
type: string[];
|
||||
credentialSubject: ClaimObject;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
15
src/interfaces/database.ts
Normal file
15
src/interfaces/database.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
export type SqlValue = string | number | null | Uint8Array;
|
||||
|
||||
export interface QueryExecResult {
|
||||
columns: Array<string>;
|
||||
values: Array<Array<SqlValue>>;
|
||||
}
|
||||
|
||||
export interface DatabaseService {
|
||||
initialize(): Promise<void>;
|
||||
query(sql: string, params?: unknown[]): Promise<QueryExecResult[]>;
|
||||
run(
|
||||
sql: string,
|
||||
params?: unknown[],
|
||||
): Promise<{ changes: number; lastId?: number }>;
|
||||
}
|
||||
@@ -1,13 +1,17 @@
|
||||
/**
|
||||
* Interfaces for the give records with limited contact information, good to show on a feed.
|
||||
**/
|
||||
|
||||
import { GiveSummaryRecord } from "./records";
|
||||
|
||||
// Common interface for contact information
|
||||
// Common interface for views with summary contact information
|
||||
export interface ContactInfo {
|
||||
known: boolean;
|
||||
displayName: string;
|
||||
profileImageUrl?: string;
|
||||
}
|
||||
|
||||
// Define the contact information fields
|
||||
// Define a subset of contact information fields
|
||||
interface GiveContactInfo {
|
||||
giver: ContactInfo;
|
||||
issuer: ContactInfo;
|
||||
@@ -17,5 +21,5 @@ interface GiveContactInfo {
|
||||
image?: string;
|
||||
}
|
||||
|
||||
// Combine GiveSummaryRecord with contact information using intersection type
|
||||
// Combine GiveSummaryRecord with contact information
|
||||
export type GiveRecordWithContactInfo = GiveSummaryRecord & GiveContactInfo;
|
||||
|
||||
@@ -1,7 +1,37 @@
|
||||
export * from "./claims";
|
||||
export * from "./claims-result";
|
||||
export * from "./common";
|
||||
export type {
|
||||
// From common.ts
|
||||
GenericCredWrapper,
|
||||
GenericVerifiableCredential,
|
||||
KeyMeta,
|
||||
// Exclude types that are also exported from other files
|
||||
// GiveVerifiableCredential,
|
||||
// OfferVerifiableCredential,
|
||||
// RegisterVerifiableCredential,
|
||||
// PlanSummaryRecord,
|
||||
// UserInfo,
|
||||
} from "./common";
|
||||
|
||||
export type {
|
||||
// From claims.ts
|
||||
GiveActionClaim,
|
||||
OfferClaim,
|
||||
RegisterActionClaim,
|
||||
} from "./claims";
|
||||
|
||||
export type {
|
||||
// From claims-result.ts
|
||||
CreateAndSubmitClaimResult,
|
||||
} from "./claims-result";
|
||||
|
||||
export type {
|
||||
// From records.ts
|
||||
PlanSummaryRecord,
|
||||
} from "./records";
|
||||
|
||||
export type {
|
||||
// From user.ts
|
||||
UserInfo,
|
||||
} from "./user";
|
||||
|
||||
export * from "./limits";
|
||||
export * from "./records";
|
||||
export * from "./user";
|
||||
export * from "./deepLinks";
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { GiveVerifiableCredential, OfferVerifiableCredential } from "./claims";
|
||||
import { GiveActionClaim, OfferClaim } from "./claims";
|
||||
|
||||
// a summary record; the VC is found the fullClaim field
|
||||
export interface GiveSummaryRecord {
|
||||
[x: string]: PropertyKey | undefined | GiveVerifiableCredential;
|
||||
[x: string]: PropertyKey | undefined | GiveActionClaim;
|
||||
type?: string;
|
||||
agentDid: string;
|
||||
amount: number;
|
||||
amountConfirmed: number;
|
||||
description: string;
|
||||
fullClaim: GiveVerifiableCredential;
|
||||
fullClaim: GiveActionClaim;
|
||||
fulfillsHandleId: string;
|
||||
fulfillsPlanHandleId?: string;
|
||||
fulfillsType?: string;
|
||||
@@ -26,7 +26,7 @@ export interface OfferSummaryRecord {
|
||||
amount: number;
|
||||
amountGiven: number;
|
||||
amountGivenConfirmed: number;
|
||||
fullClaim: OfferVerifiableCredential;
|
||||
fullClaim: OfferClaim;
|
||||
fulfillsPlanHandleId: string;
|
||||
handleId: string;
|
||||
issuerDid: string;
|
||||
|
||||
@@ -32,7 +32,7 @@ export const newIdentifier = (
|
||||
publicHex: string,
|
||||
privateHex: string,
|
||||
derivationPath: string,
|
||||
): Omit<IIdentifier, keyof "provider"> => {
|
||||
): IIdentifier => {
|
||||
return {
|
||||
did: DEFAULT_DID_PROVIDER_NAME + ":" + address,
|
||||
keys: [
|
||||
@@ -159,7 +159,7 @@ export const nextDerivationPath = (origDerivPath: string) => {
|
||||
};
|
||||
|
||||
// Base64 encoding/decoding utilities for browser
|
||||
function base64ToArrayBuffer(base64: string): Uint8Array {
|
||||
export function base64ToArrayBuffer(base64: string): Uint8Array {
|
||||
const binaryString = atob(base64);
|
||||
const bytes = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
@@ -168,7 +168,7 @@ function base64ToArrayBuffer(base64: string): Uint8Array {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function arrayBufferToBase64(buffer: ArrayBuffer): string {
|
||||
export function arrayBufferToBase64(buffer: ArrayBuffer): string {
|
||||
const binary = String.fromCharCode(...new Uint8Array(buffer));
|
||||
return btoa(binary);
|
||||
}
|
||||
@@ -178,7 +178,7 @@ const IV_LENGTH = 12;
|
||||
const KEY_LENGTH = 256;
|
||||
const ITERATIONS = 100000;
|
||||
|
||||
// Encryption helper function
|
||||
// Message encryption helper function, used for onboarding meeting messages
|
||||
export async function encryptMessage(message: string, password: string) {
|
||||
const encoder = new TextEncoder();
|
||||
const salt = crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
|
||||
@@ -226,7 +226,7 @@ export async function encryptMessage(message: string, password: string) {
|
||||
return btoa(JSON.stringify(result));
|
||||
}
|
||||
|
||||
// Decryption helper function
|
||||
// Message decryption helper function, used for onboarding meeting messages
|
||||
export async function decryptMessage(encryptedJson: string, password: string) {
|
||||
const decoder = new TextDecoder();
|
||||
const { salt, iv, encrypted } = JSON.parse(atob(encryptedJson));
|
||||
@@ -273,7 +273,7 @@ export async function decryptMessage(encryptedJson: string, password: string) {
|
||||
}
|
||||
|
||||
// Test function to verify encryption/decryption
|
||||
export async function testEncryptionDecryption() {
|
||||
export async function testMessageEncryptionDecryption() {
|
||||
try {
|
||||
const testMessage = "Hello, this is a test message! 🚀";
|
||||
const testPassword = "myTestPassword123";
|
||||
@@ -299,9 +299,111 @@ export async function testEncryptionDecryption() {
|
||||
logger.log("\nTesting with wrong password...");
|
||||
try {
|
||||
await decryptMessage(encrypted, "wrongPassword");
|
||||
logger.log("Should not reach here");
|
||||
logger.log("Incorrectly decrypted with wrong password ❌");
|
||||
} catch (error) {
|
||||
logger.log("Correctly failed with wrong password ✅");
|
||||
logger.log("Correctly failed to decrypt with wrong password ✅");
|
||||
}
|
||||
|
||||
return success;
|
||||
} catch (error) {
|
||||
logger.error("Test failed with error:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Simple encryption using Node's crypto, used for the initial encryption of the identity and mnemonic
|
||||
export async function simpleEncrypt(
|
||||
text: string,
|
||||
secret: ArrayBuffer,
|
||||
): Promise<ArrayBuffer> {
|
||||
const iv = crypto.getRandomValues(new Uint8Array(16));
|
||||
|
||||
// Derive a 256-bit key from the secret using SHA-256
|
||||
const keyData = await crypto.subtle.digest("SHA-256", secret);
|
||||
const key = await crypto.subtle.importKey(
|
||||
"raw",
|
||||
keyData,
|
||||
{ name: "AES-GCM" },
|
||||
false,
|
||||
["encrypt"],
|
||||
);
|
||||
|
||||
const encrypted = await crypto.subtle.encrypt(
|
||||
{ name: "AES-GCM", iv },
|
||||
key,
|
||||
new TextEncoder().encode(text),
|
||||
);
|
||||
|
||||
// Combine IV and encrypted data
|
||||
const result = new Uint8Array(iv.length + encrypted.byteLength);
|
||||
result.set(iv);
|
||||
result.set(new Uint8Array(encrypted), iv.length);
|
||||
|
||||
return result.buffer;
|
||||
}
|
||||
|
||||
// Simple decryption using Node's crypto, used for the default decryption of identity and mnemonic
|
||||
export async function simpleDecrypt(
|
||||
encryptedText: ArrayBuffer,
|
||||
secret: ArrayBuffer,
|
||||
): Promise<string> {
|
||||
const data = new Uint8Array(encryptedText);
|
||||
|
||||
// Extract IV and encrypted data
|
||||
const iv = data.slice(0, 16);
|
||||
const encrypted = data.slice(16);
|
||||
|
||||
// Derive the same 256-bit key from the secret using SHA-256
|
||||
const keyData = await crypto.subtle.digest("SHA-256", secret);
|
||||
const key = await crypto.subtle.importKey(
|
||||
"raw",
|
||||
keyData,
|
||||
{ name: "AES-GCM" },
|
||||
false,
|
||||
["decrypt"],
|
||||
);
|
||||
|
||||
const decrypted = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv },
|
||||
key,
|
||||
encrypted,
|
||||
);
|
||||
|
||||
return new TextDecoder().decode(decrypted);
|
||||
}
|
||||
|
||||
// Test function for simple encryption/decryption
|
||||
export async function testSimpleEncryptionDecryption() {
|
||||
try {
|
||||
const testMessage = "Hello, this is a test message! 🚀";
|
||||
const testSecret = crypto.getRandomValues(new Uint8Array(32));
|
||||
|
||||
logger.log("Original message:", testMessage);
|
||||
|
||||
// Test encryption
|
||||
logger.log("Encrypting...");
|
||||
const encrypted = await simpleEncrypt(testMessage, testSecret);
|
||||
const encryptedBase64 = arrayBufferToBase64(encrypted);
|
||||
logger.log("Encrypted result:", encryptedBase64);
|
||||
|
||||
// Test decryption
|
||||
logger.log("Decrypting...");
|
||||
const encryptedArrayBuffer = base64ToArrayBuffer(encryptedBase64);
|
||||
const decrypted = await simpleDecrypt(encryptedArrayBuffer, testSecret);
|
||||
logger.log("Decrypted result:", decrypted);
|
||||
|
||||
// Verify
|
||||
const success = testMessage === decrypted;
|
||||
logger.log("Test " + (success ? "PASSED ✅" : "FAILED ❌"));
|
||||
logger.log("Messages match:", success);
|
||||
|
||||
// Test with wrong secret
|
||||
logger.log("\nTesting with wrong secret...");
|
||||
try {
|
||||
await simpleDecrypt(encryptedArrayBuffer, new Uint8Array(32));
|
||||
logger.log("Incorrectly decrypted with wrong secret ❌");
|
||||
} catch (error) {
|
||||
logger.log("Correctly failed to decrypt with wrong secret ✅");
|
||||
}
|
||||
|
||||
return success;
|
||||
|
||||
@@ -17,29 +17,12 @@ import { didEthLocalResolver } from "./did-eth-local-resolver";
|
||||
import { PEER_DID_PREFIX, verifyPeerSignature } from "./didPeer";
|
||||
import { base64urlDecodeString, createDidPeerJwt } from "./passkeyDidPeer";
|
||||
import { urlBase64ToUint8Array } from "./util";
|
||||
import { KeyMeta, KeyMetaWithPrivate } from "../../../interfaces/common";
|
||||
|
||||
export const ETHR_DID_PREFIX = "did:ethr:";
|
||||
export const JWT_VERIFY_FAILED_CODE = "JWT_VERIFY_FAILED";
|
||||
export const UNSUPPORTED_DID_METHOD_CODE = "UNSUPPORTED_DID_METHOD";
|
||||
|
||||
/**
|
||||
* Meta info about a key
|
||||
*/
|
||||
export interface KeyMeta {
|
||||
/**
|
||||
* Decentralized ID for the key
|
||||
*/
|
||||
did: string;
|
||||
/**
|
||||
* Stringified IIDentifier object from Veramo
|
||||
*/
|
||||
identity?: string;
|
||||
/**
|
||||
* The Webauthn credential ID in hex, if this is from a passkey
|
||||
*/
|
||||
passkeyCredIdHex?: string;
|
||||
}
|
||||
|
||||
const ethLocalResolver = new Resolver({ ethr: didEthLocalResolver });
|
||||
|
||||
/**
|
||||
@@ -51,7 +34,7 @@ export function isFromPasskey(keyMeta?: KeyMeta): boolean {
|
||||
}
|
||||
|
||||
export async function createEndorserJwtForKey(
|
||||
account: KeyMeta,
|
||||
account: KeyMetaWithPrivate,
|
||||
payload: object,
|
||||
expiresIn?: number,
|
||||
) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Buffer } from "buffer/";
|
||||
import { JWTPayload } from "did-jwt";
|
||||
import { DIDResolutionResult } from "did-resolver";
|
||||
import { sha256 } from "ethereum-cryptography/sha256.js";
|
||||
import { p256 } from "@noble/curves/p256";
|
||||
import {
|
||||
startAuthentication,
|
||||
startRegistration,
|
||||
@@ -11,12 +10,13 @@ import {
|
||||
generateRegistrationOptions,
|
||||
verifyAuthenticationResponse,
|
||||
verifyRegistrationResponse,
|
||||
VerifyAuthenticationResponseOpts,
|
||||
} from "@simplewebauthn/server";
|
||||
import { VerifyAuthenticationResponseOpts } from "@simplewebauthn/server/esm/authentication/verifyAuthenticationResponse";
|
||||
import {
|
||||
Base64URLString,
|
||||
PublicKeyCredentialCreationOptionsJSON,
|
||||
PublicKeyCredentialRequestOptionsJSON,
|
||||
AuthenticatorAssertionResponse,
|
||||
} from "@simplewebauthn/types";
|
||||
|
||||
import { AppString } from "../../../constants/app";
|
||||
@@ -194,16 +194,19 @@ export class PeerSetup {
|
||||
},
|
||||
};
|
||||
|
||||
const credential = await navigator.credentials.get(options);
|
||||
const credential = (await navigator.credentials.get(
|
||||
options,
|
||||
)) as PublicKeyCredential;
|
||||
// console.log("nav credential get", credential);
|
||||
|
||||
this.authenticatorData = credential?.response.authenticatorData;
|
||||
const response = credential?.response as AuthenticatorAssertionResponse;
|
||||
this.authenticatorData = response?.authenticatorData;
|
||||
const authenticatorDataBase64Url = arrayBufferToBase64URLString(
|
||||
this.authenticatorData as ArrayBuffer,
|
||||
);
|
||||
|
||||
this.clientDataJsonBase64Url = arrayBufferToBase64URLString(
|
||||
credential?.response.clientDataJSON,
|
||||
response?.clientDataJSON,
|
||||
);
|
||||
|
||||
// Our custom type of JWANT means the signature is based on a concatenation of the two Webauthn properties
|
||||
@@ -228,9 +231,7 @@ export class PeerSetup {
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/, "");
|
||||
|
||||
const origSignature = Buffer.from(credential?.response.signature).toString(
|
||||
"base64",
|
||||
);
|
||||
const origSignature = Buffer.from(response?.signature).toString("base64");
|
||||
this.signature = origSignature
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
@@ -315,24 +316,18 @@ export async function createDidPeerJwt(
|
||||
// ... and this import:
|
||||
// import { p256 } from "@noble/curves/p256";
|
||||
export async function verifyJwtP256(
|
||||
credIdHex: string,
|
||||
issuerDid: string,
|
||||
authenticatorData: ArrayBuffer,
|
||||
challenge: Uint8Array,
|
||||
clientDataJsonBase64Url: Base64URLString,
|
||||
signature: Base64URLString,
|
||||
) {
|
||||
const authDataFromBase = Buffer.from(authenticatorData);
|
||||
const clientDataFromBase = Buffer.from(clientDataJsonBase64Url, "base64");
|
||||
const sigBuffer = Buffer.from(signature, "base64");
|
||||
const finalSigBuffer = unwrapEC2Signature(sigBuffer);
|
||||
const publicKeyBytes = peerDidToPublicKeyBytes(issuerDid);
|
||||
|
||||
// Hash the client data
|
||||
const hash = sha256(clientDataFromBase);
|
||||
|
||||
// Construct the preimage
|
||||
const preimage = Buffer.concat([authDataFromBase, hash]);
|
||||
// Use challenge in preimage construction
|
||||
const preimage = Buffer.concat([authDataFromBase, Buffer.from(challenge)]);
|
||||
|
||||
const isValid = p256.verify(
|
||||
finalSigBuffer,
|
||||
@@ -383,122 +378,37 @@ export async function verifyJwtSimplewebauthn(
|
||||
|
||||
// similar code is in endorser-ch util-crypto.ts verifyPeerSignature
|
||||
export async function verifyJwtWebCrypto(
|
||||
credId: Base64URLString,
|
||||
issuerDid: string,
|
||||
authenticatorData: ArrayBuffer,
|
||||
challenge: Uint8Array,
|
||||
clientDataJsonBase64Url: Base64URLString,
|
||||
signature: Base64URLString,
|
||||
) {
|
||||
const authDataFromBase = Buffer.from(authenticatorData);
|
||||
const clientDataFromBase = Buffer.from(clientDataJsonBase64Url, "base64");
|
||||
const sigBuffer = Buffer.from(signature, "base64");
|
||||
const finalSigBuffer = unwrapEC2Signature(sigBuffer);
|
||||
|
||||
// Hash the client data
|
||||
const hash = sha256(clientDataFromBase);
|
||||
// Use challenge in preimage construction
|
||||
const preimage = Buffer.concat([authDataFromBase, Buffer.from(challenge)]);
|
||||
|
||||
// Construct the preimage
|
||||
const preimage = Buffer.concat([authDataFromBase, hash]);
|
||||
return verifyPeerSignature(preimage, issuerDid, finalSigBuffer);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
async function peerDidToDidDocument(did: string): Promise<DIDResolutionResult> {
|
||||
if (!did.startsWith("did:peer:0z")) {
|
||||
throw new Error(
|
||||
"This only verifies a peer DID, method 0, encoded base58btc.",
|
||||
);
|
||||
}
|
||||
// this is basically hard-coded from https://www.w3.org/TR/did-core/#example-various-verification-method-types
|
||||
// (another reference is the @aviarytech/did-peer resolver)
|
||||
// Remove unused functions:
|
||||
// - peerDidToDidDocument
|
||||
// - COSEtoPEM
|
||||
// - base64urlDecodeArrayBuffer
|
||||
// - base64urlEncodeArrayBuffer
|
||||
// - pemToCryptoKey
|
||||
|
||||
/**
|
||||
* Looks like JsonWebKey2020 isn't too difficult:
|
||||
* - change context security/suites link to jws-2020/v1
|
||||
* - change publicKeyMultibase to publicKeyJwk generated with cborToKeys
|
||||
* - change type to JsonWebKey2020
|
||||
*/
|
||||
|
||||
const id = did.split(":")[2];
|
||||
const multibase = id.slice(1);
|
||||
const encnumbasis = multibase.slice(1);
|
||||
const didDocument = {
|
||||
"@context": [
|
||||
"https://www.w3.org/ns/did/v1",
|
||||
"https://w3id.org/security/suites/secp256k1-2019/v1",
|
||||
],
|
||||
assertionMethod: [did + "#" + encnumbasis],
|
||||
authentication: [did + "#" + encnumbasis],
|
||||
capabilityDelegation: [did + "#" + encnumbasis],
|
||||
capabilityInvocation: [did + "#" + encnumbasis],
|
||||
id: did,
|
||||
keyAgreement: undefined,
|
||||
service: undefined,
|
||||
verificationMethod: [
|
||||
{
|
||||
controller: did,
|
||||
id: did + "#" + encnumbasis,
|
||||
publicKeyMultibase: multibase,
|
||||
type: "EcdsaSecp256k1VerificationKey2019",
|
||||
},
|
||||
],
|
||||
};
|
||||
return {
|
||||
didDocument,
|
||||
didDocumentMetadata: {},
|
||||
didResolutionMetadata: { contentType: "application/did+ld+json" },
|
||||
};
|
||||
}
|
||||
|
||||
// convert COSE public key to PEM format
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function COSEtoPEM(cose: Buffer) {
|
||||
// const alg = cose.get(3); // Algorithm
|
||||
const x = cose[-2]; // x-coordinate
|
||||
const y = cose[-3]; // y-coordinate
|
||||
|
||||
// Ensure the coordinates are in the correct format
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error because it complains about the type of x and y
|
||||
const pubKeyBuffer = Buffer.concat([Buffer.from([0x04]), x, y]);
|
||||
|
||||
// Convert to PEM format
|
||||
const pem = `-----BEGIN PUBLIC KEY-----
|
||||
${pubKeyBuffer.toString("base64")}
|
||||
-----END PUBLIC KEY-----`;
|
||||
|
||||
return pem;
|
||||
}
|
||||
|
||||
// tried the base64url library but got an error using their Buffer
|
||||
// Keep only the used functions:
|
||||
export function base64urlDecodeString(input: string) {
|
||||
return atob(input.replace(/-/g, "+").replace(/_/g, "/"));
|
||||
}
|
||||
|
||||
// tried the base64url library but got an error using their Buffer
|
||||
export function base64urlEncodeString(input: string) {
|
||||
return btoa(input).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function base64urlDecodeArrayBuffer(input: string) {
|
||||
input = input.replace(/-/g, "+").replace(/_/g, "/");
|
||||
const pad = input.length % 4 === 0 ? "" : "====".slice(input.length % 4);
|
||||
const str = atob(input + pad);
|
||||
const bytes = new Uint8Array(str.length);
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
bytes[i] = str.charCodeAt(i);
|
||||
}
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function base64urlEncodeArrayBuffer(buffer: ArrayBuffer) {
|
||||
const str = String.fromCharCode(...new Uint8Array(buffer));
|
||||
return base64urlEncodeString(str);
|
||||
}
|
||||
|
||||
// from @simplewebauthn/browser
|
||||
function arrayBufferToBase64URLString(buffer: ArrayBuffer) {
|
||||
const bytes = new Uint8Array(buffer);
|
||||
@@ -523,28 +433,3 @@ function base64URLStringToArrayBuffer(base64URLString: string) {
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
async function pemToCryptoKey(pem: string) {
|
||||
const binaryDerString = atob(
|
||||
pem
|
||||
.split("\n")
|
||||
.filter((x) => !x.includes("-----"))
|
||||
.join(""),
|
||||
);
|
||||
const binaryDer = new Uint8Array(binaryDerString.length);
|
||||
for (let i = 0; i < binaryDerString.length; i++) {
|
||||
binaryDer[i] = binaryDerString.charCodeAt(i);
|
||||
}
|
||||
// console.log("binaryDer", binaryDer.buffer);
|
||||
return await window.crypto.subtle.importKey(
|
||||
"spki",
|
||||
binaryDer.buffer,
|
||||
{
|
||||
name: "RSASSA-PKCS1-v1_5",
|
||||
hash: "SHA-256",
|
||||
},
|
||||
true,
|
||||
["verify"],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -26,29 +26,42 @@ import {
|
||||
DEFAULT_IMAGE_API_SERVER,
|
||||
NotificationIface,
|
||||
APP_SERVER,
|
||||
USE_DEXIE_DB,
|
||||
} from "../constants/app";
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
import { accessToken, deriveAddress, nextDerivationPath } from "../libs/crypto";
|
||||
import { logConsoleAndDb, NonsensitiveDexie } from "../db/index";
|
||||
|
||||
import { NonsensitiveDexie } from "../db/index";
|
||||
import { logConsoleAndDb } from "../db/databaseUtil";
|
||||
import {
|
||||
retrieveAccountMetadata,
|
||||
retrieveFullyDecryptedAccount,
|
||||
getPasskeyExpirationSeconds,
|
||||
} from "../libs/util";
|
||||
import { createEndorserJwtForKey, KeyMeta } from "../libs/crypto/vc";
|
||||
import { createEndorserJwtForKey } from "../libs/crypto/vc";
|
||||
import {
|
||||
GiveActionClaim,
|
||||
JoinActionClaim,
|
||||
OfferClaim,
|
||||
PlanActionClaim,
|
||||
RegisterActionClaim,
|
||||
TenureClaim,
|
||||
} from "../interfaces/claims";
|
||||
|
||||
import {
|
||||
GiveVerifiableCredential,
|
||||
OfferVerifiableCredential,
|
||||
RegisterVerifiableCredential,
|
||||
GenericVerifiableCredential,
|
||||
GenericCredWrapper,
|
||||
PlanSummaryRecord,
|
||||
GenericVerifiableCredential,
|
||||
AxiosErrorResponse,
|
||||
UserInfo,
|
||||
CreateAndSubmitClaimResult,
|
||||
} from "../interfaces";
|
||||
ClaimObject,
|
||||
VerifiableCredentialClaim,
|
||||
QuantitativeValue,
|
||||
KeyMetaWithPrivate,
|
||||
KeyMetaMaybeWithPrivate,
|
||||
} from "../interfaces/common";
|
||||
import { PlanSummaryRecord } from "../interfaces/records";
|
||||
import { logger } from "../utils/logger";
|
||||
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
|
||||
|
||||
/**
|
||||
* Standard context for schema.org data
|
||||
@@ -100,7 +113,10 @@ export const ENDORSER_CH_HANDLE_PREFIX = "https://endorser.ch/entity/";
|
||||
|
||||
export const BLANK_GENERIC_SERVER_RECORD: GenericCredWrapper<GenericVerifiableCredential> =
|
||||
{
|
||||
claim: { "@type": "" },
|
||||
claim: {
|
||||
"@context": SCHEMA_ORG_CONTEXT,
|
||||
"@type": "",
|
||||
},
|
||||
handleId: "",
|
||||
id: "",
|
||||
issuedAt: "",
|
||||
@@ -125,7 +141,7 @@ export function isDid(did: string): boolean {
|
||||
* @param {string} did - The DID to check
|
||||
* @returns {boolean} True if DID is hidden
|
||||
*/
|
||||
export function isHiddenDid(did: string): boolean {
|
||||
export function isHiddenDid(did: string | undefined): boolean {
|
||||
return did === HIDDEN_DID;
|
||||
}
|
||||
|
||||
@@ -180,37 +196,21 @@ export function isEmptyOrHiddenDid(did?: string): boolean {
|
||||
* };
|
||||
* testRecursivelyOnStrings(isHiddenDid, obj); // Returns: true
|
||||
*/
|
||||
function testRecursivelyOnStrings(
|
||||
func: (arg0: unknown) => boolean,
|
||||
const testRecursivelyOnStrings = (
|
||||
input: unknown,
|
||||
): boolean {
|
||||
// Test direct string values
|
||||
if (Object.prototype.toString.call(input) === "[object String]") {
|
||||
return func(input);
|
||||
test: (s: string) => boolean,
|
||||
): boolean => {
|
||||
if (typeof input === "string") {
|
||||
return test(input);
|
||||
} else if (Array.isArray(input)) {
|
||||
return input.some((item) => testRecursivelyOnStrings(item, test));
|
||||
} else if (input && typeof input === "object") {
|
||||
return Object.values(input as Record<string, unknown>).some((value) =>
|
||||
testRecursivelyOnStrings(value, test),
|
||||
);
|
||||
}
|
||||
// Recursively test objects and arrays
|
||||
else if (input instanceof Object) {
|
||||
if (!Array.isArray(input)) {
|
||||
// Handle plain objects
|
||||
for (const key in input) {
|
||||
if (testRecursivelyOnStrings(func, input[key])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Handle arrays
|
||||
for (const value of input) {
|
||||
if (testRecursivelyOnStrings(func, value)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} else {
|
||||
// Non-string, non-object values can't contain strings
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function containsHiddenDid(obj: any) {
|
||||
@@ -551,7 +551,11 @@ export async function setPlanInCache(
|
||||
* @returns {string|undefined} User-friendly message or undefined if none found
|
||||
*/
|
||||
export function serverMessageForUser(error: unknown): string | undefined {
|
||||
return error?.response?.data?.error?.message;
|
||||
if (error && typeof error === "object" && "response" in error) {
|
||||
const err = error as AxiosErrorResponse;
|
||||
return err.response?.data?.error?.message;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -573,18 +577,27 @@ export function errorStringForLog(error: unknown) {
|
||||
// --- property '_value' closes the circle
|
||||
}
|
||||
let fullError = "" + error + " - JSON: " + stringifiedError;
|
||||
const errorResponseText = JSON.stringify(error.response);
|
||||
// for some reason, error.response is not included in stringify result (eg. for 400 errors on invite redemptions)
|
||||
if (!R.empty(errorResponseText) && !fullError.includes(errorResponseText)) {
|
||||
// add error.response stuff
|
||||
if (R.equals(error?.config, error?.response?.config)) {
|
||||
// but exclude "config" because it's already in there
|
||||
const newErrorResponseText = JSON.stringify(
|
||||
R.omit(["config"] as never[], error.response),
|
||||
);
|
||||
fullError += " - .response w/o same config JSON: " + newErrorResponseText;
|
||||
} else {
|
||||
fullError += " - .response JSON: " + errorResponseText;
|
||||
|
||||
if (error && typeof error === "object" && "response" in error) {
|
||||
const err = error as AxiosErrorResponse;
|
||||
const errorResponseText = JSON.stringify(err.response);
|
||||
// for some reason, error.response is not included in stringify result (eg. for 400 errors on invite redemptions)
|
||||
if (!R.empty(errorResponseText) && !fullError.includes(errorResponseText)) {
|
||||
// add error.response stuff
|
||||
if (
|
||||
err.response?.config &&
|
||||
err.config &&
|
||||
R.equals(err.config, err.response.config)
|
||||
) {
|
||||
// but exclude "config" because it's already in there
|
||||
const newErrorResponseText = JSON.stringify(
|
||||
R.omit(["config"] as never[], err.response),
|
||||
);
|
||||
fullError +=
|
||||
" - .response w/o same config JSON: " + newErrorResponseText;
|
||||
} else {
|
||||
fullError += " - .response JSON: " + errorResponseText;
|
||||
}
|
||||
}
|
||||
}
|
||||
return fullError;
|
||||
@@ -642,7 +655,7 @@ export async function getNewOffersToUserProjects(
|
||||
* @param lastClaimId supplied when editing a previous claim
|
||||
*/
|
||||
export function hydrateGive(
|
||||
vcClaimOrig?: GiveVerifiableCredential,
|
||||
vcClaimOrig?: GiveActionClaim,
|
||||
fromDid?: string,
|
||||
toDid?: string,
|
||||
description?: string,
|
||||
@@ -650,14 +663,12 @@ export function hydrateGive(
|
||||
unitCode?: string,
|
||||
fulfillsProjectHandleId?: string,
|
||||
fulfillsOfferHandleId?: string,
|
||||
isTrade: boolean = false, // remove, because this app is all for gifting
|
||||
isTrade: boolean = false,
|
||||
imageUrl?: string,
|
||||
providerPlanHandleId?: string,
|
||||
lastClaimId?: string,
|
||||
): GiveVerifiableCredential {
|
||||
// Remember: replace values or erase if it's null
|
||||
|
||||
const vcClaim: GiveVerifiableCredential = vcClaimOrig
|
||||
): GiveActionClaim {
|
||||
const vcClaim: GiveActionClaim = vcClaimOrig
|
||||
? R.clone(vcClaimOrig)
|
||||
: {
|
||||
"@context": SCHEMA_ORG_CONTEXT,
|
||||
@@ -665,55 +676,71 @@ export function hydrateGive(
|
||||
};
|
||||
|
||||
if (lastClaimId) {
|
||||
// this is an edit
|
||||
vcClaim.lastClaimId = lastClaimId;
|
||||
delete vcClaim.identifier;
|
||||
}
|
||||
|
||||
vcClaim.agent = fromDid ? { identifier: fromDid } : undefined;
|
||||
vcClaim.recipient = toDid ? { identifier: toDid } : undefined;
|
||||
if (fromDid) {
|
||||
vcClaim.agent = { identifier: fromDid };
|
||||
}
|
||||
if (toDid) {
|
||||
vcClaim.recipient = { identifier: toDid };
|
||||
}
|
||||
vcClaim.description = description || undefined;
|
||||
vcClaim.object =
|
||||
amount && !isNaN(amount)
|
||||
? { amountOfThisGood: amount, unitCode: unitCode || "HUR" }
|
||||
: undefined;
|
||||
|
||||
// ensure fulfills is an array
|
||||
if (amount && !isNaN(amount)) {
|
||||
const quantitativeValue: QuantitativeValue = {
|
||||
amountOfThisGood: amount,
|
||||
unitCode: unitCode || "HUR",
|
||||
};
|
||||
vcClaim.object = quantitativeValue;
|
||||
}
|
||||
|
||||
// Initialize fulfills array if not present
|
||||
if (!Array.isArray(vcClaim.fulfills)) {
|
||||
vcClaim.fulfills = vcClaim.fulfills ? [vcClaim.fulfills] : [];
|
||||
}
|
||||
// ... and replace or add each element, ending with Trade or Donate
|
||||
// I realize the following doesn't change any elements that are not PlanAction or Offer or Trade/Action.
|
||||
|
||||
// Filter and add fulfills elements
|
||||
vcClaim.fulfills = vcClaim.fulfills.filter(
|
||||
(elem) => elem["@type"] !== "PlanAction",
|
||||
(elem: { "@type": string }) => elem["@type"] !== "PlanAction",
|
||||
);
|
||||
|
||||
if (fulfillsProjectHandleId) {
|
||||
vcClaim.fulfills.push({
|
||||
"@type": "PlanAction",
|
||||
identifier: fulfillsProjectHandleId,
|
||||
});
|
||||
}
|
||||
|
||||
vcClaim.fulfills = vcClaim.fulfills.filter(
|
||||
(elem) => elem["@type"] !== "Offer",
|
||||
(elem: { "@type": string }) => elem["@type"] !== "Offer",
|
||||
);
|
||||
|
||||
if (fulfillsOfferHandleId) {
|
||||
vcClaim.fulfills.push({
|
||||
"@type": "Offer",
|
||||
identifier: fulfillsOfferHandleId,
|
||||
});
|
||||
}
|
||||
// do Trade/Donate last because current endorser.ch only looks at the first for plans & offers
|
||||
|
||||
vcClaim.fulfills = vcClaim.fulfills.filter(
|
||||
(elem) =>
|
||||
(elem: { "@type": string }) =>
|
||||
elem["@type"] !== "DonateAction" && elem["@type"] !== "TradeAction",
|
||||
);
|
||||
vcClaim.fulfills.push({ "@type": isTrade ? "TradeAction" : "DonateAction" });
|
||||
|
||||
vcClaim.fulfills.push({
|
||||
"@type": isTrade ? "TradeAction" : "DonateAction",
|
||||
});
|
||||
|
||||
vcClaim.image = imageUrl || undefined;
|
||||
|
||||
vcClaim.provider = providerPlanHandleId
|
||||
? { "@type": "PlanAction", identifier: providerPlanHandleId }
|
||||
: undefined;
|
||||
if (providerPlanHandleId) {
|
||||
vcClaim.provider = {
|
||||
"@type": "PlanAction",
|
||||
identifier: providerPlanHandleId,
|
||||
};
|
||||
}
|
||||
|
||||
return vcClaim;
|
||||
}
|
||||
@@ -774,7 +801,7 @@ export async function createAndSubmitGive(
|
||||
export async function editAndSubmitGive(
|
||||
axios: Axios,
|
||||
apiServer: string,
|
||||
fullClaim: GenericCredWrapper<GiveVerifiableCredential>,
|
||||
fullClaim: GenericCredWrapper<GiveActionClaim>,
|
||||
issuerDid: string,
|
||||
fromDid?: string,
|
||||
toDid?: string,
|
||||
@@ -815,7 +842,7 @@ export async function editAndSubmitGive(
|
||||
* @param lastClaimId supplied when editing a previous claim
|
||||
*/
|
||||
export function hydrateOffer(
|
||||
vcClaimOrig?: OfferVerifiableCredential,
|
||||
vcClaimOrig?: OfferClaim,
|
||||
fromDid?: string,
|
||||
toDid?: string,
|
||||
itemDescription?: string,
|
||||
@@ -825,10 +852,8 @@ export function hydrateOffer(
|
||||
fulfillsProjectHandleId?: string,
|
||||
validThrough?: string,
|
||||
lastClaimId?: string,
|
||||
): OfferVerifiableCredential {
|
||||
// Remember: replace values or erase if it's null
|
||||
|
||||
const vcClaim: OfferVerifiableCredential = vcClaimOrig
|
||||
): OfferClaim {
|
||||
const vcClaim: OfferClaim = vcClaimOrig
|
||||
? R.clone(vcClaimOrig)
|
||||
: {
|
||||
"@context": SCHEMA_ORG_CONTEXT,
|
||||
@@ -841,14 +866,20 @@ export function hydrateOffer(
|
||||
delete vcClaim.identifier;
|
||||
}
|
||||
|
||||
vcClaim.offeredBy = fromDid ? { identifier: fromDid } : undefined;
|
||||
vcClaim.recipient = toDid ? { identifier: toDid } : undefined;
|
||||
if (fromDid) {
|
||||
vcClaim.offeredBy = { identifier: fromDid };
|
||||
}
|
||||
if (toDid) {
|
||||
vcClaim.recipient = { identifier: toDid };
|
||||
}
|
||||
vcClaim.description = conditionDescription || undefined;
|
||||
|
||||
vcClaim.includesObject =
|
||||
amount && !isNaN(amount)
|
||||
? { amountOfThisGood: amount, unitCode: unitCode || "HUR" }
|
||||
: undefined;
|
||||
if (amount && !isNaN(amount)) {
|
||||
vcClaim.includesObject = {
|
||||
amountOfThisGood: amount,
|
||||
unitCode: unitCode || "HUR",
|
||||
};
|
||||
}
|
||||
|
||||
if (itemDescription || fulfillsProjectHandleId) {
|
||||
vcClaim.itemOffered = vcClaim.itemOffered || {};
|
||||
@@ -860,6 +891,7 @@ export function hydrateOffer(
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
vcClaim.validThrough = validThrough || undefined;
|
||||
|
||||
return vcClaim;
|
||||
@@ -899,7 +931,7 @@ export async function createAndSubmitOffer(
|
||||
undefined,
|
||||
);
|
||||
return createAndSubmitClaim(
|
||||
vcClaim as OfferVerifiableCredential,
|
||||
vcClaim as OfferClaim,
|
||||
issuerDid,
|
||||
apiServer,
|
||||
axios,
|
||||
@@ -909,7 +941,7 @@ export async function createAndSubmitOffer(
|
||||
export async function editAndSubmitOffer(
|
||||
axios: Axios,
|
||||
apiServer: string,
|
||||
fullClaim: GenericCredWrapper<OfferVerifiableCredential>,
|
||||
fullClaim: GenericCredWrapper<OfferClaim>,
|
||||
issuerDid: string,
|
||||
itemDescription: string,
|
||||
amount?: number,
|
||||
@@ -932,7 +964,7 @@ export async function editAndSubmitOffer(
|
||||
fullClaim.id,
|
||||
);
|
||||
return createAndSubmitClaim(
|
||||
vcClaim as OfferVerifiableCredential,
|
||||
vcClaim as OfferClaim,
|
||||
issuerDid,
|
||||
apiServer,
|
||||
axios,
|
||||
@@ -988,26 +1020,25 @@ export async function createAndSubmitClaim(
|
||||
},
|
||||
});
|
||||
|
||||
return { type: "success", response };
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (error: any) {
|
||||
return { success: true, handleId: response.data?.handleId };
|
||||
} catch (error: unknown) {
|
||||
logger.error("Error submitting claim:", error);
|
||||
const errorMessage: string =
|
||||
serverMessageForUser(error) ||
|
||||
error.message ||
|
||||
(error && typeof error === "object" && "message" in error
|
||||
? String(error.message)
|
||||
: undefined) ||
|
||||
"Got some error submitting the claim. Check your permissions, network, and error logs.";
|
||||
|
||||
return {
|
||||
type: "error",
|
||||
error: {
|
||||
error: errorMessage,
|
||||
},
|
||||
success: false,
|
||||
error: errorMessage,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateEndorserJwtUrlForAccount(
|
||||
account: KeyMeta,
|
||||
account: KeyMetaMaybeWithPrivate,
|
||||
isRegistered: boolean,
|
||||
givenName: string,
|
||||
profileImageUrl: string,
|
||||
@@ -1031,12 +1062,9 @@ export async function generateEndorserJwtUrlForAccount(
|
||||
}
|
||||
|
||||
// Add the next key -- not recommended for the QR code for such a high resolution
|
||||
if (isContact && account?.mnemonic && account?.derivationPath) {
|
||||
const newDerivPath = nextDerivationPath(account.derivationPath as string);
|
||||
const nextPublicHex = deriveAddress(
|
||||
account.mnemonic as string,
|
||||
newDerivPath,
|
||||
)[2];
|
||||
if (isContact && account.derivationPath && account.mnemonic) {
|
||||
const newDerivPath = nextDerivationPath(account.derivationPath);
|
||||
const nextPublicHex = deriveAddress(account.mnemonic, newDerivPath)[2];
|
||||
const nextPublicEncKey = Buffer.from(nextPublicHex, "hex");
|
||||
const nextPublicEncKeyHash = sha256(nextPublicEncKey);
|
||||
const nextPublicEncKeyHashBase64 =
|
||||
@@ -1056,7 +1084,11 @@ export async function createEndorserJwtForDid(
|
||||
expiresIn?: number,
|
||||
) {
|
||||
const account = await retrieveFullyDecryptedAccount(issuerDid);
|
||||
return createEndorserJwtForKey(account as KeyMeta, payload, expiresIn);
|
||||
return createEndorserJwtForKey(
|
||||
account as KeyMetaWithPrivate,
|
||||
payload,
|
||||
expiresIn,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1104,21 +1136,21 @@ export const capitalizeAndInsertSpacesBeforeCaps = (text: string) => {
|
||||
|
||||
similar code is also contained in endorser-mobile
|
||||
**/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const claimSummary = (
|
||||
claim: GenericCredWrapper<GenericVerifiableCredential>,
|
||||
claim:
|
||||
| GenericVerifiableCredential
|
||||
| GenericCredWrapper<GenericVerifiableCredential>,
|
||||
) => {
|
||||
if (!claim) {
|
||||
// to differentiate from "something" above
|
||||
return "something";
|
||||
}
|
||||
let specificClaim:
|
||||
| GenericVerifiableCredential
|
||||
| GenericCredWrapper<GenericVerifiableCredential> = claim;
|
||||
if (claim.claim) {
|
||||
// probably a Verified Credential
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
specificClaim = claim.claim;
|
||||
let specificClaim: GenericVerifiableCredential;
|
||||
if ("claim" in claim) {
|
||||
// It's a GenericCredWrapper
|
||||
specificClaim = claim.claim as GenericVerifiableCredential;
|
||||
} else {
|
||||
// It's already a GenericVerifiableCredential
|
||||
specificClaim = claim;
|
||||
}
|
||||
if (Array.isArray(specificClaim)) {
|
||||
if (specificClaim.length === 1) {
|
||||
@@ -1153,88 +1185,112 @@ export const claimSpecialDescription = (
|
||||
identifiers: Array<string>,
|
||||
contacts: Array<Contact>,
|
||||
) => {
|
||||
let claim = record.claim;
|
||||
if (claim.claim) {
|
||||
// it's probably a Verified Credential
|
||||
claim = claim.claim;
|
||||
let claim:
|
||||
| GenericVerifiableCredential
|
||||
| GenericCredWrapper<GenericVerifiableCredential> = record.claim;
|
||||
if ("claim" in claim) {
|
||||
// it's a nested GenericCredWrapper
|
||||
claim = claim.claim as GenericVerifiableCredential;
|
||||
}
|
||||
|
||||
const issuer = didInfo(record.issuer, activeDid, identifiers, contacts);
|
||||
const type = claim["@type"] || "UnknownType";
|
||||
|
||||
if (type === "AgreeAction") {
|
||||
return issuer + " agreed with " + claimSummary(claim.object);
|
||||
return (
|
||||
issuer +
|
||||
" agreed with " +
|
||||
claimSummary(claim.object as GenericVerifiableCredential)
|
||||
);
|
||||
} else if (isAccept(claim)) {
|
||||
return issuer + " accepted " + claimSummary(claim.object);
|
||||
return (
|
||||
issuer +
|
||||
" accepted " +
|
||||
claimSummary(claim.object as GenericVerifiableCredential)
|
||||
);
|
||||
} else if (type === "GiveAction") {
|
||||
// agent.did is for legacy data, before March 2023
|
||||
const giver = claim.agent?.identifier || claim.agent?.did;
|
||||
const giveClaim = claim as GiveActionClaim;
|
||||
// @ts-expect-error because .did may be found in legacy data, before March 2023
|
||||
const legacyGiverDid = giveClaim.agent?.did;
|
||||
const giver = giveClaim.agent?.identifier || legacyGiverDid;
|
||||
const giverInfo = didInfo(giver, activeDid, identifiers, contacts);
|
||||
let gaveAmount = claim.object?.amountOfThisGood
|
||||
? displayAmount(claim.object.unitCode, claim.object.amountOfThisGood)
|
||||
let gaveAmount = giveClaim.object?.amountOfThisGood
|
||||
? displayAmount(
|
||||
giveClaim.object.unitCode as string,
|
||||
giveClaim.object.amountOfThisGood as number,
|
||||
)
|
||||
: "";
|
||||
if (claim.description) {
|
||||
if (giveClaim.description) {
|
||||
if (gaveAmount) {
|
||||
gaveAmount = gaveAmount + ", and also: ";
|
||||
}
|
||||
gaveAmount = gaveAmount + claim.description;
|
||||
gaveAmount = gaveAmount + giveClaim.description;
|
||||
}
|
||||
if (!gaveAmount) {
|
||||
gaveAmount = "something not described";
|
||||
}
|
||||
// recipient.did is for legacy data, before March 2023
|
||||
const gaveRecipientId = claim.recipient?.identifier || claim.recipient?.did;
|
||||
// @ts-expect-error because .did may be found in legacy data, before March 2023
|
||||
const legacyRecipDid = giveClaim.recipient?.did;
|
||||
const gaveRecipientId = giveClaim.recipient?.identifier || legacyRecipDid;
|
||||
const gaveRecipientInfo = gaveRecipientId
|
||||
? " to " + didInfo(gaveRecipientId, activeDid, identifiers, contacts)
|
||||
: "";
|
||||
return giverInfo + " gave" + gaveRecipientInfo + ": " + gaveAmount;
|
||||
} else if (type === "JoinAction") {
|
||||
// agent.did is for legacy data, before March 2023
|
||||
const agent = claim.agent?.identifier || claim.agent?.did;
|
||||
const joinClaim = claim as JoinActionClaim;
|
||||
// @ts-expect-error because .did may be found in legacy data, before March 2023
|
||||
const legacyDid = joinClaim.agent?.did;
|
||||
const agent = joinClaim.agent?.identifier || legacyDid;
|
||||
const contactInfo = didInfo(agent, activeDid, identifiers, contacts);
|
||||
|
||||
let eventOrganizer =
|
||||
claim.event && claim.event.organizer && claim.event.organizer.name;
|
||||
joinClaim.event &&
|
||||
joinClaim.event.organizer &&
|
||||
joinClaim.event.organizer.name;
|
||||
eventOrganizer = eventOrganizer || "";
|
||||
let eventName = claim.event && claim.event.name;
|
||||
let eventName = joinClaim.event && joinClaim.event.name;
|
||||
eventName = eventName ? " " + eventName : "";
|
||||
let fullEvent = eventOrganizer + eventName;
|
||||
fullEvent = fullEvent ? " attended the " + fullEvent : "";
|
||||
|
||||
let eventDate = claim.event && claim.event.startTime;
|
||||
let eventDate = joinClaim.event && joinClaim.event.startTime;
|
||||
eventDate = eventDate ? " at " + eventDate : "";
|
||||
return contactInfo + fullEvent + eventDate;
|
||||
} else if (isOffer(claim)) {
|
||||
const offerer = claim.offeredBy?.identifier;
|
||||
const offerClaim = claim as OfferClaim;
|
||||
const offerer = offerClaim.offeredBy?.identifier;
|
||||
const contactInfo = didInfo(offerer, activeDid, identifiers, contacts);
|
||||
let offering = "";
|
||||
if (claim.includesObject) {
|
||||
if (offerClaim.includesObject) {
|
||||
offering +=
|
||||
" " +
|
||||
displayAmount(
|
||||
claim.includesObject.unitCode,
|
||||
claim.includesObject.amountOfThisGood,
|
||||
offerClaim.includesObject.unitCode,
|
||||
offerClaim.includesObject.amountOfThisGood,
|
||||
);
|
||||
}
|
||||
if (claim.itemOffered?.description) {
|
||||
offering += ", saying: " + claim.itemOffered?.description;
|
||||
if (offerClaim.itemOffered?.description) {
|
||||
offering += ", saying: " + offerClaim.itemOffered?.description;
|
||||
}
|
||||
// recipient.did is for legacy data, before March 2023
|
||||
const offerRecipientId =
|
||||
claim.recipient?.identifier || claim.recipient?.did;
|
||||
// @ts-expect-error because .did may be found in legacy data, before March 2023
|
||||
const legacyDid = offerClaim.recipient?.did;
|
||||
const offerRecipientId = offerClaim.recipient?.identifier || legacyDid;
|
||||
const offerRecipientInfo = offerRecipientId
|
||||
? " to " + didInfo(offerRecipientId, activeDid, identifiers, contacts)
|
||||
: "";
|
||||
return contactInfo + " offered" + offering + offerRecipientInfo;
|
||||
} else if (type === "PlanAction") {
|
||||
const claimer = claim.agent?.identifier || record.issuer;
|
||||
const planClaim = claim as PlanActionClaim;
|
||||
const claimer = planClaim.agent?.identifier || record.issuer;
|
||||
const claimerInfo = didInfo(claimer, activeDid, identifiers, contacts);
|
||||
return claimerInfo + " announced a project: " + claim.name;
|
||||
return claimerInfo + " announced a project: " + planClaim.name;
|
||||
} else if (type === "Tenure") {
|
||||
// party.did is for legacy data, before March 2023
|
||||
const claimer = claim.party?.identifier || claim.party?.did;
|
||||
const tenureClaim = claim as TenureClaim;
|
||||
// @ts-expect-error because .did may be found in legacy data, before March 2023
|
||||
const legacyDid = tenureClaim.party?.did;
|
||||
const claimer = tenureClaim.party?.identifier || legacyDid;
|
||||
const contactInfo = didInfo(claimer, activeDid, identifiers, contacts);
|
||||
const polygon = claim.spatialUnit?.geo?.polygon || "";
|
||||
const polygon = tenureClaim.spatialUnit?.geo?.polygon || "";
|
||||
return (
|
||||
contactInfo +
|
||||
" possesses [" +
|
||||
@@ -1242,11 +1298,7 @@ export const claimSpecialDescription = (
|
||||
"...]"
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
issuer +
|
||||
" declared " +
|
||||
claimSummary(claim as GenericCredWrapper<GenericVerifiableCredential>)
|
||||
);
|
||||
return issuer + " declared " + claimSummary(claim);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1286,32 +1338,42 @@ export async function createEndorserJwtVcFromClaim(
|
||||
return createEndorserJwtForDid(issuerDid, vcPayload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a JWT for a RegisterAction claim.
|
||||
*
|
||||
* @param activeDid - The DID of the user creating the invite
|
||||
* @param contact - The contact to register, with a 'did' field (all optional for invites)
|
||||
* @param identifier - The identifier for the invite, usually random
|
||||
* @param expiresIn - The number of seconds until the invite expires
|
||||
* @returns The JWT for the RegisterAction claim
|
||||
*/
|
||||
export async function createInviteJwt(
|
||||
activeDid: string,
|
||||
contact?: Contact,
|
||||
inviteId?: string,
|
||||
expiresIn?: number,
|
||||
identifier?: string,
|
||||
expiresIn?: number, // in seconds
|
||||
): Promise<string> {
|
||||
const vcClaim: RegisterVerifiableCredential = {
|
||||
const vcClaim: RegisterActionClaim = {
|
||||
"@context": SCHEMA_ORG_CONTEXT,
|
||||
"@type": "RegisterAction",
|
||||
agent: { identifier: activeDid },
|
||||
object: SERVICE_ID,
|
||||
identifier: identifier,
|
||||
};
|
||||
if (contact) {
|
||||
if (contact?.did) {
|
||||
vcClaim.participant = { identifier: contact.did };
|
||||
}
|
||||
if (inviteId) {
|
||||
vcClaim.identifier = inviteId;
|
||||
}
|
||||
|
||||
// Make a payload for the claim
|
||||
const vcPayload = {
|
||||
const vcPayload: { vc: VerifiableCredentialClaim } = {
|
||||
vc: {
|
||||
"@context": ["https://www.w3.org/2018/credentials/v1"],
|
||||
"@type": "VerifiableCredential",
|
||||
type: ["VerifiableCredential"],
|
||||
credentialSubject: vcClaim,
|
||||
credentialSubject: vcClaim as unknown as ClaimObject, // Type assertion needed due to object being string
|
||||
},
|
||||
};
|
||||
|
||||
// Create a signature using private key of identity
|
||||
const vcJwt = await createEndorserJwtForDid(activeDid, vcPayload, expiresIn);
|
||||
return vcJwt;
|
||||
@@ -1323,21 +1385,44 @@ export async function register(
|
||||
axios: Axios,
|
||||
contact: Contact,
|
||||
): Promise<{ success?: boolean; error?: string }> {
|
||||
const vcJwt = await createInviteJwt(activeDid, contact);
|
||||
try {
|
||||
const vcJwt = await createInviteJwt(activeDid, contact);
|
||||
const url = apiServer + "/api/v2/claim";
|
||||
const resp = await axios.post<{
|
||||
success?: {
|
||||
handleId?: string;
|
||||
embeddedRecordError?: string;
|
||||
};
|
||||
error?: string;
|
||||
message?: string;
|
||||
}>(url, { jwtEncoded: vcJwt });
|
||||
|
||||
const url = apiServer + "/api/v2/claim";
|
||||
const resp = await axios.post(url, { jwtEncoded: vcJwt });
|
||||
if (resp.data?.success?.handleId) {
|
||||
return { success: true };
|
||||
} else if (resp.data?.success?.embeddedRecordError) {
|
||||
let message =
|
||||
"There was some problem with the registration and so it may not be complete.";
|
||||
if (typeof resp.data.success.embeddedRecordError == "string") {
|
||||
message += " " + resp.data.success.embeddedRecordError;
|
||||
if (resp.data?.success?.handleId) {
|
||||
return { success: true };
|
||||
} else if (resp.data?.success?.embeddedRecordError) {
|
||||
let message =
|
||||
"There was some problem with the registration and so it may not be complete.";
|
||||
if (typeof resp.data.success.embeddedRecordError === "string") {
|
||||
message += " " + resp.data.success.embeddedRecordError;
|
||||
}
|
||||
return { error: message };
|
||||
} else {
|
||||
logger.error("Registration error:", JSON.stringify(resp.data));
|
||||
return { error: "Got a server error when registering." };
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (error && typeof error === "object") {
|
||||
const err = error as AxiosErrorResponse;
|
||||
const errorMessage =
|
||||
err.message ||
|
||||
(err.response?.data &&
|
||||
typeof err.response.data === "object" &&
|
||||
"message" in err.response.data
|
||||
? (err.response.data as { message: string }).message
|
||||
: undefined);
|
||||
logger.error("Registration error:", errorMessage || JSON.stringify(err));
|
||||
return { error: errorMessage || "Got a server error when registering." };
|
||||
}
|
||||
return { error: message };
|
||||
} else {
|
||||
logger.error(resp);
|
||||
return { error: "Got a server error when registering." };
|
||||
}
|
||||
}
|
||||
@@ -1363,7 +1448,14 @@ export async function setVisibilityUtil(
|
||||
if (resp.status === 200) {
|
||||
const success = resp.data.success;
|
||||
if (success) {
|
||||
db.contacts.update(contact.did, { seesMe: visibility });
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
await platformService.dbExec(
|
||||
"UPDATE contacts SET seesMe = ? WHERE did = ?",
|
||||
[visibility, contact.did],
|
||||
);
|
||||
if (USE_DEXIE_DB) {
|
||||
db.contacts.update(contact.did, { seesMe: visibility });
|
||||
}
|
||||
}
|
||||
return { success };
|
||||
} else {
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
faCircleCheck,
|
||||
faCircleInfo,
|
||||
faCircleQuestion,
|
||||
faCircleRight,
|
||||
faCircleUser,
|
||||
faClock,
|
||||
faCoins,
|
||||
@@ -60,6 +61,7 @@ import {
|
||||
faLightbulb,
|
||||
faLink,
|
||||
faLocationDot,
|
||||
faLock,
|
||||
faLongArrowAltLeft,
|
||||
faLongArrowAltRight,
|
||||
faMagnifyingGlass,
|
||||
@@ -79,6 +81,7 @@ import {
|
||||
faSquareCaretDown,
|
||||
faSquareCaretUp,
|
||||
faSquarePlus,
|
||||
faThumbtack,
|
||||
faTrashCan,
|
||||
faTriangleExclamation,
|
||||
faUser,
|
||||
@@ -111,6 +114,7 @@ library.add(
|
||||
faCircleCheck,
|
||||
faCircleInfo,
|
||||
faCircleQuestion,
|
||||
faCircleRight,
|
||||
faCircleUser,
|
||||
faClock,
|
||||
faCoins,
|
||||
@@ -142,6 +146,7 @@ library.add(
|
||||
faLightbulb,
|
||||
faLink,
|
||||
faLocationDot,
|
||||
faLock,
|
||||
faLongArrowAltLeft,
|
||||
faLongArrowAltRight,
|
||||
faMagnifyingGlass,
|
||||
@@ -161,6 +166,7 @@ library.add(
|
||||
faSquareCaretDown,
|
||||
faSquareCaretUp,
|
||||
faSquarePlus,
|
||||
faThumbtack,
|
||||
faTrashCan,
|
||||
faTriangleExclamation,
|
||||
faUser,
|
||||
|
||||
482
src/libs/util.ts
482
src/libs/util.ts
@@ -5,33 +5,52 @@ import { Buffer } from "buffer";
|
||||
import * as R from "ramda";
|
||||
import { useClipboard } from "@vueuse/core";
|
||||
|
||||
import { DEFAULT_PUSH_SERVER, NotificationIface } from "../constants/app";
|
||||
import {
|
||||
DEFAULT_PUSH_SERVER,
|
||||
NotificationIface,
|
||||
USE_DEXIE_DB,
|
||||
} from "../constants/app";
|
||||
import {
|
||||
accountsDBPromise,
|
||||
retrieveSettingsForActiveAccount,
|
||||
updateAccountSettings,
|
||||
updateDefaultSettings,
|
||||
} from "../db/index";
|
||||
import { Account } from "../db/tables/accounts";
|
||||
import { Account, AccountEncrypted } from "../db/tables/accounts";
|
||||
import { Contact } from "../db/tables/contacts";
|
||||
import * as databaseUtil from "../db/databaseUtil";
|
||||
import { DEFAULT_PASSKEY_EXPIRATION_MINUTES } from "../db/tables/settings";
|
||||
import { deriveAddress, generateSeed, newIdentifier } from "../libs/crypto";
|
||||
import * as serverUtil from "../libs/endorserServer";
|
||||
import {
|
||||
containsHiddenDid,
|
||||
arrayBufferToBase64,
|
||||
base64ToArrayBuffer,
|
||||
deriveAddress,
|
||||
generateSeed,
|
||||
newIdentifier,
|
||||
simpleDecrypt,
|
||||
simpleEncrypt,
|
||||
} from "../libs/crypto";
|
||||
import * as serverUtil from "../libs/endorserServer";
|
||||
import { containsHiddenDid } from "../libs/endorserServer";
|
||||
import {
|
||||
GenericCredWrapper,
|
||||
GenericVerifiableCredential,
|
||||
GiveSummaryRecord,
|
||||
OfferVerifiableCredential,
|
||||
} from "../libs/endorserServer";
|
||||
import { KeyMeta } from "../libs/crypto/vc";
|
||||
KeyMetaWithPrivate,
|
||||
} from "../interfaces/common";
|
||||
import { GiveSummaryRecord } from "../interfaces/records";
|
||||
import { OfferClaim } from "../interfaces/claims";
|
||||
import { createPeerDid } from "../libs/crypto/vc/didPeer";
|
||||
import { registerCredential } from "../libs/crypto/vc/passkeyDidPeer";
|
||||
import { logger } from "../utils/logger";
|
||||
import { PlatformServiceFactory } from "@/services/PlatformServiceFactory";
|
||||
import { sha256 } from "ethereum-cryptography/sha256";
|
||||
import { IIdentifier } from "@veramo/core";
|
||||
import { insertDidSpecificSettings, parseJsonField } from "../db/databaseUtil";
|
||||
|
||||
export interface GiverReceiverInputInfo {
|
||||
did?: string;
|
||||
name?: string;
|
||||
image?: string;
|
||||
handleId?: string;
|
||||
}
|
||||
|
||||
export enum OnboardPage {
|
||||
@@ -66,18 +85,24 @@ export const UNIT_LONG: Record<string, string> = {
|
||||
};
|
||||
/* eslint-enable prettier/prettier */
|
||||
|
||||
const UNIT_CODES: Record<string, Record<string, string>> = {
|
||||
const UNIT_CODES: Record<
|
||||
string,
|
||||
{ name: string; faIcon: string; decimals: number }
|
||||
> = {
|
||||
BTC: {
|
||||
name: "Bitcoin",
|
||||
faIcon: "bitcoin-sign",
|
||||
decimals: 4,
|
||||
},
|
||||
HUR: {
|
||||
name: "hours",
|
||||
faIcon: "clock",
|
||||
decimals: 0,
|
||||
},
|
||||
USD: {
|
||||
name: "US Dollars",
|
||||
faIcon: "dollar",
|
||||
decimals: 2,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -85,6 +110,13 @@ export function iconForUnitCode(unitCode: string) {
|
||||
return UNIT_CODES[unitCode]?.faIcon || "question";
|
||||
}
|
||||
|
||||
export function formattedAmount(amount: number, unitCode: string) {
|
||||
const unit = UNIT_CODES[unitCode];
|
||||
const amountStr = amount.toFixed(unit?.decimals ?? 4);
|
||||
const unitName = unit?.name || "?";
|
||||
return amountStr + " " + unitName;
|
||||
}
|
||||
|
||||
// from https://stackoverflow.com/a/175787/845494
|
||||
// ... though it appears even this isn't precisely right so keep doing "|| 0" or something in sensitive places
|
||||
//
|
||||
@@ -364,16 +396,19 @@ export function base64ToBlob(base64DataUrl: string, sliceSize = 512) {
|
||||
* @param veriClaim is expected to have fields: claim and issuer
|
||||
*/
|
||||
export function offerGiverDid(
|
||||
veriClaim: GenericCredWrapper<OfferVerifiableCredential>,
|
||||
veriClaim: GenericCredWrapper<OfferClaim>,
|
||||
): string | undefined {
|
||||
let giver;
|
||||
if (
|
||||
veriClaim.claim.offeredBy?.identifier &&
|
||||
!serverUtil.isHiddenDid(veriClaim.claim.offeredBy.identifier as string)
|
||||
) {
|
||||
giver = veriClaim.claim.offeredBy.identifier;
|
||||
} else if (veriClaim.issuer && !serverUtil.isHiddenDid(veriClaim.issuer)) {
|
||||
giver = veriClaim.issuer;
|
||||
const innerClaim = veriClaim.claim as OfferClaim;
|
||||
let giver: string | undefined = undefined;
|
||||
|
||||
giver = innerClaim.offeredBy?.identifier;
|
||||
if (giver && !serverUtil.isHiddenDid(giver)) {
|
||||
return giver;
|
||||
}
|
||||
|
||||
giver = veriClaim.issuer;
|
||||
if (giver && !serverUtil.isHiddenDid(giver)) {
|
||||
return giver;
|
||||
}
|
||||
return giver;
|
||||
}
|
||||
@@ -384,10 +419,12 @@ export function offerGiverDid(
|
||||
*/
|
||||
export const canFulfillOffer = (
|
||||
veriClaim: GenericCredWrapper<GenericVerifiableCredential>,
|
||||
isRegistered: boolean,
|
||||
) => {
|
||||
return (
|
||||
isRegistered &&
|
||||
veriClaim.claimType === "Offer" &&
|
||||
!!offerGiverDid(veriClaim as GenericCredWrapper<OfferVerifiableCredential>)
|
||||
!!offerGiverDid(veriClaim as GenericCredWrapper<OfferClaim>)
|
||||
);
|
||||
};
|
||||
|
||||
@@ -457,74 +494,236 @@ export function findAllVisibleToDids(
|
||||
*
|
||||
**/
|
||||
|
||||
export interface AccountKeyInfo extends Account, KeyMeta {}
|
||||
export type AccountKeyInfo = Account & KeyMetaWithPrivate;
|
||||
|
||||
export const retrieveAccountCount = async (): Promise<number> => {
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
return await accountsDB.accounts.count();
|
||||
let result = 0;
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const dbResult = await platformService.dbQuery(
|
||||
`SELECT COUNT(*) FROM accounts`,
|
||||
);
|
||||
if (dbResult?.values?.[0]?.[0]) {
|
||||
result = dbResult.values[0][0] as number;
|
||||
}
|
||||
|
||||
if (USE_DEXIE_DB) {
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
result = await accountsDB.accounts.count();
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
export const retrieveAccountDids = async (): Promise<string[]> => {
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
const allAccounts = await accountsDB.accounts.toArray();
|
||||
const allDids = allAccounts.map((acc) => acc.did);
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const dbAccounts = await platformService.dbQuery(`SELECT did FROM accounts`);
|
||||
let allDids =
|
||||
databaseUtil
|
||||
.mapQueryResultToValues(dbAccounts)
|
||||
?.map((row) => row[0] as string) || [];
|
||||
if (USE_DEXIE_DB) {
|
||||
// this is the old way
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
const allAccounts = await accountsDB.accounts.toArray();
|
||||
allDids = allAccounts.map((acc) => acc.did);
|
||||
}
|
||||
return allDids;
|
||||
};
|
||||
|
||||
// This is provided and recommended when the full key is not necessary so that
|
||||
// future work could separate this info from the sensitive key material.
|
||||
/**
|
||||
* This is provided and recommended when the full key is not necessary so that
|
||||
* future work could separate this info from the sensitive key material.
|
||||
*
|
||||
* If you need the private key data, use retrieveFullyDecryptedAccount instead.
|
||||
*/
|
||||
export const retrieveAccountMetadata = async (
|
||||
activeDid: string,
|
||||
): Promise<AccountKeyInfo | undefined> => {
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
const account = (await accountsDB.accounts
|
||||
.where("did")
|
||||
.equals(activeDid)
|
||||
.first()) as Account;
|
||||
): Promise<Account | undefined> => {
|
||||
let result: Account | undefined = undefined;
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const dbAccount = await platformService.dbQuery(
|
||||
`SELECT * FROM accounts WHERE did = ?`,
|
||||
[activeDid],
|
||||
);
|
||||
const account = databaseUtil.mapQueryResultToValues(dbAccount)[0] as Account;
|
||||
if (account) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { identity, mnemonic, ...metadata } = account;
|
||||
return metadata;
|
||||
result = metadata;
|
||||
} else {
|
||||
return undefined;
|
||||
result = undefined;
|
||||
}
|
||||
if (USE_DEXIE_DB) {
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
const account = (await accountsDB.accounts
|
||||
.where("did")
|
||||
.equals(activeDid)
|
||||
.first()) as Account;
|
||||
if (account) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { identity, mnemonic, ...metadata } = account;
|
||||
result = metadata;
|
||||
} else {
|
||||
result = undefined;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
export const retrieveAllAccountsMetadata = async (): Promise<Account[]> => {
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
const array = await accountsDB.accounts.toArray();
|
||||
return array.map((account) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { identity, mnemonic, ...metadata } = account;
|
||||
return metadata;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* This contains sensitive data. If possible, use retrieveAccountMetadata instead.
|
||||
*
|
||||
* @param activeDid
|
||||
* @returns account info with private key data decrypted
|
||||
*/
|
||||
export const retrieveFullyDecryptedAccount = async (
|
||||
activeDid: string,
|
||||
): Promise<AccountKeyInfo | undefined> => {
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
const account = (await accountsDB.accounts
|
||||
.where("did")
|
||||
.equals(activeDid)
|
||||
.first()) as Account;
|
||||
return account;
|
||||
): Promise<Account | undefined> => {
|
||||
let result: Account | undefined = undefined;
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const dbSecrets = await platformService.dbQuery(
|
||||
`SELECT secretBase64 from secret`,
|
||||
);
|
||||
if (
|
||||
!dbSecrets ||
|
||||
dbSecrets.values.length === 0 ||
|
||||
dbSecrets.values[0].length === 0
|
||||
) {
|
||||
throw new Error(
|
||||
"No secret found. We recommend you clear your data and start over.",
|
||||
);
|
||||
}
|
||||
const secretBase64 = dbSecrets.values[0][0] as string;
|
||||
const secret = base64ToArrayBuffer(secretBase64);
|
||||
const dbAccount = await platformService.dbQuery(
|
||||
`SELECT * FROM accounts WHERE did = ?`,
|
||||
[activeDid],
|
||||
);
|
||||
if (
|
||||
!dbAccount ||
|
||||
dbAccount.values.length === 0 ||
|
||||
dbAccount.values[0].length === 0
|
||||
) {
|
||||
throw new Error("Account not found.");
|
||||
}
|
||||
const fullAccountData = databaseUtil.mapQueryResultToValues(
|
||||
dbAccount,
|
||||
)[0] as AccountEncrypted;
|
||||
const identityEncr = base64ToArrayBuffer(fullAccountData.identityEncrBase64);
|
||||
const mnemonicEncr = base64ToArrayBuffer(fullAccountData.mnemonicEncrBase64);
|
||||
fullAccountData.identity = await simpleDecrypt(identityEncr, secret);
|
||||
fullAccountData.mnemonic = await simpleDecrypt(mnemonicEncr, secret);
|
||||
result = fullAccountData;
|
||||
|
||||
if (USE_DEXIE_DB) {
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
const account = (await accountsDB.accounts
|
||||
.where("did")
|
||||
.equals(activeDid)
|
||||
.first()) as Account;
|
||||
result = account;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// let's try and eliminate this
|
||||
export const retrieveAllFullyDecryptedAccounts = async (): Promise<
|
||||
Array<AccountKeyInfo>
|
||||
export const retrieveAllAccountsMetadata = async (): Promise<
|
||||
AccountEncrypted[]
|
||||
> => {
|
||||
const accountsDB = await accountsDBPromise;
|
||||
const allAccounts = await accountsDB.accounts.toArray();
|
||||
return allAccounts;
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const dbAccounts = await platformService.dbQuery(`SELECT * FROM accounts`);
|
||||
const accounts = databaseUtil.mapQueryResultToValues(dbAccounts) as Account[];
|
||||
let result = accounts.map((account) => {
|
||||
return account as AccountEncrypted;
|
||||
});
|
||||
if (USE_DEXIE_DB) {
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
const array = await accountsDB.accounts.toArray();
|
||||
result = array.map((account) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { identity, mnemonic, ...metadata } = account;
|
||||
// This is not accurate because they can't be decrypted, but we're removing Dexie anyway.
|
||||
const identityStr = JSON.stringify(identity);
|
||||
const encryptedAccount = {
|
||||
identityEncrBase64: sha256(
|
||||
new TextEncoder().encode(identityStr),
|
||||
).toString(),
|
||||
mnemonicEncrBase64: sha256(
|
||||
new TextEncoder().encode(account.mnemonic),
|
||||
).toString(),
|
||||
...metadata,
|
||||
};
|
||||
return encryptedAccount as AccountEncrypted;
|
||||
});
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves a new identity to both SQL and Dexie databases
|
||||
*/
|
||||
export async function saveNewIdentity(
|
||||
identity: IIdentifier,
|
||||
mnemonic: string,
|
||||
derivationPath: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
// add to the new sql db
|
||||
const platformService = PlatformServiceFactory.getInstance();
|
||||
const secrets = await platformService.dbQuery(
|
||||
`SELECT secretBase64 FROM secret`,
|
||||
);
|
||||
if (!secrets?.values?.length || !secrets.values[0]?.length) {
|
||||
throw new Error(
|
||||
"No initial encryption supported. We recommend you clear your data and start over.",
|
||||
);
|
||||
}
|
||||
const secretBase64 = secrets.values[0][0] as string;
|
||||
const secret = base64ToArrayBuffer(secretBase64);
|
||||
const identityStr = JSON.stringify(identity);
|
||||
const encryptedIdentity = await simpleEncrypt(identityStr, secret);
|
||||
const encryptedMnemonic = await simpleEncrypt(mnemonic, secret);
|
||||
const encryptedIdentityBase64 = arrayBufferToBase64(encryptedIdentity);
|
||||
const encryptedMnemonicBase64 = arrayBufferToBase64(encryptedMnemonic);
|
||||
const sql = `INSERT INTO accounts (dateCreated, derivationPath, did, identityEncrBase64, mnemonicEncrBase64, publicKeyHex)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`;
|
||||
const params = [
|
||||
new Date().toISOString(),
|
||||
derivationPath,
|
||||
identity.did,
|
||||
encryptedIdentityBase64,
|
||||
encryptedMnemonicBase64,
|
||||
identity.keys[0].publicKeyHex,
|
||||
];
|
||||
await platformService.dbExec(sql, params);
|
||||
await databaseUtil.updateDefaultSettings({ activeDid: identity.did });
|
||||
await databaseUtil.insertDidSpecificSettings(identity.did);
|
||||
|
||||
if (USE_DEXIE_DB) {
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
await accountsDB.accounts.add({
|
||||
dateCreated: new Date().toISOString(),
|
||||
derivationPath: derivationPath,
|
||||
did: identity.did,
|
||||
identity: identityStr,
|
||||
mnemonic: mnemonic,
|
||||
publicKeyHex: identity.keys[0].publicKeyHex,
|
||||
});
|
||||
await updateDefaultSettings({ activeDid: identity.did });
|
||||
await insertDidSpecificSettings(identity.did);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("Failed to update default settings:", error);
|
||||
throw new Error(
|
||||
"Failed to set default settings. Please try again or restart the app.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a new identity, saves it to the database, and sets it as the active identity.
|
||||
* @return {Promise<string>} with the DID of the new identity
|
||||
@@ -536,28 +735,14 @@ export const generateSaveAndActivateIdentity = async (): Promise<string> => {
|
||||
deriveAddress(mnemonic);
|
||||
|
||||
const newId = newIdentifier(address, publicHex, privateHex, derivationPath);
|
||||
const identity = JSON.stringify(newId);
|
||||
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
try {
|
||||
const accountsDB = await accountsDBPromise;
|
||||
await accountsDB.accounts.add({
|
||||
dateCreated: new Date().toISOString(),
|
||||
derivationPath: derivationPath,
|
||||
did: newId.did,
|
||||
identity: identity,
|
||||
mnemonic: mnemonic,
|
||||
publicKeyHex: newId.keys[0].publicKeyHex,
|
||||
});
|
||||
|
||||
await updateDefaultSettings({ activeDid: newId.did });
|
||||
} catch (error) {
|
||||
console.error("Failed to update default settings:", error);
|
||||
throw new Error(
|
||||
"Failed to set default settings. Please try again or restart the app.",
|
||||
);
|
||||
await saveNewIdentity(newId, mnemonic, derivationPath);
|
||||
await databaseUtil.updateDidSpecificSettings(newId.did, {
|
||||
isRegistered: false,
|
||||
});
|
||||
if (USE_DEXIE_DB) {
|
||||
await updateAccountSettings(newId.did, { isRegistered: false });
|
||||
}
|
||||
await updateAccountSettings(newId.did, { isRegistered: false });
|
||||
return newId.did;
|
||||
};
|
||||
|
||||
@@ -575,9 +760,19 @@ export const registerAndSavePasskey = async (
|
||||
passkeyCredIdHex,
|
||||
publicKeyHex: Buffer.from(publicKeyBytes).toString("hex"),
|
||||
};
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
await accountsDB.accounts.add(account);
|
||||
const insertStatement = databaseUtil.generateInsertStatement(
|
||||
account,
|
||||
"accounts",
|
||||
);
|
||||
await PlatformServiceFactory.getInstance().dbExec(
|
||||
insertStatement.sql,
|
||||
insertStatement.params,
|
||||
);
|
||||
if (USE_DEXIE_DB) {
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
await accountsDB.accounts.add(account);
|
||||
}
|
||||
return account;
|
||||
};
|
||||
|
||||
@@ -585,13 +780,22 @@ export const registerSaveAndActivatePasskey = async (
|
||||
keyName: string,
|
||||
): Promise<Account> => {
|
||||
const account = await registerAndSavePasskey(keyName);
|
||||
await updateDefaultSettings({ activeDid: account.did });
|
||||
await updateAccountSettings(account.did, { isRegistered: false });
|
||||
await databaseUtil.updateDefaultSettings({ activeDid: account.did });
|
||||
await databaseUtil.updateDidSpecificSettings(account.did, {
|
||||
isRegistered: false,
|
||||
});
|
||||
if (USE_DEXIE_DB) {
|
||||
await updateDefaultSettings({ activeDid: account.did });
|
||||
await updateAccountSettings(account.did, { isRegistered: false });
|
||||
}
|
||||
return account;
|
||||
};
|
||||
|
||||
export const getPasskeyExpirationSeconds = async (): Promise<number> => {
|
||||
const settings = await retrieveSettingsForActiveAccount();
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
return (
|
||||
(settings?.passkeyExpirationMinutes ?? DEFAULT_PASSKEY_EXPIRATION_MINUTES) *
|
||||
60
|
||||
@@ -607,7 +811,10 @@ export const sendTestThroughPushServer = async (
|
||||
subscriptionJSON: PushSubscriptionJSON,
|
||||
skipFilter: boolean,
|
||||
): Promise<AxiosResponse> => {
|
||||
const settings = await retrieveSettingsForActiveAccount();
|
||||
let settings = await databaseUtil.retrieveSettingsForActiveAccount();
|
||||
if (USE_DEXIE_DB) {
|
||||
settings = await retrieveSettingsForActiveAccount();
|
||||
}
|
||||
let pushUrl: string = DEFAULT_PUSH_SERVER as string;
|
||||
if (settings?.webPushServer) {
|
||||
pushUrl = settings.webPushServer;
|
||||
@@ -635,3 +842,96 @@ export const sendTestThroughPushServer = async (
|
||||
logger.log("Got response from web push server:", response);
|
||||
return response;
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts a Contact object to a CSV line string following the established format.
|
||||
* The format matches CONTACT_CSV_HEADER: "name,did,pubKeyBase64,seesMe,registered,contactMethods"
|
||||
* where contactMethods is stored as a stringified JSON array.
|
||||
*
|
||||
* @param contact - The Contact object to convert
|
||||
* @returns A CSV-formatted string representing the contact
|
||||
* @throws {Error} If the contact object is missing required fields
|
||||
*/
|
||||
export const contactToCsvLine = (contact: Contact): string => {
|
||||
if (!contact.did) {
|
||||
throw new Error("Contact must have a did field");
|
||||
}
|
||||
|
||||
// Escape fields that might contain commas or quotes
|
||||
const escapeField = (field: string | boolean | undefined): string => {
|
||||
if (field === undefined) return "";
|
||||
const str = String(field);
|
||||
if (str.includes(",") || str.includes('"')) {
|
||||
return `"${str.replace(/"/g, '""')}"`;
|
||||
}
|
||||
return str;
|
||||
};
|
||||
|
||||
// Handle contactMethods array by stringifying it
|
||||
const contactMethodsStr = contact.contactMethods
|
||||
? escapeField(JSON.stringify(parseJsonField(contact.contactMethods, [])))
|
||||
: "";
|
||||
|
||||
const fields = [
|
||||
escapeField(contact.name),
|
||||
escapeField(contact.did),
|
||||
escapeField(contact.publicKeyBase64),
|
||||
escapeField(contact.seesMe),
|
||||
escapeField(contact.registered),
|
||||
contactMethodsStr,
|
||||
];
|
||||
|
||||
return fields.join(",");
|
||||
};
|
||||
|
||||
/**
|
||||
* Interface for the JSON export format of database tables
|
||||
*/
|
||||
export interface TableExportData {
|
||||
tableName: string;
|
||||
rows: Array<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface for the complete database export format
|
||||
*/
|
||||
export interface DatabaseExport {
|
||||
data: {
|
||||
data: Array<TableExportData>;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an array of contacts to the standardized database export JSON format.
|
||||
* This format is used for data migration and backup purposes.
|
||||
*
|
||||
* @param contacts - Array of Contact objects to convert
|
||||
* @returns DatabaseExport object in the standardized format
|
||||
*/
|
||||
export const contactsToExportJson = (contacts: Contact[]): DatabaseExport => {
|
||||
// Convert each contact to a plain object and ensure all fields are included
|
||||
const rows = contacts.map((contact) => ({
|
||||
did: contact.did,
|
||||
name: contact.name || null,
|
||||
contactMethods: contact.contactMethods
|
||||
? JSON.stringify(parseJsonField(contact.contactMethods, []))
|
||||
: null,
|
||||
nextPubKeyHashB64: contact.nextPubKeyHashB64 || null,
|
||||
notes: contact.notes || null,
|
||||
profileImageUrl: contact.profileImageUrl || null,
|
||||
publicKeyBase64: contact.publicKeyBase64 || null,
|
||||
seesMe: contact.seesMe || false,
|
||||
registered: contact.registered || false,
|
||||
}));
|
||||
|
||||
return {
|
||||
data: {
|
||||
data: [
|
||||
{
|
||||
tableName: "contacts",
|
||||
rows,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -34,7 +34,7 @@ import router from "./router";
|
||||
import { handleApiError } from "./services/api";
|
||||
import { AxiosError } from "axios";
|
||||
import { DeepLinkHandler } from "./services/deepLinks";
|
||||
import { logConsoleAndDb } from "./db";
|
||||
import { logConsoleAndDb } from "./db/databaseUtil";
|
||||
import { logger } from "./utils/logger";
|
||||
|
||||
logger.log("[Capacitor] Starting initialization");
|
||||
|
||||
@@ -10,6 +10,12 @@ import { FontAwesomeIcon } from "./libs/fontawesome";
|
||||
import Camera from "simple-vue-camera";
|
||||
import { logger } from "./utils/logger";
|
||||
|
||||
const platform = process.env.VITE_PLATFORM;
|
||||
const pwa_enabled = process.env.VITE_PWA_ENABLED === "true";
|
||||
|
||||
logger.log("Platform", JSON.stringify({ platform }));
|
||||
logger.log("PWA enabled", JSON.stringify({ pwa_enabled }));
|
||||
|
||||
// Global Error Handler
|
||||
function setupGlobalErrorHandler(app: VueApp) {
|
||||
logger.log("[App Init] Setting up global error handler");
|
||||
|
||||
@@ -1,4 +1,16 @@
|
||||
import { initializeApp } from "./main.common";
|
||||
import { logger } from "./utils/logger";
|
||||
|
||||
const platform = process.env.VITE_PLATFORM;
|
||||
const pwa_enabled = process.env.VITE_PWA_ENABLED === "true";
|
||||
|
||||
logger.info("[Electron] Initializing app");
|
||||
logger.info("[Electron] Platform:", { platform });
|
||||
logger.info("[Electron] PWA enabled:", { pwa_enabled });
|
||||
|
||||
if (pwa_enabled) {
|
||||
logger.warn("[Electron] PWA is enabled, but not supported in electron");
|
||||
}
|
||||
|
||||
const app = initializeApp();
|
||||
app.mount("#app");
|
||||
|
||||
215
src/main.ts
215
src/main.ts
@@ -1,215 +0,0 @@
|
||||
import { createPinia } from "pinia";
|
||||
import { App as VueApp, ComponentPublicInstance, createApp } from "vue";
|
||||
import App from "./App.vue";
|
||||
import "./registerServiceWorker";
|
||||
import router from "./router";
|
||||
import axios from "axios";
|
||||
import VueAxios from "vue-axios";
|
||||
import Notifications from "notiwind";
|
||||
import "./assets/styles/tailwind.css";
|
||||
|
||||
import { library } from "@fortawesome/fontawesome-svg-core";
|
||||
import {
|
||||
faArrowDown,
|
||||
faArrowLeft,
|
||||
faArrowRight,
|
||||
faArrowRotateBackward,
|
||||
faArrowUpRightFromSquare,
|
||||
faArrowUp,
|
||||
faBan,
|
||||
faBitcoinSign,
|
||||
faBurst,
|
||||
faCalendar,
|
||||
faCamera,
|
||||
faCameraRotate,
|
||||
faCaretDown,
|
||||
faChair,
|
||||
faCheck,
|
||||
faChevronDown,
|
||||
faChevronLeft,
|
||||
faChevronRight,
|
||||
faChevronUp,
|
||||
faCircle,
|
||||
faCircleCheck,
|
||||
faCircleInfo,
|
||||
faCircleQuestion,
|
||||
faCircleUser,
|
||||
faClock,
|
||||
faCoins,
|
||||
faComment,
|
||||
faCopy,
|
||||
faDollar,
|
||||
faEllipsis,
|
||||
faEllipsisVertical,
|
||||
faEnvelopeOpenText,
|
||||
faEraser,
|
||||
faEye,
|
||||
faEyeSlash,
|
||||
faFileContract,
|
||||
faFileLines,
|
||||
faFilter,
|
||||
faFloppyDisk,
|
||||
faFolderOpen,
|
||||
faForward,
|
||||
faGift,
|
||||
faGlobe,
|
||||
faHammer,
|
||||
faHand,
|
||||
faHandHoldingDollar,
|
||||
faHandHoldingHeart,
|
||||
faHouseChimney,
|
||||
faImage,
|
||||
faImagePortrait,
|
||||
faLeftRight,
|
||||
faLightbulb,
|
||||
faLink,
|
||||
faLocationDot,
|
||||
faLongArrowAltLeft,
|
||||
faLongArrowAltRight,
|
||||
faMagnifyingGlass,
|
||||
faMessage,
|
||||
faMinus,
|
||||
faPen,
|
||||
faPersonCircleCheck,
|
||||
faPersonCircleQuestion,
|
||||
faPlus,
|
||||
faQuestion,
|
||||
faQrcode,
|
||||
faRightFromBracket,
|
||||
faRotate,
|
||||
faShareNodes,
|
||||
faSpinner,
|
||||
faSquare,
|
||||
faSquareCaretDown,
|
||||
faSquareCaretUp,
|
||||
faSquarePlus,
|
||||
faTrashCan,
|
||||
faTriangleExclamation,
|
||||
faUser,
|
||||
faUsers,
|
||||
faXmark,
|
||||
} from "@fortawesome/free-solid-svg-icons";
|
||||
|
||||
library.add(
|
||||
faArrowDown,
|
||||
faArrowLeft,
|
||||
faArrowRight,
|
||||
faArrowRotateBackward,
|
||||
faArrowUpRightFromSquare,
|
||||
faArrowUp,
|
||||
faBan,
|
||||
faBitcoinSign,
|
||||
faBurst,
|
||||
faCalendar,
|
||||
faCamera,
|
||||
faCameraRotate,
|
||||
faCaretDown,
|
||||
faChair,
|
||||
faCheck,
|
||||
faChevronDown,
|
||||
faChevronLeft,
|
||||
faChevronRight,
|
||||
faChevronUp,
|
||||
faCircle,
|
||||
faCircleCheck,
|
||||
faCircleInfo,
|
||||
faCircleQuestion,
|
||||
faCircleUser,
|
||||
faClock,
|
||||
faCoins,
|
||||
faComment,
|
||||
faCopy,
|
||||
faDollar,
|
||||
faEllipsis,
|
||||
faEllipsisVertical,
|
||||
faEnvelopeOpenText,
|
||||
faEraser,
|
||||
faEye,
|
||||
faEyeSlash,
|
||||
faFileContract,
|
||||
faFileLines,
|
||||
faFilter,
|
||||
faFloppyDisk,
|
||||
faFolderOpen,
|
||||
faForward,
|
||||
faGift,
|
||||
faGlobe,
|
||||
faHammer,
|
||||
faHand,
|
||||
faHandHoldingDollar,
|
||||
faHandHoldingHeart,
|
||||
faHouseChimney,
|
||||
faImage,
|
||||
faImagePortrait,
|
||||
faLeftRight,
|
||||
faLightbulb,
|
||||
faLink,
|
||||
faLocationDot,
|
||||
faLongArrowAltLeft,
|
||||
faLongArrowAltRight,
|
||||
faMagnifyingGlass,
|
||||
faMessage,
|
||||
faMinus,
|
||||
faPen,
|
||||
faPersonCircleCheck,
|
||||
faPersonCircleQuestion,
|
||||
faPlus,
|
||||
faQrcode,
|
||||
faQuestion,
|
||||
faRotate,
|
||||
faRightFromBracket,
|
||||
faShareNodes,
|
||||
faSpinner,
|
||||
faSquare,
|
||||
faSquareCaretDown,
|
||||
faSquareCaretUp,
|
||||
faSquarePlus,
|
||||
faTrashCan,
|
||||
faTriangleExclamation,
|
||||
faUser,
|
||||
faUsers,
|
||||
faXmark,
|
||||
);
|
||||
|
||||
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
|
||||
import Camera from "simple-vue-camera";
|
||||
import { logger } from "./utils/logger";
|
||||
|
||||
// Can trigger this with a 'throw' inside some top-level function, eg. on the HomeView
|
||||
function setupGlobalErrorHandler(app: VueApp) {
|
||||
// @ts-expect-error 'cause we cannot see why config is not defined
|
||||
app.config.errorHandler = (
|
||||
err: Error,
|
||||
instance: ComponentPublicInstance | null,
|
||||
info: string,
|
||||
) => {
|
||||
logger.error(
|
||||
"Ouch! Global Error Handler.",
|
||||
"Error:",
|
||||
err,
|
||||
"- Error toString:",
|
||||
err.toString(),
|
||||
"- Info:",
|
||||
info,
|
||||
"- Instance:",
|
||||
instance,
|
||||
);
|
||||
// Want to show a nice notiwind notification but can't figure out how.
|
||||
alert(
|
||||
(err.message || "Something bad happened") +
|
||||
" - Try reloading or restarting the app.",
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
const app = createApp(App)
|
||||
.component("fa", FontAwesomeIcon)
|
||||
.component("camera", Camera)
|
||||
.use(createPinia())
|
||||
.use(VueAxios, axios)
|
||||
.use(router)
|
||||
.use(Notifications);
|
||||
|
||||
setupGlobalErrorHandler(app);
|
||||
|
||||
app.mount("#app");
|
||||
@@ -1,5 +1,37 @@
|
||||
import { initBackend } from "absurd-sql/dist/indexeddb-main-thread";
|
||||
import { initializeApp } from "./main.common";
|
||||
import "./registerServiceWorker"; // Web PWA support
|
||||
import { logger } from "./utils/logger";
|
||||
|
||||
const platform = process.env.VITE_PLATFORM;
|
||||
const pwa_enabled = process.env.VITE_PWA_ENABLED === "true";
|
||||
|
||||
logger.info("[Web] PWA enabled", { pwa_enabled });
|
||||
logger.info("[Web] Platform", { platform });
|
||||
|
||||
// Only import service worker for web builds
|
||||
if (platform !== "electron" && pwa_enabled) {
|
||||
import("./registerServiceWorker"); // Web PWA support
|
||||
}
|
||||
|
||||
const app = initializeApp();
|
||||
|
||||
function sqlInit() {
|
||||
// see https://github.com/jlongster/absurd-sql
|
||||
const worker = new Worker(
|
||||
new URL("./registerSQLWorker.js", import.meta.url),
|
||||
{
|
||||
type: "module",
|
||||
},
|
||||
);
|
||||
// This is only required because Safari doesn't support nested
|
||||
// workers. This installs a handler that will proxy creating web
|
||||
// workers through the main thread
|
||||
initBackend(worker);
|
||||
}
|
||||
if (platform === "web" || platform === "development") {
|
||||
sqlInit();
|
||||
} else {
|
||||
logger.info("[Web] SQL not initialized for platform", { platform });
|
||||
}
|
||||
|
||||
app.mount("#app");
|
||||
|
||||
6
src/registerSQLWorker.js
Normal file
6
src/registerSQLWorker.js
Normal file
@@ -0,0 +1,6 @@
|
||||
import databaseService from "./services/AbsurdSqlDatabaseService";
|
||||
|
||||
async function run() {
|
||||
await databaseService.initialize();
|
||||
}
|
||||
run();
|
||||
@@ -2,8 +2,18 @@
|
||||
|
||||
import { register } from "register-service-worker";
|
||||
|
||||
// Only register service worker if explicitly enabled and in production
|
||||
// Check if we're in an Electron environment
|
||||
const isElectron =
|
||||
process.env.VITE_PLATFORM === "electron" ||
|
||||
process.env.VITE_DISABLE_PWA === "true" ||
|
||||
window.navigator.userAgent.toLowerCase().includes("electron");
|
||||
|
||||
// Only register service worker if:
|
||||
// 1. Not in Electron
|
||||
// 2. PWA is explicitly enabled
|
||||
// 3. In production mode
|
||||
if (
|
||||
!isElectron &&
|
||||
process.env.VITE_PWA_ENABLED === "true" &&
|
||||
process.env.NODE_ENV === "production"
|
||||
) {
|
||||
@@ -34,6 +44,12 @@ if (
|
||||
});
|
||||
} else {
|
||||
console.log(
|
||||
"Service worker registration skipped - not enabled or not in production",
|
||||
`Service worker registration skipped - ${
|
||||
isElectron
|
||||
? "running in Electron"
|
||||
: process.env.VITE_PWA_ENABLED !== "true"
|
||||
? "PWA not enabled"
|
||||
: "not in production mode"
|
||||
}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,35 +2,11 @@ import {
|
||||
createRouter,
|
||||
createWebHistory,
|
||||
createMemoryHistory,
|
||||
NavigationGuardNext,
|
||||
RouteLocationNormalized,
|
||||
RouteRecordRaw,
|
||||
} from "vue-router";
|
||||
import { accountsDBPromise } from "../db/index";
|
||||
import { logger } from "../utils/logger";
|
||||
|
||||
/**
|
||||
*
|
||||
* @param to :RouteLocationNormalized
|
||||
* @param from :RouteLocationNormalized
|
||||
* @param next :NavigationGuardNext
|
||||
*/
|
||||
const enterOrStart = async (
|
||||
to: RouteLocationNormalized,
|
||||
from: RouteLocationNormalized,
|
||||
next: NavigationGuardNext,
|
||||
) => {
|
||||
// one of the few times we use accountsDBPromise directly; try to avoid more usage
|
||||
const accountsDB = await accountsDBPromise;
|
||||
const num_accounts = await accountsDB.accounts.count();
|
||||
|
||||
if (num_accounts > 0) {
|
||||
next();
|
||||
} else {
|
||||
next({ name: "start" });
|
||||
}
|
||||
};
|
||||
|
||||
const routes: Array<RouteRecordRaw> = [
|
||||
{
|
||||
path: "/account",
|
||||
@@ -216,7 +192,6 @@ const routes: Array<RouteRecordRaw> = [
|
||||
path: "/projects",
|
||||
name: "projects",
|
||||
component: () => import("../views/ProjectsView.vue"),
|
||||
beforeEnter: enterOrStart,
|
||||
},
|
||||
{
|
||||
path: "/quick-action-bvc",
|
||||
|
||||
29
src/services/AbsurdSqlDatabaseService.d.ts
vendored
Normal file
29
src/services/AbsurdSqlDatabaseService.d.ts
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
import { DatabaseService } from "../interfaces/database";
|
||||
|
||||
declare module "@jlongster/sql.js" {
|
||||
interface SQL {
|
||||
Database: unknown;
|
||||
FS: unknown;
|
||||
register_for_idb: (fs: unknown) => void;
|
||||
}
|
||||
|
||||
function initSqlJs(config: {
|
||||
locateFile: (file: string) => string;
|
||||
}): Promise<SQL>;
|
||||
export default initSqlJs;
|
||||
}
|
||||
|
||||
declare module "absurd-sql" {
|
||||
export class SQLiteFS {
|
||||
constructor(fs: unknown, backend: unknown);
|
||||
}
|
||||
}
|
||||
|
||||
declare module "absurd-sql/dist/indexeddb-backend" {
|
||||
export default class IndexedDBBackend {
|
||||
constructor();
|
||||
}
|
||||
}
|
||||
|
||||
declare const databaseService: DatabaseService;
|
||||
export default databaseService;
|
||||
231
src/services/AbsurdSqlDatabaseService.ts
Normal file
231
src/services/AbsurdSqlDatabaseService.ts
Normal file
@@ -0,0 +1,231 @@
|
||||
import initSqlJs from "@jlongster/sql.js";
|
||||
import { SQLiteFS } from "absurd-sql";
|
||||
import IndexedDBBackend from "absurd-sql/dist/indexeddb-backend";
|
||||
|
||||
import { runMigrations } from "../db-sql/migration";
|
||||
import type { DatabaseService, QueryExecResult } from "../interfaces/database";
|
||||
import { logger } from "@/utils/logger";
|
||||
|
||||
interface QueuedOperation {
|
||||
type: "run" | "query";
|
||||
sql: string;
|
||||
params: unknown[];
|
||||
resolve: (value: unknown) => void;
|
||||
reject: (reason: unknown) => void;
|
||||
}
|
||||
|
||||
interface AbsurdSqlDatabase {
|
||||
exec: (sql: string, params?: unknown[]) => Promise<QueryExecResult[]>;
|
||||
run: (
|
||||
sql: string,
|
||||
params?: unknown[],
|
||||
) => Promise<{ changes: number; lastId?: number }>;
|
||||
}
|
||||
|
||||
class AbsurdSqlDatabaseService implements DatabaseService {
|
||||
private static instance: AbsurdSqlDatabaseService | null = null;
|
||||
private db: AbsurdSqlDatabase | null;
|
||||
private initialized: boolean;
|
||||
private initializationPromise: Promise<void> | null = null;
|
||||
private operationQueue: Array<QueuedOperation> = [];
|
||||
private isProcessingQueue: boolean = false;
|
||||
|
||||
private constructor() {
|
||||
this.db = null;
|
||||
this.initialized = false;
|
||||
}
|
||||
|
||||
static getInstance(): AbsurdSqlDatabaseService {
|
||||
if (!AbsurdSqlDatabaseService.instance) {
|
||||
AbsurdSqlDatabaseService.instance = new AbsurdSqlDatabaseService();
|
||||
}
|
||||
return AbsurdSqlDatabaseService.instance;
|
||||
}
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
// If already initialized, return immediately
|
||||
if (this.initialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If initialization is in progress, wait for it
|
||||
if (this.initializationPromise) {
|
||||
return this.initializationPromise;
|
||||
}
|
||||
|
||||
// Start initialization
|
||||
this.initializationPromise = this._initialize();
|
||||
try {
|
||||
await this.initializationPromise;
|
||||
} catch (error) {
|
||||
logger.error(`AbsurdSqlDatabaseService initialize method failed:`, error);
|
||||
this.initializationPromise = null; // Reset on failure
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async _initialize(): Promise<void> {
|
||||
if (this.initialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
const SQL = await initSqlJs({
|
||||
locateFile: (file: string) => {
|
||||
return new URL(
|
||||
`/node_modules/@jlongster/sql.js/dist/${file}`,
|
||||
import.meta.url,
|
||||
).href;
|
||||
},
|
||||
});
|
||||
|
||||
const sqlFS = new SQLiteFS(SQL.FS, new IndexedDBBackend());
|
||||
SQL.register_for_idb(sqlFS);
|
||||
|
||||
SQL.FS.mkdir("/sql");
|
||||
SQL.FS.mount(sqlFS, {}, "/sql");
|
||||
|
||||
const path = "/sql/timesafari.absurd-sql";
|
||||
if (typeof SharedArrayBuffer === "undefined") {
|
||||
const stream = SQL.FS.open(path, "a+");
|
||||
await stream.node.contents.readIfFallback();
|
||||
SQL.FS.close(stream);
|
||||
}
|
||||
|
||||
this.db = new SQL.Database(path, { filename: true });
|
||||
if (!this.db) {
|
||||
throw new Error(
|
||||
"The database initialization failed. We recommend you restart or reinstall.",
|
||||
);
|
||||
}
|
||||
|
||||
// An error is thrown without this pragma: "File has invalid page size. (the first block of a new file must be written first)"
|
||||
await this.db.exec(`PRAGMA journal_mode=MEMORY;`);
|
||||
const sqlExec = this.db.run.bind(this.db);
|
||||
const sqlQuery = this.db.exec.bind(this.db);
|
||||
|
||||
// Extract the migration names for the absurd-sql format
|
||||
const extractMigrationNames: (result: QueryExecResult[]) => Set<string> = (
|
||||
result,
|
||||
) => {
|
||||
// Even with the "select name" query, the QueryExecResult may be [] (which doesn't make sense to me).
|
||||
const names = result?.[0]?.values.map((row) => row[0] as string) || [];
|
||||
return new Set(names);
|
||||
};
|
||||
|
||||
// Run migrations
|
||||
await runMigrations(sqlExec, sqlQuery, extractMigrationNames);
|
||||
|
||||
this.initialized = true;
|
||||
|
||||
// Start processing the queue after initialization
|
||||
this.processQueue();
|
||||
}
|
||||
|
||||
private async processQueue(): Promise<void> {
|
||||
if (this.isProcessingQueue || !this.initialized || !this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isProcessingQueue = true;
|
||||
|
||||
while (this.operationQueue.length > 0) {
|
||||
const operation = this.operationQueue.shift();
|
||||
if (!operation) continue;
|
||||
|
||||
try {
|
||||
let result: unknown;
|
||||
switch (operation.type) {
|
||||
case "run":
|
||||
result = await this.db.run(operation.sql, operation.params);
|
||||
break;
|
||||
case "query":
|
||||
result = await this.db.exec(operation.sql, operation.params);
|
||||
break;
|
||||
}
|
||||
operation.resolve(result);
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
"Error while processing SQL queue:",
|
||||
error,
|
||||
" ... for sql:",
|
||||
operation.sql,
|
||||
" ... with params:",
|
||||
operation.params,
|
||||
);
|
||||
operation.reject(error);
|
||||
}
|
||||
}
|
||||
|
||||
this.isProcessingQueue = false;
|
||||
}
|
||||
|
||||
private async queueOperation<R>(
|
||||
type: QueuedOperation["type"],
|
||||
sql: string,
|
||||
params: unknown[] = [],
|
||||
): Promise<R> {
|
||||
return new Promise<R>((resolve, reject) => {
|
||||
const operation: QueuedOperation = {
|
||||
type,
|
||||
sql,
|
||||
params,
|
||||
resolve: (value: unknown) => resolve(value as R),
|
||||
reject,
|
||||
};
|
||||
this.operationQueue.push(operation);
|
||||
|
||||
// If we're already initialized, start processing the queue
|
||||
if (this.initialized && this.db) {
|
||||
this.processQueue();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async waitForInitialization(): Promise<void> {
|
||||
// If we have an initialization promise, wait for it
|
||||
if (this.initializationPromise) {
|
||||
await this.initializationPromise;
|
||||
return;
|
||||
}
|
||||
|
||||
// If not initialized and no promise, start initialization
|
||||
if (!this.initialized) {
|
||||
await this.initialize();
|
||||
return;
|
||||
}
|
||||
|
||||
// If initialized but no db, something went wrong
|
||||
if (!this.db) {
|
||||
logger.error(
|
||||
`Database not properly initialized after await waitForInitialization() - initialized flag is true but db is null`,
|
||||
);
|
||||
throw new Error(
|
||||
`The database could not be initialized. We recommend you restart or reinstall.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Used for inserts, updates, and deletes
|
||||
async run(
|
||||
sql: string,
|
||||
params: unknown[] = [],
|
||||
): Promise<{ changes: number; lastId?: number }> {
|
||||
await this.waitForInitialization();
|
||||
return this.queueOperation<{ changes: number; lastId?: number }>(
|
||||
"run",
|
||||
sql,
|
||||
params,
|
||||
);
|
||||
}
|
||||
|
||||
// Note that the resulting array may be empty if there are no results from the query
|
||||
async query(sql: string, params: unknown[] = []): Promise<QueryExecResult[]> {
|
||||
await this.waitForInitialization();
|
||||
return this.queueOperation<QueryExecResult[]>("query", sql, params);
|
||||
}
|
||||
}
|
||||
|
||||
// Create a singleton instance
|
||||
const databaseService = AbsurdSqlDatabaseService.getInstance();
|
||||
|
||||
export default databaseService;
|
||||
@@ -1,3 +1,5 @@
|
||||
import { QueryExecResult } from "@/interfaces/database";
|
||||
|
||||
/**
|
||||
* Represents the result of an image capture or selection operation.
|
||||
* Contains both the image data as a Blob and the associated filename.
|
||||
@@ -106,4 +108,26 @@ export interface PlatformService {
|
||||
* @returns Promise that resolves when the deep link has been handled
|
||||
*/
|
||||
handleDeepLink(url: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* Executes a SQL query on the database.
|
||||
* @param sql - The SQL query to execute
|
||||
* @param params - The parameters to pass to the query
|
||||
* @returns Promise resolving to the query result
|
||||
*/
|
||||
dbQuery(
|
||||
sql: string,
|
||||
params?: unknown[],
|
||||
): Promise<QueryExecResult | undefined>;
|
||||
|
||||
/**
|
||||
* Executes a create/update/delete on the database.
|
||||
* @param sql - The SQL statement to execute
|
||||
* @param params - The parameters to pass to the statement
|
||||
* @returns Promise resolving to the result of the statement
|
||||
*/
|
||||
dbExec(
|
||||
sql: string,
|
||||
params?: unknown[],
|
||||
): Promise<{ changes: number; lastId?: number }>;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,13 @@ import {
|
||||
StartScanOptions,
|
||||
LensFacing,
|
||||
} from "@capacitor-mlkit/barcode-scanning";
|
||||
import { QRScannerService, ScanListener, QRScannerOptions } from "./types";
|
||||
import {
|
||||
QRScannerService,
|
||||
ScanListener,
|
||||
QRScannerOptions,
|
||||
CameraStateListener,
|
||||
CameraState,
|
||||
} from "./types";
|
||||
import { logger } from "@/utils/logger";
|
||||
|
||||
export class CapacitorQRScanner implements QRScannerService {
|
||||
@@ -12,6 +18,9 @@ export class CapacitorQRScanner implements QRScannerService {
|
||||
private isScanning = false;
|
||||
private listenerHandles: Array<() => Promise<void>> = [];
|
||||
private cleanupPromise: Promise<void> | null = null;
|
||||
private cameraStateListeners: Set<CameraStateListener> = new Set();
|
||||
private currentState: CameraState = "off";
|
||||
private currentStateMessage?: string;
|
||||
|
||||
async checkPermissions(): Promise<boolean> {
|
||||
try {
|
||||
@@ -79,8 +88,11 @@ export class CapacitorQRScanner implements QRScannerService {
|
||||
}
|
||||
|
||||
try {
|
||||
this.updateCameraState("initializing", "Starting camera...");
|
||||
|
||||
// Ensure we have permissions before starting
|
||||
if (!(await this.checkPermissions())) {
|
||||
this.updateCameraState("permission_denied", "Camera permission denied");
|
||||
logger.debug("Requesting camera permissions");
|
||||
const granted = await this.requestPermissions();
|
||||
if (!granted) {
|
||||
@@ -90,11 +102,16 @@ export class CapacitorQRScanner implements QRScannerService {
|
||||
|
||||
// Check if scanning is supported
|
||||
if (!(await this.isSupported())) {
|
||||
this.updateCameraState(
|
||||
"error",
|
||||
"QR scanning not supported on this device",
|
||||
);
|
||||
throw new Error("QR scanning not supported on this device");
|
||||
}
|
||||
|
||||
logger.info("Starting MLKit scanner");
|
||||
this.isScanning = true;
|
||||
this.updateCameraState("active", "Camera is active");
|
||||
|
||||
const scanOptions: StartScanOptions = {
|
||||
formats: [BarcodeFormat.QrCode],
|
||||
@@ -126,6 +143,7 @@ export class CapacitorQRScanner implements QRScannerService {
|
||||
stack: wrappedError.stack,
|
||||
});
|
||||
this.isScanning = false;
|
||||
this.updateCameraState("error", wrappedError.message);
|
||||
await this.cleanup();
|
||||
this.scanListener?.onError?.(wrappedError);
|
||||
throw wrappedError;
|
||||
@@ -140,6 +158,7 @@ export class CapacitorQRScanner implements QRScannerService {
|
||||
|
||||
try {
|
||||
logger.debug("Stopping QR scanner");
|
||||
this.updateCameraState("off", "Camera stopped");
|
||||
await BarcodeScanner.stopScan();
|
||||
logger.info("QR scanner stopped successfully");
|
||||
} catch (error) {
|
||||
@@ -149,6 +168,7 @@ export class CapacitorQRScanner implements QRScannerService {
|
||||
error: wrappedError.message,
|
||||
stack: wrappedError.stack,
|
||||
});
|
||||
this.updateCameraState("error", wrappedError.message);
|
||||
this.scanListener?.onError?.(wrappedError);
|
||||
throw wrappedError;
|
||||
} finally {
|
||||
@@ -207,4 +227,23 @@ export class CapacitorQRScanner implements QRScannerService {
|
||||
// No-op for native scanner
|
||||
callback(null);
|
||||
}
|
||||
|
||||
addCameraStateListener(listener: CameraStateListener): void {
|
||||
this.cameraStateListeners.add(listener);
|
||||
// Immediately notify the new listener of current state
|
||||
listener.onStateChange(this.currentState, this.currentStateMessage);
|
||||
}
|
||||
|
||||
removeCameraStateListener(listener: CameraStateListener): void {
|
||||
this.cameraStateListeners.delete(listener);
|
||||
}
|
||||
|
||||
private updateCameraState(state: CameraState, message?: string): void {
|
||||
this.currentState = state;
|
||||
this.currentStateMessage = message;
|
||||
// Notify all listeners of state change
|
||||
for (const listener of this.cameraStateListeners) {
|
||||
listener.onStateChange(state, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,14 +30,16 @@ export class WebInlineQRScanner implements QRScannerService {
|
||||
private cameraStateListeners: Set<CameraStateListener> = new Set();
|
||||
private currentState: CameraState = "off";
|
||||
private currentStateMessage?: string;
|
||||
private options: QRScannerOptions;
|
||||
|
||||
constructor(private options?: QRScannerOptions) {
|
||||
constructor(options?: QRScannerOptions) {
|
||||
// Generate a short random ID for this scanner instance
|
||||
this.id = Math.random().toString(36).substring(2, 8).toUpperCase();
|
||||
this.options = options ?? {};
|
||||
logger.error(
|
||||
`[WebInlineQRScanner:${this.id}] Initializing scanner with options:`,
|
||||
{
|
||||
...options,
|
||||
...this.options,
|
||||
buildId: BUILD_ID,
|
||||
targetFps: this.TARGET_FPS,
|
||||
},
|
||||
@@ -494,26 +496,34 @@ export class WebInlineQRScanner implements QRScannerService {
|
||||
}
|
||||
}
|
||||
|
||||
async startScan(): Promise<void> {
|
||||
async startScan(options?: QRScannerOptions): Promise<void> {
|
||||
if (this.isScanning) {
|
||||
logger.error(`[WebInlineQRScanner:${this.id}] Scanner already running`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Update options if provided
|
||||
if (options) {
|
||||
this.options = { ...this.options, ...options };
|
||||
}
|
||||
|
||||
try {
|
||||
this.isScanning = true;
|
||||
this.scanAttempts = 0;
|
||||
this.lastScanTime = Date.now();
|
||||
this.updateCameraState("initializing", "Starting camera...");
|
||||
logger.error(`[WebInlineQRScanner:${this.id}] Starting scan`);
|
||||
logger.error(
|
||||
`[WebInlineQRScanner:${this.id}] Starting scan with options:`,
|
||||
this.options,
|
||||
);
|
||||
|
||||
// Get camera stream
|
||||
// Get camera stream with options
|
||||
logger.error(
|
||||
`[WebInlineQRScanner:${this.id}] Requesting camera stream...`,
|
||||
);
|
||||
this.stream = await navigator.mediaDevices.getUserMedia({
|
||||
video: {
|
||||
facingMode: "environment",
|
||||
facingMode: this.options.camera === "front" ? "user" : "environment",
|
||||
width: { ideal: 1280 },
|
||||
height: { ideal: 720 },
|
||||
},
|
||||
@@ -527,11 +537,18 @@ export class WebInlineQRScanner implements QRScannerService {
|
||||
label: t.label,
|
||||
readyState: t.readyState,
|
||||
})),
|
||||
options: this.options,
|
||||
});
|
||||
|
||||
// Set up video element
|
||||
if (this.video) {
|
||||
this.video.srcObject = this.stream;
|
||||
// Only show preview if showPreview is true
|
||||
if (this.options.showPreview) {
|
||||
this.video.style.display = "block";
|
||||
} else {
|
||||
this.video.style.display = "none";
|
||||
}
|
||||
await this.video.play();
|
||||
logger.error(
|
||||
`[WebInlineQRScanner:${this.id}] Video element started playing`,
|
||||
|
||||
@@ -52,7 +52,7 @@ import {
|
||||
routeSchema,
|
||||
DeepLinkRoute,
|
||||
} from "../interfaces/deepLinks";
|
||||
import { logConsoleAndDb } from "../db";
|
||||
import { logConsoleAndDb } from "../db/databaseUtil";
|
||||
import type { DeepLinkError } from "../interfaces/deepLinks";
|
||||
|
||||
/**
|
||||
@@ -119,6 +119,15 @@ export class DeepLinkHandler {
|
||||
const [path, queryString] = parts[1].split("?");
|
||||
const [routePath, param] = path.split("/");
|
||||
|
||||
// Validate route exists before proceeding
|
||||
if (!this.ROUTE_MAP[routePath]) {
|
||||
throw {
|
||||
code: "INVALID_ROUTE",
|
||||
message: `Invalid route path: ${routePath}`,
|
||||
details: { routePath },
|
||||
};
|
||||
}
|
||||
|
||||
const query: Record<string, string> = {};
|
||||
if (queryString) {
|
||||
new URLSearchParams(queryString).forEach((value, key) => {
|
||||
@@ -128,11 +137,9 @@ export class DeepLinkHandler {
|
||||
|
||||
const params: Record<string, string> = {};
|
||||
if (param) {
|
||||
if (this.ROUTE_MAP[routePath].paramKey) {
|
||||
params[this.ROUTE_MAP[routePath].paramKey] = param;
|
||||
} else {
|
||||
params["id"] = param;
|
||||
}
|
||||
// Now we know routePath exists in ROUTE_MAP
|
||||
const routeConfig = this.ROUTE_MAP[routePath];
|
||||
params[routeConfig.paramKey ?? "id"] = param;
|
||||
}
|
||||
return { path: routePath, params, query };
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user