mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-04 08:13:35 +00:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0870e227d9 | ||
|
|
57c646f919 | ||
|
|
81fae13219 | ||
|
|
3aedc574d7 | ||
|
|
be71f350fc | ||
|
|
03578ab05d | ||
|
|
a26a755505 | ||
|
|
849693416a | ||
|
|
58322d237e | ||
|
|
976164b480 | ||
|
|
36756f56a9 | ||
|
|
3701c14c37 | ||
|
|
33614b1ddd | ||
|
|
ca9c88b5ea | ||
|
|
95881bb09f | ||
|
|
ba1a7871a0 | ||
|
|
a98151688d |
No files matched your search
@@ -114,9 +114,9 @@ This project comes with custom hooks for querying and publishing events on the N
|
||||
|
||||
### Nostr Implementation Guidelines
|
||||
|
||||
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
|
||||
- Always check the full list of existing NIPs before implementing any Nostr features to see what kinds are currently in use across all NIPs.
|
||||
- If any existing kind or NIP might offer the required functionality, read the relevant NIPs to investigate thoroughly. Several NIPs may need to be read before making a decision.
|
||||
- Only generate new kind numbers if no existing suitable kinds are found after comprehensive research.
|
||||
|
||||
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
|
||||
|
||||
@@ -124,7 +124,7 @@ Knowing when to create a new kind versus reusing an existing kind requires caref
|
||||
|
||||
When implementing features that could use existing NIPs, follow this decision framework:
|
||||
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Get an overview of all NIPs, and then read specific NIPs and kind documentation to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
|
||||
|
||||
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
|
||||
|
||||
@@ -142,7 +142,7 @@ When implementing features that could use existing NIPs, follow this decision fr
|
||||
- The data structure is fundamentally different from existing patterns
|
||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||
|
||||
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
6. **Custom Kind Publishing**: When publishing events with custom generated kinds, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
|
||||
|
||||
**Example Decision Process**:
|
||||
```
|
||||
@@ -281,6 +281,85 @@ function useCustomHook() {
|
||||
}
|
||||
```
|
||||
|
||||
### Connecting to Multiple Nostr Relays
|
||||
|
||||
By default, the `nostr` object from `useNostr` uses a pool configuration that reads data from 1 relay and publishes to all configured relays. However, you can connect to specific relays or groups of relays for more granular control:
|
||||
|
||||
#### Single Relay Connection
|
||||
|
||||
To read and publish from one specific relay, use `nostr.relay()` with a WebSocket URL:
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useSpecificRelay() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// Connect to a specific relay
|
||||
const relay = nostr.relay('wss://relay.damus.io');
|
||||
|
||||
// Query from this specific relay only
|
||||
const events = await relay.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
|
||||
// Publish to this specific relay only
|
||||
await relay.event({ kind: 1, content: 'Hello from specific relay!' });
|
||||
}
|
||||
```
|
||||
|
||||
#### Multiple Relay Group
|
||||
|
||||
To read and publish from a specific set of relays, use `nostr.group()` with an array of relay URLs:
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useRelayGroup() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// Create a group of specific relays
|
||||
const relayGroup = nostr.group([
|
||||
'wss://relay.damus.io',
|
||||
'wss://relay.nostr.band',
|
||||
'wss://nos.lol'
|
||||
]);
|
||||
|
||||
// Query from all relays in the group
|
||||
const events = await relayGroup.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
|
||||
// Publish to all relays in the group
|
||||
await relayGroup.event({ kind: 1, content: 'Hello from relay group!' });
|
||||
}
|
||||
```
|
||||
|
||||
#### API Consistency
|
||||
|
||||
Both `relay` and `group` objects have the same API as the main `nostr` object, including:
|
||||
|
||||
- `.query()` - Query events with filters
|
||||
- `.req()` - Create subscriptions
|
||||
- `.event()` - Publish events
|
||||
- All other Nostr protocol methods
|
||||
|
||||
#### Use Cases
|
||||
|
||||
**Single Relay (`nostr.relay()`):**
|
||||
- Testing specific relay behavior
|
||||
- Querying relay-specific content
|
||||
- Debugging connectivity issues
|
||||
- Working with specialized relays
|
||||
|
||||
**Relay Group (`nostr.group()`):**
|
||||
- Querying from trusted relay sets
|
||||
- Publishing to specific communities
|
||||
- Load balancing across relay subsets
|
||||
- Geographic relay optimization
|
||||
|
||||
**Default Pool (`nostr`):**
|
||||
- General application queries
|
||||
- Maximum reach for publishing
|
||||
- Default user experience
|
||||
- Simplified relay management
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
@@ -938,14 +1017,14 @@ import { Card, CardContent } from '@/components/ui/card';
|
||||
|
||||
To add custom fonts, follow these steps:
|
||||
|
||||
1. **Install a font package** using the `js-dev__npm_add_package` tool:
|
||||
1. **Install a font package** using npm:
|
||||
|
||||
**Any Google Font can be installed** using the @fontsource packages. Examples:
|
||||
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
|
||||
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
|
||||
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
|
||||
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
|
||||
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
|
||||
- For Inter Variable: `@fontsource-variable/inter`
|
||||
- For Roboto: `@fontsource/roboto`
|
||||
- For Outfit Variable: `@fontsource-variable/outfit`
|
||||
- For Poppins: `@fontsource/poppins`
|
||||
- For Open Sans: `@fontsource/open-sans`
|
||||
|
||||
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
|
||||
|
||||
@@ -1018,7 +1097,7 @@ There is an important distinction between **writing new tests** and **running ex
|
||||
### Running Tests (Executing the Test Suite)
|
||||
**ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not.
|
||||
|
||||
- **You must run the test script** using `js-dev__run_script` tool with the "test" parameter
|
||||
- **You must run the test script** to validate your changes
|
||||
- **Your task is not complete** until the test script passes without errors
|
||||
- **This applies to all changes** - bug fixes, new features, refactoring, or any code modifications
|
||||
- **The test script includes** TypeScript compilation, ESLint checks, and existing test validation
|
||||
@@ -1052,10 +1131,26 @@ describe('MyComponent', () => {
|
||||
});
|
||||
```
|
||||
|
||||
## Testing Your Changes
|
||||
## Validating Your Changes
|
||||
|
||||
**CRITICAL**: Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
|
||||
**CRITICAL**: After making any code changes, you must validate your work by running available validation tools.
|
||||
|
||||
**Your task is not considered finished until this test passes without errors.**
|
||||
**Your task is not considered finished until the code successfully type-checks and builds without errors.**
|
||||
|
||||
**This requirement applies regardless of whether you wrote new tests or not.** The test script validates the entire codebase, including TypeScript compilation, ESLint rules, and existing test suite.
|
||||
### Validation Priority Order
|
||||
|
||||
Run available tools in this priority order:
|
||||
|
||||
1. **Type Checking** (Required): Ensure TypeScript compilation succeeds
|
||||
2. **Building/Compilation** (Required): Verify the project builds successfully
|
||||
3. **Linting** (Recommended): Check code style and catch potential issues
|
||||
4. **Tests** (If Available): Run existing test suite
|
||||
5. **Git Commit** (Required): Create a commit with your changes when finished
|
||||
|
||||
**Minimum Requirements:**
|
||||
- Code must type-check without errors
|
||||
- Code must build/compile successfully
|
||||
- Fix any critical linting errors that would break functionality
|
||||
- Create a git commit when your changes are complete
|
||||
|
||||
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
|
||||
@@ -1 +0,0 @@
|
||||
AGENTS.md
|
||||
@@ -1,3 +1,238 @@
|
||||
# MKStack
|
||||
|
||||
Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
**The Complete Framework for Building Nostr Clients with AI**
|
||||
|
||||
MKStack is an AI-powered framework for building Nostr applications with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify. Build powerful Nostr applications with AI-first development - from social feeds to private messaging, MKStack provides everything you need to create decentralized apps on the Nostr protocol.
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
Build your Nostr app in 3 simple steps:
|
||||
|
||||
### 1. Install & Create
|
||||
```bash
|
||||
npm install -g @getstacks/stacks
|
||||
stacks mkstack
|
||||
```
|
||||
|
||||
### 2. Build with AI
|
||||
```bash
|
||||
stacks agent
|
||||
# Tell Dork AI what you want: "Build a group chat application"
|
||||
```
|
||||
|
||||
### 3. Deploy Instantly
|
||||
```bash
|
||||
npm run deploy
|
||||
# ✅ App deployed to NostrDeploy.com!
|
||||
```
|
||||
|
||||
## ✨ What Makes MKStack Special
|
||||
|
||||
- **🤖 AI-First Development**: Build complete Nostr apps with just one prompt using Dork AI agent
|
||||
- **⚡ 8 Minutes Average**: From idea to deployed application in minutes, not months
|
||||
- **🔗 50+ NIPs Supported**: Comprehensive Nostr protocol implementation
|
||||
- **🎨 Beautiful UI**: 48+ shadcn/ui components with light/dark theme support
|
||||
- **🔐 Built-in Security**: NIP-07 browser signing, NIP-44 encryption, event validation
|
||||
- **💰 Payments Ready**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Wallet Connect (NIP-47)
|
||||
- **📱 Production Ready**: TypeScript, testing, deployment, and responsive design included
|
||||
|
||||
## 🛠 Technology Stack
|
||||
|
||||
- **React 18.x**: Stable version with hooks, concurrent rendering, and improved performance
|
||||
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
|
||||
- **Vite**: Fast build tool and development server
|
||||
- **shadcn/ui**: 48+ unstyled, accessible UI components built with Radix UI
|
||||
- **Nostrify**: Nostr protocol framework for Deno and web
|
||||
- **React Router**: Client-side routing with BrowserRouter
|
||||
- **TanStack Query**: Data fetching, caching, and state management
|
||||
- **TypeScript**: Type-safe JavaScript development
|
||||
|
||||
## 🎯 Real-World Examples
|
||||
|
||||
### Built with One Prompt
|
||||
|
||||
Each of these applications was created with just a single prompt to Dork AI:
|
||||
|
||||
- **Group Chat Application**: `"Build me a group chat application"`
|
||||
- [Live Demo](https://groupchat-74z9j26wq-mks-projects-1f1254c4.vercel.app/)
|
||||
|
||||
- **Decentralized Goodreads**: `"Build a decentralized goodreads alternative. Use OpenLibrary API for book data."`
|
||||
- [Live Demo](https://bookstr123-87phkwjcy-mks-projects-1f1254c4.vercel.app/)
|
||||
|
||||
- **Chess Game**: `"Build a chess game with NIP 64"`
|
||||
- [Live Demo](https://chess-l0d7ms7m3-mks-projects-1f1254c4.vercel.app/chess)
|
||||
|
||||
### Production Apps
|
||||
|
||||
Real Nostr applications built using MKStack:
|
||||
|
||||
- **[Chorus](https://chorus.community/)**: Facebook-style groups on Nostr with built-in eCash wallet
|
||||
- **[Blobbi](https://www.blobbi.pet/)**: Digital pet companions that live forever on the decentralized web
|
||||
- **[Treasures](https://treasures.to/)**: Decentralized geocaching adventure powered by Nostr
|
||||
|
||||
[Browse more apps made with MKStack →](https://nostrhub.io/apps/t/mkstack/)
|
||||
|
||||
## 🔧 Core Features
|
||||
|
||||
### Authentication & Users
|
||||
- `LoginArea` component with account switching
|
||||
- `useCurrentUser` hook for authentication state
|
||||
- `useAuthor` hook for fetching user profiles
|
||||
- NIP-07 browser signing support
|
||||
- Multi-account management
|
||||
|
||||
### Nostr Protocol Support
|
||||
- **Social Features**: User profiles (NIP-01), follow lists (NIP-02), reactions (NIP-25), reposts (NIP-18)
|
||||
- **Messaging**: Private DMs (NIP-17), public chat (NIP-28), group chat (NIP-29), encryption (NIP-44)
|
||||
- **Payments**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Nutzaps (NIP-61), Wallet Connect (NIP-47)
|
||||
- **Content**: Long-form articles (NIP-23), file metadata (NIP-94), live events (NIP-53), calendars (NIP-52)
|
||||
|
||||
### Data Management
|
||||
- `useNostr` hook for querying and publishing
|
||||
- `useNostrPublish` hook with automatic client tagging
|
||||
- Event validation and filtering
|
||||
- Infinite scroll with TanStack Query
|
||||
- Multi-relay support
|
||||
|
||||
### UI Components
|
||||
- 48+ shadcn/ui components (buttons, forms, dialogs, etc.)
|
||||
- `NoteContent` component for rich text rendering
|
||||
- `EditProfileForm` for profile management
|
||||
- `RelaySelector` for relay switching
|
||||
- `CommentsSection` for threaded discussions
|
||||
- Light/dark theme system
|
||||
|
||||
### Media & Files
|
||||
- `useUploadFile` hook with Blossom server integration
|
||||
- NIP-94 compatible file metadata
|
||||
- Image and video support
|
||||
- File attachment to events
|
||||
|
||||
### Advanced Features
|
||||
- NIP-19 identifier routing (`npub1`, `note1`, `nevent1`, `naddr1`)
|
||||
- Cryptographic operations (encryption/decryption)
|
||||
- Lightning payments and zaps
|
||||
- Real-time event subscriptions
|
||||
- Responsive design with mobile support
|
||||
|
||||
## 🤖 AI Development with Dork
|
||||
|
||||
MKStack includes Dork, a built-in AI agent that understands your codebase and Nostr protocols:
|
||||
|
||||
### Supported AI Providers
|
||||
|
||||
Configure your AI provider with `stacks configure`:
|
||||
|
||||
- **OpenRouter** ([openrouter.ai](https://openrouter.ai/)): Enter your API key from settings
|
||||
- **Routstr** ([routstr.com](https://www.routstr.com/)): Use Cashu tokens for payment
|
||||
- **PayPerQ** ([ppq.ai](https://ppq.ai/)): OpenAI-compatible API
|
||||
|
||||
### How Dork Works
|
||||
|
||||
- **Context-Aware**: Understands your entire codebase and project structure
|
||||
- **Nostr Expert**: Built-in knowledge of 50+ NIPs and best practices
|
||||
- **Instant Implementation**: Makes changes directly to your code following React/TypeScript best practices
|
||||
|
||||
Example prompts:
|
||||
```bash
|
||||
"Add user profiles with avatars and bio"
|
||||
"Implement NIP-17 private messaging"
|
||||
"Add a dark mode toggle"
|
||||
"Create a marketplace with NIP-15"
|
||||
```
|
||||
|
||||
## 📁 Project Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── components/ # UI components
|
||||
│ ├── ui/ # shadcn/ui components (48+ available)
|
||||
│ ├── auth/ # Authentication components
|
||||
│ └── comments/ # Comment system components
|
||||
├── hooks/ # Custom React hooks
|
||||
│ ├── useNostr # Core Nostr integration
|
||||
│ ├── useAuthor # User profile data
|
||||
│ ├── useCurrentUser # Authentication state
|
||||
│ ├── useNostrPublish # Event publishing
|
||||
│ ├── useUploadFile # File uploads
|
||||
│ └── useZaps # Lightning payments
|
||||
├── pages/ # Page components
|
||||
├── lib/ # Utility functions
|
||||
├── contexts/ # React context providers
|
||||
└── test/ # Testing utilities
|
||||
```
|
||||
|
||||
## 🎨 UI Components
|
||||
|
||||
MKStack includes 48+ shadcn/ui components:
|
||||
|
||||
**Layout**: Card, Separator, Sheet, Sidebar, ScrollArea, Resizable
|
||||
**Navigation**: Breadcrumb, NavigationMenu, Menubar, Tabs, Pagination
|
||||
**Forms**: Button, Input, Textarea, Select, Checkbox, RadioGroup, Switch, Slider
|
||||
**Feedback**: Alert, AlertDialog, Toast, Progress, Skeleton
|
||||
**Overlay**: Dialog, Popover, HoverCard, Tooltip, ContextMenu, DropdownMenu
|
||||
**Data Display**: Table, Avatar, Badge, Calendar, Chart, Carousel
|
||||
**And many more...
|
||||
|
||||
## 🔐 Security & Best Practices
|
||||
|
||||
- **Never use `any` type**: Always use proper TypeScript types
|
||||
- **Event validation**: Filter events through validator functions for custom kinds
|
||||
- **Efficient queries**: Minimize separate queries to avoid rate limiting
|
||||
- **Proper error handling**: Graceful handling of invalid NIP-19 identifiers
|
||||
- **Secure authentication**: Use signer interface, never request private keys directly
|
||||
|
||||
## 📱 Responsive Design
|
||||
|
||||
- Mobile-first approach with Tailwind breakpoints
|
||||
- `useIsMobile` hook for responsive behavior
|
||||
- Touch-friendly interactions
|
||||
- Optimized for all screen sizes
|
||||
|
||||
## 🧪 Testing
|
||||
|
||||
- Vitest with jsdom environment
|
||||
- React Testing Library with jest-dom matchers
|
||||
- `TestApp` component provides all necessary context providers
|
||||
- Mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
|
||||
|
||||
## 🚀 Deployment
|
||||
|
||||
Built-in deployment to NostrDeploy.com:
|
||||
|
||||
```bash
|
||||
npm run deploy
|
||||
```
|
||||
|
||||
Your app goes live instantly with:
|
||||
- Automatic builds
|
||||
- CDN distribution
|
||||
- HTTPS support
|
||||
- Custom domains available
|
||||
|
||||
## 📚 Documentation
|
||||
|
||||
For detailed documentation on building Nostr applications with MKStack:
|
||||
|
||||
- [Tutorial](https://soapbox.pub/blog/mkstack-tutorial)
|
||||
- [Nostr Protocol Documentation](https://nostr.com)
|
||||
- [shadcn/ui Components](https://ui.shadcn.com)
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
MKStack is open source and welcomes contributions. The framework is designed to be:
|
||||
|
||||
- **Extensible**: Easy to add new NIPs and features
|
||||
- **Maintainable**: Clean architecture with TypeScript
|
||||
- **Testable**: Comprehensive testing setup included
|
||||
- **Documented**: Clear patterns and examples
|
||||
|
||||
## 📄 License
|
||||
|
||||
Open source - build amazing Nostr applications and help grow the decentralized web!
|
||||
|
||||
---
|
||||
|
||||
**"Vibed with MKStack"** - [Learn more about MKStack](https://soapbox.pub/mkstack)
|
||||
|
||||
*Build your Nostr app in minutes, not months. Start with AI, deploy instantly.*
|
||||
Generated
+7
@@ -48,6 +48,7 @@
|
||||
"cmdk": "^1.0.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"idb": "^8.0.3",
|
||||
"input-otp": "^1.2.4",
|
||||
"lucide-react": "^0.462.0",
|
||||
"nostr-tools": "^2.13.0",
|
||||
@@ -5486,6 +5487,12 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/idb": {
|
||||
"version": "8.0.3",
|
||||
"resolved": "https://registry.npmjs.org/idb/-/idb-8.0.3.tgz",
|
||||
"integrity": "sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
|
||||
+4
-3
@@ -4,9 +4,9 @@
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "npm i && vite",
|
||||
"build": "npm i && vite build && cp dist/index.html dist/404.html",
|
||||
"test": "npm i && tsc -p tsconfig.app.json --noEmit && eslint && vitest run && vite build",
|
||||
"dev": "npm i --silent && vite",
|
||||
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
||||
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
|
||||
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -50,6 +50,7 @@
|
||||
"cmdk": "^1.0.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"idb": "^8.0.3",
|
||||
"input-otp": "^1.2.4",
|
||||
"lucide-react": "^0.462.0",
|
||||
"nostr-tools": "^2.13.0",
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
||||
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, Lock, CheckCircle, Upload, Globe, FileSignature, Wand2 } from 'lucide-react';
|
||||
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, CheckCircle, Upload, Globe } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
|
||||
@@ -9,7 +9,7 @@ export const buttonVariants = cva(
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline:
|
||||
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||
"border border-input hover:bg-accent hover:text-accent-foreground",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
|
||||
+12
-12
@@ -1,19 +1,19 @@
|
||||
import * as React from "react"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
const MOBILE_BREAKPOINT = 768;
|
||||
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
export function useIsMobile(): boolean {
|
||||
const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
}
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
mql.addEventListener("change", onChange);
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
return () => mql.removeEventListener("change", onChange);
|
||||
}, []);
|
||||
|
||||
return !!isMobile
|
||||
return !!isMobile;
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
|
||||
interface BaseSendDMParams {
|
||||
recipientPubkey: string;
|
||||
content: string;
|
||||
attachments?: Array<{
|
||||
url: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
name: string;
|
||||
tags: string[][];
|
||||
}>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for sending direct messages using NIP-04 and NIP-17 protocols
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const { sendNIP4Message, sendNIP17Message } = useSendDM();
|
||||
*
|
||||
* // Send NIP-04 message
|
||||
* await sendNIP4Message.mutateAsync({
|
||||
* recipientPubkey: 'hex-pubkey',
|
||||
* content: 'Hello!'
|
||||
* });
|
||||
*
|
||||
* // Send NIP-17 message (more secure, uses NIP-44 + gift wrapping)
|
||||
* await sendNIP17Message.mutateAsync({
|
||||
* recipientPubkey: 'hex-pubkey',
|
||||
* content: 'Hello securely!'
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function useSendDM() {
|
||||
const { mutateAsync: createEvent } = useNostrPublish();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
|
||||
// Helper function to prepare content with attachments
|
||||
const prepareMessageContent = (content: string, attachments: BaseSendDMParams['attachments'] = []) => {
|
||||
if (attachments.length === 0) return content;
|
||||
|
||||
const fileUrls = attachments.map(file => file.url).join('\n');
|
||||
return content ? `${content}\n\n${fileUrls}` : fileUrls;
|
||||
};
|
||||
|
||||
// Helper function to create imeta tags for attachments (NIP-92)
|
||||
const createImetaTags = (attachments: BaseSendDMParams['attachments'] = []) => {
|
||||
return attachments.map(file => {
|
||||
const imetaTag = ["imeta"];
|
||||
imetaTag.push(`url ${file.url}`);
|
||||
if (file.mimeType) imetaTag.push(`m ${file.mimeType}`);
|
||||
if (file.size) imetaTag.push(`size ${file.size}`);
|
||||
if (file.name) imetaTag.push(`alt ${file.name}`);
|
||||
|
||||
file.tags.forEach(tag => {
|
||||
if (tag[0] === 'x') imetaTag.push(`x ${tag[1]}`);
|
||||
if (tag[0] === 'ox') imetaTag.push(`ox ${tag[1]}`);
|
||||
});
|
||||
|
||||
return imetaTag;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Send a NIP-04 encrypted direct message
|
||||
* Uses legacy NIP-04 encryption (nip04.encrypt)
|
||||
*/
|
||||
const sendNIP4Message = useMutation({
|
||||
mutationFn: async ({ recipientPubkey, content, attachments = [] }: BaseSendDMParams) => {
|
||||
if (!user?.signer?.nip04) {
|
||||
console.error('[SendDM] NIP-04 encryption not available');
|
||||
throw new Error('NIP-04 encryption not available');
|
||||
}
|
||||
|
||||
console.log('[SendDM] Sending NIP-04 message');
|
||||
|
||||
const messageContent = prepareMessageContent(content, attachments);
|
||||
const encryptedContent = await user.signer.nip04.encrypt(recipientPubkey, messageContent);
|
||||
|
||||
const tags = [
|
||||
["p", recipientPubkey],
|
||||
...createImetaTags(attachments)
|
||||
];
|
||||
|
||||
const event = await createEvent({
|
||||
kind: 4, // NIP-04 encrypted DM
|
||||
content: encryptedContent,
|
||||
tags,
|
||||
});
|
||||
|
||||
console.log('[SendDM] Created NIP-04 message:', event);
|
||||
return event;
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('Failed to send NIP-04 DM:', error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to send NIP-04 message. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Send a NIP-17 encrypted direct message (Gift Wrapped)
|
||||
* Uses NIP-44 encryption with gift wrapping (NIP-59) for enhanced privacy
|
||||
*
|
||||
* Creates:
|
||||
* 1. Kind 14 Private DM event (signed by sender)
|
||||
* 2. Kind 13 Seal events (encrypted to recipient and sender)
|
||||
* 3. Kind 1059 Gift Wrap events (for recipient and sender to find messages)
|
||||
*/
|
||||
const sendNIP17Message = useMutation({
|
||||
mutationFn: async ({ recipientPubkey, content, attachments = [] }: BaseSendDMParams) => {
|
||||
if (!user?.signer?.nip44) {
|
||||
console.error('[SendDM] NIP-44 encryption not available for NIP-17');
|
||||
throw new Error('NIP-44 encryption not available for NIP-17');
|
||||
}
|
||||
|
||||
console.log('[SendDM] Sending NIP-17 Gift Wrap message');
|
||||
|
||||
const messageContent = prepareMessageContent(content, attachments);
|
||||
|
||||
// Step 1: Create and sign the Kind 14 Private DM event
|
||||
const privateDMTags = [
|
||||
["p", recipientPubkey],
|
||||
...createImetaTags(attachments)
|
||||
];
|
||||
|
||||
const privateDM = await user.signer.signEvent({
|
||||
kind: 14,
|
||||
content: messageContent,
|
||||
tags: privateDMTags,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
|
||||
// Step 2: Create TWO Kind 13 Seal events - one for recipient, one for sender
|
||||
|
||||
// Seal for recipient (encrypted to them)
|
||||
const recipientSeal = await user.signer.signEvent({
|
||||
kind: 13,
|
||||
content: await user.signer.nip44.encrypt(recipientPubkey, JSON.stringify(privateDM)),
|
||||
tags: [], // Seal events typically have no tags
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
|
||||
// Seal for sender (encrypted to us)
|
||||
const senderSeal = await user.signer.signEvent({
|
||||
kind: 13,
|
||||
content: await user.signer.nip44.encrypt(user.pubkey, JSON.stringify(privateDM)),
|
||||
tags: [], // Seal events typically have no tags
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
|
||||
// Step 3: Create TWO Kind 1059 Gift Wrap events
|
||||
// One for the recipient, one for myself (so I can see sent messages)
|
||||
|
||||
// Gift Wrap for recipient - they should be able to find it via their pubkey in p tag
|
||||
const recipientGiftWrap = await createEvent({
|
||||
kind: 1059, // Gift Wrap
|
||||
content: await user.signer.nip44.encrypt(recipientPubkey, JSON.stringify(recipientSeal)),
|
||||
tags: [["p", recipientPubkey]], // Recipient can find this via their pubkey
|
||||
});
|
||||
|
||||
// Gift Wrap for myself - I should be able to find it via my pubkey in p tag
|
||||
const myGiftWrap = await createEvent({
|
||||
kind: 1059, // Gift Wrap
|
||||
content: await user.signer.nip44.encrypt(user.pubkey, JSON.stringify(senderSeal)),
|
||||
tags: [["p", user.pubkey]], // I can find this via my pubkey
|
||||
});
|
||||
|
||||
return { recipientGiftWrap, myGiftWrap };
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('Failed to send NIP-17 DM:', error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to send NIP-17 message. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
sendNIP4Message,
|
||||
sendNIP17Message,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { MESSAGE_PROTOCOL, type MessageProtocol } from '@/types/dm';
|
||||
|
||||
/**
|
||||
* Helper function to determine message protocol from event kind
|
||||
*/
|
||||
export function getMessageProtocol(kind: number): MessageProtocol {
|
||||
switch (kind) {
|
||||
case 4: return MESSAGE_PROTOCOL.NIP04;
|
||||
case 1059: return MESSAGE_PROTOCOL.NIP17; // Gift Wrap
|
||||
case 14: return MESSAGE_PROTOCOL.NIP17; // Private DM (decrypted NIP-17)
|
||||
default: return MESSAGE_PROTOCOL.UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Protocol indicator configuration for UI display
|
||||
*/
|
||||
export const PROTOCOL_CONFIG = {
|
||||
[MESSAGE_PROTOCOL.NIP04]: {
|
||||
color: 'bg-orange-500',
|
||||
textColor: 'text-orange-600 dark:text-orange-400',
|
||||
label: 'NIP-04',
|
||||
title: 'NIP-04 encrypted message'
|
||||
},
|
||||
[MESSAGE_PROTOCOL.NIP17]: {
|
||||
color: 'bg-purple-500',
|
||||
textColor: 'text-purple-600 dark:text-purple-400',
|
||||
label: 'NIP-17',
|
||||
title: 'NIP-44/NIP-17 encrypted message'
|
||||
},
|
||||
[MESSAGE_PROTOCOL.UNKNOWN]: {
|
||||
color: 'bg-gray-400',
|
||||
textColor: 'text-gray-600 dark:text-gray-400',
|
||||
label: 'Unknown',
|
||||
title: 'Unknown message type'
|
||||
}
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Constants for consistent naming across the app
|
||||
*/
|
||||
export const PROTOCOL_CONSTANTS = {
|
||||
// localStorage keys
|
||||
NIP17_ENABLED_KEY: 'enableNIP17',
|
||||
|
||||
// Logger prefixes
|
||||
NIP4_LOG_PREFIX: 'DMS: [NIP4]',
|
||||
NIP17_LOG_PREFIX: 'DMS: [NIP17]',
|
||||
DMCHAT_LOG_PREFIX: 'DMS: [DMCHAT]',
|
||||
DIRECT_MESSAGES_LOG_PREFIX: 'DMS: [DirectMessages]',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Message pagination constants
|
||||
*/
|
||||
export const MESSAGES_PER_PAGE = 25;
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import type { DecryptedMessage, DMConversation } from '@/types/dm';
|
||||
|
||||
/**
|
||||
* Shared validation function for DM events
|
||||
* Validates both NIP-04 (kind 4) and NIP-17 (kind 1059) encrypted DMs
|
||||
*/
|
||||
export function validateDMEvent(event: NostrEvent): boolean {
|
||||
// Accept both NIP-04 (kind 4) and NIP-17 (kind 1059) encrypted DMs
|
||||
if (![4, 1059].includes(event.kind)) return false;
|
||||
|
||||
// Must have a 'p' tag for the recipient
|
||||
const hasP = event.tags.some(([name]) => name === 'p');
|
||||
if (!hasP) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the recipient pubkey from a DM event
|
||||
*/
|
||||
export function getRecipientPubkey(event: NostrEvent): string | null {
|
||||
const pTag = event.tags.find(([name]) => name === 'p');
|
||||
return pTag ? pTag[1] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a message is from the current user
|
||||
*/
|
||||
export function isMessageFromUser(message: DecryptedMessage, userPubkey: string): boolean {
|
||||
return message.pubkey === userPubkey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort conversations by last activity (most recent first)
|
||||
*/
|
||||
export function sortConversationsByActivity(conversations: DMConversation[]): DMConversation[] {
|
||||
return [...conversations].sort((a, b) => b.lastMessageTime - a.lastMessageTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter conversations by search query
|
||||
* Searches in decrypted message content and participant info
|
||||
*/
|
||||
export function filterConversationsByQuery(
|
||||
conversations: DMConversation[],
|
||||
query: string
|
||||
): DMConversation[] {
|
||||
if (!query.trim()) return conversations;
|
||||
|
||||
const lowerQuery = query.toLowerCase();
|
||||
return conversations.filter(conv => {
|
||||
// Search in pubkey
|
||||
if (conv.pubkey.toLowerCase().includes(lowerQuery)) return true;
|
||||
|
||||
// Search in last message content
|
||||
if (conv.lastMessage?.decryptedContent?.toLowerCase().includes(lowerQuery)) return true;
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { openDB, IDBPDatabase } from 'idb';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
// Match the in-memory structure exactly
|
||||
interface StoredParticipant {
|
||||
messages: NostrEvent[]; // Store only basic NostrEvent in IndexedDB
|
||||
lastActivity: number;
|
||||
hasNIP4: boolean;
|
||||
hasNIP17: boolean;
|
||||
}
|
||||
|
||||
// Store structure: Map<participantPubkey, StoredParticipant>
|
||||
interface MessageStore {
|
||||
participants: Record<string, StoredParticipant>;
|
||||
lastSync: {
|
||||
nip4: number | null;
|
||||
nip17: number | null;
|
||||
};
|
||||
}
|
||||
|
||||
// IndexedDB configuration
|
||||
const DB_NAME = 'nostr-messages';
|
||||
const DB_VERSION = 1;
|
||||
|
||||
/**
|
||||
* Initialize IndexedDB for a specific user
|
||||
* Creates a user-specific store if it doesn't exist
|
||||
*/
|
||||
async function initDB(userNpub: string): Promise<IDBPDatabase> {
|
||||
const storeName = `messages-${userNpub}`;
|
||||
|
||||
return openDB(DB_NAME, DB_VERSION, {
|
||||
upgrade(db, _oldVersion, _newVersion) {
|
||||
// Create store for this user if it doesn't exist
|
||||
if (!db.objectStoreNames.contains(storeName)) {
|
||||
db.createObjectStore(storeName, { keyPath: 'id' });
|
||||
console.log(`DMS: Created store ${storeName} in IndexedDB`);
|
||||
}
|
||||
},
|
||||
blocked() {
|
||||
console.warn('IndexedDB upgrade blocked - another tab may have the database open');
|
||||
},
|
||||
blocking() {
|
||||
console.warn('IndexedDB upgrade blocking - this tab is preventing another tab from upgrading');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Read all messages from IndexedDB for a specific user
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const messageStore = await readMessagesFromDB('npub1...');
|
||||
* if (messageStore) {
|
||||
* console.log('Loaded messages:', messageStore.participants);
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export async function readMessagesFromDB(userNpub: string): Promise<MessageStore | null> {
|
||||
try {
|
||||
const db = await initDB(userNpub);
|
||||
const storeName = `messages-${userNpub}`;
|
||||
|
||||
// Check if the store exists before trying to read from it
|
||||
if (!db.objectStoreNames.contains(storeName)) {
|
||||
console.log(`Store ${storeName} does not exist yet for user ${userNpub.slice(0, 8)}...`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Read the entire store as one object
|
||||
const storeData = await db.get(storeName, 'messageStore');
|
||||
|
||||
if (storeData) {
|
||||
console.log(`Read message store from IndexedDB for user ${userNpub.slice(0, 8)}...`);
|
||||
return storeData as MessageStore;
|
||||
} else {
|
||||
console.log(`DMS: No message store found in IndexedDB for user ${userNpub.slice(0, 8)}...`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error reading messages from IndexedDB:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write messages to IndexedDB for a specific user
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await writeMessagesToDB('npub1...', {
|
||||
* participants: {
|
||||
* 'hex-pubkey': {
|
||||
* messages: [...],
|
||||
* lastActivity: Date.now(),
|
||||
* hasNIP4: true,
|
||||
* hasNIP17: false
|
||||
* }
|
||||
* },
|
||||
* lastSync: { nip4: Date.now(), nip17: null }
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export async function writeMessagesToDB(userNpub: string, messageStore: MessageStore): Promise<void> {
|
||||
try {
|
||||
const db = await initDB(userNpub);
|
||||
const storeName = `messages-${userNpub}`;
|
||||
|
||||
// Check if the store exists before trying to write to it
|
||||
if (!db.objectStoreNames.contains(storeName)) {
|
||||
console.log(`Store ${storeName} does not exist yet for user ${userNpub.slice(0, 8)}..., creating it`);
|
||||
// Force a database upgrade to create the store
|
||||
await db.close();
|
||||
const newDb = await openDB(DB_NAME, DB_VERSION + 1, {
|
||||
upgrade(db, _oldVersion, _newVersion) {
|
||||
if (!db.objectStoreNames.contains(storeName)) {
|
||||
db.createObjectStore(storeName, { keyPath: 'id' });
|
||||
console.log(`DMS: Created store ${storeName} in IndexedDB during write`);
|
||||
}
|
||||
},
|
||||
});
|
||||
await newDb.put(storeName, { id: 'messageStore', ...messageStore });
|
||||
await newDb.close();
|
||||
} else {
|
||||
// Store the entire message store as one object
|
||||
await db.put(storeName, { id: 'messageStore', ...messageStore });
|
||||
}
|
||||
|
||||
console.log(`Wrote message store to IndexedDB for user ${userNpub.slice(0, 8)}... (${Object.keys(messageStore.participants).length} participants)`);
|
||||
} catch (error) {
|
||||
console.error('Error writing messages to IndexedDB:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all messages from IndexedDB for a specific user
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await clearMessagesFromDB('npub1...');
|
||||
* ```
|
||||
*/
|
||||
export async function clearMessagesFromDB(userNpub: string): Promise<void> {
|
||||
try {
|
||||
const db = await initDB(userNpub);
|
||||
const storeName = `messages-${userNpub}`;
|
||||
|
||||
if (db.objectStoreNames.contains(storeName)) {
|
||||
// Clear the entire store
|
||||
const tx = db.transaction(storeName, 'readwrite');
|
||||
const store = tx.objectStore(storeName);
|
||||
await store.clear();
|
||||
await tx.done;
|
||||
|
||||
console.log(`DMS: Cleared message store from IndexedDB for user ${userNpub.slice(0, 8)}...`);
|
||||
} else {
|
||||
console.log(`DMS: Store ${storeName} does not exist for user ${userNpub.slice(0, 8)}..., nothing to clear`);
|
||||
}
|
||||
|
||||
await db.close();
|
||||
} catch (error) {
|
||||
console.error('DMS: Error clearing messages from IndexedDB:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
/**
|
||||
* DM Tab Types - for organizing conversations
|
||||
*/
|
||||
export type DMTabType = 'known' | 'newRequests';
|
||||
|
||||
/**
|
||||
* Message Protocol Types
|
||||
*/
|
||||
export const MESSAGE_PROTOCOL = {
|
||||
NIP04: 'NIP04',
|
||||
NIP17: 'NIP17',
|
||||
UNKNOWN: 'UNKNOWN'
|
||||
} as const;
|
||||
|
||||
export type MessageProtocol = typeof MESSAGE_PROTOCOL[keyof typeof MESSAGE_PROTOCOL];
|
||||
|
||||
/**
|
||||
* Decrypted message with additional metadata
|
||||
*/
|
||||
export interface DecryptedMessage extends NostrEvent {
|
||||
decryptedContent?: string;
|
||||
error?: string;
|
||||
isSending?: boolean;
|
||||
clientFirstSeen?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* DM Conversation structure
|
||||
*/
|
||||
export interface DMConversation {
|
||||
id: string; // The other person's pubkey
|
||||
pubkey: string;
|
||||
lastMessage?: DecryptedMessage;
|
||||
lastMessageTime: number;
|
||||
unreadCount: number;
|
||||
// Conversation categorization
|
||||
isKnown?: boolean; // User has sent at least one message to this person
|
||||
isRequest?: boolean; // Other person has sent messages, but user hasn't replied
|
||||
// Reply status tracking
|
||||
lastMessageFromUser?: boolean; // True if user sent the last message, false if other person did
|
||||
}
|
||||
|
||||
/**
|
||||
* Message sending parameters
|
||||
*/
|
||||
export interface SendMessageParams {
|
||||
recipientPubkey: string;
|
||||
content: string;
|
||||
protocol?: MessageProtocol; // Optional - defaults to NIP-04
|
||||
attachments?: Array<{
|
||||
url: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
name: string;
|
||||
tags: string[][];
|
||||
}>;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": false,
|
||||
"strictNullChecks": true,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noImplicitAny": false,
|
||||
"noFallthroughCasesInSwitch": false,
|
||||
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
+25
-13
@@ -1,19 +1,31 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
],
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": false,
|
||||
"strictNullChecks": true,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noImplicitAny": false,
|
||||
"noFallthroughCasesInSwitch": false,
|
||||
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
"noImplicitAny": false,
|
||||
"noUnusedParameters": false,
|
||||
"skipLibCheck": true,
|
||||
"allowJs": true,
|
||||
"noUnusedLocals": false,
|
||||
"strictNullChecks": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user