Compare commits

..
2 Commits
Author SHA1 Message Date
Alex Gleason cbf55c9117 Add pnpm lockfile support 2025-10-16 13:41:47 -05:00
Alex Gleason d87700e731 Support building svelvekit projects 2025-10-15 20:49:26 -05:00
87 changed files with 3710 additions and 6256 deletions

No files matched your search

+1 -10
View File
@@ -1,11 +1,2 @@
# GitHub OAuth Configuration
VITE_GITHUB_OAUTH_CLIENT_ID="********************"
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
# Netlify OAuth Configuration
VITE_NETLIFY_OAUTH_CLIENT_ID="********************"
VITE_NETLIFY_OAUTH_CLIENT_SECRET="****************************************"
# Vercel OAuth Configuration
VITE_VERCEL_OAUTH_CLIENT_ID="********************"
VITE_VERCEL_OAUTH_CLIENT_SECRET="****************************************"
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
+96 -1
View File
@@ -108,6 +108,99 @@ Shakespeare provides full Git functionality in the browser using `isomorphic-git
Git operations happen transparently in the background, providing professional version control without requiring Git knowledge from users.
## Build System
Shakespeare includes a browser-based build system that compiles projects entirely in the browser using esbuild-wasm. The build system supports multiple project types and automatically detects the appropriate build strategy.
### Supported Project Types
#### React/Vite Projects
- **Detection**: Projects with `index.html` at the root
- **Entry Point**: Script tags in `index.html` with `type="module"`
- **Static Assets**: Files in `public/` directory
- **Build Output**: Bundled JavaScript, CSS, and HTML in `dist/` directory
#### SvelteKit Projects
- **Detection**: Projects with `src/app.html` or `svelte.config.js`/`svelte.config.ts`
- **Entry Point**: Svelte components in `src/routes/`
- **Static Assets**: Files in `static/` directory
- **Build Output**: Compiled Svelte components with client-side rendering
### Build System Architecture
The build system is located in `src/lib/build/` and consists of several plugins:
- **esmPlugin**: Resolves npm packages from esm.sh CDN, handles package-lock.json and yarn.lock
- **fsPlugin**: Provides filesystem access for imports, handles path aliases like `@/`
- **sveltePlugin**: Compiles `.svelte` files using the Svelte compiler from CDN
- **shakespearePlugin**: Provides polyfills and workarounds for browser compatibility
### Project Detection
The build system automatically detects project type using the following logic:
```typescript
// A project is considered SvelteKit if:
// 1. It has src/app.html OR svelte.config.js/ts, AND
// 2. It does NOT have a root index.html (which indicates React/Vite)
// Otherwise, it's treated as a React/Vite project
```
This detection is used in two places:
- `buildProject()` in `src/lib/build/index.ts` - for building projects
- `useIsProjectPreviewable()` in `src/hooks/useIsProjectPreviewable.ts` - for determining if preview is available
### Building Projects
Projects can be built using the `BuildProjectTool` or by calling `buildProject()` directly:
```typescript
const result = await buildProject({
fs, // Virtual filesystem
projectPath, // Project directory path
domParser, // DOMParser instance
target: "esnext", // ECMAScript target
esmUrl, // ESM CDN URL
outputPath, // Optional output directory
});
```
The build process:
1. Detects project type (React/Vite or SvelteKit)
2. Reads package.json, tsconfig.json, and lock files
3. Bundles code with esbuild and appropriate plugins
4. Processes HTML template (index.html or app.html)
5. Copies static assets from public/ or static/
6. Writes output to dist/ directory
7. Emits `buildComplete` event for preview refresh
### SvelteKit-Specific Features
When building SvelteKit projects:
- Compiles `.svelte` components using Svelte 5 compiler from esm.sh
- Replaces SvelteKit placeholders in app.html:
- `%sveltekit.head%` - Replaced with script/style tags
- `%sveltekit.body%` - Replaced with `<div id="svelte"></div>`
- `%sveltekit.assets%` - Replaced with empty string
- `%sveltekit.nonce%` - Replaced with empty string
- Looks for entry points in `src/routes/` directory
- Copies static assets from `static/` instead of `public/`
### Preview System
The preview system uses `useIsProjectPreviewable()` to determine if a project can be previewed:
- Returns `true` for React/Vite projects with `index.html` and `package.json`
- Returns `true` for SvelteKit projects with (`src/app.html` OR `svelte.config.*`) and `package.json`
- Returns `false` otherwise
When a project is previewable, the PreviewPane component shows:
- Build button to trigger compilation
- Live preview iframe with the built application
- Console output and error messages
- Browser-like address bar
## AI Message Format
Shakespeare uses OpenAI-compatible messages for communication between users and AI assistants. The message format follows these conventions:
@@ -198,7 +291,9 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useNWCContext`: Access NWC context provider
- `/src/pages/`: Page components used by React Router (Index, NotFound, ProjectView, Settings pages)
- `/src/lib/`: Utility functions and shared logic
- `/src/lib/build/`: Project build system with esbuild integration (esmPlugin, fsPlugin)
- `/src/lib/build/`: Project build system with esbuild integration (esmPlugin, fsPlugin, sveltePlugin)
- Supports both React/Vite projects and SvelteKit projects
- Automatic project type detection based on file structure
- `/src/lib/commands/`: Shell command implementations for virtual filesystem
- `/src/lib/commands/git/`: Git command implementations (add, commit, push, pull, etc.)
- Unix-style commands: `cat`, `cd`, `cp`, `find`, `grep`, `ls`, `mkdir`, `mv`, `rm`, etc.
+209
View File
@@ -0,0 +1,209 @@
# Fork PR Workflow - Troubleshooting Guide
## Common Issues and Solutions
### "Validation Failed" Error
This error from GitHub usually means the PR can't be created. The system now shows detailed reasons:
**Common causes:**
1. **Branch doesn't exist in fork**
- **Solution**: The system now automatically pushes your branch to the fork before creating the PR
- If it still fails, try manually: Git Management → Branches → Push to remote
2. **No commits on the branch**
- **Error**: "head: No commits between..."
- **Solution**: Make sure you've committed your changes before creating a PR
- Go to Git Management → Changes → Commit your work
3. **PR already exists**
- **Error**: "A pull request already exists for..."
- **Solution**: Check the upstream repository - you might already have an open PR from this branch
- Update the existing PR instead of creating a new one
4. **Invalid branch name**
- **Error**: "Reference does not exist"
- **Solution**: Make sure your branch name doesn't have special characters
- Use alphanumeric characters, hyphens, and underscores only
### "Failed to push branch to your fork"
**Causes:**
1. **Branch not committed**
```
Error: Failed to push branch 'my-branch' to your fork.
This usually means:
1. The branch hasn't been committed yet
2. Network/authentication issues
```
**Solution**:
- Go to Git Management → Changes tab
- Review your changes
- Commit them before creating a PR
2. **Authentication issues**
- **Solution**: Check Settings → Git → Make sure your GitHub token is valid
- Token must have `public_repo` scope
- Try re-authenticating if the token expired
3. **Network/CORS issues**
- **Solution**: Check your internet connection
- Some networks block Git operations
- Try again or use a different network
### Fork Workflow Steps
When you create a PR and don't have push access, the system:
1. **Detects you need a fork**
- Shows: "You don't have push access to this repository"
- Explains: "Your changes will be pushed to your fork at username/repo"
2. **Checks for existing fork**
- If found: Uses it
- If not found: Creates a new fork
- Waits for fork to be ready (GitHub takes a few seconds)
3. **Sets up remotes**
- Checks if 'origin' points to your fork
- If not, adds a 'fork' remote
- Determines which remote to use for pushing
4. **Pushes your branch**
- Pushes current branch to fork
- Uses your GitHub credentials
- Shows detailed error if push fails
5. **Creates PR**
- Uses format: `yourname:branch` → `upstream:main`
- Enables "maintainer can modify" by default
- Returns PR URL on success
### Error Message Improvements
The system now shows much more detailed errors:
**Before:**
```
Error: Validation Failed
```
**After:**
```
Validation Failed
Details: head: No commits between master and yourname:test-branch
See: https://docs.github.com/rest/pulls/pulls#create-a-pull-request
```
**With field errors:**
```
Validation Failed
Details: base: Does not exist;
head: Must be formatted as 'owner:branch'
See: https://docs.github.com/rest/pulls/pulls#create-a-pull-request
```
### Debug Checklist
Before creating a PR, verify:
- [ ] You've made changes to files
- [ ] Changes are committed (check Git Management → Changes)
- [ ] You're on the correct branch
- [ ] Branch has a valid name (no spaces or special chars)
- [ ] You have valid GitHub credentials (Settings → Git)
- [ ] Your token has `public_repo` scope
- [ ] The upstream repository allows forks
- [ ] The target branch exists in upstream (usually `main` or `master`)
### Manual Override
If the automatic workflow fails, you can:
1. **Fork manually** on GitHub.com
2. **Add fork as remote**:
- Git Management → (manually configure remotes if needed)
3. **Push branch** to fork:
- Use the existing "Create Pull Request" button
- Or push via command line
4. **Create PR** on GitHub.com directly
### Understanding Remotes
After forking, your remotes should look like:
```
origin → [email protected]:yourname/repo.git (your fork)
upstream → [email protected]:original/repo.git (original repo)
```
Or if system adds a fork remote:
```
origin → [email protected]:original/repo.git (original)
fork → [email protected]:yourname/repo.git (your fork)
```
Both configurations work - the system detects which to use.
### Still Having Issues?
Check the browser console (F12 → Console) for detailed logs:
- `Detected GitHub SSH/HTTPS:` - Shows parsed repository info
- `Pushing branch X to fork Y` - Shows push operation
- `GitHub response status:` - Shows API response codes
- `GitHub API error response:` - Shows full error from GitHub
These logs will show exactly what's happening and where it's failing.
### GitHub API Rate Limits
If you see:
```
Error: API rate limit exceeded
```
**Solution:**
- Wait an hour (unauthenticated limit: 60 requests/hour)
- Or authenticate with a token (limit: 5000 requests/hour)
- Check Settings → Git to ensure token is configured
### Fork Already Exists
If you see:
```
Error: fork already exists for this repository
```
**This is normal!** The system will use your existing fork. The error is just informational.
### Repository Owner Can't Fork
If you own the repository, you can't fork it. You don't need to - you have push access!
The system should detect this and skip the fork workflow. If you see this error, please report it.
## Getting Help
If you encounter an error not covered here:
1. Check the full error message (now includes details)
2. Look at browser console logs
3. Verify your setup (credentials, branch, commits)
4. Try the manual workflow as a workaround
5. Report the issue with:
- Full error message
- Console logs
- Repository URL (if public)
- Branch name
+163
View File
@@ -0,0 +1,163 @@
# Nostr Git Integration
Shakespeare supports creating patches for Nostr git repositories following [NIP-34 (git stuff)](https://github.com/nostr-protocol/nips/blob/master/34.md).
## Overview
Nostr git is a decentralized approach to code collaboration using Nostr events instead of centralized git hosting platforms. With Nostr git:
- **Repository announcements** (kind 30617) declare the existence of git repositories
- **Patches** (kind 1617) are submitted as Nostr events, similar to pull requests
- **Anyone can submit patches** without needing push access or creating forks
- **Maintainers review and apply patches** through status events
## How It Works in Shakespeare
### 1. Repository URL Format
Nostr git repositories use a special URL format:
```
nostr://<pubkey>/<repo-id>
```
- `<pubkey>`: The repository maintainer's Nostr public key (hex format or npub)
- `<repo-id>`: The repository identifier (d tag, usually kebab-case)
**Important**: The system expects hex pubkeys but will automatically convert npub to hex if provided.
Examples:
- `nostr://abc123def456.../my-project` (hex pubkey)
- `nostr://npub1abc123.../my-project` (will be converted to hex)
### 2. Creating Patches (Pull Requests)
When you create a "Pull Request" for a Nostr git repository, Shakespeare:
1. **Detects Nostr git URL** - Recognizes the `nostr://` prefix
2. **Creates patch event** - Generates a kind 1617 event with:
- Patch content (git diff or description)
- Reference to repository announcement (`a` tag)
- Tags for repository owner, patch title, description
- NIP-31 `alt` tag for human-readable description
3. **Publishes to Nostr** - Sends the patch to the repository's designated relays
4. **No forking required** - Unlike GitHub/GitLab, patches go directly to the upstream repo
### 3. UI Integration
The existing Pull Request dialog automatically adapts for Nostr git:
- **Button text**: "Create Patch" instead of "Create Pull Request"
- **No credentials needed**: Uses your Nostr signer (logged-in account)
- **No fork workflow**: Patches are submitted directly
- **Success message**: Shows the Nostr event ID as confirmation
### 4. Key Differences from GitHub/GitLab
| Feature | GitHub/GitLab | Nostr Git |
|---------|---------------|-----------|
| Authentication | Personal access token | Nostr signer |
| Fork required | Yes (if no push access) | No |
| Push to remote | Yes | No (patch is in event) |
| PR/Patch format | API-based | Nostr event (kind 1617) |
| Relay/server | Centralized | Decentralized relays |
## Implementation Details
### GitHostProvider Interface
Nostr git is implemented as a `NostrGitProvider` that implements the `GitHostProvider` interface:
```typescript
class NostrGitProvider implements GitHostProvider {
// Query repository announcements (kind 30617)
async getRepository(owner: string, repo: string): Promise<GitRepository>
// Check if user is a maintainer
async canUserPush(owner: string, repo: string): Promise<boolean>
// Create patch event (kind 1617)
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest>
// ... other methods
}
```
### Patch Event Structure
Patches follow NIP-34 specifications:
```json
{
"kind": 1617,
"content": "<patch content>",
"tags": [
["a", "30617:<repo-owner-pubkey>:<repo-id>"],
["p", "<repository-owner>"],
["t", "root"],
["t", "root-revision"],
["subject", "<patch-title>"],
["description", "<patch-description>"],
["alt", "Patch proposal for <repo>: <title>"]
]
}
```
### Repository Detection
The system detects Nostr git URLs in multiple places:
1. **URL parsing** - `detectGitHost()` checks for `nostr://` prefix
2. **Remote info** - Extracts owner (pubkey) and repo (d tag) from URL
3. **Provider creation** - Instantiates `NostrGitProvider` with signer
## Future Enhancements
Potential improvements to Nostr git integration:
- [ ] Generate actual git patches using `git format-patch`
- [ ] Support patch series (multiple commits)
- [ ] Display patch status (open/closed/applied)
- [ ] Show existing patches for a repository
- [ ] Support patch reviews and comments (kind 1621)
- [ ] Apply patches locally for testing
- [ ] Maintainer tools for applying/merging patches
## Related NIPs
- **NIP-34**: git stuff (repository announcements, patches, issues)
- **NIP-31**: alt tag for unknown event kinds
- **NIP-22**: Comments (for patch discussions)
## Example Workflow
1. **Clone Nostr git repo**:
```bash
# Repository URL: nostr://abc123.../my-project
git clone https://actual-clone-url.git
```
2. **Make changes and commit**:
```bash
git checkout -b my-feature
# ... make changes ...
git commit -m "Add new feature"
```
3. **Create patch in Shakespeare**:
- Open Pull Request dialog
- System detects Nostr git URL
- Fill in title and description
- Click "Create Patch"
- Patch is published to Nostr relays
4. **Maintainer receives patch**:
- Sees patch event on their relays
- Reviews the proposed changes
- Applies or rejects via status events
## Resources
- [NIP-34 Specification](https://github.com/nostr-protocol/nips/blob/master/34.md)
- [Nostr Protocol](https://nostr.com)
- [Git Format-Patch](https://git-scm.com/docs/git-format-patch)
+270
View File
@@ -0,0 +1,270 @@
# Nostr Git Debugging Guide
## Understanding the Problem
Patches are being published successfully but not showing up in NostrHub or other Nostr git clients. This is likely a **relay synchronization issue**.
## How Nostr Git Discovery Works
1. **Repository Announcement (Kind 30617)**
- Published once per repository (auto-announced on first patch)
- Contains metadata: name, description, clone URLs, relays
- Includes `r` tag with earliest unique commit (euc)
- Has `d` tag with repository identifier
- Coordinate: `30617:<pubkey>:<repo-id>`
2. **Patches (Kind 1617)**
- Reference repository via `a` tag: `30617:<pubkey>:<repo-id>`
- Include `r` tag with euc for repository-specific filtering
- Published to relays specified in repository announcement
3. **Discovery Flow**
- Client queries for repositories (kind 30617)
- User selects a repository
- Client queries for patches using `#a` filter: `#a: ["30617:<pubkey>:<repo-id>"]`
4. **Auto-Announcement (Shakespeare Feature)**
- When creating first patch, repository is auto-announced
- Uses configured relay from settings
- Ensures announcement and patch on same relay
- Eliminates manual "Announce Repository" step
## The Relay Problem
**Key Issue**: Events must be on the **same relay** for discovery to work.
### Scenario:
1. You're connected to `wss://relay.primal.net` in Shakespeare
2. You announce repository → published to `wss://relay.primal.net`
3. You create patch → published to `wss://relay.primal.net`
4. NostrHub is connected to `wss://relay.nostr.band`
5. NostrHub queries `wss://relay.nostr.band` → **finds nothing**
### Why This Happens:
- Nostr relays don't automatically sync with each other
- Each relay is independent
- Events are only on relays they were explicitly published to
- Relay hints in events are suggestions, not guarantees
## Debugging Steps
### Step 1: Check Which Relay You're On
In Shakespeare, check the current relay:
- Look at bottom of the page or settings
- Default is `wss://relay.primal.net`
### Step 2: Verify Repository Announcement
After clicking "Announce Repository", check console logs:
```
=== ANNOUNCING REPOSITORY ===
Repository ID: git.shakespeare.diy/portfoliux
Owner pubkey: 932614571afcbad4d17a191ee281e39eebbb41b93fac8fd87829622aeb112f4d
Event coordinate: 30617:932614571afcbad4d17a191ee281e39eebbb41b93fac8fd87829622aeb112f4d:git.shakespeare.diy/portfoliux
Published repository announcement to Nostr relays
To verify: Query for kind 30617 with authors=[...] and #d=[...]
```
### Step 3: Verify Patch Can Find Repository
When creating a patch, check console logs:
**If repository exists:**
```
Querying for repository announcement with filter: {...}
Repository announcement query returned 1 events ✅ GOOD
Found repository announcement event: {...}
```
**If repository doesn't exist (auto-announce):**
```
Repository announcement query returned 0 events
Repository announcement not found - creating one automatically
Auto-creating repository announcement: {...}
Successfully auto-announced repository ✅ GOOD
```
**If auto-announce fails:**
```
Repository announcement query returned 0 events
Failed to auto-announce repository: <error> ❌ BAD
```
### Step 4: Check NostrHub's Relay
1. Open NostrHub (nostrhub.io)
2. Check which relay it's using
3. Compare with Shakespeare's relay
## Solutions
### Solution 1: Use Same Relay as NostrHub
1. In Shakespeare settings, change relay to match NostrHub
2. Common NostrHub relays:
- `wss://relay.nostr.band`
- `wss://relay.damus.io`
3. Re-announce repository on this relay
4. Create new patch
### Solution 2: Publish to Multiple Relays
When announcing repository, add multiple relays:
- `wss://relay.primal.net`
- `wss://relay.nostr.band`
- `wss://relay.damus.io`
The announcement event will be published to all of these, and patches will follow.
### Solution 3: Use NIP-65 Relay Lists (Future Enhancement)
Proper solution would be to:
1. Query user's NIP-65 relay list
2. Publish repository announcements to all user's read/write relays
3. Patches automatically go to same relays
## Verifying Success
### Check Repository is Discoverable:
1. Open NostrHub
2. Go to Repositories page
3. Look for your repository
4. If found → announcement is on correct relay ✅
### Check Patches are Discoverable:
1. Find your repository on NostrHub
2. Click into repository
3. Check Patches tab
4. Your patches should appear ✅
## Common Issues
### Issue: "Repository announcement not found"
**Cause**: Announcement not on current relay
**Fix**: Re-announce on current relay
### Issue: Patches published but not visible
**Cause**: Patches on different relay than announcement
**Fix**: Ensure both announcement and patches on same relay
### Issue: Works in Shakespeare but not NostrHub
**Cause**: Different relays
**Fix**: Use same relay in both clients
### Issue: Relay hints not working
**Explanation**: Relay hints are suggestions only - clients may ignore them
**Fix**: Ensure announcement is on relay the client uses
## Event Format Reference
### Repository Announcement (Kind 30617)
```json
{
"kind": 30617,
"content": "",
"tags": [
["d", "git.shakespeare.diy/portfoliux"],
["name", "Portfoliux"],
["description", "Portfolio website"],
["clone", "nostr://npub.../git.shakespeare.diy/portfoliux"],
["relays", "wss://relay.nostr.band"],
["r", "abc123...", "euc"]
]
}
```
### Patch Event (Kind 1617)
```json
{
"kind": 1617,
"content": "From abc... Mon Sep 17...\n<git format-patch content>",
"tags": [
["a", "30617:932614571afcbad4d17a191ee281e39eebbb41b93fac8fd87829622aeb112f4d:git.shakespeare.diy/portfoliux"],
["p", "932614571afcbad4d17a191ee281e39eebbb41b93fac8fd87829622aeb112f4d"],
["t", "root"],
["t", "root-revision"],
["subject", "Fix bug in component"],
["r", "abc123..."],
["commit", "def456..."],
["parent-commit", "ghi789..."]
]
}
```
## Testing Relay Synchronization
To test if events are on a relay:
1. **Using nostr.band explorer:**
- Go to https://nostr.band
- Search for your event ID or repository coordinate
- Check which relays have the event
2. **Using console in Shakespeare:**
```javascript
// Check repository announcement
await nostr.query([{
kinds: [30617],
authors: ["your-pubkey"],
"#d": ["your-repo-id"],
limit: 1
}]);
// Check patches
await nostr.query([{
kinds: [1617],
"#a": ["30617:your-pubkey:your-repo-id"],
limit: 10
}]);
```
## Recommended Workflow
### Simplified (Auto-Announce Enabled)
1. **Configure relay** (one time):
- Settings → Select relay (e.g., `wss://relay.nostr.band`)
- This relay will be used for all Nostr git operations
2. **Create patches** (automatic announcement):
- Click "Create Patch"
- System automatically announces repository if needed
- Patch is published with proper references
- Check "Your Patches" section to verify
3. **View in NostrHub:**
- Ensure NostrHub uses same relay
- Browse to Repositories → Find your repository
- View patches in Patches tab
### Manual (If Auto-Announce Fails)
1. **First time setup:**
- Switch to `wss://relay.nostr.band` (widely used)
- Click "Announce Repository" button
- Verify announcement succeeded
2. **Creating patches:**
- Ensure same relay as announcement
- Create patch
- Check console for successful repository lookup
- Verify patch appears in "Your Patches" section
3. **Checking in NostrHub:**
- Ensure NostrHub on same relay
- Browse to Repositories
- Find your repository
- View patches
## Future Improvements Needed
1. **Multi-relay publishing**: Publish to multiple relays automatically
2. **NIP-65 integration**: Use user's relay list
3. **Relay fallback**: Try multiple relays when querying
4. **Relay selection UI**: Easy relay switching before operations
5. **Event verification**: Confirm events were published successfully
6. **Cross-relay search**: Query multiple relays for better discovery
+308
View File
@@ -0,0 +1,308 @@
# Contributing to Upstream Projects
Shakespeare's Git management system now supports contributing to upstream open source projects through automatic forking, even if you don't have push access to the repository.
## How It Works
When you try to create a pull request to a repository where you don't have push permissions, Shakespeare automatically:
1. **Detects your permissions** via the Git host API (GitHub/GitLab)
2. **Checks for an existing fork** under your account
3. **Creates a fork** if one doesn't exist
4. **Configures the PR** to use your fork as the source
5. **Creates the pull request** from `your-fork:branch` → `upstream:main`
This all happens transparently - you just fill out the PR form and click create.
## User Experience
### For Repository Owners (Have Push Access)
If you have push access to the repository:
- Create branches normally
- Push changes directly
- Create PRs within the same repository
- Standard workflow - nothing changes
### For Contributors (No Push Access)
If you don't have push access:
- Make your changes (on any branch, even main/master)
- Open Git Management → Pull Request tab
- Fill out title/description
- Click "Fork & Create PR"
- Shakespeare automatically:
- Creates a feature branch (if you're on main/master)
- Forks the repo (if needed)
- Pushes your branch
- Creates the PR
You'll see a message like:
> "You don't have push access to this repository. Your changes will be pushed to your fork at **username/repo** and a pull request will be created from there."
## Step-by-Step Guide
### 1. Clone an Upstream Repository
```bash
# Clone any open source project in Shakespeare
git clone https://github.com/upstream-org/project.git
```
### 2. Make Your Changes
- Edit files in Shakespeare
- Use AI assistance or manual code editing
- Test your changes
### 3. Commit Your Changes (Optional)
> **Note:** You can skip this step! If you're on the main/master branch, a feature branch will be created automatically when you create the PR.
If you want to create a branch manually:
- Open Git Management → "Branches" tab
- Click "Create Branch"
- Name it something descriptive (e.g., `fix-typo`)
### 4. Create Pull Request
- Go to "Pull Request" tab
- Select target branch (usually `main` or `master`)
- Enter PR title and description
- If you're on main/master: You'll see "A feature branch will be automatically created from your PR title"
- Click "Fork & Create PR" (or just "Create Pull Request" if you have access)
### 5. Done!
- Your fork is created automatically
- Changes are pushed to your fork
- PR is opened from fork to upstream
- You get a link to view the PR
## Automatic Feature Branch Creation
### Why?
Most users will make changes directly on the `main` or `master` branch without realizing they should create a feature branch first. To make contributing easier, Shakespeare automatically creates a feature branch for you when needed.
### When Does This Happen?
When you create a PR and you're currently on `main` or `master`, the system:
1. **Generates a branch name** from your PR title
- Converts to lowercase
- Replaces spaces with hyphens
- Removes special characters
- Adds a unique suffix (timestamp-based)
2. **Creates the branch** from your current position
3. **Checks it out** automatically
4. **Continues with PR creation** on the new branch
### Example
**Your PR title:** "Fix login button styling"
**Generated branch:** `fix-login-button-styling-k7m2`
**What happens:**
```
Before: You're on 'main' with uncommitted changes
After: You're on 'fix-login-button-styling-k7m2' with the same changes
Result: PR created from the feature branch → upstream/main
```
### UI Indicators
You'll see these messages when on main/master:
**Alert Box:**
> You're on the **main** branch. A feature branch will be automatically created from your PR title for this contribution.
**Branch Comparison:**
```
upstream/repo:main ← main
Note: A new branch will be created automatically
```
**Toast Notification:**
> Feature branch created
> Created branch 'fix-login-button-styling-k7m2' for your changes
### What If You Want to Use Your Own Branch?
Simple! Just create a branch manually first:
1. Git Management → Branches tab
2. Click "Create Branch"
3. Name it whatever you want
4. Now create your PR - no auto-branch will be created
### Benefits
- **No Git knowledge needed** - Users don't need to understand branching
- **Best practices enforced** - Never commit directly to main
- **Clean history** - Each PR gets its own branch
- **Easy to understand** - Branch names match PR titles
- **Safe** - Your main branch stays clean
## Behind the Scenes
### Permission Detection
```typescript
// Checks via API if user can push
const canPush = await checkPushPermissions(repo, token);
if (!canPush) {
// Fork workflow
const fork = await ensureFork(repo, token);
// Use fork_owner:branch as head ref
}
```
### Fork Management
- **Checks existing forks first** - doesn't create duplicates
- **Waits for fork to be ready** - GitHub/GitLab need time to fork
- **Configures head ref properly** - `username:branch` format for cross-repo PRs
### API Calls
**GitHub:**
- `GET /repos/{owner}/{repo}` - Check permissions
- `GET /repos/{username}/{repo}` - Check if fork exists
- `POST /repos/{owner}/{repo}/forks` - Create fork
- `POST /repos/{owner}/{repo}/pulls` - Create PR with cross-fork head
**GitLab:**
- `GET /projects/{id}` - Check permissions (access_level >= 30)
- `GET /projects/{username}/{repo}` - Check if fork exists
- `POST /projects/{id}/fork` - Create fork
- `POST /projects/{id}/merge_requests` - Create MR
## Supported Platforms
| Platform | Fork Detection | Fork Creation | Cross-Fork PR | Status |
|----------|---------------|---------------|---------------|--------|
| GitHub | ✅ | ✅ | ✅ | Full |
| GitLab | ✅ | ✅ | ✅ | Full |
| Codeberg | ✅ | ✅ | ✅ | Full |
| Gitea | ✅ | ✅ | ✅ | Full |
## UI Indicators
The system provides clear visual feedback:
### Permission Check
```
⏳ Checking repository permissions...
```
### Fork Notice
```
ℹ️ You don't have push access to this repository.
Your changes will be pushed to your fork at username/repo
and a pull request will be created from there.
```
### Branch Comparison
Shows the full fork relationship:
```
upstream/repo:main ← username/repo:feature-branch
```
### Create Button
Changes based on permissions:
- **Direct access**: "Create Pull Request" with PR icon
- **Fork needed**: "Fork & Create PR" with fork icon
## Authentication
Uses existing Shakespeare Git credentials:
1. **GitHub OAuth** - One-click authentication (Settings → Git)
2. **Personal Access Tokens** - Manual token entry for any platform
Required token scopes:
- **GitHub**: `public_repo` (for public repositories)
- **GitLab**: `api` or `write_repository`
Tokens are stored locally in browser IndexedDB and never sent to Shakespeare servers.
## Troubleshooting
### "No credentials found"
- Add your Git credentials in Settings → Git
- Make sure the token has the right scopes
- Verify the token hasn't expired
### "Failed to create fork"
- Check if you already have a fork (only one fork per user)
- Ensure your token has fork permissions
- Some organizations disable forking - check repo settings
### "Permission denied"
- Your token may have expired or been revoked
- Re-authenticate in Settings → Git
- Check token scopes include repository write access
### Fork exists but PR fails
- Make sure your fork is up to date
- Try pushing your branch manually first
- Check if the branch name conflicts with upstream
## Example Workflow
Contributing a bug fix to an open source project (the easy way):
1. **Clone**: Clone `facebook/react` in Shakespeare
2. **Edit**: Make your fixes (don't worry about branches!)
3. **PR Tab**: Open Git Management → Pull Request
4. **Fill form**:
- Title: "Fix useEffect memory leak in concurrent mode"
- Description: Detailed explanation of the bug and fix
- Target: `main`
5. **Submit**: Click "Fork & Create PR"
6. **Automatic magic**:
- Creates branch: `fix-useeffect-memory-leak-in-concurrent-mode-x7k2`
- Checks out the new branch
- Forks to `yourusername/react`
- Pushes branch to your fork
- Creates PR: `facebook/react:main` ← `yourusername:react:fix-useeffect-memory-leak-in-concurrent-mode-x7k2`
**Total steps for you:** 3 (clone, edit, submit)
**Total steps Shakespeare handles:** 6 (branch, fork, push, configure remotes, create PR)
## Integration with Existing Features
This fork workflow integrates seamlessly with existing Git features:
- **Branch Management** - Create/switch/delete branches as usual
- **Diff Viewer** - Review changes before creating PR
- **Compare View** - Compare branches and commits
- **Git Credentials** - Uses existing auth system
- **Remote Management** - Works with origin/upstream remotes
No new settings or configuration needed - it just works when you try to contribute to repos where you don't have push access.
## Privacy & Security
- **No server involvement** - All Git operations happen in your browser
- **Local token storage** - Tokens stored in IndexedDB, never sent to Shakespeare
- **Minimal API calls** - Only checks permissions when needed
- **Read-only checks** - Permission detection doesn't modify anything
- **User confirmation** - Always shows what will happen before forking
## Future Enhancements
Potential improvements:
- Conflict resolution UI when upstream has changed
- Sync fork with upstream (rebase/merge)
- Multi-commit PRs with better history
- Draft PR support
- PR templates
- Reviewer/assignee selection
-544
View File
@@ -1,544 +0,0 @@
# Unified OAuth System
Shakespeare implements a unified OAuth 2.0 authentication system that supports multiple providers with a consistent API. This document explains how the system works and how to add new OAuth providers.
## Architecture
The OAuth system consists of three main components:
1. **Generic OAuth Hook** (`useOAuth`) - Core OAuth logic that works with any provider
2. **Provider-Specific Hooks** - Thin wrappers that configure the generic hook for specific providers
3. **OAuth Callback Pages** - React components that handle the OAuth redirect flow
### Current Supported Providers
- **GitHub** - Git repository hosting (with PKCE support)
- **Netlify** - Static site deployment
- **Vercel** - Static site deployment
## File Structure
```
src/
├── hooks/
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
│ └── useVercelOAuth.ts # Vercel-specific configuration
├── pages/
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
│ └── VercelOAuth.tsx # Vercel OAuth callback page
└── AppRouter.tsx # Routes for OAuth callbacks
```
## Environment Variables
OAuth credentials are stored in environment variables and loaded from `process.env`:
```bash
# GitHub OAuth Configuration
VITE_GITHUB_OAUTH_CLIENT_ID="your_github_client_id"
VITE_GITHUB_OAUTH_CLIENT_SECRET="your_github_client_secret"
# Netlify OAuth Configuration
VITE_NETLIFY_OAUTH_CLIENT_ID="your_netlify_client_id"
VITE_NETLIFY_OAUTH_CLIENT_SECRET="your_netlify_client_secret"
# Vercel OAuth Configuration
VITE_VERCEL_OAUTH_CLIENT_ID="your_vercel_client_id"
VITE_VERCEL_OAUTH_CLIENT_SECRET="your_vercel_client_secret"
```
### Security Note
**Client secrets are stored in environment variables** and bundled into the client-side JavaScript. This is necessary because the OAuth flow runs entirely in the browser. While this approach is less secure than a traditional server-side OAuth flow, it's acceptable for this use case because:
1. Shakespeare is a client-side application with no backend
2. The OAuth tokens are scoped to specific permissions
3. Users can revoke tokens at any time from the provider's settings
4. The redirect URIs are validated by the OAuth provider
For production deployments, consider using a serverless function or backend service to handle the token exchange step, keeping client secrets secure.
## How It Works
### 1. Generic OAuth Hook (`useOAuth`)
The `useOAuth` hook implements the OAuth 2.0 authorization code flow with optional PKCE (Proof Key for Code Exchange) support. It accepts a configuration object and returns methods to initiate and handle the OAuth flow.
**Configuration Interface:**
```typescript
interface OAuthConfig {
provider: 'github' | 'netlify' | 'vercel'; // Provider identifier
clientId: string; // OAuth client ID
clientSecret: string; // OAuth client secret
authorizeUrl: string; // Provider's authorization endpoint
tokenUrl: string; // Provider's token exchange endpoint
scope?: string; // Requested OAuth scopes (optional)
redirectUri: string; // Callback URL after authorization
usePKCE?: boolean; // Enable PKCE (default: false)
getUserInfo?: ( // Optional function to fetch user info
accessToken: string,
corsProxy: string
) => Promise<{
username: string;
[key: string]: unknown;
}>;
}
```
**Returned API:**
```typescript
{
isLoading: boolean; // True during token exchange
error: string | null; // Error message if OAuth fails
isOAuthConfigured: boolean; // True if client ID and secret are set
initiateOAuth: () => void; // Start the OAuth flow
handleCallback: ( // Handle the OAuth callback
code: string,
state: string
) => Promise<OAuthResult | null>;
}
```
### 2. OAuth Flow Steps
#### Step 1: Initiate OAuth
When the user clicks "Connect to [Provider]", the `initiateOAuth()` function:
1. Generates a random `state` parameter for CSRF protection
2. Optionally generates PKCE parameters (code verifier and challenge)
3. Stores the state and code verifier in localStorage
4. Redirects to the provider's authorization page
```typescript
const { initiateOAuth } = useGitHubOAuth();
// User clicks button
<Button onClick={initiateOAuth}>Connect to GitHub</Button>
```
#### Step 2: User Authorizes
The user is redirected to the provider's authorization page where they:
1. Log in to their account (if not already logged in)
2. Review the requested permissions
3. Approve or deny the authorization request
#### Step 3: OAuth Callback
After authorization, the provider redirects back to the callback URL with:
- `code` - Authorization code
- `state` - The state parameter we sent
- `error` (optional) - Error code if authorization failed
- `error_description` (optional) - Human-readable error description
The callback page (e.g., `GitHubOAuth.tsx`) extracts these parameters and calls `handleCallback()`.
#### Step 4: Token Exchange
The `handleCallback()` function:
1. Verifies the `state` parameter matches what we stored
2. Retrieves the PKCE code verifier (if PKCE is enabled)
3. Exchanges the authorization code for an access token
4. Optionally fetches user information using the access token
5. Returns an `OAuthResult` object with the token and user data
```typescript
interface OAuthResult {
accessToken: string; // OAuth access token
username?: string; // User's username/email
scopes?: string[]; // Granted OAuth scopes
userData?: Record<string, unknown>; // Additional user data
}
```
#### Step 5: Store Credentials
Provider-specific hooks override `handleCallback` to store the credentials appropriately:
- **GitHub**: Stores in Git settings (for push/pull operations)
- **Netlify/Vercel**: Stores in Deploy settings (for deployment operations)
### 3. PKCE Support
PKCE (Proof Key for Code Exchange) adds an extra layer of security to the OAuth flow by preventing authorization code interception attacks. It's recommended for public clients like browser-based apps.
**How PKCE works:**
1. Generate a random `code_verifier` (cryptographically random string)
2. Create a `code_challenge` by hashing the verifier with SHA-256
3. Send the `code_challenge` during authorization
4. Send the `code_verifier` during token exchange
5. The server verifies that the verifier matches the challenge
**Enabling PKCE:**
```typescript
const config: OAuthConfig = {
// ... other config
usePKCE: true, // Enable PKCE
};
```
**Provider Support:**
- ✅ GitHub - Supports PKCE (enabled)
- ❌ Netlify - Doesn't support PKCE (disabled)
- ❌ Vercel - Doesn't support PKCE (disabled)
### Scope Parameter
The `scope` parameter is optional in the OAuth configuration. Some providers (like Netlify) don't use scopes in the authorization request - instead, permissions are configured when you create the OAuth application in the provider's settings.
**Provider Scope Usage:**
- ✅ GitHub - Uses scopes (e.g., `repo workflow`)
- ❌ Netlify - No scope parameter (permissions set in app settings)
- ✅ Vercel - Uses scopes (e.g., `deployments:write projects:read`)
## Adding a New OAuth Provider
To add a new OAuth provider, follow these steps:
### 1. Add Environment Variables
Add the client ID and secret to `.env.example`:
```bash
# NewProvider OAuth Configuration
VITE_NEWPROVIDER_OAUTH_CLIENT_ID="********************"
VITE_NEWPROVIDER_OAUTH_CLIENT_SECRET="****************************************"
```
### 2. Create Provider-Specific Hook
Create a new file `src/hooks/useNewProviderOAuth.ts`:
```typescript
import { useCallback } from 'react';
import { useOAuth, type OAuthConfig, type OAuthResult } from './useOAuth';
import { proxyUrl } from '@/lib/proxyUrl';
interface NewProviderUserInfo {
id: string;
email: string;
// ... other user fields
}
export function useNewProviderOAuth() {
// Get the context where you want to store credentials
// e.g., useDeploySettings() or useGitSettings()
const { setProviders, settings } = useDeploySettings();
const config: OAuthConfig = {
provider: 'newprovider',
clientId: import.meta.env.VITE_NEWPROVIDER_OAUTH_CLIENT_ID || '',
clientSecret: import.meta.env.VITE_NEWPROVIDER_OAUTH_CLIENT_SECRET || '',
authorizeUrl: 'https://provider.com/oauth/authorize',
tokenUrl: 'https://provider.com/oauth/token',
scope: 'read write', // Optional - omit if provider doesn't use scopes
redirectUri: window.location.origin + '/oauth/newprovider',
usePKCE: false, // Set to true if provider supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.provider.com/user');
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
},
});
if (!userResponse.ok) {
throw new Error(`Failed to verify token: ${userResponse.statusText}`);
}
const userData: NewProviderUserInfo = await userResponse.json();
return {
username: userData.email,
...userData,
};
},
};
const oauth = useOAuth(config);
const handleCallbackAndStore = useCallback(async (
code: string,
state: string
): Promise<boolean> => {
const result: OAuthResult | null = await oauth.handleCallback(code, state);
if (!result) {
return false;
}
// Store the credentials in the appropriate context
// This will vary based on what the provider is used for
const newProvider = {
id: crypto.randomUUID(),
name: result.username ? `NewProvider (${result.username})` : 'NewProvider',
type: 'newprovider',
apiKey: result.accessToken,
proxy: true,
};
setProviders([...settings.providers, newProvider]);
return true;
}, [oauth, setProviders, settings.providers]);
return {
...oauth,
handleCallback: handleCallbackAndStore,
};
}
```
### 3. Create OAuth Callback Page
Create a new file `src/pages/NewProviderOAuth.tsx`:
```typescript
import { useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useNewProviderOAuth } from '@/hooks/useNewProviderOAuth';
import { useToast } from '@/hooks/useToast';
import { Card, CardContent } from '@/components/ui/card';
export default function NewProviderOAuth() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { handleCallback } = useNewProviderOAuth();
const { toast } = useToast();
useEffect(() => {
const code = searchParams.get('code');
const state = searchParams.get('state');
const error = searchParams.get('error');
const errorDescription = searchParams.get('error_description');
const storedState = localStorage.getItem('newprovider_oauth_state');
if (error) {
toast({
title: "NewProvider OAuth Error",
description: errorDescription || error,
variant: "destructive",
});
navigate('/settings/deploy'); // or appropriate settings page
return;
}
if (code && state && storedState) {
handleCallback(code, state).then((success) => {
if (success) {
toast({
title: "NewProvider Connected",
description: "Successfully connected to NewProvider.",
});
} else {
toast({
title: "Connection Failed",
description: "Failed to connect to NewProvider. Please try again.",
variant: "destructive",
});
}
navigate('/settings/deploy'); // or appropriate settings page
});
} else {
navigate('/settings/deploy');
}
}, [searchParams, handleCallback, toast, navigate]);
return (
<div className="min-h-screen flex items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardContent className="py-12 px-8 text-center">
<div className="space-y-6">
{/* Provider logo/icon */}
<div className="flex justify-center">
<svg className="h-12 w-12 text-primary" viewBox="0 0 24 24">
{/* Provider icon SVG */}
</svg>
</div>
<div className="space-y-2">
<h1 className="text-xl font-semibold">Connecting to NewProvider</h1>
<p className="text-muted-foreground">
Processing your NewProvider authentication...
</p>
</div>
<div className="flex justify-center">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
```
### 4. Add Route
Add the OAuth callback route to `src/AppRouter.tsx`:
```typescript
import NewProviderOAuth from "./pages/NewProviderOAuth";
// ...
<Route path="/oauth/newprovider" element={<NewProviderOAuth />} />
```
### 5. Add to UI
Add the provider to the appropriate settings page (e.g., `DeploySettings.tsx`):
```typescript
import { useNewProviderOAuth } from '@/hooks/useNewProviderOAuth';
// In component:
const newProviderOAuth = useNewProviderOAuth();
// In PRESET_PROVIDERS array:
{
id: 'newprovider',
type: 'newprovider',
name: 'NewProvider',
description: 'Deploy to NewProvider',
apiKeyLabel: 'Access Token',
apiKeyURL: 'https://provider.com/settings/tokens',
proxy: true,
}
// In the render logic, add the OAuth hook to the switch:
const oauthHook = preset.type === 'netlify' ? netlifyOAuth :
preset.type === 'vercel' ? vercelOAuth :
preset.type === 'newprovider' ? newProviderOAuth : null;
```
### 6. Register OAuth Application
Register your OAuth application with the provider:
1. Go to the provider's developer settings
2. Create a new OAuth application
3. Set the **redirect URI** to: `https://yourdomain.com/oauth/newprovider`
4. Note the **client ID** and **client secret**
5. Add them to your `.env` file
## Testing OAuth Flow
To test the OAuth flow locally:
1. **Set up a tunnel** (e.g., ngrok, cloudflared) to expose localhost:
```bash
npx cloudflared tunnel --url http://localhost:5173
```
2. **Register OAuth app** with the tunnel URL as the redirect URI:
```
https://your-tunnel-url.trycloudflare.com/oauth/provider
```
3. **Add credentials** to `.env`:
```bash
VITE_PROVIDER_OAUTH_CLIENT_ID="your_client_id"
VITE_PROVIDER_OAUTH_CLIENT_SECRET="your_client_secret"
```
4. **Start the dev server**:
```bash
npm run dev
```
5. **Test the flow** by clicking the "Connect to Provider" button
## Error Handling
The OAuth system handles several types of errors:
### User Denies Authorization
If the user denies authorization, the provider redirects with an `error` parameter:
```
/oauth/provider?error=access_denied&error_description=User+denied+access
```
The callback page displays an error toast and redirects to settings.
### Invalid State Parameter
If the `state` parameter doesn't match what we stored (CSRF attack), the flow is aborted and an error is shown.
### Token Exchange Failure
If the token exchange fails (invalid code, expired, etc.), an error is logged and shown to the user.
### Missing PKCE Verifier
If PKCE is enabled but the code verifier is missing from localStorage, the flow is aborted.
## Security Considerations
1. **State Parameter**: Always used for CSRF protection
2. **PKCE**: Used when supported by the provider for additional security
3. **HTTPS Only**: OAuth should only be used over HTTPS in production
4. **Token Storage**: Tokens are stored in browser storage (localStorage/IndexedDB)
5. **Token Revocation**: Users can revoke tokens from the provider's settings
6. **Scope Limitation**: Request only the minimum required scopes
## Troubleshooting
### "OAuth client ID not configured"
The environment variables are not set. Check your `.env` file and ensure the variables are prefixed with `VITE_`.
### "Invalid OAuth state parameter"
The state parameter doesn't match. This could be caused by:
- Multiple OAuth flows running simultaneously
- Browser localStorage being cleared mid-flow
- CSRF attack attempt
### "Failed to verify token"
The provider's API rejected the access token. This could be caused by:
- Incorrect API endpoint URL
- Token doesn't have required scopes
- Provider API is down
### Redirect URI Mismatch
The redirect URI in your OAuth app registration must exactly match the URI in your code:
```typescript
redirectUri: window.location.origin + '/oauth/provider'
```
For local development with a tunnel, this would be:
```
https://your-tunnel-url.trycloudflare.com/oauth/provider
```
## Best Practices
1. **Always use PKCE** when the provider supports it
2. **Request minimal scopes** - only what you need
3. **Handle errors gracefully** - show user-friendly error messages
4. **Clear localStorage** on errors to prevent stuck states
5. **Validate tokens** by fetching user info after exchange
6. **Store tokens securely** - use appropriate browser storage APIs
7. **Provide token revocation** - link to provider's token management page
8. **Test error cases** - user denial, network failures, etc.
## Future Improvements
Potential enhancements to the OAuth system:
1. **Token Refresh**: Implement refresh token flow for long-lived sessions
2. **Token Expiry**: Track token expiration and prompt for re-authentication
3. **Multiple Accounts**: Support multiple accounts per provider
4. **Backend Proxy**: Optional backend service for secure token exchange
5. **Device Flow**: Support OAuth device flow for CLI tools
6. **Biometric Auth**: Integrate with WebAuthn for passwordless OAuth
-1
View File
@@ -10,7 +10,6 @@
<meta property="og:type" content="website">
<meta property="og:title" content="Shakespeare - Open Source AI Builder">
<meta property="og:description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
<meta property="og:image" content="https://shakespeare.diy/og-image.png">
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
+168 -1254
View File
File diff suppressed because it is too large. Load diff
+1 -6
View File
@@ -52,8 +52,6 @@
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"@webpm/store": "file:../webpm/packages/store",
"@webpm/webpm": "file:../webpm/packages/webpm",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -61,7 +59,6 @@
"decimal.js": "^10.6.0",
"embla-carousel-react": "^8.3.0",
"esbuild-wasm": "^0.25.8",
"fflate": "^0.8.2",
"i18next": "^25.5.2",
"ignore": "^7.0.5",
"input-otp": "^1.2.4",
@@ -69,7 +66,6 @@
"jsonc-parser": "^3.3.1",
"jszip": "^3.10.1",
"lucide-react": "^0.525.0",
"mime": "^4.1.0",
"nostr-tools": "^2.15.2",
"openai": "^5.15.0",
"path-browserify": "^1.0.1",
@@ -89,12 +85,10 @@
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"tailwindcss-safe-area": "^0.8.0",
"tar-stream": "^3.1.7",
"turndown": "^7.2.1",
"uri-templates": "^0.2.0",
"use-stick-to-bottom": "^1.1.1",
"vaul": "^0.9.3",
"vite-plugin-node-polyfills": "^0.24.0",
"webln": "^0.3.2",
"zod": "^3.25.76"
},
@@ -123,6 +117,7 @@
"globals": "^15.9.0",
"jsdom": "^26.1.0",
"postcss": "^8.4.47",
"svelte": "^5.40.1",
"tailwindcss": "^3.4.11",
"typescript": "^5.5.3",
"typescript-eslint": "^8.0.1",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

+12 -15
View File
@@ -14,7 +14,6 @@ import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import { AISettingsProvider } from '@/components/AISettingsProvider';
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
import { DeploySettingsProvider } from '@/components/DeploySettingsProvider';
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
import { FSProvider } from '@/components/FSProvider';
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
@@ -42,11 +41,11 @@ const queryClient = new QueryClient({
const defaultConfig: AppConfig = {
theme: "system",
relayUrl: "wss://relay.ditto.pub",
relayUrl: "wss://relay.primal.net",
projectTemplate: "https://gitlab.com/soapbox-pub/mkstack.git",
deployServer: "shakespeare.wtf",
esmUrl: "https://esm.shakespeare.diy",
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
faviconUrl: "https://external-content.duckduckgo.com/ip3/{hostname}.ico",
previewDomain: "local-shakespeare.dev",
showcaseEnabled: true,
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
@@ -54,7 +53,7 @@ const defaultConfig: AppConfig = {
};
const presetRelays = [
{ url: 'wss://relay.ditto.pub', name: 'Ditto' },
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
{ url: 'wss://relay.damus.io', name: 'Damus' },
{ url: 'wss://relay.primal.net', name: 'Primal' },
@@ -88,17 +87,15 @@ export function App() {
<NostrProvider>
<AISettingsProvider>
<GitSettingsProvider>
<DeploySettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
</DeploySettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
</GitSettingsProvider>
</AISettingsProvider>
</NostrProvider>
-6
View File
@@ -10,14 +10,11 @@ import Preferences from "./pages/Preferences";
import NostrSettings from "./pages/NostrSettings";
import AISettings from "./pages/AISettings";
import GitSettings from "./pages/GitSettings";
import DeploySettings from "./pages/DeploySettings";
import SystemSettings from "./pages/SystemSettings";
import StorageSettings from "./pages/StorageSettings";
import AboutSettings from "./pages/AboutSettings";
import GitHubOAuth from "./pages/GitHubOAuth";
import NetlifyOAuth from "./pages/NetlifyOAuth";
import VercelOAuth from "./pages/VercelOAuth";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
@@ -33,15 +30,12 @@ export function AppRouter() {
<Route path="/" element={<Index />} />
<Route path="/clone" element={<Clone />} />
<Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
<Route path="/oauth/vercel" element={<VercelOAuth />} />
<Route path="/settings" element={<SettingsLayout />}>
<Route index element={<Settings />} />
<Route path="preferences" element={<Preferences />} />
<Route path="nostr" element={<NostrSettings />} />
<Route path="ai" element={<AISettings />} />
<Route path="git" element={<GitSettings />} />
<Route path="deploy" element={<DeploySettings />} />
<Route path="system" element={<SystemSettings />} />
<Route path="storage" element={<StorageSettings />} />
<Route path="about" element={<AboutSettings />} />
@@ -182,4 +182,36 @@ describe('AISettingsProvider', () => {
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-models'] });
});
it('should not invalidate provider-models query when updateSettings is called without providers', async () => {
// Mock the QueryClient.invalidateQueries method
const mockInvalidateQueries = vi.fn();
// Create a custom TestApp that mocks the query client
const MockedTestApp = ({ children }: { children: React.ReactNode }) => {
const queryClient = useQueryClient();
vi.spyOn(queryClient, 'invalidateQueries').mockImplementation(mockInvalidateQueries);
return <>{children}</>;
};
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<MockedTestApp>{children}</MockedTestApp>
</TestApp>
),
});
await waitFor(() => {
expect(result.current.settings.recentlyUsedModels).toEqual([]);
});
act(() => {
result.current.updateSettings({
recentlyUsedModels: ['test-model']
});
});
expect(mockInvalidateQueries).not.toHaveBeenCalled();
});
});
+1 -19
View File
@@ -12,11 +12,9 @@ import {
MessageSquarePlus,
History,
Folder,
Rocket,
} from 'lucide-react';
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
import { GitDialog } from '@/components/GitDialog';
import { DeployDialog } from '@/components/DeployDialog';
interface ActionsMenuProps {
projectId: string;
@@ -31,7 +29,7 @@ interface ActionsMenuProps {
export function ActionsMenu({
projectId,
projectName,
projectName: _projectName,
onNewChat,
onProjectDetails,
isLoading = false,
@@ -41,7 +39,6 @@ export function ActionsMenu({
}: ActionsMenuProps) {
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
const [gitDialogOpen, setGitDialogOpen] = useState(false);
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
const isAnyLoading = isLoading || isBuildLoading;
@@ -89,15 +86,6 @@ export function ActionsMenu({
Repository
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setDeployDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<Rocket className="h-4 w-4" />
Deploy
</DropdownMenuItem>
<DropdownMenuItem
onClick={onProjectDetails}
disabled={isAnyLoading}
@@ -124,12 +112,6 @@ export function ActionsMenu({
onOpenChange={setGitHistoryOpen}
/>
<DeployDialog
projectId={projectId}
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
/>
</>
);
+1 -1
View File
@@ -19,9 +19,9 @@ const AppConfigSchema = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
projectTemplate: z.string().url(),
deployServer: z.string().min(1),
esmUrl: z.string().url(),
corsProxy: z.string().url(),
faviconUrl: z.string().url(),
previewDomain: z.string().min(1),
language: z.string(),
showcaseEnabled: z.boolean(),
+131 -469
View File
@@ -1,520 +1,182 @@
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Rocket, ExternalLink, AlertCircle } from 'lucide-react';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { useDeploySettings } from '@/hooks/useDeploySettings';
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useFS } from '@/hooks/useFS';
import { useToast } from '@/hooks/useToast';
import { useAppContext } from '@/hooks/useAppContext';
import { useNostr } from '@nostrify/react';
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy';
import { Link } from 'react-router-dom';
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider } from '@/contexts/DeploySettingsContext';
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
/**
* Helper function to get provider URL for favicon
*/
function getProviderUrl(provider: DeployProvider): string | null {
switch (provider.type) {
case 'shakespeare':
if (provider.host) {
return `https://${provider.host}`;
}
return 'https://shakespeare.diy';
case 'netlify':
if (provider.baseURL) {
return provider.baseURL;
}
return 'https://netlify.com';
case 'vercel':
if (provider.baseURL) {
return provider.baseURL;
}
return 'https://vercel.com';
case 'nsite':
return null;
default:
return null;
}
}
/**
* Render provider icon using favicon or fallback
*/
function renderProviderIcon(provider: DeployProvider, size = 14) {
const url = getProviderUrl(provider);
if (url) {
return (
<ExternalFavicon
url={url}
size={size}
fallback={<Rocket size={size} />}
/>
);
}
return <Rocket size={size} />;
}
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useMutation } from '@tanstack/react-query';
import { deployProject } from '@/lib/deploy';
import { useFS } from '@/hooks/useFS';
import {
CloudUpload,
Loader2,
} from 'lucide-react';
interface DeployDialogProps {
projectId: string;
projectName: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onFirstInteraction?: () => void;
}
interface ShakespeareFormData {
subdomain: string;
}
interface NsiteFormData {
nsec: string;
}
interface NetlifyFormData {
siteId: string;
siteName: string;
}
interface VercelFormData {
projectName: string;
teamId: string;
}
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
const { t } = useTranslation();
const { settings } = useDeploySettings();
const { settings: projectSettings, updateSettings: updateProjectSettings } = useProjectDeploySettings(projectId);
export function DeployDialog({
projectId,
projectName,
open,
onOpenChange,
onFirstInteraction
}: DeployDialogProps) {
const { config } = useAppContext();
const { user } = useCurrentUser();
const { fs } = useFS();
const { config } = useAppContext();
const { nostr } = useNostr();
const { toast } = useToast();
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
const [isDeploying, setIsDeploying] = useState(false);
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
const [error, setError] = useState<string | null>(null);
// State for the deploy URL input
const [deployUrl, setDeployUrl] = useState('');
// Provider-specific form data
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
subdomain: projectId,
});
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
nsec: '',
});
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
siteId: '',
siteName: '',
});
const [vercelForm, setVercelForm] = useState<VercelFormData>({
projectName: projectName || projectId,
teamId: '',
});
// Load project settings when dialog opens
// Initialize deploy URL when dialog opens
useEffect(() => {
if (open) {
// First, try to use the currentProvider from project settings
if (projectSettings.currentProvider && settings.providers.some(p => p.id === projectSettings.currentProvider)) {
setSelectedProviderId(projectSettings.currentProvider);
} else {
// Otherwise, find the first configured provider in project settings
const providerIds = Object.keys(projectSettings.providers);
if (providerIds.length > 0) {
setSelectedProviderId(providerIds[0]);
}
}
setDeployUrl(`${projectId}.${config.deployServer}`);
}
}, [open, projectSettings, settings.providers]);
}, [open, projectId, config.deployServer]);
const selectedProvider = settings.providers.find(p => p.id === selectedProviderId);
const handleDeploy = async () => {
if (!selectedProvider) return;
setIsDeploying(true);
setError(null);
setDeployResult(null);
try {
const projectPath = `/projects/${projectId}`;
let adapter: DeployAdapter;
if (selectedProvider.type === 'shakespeare') {
if (!user) {
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
}
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
adapter = new ShakespeareAdapter({
fs,
signer: user.signer,
host: shakespeareProvider.host,
subdomain: shakespeareForm.subdomain || undefined,
corsProxy: shakespeareProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'nsite') {
const nsiteProvider = selectedProvider as import('@/contexts/DeploySettingsContext').NsiteProvider;
if (!nsiteForm.nsec) {
throw new Error('Site private key (nsec) is required');
}
adapter = new NsiteAdapter({
fs,
nostr,
nsec: nsiteForm.nsec,
gateway: nsiteProvider.gateway,
relayUrls: nsiteProvider.relayUrls,
blossomServers: nsiteProvider.blossomServers,
});
} else if (selectedProvider.type === 'netlify') {
const netlifyProvider = selectedProvider as NetlifyProvider;
if (!netlifyProvider.apiKey) {
throw new Error('Netlify API key is required');
}
// If siteId is empty, we're creating a new site, so only pass siteName
// If siteId is set, we're updating an existing site
adapter = new NetlifyAdapter({
fs,
apiKey: netlifyProvider.apiKey,
baseURL: netlifyProvider.baseURL,
siteName: netlifyForm.siteId ? undefined : (netlifyForm.siteName || undefined),
siteId: netlifyForm.siteId || undefined,
corsProxy: netlifyProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'vercel') {
const vercelProvider = selectedProvider as VercelProvider;
if (!vercelProvider.apiKey) {
throw new Error('Vercel API key is required');
}
adapter = new VercelAdapter({
fs,
apiKey: vercelProvider.apiKey,
baseURL: vercelProvider.baseURL,
teamId: vercelForm.teamId || undefined,
projectName: vercelForm.projectName || undefined,
corsProxy: vercelProvider.proxy ? config.corsProxy : undefined,
});
} else {
throw new Error('Unknown provider type');
const deployMutation = useMutation({
mutationFn: async () => {
if (!user) {
throw new Error("You must be logged into Nostr to deploy a project");
}
const result = await adapter.deploy({
projectId,
projectPath,
// Parse the deploy URL to extract hostname and server
const hostname = deployUrl.trim();
const parts = hostname.split('.');
if (parts.length < 2) {
throw new Error("Invalid deploy URL format. Please use format: subdomain.domain.com");
}
// Extract the deploy server (everything after the first dot)
const deployServer = parts.slice(1).join('.');
return await deployProject({
fs,
projectId, // Keep the original projectId for file path
deployServer,
projectPath: `/projects/${projectId}`,
signer: user.signer,
customHostname: hostname, // Pass the custom hostname
});
},
onSuccess: (result) => {
toast({
title: "Deployment successful!",
description: `Your project is now live at ${result.hostname}`,
});
// Save project-specific settings (updateSettings now automatically sets currentProvider)
if (selectedProvider.type === 'shakespeare') {
await updateProjectSettings(selectedProviderId, {
type: 'shakespeare',
data: {
subdomain: shakespeareForm.subdomain || undefined,
},
});
} else if (selectedProvider.type === 'nsite') {
await updateProjectSettings(selectedProviderId, {
type: 'nsite',
data: {
nsec: nsiteForm.nsec,
},
});
} else if (selectedProvider.type === 'netlify') {
await updateProjectSettings(selectedProviderId, {
type: 'netlify',
data: {
siteId: result.metadata?.siteId as string | undefined,
},
});
} else if (selectedProvider.type === 'vercel') {
await updateProjectSettings(selectedProviderId, {
type: 'vercel',
data: {
teamId: vercelForm.teamId || undefined,
projectId: vercelForm.projectName || undefined,
},
});
}
// Open the deployed site in a new tab
window.open(result.url, '_blank');
setDeployResult(result);
} catch (err) {
setError(err instanceof Error ? err.message : 'Deployment failed');
} finally {
setIsDeploying(false);
// Close the dialog
onOpenChange(false);
},
onError: (error) => {
toast({
title: "Deployment failed",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
},
});
const handleDeploy = () => {
if (onFirstInteraction) {
onFirstInteraction();
}
deployMutation.mutate();
};
const handleClose = () => {
setSelectedProviderId('');
setDeployResult(null);
setError(null);
// Reset forms
setShakespeareForm({ subdomain: projectId });
setNsiteForm({ nsec: '' });
setNetlifyForm({ siteId: '', siteName: '' });
setVercelForm({ projectName: projectName || projectId, teamId: '' });
onOpenChange(false);
const handleUrlChange = (value: string) => {
// Remove protocol if user enters it
const cleanValue = value.replace(/^https?:\/\//, '');
setDeployUrl(cleanValue);
};
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
setShakespeareForm({ subdomain });
}, []);
const handleNsiteNsecChange = useCallback((nsec: string) => {
setNsiteForm({ nsec });
}, []);
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
setNetlifyForm({ siteId, siteName });
}, []);
const handleVercelConfigChange = useCallback((projectName: string, teamId: string) => {
setVercelForm({ projectName, teamId });
}, []);
const renderProviderFields = () => {
if (!selectedProvider) return null;
if (selectedProvider.type === 'shakespeare') {
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
return (
<ShakespeareDeployForm
host={shakespeareProvider.host}
projectId={projectId}
onSubdomainChange={handleShakespeareSubdomainChange}
/>
);
}
if (selectedProvider.type === 'nsite') {
const savedConfig = projectSettings.providers[selectedProviderId];
const savedNsec = savedConfig?.type === 'nsite' ? savedConfig.data.nsec : undefined;
return (
<NsiteDeployForm
gateway={selectedProvider.gateway}
savedNsec={savedNsec}
onNsecChange={handleNsiteNsecChange}
/>
);
}
if (selectedProvider.type === 'netlify') {
const savedConfig = projectSettings.providers[selectedProviderId];
const savedSiteId = savedConfig?.type === 'netlify' ? savedConfig.data.siteId : undefined;
return (
<NetlifyDeployForm
apiKey={selectedProvider.apiKey}
baseURL={selectedProvider.baseURL}
projectId={projectId}
projectName={projectName}
savedSiteId={savedSiteId}
onSiteChange={handleNetlifySiteChange}
corsProxy={selectedProvider.proxy ? config.corsProxy : undefined}
/>
);
}
if (selectedProvider.type === 'vercel') {
const savedConfig = projectSettings.providers[selectedProviderId];
const savedTeamId = savedConfig?.type === 'vercel' ? savedConfig.data.teamId : undefined;
const savedProjectName = savedConfig?.type === 'vercel' ? savedConfig.data.projectId : undefined;
return (
<VercelDeployForm
projectId={projectId}
projectName={projectName}
savedTeamId={savedTeamId}
savedProjectName={savedProjectName}
onConfigChange={handleVercelConfigChange}
/>
);
}
return null;
const isValidUrl = () => {
const trimmed = deployUrl.trim();
return trimmed.length > 0 && trimmed.includes('.') && !trimmed.startsWith('.') && !trimmed.endsWith('.');
};
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[500px]">
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Rocket className="h-5 w-5" />
Deploy Project
<CloudUpload className="h-5 w-5" />
Deploy "{projectName}"
</DialogTitle>
<DialogDescription>
Deploy your project to a hosting platform
</DialogDescription>
</DialogHeader>
{deployResult ? (
<div className="space-y-4">
<Alert>
<Rocket className="h-4 w-4" />
<AlertDescription>
Your project has been successfully deployed!
</AlertDescription>
</Alert>
<div className="space-y-2">
<Label>Deployed URL</Label>
<div className="flex gap-2">
<Input
value={deployResult.url}
readOnly
className="flex-1"
/>
<Button
size="sm"
variant="outline"
onClick={() => window.open(deployResult.url, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<div className="flex justify-end gap-2">
<Button onClick={handleClose}>
{t('close')}
</Button>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="deploy-url">Deploy URL</Label>
<div className="relative">
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground">
https://
</span>
<Input
id="deploy-url"
value={deployUrl}
onChange={(e) => handleUrlChange(e.target.value)}
placeholder={`${projectId}.${config.deployServer}`}
className="pl-16"
disabled={deployMutation.isPending}
/>
</div>
<p className="text-xs text-muted-foreground">
Your project will be deployed to this URL. You can customize the subdomain.
</p>
</div>
) : (
<div className="space-y-4">
{settings.providers.length === 0 ? (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
No deployment providers configured.{' '}
<Link
to="/settings/deploy"
className="underline hover:no-underline"
onClick={handleClose}
>
Configure deployment settings
</Link>
</AlertDescription>
</Alert>
{!user && (
<div className="p-3 bg-muted rounded-lg">
<p className="text-sm text-muted-foreground">
You must be logged into Nostr to deploy projects.
</p>
</div>
)}
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={deployMutation.isPending}
>
Cancel
</Button>
<Button
onClick={handleDeploy}
disabled={!user || !isValidUrl() || deployMutation.isPending}
className="gap-2"
>
{deployMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<>
<div className="space-y-2">
<Label htmlFor="provider">Select Provider</Label>
<Select value={selectedProviderId} onValueChange={setSelectedProviderId}>
<SelectTrigger id="provider">
{selectedProvider ? (
<div className="flex items-center gap-2">
{renderProviderIcon(selectedProvider, 14)}
<span>{selectedProvider.name}</span>
</div>
) : (
<SelectValue placeholder="Choose a deployment provider..." />
)}
</SelectTrigger>
<SelectContent>
{settings.providers.map((provider) => (
<SelectItem key={provider.id} value={provider.id}>
<div className="flex items-center gap-2">
{renderProviderIcon(provider, 14)}
<span>{provider.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedProvider && renderProviderFields()}
{selectedProvider?.type === 'shakespeare' && !user && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
You must be logged in with Nostr to use Shakespeare Deploy.{' '}
<Link
to="/settings/nostr"
className="underline hover:no-underline"
onClick={handleClose}
>
Go to Nostr Settings
</Link>
</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={handleClose}>
{t('cancel')}
</Button>
<Button
onClick={handleDeploy}
disabled={
!selectedProvider ||
isDeploying ||
(selectedProvider.type === 'shakespeare' && !user) ||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName)
}
>
{isDeploying ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
Deploying...
</>
) : (
<>
<Rocket className="h-4 w-4 mr-2" />
Deploy
</>
)}
</Button>
</div>
</>
<CloudUpload className="h-4 w-4" />
)}
</div>
)}
{deployMutation.isPending ? 'Deploying...' : 'Deploy'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
}
-80
View File
@@ -1,80 +0,0 @@
import { useState, useEffect, useMemo, type ReactNode } from 'react';
import { DeploySettingsContext, type DeploySettings, type DeployProvider } from '@/contexts/DeploySettingsContext';
import { useFS } from '@/hooks/useFS';
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
const DEFAULT_SETTINGS: DeploySettings = {
providers: [],
};
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
const { fs } = useFS();
const [settings, setSettings] = useState<DeploySettings>(DEFAULT_SETTINGS);
const [isInitialized, setIsInitialized] = useState(false);
// Initialize settings from VFS on mount
useEffect(() => {
const initializeSettings = async () => {
try {
const settings = await readDeploySettings(fs);
setSettings(settings);
} catch (error) {
console.error('Failed to initialize deploy settings:', error);
setSettings(DEFAULT_SETTINGS);
} finally {
setIsInitialized(true);
}
};
initializeSettings();
}, [fs]);
// Save settings to VFS whenever they change (but not during initialization)
useEffect(() => {
if (!isInitialized) return;
const saveSettings = async () => {
try {
await writeDeploySettings(fs, settings);
} catch (error) {
console.error('Failed to save deploy settings:', error);
}
};
saveSettings();
}, [fs, settings, isInitialized]);
const updateSettings = (updates: Partial<DeploySettings>) => {
setSettings(prev => ({ ...prev, ...updates }));
};
const removeProvider = (index: number) => {
setSettings(prev => ({
...prev,
providers: prev.providers.filter((_, i) => i !== index),
}));
};
const setProviders = (providers: DeployProvider[]) => {
setSettings(prev => ({ ...prev, providers }));
};
const isConfigured = useMemo(() => {
return settings.providers.length > 0;
}, [settings.providers]);
const value = {
settings,
updateSettings,
removeProvider,
setProviders,
isConfigured,
isInitialized,
};
return (
<DeploySettingsContext.Provider value={value}>
{children}
</DeploySettingsContext.Provider>
);
}
-57
View File
@@ -1,57 +0,0 @@
import { useAppContext } from '@/hooks/useAppContext';
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
import { ReactNode } from 'react';
interface ExternalFaviconProps {
/** The URL to fetch the favicon for */
url: string;
/** Size of the favicon in pixels */
size?: number;
/** Fallback element to display if favicon fails to load */
fallback?: ReactNode;
/** Additional CSS classes */
className?: string;
}
/**
* ExternalFavicon component that fetches and displays a favicon for a given URL
* using the configurable favicon service from app settings.
*/
export function ExternalFavicon({
url,
size = 16,
fallback,
className = '',
}: ExternalFaviconProps) {
const { config } = useAppContext();
// Normalize the URL to ensure it has a protocol
const normalizedUrl = normalizeUrl(url);
// Generate the favicon URL using the configured template
const faviconSrc = faviconUrl(config.faviconUrl, normalizedUrl);
return (
<span className={`inline-flex items-center justify-center ${className}`}>
<img
src={faviconSrc}
alt=""
className="object-contain"
style={{ width: size, height: size }}
onError={(e) => {
// Hide the image and show the fallback on error
e.currentTarget.style.display = 'none';
const fallbackElement = e.currentTarget.nextElementSibling as HTMLElement;
if (fallbackElement) {
fallbackElement.style.display = 'inline-block';
}
}}
/>
{fallback && (
<span style={{ display: 'none' }}>
{fallback}
</span>
)}
</span>
);
}
+2 -2
View File
@@ -424,8 +424,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
});
// Set origin remote to Nostr URL
// Format: nostr://<npub>/<repo-id>
const nostrUrl = `nostr://${nip19.npubEncode(user.pubkey)}/${projectId}`;
// Format: nostr://<hex-pubkey>/<repo-id>
const nostrUrl = `nostr://${user.pubkey}/${projectId}`;
try {
// Remove existing origin if it exists
-1
View File
@@ -131,7 +131,6 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
removeHostToken,
updateHostToken,
isConfigured,
isInitialized,
};
return (
+3 -3
View File
@@ -1,4 +1,4 @@
import { useState, useMemo, useEffect, memo } from 'react';
import { useState, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert } from 'lucide-react';
@@ -24,7 +24,7 @@ interface ModelSelectorProps {
onOpenChange?: (open: boolean) => void;
}
export const ModelSelector = memo(function ModelSelector({
export function ModelSelector({
value,
onChange,
className,
@@ -423,4 +423,4 @@ export const ModelSelector = memo(function ModelSelector({
</div>
</TooltipProvider>
);
});
}
+1 -1
View File
@@ -31,7 +31,7 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
// Update refs when config changes
useEffect(() => {
relayUrl.current = config.relayUrl;
queryClient.invalidateQueries({ queryKey: ['nostr'] });
queryClient.resetQueries();
}, [config.relayUrl, queryClient]);
// Initialize NPool only once
-249
View File
@@ -1,249 +0,0 @@
import { useState, useCallback, memo } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { CircularProgress } from '@/components/ui/circular-progress';
import { FileAttachment } from '@/components/ui/file-attachment';
import { Square, ArrowUp } from 'lucide-react';
import { ModelSelector } from '@/components/ModelSelector';
interface ChatInputProps {
isLoading: boolean;
isConfigured: boolean;
providerModel: string;
onProviderModelChange: (model: string) => void;
onSend: (input: string, files: File[]) => void;
onStop: () => void;
onFocus: () => void;
onFirstInteraction: () => void;
isModelSelectorOpen: boolean;
onModelSelectorOpenChange: (open: boolean) => void;
contextUsagePercentage: number;
currentModelContextLength?: number;
lastInputTokens?: number;
totalCost: number;
isDragOver: boolean;
onDragEnter: (e: React.DragEvent) => void;
onDragOver: (e: React.DragEvent) => void;
onDragLeave: (e: React.DragEvent) => void;
onDrop: (e: React.DragEvent) => void;
}
export const ChatInput = memo(function ChatInput({
isLoading,
isConfigured,
providerModel,
onProviderModelChange,
onSend,
onStop,
onFocus,
onFirstInteraction,
isModelSelectorOpen,
onModelSelectorOpenChange,
contextUsagePercentage,
currentModelContextLength,
lastInputTokens,
totalCost,
isDragOver,
onDragEnter,
onDragOver,
onDragLeave,
onDrop,
}: ChatInputProps) {
const { t } = useTranslation();
const [input, setInput] = useState('');
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const handleFileSelect = useCallback((file: File) => {
setAttachedFiles(prev => [...prev, file]);
}, []);
const handleFileRemove = useCallback((fileToRemove: File) => {
setAttachedFiles(prev => prev.filter(file => file !== fileToRemove));
}, []);
const handleSend = useCallback(() => {
if ((!input.trim() && attachedFiles.length === 0) || isLoading) return;
if (!isConfigured || !providerModel.trim()) return;
const currentInput = input;
const currentFiles = [...attachedFiles];
setInput('');
setAttachedFiles([]);
onSend(currentInput, currentFiles);
}, [input, attachedFiles, isLoading, isConfigured, providerModel, onSend]);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}, [handleSend]);
const handlePaste = useCallback(async (e: React.ClipboardEvent) => {
const items = e.clipboardData?.items;
if (!items) return;
for (let i = 0; i < items.length; i++) {
const item = items[i];
// Check if the item is an image
if (item.type.startsWith('image/')) {
e.preventDefault(); // Prevent default paste behavior for images
const file = item.getAsFile();
if (file) {
// Generate a filename with timestamp
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const extension = file.type.split('/')[1] || 'png';
const filename = `pasted-image-${timestamp}.${extension}`;
// Create a new File object with the generated name
const namedFile = new File([file], filename, { type: file.type });
// Add to attached files
setAttachedFiles(prev => [...prev, namedFile]);
}
break; // Only handle the first image found
}
}
}, []);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
setInput(e.target.value);
}, []);
return (
<div className="border-t p-4">
{/* Chat Input Container */}
<div
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${
isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
}`}
onDragEnter={onDragEnter}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
>
<Textarea
value={input}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onFocus={onFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoading || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
{/* File Attachment */}
<FileAttachment
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
selectedFiles={attachedFiles}
disabled={isLoading}
multiple={true}
/>
{/* Context Usage Wheel */}
{contextUsagePercentage >= 10 && currentModelContextLength && lastInputTokens && lastInputTokens > 0 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="cursor-help">
<CircularProgress
value={contextUsagePercentage}
size={20}
strokeWidth={2}
/>
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('contextUsage', {
tokens: lastInputTokens.toLocaleString(),
total: currentModelContextLength.toLocaleString(),
percentage: contextUsagePercentage.toFixed(1)
})}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* Cost Display */}
{totalCost >= 0.01 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="text-xs text-muted-foreground px-2 py-1 bg-muted/50 rounded-md whitespace-nowrap cursor-help">
${totalCost.toFixed(2)}
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('totalCostSession')}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* Model Selector */}
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
<ModelSelector
value={providerModel}
onChange={onProviderModelChange}
disabled={isLoading}
placeholder={t('chooseModel')}
open={isModelSelectorOpen}
onOpenChange={onModelSelectorOpenChange}
/>
</div>
{/* Send/Stop Button */}
<div>
{isLoading ? (
<Button
onClick={onStop}
size="sm"
variant="ghost"
className="size-8 rounded-full p-0 bg-foreground/10 [&_svg]:size-3.5 [&_svg]:fill-foreground hover:bg-foreground/20"
>
<Square />
</Button>
) : (
<Button
onClick={handleSend}
onMouseDown={onFirstInteraction}
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
size="sm"
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
<ArrowUp />
</Button>
)}
</div>
</div>
</div>
</div>
);
});
+207 -41
View File
@@ -2,9 +2,13 @@ import { useState, useRef, useEffect, forwardRef, useImperativeHandle, useMemo,
import { useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Skeleton } from '@/components/ui/skeleton';
import { CircularProgress } from '@/components/ui/circular-progress';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { FileAttachment } from '@/components/ui/file-attachment';
import { OnboardingDialog } from '@/components/OnboardingDialog';
import { Loader2, ChevronDown } from 'lucide-react';
import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
import { useCurrentUser } from '@/hooks/useCurrentUser';
@@ -12,6 +16,7 @@ import { useKeepAlive } from '@/hooks/useKeepAlive';
import { useAppContext } from '@/hooks/useAppContext';
import { useAIChat } from '@/hooks/useAIChat';
import { useProviderModels } from '@/hooks/useProviderModels';
import { ModelSelector } from '@/components/ModelSelector';
import { AIMessageItem } from '@/components/AIMessageItem';
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
@@ -39,7 +44,6 @@ import { saveFileToTmp } from '@/lib/fileUtils';
import { useGit } from '@/hooks/useGit';
import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ChatInput } from '@/components/Shakespeare/ChatInput';
// Clean interfaces now handled by proper hooks
@@ -75,7 +79,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const { user } = useCurrentUser();
const { models } = useProviderModels();
const { config } = useAppContext();
const [input, setInput] = useState('');
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const [isDragOver, setIsDragOver] = useState(false);
const [scrolledProjects] = useState(() => new Set<string>());
const [showOnboarding, setShowOnboarding] = useState(false);
@@ -98,11 +104,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const [shouldAutostart, setShouldAutostart] = useState(false);
const autostartedRef = useRef(false);
// Memoize model selector onChange handler to prevent unnecessary re-renders
const handleModelChange = useCallback((newModel: string) => {
setProviderModel(newModel);
}, []);
useEffect(() => {
if (!providerModel && settings.recentlyUsedModels?.length) {
setProviderModel(settings.recentlyUsedModels[0]);
@@ -372,22 +373,30 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [projectId, scrolledProjects, scrollToBottom]);
const handleFileSelect = (file: File) => {
setAttachedFiles(prev => [...prev, file]);
};
const handleFileRemove = (fileToRemove: File) => {
setAttachedFiles(prev => prev.filter(file => file !== fileToRemove));
};
// Drag and drop handlers
const handleDragEnter = useCallback((e: React.DragEvent) => {
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(true);
}, []);
};
const handleDragOver = useCallback((e: React.DragEvent) => {
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
if (!isDragOver) {
setIsDragOver(true);
}
}, [isDragOver]);
};
const handleDragLeave = useCallback((e: React.DragEvent) => {
const handleDragLeave = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
@@ -399,15 +408,23 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
if (!container.contains(relatedTarget)) {
setIsDragOver(false);
}
}, []);
};
const handleDrop = useCallback((e: React.DragEvent) => {
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
}, []);
const handleSend = useCallback(async (input: string, attachedFiles: File[]) => {
if (isLoading || !providerModel.trim()) return;
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
// Add all files without validation
setAttachedFiles(prev => [...prev, ...files]);
};
const send = useCallback(async (input: string, attachedFiles: File[]) => {
if ((!input.trim() && attachedFiles.length === 0) || isLoading) return;
// If AI is not configured, show onboarding dialog
@@ -457,6 +474,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
});
}
setInput('');
setAttachedFiles([]);
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
@@ -465,24 +485,64 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
await sendMessage(messageContent, modelToUse);
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]);
const handleSend = useCallback(async () => {
await send(input, attachedFiles);
}, [input, attachedFiles, send]);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
};
const handlePaste = async (e: React.ClipboardEvent) => {
const items = e.clipboardData?.items;
if (!items) return;
for (let i = 0; i < items.length; i++) {
const item = items[i];
// Check if the item is an image
if (item.type.startsWith('image/')) {
e.preventDefault(); // Prevent default paste behavior for images
const file = item.getAsFile();
if (file) {
// Generate a filename with timestamp
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const extension = file.type.split('/')[1] || 'png';
const filename = `pasted-image-${timestamp}.${extension}`;
// Create a new File object with the generated name
const namedFile = new File([file], filename, { type: file.type });
// Add to attached files
setAttachedFiles(prev => [...prev, namedFile]);
}
break; // Only handle the first image found
}
}
};
// Handle textarea focus - show onboarding if not configured
const handleTextareaFocus = useCallback(() => {
const handleTextareaFocus = () => {
if (!isConfigured) {
setShowOnboarding(true);
}
if (onFirstInteraction) {
onFirstInteraction();
}
}, [isConfigured, onFirstInteraction]);
};
// Handle first user interaction to enable audio context
const handleFirstInteraction = useCallback(() => {
const handleFirstInteraction = () => {
// This will be handled automatically by the useKeepAlive hook
// when isLoading becomes true after user interaction
if (onFirstInteraction) {
onFirstInteraction();
}
}, [onFirstInteraction]);
};
// Expose startNewSession function via ref
useImperativeHandle(ref, () => ({
@@ -614,27 +674,133 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
)}
<ChatInput
isLoading={isLoading}
isConfigured={isConfigured}
providerModel={providerModel}
onProviderModelChange={handleModelChange}
onSend={handleSend}
onStop={stopGeneration}
onFocus={handleTextareaFocus}
onFirstInteraction={handleFirstInteraction}
isModelSelectorOpen={isModelSelectorOpen}
onModelSelectorOpenChange={setIsModelSelectorOpen}
contextUsagePercentage={contextUsagePercentage}
currentModelContextLength={currentModel?.contextLength}
lastInputTokens={lastInputTokens}
totalCost={totalCost}
isDragOver={isDragOver}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
/>
<div className="border-t p-4">
{/* Chat Input Container */}
<div
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
}`}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<Textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onFocus={handleTextareaFocus}
placeholder={
!isConfigured
? t('askToAddFeatures')
: providerModel.trim()
? t('askToAddFeatures')
: t('selectModelFirst')
}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isLoading || (isConfigured && !providerModel.trim())}
rows={1}
aria-label="Chat message input"
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
{/* File Attachment */}
<FileAttachment
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
selectedFiles={attachedFiles}
disabled={isLoading}
multiple={true}
/>
{/* Context Usage Wheel */}
{contextUsagePercentage >= 10 && currentModel?.contextLength && lastInputTokens > 0 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="cursor-help">
<CircularProgress
value={contextUsagePercentage}
size={20}
strokeWidth={2}
/>
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('contextUsage', {
tokens: lastInputTokens.toLocaleString(),
total: currentModel.contextLength.toLocaleString(),
percentage: contextUsagePercentage.toFixed(1)
})}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* Cost Display */}
{totalCost >= 0.01 && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div className="text-xs text-muted-foreground px-2 py-1 bg-muted/50 rounded-md whitespace-nowrap cursor-help">
${totalCost.toFixed(2)}
</div>
</TooltipTrigger>
<TooltipContent>
<p>{t('totalCostSession')}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* Model Selector */}
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
disabled={isLoading}
placeholder={t('chooseModel')}
open={isModelSelectorOpen}
onOpenChange={setIsModelSelectorOpen}
/>
</div>
{/* Send/Stop Button */}
<div>
{isLoading ? (
<Button
onClick={stopGeneration}
size="sm"
variant="ghost"
className="size-8 rounded-full p-0 bg-foreground/10 [&_svg]:size-3.5 [&_svg]:fill-foreground hover:bg-foreground/20"
>
<Square />
</Button>
) : (
<Button
onClick={handleSend}
onMouseDown={handleFirstInteraction}
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
size="sm"
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
<ArrowUp />
</Button>
)}
</div>
</div>
</div>
</div>
{/* Onboarding Dialog */}
<OnboardingDialog
+4 -3
View File
@@ -9,7 +9,7 @@ import { useBuildProject } from '@/hooks/useBuildProject';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, Rocket, X, Terminal } from 'lucide-react';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X, Terminal } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
@@ -71,7 +71,7 @@ interface JSONRPCResponse {
id: number;
}
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction: _onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
const { t } = useTranslation();
const { config } = useAppContext();
const { previewDomain } = config;
@@ -651,7 +651,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
disabled={isAnyLoading}
className="gap-2"
>
<Rocket className="h-4 w-4" />
<CloudUpload className="h-4 w-4" />
Deploy
</DropdownMenuItem>
</DropdownMenuContent>
@@ -933,6 +933,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
onFirstInteraction={onFirstInteraction}
/>
)}
</div>
-193
View File
@@ -1,193 +0,0 @@
import { useState, useEffect, useCallback } from 'react';
import { Plus, ExternalLink } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Skeleton } from '@/components/ui/skeleton';
import { proxyUrl } from '@/lib/proxyUrl';
interface NetlifySite {
id: string;
site_id: string;
name: string;
url: string;
admin_url: string;
}
interface NetlifyDeployFormProps {
apiKey: string;
baseURL?: string;
projectId: string;
projectName?: string;
savedSiteId?: string;
onSiteChange: (siteId: string, siteName: string) => void;
corsProxy?: string;
}
export function NetlifyDeployForm({
apiKey,
baseURL = 'https://api.netlify.com/api/v1',
projectId,
projectName,
savedSiteId,
onSiteChange,
corsProxy,
}: NetlifyDeployFormProps) {
const [sites, setSites] = useState<NetlifySite[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedSiteId, setSelectedSiteId] = useState<string>('');
const [newSiteName, setNewSiteName] = useState(projectName || projectId);
const fetchSites = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const url = `${baseURL}/sites`;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const response = await fetch(targetUrl, {
headers: {
'Authorization': `Bearer ${apiKey}`,
},
});
if (!response.ok) {
throw new Error(`Failed to fetch sites: ${response.status} ${response.statusText}`);
}
const data: NetlifySite[] = await response.json();
setSites(data);
// If there's a saved site ID and it exists in the list, select it
// Otherwise leave it empty (showing placeholder)
if (savedSiteId && data.some(s => s.id === savedSiteId)) {
setSelectedSiteId(savedSiteId);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch sites');
} finally {
setIsLoading(false);
}
}, [apiKey, baseURL, savedSiteId, corsProxy]);
useEffect(() => {
fetchSites();
}, [fetchSites]);
// Update newSiteName when switching to "new" if it's empty
useEffect(() => {
if (selectedSiteId === 'new' && !newSiteName) {
setNewSiteName(projectName || projectId);
}
}, [selectedSiteId, newSiteName, projectName, projectId]);
useEffect(() => {
if (selectedSiteId === '') {
// No selection yet - don't call onSiteChange
return;
} else if (selectedSiteId === 'new') {
onSiteChange('', newSiteName);
} else {
const site = sites.find(s => s.id === selectedSiteId);
if (site) {
onSiteChange(site.id, site.name);
}
}
}, [selectedSiteId, newSiteName, sites, onSiteChange]);
if (isLoading) {
return (
<div className="space-y-4">
<div className="space-y-2">
<Label>Site</Label>
<Skeleton className="h-10 w-full" />
</div>
<Skeleton className="h-4 w-3/4" />
</div>
);
}
const selectedSite = sites.find(s => s.id === selectedSiteId);
return (
<div className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="netlify-site">Select Site</Label>
<Select value={selectedSiteId} onValueChange={setSelectedSiteId}>
<SelectTrigger id="netlify-site">
<SelectValue placeholder="Select a site or create new..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Create new site
</div>
</SelectItem>
{sites.map((site) => (
<SelectItem key={site.id} value={site.id}>
{site.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedSiteId === 'new' ? (
<div className="space-y-2">
<Label htmlFor="new-site-name">New Site Name</Label>
<Input
id="new-site-name"
value={newSiteName}
onChange={(e) => setNewSiteName(e.target.value)}
placeholder={projectName || projectId}
/>
<p className="text-xs text-muted-foreground">
Domain: <span className="font-mono">{newSiteName || projectId}.netlify.app</span>
</p>
<p className="text-xs text-muted-foreground">
A new site will be created when you deploy
</p>
</div>
) : selectedSite ? (
<div className="space-y-2">
<div className="rounded-lg border p-3 space-y-2">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">{selectedSite.name}</p>
<p className="text-xs text-muted-foreground font-mono">{selectedSite.url}</p>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => window.open(selectedSite.admin_url, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
Deployment will update this existing site
</p>
</div>
) : null}
</div>
);
}
-109
View File
@@ -1,109 +0,0 @@
import { useState, useEffect, useRef } from 'react';
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
import { nip19 } from 'nostr-tools';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { PasswordInput } from '@/components/ui/password-input';
import { RefreshCw } from 'lucide-react';
interface NsiteDeployFormProps {
gateway: string;
savedNsec?: string;
onNsecChange: (nsec: string) => void;
}
export function NsiteDeployForm({
gateway,
savedNsec,
onNsecChange,
}: NsiteDeployFormProps) {
const [nsec, setNsec] = useState(savedNsec || '');
const [npub, setNpub] = useState('');
const initialized = useRef(false);
// Initialize nsec on mount
useEffect(() => {
if (!initialized.current) {
initialized.current = true;
if (savedNsec) {
// If we have a saved nsec, notify parent immediately
onNsecChange(savedNsec);
} else if (!nsec) {
// Generate a new nsec if none exists
const sk = generateSecretKey();
const newNsec = nip19.nsecEncode(sk);
setNsec(newNsec);
onNsecChange(newNsec);
}
}
}, [savedNsec, nsec, onNsecChange]);
// Update npub when nsec changes
useEffect(() => {
if (nsec) {
try {
const decoded = nip19.decode(nsec);
if (decoded.type === 'nsec') {
const pk = getPublicKey(decoded.data);
const npubEncoded = nip19.npubEncode(pk);
setNpub(npubEncoded);
}
} catch {
setNpub('');
}
}
}, [nsec]);
const handleNsecChange = (value: string) => {
setNsec(value);
onNsecChange(value);
};
const handleGenerateNew = () => {
const sk = generateSecretKey();
const newNsec = nip19.nsecEncode(sk);
setNsec(newNsec);
onNsecChange(newNsec);
};
const fullDomain = npub ? `${npub}.${gateway}` : `npub1...${gateway}`;
return (
<div className="space-y-4">
<div className="space-y-2">
<Label>Site URL</Label>
<p className="text-sm font-mono bg-muted p-2 rounded-md break-all">
{fullDomain}
</p>
<p className="text-xs text-muted-foreground">
Each site has a unique Nostr keypair
</p>
</div>
<div className="space-y-2">
<Label htmlFor="nsite-nsec">Site Private Key (nsec)</Label>
<div className="flex gap-2">
<PasswordInput
id="nsite-nsec"
value={nsec}
onChange={(e) => handleNsecChange(e.target.value)}
placeholder="nsec1..."
className="flex-1"
/>
<Button
type="button"
variant="outline"
size="icon"
onClick={handleGenerateNew}
title="Generate new key"
>
<RefreshCw className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">
Keep this private key secure. It's used to sign site metadata.
</p>
</div>
</div>
);
}
@@ -1,40 +0,0 @@
import { useState, useEffect } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
interface ShakespeareDeployFormProps {
host?: string;
projectId: string;
onSubdomainChange: (subdomain: string) => void;
}
export function ShakespeareDeployForm({
host = 'shakespeare.wtf',
projectId,
onSubdomainChange,
}: ShakespeareDeployFormProps) {
const [subdomain, setSubdomain] = useState(projectId);
useEffect(() => {
onSubdomainChange(subdomain);
}, [subdomain, onSubdomainChange]);
const fullDomain = subdomain ? `${subdomain}.${host}` : `${projectId}.${host}`;
return (
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="shakespeare-subdomain">Subdomain</Label>
<Input
id="shakespeare-subdomain"
value={subdomain}
onChange={(e) => setSubdomain(e.target.value)}
placeholder={projectId}
/>
<p className="text-xs text-muted-foreground">
Will deploy to: <span className="font-mono">{fullDomain}</span>
</p>
</div>
</div>
);
}
@@ -1,55 +0,0 @@
import { useState, useEffect } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
interface VercelDeployFormProps {
projectId: string;
projectName?: string;
savedTeamId?: string;
savedProjectName?: string;
onConfigChange: (projectName: string, teamId: string) => void;
}
export function VercelDeployForm({
projectId,
projectName: initialProjectName,
savedTeamId,
savedProjectName,
onConfigChange,
}: VercelDeployFormProps) {
const [projectName, setProjectName] = useState(savedProjectName || initialProjectName || projectId);
const [teamId, setTeamId] = useState(savedTeamId || '');
useEffect(() => {
onConfigChange(projectName, teamId);
}, [projectName, teamId, onConfigChange]);
return (
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="vercel-project-name">Project Name</Label>
<Input
id="vercel-project-name"
value={projectName}
onChange={(e) => setProjectName(e.target.value)}
placeholder={initialProjectName || projectId}
/>
<p className="text-xs text-muted-foreground">
URL: <span className="font-mono">{projectName || projectId}.vercel.app</span>
</p>
</div>
<div className="space-y-2">
<Label htmlFor="vercel-team-id">Team ID (optional)</Label>
<Input
id="vercel-team-id"
value={teamId}
onChange={(e) => setTeamId(e.target.value)}
placeholder="Leave empty for personal account"
/>
<p className="text-xs text-muted-foreground">
Deploy to a team account instead of your personal account
</p>
</div>
</div>
);
}
-4
View File
@@ -1,4 +0,0 @@
export { ShakespeareDeployForm } from './ShakespeareDeployForm';
export { NetlifyDeployForm } from './NetlifyDeployForm';
export { VercelDeployForm } from './VercelDeployForm';
export { NsiteDeployForm } from './NsiteDeployForm';
+2 -2
View File
@@ -9,12 +9,12 @@ export interface AppConfig {
relayUrl: string;
/** Git repository URL to use as project template */
projectTemplate: string;
/** Deploy server domain (e.g., "shakespeare.wtf") */
deployServer: string;
/** ESM CDN URL for package imports */
esmUrl: string;
/** HTTP proxy used to bypass CORS for AI and Git operations */
corsProxy: string;
/** Favicon URL template (e.g., "https://external-content.duckduckgo.com/ip3/{hostname}.ico") */
faviconUrl: string;
/** Preview domain for iframe sandboxing (e.g., "local-shakespeare.dev") */
previewDomain: string;
/** Selected language */
-50
View File
@@ -1,50 +0,0 @@
import { createContext } from 'react';
export interface BaseDeployProvider {
id: string;
name: string;
}
export interface ShakespeareDeployProvider extends BaseDeployProvider {
type: 'shakespeare';
host?: string;
proxy?: boolean;
}
export interface NetlifyProvider extends BaseDeployProvider {
type: 'netlify';
apiKey: string;
baseURL?: string;
proxy?: boolean;
}
export interface VercelProvider extends BaseDeployProvider {
type: 'vercel';
apiKey: string;
baseURL?: string;
proxy?: boolean;
}
export interface NsiteProvider extends BaseDeployProvider {
type: 'nsite';
gateway: string;
relayUrls: string[];
blossomServers: string[];
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider;
export interface DeploySettings {
providers: DeployProvider[];
}
export interface DeploySettingsContextType {
settings: DeploySettings;
updateSettings: (settings: Partial<DeploySettings>) => void;
removeProvider: (index: number) => void;
setProviders: (providers: DeployProvider[]) => void;
isConfigured: boolean;
isInitialized: boolean;
}
export const DeploySettingsContext = createContext<DeploySettingsContextType | undefined>(undefined);
-1
View File
@@ -30,7 +30,6 @@ export interface GitSettingsContextType {
removeHostToken: (host: string) => void;
updateHostToken: (host: string, token: Partial<GitHostToken>) => void;
isConfigured: boolean;
isInitialized: boolean;
}
export const GitSettingsContext = createContext<GitSettingsContextType | undefined>(undefined);
+1 -1
View File
@@ -43,9 +43,9 @@ describe('useAIProjectId', () => {
theme: 'dark',
relayUrl: 'wss://relay.damus.io',
projectTemplate: 'https://github.com/example/template',
deployServer: 'shakespeare.wtf',
esmUrl: 'https://esm.sh',
corsProxy: 'https://proxy.example.com/{href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
previewDomain: 'local-shakespeare.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
+1 -1
View File
@@ -39,7 +39,7 @@ export function useAppSubmissions() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'app-submissions'],
queryKey: ['app-submissions'],
queryFn: async (): Promise<AppSubmission[]> => {
// Get Soapbox team follow pack for auto-approval
const teamPubkeys = new Set<string>();
+1 -1
View File
@@ -6,7 +6,7 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id, limit],
queryKey: ['comments', root instanceof URL ? root.toString() : root.id, limit],
queryFn: async (c) => {
const filter: NostrFilter = { kinds: [1111] };
+26
View File
@@ -0,0 +1,26 @@
import { useMutation } from "@tanstack/react-query";
import { deployProject } from "@/lib/deploy";
import { useFS } from "./useFS";
import { useAppContext } from "./useAppContext";
import { useCurrentUser } from "./useCurrentUser";
export function useDeployProject(projectId: string) {
const { fs } = useFS();
const { user } = useCurrentUser();
const { config } = useAppContext();
return useMutation({
mutationFn: async () => {
if (!user) {
throw new Error("You must be logged into Nostr to deploy a project");
}
return await deployProject({
fs,
projectId: projectId,
deployServer: config.deployServer,
projectPath: `/projects/${projectId}`,
signer: user.signer,
});
},
});
}
-10
View File
@@ -1,10 +0,0 @@
import { useContext } from 'react';
import { DeploySettingsContext } from '@/contexts/DeploySettingsContext';
export function useDeploySettings() {
const context = useContext(DeploySettingsContext);
if (!context) {
throw new Error('useDeploySettings must be used within DeploySettingsProvider');
}
return context;
}
+1 -1
View File
@@ -35,9 +35,9 @@ function createWrapper(corsProxy: string) {
theme: 'light',
relayUrl: 'wss://relay.test',
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
deployServer: 'test.com',
esmUrl: 'https://esm.test',
corsProxy,
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
previewDomain: 'local-test.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
+185
View File
@@ -0,0 +1,185 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { createElement } from 'react';
import { useGitHubOAuth } from './useGitHubOAuth';
import { TestApp } from '@/test/TestApp';
import { AppProvider } from '@/components/AppProvider';
import type { AppConfig } from '@/contexts/AppContext';
// Mock environment variables for testing
vi.stubEnv('VITE_GITHUB_OAUTH_CLIENT_ID', '********************');
vi.stubEnv('VITE_GITHUB_OAUTH_CLIENT_SECRET', '****************************************');
// Wrapper component to provide AppContext
function Wrapper({ children }: { children: React.ReactNode }) {
const defaultConfig: AppConfig = {
theme: 'light',
relayUrl: 'wss://relay.test',
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
deployServer: 'test.com',
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
previewDomain: 'local-test.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
};
return createElement(
TestApp,
null,
createElement(
AppProvider,
{ storageKey: 'test-app-config', defaultConfig, children }
)
);
}
// Mock crypto.subtle for PKCE testing
const mockCryptoSubtle = {
digest: vi.fn(),
};
const mockCrypto = {
getRandomValues: vi.fn(),
randomUUID: vi.fn(),
subtle: mockCryptoSubtle,
};
Object.defineProperty(global, 'crypto', {
value: mockCrypto,
writable: true,
});
// Mock btoa for base64 encoding
global.btoa = vi.fn((str: string) => Buffer.from(str, 'binary').toString('base64'));
describe('useGitHubOAuth PKCE', () => {
beforeEach(() => {
vi.clearAllMocks();
localStorage.clear();
// Setup crypto mocks
mockCrypto.getRandomValues.mockImplementation((array: Uint8Array) => {
// Fill with predictable values for testing
for (let i = 0; i < array.length; i++) {
array[i] = i % 256;
}
return array;
});
mockCrypto.randomUUID.mockReturnValue('test-state-uuid');
// Mock SHA-256 digest to return predictable hash
mockCryptoSubtle.digest.mockResolvedValue(
new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32])
);
});
afterEach(() => {
localStorage.clear();
});
it('should validate state parameter in callback', async () => {
// Setup stored state
localStorage.setItem('github_oauth_state', 'correct-state');
localStorage.setItem('github_oauth_code_verifier', 'test-verifier');
const { result } = renderHook(() => useGitHubOAuth(), {
wrapper: Wrapper,
});
// Mock fetch for token exchange and user info (using proxy URLs)
const mockFetch = vi.fn()
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ access_token: 'test-token' }),
})
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ login: 'testuser' }),
});
global.fetch = mockFetch;
let success: boolean | undefined;
await act(async () => {
success = await result.current.handleCallback('test-code', 'correct-state');
});
expect(success).toBe(true);
expect(localStorage.getItem('github_oauth_state')).toBeNull();
expect(localStorage.getItem('github_oauth_code_verifier')).toBeNull();
});
it('should reject invalid state parameter', async () => {
localStorage.setItem('github_oauth_state', 'correct-state');
localStorage.setItem('github_oauth_code_verifier', 'test-verifier');
const { result } = renderHook(() => useGitHubOAuth(), {
wrapper: Wrapper,
});
let success: boolean | undefined;
await act(async () => {
success = await result.current.handleCallback('test-code', 'wrong-state');
});
expect(success).toBe(false);
expect(result.current.error).toBe('Invalid OAuth state parameter');
// Should clean up on error
expect(localStorage.getItem('github_oauth_state')).toBeNull();
expect(localStorage.getItem('github_oauth_code_verifier')).toBeNull();
});
it('should reject missing code verifier', async () => {
localStorage.setItem('github_oauth_state', 'correct-state');
// Don't set code verifier
const { result } = renderHook(() => useGitHubOAuth(), {
wrapper: Wrapper,
});
let success: boolean | undefined;
await act(async () => {
success = await result.current.handleCallback('test-code', 'correct-state');
});
expect(success).toBe(false);
expect(result.current.error).toBe('PKCE code verifier not found. Please restart the OAuth flow.');
});
it('should include code_verifier in token request', async () => {
localStorage.setItem('github_oauth_state', 'correct-state');
localStorage.setItem('github_oauth_code_verifier', 'test-verifier');
const { result } = renderHook(() => useGitHubOAuth(), {
wrapper: Wrapper,
});
const mockFetch = vi.fn()
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ access_token: 'test-token' }),
})
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ login: 'testuser' }),
});
global.fetch = mockFetch;
await act(async () => {
await result.current.handleCallback('test-code', 'correct-state');
});
// Check that the token request includes the code verifier
expect(mockFetch).toHaveBeenCalledWith(
'https://proxy.shakespeare.diy/?url=https%3A%2F%2Fgithub.com%2Flogin%2Foauth%2Faccess_token',
expect.objectContaining({
method: 'POST',
body: expect.stringContaining('"code_verifier":"test-verifier"'),
})
);
});
});
+176 -68
View File
@@ -1,40 +1,157 @@
import { useCallback } from 'react';
import { useOAuth, type OAuthConfig, type OAuthResult } from './useOAuth';
import { useState, useCallback } from 'react';
import { useGitSettings } from './useGitSettings';
import { useAppContext } from './useAppContext';
import { proxyUrl } from '@/lib/proxyUrl';
import type { GitHostToken } from '@/contexts/GitSettingsContext';
interface GitHubUserInfo {
login: string;
id: number;
avatar_url?: string;
name?: string;
email?: string;
[key: string]: unknown;
interface GitHubOAuthState {
isLoading: boolean;
error: string | null;
}
/**
* Hook for GitHub OAuth authentication.
* Uses the generic useOAuth hook with GitHub-specific configuration.
*/
export function useGitHubOAuth() {
const { addCredential, addHostToken, isInitialized } = useGitSettings();
interface GitHubTokenResponse {
access_token: string;
token_type: string;
scope: string;
}
// GitHub OAuth configuration
const config: OAuthConfig = {
provider: 'github',
clientId: import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID || '',
clientSecret: import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET || '',
authorizeUrl: 'https://github.com/login/oauth/authorize',
tokenUrl: 'https://github.com/login/oauth/access_token',
scope: 'repo workflow',
redirectUri: window.location.origin + '/oauth/github',
usePKCE: true, // GitHub supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
export function useGitHubOAuth() {
const [state, setState] = useState<GitHubOAuthState>({
isLoading: false,
error: null,
});
const { addCredential, addHostToken } = useGitSettings();
const { config } = useAppContext();
const { corsProxy } = config;
// Check if OAuth is configured
const isOAuthConfigured = !!(
import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID &&
import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET
);
// Generate a cryptographically secure random string for PKCE code verifier
const generateCodeVerifier = (): string => {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return btoa(String.fromCharCode(...array))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
// Create SHA-256 hash of the code verifier for PKCE code challenge
const generateCodeChallenge = async (codeVerifier: string): Promise<string> => {
const encoder = new TextEncoder();
const data = encoder.encode(codeVerifier);
const digest = await crypto.subtle.digest('SHA-256', data);
return btoa(String.fromCharCode(...new Uint8Array(digest)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
const initiateOAuth = useCallback(async () => {
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
if (!clientId) {
setState(prev => ({ ...prev, error: 'GitHub OAuth client ID not configured' }));
return;
}
try {
// Generate PKCE parameters
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
// Generate a random state parameter for security
const state = crypto.randomUUID();
// Store both state and code verifier for later use
localStorage.setItem('github_oauth_state', state);
localStorage.setItem('github_oauth_code_verifier', codeVerifier);
// Redirect to GitHub OAuth with PKCE parameters
const params = new URLSearchParams({
client_id: clientId,
redirect_uri: window.location.origin + '/oauth/github',
scope: 'repo workflow',
state: state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});
window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`;
} catch (error) {
console.error('Failed to initiate OAuth with PKCE:', error);
setState(prev => ({
...prev,
error: 'Failed to generate PKCE parameters. Please try again.'
}));
}
}, []);
const handleCallback = useCallback(async (code: string, state: string) => {
setState(prev => ({ ...prev, isLoading: true, error: null }));
try {
// Verify state parameter
const storedState = localStorage.getItem('github_oauth_state');
if (!storedState || storedState !== state) {
throw new Error('Invalid OAuth state parameter');
}
// Get the stored code verifier for PKCE
const codeVerifier = localStorage.getItem('github_oauth_code_verifier');
if (!codeVerifier) {
throw new Error('PKCE code verifier not found. Please restart the OAuth flow.');
}
// Clean up stored values
localStorage.removeItem('github_oauth_state');
localStorage.removeItem('github_oauth_code_verifier');
const clientId = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_ID;
const clientSecret = import.meta.env.VITE_GITHUB_OAUTH_CLIENT_SECRET;
if (!clientId || !clientSecret) {
throw new Error('GitHub OAuth credentials not configured');
}
// Exchange code for access token with PKCE code verifier
const tokenRequestBody = {
client_id: clientId,
client_secret: clientSecret,
code: code,
redirect_uri: window.location.origin + '/oauth/github',
code_verifier: codeVerifier,
};
const tokenUrl = proxyUrl(corsProxy, 'https://github.com/login/oauth/access_token');
const tokenResponse = await fetch(tokenUrl, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(tokenRequestBody),
});
if (!tokenResponse.ok) {
throw new Error(`GitHub OAuth token exchange failed: ${tokenResponse.statusText}`);
}
const tokenData: GitHubTokenResponse = await tokenResponse.json();
if (!tokenData.access_token) {
throw new Error('No access token received from GitHub');
}
// Get user info to verify the token works
const userUrl = proxyUrl(corsProxy, 'https://api.github.com/user');
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Authorization': `Bearer ${tokenData.access_token}`,
'Accept': 'application/vnd.github.v3+json',
},
});
@@ -43,54 +160,45 @@ export function useGitHubOAuth() {
throw new Error(`Failed to verify GitHub token: ${userResponse.statusText}`);
}
const userData: GitHubUserInfo = await userResponse.json();
return {
const userData = await userResponse.json();
// Store the credentials (legacy format for existing push/pull operations)
addCredential('https://github.com', {
username: userData.login || 'git',
password: tokenData.access_token,
});
// Also store as host token for PR/contribution operations
const hostToken: GitHostToken = {
token: tokenData.access_token,
username: userData.login,
...userData,
scopes: tokenData.scope ? tokenData.scope.split(',').map(s => s.trim()) : [],
createdAt: Date.now(),
};
},
};
addHostToken('github.com', hostToken);
const oauth = useOAuth(config);
setState(prev => ({ ...prev, isLoading: false }));
return true;
} catch (error) {
console.error('GitHub OAuth error:', error);
/**
* Handles the OAuth callback and stores the credentials in git settings.
*/
const handleCallbackAndStore = useCallback(async (
code: string,
state: string
): Promise<boolean> => {
// Wait for settings to be initialized before processing
if (!isInitialized) {
// Clean up any remaining OAuth data on error
localStorage.removeItem('github_oauth_state');
localStorage.removeItem('github_oauth_code_verifier');
setState(prev => ({
...prev,
isLoading: false,
error: error instanceof Error ? error.message : 'OAuth authentication failed'
}));
return false;
}
const result: OAuthResult | null = await oauth.handleCallback(code, state);
if (!result) {
return false;
}
// Store the credentials (legacy format for existing push/pull operations)
addCredential('https://github.com', {
username: result.username || 'git',
password: result.accessToken,
});
// Also store as host token for PR/contribution operations
const hostToken: GitHostToken = {
token: result.accessToken,
username: result.username || 'git',
scopes: result.scopes || [],
createdAt: Date.now(),
};
addHostToken('github.com', hostToken);
return true;
}, [oauth, addCredential, addHostToken, isInitialized]);
}, [addCredential, addHostToken, corsProxy]);
return {
...oauth,
handleCallback: handleCallbackAndStore,
...state,
isOAuthConfigured,
initiateOAuth,
handleCallback,
};
}
+181
View File
@@ -0,0 +1,181 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { useIsProjectPreviewable } from './useIsProjectPreviewable';
import { TestApp } from '@/test/TestApp';
// Mock the useProjectsManager hook
const mockFileExists = vi.fn();
vi.mock('./useProjectsManager', () => ({
useProjectsManager: () => ({
fileExists: mockFileExists,
}),
}));
describe('useIsProjectPreviewable', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('returns true when all required files exist', async () => {
mockFileExists.mockResolvedValue(true);
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(true);
expect(mockFileExists).toHaveBeenCalledWith('test-project', 'index.html');
expect(mockFileExists).toHaveBeenCalledWith('test-project', 'package.json');
});
it('returns false when index.html is missing and not a SvelteKit project', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'index.html') return Promise.resolve(false);
if (filePath === 'src/app.html') return Promise.resolve(false);
if (filePath === 'svelte.config.js') return Promise.resolve(false);
if (filePath === 'svelte.config.ts') return Promise.resolve(false);
return Promise.resolve(true);
});
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(false);
});
it('returns true for SvelteKit project with src/app.html', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'package.json') return Promise.resolve(true);
if (filePath === 'index.html') return Promise.resolve(false);
if (filePath === 'src/app.html') return Promise.resolve(true);
return Promise.resolve(false);
});
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(true);
});
it('returns true for SvelteKit project with svelte.config.js', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'package.json') return Promise.resolve(true);
if (filePath === 'index.html') return Promise.resolve(false);
if (filePath === 'svelte.config.js') return Promise.resolve(true);
return Promise.resolve(false);
});
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(true);
});
it('returns true for SvelteKit project with svelte.config.ts', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'package.json') return Promise.resolve(true);
if (filePath === 'index.html') return Promise.resolve(false);
if (filePath === 'svelte.config.ts') return Promise.resolve(true);
return Promise.resolve(false);
});
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(true);
});
it('returns false when package.json is missing', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'package.json') return Promise.resolve(false);
return Promise.resolve(true);
});
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(false);
});
it('returns true even when package-lock.json is missing (yarn.lock or no lock file is acceptable)', async () => {
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
if (filePath === 'package-lock.json') return Promise.resolve(false);
return Promise.resolve(true);
});
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
// Should still be previewable since package-lock.json is not required
// (projects can use yarn.lock or no lock file)
expect(result.current.data).toBe(true);
});
it('returns false when projectId is empty', async () => {
const { result } = renderHook(
() => useIsProjectPreviewable(''),
{ wrapper: TestApp }
);
// When projectId is empty, the query is disabled, so it should not be loading or successful
expect(result.current.data).toBe(false);
expect(result.current.isLoading).toBe(false);
expect(mockFileExists).not.toHaveBeenCalled();
});
it('returns false when file check throws an error', async () => {
mockFileExists.mockRejectedValue(new Error('File system error'));
const { result } = renderHook(
() => useIsProjectPreviewable('test-project'),
{ wrapper: TestApp }
);
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
});
expect(result.current.data).toBe(false);
});
});
+20 -4
View File
@@ -3,7 +3,9 @@ import { useProjectsManager } from './useProjectsManager';
/**
* Hook to check if a project is previewable
* A project is previewable if it has index.html and package.json
* A project is previewable if it's either:
* 1. A React/Vite project (has index.html and package.json)
* 2. A SvelteKit project (has src/app.html or svelte.config.js/ts and package.json)
*/
export function useIsProjectPreviewable(projectId: string) {
const projectsManager = useProjectsManager();
@@ -12,10 +14,24 @@ export function useIsProjectPreviewable(projectId: string) {
queryKey: ['project-previewable', projectId],
queryFn: async () => {
try {
// Check for required files
const hasIndexHtml = await projectsManager.fileExists(projectId, 'index.html');
// Check for package.json (required for all projects)
const hasPackageJson = await projectsManager.fileExists(projectId, 'package.json');
if (!hasPackageJson) return false;
return hasIndexHtml;
// Check for React/Vite project (index.html at root)
const hasIndexHtml = await projectsManager.fileExists(projectId, 'index.html');
if (hasIndexHtml) return true;
// Check for SvelteKit project
const [hasAppHtml, hasSvelteConfigJs, hasSvelteConfigTs] = await Promise.all([
projectsManager.fileExists(projectId, 'src/app.html'),
projectsManager.fileExists(projectId, 'svelte.config.js'),
projectsManager.fileExists(projectId, 'svelte.config.ts'),
]);
// SvelteKit project if it has app.html or svelte.config
const isSvelteKit = hasAppHtml || hasSvelteConfigJs || hasSvelteConfigTs;
return isSvelteKit;
} catch (error) {
console.error('Failed to check if project is previewable:', error);
return false;
+1 -1
View File
@@ -15,7 +15,7 @@ export function useLoggedInAccounts() {
const { logins, setLogin, removeLogin } = useNostrLogin();
const { data: authors = [], isLoading } = useQuery({
queryKey: ['nostr', 'logins', logins.map((l) => l.id).join(';')],
queryKey: ['logins', logins.map((l) => l.id).join(';')],
queryFn: async ({ signal }) => {
const events = await nostr.query(
[{ kinds: [0], authors: logins.map((l) => l.pubkey) }],
-92
View File
@@ -1,92 +0,0 @@
import { useCallback } from 'react';
import { useOAuth, type OAuthConfig, type OAuthResult } from './useOAuth';
import { useDeploySettings } from './useDeploySettings';
import { proxyUrl } from '@/lib/proxyUrl';
import type { NetlifyProvider } from '@/contexts/DeploySettingsContext';
interface NetlifyUserInfo {
id: string;
email: string;
full_name?: string;
avatar_url?: string;
[key: string]: unknown;
}
/**
* Hook for Netlify OAuth authentication.
* Uses the generic useOAuth hook with Netlify-specific configuration.
*/
export function useNetlifyOAuth() {
const { setProviders, settings, isInitialized } = useDeploySettings();
// Netlify OAuth configuration
const config: OAuthConfig = {
provider: 'netlify',
clientId: import.meta.env.VITE_NETLIFY_OAUTH_CLIENT_ID || '',
clientSecret: import.meta.env.VITE_NETLIFY_OAUTH_CLIENT_SECRET || '',
authorizeUrl: 'https://app.netlify.com/authorize',
tokenUrl: 'https://api.netlify.com/oauth/token',
// Netlify doesn't use scope parameter - permissions are configured in the OAuth app settings
redirectUri: window.location.origin + '/oauth/netlify',
usePKCE: false, // Netlify doesn't support PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.netlify.com/api/v1/user');
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
},
});
if (!userResponse.ok) {
throw new Error(`Failed to verify Netlify token: ${userResponse.statusText}`);
}
const userData: NetlifyUserInfo = await userResponse.json();
return {
username: userData.email || userData.full_name || 'Netlify User',
...userData,
};
},
};
const oauth = useOAuth(config);
/**
* Handles the OAuth callback and stores the credentials in deploy settings.
*/
const handleCallbackAndStore = useCallback(async (
code: string,
state: string
): Promise<boolean> => {
// Wait for settings to be initialized before processing
if (!isInitialized) {
return false;
}
const result: OAuthResult | null = await oauth.handleCallback(code, state);
if (!result) {
return false;
}
// Create a new Netlify provider with the OAuth token
// Use the preset ID 'netlify' for OAuth-added providers
const newProvider: NetlifyProvider = {
id: 'netlify',
name: result.username ? `Netlify (${result.username})` : 'Netlify',
type: 'netlify',
apiKey: result.accessToken,
proxy: true, // Netlify typically requires CORS proxy
};
// Add the new provider to settings
setProviders([...settings.providers, newProvider]);
return true;
}, [oauth, setProviders, settings.providers, isInitialized]);
return {
...oauth,
handleCallback: handleCallbackAndStore,
};
}
-237
View File
@@ -1,237 +0,0 @@
import { useState, useCallback } from 'react';
import { useAppContext } from './useAppContext';
import { proxyUrl } from '@/lib/proxyUrl';
export interface OAuthConfig {
provider: 'github' | 'netlify' | 'vercel';
clientId: string;
clientSecret: string;
authorizeUrl: string;
tokenUrl: string;
scope?: string; // Optional - some providers don't use scopes
redirectUri: string;
usePKCE?: boolean;
getUserInfo?: (accessToken: string, corsProxy: string) => Promise<{
username: string;
[key: string]: unknown;
}>;
}
export interface OAuthState {
isLoading: boolean;
error: string | null;
}
export interface OAuthTokenResponse {
access_token: string;
token_type: string;
scope?: string;
[key: string]: unknown;
}
export interface OAuthResult {
accessToken: string;
username?: string;
scopes?: string[];
userData?: Record<string, unknown>;
}
/**
* Generic OAuth hook that handles the OAuth 2.0 flow with optional PKCE support.
* This hook can be used for any OAuth provider by passing the appropriate configuration.
*/
export function useOAuth(config: OAuthConfig) {
const [state, setState] = useState<OAuthState>({
isLoading: false,
error: null,
});
const { config: appConfig } = useAppContext();
const { corsProxy } = appConfig;
// Check if OAuth is configured
const isOAuthConfigured = !!(config.clientId && config.clientSecret);
// Generate a cryptographically secure random string for PKCE code verifier
const generateCodeVerifier = (): string => {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return btoa(String.fromCharCode(...array))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
// Create SHA-256 hash of the code verifier for PKCE code challenge
const generateCodeChallenge = async (codeVerifier: string): Promise<string> => {
const encoder = new TextEncoder();
const data = encoder.encode(codeVerifier);
const digest = await crypto.subtle.digest('SHA-256', data);
return btoa(String.fromCharCode(...new Uint8Array(digest)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
/**
* Initiates the OAuth flow by redirecting to the provider's authorization page.
*/
const initiateOAuth = useCallback(async () => {
if (!config.clientId) {
setState(prev => ({ ...prev, error: `${config.provider} OAuth client ID not configured` }));
return;
}
try {
// Generate a random state parameter for security
const state = crypto.randomUUID();
const storagePrefix = `${config.provider}_oauth`;
// Store state for later verification
localStorage.setItem(`${storagePrefix}_state`, state);
// Build authorization URL params
const params = new URLSearchParams({
client_id: config.clientId,
redirect_uri: config.redirectUri,
state: state,
response_type: 'code',
});
// Add scope if provided (some providers don't use scopes)
if (config.scope) {
params.append('scope', config.scope);
}
// Add PKCE parameters if enabled
if (config.usePKCE) {
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
localStorage.setItem(`${storagePrefix}_code_verifier`, codeVerifier);
params.append('code_challenge', codeChallenge);
params.append('code_challenge_method', 'S256');
}
// Redirect to provider's authorization page
window.location.href = `${config.authorizeUrl}?${params.toString()}`;
} catch (error) {
console.error(`Failed to initiate ${config.provider} OAuth:`, error);
setState(prev => ({
...prev,
error: config.usePKCE
? 'Failed to generate PKCE parameters. Please try again.'
: 'Failed to initiate OAuth. Please try again.'
}));
}
}, [config]);
/**
* Handles the OAuth callback after the user authorizes the application.
* Exchanges the authorization code for an access token.
*/
const handleCallback = useCallback(async (
code: string,
state: string
): Promise<OAuthResult | null> => {
setState(prev => ({ ...prev, isLoading: true, error: null }));
const storagePrefix = `${config.provider}_oauth`;
try {
// Verify state parameter
const storedState = localStorage.getItem(`${storagePrefix}_state`);
if (!storedState || storedState !== state) {
throw new Error('Invalid OAuth state parameter');
}
// Build token request body
const tokenRequestBody: Record<string, string> = {
client_id: config.clientId,
client_secret: config.clientSecret,
code: code,
redirect_uri: config.redirectUri,
grant_type: 'authorization_code',
};
// Add PKCE code verifier if enabled
if (config.usePKCE) {
const codeVerifier = localStorage.getItem(`${storagePrefix}_code_verifier`);
if (!codeVerifier) {
throw new Error('PKCE code verifier not found. Please restart the OAuth flow.');
}
tokenRequestBody.code_verifier = codeVerifier;
}
// Clean up stored values
localStorage.removeItem(`${storagePrefix}_state`);
if (config.usePKCE) {
localStorage.removeItem(`${storagePrefix}_code_verifier`);
}
// Exchange code for access token
const tokenUrl = proxyUrl(corsProxy, config.tokenUrl);
const tokenResponse = await fetch(tokenUrl, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(tokenRequestBody),
});
if (!tokenResponse.ok) {
const errorText = await tokenResponse.text();
throw new Error(`OAuth token exchange failed: ${tokenResponse.statusText} - ${errorText}`);
}
const tokenData: OAuthTokenResponse = await tokenResponse.json();
if (!tokenData.access_token) {
throw new Error('No access token received');
}
// Build result object
const result: OAuthResult = {
accessToken: tokenData.access_token,
scopes: tokenData.scope ? tokenData.scope.split(/[\s,]+/).map(s => s.trim()).filter(Boolean) : [],
};
// Get user info if getUserInfo function is provided
if (config.getUserInfo) {
try {
const userData = await config.getUserInfo(tokenData.access_token, corsProxy);
result.username = userData.username;
result.userData = userData;
} catch (error) {
console.warn(`Failed to fetch user info for ${config.provider}:`, error);
// Continue without user info - it's optional
}
}
setState(prev => ({ ...prev, isLoading: false }));
return result;
} catch (error) {
console.error(`${config.provider} OAuth error:`, error);
// Clean up any remaining OAuth data on error
localStorage.removeItem(`${storagePrefix}_state`);
if (config.usePKCE) {
localStorage.removeItem(`${storagePrefix}_code_verifier`);
}
setState(prev => ({
...prev,
isLoading: false,
error: error instanceof Error ? error.message : 'OAuth authentication failed'
}));
return null;
}
}, [config, corsProxy]);
return {
...state,
isOAuthConfigured,
initiateOAuth,
handleCallback,
};
}
-117
View File
@@ -1,117 +0,0 @@
import { useState, useEffect, useCallback } from 'react';
import { useFS } from './useFS';
export interface ShakespeareProjectConfig {
type: 'shakespeare';
data: {
subdomain?: string;
};
}
export interface NsiteProjectConfig {
type: 'nsite';
data: {
nsec: string;
};
}
export interface NetlifyProjectConfig {
type: 'netlify';
data: {
siteId?: string;
};
}
export interface VercelProjectConfig {
type: 'vercel';
data: {
teamId?: string;
projectId?: string;
};
}
export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig;
export interface ProjectDeploySettings {
providers: Record<string, ProjectProviderConfig>;
currentProvider?: string;
}
/**
* Hook to manage project-specific deployment settings
* Stores settings in .git/shakespeare/deploy.json
*/
export function useProjectDeploySettings(projectId: string) {
const fs = useFS();
const [settings, setSettings] = useState<ProjectDeploySettings>({ providers: {} });
const [isLoading, setIsLoading] = useState(true);
const settingsPath = `/projects/${projectId}/.git/shakespeare/deploy.json`;
const loadSettings = useCallback(async () => {
try {
setIsLoading(true);
const content = await fs.fs.readFile(settingsPath, 'utf8');
const parsed = JSON.parse(content as string);
// Handle migration from old format (flat Record) to new format (with providers key)
if (parsed && typeof parsed === 'object' && !('providers' in parsed)) {
// Old format: Record<string, ProjectProviderConfig>
// Migrate to new format
setSettings({ providers: parsed });
} else {
// New format or empty
setSettings(parsed || { providers: {} });
}
} catch {
// File doesn't exist or is invalid, use empty settings
setSettings({ providers: {} });
} finally {
setIsLoading(false);
}
}, [fs.fs, settingsPath]);
useEffect(() => {
loadSettings();
}, [loadSettings]);
const saveSettings = async (newSettings: ProjectDeploySettings) => {
try {
// Ensure .git/shakespeare directory exists
const shakespeareDir = `/projects/${projectId}/.git/shakespeare`;
try {
await fs.fs.stat(shakespeareDir);
} catch {
await fs.fs.mkdir(shakespeareDir, { recursive: true });
}
// Save settings
await fs.fs.writeFile(settingsPath, JSON.stringify(newSettings, null, 2), 'utf8');
setSettings(newSettings);
} catch (error) {
console.error('Failed to save deploy settings:', error);
throw error;
}
};
const updateSettings = async (providerId: string, config: ProjectProviderConfig) => {
const newSettings = {
...settings,
providers: { ...settings.providers, [providerId]: config },
currentProvider: providerId,
};
await saveSettings(newSettings);
};
const getProviderConfig = (providerId: string): ProjectProviderConfig | undefined => {
return settings.providers[providerId];
};
return {
settings,
isLoading,
updateSettings,
saveSettings,
getProviderConfig,
};
}
-96
View File
@@ -1,96 +0,0 @@
import { useCallback } from 'react';
import { useOAuth, type OAuthConfig, type OAuthResult } from './useOAuth';
import { useDeploySettings } from './useDeploySettings';
import { proxyUrl } from '@/lib/proxyUrl';
import type { VercelProvider } from '@/contexts/DeploySettingsContext';
interface VercelUserInfo {
user: {
id: string;
email: string;
name?: string;
username?: string;
avatar?: string;
[key: string]: unknown;
};
[key: string]: unknown;
}
/**
* Hook for Vercel OAuth authentication.
* Uses the generic useOAuth hook with Vercel-specific configuration.
*/
export function useVercelOAuth() {
const { setProviders, settings, isInitialized } = useDeploySettings();
// Vercel OAuth configuration
const config: OAuthConfig = {
provider: 'vercel',
clientId: import.meta.env.VITE_VERCEL_OAUTH_CLIENT_ID || '',
clientSecret: import.meta.env.VITE_VERCEL_OAUTH_CLIENT_SECRET || '',
authorizeUrl: 'https://vercel.com/oauth/authorize',
tokenUrl: 'https://api.vercel.com/v2/oauth/access_token',
scope: 'deployments:write deployments:read projects:read projects:write',
redirectUri: window.location.origin + '/oauth/vercel',
usePKCE: false, // Vercel doesn't require PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.vercel.com/v2/user');
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
},
});
if (!userResponse.ok) {
throw new Error(`Failed to verify Vercel token: ${userResponse.statusText}`);
}
const userData: VercelUserInfo = await userResponse.json();
return {
username: userData.user.username || userData.user.email || userData.user.name || 'Vercel User',
...userData.user,
};
},
};
const oauth = useOAuth(config);
/**
* Handles the OAuth callback and stores the credentials in deploy settings.
*/
const handleCallbackAndStore = useCallback(async (
code: string,
state: string
): Promise<boolean> => {
// Wait for settings to be initialized before processing
if (!isInitialized) {
return false;
}
const result: OAuthResult | null = await oauth.handleCallback(code, state);
if (!result) {
return false;
}
// Create a new Vercel provider with the OAuth token
// Use the preset ID 'vercel' for OAuth-added providers
const newProvider: VercelProvider = {
id: 'vercel',
name: result.username ? `Vercel (${result.username})` : 'Vercel',
type: 'vercel',
apiKey: result.accessToken,
proxy: true, // Vercel typically requires CORS proxy
};
// Add the new provider to settings
setProviders([...settings.providers, newProvider]);
return true;
}, [oauth, setProviders, settings.providers, isInitialized]);
return {
...oauth,
handleCallback: handleCallbackAndStore,
};
}
+3 -3
View File
@@ -4,14 +4,14 @@
*/
export interface JSRuntimeFS {
// Core file operations with proper overloads for type safety
readFile(path: string): Promise<Uint8Array<ArrayBuffer>>;
readFile(path: string): Promise<Uint8Array>;
readFile(path: string, options: 'utf8'): Promise<string>;
readFile(path: string, options: string): Promise<string>;
readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
readFile(path: string, options: { encoding: string }): Promise<string>;
readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array<ArrayBuffer>>;
readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
writeFile(path: string, data: string | Uint8Array<ArrayBuffer>, options?: string | { encoding?: string }): Promise<void>;
writeFile(path: string, data: string | Uint8Array, options?: string | { encoding?: string }): Promise<void>;
// readdir overloads for different return types
readdir(path: string): Promise<string[]>;
+2 -1
View File
@@ -222,6 +222,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
switch (moduleName) {
case "buffer":
case "events":
return {
path: `${esmUrl}/${moduleName}?target=${target ?? "esnext"}`,
namespace: "esm",
@@ -324,7 +325,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
? `${cdnName}@${version}${packagePath}`
: `${cdnName}${packagePath}`;
const url = new URL(`${esmUrl}/*${specifier}`);
const url = new URL(`${esmUrl}/${specifier}`);
if (target) url.searchParams.set("target", target);
if (childLockPath) url.searchParams.set("lp", encodeURIComponent(childLockPath));
+58 -5
View File
@@ -35,16 +35,69 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
return;
}
let resolved: string;
let resolved: string | undefined;
// 1. Absolute paths from CSS files should be treated as external (public assets)
if (args.path.startsWith("/")) {
// Check if the importer is a CSS file
const importerExt = args.importer ? extname(args.importer).slice(1) : '';
if (importerExt === 'css') {
// CSS imports of absolute paths are public assets (fonts, images, etc.)
return {
path: args.path,
external: true,
};
}
resolved = args.path;
} else if (args.path.startsWith("@/")) {
}
// 2. Built-in @/ alias (always points to src/)
else if (args.path.startsWith("@/")) {
resolved = join(cwd, "src", args.path.slice(2));
} else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
}
// 3. Relative paths
else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
resolved = join(dirname(args.importer), args.path);
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
}
// 4. Try tsconfig paths
else if (tsconfig?.compilerOptions?.paths) {
const paths = tsconfig.compilerOptions.paths;
const baseUrl = tsconfig.compilerOptions.baseUrl || ".";
// Try to match against tsconfig paths
for (const [pattern, mappings] of Object.entries(paths)) {
// Handle exact matches
if (pattern === args.path) {
const mapping = mappings[0];
if (mapping) {
resolved = join(cwd, baseUrl, mapping);
break;
}
}
// Handle wildcard patterns (e.g., "$lib/*": ["src/lib/*"])
if (pattern.endsWith('/*')) {
const prefix = pattern.slice(0, -2);
if (args.path.startsWith(prefix + '/') || args.path === prefix) {
const suffix = args.path.slice(prefix.length);
const mapping = mappings[0];
if (mapping) {
// Replace the * in the mapping with the suffix
const resolvedMapping = mapping.replace('*', suffix.slice(1) || '');
resolved = join(cwd, baseUrl, resolvedMapping);
break;
}
}
}
}
}
// 5. Try baseUrl as fallback
if (!resolved && args.importer && tsconfig?.compilerOptions?.baseUrl) {
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
} else {
}
// If still not resolved, let other plugins handle it
if (!resolved) {
return;
}
+388 -27
View File
@@ -7,7 +7,9 @@ import { addDomainToCSP } from "@/lib/csp";
import { shakespearePlugin } from "./shakespearePlugin";
import { esmPlugin } from "./esmPlugin";
import { fsPlugin } from "./fsPlugin";
import { sveltePlugin } from "./sveltePlugin";
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
import { convertPnpmLockToPackageLock } from "./pnpmLockConverter";
import type { JSRuntimeFS } from '@/lib/JSRuntime';
@@ -20,6 +22,270 @@ export interface BuildProjectOptions {
esmUrl: string;
}
/**
* Bundle a SvelteKit project
*/
async function bundleSvelteKit(
options: BuildProjectOptions,
): Promise<Record<string, Uint8Array>> {
const { fs, projectPath, domParser, target = "esnext", esmUrl } = options;
const esbuild = await getEsbuild(esmUrl);
// Read app.html template
const appHtmlText = await fs.readFile(
`${projectPath}/src/app.html`,
"utf8",
);
// Read package.json
const packageJsonText = await fs.readFile(
`${projectPath}/package.json`,
"utf8",
);
const packageJson = JSON.parse(packageJsonText);
// Try to read tsconfig.json
let tsconfig;
try {
const tsconfigText = await fs.readFile(
`${projectPath}/tsconfig.json`,
"utf8",
);
tsconfig = JSONC.parse(tsconfigText);
} catch {
tsconfig = undefined;
}
// Extract aliases from svelte.config.js and merge with tsconfig paths
const svelteAliases = await extractSvelteAliases(fs, projectPath);
// Always add default SvelteKit $lib alias
const defaultSvelteAliases: Record<string, string> = {
'$lib': 'src/lib',
'$lib/*': 'src/lib/*',
};
const allSvelteAliases = { ...defaultSvelteAliases, ...svelteAliases };
if (Object.keys(allSvelteAliases).length > 0) {
// Convert Svelte aliases to tsconfig paths format
const pathsFromAliases: Record<string, string[]> = {};
for (const [alias, path] of Object.entries(allSvelteAliases)) {
// Handle different alias formats:
// 'my-file' -> 'path/to/file.js' becomes 'my-file': ['path/to/file.js']
// 'my-dir' -> 'path/to/dir' becomes 'my-dir/*': ['path/to/dir/*']
// 'my-dir/*' -> 'path/to/dir/*' stays as is
if (alias.endsWith('/*')) {
pathsFromAliases[alias] = [path];
} else if (path.includes('.')) {
// Likely a file
pathsFromAliases[alias] = [path];
} else {
// Likely a directory - add /* for directory resolution
pathsFromAliases[`${alias}/*`] = [`${path}/*`];
// Also add exact match for the directory itself
pathsFromAliases[alias] = [path];
}
}
// Merge with existing tsconfig paths
if (!tsconfig) {
tsconfig = { compilerOptions: {} };
}
if (!tsconfig.compilerOptions) {
tsconfig.compilerOptions = {};
}
tsconfig.compilerOptions.paths = {
...pathsFromAliases,
...tsconfig.compilerOptions.paths, // tsconfig paths take precedence
};
console.log('Merged Svelte aliases into tsconfig paths:', tsconfig.compilerOptions.paths);
}
// Try to read package-lock.json first, fall back to yarn.lock, then pnpm-lock.yaml
let packageLock;
let buildMode: string;
try {
const packageLockText = await fs.readFile(
`${projectPath}/package-lock.json`,
"utf8",
);
packageLock = JSON.parse(packageLockText);
buildMode = "npm (package-lock.json)";
} catch {
try {
const yarnLockText = await fs.readFile(
`${projectPath}/yarn.lock`,
"utf8",
);
packageLock = convertYarnLockToPackageLock(yarnLockText);
buildMode = "yarn (yarn.lock)";
} catch {
try {
const pnpmLockText = await fs.readFile(
`${projectPath}/pnpm-lock.yaml`,
"utf8",
);
packageLock = convertPnpmLockToPackageLock(pnpmLockText);
buildMode = "pnpm (pnpm-lock.yaml)";
} catch {
packageLock = { packages: {} };
buildMode = "package.json only (no lock file)";
}
}
}
console.log(`Building SvelteKit project with ${buildMode}`);
// Find entry point - typically src/routes/+page.svelte or a layout
const entryPoints: string[] = [];
// Check for common SvelteKit entry points
const possibleEntries = [
join(projectPath, "src", "routes", "+layout.svelte"),
join(projectPath, "src", "routes", "+page.svelte"),
];
for (const entry of possibleEntries) {
if (await fileExists(fs, entry)) {
entryPoints.push(entry);
break; // Use the first one found
}
}
// If no entry found, scan the routes directory
if (entryPoints.length === 0) {
try {
const routesPath = join(projectPath, "src", "routes");
const routes = await fs.readdir(routesPath);
for (const route of routes) {
if (route.endsWith(".svelte")) {
entryPoints.push(join(routesPath, route));
break;
}
}
} catch {
throw new Error("Could not find SvelteKit entry point in src/routes/");
}
}
// Build with esbuild
const results = await esbuild.build({
entryPoints,
bundle: true,
write: false,
format: "esm",
target,
outdir: "/",
metafile: true,
sourcemap: true,
entryNames: "[name]-[hash]",
chunkNames: "[name]-[hash]",
assetNames: "[name]-[hash]",
plugins: [
shakespearePlugin({ esmUrl }),
sveltePlugin({ fs, projectPath }),
fsPlugin({ fs, cwd: projectPath, tsconfig }),
esmPlugin({ packageJson, packageLock, target, esmUrl }),
],
define: {
"import.meta.env": JSON.stringify({}),
},
});
const dist: Record<string, Uint8Array> = {};
const doc = domParser.parseFromString(appHtmlText, "text/html");
// Track the main component file for mounting
let mainComponentPath: string | undefined;
// Process output files
for (const file of results.outputFiles) {
const ext = file.path.split('.').pop();
const filename = `${file.path.slice(1)}`;
const entryPoint = results.metafile.outputs[filename]?.entryPoint?.replace(/^fs:/, '');
if (ext === "js") {
// Track the main component for mounting
if (entryPoint && entryPoints.includes(entryPoint)) {
mainComponentPath = "/" + filename;
}
dist[filename] = file.contents;
} else if (ext === "css") {
const style = doc.createElement("link");
style.rel = "stylesheet";
style.href = "/" + filename;
if (doc.head.textContent?.includes("%sveltekit.head%")) {
doc.head.innerHTML = doc.head.innerHTML.replace("%sveltekit.head%", style.outerHTML);
} else {
doc.head.appendChild(style);
}
dist[filename] = file.contents;
} else {
dist[filename] = file.contents;
}
}
// Create a mounting script for the Svelte component
if (mainComponentPath) {
// Get svelte version from package.json
const svelteVersion = packageJson.dependencies?.svelte ||
packageJson.devDependencies?.svelte ||
'5';
const mountScript = `
import Component from '${mainComponentPath}';
import { mount } from '${esmUrl}/svelte@${svelteVersion}';
// Mount the component to the target element
const target = document.getElementById('svelte') || document.body;
mount(Component, { target });
`;
const mountScriptHash = Math.random().toString(36).substring(7);
const mountScriptFilename = `mount-${mountScriptHash}.js`;
dist[mountScriptFilename] = new TextEncoder().encode(mountScript);
// Add the mount script to the HTML
const script = document.createElement("script");
script.type = "module";
script.src = "/" + mountScriptFilename;
doc.head.appendChild(script);
}
// Replace SvelteKit placeholders
let htmlContent = doc.documentElement.outerHTML;
// Replace common placeholders
htmlContent = htmlContent.replace(/%sveltekit\.head%/g, "");
htmlContent = htmlContent.replace(/%sveltekit\.body%/g, '<div id="svelte"></div>');
htmlContent = htmlContent.replace(/%sveltekit\.assets%/g, "");
htmlContent = htmlContent.replace(/%sveltekit\.nonce%/g, "");
// Parse CSP and ensure ESM CDN is allowed
const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]");
if (cspMeta) {
const cspContent = cspMeta.getAttribute("content");
if (cspContent) {
const updatedCSP = updateCSPForEsmSh(cspContent, esmUrl);
htmlContent = htmlContent.replace(cspContent, updatedCSP);
}
}
const updatedHtml = "<!DOCTYPE html>\n" + htmlContent;
dist["index.html"] = new TextEncoder().encode(updatedHtml);
return dist;
}
async function bundle(
options: BuildProjectOptions,
): Promise<Record<string, Uint8Array>> {
@@ -32,16 +298,11 @@ async function bundle(
);
// Read package.json
let packageJson;
try {
const packageJsonText = await fs.readFile(
`${projectPath}/package.json`,
"utf8",
);
packageJson = JSON.parse(packageJsonText);
} catch {
packageJson = {};
}
const packageJsonText = await fs.readFile(
`${projectPath}/package.json`,
"utf8",
);
const packageJson = JSON.parse(packageJsonText);
// Try to read tsconfig.json
let tsconfig;
@@ -56,7 +317,7 @@ async function bundle(
tsconfig = undefined;
}
// Try to read package-lock.json first, fall back to yarn.lock
// Try to read package-lock.json first, fall back to yarn.lock, then pnpm-lock.yaml
let packageLock;
let buildMode: string;
try {
@@ -76,9 +337,19 @@ async function bundle(
packageLock = convertYarnLockToPackageLock(yarnLockText);
buildMode = "yarn (yarn.lock)";
} catch {
// If neither exists, use empty packages object
packageLock = { packages: {} };
buildMode = "package.json only (no lock file)";
// If yarn.lock doesn't exist, try pnpm-lock.yaml
try {
const pnpmLockText = await fs.readFile(
`${projectPath}/pnpm-lock.yaml`,
"utf8",
);
packageLock = convertPnpmLockToPackageLock(pnpmLockText);
buildMode = "pnpm (pnpm-lock.yaml)";
} catch {
// If no lock file exists, use empty packages object
packageLock = { packages: {} };
buildMode = "package.json only (no lock file)";
}
}
}
@@ -192,15 +463,39 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
}> {
const { fs, projectPath, outputPath = `${projectPath}/dist` } = options;
// Check if index.html exists
// Check if we're in a valid project directory
try {
await fs.readFile(`${projectPath}/index.html`, "utf8");
await fs.readFile(`${projectPath}/package.json`, "utf8");
} catch {
throw new Error(`❌ Could not find index.html at ${projectPath}. This is required for building the project.`);
throw new Error(`❌ Could not find package.json at ${projectPath}. Make sure you're in a valid project directory.`);
}
// Run the build
const dist = await bundle(options);
// Detect if this is a SvelteKit project
const isSvelteKit = await isSvelteKitProject(fs, projectPath);
let dist: Record<string, Uint8Array>;
if (isSvelteKit) {
// Check for src/app.html (required for SvelteKit)
try {
await fs.readFile(`${projectPath}/src/app.html`, "utf8");
} catch {
throw new Error(`❌ Could not find src/app.html at ${projectPath}. This is required for building SvelteKit projects.`);
}
console.log("🎭 Detected SvelteKit project");
dist = await bundleSvelteKit(options);
} else {
// Check if index.html exists (required for React/Vite projects)
try {
await fs.readFile(`${projectPath}/index.html`, "utf8");
} catch {
throw new Error(`❌ Could not find index.html at ${projectPath}. This is required for building the project.`);
}
// Run the standard build
dist = await bundle(options);
}
// Delete all existing files in output directory
try {
@@ -220,15 +515,19 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
await fs.writeFile(`${outputPath}/${path}`, contents);
}
// Copy files from public directory if it exists
try {
const publicPath = `${projectPath}/public`;
const stat = await fs.stat(publicPath);
if (stat.isDirectory()) {
await copyFiles(fs, fs, publicPath, outputPath);
// Copy files from public directory (React/Vite) or static directory (SvelteKit)
const staticDirs = isSvelteKit ? ["static"] : ["public"];
for (const dirName of staticDirs) {
try {
const staticPath = `${projectPath}/${dirName}`;
const stat = await fs.stat(staticPath);
if (stat.isDirectory()) {
await copyFiles(fs, fs, staticPath, outputPath);
}
} catch {
// Static directory doesn't exist, which is fine
}
} catch {
// Public directory doesn't exist, which is fine
}
// Extract project ID from the project path
@@ -259,6 +558,68 @@ async function fileExists(fs: JSRuntimeFS, path: string): Promise<boolean> {
}
}
/**
* Extract aliases from svelte.config.js
*/
async function extractSvelteAliases(fs: JSRuntimeFS, projectPath: string): Promise<Record<string, string> | undefined> {
try {
// Try to read svelte.config.js
let configPath: string | undefined;
if (await fileExists(fs, join(projectPath, "svelte.config.js"))) {
configPath = join(projectPath, "svelte.config.js");
} else if (await fileExists(fs, join(projectPath, "svelte.config.ts"))) {
configPath = join(projectPath, "svelte.config.ts");
}
if (!configPath) return undefined;
const configText = await fs.readFile(configPath, "utf8");
// Try to extract alias object using regex
// Look for: alias: { ... }
const aliasMatch = configText.match(/alias\s*:\s*\{([^}]+)\}/s);
if (!aliasMatch) return undefined;
const aliasContent = aliasMatch[1];
const aliases: Record<string, string> = {};
// Parse each alias line: 'key': 'value' or "key": "value"
const aliasPattern = /['"]([^'"]+)['"]\s*:\s*['"]([^'"]+)['"]/g;
let match;
while ((match = aliasPattern.exec(aliasContent)) !== null) {
const [, key, value] = match;
aliases[key] = value;
}
return Object.keys(aliases).length > 0 ? aliases : undefined;
} catch (error) {
console.warn('Failed to extract Svelte aliases:', error);
return undefined;
}
}
/**
* Detect if a project is a SvelteKit project
*/
async function isSvelteKitProject(fs: JSRuntimeFS, projectPath: string): Promise<boolean> {
// Check for src/app.html (required for SvelteKit)
const hasAppHtml = await fileExists(fs, join(projectPath, "src", "app.html"));
// Check for svelte.config.js or svelte.config.ts
const hasSvelteConfig =
await fileExists(fs, join(projectPath, "svelte.config.js")) ||
await fileExists(fs, join(projectPath, "svelte.config.ts"));
// Check if index.html exists at root (indicates React/Vite project, not SvelteKit)
const hasRootIndexHtml = await fileExists(fs, join(projectPath, "index.html"));
// A project is considered SvelteKit if:
// 1. It has app.html or svelte.config, AND
// 2. It does NOT have a root index.html (which would indicate React/Vite)
return (hasAppHtml || hasSvelteConfig) && !hasRootIndexHtml;
}
/** Updates CSP to allow ESM CDN for scripts, assets, fonts, and CSS */
export function updateCSPForEsmSh(csp: string, esmUrl: string): string {
const esmDirectives = [
+270
View File
@@ -0,0 +1,270 @@
import { describe, it, expect } from 'vitest';
import { convertPnpmLockToPackageLock } from './pnpmLockConverter';
describe('convertPnpmLockToPackageLock', () => {
it('should convert a simple pnpm-lock.yaml entry', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/react@18.2.0:
version: 18.2.0
resolution: {integrity: sha512-...}
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/react']).toEqual({
name: 'react',
version: '18.2.0',
});
});
it('should convert scoped packages', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/@babel/core@7.23.0:
version: 7.23.0
resolution: {integrity: sha512-...}
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/@babel/core']).toEqual({
name: '@babel/core',
version: '7.23.0',
});
});
it('should parse dependencies', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/react-dom@18.2.0(react@18.2.0):
version: 18.2.0
resolution: {integrity: sha512-...}
dependencies:
loose-envify: 1.4.0
scheduler: 0.23.0
peerDependencies:
react: ^18.2.0
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/react-dom']).toEqual({
name: 'react-dom',
version: '18.2.0',
dependencies: {
'loose-envify': '1.4.0',
'scheduler': '0.23.0',
},
peerDependencies: {
'react': '^18.2.0',
},
});
});
it('should parse peer dependencies', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/@testing-library/react@14.0.0(react-dom@18.2.0)(react@18.2.0):
version: 14.0.0
resolution: {integrity: sha512-...}
peerDependencies:
react: ^18.0.0
react-dom: ^18.0.0
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/@testing-library/react']).toEqual({
name: '@testing-library/react',
version: '14.0.0',
peerDependencies: {
react: '^18.0.0',
'react-dom': '^18.0.0',
},
});
});
it('should handle multiple packages', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/react@18.2.0:
version: 18.2.0
resolution: {integrity: sha512-...}
/react-dom@18.2.0(react@18.2.0):
version: 18.2.0
resolution: {integrity: sha512-...}
dependencies:
react: 18.2.0
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/react']).toEqual({
name: 'react',
version: '18.2.0',
});
expect(result.packages['node_modules/react-dom']).toEqual({
name: 'react-dom',
version: '18.2.0',
dependencies: {
react: '18.2.0',
},
});
});
it('should skip entries without version', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/invalid-entry@1.0.0:
resolution: {integrity: sha512-...}
/valid-entry@1.0.0:
version: 1.0.0
resolution: {integrity: sha512-...}
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/invalid-entry']).toBeUndefined();
expect(result.packages['node_modules/valid-entry']).toEqual({
name: 'valid-entry',
version: '1.0.0',
});
});
it('should handle empty pnpm-lock.yaml', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages).toEqual({});
});
it('should handle packages with peer dependency specifiers in key', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/styled-components@6.0.0(react-dom@18.2.0)(react@18.2.0):
version: 6.0.0
resolution: {integrity: sha512-...}
dependencies:
some-dep: 1.0.0
peerDependencies:
react: '>= 16.8.0'
react-dom: '>= 16.8.0'
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
expect(result.packages['node_modules/styled-components']).toEqual({
name: 'styled-components',
version: '6.0.0',
dependencies: {
'some-dep': '1.0.0',
},
peerDependencies: {
react: '>= 16.8.0',
'react-dom': '>= 16.8.0',
},
});
});
it('should stop parsing after packages section ends', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/react@18.2.0:
version: 18.2.0
resolution: {integrity: sha512-...}
snapshots:
/react@18.2.0:
dependencies:
loose-envify: 1.4.0
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
// Should only have the package from packages section, not from snapshots
expect(result.packages['node_modules/react']).toEqual({
name: 'react',
version: '18.2.0',
});
expect(Object.keys(result.packages).length).toBe(1);
});
it('should handle multiple installations of same package@version with different peer deps', () => {
const pnpmLock = `
lockfileVersion: '9.0'
packages:
/eslint-plugin-svelte@3.9.3(eslint@9.34.0)(svelte@5.39.8):
version: 3.9.3
resolution: {integrity: sha512-...}
peerDependencies:
eslint: ^8.0.0 || ^9.0.0
svelte: ^4.0.0 || ^5.0.0
/eslint-plugin-svelte@3.9.3(eslint@8.57.1)(svelte@5.39.8):
version: 3.9.3
resolution: {integrity: sha512-...}
peerDependencies:
eslint: ^8.0.0 || ^9.0.0
svelte: ^4.0.0 || ^5.0.0
`;
const result = convertPnpmLockToPackageLock(pnpmLock);
// First installation should use simple path
expect(result.packages['node_modules/eslint-plugin-svelte']).toEqual({
name: 'eslint-plugin-svelte',
version: '3.9.3',
peerDependencies: {
eslint: '^8.0.0 || ^9.0.0',
svelte: '^4.0.0 || ^5.0.0',
},
});
// Second installation should use nested path
expect(result.packages['node_modules/.pnpm/eslint-plugin-svelte_1']).toEqual({
name: 'eslint-plugin-svelte',
version: '3.9.3',
peerDependencies: {
eslint: '^8.0.0 || ^9.0.0',
svelte: '^4.0.0 || ^5.0.0',
},
});
expect(Object.keys(result.packages).length).toBe(2);
});
});
+215
View File
@@ -0,0 +1,215 @@
/**
* Converts pnpm-lock.yaml format to package-lock.json format for use with esmPlugin.
* This is a simplified converter that extracts enough information for dependency resolution.
*/
interface PnpmLockPackage {
version?: string;
dependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
}
interface PackageLockPackage {
name?: string;
version: string;
dependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
}
interface PackageLock {
packages: {
[key: string]: PackageLockPackage;
};
}
/**
* Parse a pnpm-lock.yaml file and convert it to package-lock.json format
*/
export function convertPnpmLockToPackageLock(pnpmLockContent: string): PackageLock {
const packages: Record<string, PackageLockPackage> = {};
// Parse pnpm-lock.yaml entries
const entries = parsePnpmLock(pnpmLockContent);
// Track which package@version combinations we've seen to handle duplicates
const seenVersions = new Map<string, number>();
for (const [key, entry] of Object.entries(entries)) {
if (!entry.version) continue;
const packageName = extractPackageName(key);
if (!packageName) continue;
const versionKey = `${packageName}@${entry.version}`;
const count = seenVersions.get(versionKey) || 0;
seenVersions.set(versionKey, count + 1);
// Determine the lock path
let lockPath: string;
if (count === 0) {
// First occurrence - use simple node_modules path
lockPath = `node_modules/${packageName}`;
} else {
// Subsequent occurrences - create unique nested paths
// This handles cases where the same package@version is installed
// multiple times with different peer dependencies
lockPath = `node_modules/.pnpm/${packageName}_${count}`;
}
packages[lockPath] = {
name: packageName,
version: entry.version,
dependencies: entry.dependencies,
peerDependencies: entry.peerDependencies,
};
}
return { packages };
}
/**
* Parse pnpm-lock.yaml content into a map of entries
* This is a simple YAML parser focused on the packages section
*/
function parsePnpmLock(content: string): Record<string, PnpmLockPackage> {
const entries: Record<string, PnpmLockPackage> = {};
const lines = content.split('\n');
let inPackagesSection = false;
let currentKey: string | null = null;
let currentEntry: Partial<PnpmLockPackage> = {};
let inDependencies = false;
let inPeerDependencies = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Skip comments and empty lines
if (line.trim().startsWith('#') || line.trim() === '') {
continue;
}
// Detect the packages section
if (line.match(/^packages:/)) {
inPackagesSection = true;
continue;
}
// Exit packages section when we hit another top-level key
if (inPackagesSection && line.match(/^[a-zA-Z]/)) {
inPackagesSection = false;
// Save last entry before exiting
if (currentKey && currentEntry.version) {
entries[currentKey] = currentEntry as PnpmLockPackage;
}
break;
}
if (!inPackagesSection) continue;
// Get indentation level
const indent = line.search(/\S/);
if (indent === -1) continue;
// Package entry (2-space indent from packages:)
// Example: " /@babel/[email protected]:"
const packageMatch = line.match(/^ {2}(\/[^:]+):\s*$/);
if (packageMatch) {
// Save previous entry
if (currentKey && currentEntry.version) {
entries[currentKey] = currentEntry as PnpmLockPackage;
}
// Start new entry
currentKey = packageMatch[1];
currentEntry = {};
inDependencies = false;
inPeerDependencies = false;
continue;
}
// Skip if we don't have a current package
if (!currentKey) continue;
// Property lines (4-space indent from package key)
const propertyMatch = line.match(/^ {4}([a-zA-Z]+):\s*$/);
const valueMatch = line.match(/^ {4}([a-zA-Z]+):\s*(.+)\s*$/);
const depMatch = line.match(/^ {6}([^:]+):\s*(.+)\s*$/);
if (propertyMatch) {
const [, key] = propertyMatch;
if (key === 'dependencies') {
inDependencies = true;
inPeerDependencies = false;
currentEntry.dependencies = {};
} else if (key === 'peerDependencies') {
inPeerDependencies = true;
inDependencies = false;
currentEntry.peerDependencies = {};
} else {
inDependencies = false;
inPeerDependencies = false;
}
} else if (valueMatch && !inDependencies && !inPeerDependencies) {
const [, key, value] = valueMatch;
if (key === 'version') {
currentEntry.version = value.trim();
}
} else if (depMatch) {
const [, key, value] = depMatch;
const cleanKey = key.trim();
// Remove quotes from value if present
const cleanValue = value.trim().replace(/^['"]|['"]$/g, '');
if (inDependencies && currentEntry.dependencies) {
currentEntry.dependencies[cleanKey] = cleanValue;
} else if (inPeerDependencies && currentEntry.peerDependencies) {
currentEntry.peerDependencies[cleanKey] = cleanValue;
}
}
}
// Save last entry
if (currentKey && currentEntry.version) {
entries[currentKey] = currentEntry as PnpmLockPackage;
}
return entries;
}
/**
* Extract the package name from a pnpm-lock.yaml key
* Examples:
* "/@babel/[email protected]" -> "@babel/core"
* "/[email protected]" -> "react"
* "/[email protected]([email protected])" -> "react-dom"
*/
function extractPackageName(key: string): string | null {
// Remove leading slash
let cleaned = key.startsWith('/') ? key.slice(1) : key;
// Remove peer dependency specifications in parentheses
// Example: "[email protected]([email protected])" -> "[email protected]"
cleaned = cleaned.replace(/\([^)]*\)$/, '');
// Handle scoped packages: "@scope/package@version"
if (cleaned.startsWith('@')) {
const parts = cleaned.split('@');
// parts will be: ['', 'scope/package', 'version']
if (parts.length >= 2) {
return `@${parts[1]}`;
}
}
// Handle regular packages: "package@version"
const atIndex = cleaned.indexOf('@');
if (atIndex > 0) {
return cleaned.substring(0, atIndex);
}
// If no @ found, return the whole string
return cleaned || null;
}
+223
View File
@@ -0,0 +1,223 @@
import type { Plugin } from "esbuild-wasm";
import type { JSRuntimeFS } from "@/lib/JSRuntime";
import { compile } from "svelte/compiler";
interface SveltePluginOptions {
fs: JSRuntimeFS;
projectPath: string;
}
/**
* Svelte plugin for esbuild to compile .svelte files in the browser.
* This is a basic implementation that transforms Svelte components to JavaScript.
*/
export function sveltePlugin(options: SveltePluginOptions): Plugin {
const { fs } = options;
return {
name: "svelte",
setup(build) {
// Stub SvelteKit $app modules
build.onResolve({ filter: /^\$app\// }, (args) => {
return {
path: args.path,
namespace: "sveltekit-stub",
};
});
build.onLoad({ filter: /.*/, namespace: "sveltekit-stub" }, (args) => {
const module = args.path;
// $app/environment
if (module === "$app/environment") {
return {
contents: `
export const browser = true;
export const building = false;
export const dev = true;
export const version = "stub";
`,
loader: "js",
};
}
// $app/navigation
if (module === "$app/navigation") {
return {
contents: `
export function afterNavigate(callback) {
// Stub: no-op in browser build
}
export function beforeNavigate(callback) {
// Stub: no-op in browser build
}
export function disableScrollHandling() {
// Stub: no-op in browser build
}
export function goto(url, opts) {
console.warn('[SvelteKit Stub] goto() called with:', url, opts);
window.location.href = typeof url === 'string' ? url : url.toString();
return Promise.resolve();
}
export function invalidate(url) {
console.warn('[SvelteKit Stub] invalidate() called');
return Promise.resolve();
}
export function invalidateAll() {
console.warn('[SvelteKit Stub] invalidateAll() called');
return Promise.resolve();
}
export function onNavigate(callback) {
// Stub: no-op in browser build
}
export function preloadCode(...args) {
console.warn('[SvelteKit Stub] preloadCode() called');
return Promise.resolve();
}
export function preloadData(url) {
console.warn('[SvelteKit Stub] preloadData() called');
return Promise.resolve();
}
export function pushState(url, state) {
console.warn('[SvelteKit Stub] pushState() called');
window.history.pushState(state, '', url);
}
export function replaceState(url, state) {
console.warn('[SvelteKit Stub] replaceState() called');
window.history.replaceState(state, '', url);
}
export function refreshAll() {
console.warn('[SvelteKit Stub] refreshAll() called');
window.location.reload();
return Promise.resolve();
}
`,
loader: "js",
};
}
// $app/stores
if (module === "$app/stores") {
return {
contents: `
import { writable, readable } from 'svelte/store';
export const page = readable({
url: new URL(window.location.href),
params: {},
route: { id: null },
status: 200,
error: null,
data: {},
form: null,
state: {}
});
export const navigating = readable(null);
export const updated = Object.assign(
readable(false),
{ check: () => Promise.resolve(false) }
);
export function getStores() {
return { page, navigating, updated };
}
`,
loader: "js",
};
}
// $app/paths
if (module === "$app/paths") {
return {
contents: `
export const base = '';
export const assets = '';
`,
loader: "js",
};
}
// $app/forms (for form actions)
if (module === "$app/forms") {
return {
contents: `
export function enhance(form, submit) {
console.warn('[SvelteKit Stub] enhance() called - form actions not supported in browser build');
return { destroy() {} };
}
export function applyAction(result) {
console.warn('[SvelteKit Stub] applyAction() called');
return Promise.resolve();
}
export function deserialize(result) {
console.warn('[SvelteKit Stub] deserialize() called');
return result;
}
`,
loader: "js",
};
}
// Unknown $app module
return {
contents: `
console.error('[SvelteKit Stub] Unknown module: ${module}');
export default {};
`,
loader: "js",
};
});
// Handle .svelte file imports
build.onLoad({ filter: /\.svelte$/ }, async (args) => {
try {
const source = await fs.readFile(args.path, "utf8");
// Compile the Svelte component
const result = compile(source, {
filename: args.path,
generate: "client", // Svelte 5 uses "client" instead of "dom"
css: "injected", // Inject CSS into the component
});
// Return the compiled JavaScript
return {
contents: result.js.code,
loader: "js",
warnings: result.warnings?.map((warning) => ({
text: warning.message,
location: warning.start ? {
file: args.path,
line: warning.start.line,
column: warning.start.column,
} : undefined,
})) || [],
};
} catch (error) {
return {
errors: [{
text: error instanceof Error ? error.message : String(error),
location: { file: args.path },
}],
};
}
});
},
};
}
+3 -81
View File
@@ -190,7 +190,7 @@ describe('CurlCommand', () => {
expect(result.stdout).toContain('100 12 100 12');
});
it('should still output response body when -s flag is used', async () => {
it('should be silent when -s flag is used', async () => {
const mockResponse = {
ok: true,
status: 200,
@@ -205,7 +205,7 @@ describe('CurlCommand', () => {
const result = await curlCommand.execute(['-s', 'https://example.com'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('Hello World');
expect(result.stdout).toBe('');
});
it('should handle HTTP error responses', async () => {
@@ -272,9 +272,7 @@ describe('CurlCommand', () => {
const result = await curlCommand.execute(['-si', 'https://example.com'], '/test');
expect(result.exitCode).toBe(0);
// Silent mode still shows response body and headers (when -i is used)
expect(result.stdout).toContain('HTTP/1.1 200 OK');
expect(result.stdout).toContain('Hello World');
expect(result.stdout).toBe(''); // Silent mode
});
it('should handle write-out format', async () => {
@@ -308,82 +306,6 @@ describe('CurlCommand', () => {
expect(result.stderr).toContain('Network error');
});
it('should suppress errors when -s is used alone', async () => {
const mockResponse = {
ok: false,
status: 404,
statusText: 'Not Found',
url: 'https://example.com/notfound',
text: vi.fn().mockResolvedValue('Page not found'),
headers: new Map(),
redirected: false,
};
mockFetch.mockResolvedValue(mockResponse);
const result = await curlCommand.execute(['-s', 'https://example.com/notfound'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('Page not found');
expect(result.stderr).toBe('');
});
it('should show errors when -sS is used together', async () => {
const mockResponse = {
ok: false,
status: 404,
statusText: 'Not Found',
url: 'https://example.com/notfound',
text: vi.fn().mockResolvedValue('Page not found'),
headers: new Map(),
redirected: false,
};
mockFetch.mockResolvedValue(mockResponse);
const result = await curlCommand.execute(['-sS', 'https://example.com/notfound'], '/test');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('HTTP 404: Not Found');
expect(result.stderr).toContain('Page not found');
});
it('should show errors when -S is used with -s separately', async () => {
const mockResponse = {
ok: false,
status: 500,
statusText: 'Internal Server Error',
url: 'https://example.com/error',
text: vi.fn().mockResolvedValue('Server error'),
headers: new Map(),
redirected: false,
};
mockFetch.mockResolvedValue(mockResponse);
const result = await curlCommand.execute(['-s', '-S', 'https://example.com/error'], '/test');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('HTTP 500: Internal Server Error');
expect(result.stderr).toContain('Server error');
});
it('should suppress network errors when -s is used alone', async () => {
mockFetch.mockRejectedValue(new Error('Network error'));
const result = await curlCommand.execute(['-s', 'https://example.com'], '/test');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
expect(result.stderr).toBe('');
});
it('should show network errors when -sS is used together', async () => {
mockFetch.mockRejectedValue(new Error('Network error'));
const result = await curlCommand.execute(['-sS', 'https://example.com'], '/test');
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('Network error');
});
it('should handle timeout', async () => {
vi.useFakeTimers();
+9 -21
View File
@@ -16,7 +16,6 @@ interface CurlOptions {
includeHeaders: boolean;
followRedirects: boolean;
silent: boolean;
showError: boolean;
verbose: boolean;
userAgent?: string;
timeout?: number;
@@ -145,16 +144,15 @@ export class CurlCommand implements ShellCommand {
}
// Handle non-success status codes
if (!response.ok) {
const shouldShowError = !options.silent || options.showError;
if (!response.ok && !options.silent) {
const errorMsg = `HTTP ${response.status}: ${response.statusText}`;
if (options.output) {
// Still write to file even on error
await this.writeToFile(options.output, responseText, cwd);
return shouldShowError ? createErrorResult(errorMsg) : createSuccessResult('');
return createErrorResult(errorMsg);
} else {
output += responseText;
return shouldShowError ? createErrorResult(`${errorMsg}\n${output}`) : createSuccessResult(output);
return createErrorResult(`${errorMsg}\n${output}`);
}
}
@@ -173,21 +171,20 @@ export class CurlCommand implements ShellCommand {
// Handle write-out format
if (options.writeOut) {
const writeOutResult = this.formatWriteOut(options.writeOut, response, responseText);
output += '\n' + writeOutResult;
if (options.silent) {
return createSuccessResult(writeOutResult);
} else {
output += '\n' + writeOutResult;
}
}
return createSuccessResult(output);
return createSuccessResult(options.silent ? '' : output);
} catch (error) {
if (timeoutId) {
clearTimeout(timeoutId);
}
const shouldShowError = !options.silent || options.showError;
if (!shouldShowError) {
return createSuccessResult('');
}
if (error instanceof Error) {
if (error.name === 'AbortError') {
return createErrorResult(`${this.name}: operation timed out after ${options.timeout} seconds`);
@@ -216,7 +213,6 @@ export class CurlCommand implements ShellCommand {
includeHeaders: false,
followRedirects: true,
silent: false,
showError: false,
verbose: false,
maxRedirects: 50,
showProgress: true,
@@ -287,11 +283,6 @@ export class CurlCommand implements ShellCommand {
options.showProgress = false;
break;
case '-S':
case '--show-error':
options.showError = true;
break;
case '-v':
case '--verbose':
options.verbose = true;
@@ -342,9 +333,6 @@ export class CurlCommand implements ShellCommand {
options.silent = true;
options.showProgress = false;
break;
case '-S':
options.showError = true;
break;
case '-L':
options.followRedirects = true;
break;
+1 -93
View File
@@ -3,14 +3,11 @@ import {
readAISettings,
writeAISettings,
readGitSettings,
writeGitSettings,
readDeploySettings,
writeDeploySettings
writeGitSettings
} from './configUtils';
import type { JSRuntimeFS } from './JSRuntime';
import type { AISettings } from '@/contexts/AISettingsContext';
import type { GitSettings } from '@/contexts/GitSettingsContext';
import type { DeploySettings } from '@/contexts/DeploySettingsContext';
// Mock filesystem
const createMockFS = (): JSRuntimeFS => ({
@@ -193,93 +190,4 @@ describe('configUtils', () => {
});
describe('Deploy Settings', () => {
const sampleDeploySettings: DeploySettings = {
providers: [
{
id: 'provider-1',
name: 'My Netlify',
type: 'netlify',
apiKey: 'netlify-token-123',
},
{
id: 'provider-2',
name: 'My Vercel',
type: 'vercel',
apiKey: 'vercel-token-456',
},
{
id: 'provider-3',
name: 'Shakespeare',
type: 'shakespeare',
},
],
};
describe('readDeploySettings', () => {
it('should read Deploy settings from VFS', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(sampleDeploySettings));
const result = await readDeploySettings(mockFS);
expect(mockFS.readFile).toHaveBeenCalledWith('/config/deploy.json', 'utf8');
expect(result).toEqual(sampleDeploySettings);
});
it('should return default settings if file does not exist', async () => {
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
const result = await readDeploySettings(mockFS);
expect(result).toEqual({
providers: [],
});
});
it('should return default settings if JSON is invalid', async () => {
vi.mocked(mockFS.readFile).mockResolvedValue('invalid json');
const result = await readDeploySettings(mockFS);
expect(result).toEqual({
providers: [],
});
});
});
describe('writeDeploySettings', () => {
it('should write Deploy settings to VFS', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('Directory not found'));
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
await writeDeploySettings(mockFS, sampleDeploySettings);
expect(mockFS.mkdir).toHaveBeenCalledWith('/config', { recursive: true });
expect(mockFS.writeFile).toHaveBeenCalledWith(
'/config/deploy.json',
JSON.stringify(sampleDeploySettings, null, 2),
'utf8'
);
});
it('should not create directory if it already exists', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
await writeDeploySettings(mockFS, sampleDeploySettings);
expect(mockFS.mkdir).not.toHaveBeenCalled();
expect(mockFS.writeFile).toHaveBeenCalledWith(
'/config/deploy.json',
JSON.stringify(sampleDeploySettings, null, 2),
'utf8'
);
});
});
});
});
-71
View File
@@ -3,12 +3,10 @@ import { filteredArray } from '@/lib/schema';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import type { AIProvider, AISettings } from '@/contexts/AISettingsContext';
import type { GitSettings } from '@/contexts/GitSettingsContext';
import type { DeployProvider, DeploySettings } from '@/contexts/DeploySettingsContext';
const CONFIG_DIR = '/config';
const AI_CONFIG_PATH = `${CONFIG_DIR}/ai.json`;
const GIT_CONFIG_PATH = `${CONFIG_DIR}/git.json`;
const DEPLOY_CONFIG_PATH = `${CONFIG_DIR}/deploy.json`;
const aiProviderSchema: z.ZodType<AIProvider> = z.object({
id: z.string(),
@@ -48,47 +46,6 @@ const gitSettingsSchema = z.object({
coAuthorEnabled: z.boolean().optional(),
});
const baseDeployProviderSchema = z.object({
id: z.string(),
name: z.string(),
proxy: z.boolean().optional(),
});
const shakespeareDeployProviderSchema = baseDeployProviderSchema.extend({
type: z.literal('shakespeare'),
host: z.string().optional(),
});
const netlifyProviderSchema = baseDeployProviderSchema.extend({
type: z.literal('netlify'),
apiKey: z.string(),
baseURL: z.string().optional(),
});
const vercelProviderSchema = baseDeployProviderSchema.extend({
type: z.literal('vercel'),
apiKey: z.string(),
baseURL: z.string().optional(),
});
const nsiteProviderSchema = baseDeployProviderSchema.extend({
type: z.literal('nsite'),
gateway: z.string(),
relayUrls: z.array(z.string()),
blossomServers: z.array(z.string()),
});
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
shakespeareDeployProviderSchema,
netlifyProviderSchema,
vercelProviderSchema,
nsiteProviderSchema,
]);
const deploySettingsSchema = z.object({
providers: filteredArray(deployProviderSchema),
});
/**
* Ensures the config directory exists
*/
@@ -162,31 +119,3 @@ export async function writeGitSettings(fs: JSRuntimeFS, settings: GitSettings):
await fs.writeFile(GIT_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8');
}
/**
* Read Deploy settings from VFS
*/
export async function readDeploySettings(fs: JSRuntimeFS): Promise<DeploySettings> {
const defaultSettings: DeploySettings = {
providers: [],
};
try {
const content = await fs.readFile(DEPLOY_CONFIG_PATH, 'utf8');
const data = JSON.parse(content);
return deploySettingsSchema.parse(data);
} catch (error) {
if (error instanceof z.ZodError) {
console.error('Deploy settings parsing error:', error.errors);
}
return defaultSettings;
}
}
/**
* Write Deploy settings to VFS
*/
export async function writeDeploySettings(fs: JSRuntimeFS, settings: DeploySettings): Promise<void> {
await ensureConfigDir(fs);
await fs.writeFile(DEPLOY_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8');
}
+92
View File
@@ -0,0 +1,92 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { deployProject } from './deploy';
import type { JSRuntimeFS } from './JSRuntime';
import type { NostrSigner } from '@nostrify/nostrify';
// Mock JSZip
vi.mock('jszip', () => {
return {
default: vi.fn().mockImplementation(() => ({
folder: vi.fn().mockReturnValue({
file: vi.fn(),
}),
file: vi.fn(),
generateAsync: vi.fn().mockResolvedValue(new Blob()),
})),
};
});
// Mock NIP98Client
vi.mock('@nostrify/nostrify', () => ({
NIP98Client: vi.fn().mockImplementation(() => ({
fetch: vi.fn().mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
}),
})),
}));
describe('deployProject', () => {
let mockFS: JSRuntimeFS;
let mockSigner: NostrSigner;
beforeEach(() => {
mockFS = {
readFile: vi.fn().mockResolvedValue('mock file content'),
readdir: vi.fn().mockResolvedValue([]),
writeFile: vi.fn().mockResolvedValue(undefined),
mkdir: vi.fn().mockResolvedValue(undefined),
stat: vi.fn().mockResolvedValue({ isDirectory: () => false, isFile: () => true }),
lstat: vi.fn().mockResolvedValue({ isDirectory: () => false, isFile: () => true }),
unlink: vi.fn().mockResolvedValue(undefined),
rmdir: vi.fn().mockResolvedValue(undefined),
rename: vi.fn().mockResolvedValue(undefined),
readlink: vi.fn().mockResolvedValue(''),
symlink: vi.fn().mockResolvedValue(undefined),
} as JSRuntimeFS;
mockSigner = {} as NostrSigner;
});
it('should construct hostname from projectId and deployServer by default', async () => {
const result = await deployProject({
projectId: 'test-project',
deployServer: 'shakespeare.wtf',
fs: mockFS,
projectPath: '/projects/test-project',
signer: mockSigner,
});
expect(result.hostname).toBe('test-project.shakespeare.wtf');
expect(result.url).toBe('https://test-project.shakespeare.wtf');
});
it('should use customHostname when provided', async () => {
const result = await deployProject({
projectId: 'test-project',
deployServer: 'shakespeare.wtf',
fs: mockFS,
projectPath: '/projects/test-project',
signer: mockSigner,
customHostname: 'my-custom-domain.example.com',
});
expect(result.hostname).toBe('my-custom-domain.example.com');
expect(result.url).toBe('https://my-custom-domain.example.com');
});
it('should handle custom subdomain with same deploy server', async () => {
const result = await deployProject({
projectId: 'original-id',
deployServer: 'shakespeare.wtf',
fs: mockFS,
projectPath: '/projects/original-id',
signer: mockSigner,
customHostname: 'custom-name.shakespeare.wtf',
});
expect(result.hostname).toBe('custom-name.shakespeare.wtf');
expect(result.url).toBe('https://custom-name.shakespeare.wtf');
});
});
+107
View File
@@ -0,0 +1,107 @@
import JSZip from 'jszip';
import { NIP98Client } from '@nostrify/nostrify';
import type { NostrSigner } from '@nostrify/nostrify';
import type { JSRuntimeFS } from './JSRuntime';
export interface DeployOptions {
/** Project ID to use for hostname construction */
projectId: string;
/** Deploy server domain (e.g., "shakespeare.wtf") */
deployServer: string;
/** Filesystem instance containing the project */
fs: JSRuntimeFS;
/** Path to the project directory */
projectPath: string;
/** Nostr signer for NIP-98 authentication */
signer: NostrSigner;
/** Custom hostname to use instead of constructing from projectId.deployServer */
customHostname?: string;
}
export interface DeployResult {
/** The deployed URL */
url: string;
/** The hostname used */
hostname: string;
}
/**
* Deploy a project by creating a ZIP of the dist directory and uploading it
* to the deployment server using NIP-98 authentication.
*/
export async function deployProject(options: DeployOptions): Promise<DeployResult> {
const { projectId, deployServer, fs, projectPath, signer, customHostname } = options;
// Use custom hostname if provided, otherwise construct from projectId.deployServer
const hostname = customHostname || `${projectId}.${deployServer}`;
const deployUrl = `https://${deployServer}/deploy`;
const siteUrl = `https://${hostname}`;
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
await fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No index.html found in dist directory. Please build the project first.');
}
// Create ZIP of dist directory
const zip = new JSZip();
await addDirectoryToZip(fs, distPath, zip);
// Generate ZIP blob
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Create FormData
const formData = new FormData();
formData.append('hostname', hostname);
formData.append('file', zipBlob, `${projectId}.zip`);
// Create NIP-98 authenticated client and deploy
const nip98Client = new NIP98Client({ signer });
const response = await nip98Client.fetch(deployUrl, {
method: 'POST',
body: formData,
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Deployment failed: ${response.status} ${response.statusText}. ${errorText}`);
}
return {
url: siteUrl,
hostname,
};
}
/**
* Recursively add all files in a directory to a JSZip instance
*/
async function addDirectoryToZip(fs: JSRuntimeFS, dirPath: string, zip: JSZip): Promise<void> {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zip.folder(entry.name);
if (folder) {
await addDirectoryToZip(fs, fullPath, folder);
}
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await fs.readFile(fullPath);
zip.file(entry.name, fileContent);
} catch {
console.warn(`Failed to read file ${fullPath}`);
}
}
}
} catch {
console.warn(`Failed to read directory ${dirPath}`);
}
}
-178
View File
@@ -1,178 +0,0 @@
import JSZip from 'jszip';
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, NetlifyDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
interface NetlifySite {
id: string;
site_id: string;
name: string;
url: string;
admin_url: string;
}
interface NetlifyBuildResponse {
id: string;
deploy_id: string;
state: string;
error?: string;
}
/**
* Netlify Deploy Adapter
* Uses Netlify API with personal access token
*/
export class NetlifyAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private apiKey: string;
private baseURL: string;
private siteName?: string;
private siteId?: string;
private corsProxy?: string;
constructor(config: NetlifyDeployConfig) {
this.fs = config.fs;
this.apiKey = config.apiKey;
this.baseURL = config.baseURL || 'https://api.netlify.com/api/v1';
this.siteName = config.siteName;
this.siteId = config.siteId;
this.corsProxy = config.corsProxy;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No index.html found in dist directory. Please build the project first.');
}
// Get or create site
let activeSiteId = this.siteId;
let siteUrl = '';
if (!activeSiteId) {
// Create new site
const site = await this.createSite(this.siteName || projectId);
activeSiteId = site.id;
siteUrl = site.url;
} else {
// Get existing site URL
const site = await this.getSite(activeSiteId);
siteUrl = site.url;
}
// Create ZIP of dist directory
const zip = new JSZip();
await this.addDirectoryToZip(distPath, zip);
// Generate ZIP blob
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Deploy to Netlify
await this.triggerDeploy(activeSiteId, zipBlob);
return {
url: siteUrl,
metadata: {
siteId: activeSiteId,
provider: 'netlify',
},
};
}
private async createSite(name: string): Promise<NetlifySite> {
const url = `${this.baseURL}/sites`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name,
created_via: 'shakespeare',
}),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to create Netlify site: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async getSite(siteId: string): Promise<NetlifySite> {
const url = `${this.baseURL}/sites/${siteId}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
},
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to get Netlify site: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async triggerDeploy(siteId: string, zipBlob: Blob): Promise<NetlifyBuildResponse> {
const url = `${this.baseURL}/sites/${siteId}/deploys`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/zip',
},
body: zipBlob,
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to trigger Netlify build: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zip.folder(entry.name);
if (folder) {
await this.addDirectoryToZip(fullPath, folder);
}
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await this.fs.readFile(fullPath);
zip.file(entry.name, fileContent);
} catch {
console.warn(`Failed to read file ${fullPath}`);
}
}
}
} catch {
console.warn(`Failed to read directory ${dirPath}`);
}
}
}
-174
View File
@@ -1,174 +0,0 @@
import { BlossomUploader } from '@nostrify/nostrify/uploaders';
import { NSecSigner, NPool } from '@nostrify/nostrify';
import type { NostrEvent } from '@nostrify/nostrify';
import mime from 'mime';
import { nip19 } from 'nostr-tools';
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, NsiteDeployConfig } from './types';
/**
* Nsite Deploy Adapter
* Deploys static sites to Nostr using kind 34128 events and Blossom file storage
*/
export class NsiteAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private nostr: NsiteDeployConfig['nostr'];
private nsec: string;
private gateway: string;
private relayUrls: string[];
private blossomServers: string[];
constructor(config: NsiteDeployConfig) {
this.fs = config.fs;
this.nostr = config.nostr;
this.nsec = config.nsec;
this.gateway = config.gateway;
this.relayUrls = config.relayUrls;
this.blossomServers = config.blossomServers;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectPath } = options;
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No index.html found in dist directory. Please build the project first.');
}
// Decode nsec to get the private key and create signer
const decoded = nip19.decode(this.nsec);
if (decoded.type !== 'nsec') {
throw new Error('Invalid nsec format');
}
const signer = new NSecSigner(decoded.data);
const pubkey = await signer.getPublicKey();
// Create a grouped Nostr client for the configured relays
const relayClient = this.nostr.group(this.relayUrls);
// Initialize Blossom uploader
const uploader = new BlossomUploader({
servers: this.blossomServers,
signer,
});
// Collect all files and upload them
const fileEvents: NostrEvent[] = [];
await this.uploadDirectory(distPath, '', uploader, signer, fileEvents);
// Publish file events and other metadata to the relays
await Promise.all([
this.publishRelayList(signer, relayClient),
this.publishServerList(signer, relayClient),
...fileEvents.map(event => relayClient.event(event, { signal: AbortSignal.timeout(5000) })),
]);
// Generate npub subdomain
const npub = nip19.npubEncode(pubkey);
const siteUrl = `https://${npub}.${this.gateway}`;
return {
url: siteUrl,
metadata: {
pubkey,
npub,
filesPublished: fileEvents.length,
provider: 'nsite',
},
};
}
private async uploadDirectory(
dirPath: string,
relativePath: string,
uploader: BlossomUploader,
signer: NSecSigner,
fileEvents: NostrEvent[]
): Promise<void> {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
await this.uploadDirectory(fullPath, relPath, uploader, signer, fileEvents);
} else if (entry.isFile()) {
await this.uploadFile(fullPath, relPath, uploader, signer, fileEvents);
}
}
}
private async uploadFile(
filePath: string,
relativePath: string,
uploader: BlossomUploader,
signer: NSecSigner,
fileEvents: NostrEvent[]
): Promise<void> {
try {
// Read file content
const content = await this.fs.readFile(filePath);
// Convert to File object for upload
const file = new File([content], relativePath.split('/').pop() || 'file', {
type: mime.getType(filePath) || undefined,
});
// Upload to Blossom and get tags
const tags = await uploader.upload(file);
// Extract sha256 hash from tags
// Tags format: [['url', 'https://...'], ['x', 'sha256hash'], ['size', '1234'], ...]
const xTag = tags.find(([name]) => name === 'x');
if (!xTag || !xTag[1]) {
throw new Error(`Failed to get sha256 hash for ${relativePath}`);
}
const sha256 = xTag[1];
// Create absolute path (must start with /)
const absolutePath = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;
// Create kind 34128 event
const event = await signer.signEvent({
kind: 34128,
content: '',
created_at: Math.floor(Date.now() / 1000),
tags: [
['d', absolutePath],
['x', sha256],
],
});
fileEvents.push(event);
} catch (error) {
console.warn(`Failed to upload file ${filePath}:`, error);
throw error;
}
}
private async publishRelayList(signer: NSecSigner, relayClient: NPool): Promise<void> {
const relayListEvent = await signer.signEvent({
kind: 10002,
content: '',
created_at: Math.floor(Date.now() / 1000),
tags: this.relayUrls.map(url => ['r', url]),
});
await relayClient.event(relayListEvent, { signal: AbortSignal.timeout(5000) });
}
private async publishServerList(signer: NSecSigner, relayClient: NPool): Promise<void> {
const serverListEvent = await signer.signEvent({
kind: 10063,
content: '',
created_at: Math.floor(Date.now() / 1000),
tags: this.blossomServers.map(server => ['server', server]),
});
await relayClient.event(serverListEvent, { signal: AbortSignal.timeout(5000) });
}
}
-122
View File
@@ -1,122 +0,0 @@
import JSZip from 'jszip';
import { NIP98 } from '@nostrify/nostrify';
import { N64 } from '@nostrify/nostrify/utils';
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, ShakespeareDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
/**
* Shakespeare Deploy Adapter
* Uses NIP-98 authentication with Nostr signer
*/
export class ShakespeareAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private signer: ShakespeareDeployConfig['signer'];
private host: string;
private subdomain?: string;
private corsProxy?: string;
constructor(config: ShakespeareDeployConfig) {
this.fs = config.fs;
this.signer = config.signer;
this.host = config.host || 'shakespeare.wtf';
this.subdomain = config.subdomain;
this.corsProxy = config.corsProxy;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// Use custom subdomain if provided, otherwise construct from projectId
const hostname = this.subdomain
? `${this.subdomain}.${this.host}`
: `${projectId}.${this.host}`;
const deployUrl = `https://${this.host}/deploy`;
const siteUrl = `https://${hostname}`;
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No index.html found in dist directory. Please build the project first.');
}
// Create ZIP of dist directory
const zip = new JSZip();
await this.addDirectoryToZip(distPath, zip);
// Generate ZIP blob
const zipBlob = await zip.generateAsync({ type: 'blob' });
// Create FormData
const formData = new FormData();
formData.append('hostname', hostname);
formData.append('file', zipBlob, `${projectId}.zip`);
// Create the request
let request = new Request(deployUrl, {
method: 'POST',
body: formData,
});
// Create NIP-98 token for authentication
const template = await NIP98.template(request);
const event = await this.signer.signEvent(template);
const token = N64.encodeEvent(event);
// Add the Authorization header
const headers = new Headers(request.headers);
headers.set('Authorization', `Nostr ${token}`);
request = new Request(request, { headers });
// Apply proxy if configured
if (this.corsProxy) {
request = new Request(proxyUrl(this.corsProxy, request.url), request);
}
// Deploy
const response = await fetch(request);
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Deployment failed: ${response.status} ${response.statusText}. ${errorText}`);
}
return {
url: siteUrl,
metadata: {
hostname,
provider: 'shakespeare',
},
};
}
private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
if (entry.isDirectory()) {
// Create folder in zip and recursively add its contents
const folder = zip.folder(entry.name);
if (folder) {
await this.addDirectoryToZip(fullPath, folder);
}
} else if (entry.isFile()) {
// Add file to zip
try {
const fileContent = await this.fs.readFile(fullPath);
zip.file(entry.name, fileContent);
} catch {
console.warn(`Failed to read file ${fullPath}`);
}
}
}
} catch {
console.warn(`Failed to read directory ${dirPath}`);
}
}
}
-146
View File
@@ -1,146 +0,0 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, VercelDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
interface VercelFile {
file: string;
data: string;
encoding: 'base64';
}
interface VercelDeployment {
id: string;
url: string;
name: string;
readyState: string;
}
/**
* Vercel Deploy Adapter
* Uses Vercel REST API with access token
*/
export class VercelAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private apiKey: string;
private baseURL: string;
private teamId?: string;
private projectName?: string;
private corsProxy?: string;
constructor(config: VercelDeployConfig) {
this.fs = config.fs;
this.apiKey = config.apiKey;
this.baseURL = config.baseURL || 'https://api.vercel.com';
this.teamId = config.teamId;
this.projectName = config.projectName;
this.corsProxy = config.corsProxy;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No index.html found in dist directory. Please build the project first.');
}
// Collect all files from dist directory
const files: VercelFile[] = [];
await this.collectFiles(distPath, '', files);
// Create deployment payload
const deploymentPayload = {
name: this.projectName || projectId,
files,
projectSettings: {
framework: null, // Static deployment
},
target: 'production' as const,
};
// Build API URL with optional team parameter
let apiUrl = `${this.baseURL}/v13/deployments`;
if (this.teamId) {
apiUrl += `?teamId=${this.teamId}`;
}
// Apply proxy if configured
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, apiUrl) : apiUrl;
// Deploy to Vercel
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(deploymentPayload),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to deploy to Vercel: ${response.status} ${response.statusText}. ${errorText}`);
}
const deployment: VercelDeployment = await response.json();
return {
url: `https://${deployment.url}`,
metadata: {
deploymentId: deployment.id,
provider: 'vercel',
readyState: deployment.readyState,
},
};
}
private async collectFiles(
dirPath: string,
relativePath: string,
files: VercelFile[]
): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
// Recursively collect files from subdirectories
await this.collectFiles(fullPath, entryRelativePath, files);
} else if (entry.isFile()) {
try {
// Read file content
const fileContent = await this.fs.readFile(fullPath);
// Convert to base64 for Vercel API
let base64Content: string;
if (typeof fileContent === 'string') {
base64Content = btoa(fileContent);
} else {
// Handle Uint8Array
const binary = Array.from(fileContent)
.map(byte => String.fromCharCode(byte))
.join('');
base64Content = btoa(binary);
}
files.push({
file: entryRelativePath,
data: base64Content,
encoding: 'base64',
});
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
}
}
-5
View File
@@ -1,5 +0,0 @@
export * from './types';
export * from './ShakespeareAdapter';
export * from './NetlifyAdapter';
export * from './VercelAdapter';
export * from './NsiteAdapter';
-56
View File
@@ -1,56 +0,0 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { NostrSigner, NPool } from '@nostrify/nostrify';
export interface DeployOptions {
/** Project ID */
projectId: string;
/** Path to the project directory */
projectPath: string;
}
export interface DeployResult {
/** The deployed URL */
url: string;
/** Additional metadata */
metadata?: Record<string, unknown>;
}
export interface DeployAdapter {
/** Deploy a project */
deploy(options: DeployOptions): Promise<DeployResult>;
}
export interface ShakespeareDeployConfig {
fs: JSRuntimeFS;
signer: NostrSigner;
host?: string;
subdomain?: string;
corsProxy?: string;
}
export interface NetlifyDeployConfig {
fs: JSRuntimeFS;
apiKey: string;
baseURL?: string;
siteName?: string;
siteId?: string;
corsProxy?: string;
}
export interface VercelDeployConfig {
fs: JSRuntimeFS;
apiKey: string;
baseURL?: string;
teamId?: string;
projectName?: string;
corsProxy?: string;
}
export interface NsiteDeployConfig {
fs: JSRuntimeFS;
nostr: NPool;
nsec: string;
gateway: string;
relayUrls: string[];
blossomServers: string[];
}
-40
View File
@@ -1,40 +0,0 @@
import UriTemplate from 'uri-templates';
/**
* Generate a favicon URL from a template and input URL
* @param template - URL template with placeholders like {hostname}, {origin}, etc.
* @param url - The URL to extract parts from
* @returns The hydrated favicon URL
*/
export function faviconUrl(template: string, url: string | URL): string {
const u = new URL(url);
return UriTemplate(template).fill({
href: u.href,
origin: u.origin,
protocol: u.protocol,
username: u.username,
password: u.password,
host: u.host,
hostname: u.hostname,
port: u.port,
pathname: u.pathname,
hash: u.hash,
search: u.search,
});
}
/**
* Normalize a URL string to ensure it has a protocol
* @param url - The URL string to normalize
* @returns A fully-qualified URL string
*/
export function normalizeUrl(url: string): string {
// If it already has a protocol, return as-is
if (/^https?:\/\//i.test(url)) {
return url;
}
// Add https:// prefix
return `https://${url}`;
}
+12 -39
View File
@@ -38,6 +38,8 @@ const resources = {
previewDomainDescription: 'Domain used for iframe preview sandboxing.',
corsProxy: 'CORS Proxy',
corsProxyDescription: 'HTTP proxy URL for bypassing CORS restrictions.',
deployServer: 'Deploy Server',
deployServerDescription: 'Server domain where projects will be deployed.',
// Language Options
english: 'English',
@@ -86,9 +88,6 @@ const resources = {
aiSettingsDescription: 'Configure AI providers and API keys',
gitSettings: 'Git Settings',
gitSettingsDescription: 'Configure Git credentials for HTTP authentication',
deploySettings: 'Deployment',
deploySettingsDescription: 'Configure deployment providers',
deploySettingsDescriptionLong: 'Configure deployment providers to deploy your projects to various hosting platforms.',
nostrSettings: 'Nostr Settings',
nostrSettingsDescription: 'Configure relay connections and Nostr preferences',
storageSettings: 'Storage',
@@ -206,11 +205,6 @@ const resources = {
loginToNostrRequired: 'Log in to Nostr to use this provider',
goToNostrSettings: 'Go to Nostr Settings',
// Deploy Settings
shakespeareDeployNostrAuth: 'This provider uses Nostr authentication. Make sure you are logged in to deploy.',
providerType: 'Provider Type',
selectProviderType: 'Select a provider type',
// Git Settings
gitSettingsDescriptionLong: 'Configure Git credentials for HTTP authentication. Settings are automatically saved and stored locally in your browser.',
configuredCredentials: 'Configured Credentials',
@@ -418,9 +412,6 @@ const resources = {
aiSettingsDescription: 'Configure provedores de IA e chaves de API',
gitSettings: 'Configurações do Git',
gitSettingsDescription: 'Configure credenciais do Git para autenticação HTTP',
deploySettings: 'Implantação',
deploySettingsDescription: 'Configure provedores de implantação',
deploySettingsDescriptionLong: 'Configure provedores de implantação para implantar seus projetos em várias plataformas de hospedagem.',
nostrSettings: 'Configurações do Nostr',
nostrSettingsDescription: 'Configure conexões de relay e preferências do Nostr',
storageSettings: 'Armazenamento',
@@ -538,11 +529,6 @@ const resources = {
loginToNostrRequired: 'Faça login no Nostr para usar este provedor',
goToNostrSettings: 'Ir para Configurações do Nostr',
// Deploy Settings
shakespeareDeployNostrAuth: 'Este provedor usa autenticação Nostr. Certifique-se de estar logado para implantar.',
providerType: 'Tipo de Provedor',
selectProviderType: 'Selecione um tipo de provedor',
// Git Settings
gitSettingsDescriptionLong: 'Configure credenciais do Git para autenticação HTTP. As configurações são salvas automaticamente e armazenadas localmente em seu navegador.',
configuredCredentials: 'Credenciais Configuradas',
@@ -560,6 +546,8 @@ const resources = {
projectTemplateDescription: 'URL do repositório Git a ser usado como modelo inicial para novos projetos.',
corsProxy: 'Proxy CORS',
corsProxyDescription: 'Proxy usado para contornar CORS para operações de IA e Git.',
deployServer: 'Servidor de Deploy',
deployServerDescription: 'Domínio do servidor onde os projetos serão implantados.',
// Data Settings
dataSettingsDescriptionLong: 'Exporte arquivos e gerencie dados locais.',
@@ -754,9 +742,6 @@ const resources = {
aiSettingsDescription: '配置AI提供商和API密钥',
gitSettings: 'Git设置',
gitSettingsDescription: '配置HTTP身份验证的Git凭据',
deploySettings: '部署',
deploySettingsDescription: '配置部署提供商',
deploySettingsDescriptionLong: '配置部署提供商以将您的项目部署到各种托管平台。',
nostrSettings: 'Nostr设置',
nostrSettingsDescription: '配置中继连接和Nostr偏好',
storageSettings: '存储',
@@ -874,11 +859,6 @@ const resources = {
loginToNostrRequired: '登录Nostr以使用此提供商',
goToNostrSettings: '前往Nostr设置',
// Deploy Settings
shakespeareDeployNostrAuth: '此提供商使用Nostr身份验证。请确保您已登录以进行部署。',
providerType: '提供商类型',
selectProviderType: '选择提供商类型',
// Git Settings
gitSettingsDescriptionLong: '配置HTTP身份验证的Git凭据。设置会自动保存并存储在您的浏览器本地。',
configuredCredentials: '已配置的凭据',
@@ -896,6 +876,8 @@ const resources = {
projectTemplateDescription: '用作新项目起始模板的Git仓库URL。',
corsProxy: 'CORS代理',
corsProxyDescription: '用于绕过CORS的代理,适用于AI和Git操作。',
deployServer: '部署服务器',
deployServerDescription: '项目将部署到的服务器域名。',
// Data Settings
dataSettingsDescriptionLong: '导出文件和管理本地数据。',
@@ -1207,11 +1189,6 @@ const resources = {
loginToNostrRequired: 'Shiga Nostr don amfani da wannan mai samarwa',
goToNostrSettings: 'Tafi zuwa Saitunan Nostr',
// Deploy Settings
shakespeareDeployNostrAuth: 'Wannan mai samarwa yana amfani da tabbatar da Nostr. Tabbatar cewa kun shiga don tura.',
providerType: 'Nau\'in Mai Samarwa',
selectProviderType: 'Zaɓi nau\'in mai samarwa',
// Git Settings
gitSettingsDescriptionLong: 'Saita bayanan shaidar Git don tabbatar da HTTP. Saitunan ana ajiye su kai tsaye kuma ana adana su a cikin burauzar ku.',
configuredCredentials: 'Bayanan Shaidar da aka Saita',
@@ -1229,6 +1206,8 @@ const resources = {
projectTemplateDescription: 'URL ɗin ma\'ajin Git da za a yi amfani da shi azaman samfurin farawa don sababbin ayyuka.',
corsProxy: 'CORS Proxy',
corsProxyDescription: 'Proxy da ake amfani da shi don ketare CORS don ayyukan AI da Git.',
deployServer: 'Sabar Turawa',
deployServerDescription: 'Wurin sabar da za a tura ayyuka zuwa.',
// Data Settings
dataSettingsDescriptionLong: 'Fitar da fayiloli da sarrafa bayanan gida.',
@@ -1540,11 +1519,6 @@ const resources = {
loginToNostrRequired: 'Wọle si Nostr lati lo olupese yii',
goToNostrSettings: 'Lọ si Awọn eto Nostr',
// Deploy Settings
shakespeareDeployNostrAuth: 'Olupese yii nlo ijẹrisi Nostr. Rii daju pe o ti wọle lati gbe jade.',
providerType: 'Iru Olupese',
selectProviderType: 'Yan iru olupese kan',
// Git Settings
gitSettingsDescriptionLong: 'Tunto awọn ẹri Git fun ijẹrisi HTTP. Awọn eto ni a fi pamọ laifọwọyi ati pe a tọju wọn ni agbegbe ninu awọn aṣawakiri rẹ.',
configuredCredentials: 'Awọn Ẹri Ti a Tunto',
@@ -1562,6 +1536,8 @@ const resources = {
projectTemplateDescription: 'URL ibi ipamọ Git lati lo bi awoṣe ibẹrẹ fun awọn iṣẹ akanṣe tuntun.',
corsProxy: 'CORS Proxy',
corsProxyDescription: 'Olupin proxy ti a lo lati kọja CORS fun awọn iṣẹ AI ati Git.',
deployServer: 'Olupin Ifilọlẹ',
deployServerDescription: 'Aaye olupin nibiti a o fi awọn iṣẹ akanṣe ranṣẹ si.',
// Data Settings
dataSettingsDescriptionLong: 'Gbe awọn faili jade ati ṣakoso data agbegbe.',
@@ -1868,11 +1844,6 @@ const resources = {
loginToNostrRequired: 'Banye na Nostr iji jiri onye na-enye a',
goToNostrSettings: 'Gaa na Ntọala Nostr',
// Deploy Settings
shakespeareDeployNostrAuth: 'Onye na-enye a na-eji nkwenye Nostr. Jide n\'aka na ị banyere iji bufee.',
providerType: 'Ụdị Onye Na-enye',
selectProviderType: 'Họrọ ụdị onye na-enye',
// Git Settings
gitSettingsDescriptionLong: 'Hazie nzere Git maka nkwenye HTTP. Ntọala na-echekwa onwe ya ma chekwaa ya na mpaghara na browser gị.',
configuredCredentials: 'Nzere Ahaziri',
@@ -1890,6 +1861,8 @@ const resources = {
projectTemplateDescription: 'URL nchekwa Git iji mee ka ụdịdị mmalite maka ọrụ ọhụrụ.',
corsProxy: 'CORS Proxy',
corsProxyDescription: 'Sava proxy ejiri gafere CORS maka ọrụ AI na Git.',
deployServer: 'Sava Nnyefe',
deployServerDescription: 'Ngalaba sava ebe a ga-eziga ọrụ.',
// Data Settings
dataSettingsDescriptionLong: 'Bupụta faịlụ ma jikwaa data mpaghara.',
+1 -8
View File
@@ -1,4 +1,4 @@
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket } from 'lucide-react';
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings } from 'lucide-react';
export interface SettingsItem {
id: string;
@@ -35,13 +35,6 @@ export const getSettingsItems = (t: (key: string) => string): SettingsItem[] =>
icon: GitBranch,
href: '/settings/git',
},
{
id: 'deploy',
title: t('deploySettings'),
description: t('deploySettingsDescription'),
icon: Rocket,
href: '/settings/deploy',
},
{
id: 'nostr',
title: t('nostrSettings'),
+7 -10
View File
@@ -2,7 +2,7 @@ import { z } from "zod";
import type { Tool } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { ShakespeareAdapter } from "../deploy";
import { deployProject } from "../deploy";
import type { NostrSigner } from "@nostrify/nostrify";
interface DeployProjectParams {
@@ -47,19 +47,16 @@ export class DeployProjectTool implements Tool<DeployProjectParams> {
throw new Error(`❌ Could not find index.html in dist directory. Please build the project first using the build tool.`);
}
// Deploy the project using ShakespeareAdapter
const adapter = new ShakespeareAdapter({
fs: this.fs,
signer: this.signer,
host: deployServer,
});
const result = await adapter.deploy({
// Deploy the project
const result = await deployProject({
projectId: this.projectId,
deployServer,
fs: this.fs,
projectPath: this.cwd,
signer: this.signer,
});
return `✅ Successfully deployed project!\n\n🌐 Live URL: ${result.url}\n\n🚀 Your project is now live and accessible to anyone with the URL!`;
return `✅ Successfully deployed project!\n\n🌐 Live URL: ${result.url}\n📡 Hostname: ${result.hostname}\n\n🚀 Your project is now live and accessible to anyone with the URL!`;
} catch (error) {
throw new Error(`❌ Deployment failed: ${String(error)}`);
}
+1 -1
View File
@@ -58,7 +58,7 @@ export class NostrFetchEventTool implements Tool<NostrFetchEventParams> {
const decoded = nip19.decode(identifier);
const defaultRelays = [
'wss://relay.ditto.pub',
'wss://ditto.pub/relay',
'wss://relay.nostr.band',
'wss://relay.primal.net',
];
+1 -21
View File
@@ -92,28 +92,8 @@ describe('ReadConsoleMessagesTool', () => {
const limitedResult = await tool.execute({ limit: 2 });
expect(limitedResult).toContain('Found 2 console messages');
// Default limit (50) should return all messages when total is less than 50
// No limit should return all messages
const allResult = await tool.execute({});
expect(allResult).toContain('Found 4 console messages');
});
it('should show truncation note when messages exceed limit', async () => {
clearConsoleMessages();
// Add more messages than the limit
for (let i = 1; i <= 60; i++) {
addConsoleMessage('log', `Message ${i}`);
}
const tool = new ReadConsoleMessagesTool();
// Default limit is 50
const result = await tool.execute({});
expect(result).toContain('(showing last 50 of 60)');
expect(result).toContain('Message 60'); // Most recent
expect(result).not.toContain('Message 10'); // Too old
// Custom limit
const limitedResult = await tool.execute({ limit: 10 });
expect(limitedResult).toContain('(showing last 10 of 60)');
});
});
+7 -19
View File
@@ -1,4 +1,3 @@
import { z } from 'zod';
import { Tool } from './Tool';
import { getConsoleMessages } from '@/lib/consoleMessages';
@@ -12,25 +11,15 @@ export interface ReadConsoleMessagesParams {
* This tool allows AI assistants to access console logs for debugging assistance.
*/
export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams> {
readonly description = 'Read console messages from the project preview. Can filter by level and limit results.';
readonly inputSchema = z.object({
filter: z.enum(['error', 'warn', 'info', 'debug', 'log', 'all']).optional().describe(
'Filter messages by level. Defaults to "all" to show all message types.'
),
limit: z.number().min(1).max(200).optional().describe(
'Maximum number of most recent messages to return. Defaults to 50. Use smaller values (10-20) for quick checks, larger values (100-200) for comprehensive debugging.'
),
});
async execute(params: ReadConsoleMessagesParams): Promise<string> {
const { filter = 'all', limit = 50 } = params;
const { filter = 'all', limit } = params;
let messages = getConsoleMessages()
.filter(msg => filter === 'all' || msg.level === filter);
// Always apply a limit to prevent unbounded output
messages = messages.slice(-limit);
if (limit && limit > 0) {
messages = messages.slice(-limit);
}
if (messages.length === 0) {
return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`;
@@ -41,9 +30,8 @@ export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams>
.join('\n');
const suffix = filter !== 'all' ? ` (level: ${filter})` : '';
const totalAvailable = getConsoleMessages().filter(msg => filter === 'all' || msg.level === filter).length;
const truncatedNote = totalAvailable > messages.length ? ` (showing last ${messages.length} of ${totalAvailable})` : '';
return `Found ${messages.length} console message${messages.length !== 1 ? 's' : ''}${suffix}${truncatedNote}:\n\n${formatted}`;
return `Found ${messages.length} console message${messages.length !== 1 ? 's' : ''}${suffix}:\n\n${formatted}`;
}
description = 'Read console messages from the project preview. Can filter by level and limit results.';
}
-1
View File
@@ -1,5 +1,4 @@
import { createRoot } from 'react-dom/client';
import { webpm, fileContentStore } from '@webpm/webpm';
// Import polyfills first
import './lib/polyfills.ts';
+2 -4
View File
@@ -92,10 +92,8 @@ describe('AISettings', () => {
);
// Should show API key inputs for non-Nostr presets like OpenAI
const openAIElements = screen.getAllByText('OpenAI');
expect(openAIElements.length).toBeGreaterThan(0);
const openRouterElements = screen.getAllByText('OpenRouter');
expect(openRouterElements.length).toBeGreaterThan(0);
expect(screen.getByText('OpenAI')).toBeInTheDocument();
expect(screen.getByText('OpenRouter')).toBeInTheDocument();
// Should show Add buttons for non-Nostr presets
const addButtons = screen.getAllByText('Add');
+28 -60
View File
@@ -35,27 +35,6 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNavigate, Link } from 'react-router-dom';
import type { AIProvider } from '@/contexts/AISettingsContext';
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
import { ExternalFavicon } from '@/components/ExternalFavicon';
/** A few provider-specific icon hacks */
function getProviderIconUrl(provider: { id: string; baseURL: string }): string {
if (provider.id === 'ollama' && provider.baseURL === 'http://localhost:11434/v1') {
return 'https://ollama.com/';
} else if (provider.baseURL === 'https://generativelanguage.googleapis.com/v1beta/openai') {
return 'https://gemini.google.com/';
} else if (provider.baseURL === 'https://api.z.ai/api/paas/v4') {
return 'https://docs.z.ai/';
}
try {
// Strip .ai and .api subdomains for a better chance at finding a favicon
const urlObj = new URL(provider.baseURL);
urlObj.hostname = urlObj.hostname.replace(/^(ai\.|api\.)/, '');
return urlObj.toString();
} catch {
// Fallback to baseURL
return provider.baseURL;
}
}
interface SortableProviderItemProps {
provider: AIProvider;
@@ -91,33 +70,37 @@ function SortableProviderItem({ provider, preset, onRemove, onSetProvider, onOpe
className="border rounded-lg"
>
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2 w-full mr-3">
{showDragHandle && (
<div
{...attributes}
{...listeners}
className="cursor-grab active:cursor-grabbing p-1 -ml-1 text-muted-foreground hover:text-foreground"
>
<GripVertical className="h-4 w-4" />
</div>
)}
{provider.baseURL ? (
<ExternalFavicon
url={getProviderIconUrl(provider)}
size={16}
fallback={<Bot size={16} />}
/>
) : (
<Bot size={16} />
)}
<span className="font-medium">
{preset?.name || provider.id}
</span>
<div className="ml-auto">
<div className="flex items-center justify-between w-full mr-3">
<div className="flex items-center gap-2">
{showDragHandle && (
<div
{...attributes}
{...listeners}
className="cursor-grab active:cursor-grabbing p-1 -ml-1 text-muted-foreground hover:text-foreground"
>
<GripVertical className="h-4 w-4" />
</div>
)}
<span className="font-medium">
{preset?.name || provider.id}
</span>
</div>
<div className="flex items-center gap-2">
<CreditsBadge
provider={provider}
onOpenDialog={() => onOpenCreditsDialog(provider.id)}
/>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
onRemove(provider.id);
}}
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</AccordionTrigger>
@@ -175,14 +158,6 @@ function SortableProviderItem({ provider, preset, onRemove, onSetProvider, onOpe
{t('useCorsProxy')}
</Label>
</div>
<Button
variant="destructive"
size="sm"
onClick={() => onRemove(provider.id)}
>
<Trash2 className="h-4 w-4 mr-2" />
{t('delete')}
</Button>
</div>
</AccordionContent>
</AccordionItem>
@@ -388,14 +363,7 @@ export function AISettings() {
return (
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ExternalFavicon
url={getProviderIconUrl(preset)}
size={16}
fallback={<Bot size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
<h5 className="font-medium">{preset.name}</h5>
{(preset.apiKeysURL && preset.id !== "routstr") && (
<button
type="button"
-895
View File
@@ -1,895 +0,0 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Rocket, ArrowLeft, Trash2, Check, GripVertical, ChevronDown } from 'lucide-react';
import { Checkbox } from '@/components/ui/checkbox';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
DndContext,
closestCenter,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
type DragEndEvent,
} from '@dnd-kit/core';
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import {
useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { Label } from '@/components/ui/label';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useDeploySettings } from '@/hooks/useDeploySettings';
import { useNetlifyOAuth } from '@/hooks/useNetlifyOAuth';
import { useVercelOAuth } from '@/hooks/useVercelOAuth';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useNavigate, Link } from 'react-router-dom';
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { normalizeUrl } from '@/lib/faviconUrl';
interface PresetProvider {
id: string;
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite';
name: string;
description: string;
requiresNostr?: boolean;
apiKeyLabel?: string;
apiKeyURL?: string;
proxy?: boolean;
}
interface SortableProviderItemProps {
provider: DeployProvider;
index: number;
preset?: PresetProvider;
onRemove: (index: number) => void;
onUpdate: (index: number, provider: DeployProvider) => void;
showDragHandle: boolean;
}
function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, showDragHandle }: SortableProviderItemProps) {
const { t } = useTranslation();
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
} = useSortable({ id: index });
const style = {
transform: CSS.Transform.toString(transform),
transition,
};
return (
<AccordionItem
ref={setNodeRef}
style={style}
value={String(index)}
className="border rounded-lg"
>
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
{showDragHandle && (
<div
{...attributes}
{...listeners}
className="cursor-grab active:cursor-grabbing p-1 -ml-1 text-muted-foreground hover:text-foreground"
>
<GripVertical className="h-4 w-4" />
</div>
)}
{(() => {
const url = getProviderUrl(provider);
return url ? (
<ExternalFavicon
url={url}
size={16}
fallback={<Rocket size={16} />}
/>
) : (
<Rocket size={16} />
);
})()}
<span className="font-medium">
{provider.name}
</span>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-name`}>Name</Label>
<Input
id={`provider-${index}-name`}
placeholder="Provider name"
value={provider.name}
onChange={(e) => onUpdate(index, { ...provider, name: e.target.value })}
/>
</div>
{provider.type === 'shakespeare' ? (
<>
<p className="text-sm text-muted-foreground">
{t('shakespeareDeployNostrAuth')}
</p>
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-host`}>
Host (Optional)
</Label>
<Input
id={`provider-${index}-host`}
placeholder="shakespeare.wtf"
value={provider.host || ''}
onChange={(e) => onUpdate(index, { ...provider, host: e.target.value })}
/>
</div>
</>
) : provider.type === 'nsite' ? (
<>
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-gateway`}>Gateway</Label>
<Input
id={`provider-${index}-gateway`}
placeholder="nsite.lol"
value={provider.gateway || ''}
onChange={(e) => onUpdate(index, { ...provider, gateway: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-relays`}>Relay URLs (comma-separated)</Label>
<Input
id={`provider-${index}-relays`}
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
value={provider.relayUrls?.join(', ') || ''}
onChange={(e) => onUpdate(index, {
...provider,
relayUrls: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
})}
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-blossom`}>Blossom Servers (comma-separated)</Label>
<Input
id={`provider-${index}-blossom`}
placeholder="https://blossom.primal.net/"
value={provider.blossomServers?.join(', ') || ''}
onChange={(e) => onUpdate(index, {
...provider,
blossomServers: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
})}
/>
</div>
</>
) : (
<>
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-apiKey`}>
{preset?.apiKeyLabel || t('apiKey')}
</Label>
<PasswordInput
id={`provider-${index}-apiKey`}
placeholder={t('enterApiKey')}
value={provider.apiKey}
onChange={(e) => {
if (provider.type === 'netlify') {
onUpdate(index, { ...provider, apiKey: e.target.value });
} else if (provider.type === 'vercel') {
onUpdate(index, { ...provider, apiKey: e.target.value });
}
}}
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-baseURL`}>
Base URL (Optional)
</Label>
<Input
id={`provider-${index}-baseURL`}
placeholder={provider.type === 'netlify' ? 'https://api.netlify.com/api/v1' : 'https://api.vercel.com'}
value={provider.baseURL || ''}
onChange={(e) => {
if (provider.type === 'netlify') {
onUpdate(index, { ...provider, baseURL: e.target.value });
} else if (provider.type === 'vercel') {
onUpdate(index, { ...provider, baseURL: e.target.value });
}
}}
/>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id={`provider-${index}-proxy`}
checked={provider.proxy || false}
onCheckedChange={(checked) => onUpdate(index, { ...provider, proxy: checked === true })}
/>
<Label
htmlFor={`provider-${index}-proxy`}
className="text-sm font-normal cursor-pointer"
>
Use CORS Proxy
</Label>
</div>
</>
)}
<Button
variant="destructive"
size="sm"
onClick={() => onRemove(index)}
>
<Trash2 className="h-4 w-4 mr-2" />
{t('delete')}
</Button>
</div>
</AccordionContent>
</AccordionItem>
);
}
const PRESET_PROVIDERS: PresetProvider[] = [
{
id: 'shakespeare',
type: 'shakespeare',
name: 'Shakespeare Deploy',
description: 'Deploy to Shakespeare hosting with Nostr authentication',
requiresNostr: true,
},
{
id: 'nsite',
type: 'nsite',
name: 'nsite',
description: 'Deploy to Nostr as a static website',
},
{
id: 'netlify',
type: 'netlify',
name: 'Netlify',
description: 'Deploy to Netlify',
apiKeyLabel: 'Personal Access Token',
apiKeyURL: 'https://app.netlify.com/user/applications#personal-access-tokens',
proxy: true,
},
{
id: 'vercel',
type: 'vercel',
name: 'Vercel',
description: 'Deploy to Vercel',
apiKeyLabel: 'Access Token',
apiKeyURL: 'https://vercel.com/account/tokens',
proxy: true,
},
];
// Helper function to generate custom provider ID
function generateCustomProviderId(type: string): string {
const uuid = crypto.randomUUID();
const randomSegment = uuid.split('-')[0];
return `${type}-${randomSegment}`;
}
function getProviderUrl(provider: DeployProvider | PresetProvider): string | null {
switch (provider.type) {
case 'shakespeare':
// For Shakespeare providers, check for custom host first, then use default
if ('host' in provider && provider.host) {
return normalizeUrl(provider.host);
}
return 'https://shakespeare.diy';
case 'netlify':
// For Netlify providers, check for custom baseURL first, then use default
if ('baseURL' in provider && provider.baseURL) {
return provider.baseURL;
}
return 'https://netlify.com';
case 'vercel':
// For Vercel providers, check for custom baseURL first, then use default
if ('baseURL' in provider && provider.baseURL) {
return provider.baseURL;
}
return 'https://vercel.com';
case 'nsite':
// nsite uses Rocket icon fallback
return null;
default:
return null;
}
}
export function DeploySettings() {
const { t } = useTranslation();
const { settings, removeProvider, setProviders } = useDeploySettings();
const { user } = useCurrentUser();
const isMobile = useIsMobile();
const navigate = useNavigate();
// OAuth hooks
const netlifyOAuth = useNetlifyOAuth();
const vercelOAuth = useVercelOAuth();
const [presetApiKeys, setPresetApiKeys] = useState<Record<string, string>>({});
const [forceManualEntry, setForceManualEntry] = useState<Record<string, boolean>>({});
// Custom provider form state
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | ''>('');
const [customName, setCustomName] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customBaseURL, setCustomBaseURL] = useState('');
const [customHost, setCustomHost] = useState('');
const [customProxy, setCustomProxy] = useState(false);
const [customGateway, setCustomGateway] = useState('');
const [customRelayUrls, setCustomRelayUrls] = useState('');
const [customBlossomServers, setCustomBlossomServers] = useState('');
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
})
);
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (over && active.id !== over.id) {
const oldIndex = settings.providers.findIndex((_, i) => i === active.id);
const newIndex = settings.providers.findIndex((_, i) => i === over.id);
const newProviders = arrayMove(settings.providers, oldIndex, newIndex);
setProviders(newProviders);
}
};
const handleAddPresetProvider = (preset: PresetProvider) => {
// For Shakespeare, just check if user is logged in
if (preset.requiresNostr && !user) {
return;
}
const apiKey = presetApiKeys[preset.id];
// For non-Shakespeare/non-nsite providers, require API key
if (!preset.requiresNostr && preset.type !== 'nsite' && !apiKey?.trim()) {
return;
}
let newProvider: DeployProvider;
if (preset.type === 'shakespeare') {
newProvider = {
id: preset.id, // Use preset ID for presets
name: preset.name,
type: 'shakespeare',
...(preset.proxy && { proxy: true }),
};
} else if (preset.type === 'nsite') {
newProvider = {
id: preset.id, // Use preset ID for presets
name: preset.name,
type: 'nsite',
gateway: 'nosto.re',
relayUrls: [
'wss://relay.nsite.lol',
'wss://relay.nosto.re',
'wss://relay.nostr.band',
'wss://relay.primal.net',
'wss://relay.damus.io',
'wss://purplerelay.com',
],
blossomServers: [
'https://blossom.primal.net',
'https://cdn.sovbit.host',
],
};
} else if (preset.type === 'netlify') {
newProvider = {
id: preset.id, // Use preset ID for presets
name: preset.name,
type: 'netlify',
apiKey: apiKey.trim(),
...(preset.proxy && { proxy: true }),
};
} else {
newProvider = {
id: preset.id, // Use preset ID for presets
name: preset.name,
type: 'vercel',
apiKey: apiKey.trim(),
...(preset.proxy && { proxy: true }),
};
}
setProviders([...settings.providers, newProvider]);
// Clear inputs
setPresetApiKeys(prev => ({ ...prev, [preset.id]: '' }));
};
const handleAddCustomProvider = () => {
if (!customProviderType || !customName.trim()) return;
let newProvider: DeployProvider;
if (customProviderType === 'shakespeare') {
newProvider = {
id: generateCustomProviderId(customProviderType), // Generate custom ID
name: customName.trim(),
type: 'shakespeare',
...(customHost?.trim() && { host: customHost.trim() }),
...(customProxy && { proxy: true }),
};
} else if (customProviderType === 'nsite') {
const gateway = customGateway.trim() || 'nsite.lol';
const relayUrls = customRelayUrls.trim()
? customRelayUrls.split(',').map(s => s.trim()).filter(Boolean)
: ['wss://relay.nostr.band'];
const blossomServers = customBlossomServers.trim()
? customBlossomServers.split(',').map(s => s.trim()).filter(Boolean)
: ['https://blossom.primal.net/'];
newProvider = {
id: generateCustomProviderId(customProviderType), // Generate custom ID
name: customName.trim(),
type: 'nsite',
gateway,
relayUrls,
blossomServers,
};
} else if (customProviderType === 'netlify') {
if (!customApiKey.trim()) return;
newProvider = {
id: generateCustomProviderId(customProviderType), // Generate custom ID
name: customName.trim(),
type: 'netlify',
apiKey: customApiKey.trim(),
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customProxy && { proxy: true }),
};
} else {
if (!customApiKey.trim()) return;
newProvider = {
id: generateCustomProviderId(customProviderType), // Generate custom ID
name: customName.trim(),
type: 'vercel',
apiKey: customApiKey.trim(),
...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }),
...(customProxy && { proxy: true }),
};
}
setProviders([...settings.providers, newProvider]);
// Clear form
setCustomProviderType('');
setCustomName('');
setCustomApiKey('');
setCustomBaseURL('');
setCustomHost('');
setCustomProxy(false);
};
const handleRemoveProvider = (index: number) => {
removeProvider(index);
};
const handleUpdateProvider = (index: number, provider: DeployProvider) => {
const newProviders = [...settings.providers];
newProviders[index] = provider;
setProviders(newProviders);
};
const configuredProviderIds = settings.providers.map(p => p.id);
const availablePresets = PRESET_PROVIDERS.filter(preset => !configuredProviderIds.includes(preset.id));
return (
<div className="p-6 space-y-6">
{isMobile && (
<div className="space-y-3">
<Button
variant="ghost"
size="sm"
onClick={() => navigate('/settings')}
className="h-8 w-auto px-2 -ml-2"
>
<ArrowLeft className="h-4 w-4 mr-2" />
{t('backToSettings')}
</Button>
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Rocket className="h-6 w-6 text-primary" />
{t('deploySettings')}
</h1>
<p className="text-muted-foreground">
{t('deploySettingsDescriptionLong')}
</p>
</div>
</div>
)}
{!isMobile && (
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<Rocket className="h-6 w-6 text-primary" />
{t('deploySettings')}
</h1>
<p className="text-muted-foreground">
{t('deploySettingsDescriptionLong')}
</p>
</div>
)}
<div className="space-y-6">
{/* Configured Providers */}
{settings.providers.length > 0 && (
<div className="space-y-3">
<h4 className="text-sm font-medium">{t('configuredProviders')}</h4>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={settings.providers.map((_, index) => index)}
strategy={verticalListSortingStrategy}
>
<Accordion type="multiple" className="w-full space-y-2">
{settings.providers.map((provider, index) => {
const preset = PRESET_PROVIDERS.find(p => p.type === provider.type);
return (
<SortableProviderItem
key={index}
provider={provider}
index={index}
preset={preset}
onRemove={handleRemoveProvider}
onUpdate={handleUpdateProvider}
showDragHandle={settings.providers.length > 1}
/>
);
})}
</Accordion>
</SortableContext>
</DndContext>
</div>
)}
{/* Available Preset Providers */}
{availablePresets.length > 0 && (
<div className="space-y-3">
<h4 className="text-sm font-medium">{t('addProvider')}</h4>
<div className="grid grid-cols-[repeat(auto-fit,minmax(min(280px,100%),1fr))] gap-3">
{availablePresets.map((preset) => {
const isNostrPreset = preset.requiresNostr;
const isLoggedIntoNostr = !!user;
const showNostrLoginRequired = isNostrPreset && !isLoggedIntoNostr;
// Get OAuth hook for this preset
const oauthHook = preset.type === 'netlify' ? netlifyOAuth :
preset.type === 'vercel' ? vercelOAuth : null;
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
const isOAuthLoading = oauthHook?.isLoading ?? false;
const oauthError = oauthHook?.error ?? null;
return (
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{(() => {
const url = getProviderUrl(preset);
return url ? (
<ExternalFavicon
url={url}
size={16}
fallback={<Rocket size={16} />}
/>
) : (
<Rocket size={16} />
);
})()}
<h5 className="font-medium">{preset.name}</h5>
</div>
{preset.apiKeyURL && !isOAuthConfigured && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeyURL, '_blank')}
>
{t('getApiKey')}
</button>
)}
</div>
<p className="text-sm text-muted-foreground">{preset.description}</p>
{showNostrLoginRequired ? (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
{t('loginToNostrRequired')}
</p>
<Button asChild className="w-full">
<Link to="/settings/nostr">
{t('goToNostrSettings')}
</Link>
</Button>
</div>
) : isOAuthConfigured && !forceManualEntry[preset.id] ? (
// Show OAuth button if OAuth is configured and not forced to manual
<div className="space-y-3">
<div className="flex gap-0">
<Button
onClick={() => oauthHook?.initiateOAuth()}
disabled={isOAuthLoading}
className="flex-1 rounded-r-none gap-2"
variant="default"
>
{isOAuthLoading ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
Connecting...
</>
) : (
<>
{(() => {
const url = getProviderUrl(preset);
return url ? (
<ExternalFavicon
url={url}
size={16}
fallback={<Rocket size={16} />}
/>
) : (
<Rocket size={16} />
);
})()}
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
</>
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="default"
className="rounded-l-none border-l border-primary-foreground/20 px-2"
disabled={isOAuthLoading}
>
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => setForceManualEntry(prev => ({ ...prev, [preset.id]: true }))}
>
Enter API key
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{oauthError && (
<p className="text-sm text-destructive">
{oauthError}
</p>
)}
</div>
) : (
// Show manual token input
<div className="space-y-2">
<div className="flex gap-2">
{!preset.requiresNostr && preset.type !== 'nsite' && (
<PasswordInput
placeholder={preset.apiKeyLabel || t('enterApiKey')}
className="flex-1"
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) {
handleAddPresetProvider(preset);
}
}}
/>
)}
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={
(preset.requiresNostr && !isLoggedIntoNostr) ||
(!preset.requiresNostr && preset.type !== 'nsite' && !presetApiKeys[preset.id]?.trim())
}
className={(preset.requiresNostr || preset.type === 'nsite') ? "w-full" : "h-10 px-4 ml-auto"}
>
{t('add')}
</Button>
</div>
</div>
)}
</div>
);
})}
</div>
</div>
)}
{/* Custom Provider */}
<div className="space-y-3">
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="custom-provider" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor="custom-provider-type">{t('providerType')}</Label>
<Select
value={customProviderType}
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite') => {
setCustomProviderType(value);
// Reset form when provider type changes
setCustomApiKey('');
setCustomBaseURL('');
setCustomHost('');
setCustomProxy(false);
setCustomGateway('');
setCustomRelayUrls('');
setCustomBlossomServers('');
}}
>
<SelectTrigger>
<SelectValue placeholder={t('selectProviderType')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="shakespeare">Shakespeare Deploy</SelectItem>
<SelectItem value="nsite">nsite</SelectItem>
<SelectItem value="netlify">Netlify</SelectItem>
<SelectItem value="vercel">Vercel</SelectItem>
</SelectContent>
</Select>
</div>
{customProviderType && (
<>
<div className="grid gap-2">
<Label htmlFor="custom-name">{t('providerName')}</Label>
<Input
id="custom-name"
placeholder="e.g., My Production Deploy"
value={customName}
onChange={(e) => setCustomName(e.target.value)}
/>
</div>
{customProviderType === 'shakespeare' ? (
<>
<p className="text-sm text-muted-foreground">
{t('shakespeareDeployNostrAuth')}
</p>
<div className="grid gap-2">
<Label htmlFor="custom-host">Host (Optional)</Label>
<Input
id="custom-host"
placeholder="shakespeare.wtf"
value={customHost}
onChange={(e) => setCustomHost(e.target.value)}
/>
</div>
</>
) : customProviderType === 'nsite' ? (
<>
<p className="text-sm text-muted-foreground">
Deploy to Nostr as a static website. Uses kind 34128 events and Blossom file storage.
</p>
<div className="grid gap-2">
<Label htmlFor="custom-gateway">Gateway</Label>
<Input
id="custom-gateway"
placeholder="nsite.lol"
value={customGateway}
onChange={(e) => setCustomGateway(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-relays">Relay URLs (comma-separated)</Label>
<Input
id="custom-relays"
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
value={customRelayUrls}
onChange={(e) => setCustomRelayUrls(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-blossom">Blossom Servers (comma-separated)</Label>
<Input
id="custom-blossom"
placeholder="https://blossom.primal.net/"
value={customBlossomServers}
onChange={(e) => setCustomBlossomServers(e.target.value)}
/>
</div>
</>
) : (
<>
<div className="grid gap-2">
<Label htmlFor="custom-apikey">
{customProviderType === 'netlify' ? 'Personal Access Token' : 'Access Token'}
</Label>
<PasswordInput
id="custom-apikey"
placeholder={t('enterApiKey')}
value={customApiKey}
onChange={(e) => setCustomApiKey(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-baseurl">Base URL (Optional)</Label>
<Input
id="custom-baseurl"
placeholder={
customProviderType === 'netlify'
? 'https://api.netlify.com/api/v1'
: 'https://api.vercel.com'
}
value={customBaseURL}
onChange={(e) => setCustomBaseURL(e.target.value)}
/>
</div>
</>
)}
<div className="flex items-center space-x-2">
<Checkbox
id="custom-proxy"
checked={customProxy}
onCheckedChange={(checked) => setCustomProxy(checked === true)}
/>
<Label htmlFor="custom-proxy" className="text-sm font-normal cursor-pointer">
Use CORS Proxy
</Label>
</div>
<Button
onClick={handleAddCustomProvider}
disabled={
!customProviderType ||
!customName.trim() ||
(customProviderType !== 'shakespeare' && customProviderType !== 'nsite' && !customApiKey.trim())
}
className="gap-2 ml-auto"
>
<Check className="h-4 w-4" />
{t('add')}
</Button>
</>
)}
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
</div>
</div>
);
}
export default DeploySettings;
+1 -8
View File
@@ -1,7 +1,6 @@
import { useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useGitHubOAuth } from '@/hooks/useGitHubOAuth';
import { useGitSettings } from '@/hooks/useGitSettings';
import { useToast } from '@/hooks/useToast';
import { Card, CardContent } from '@/components/ui/card';
import { Github } from 'lucide-react';
@@ -10,15 +9,9 @@ export default function GitHubOAuth() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { handleCallback } = useGitHubOAuth();
const { isInitialized } = useGitSettings();
const { toast } = useToast();
useEffect(() => {
// Wait for git settings to be initialized
if (!isInitialized) {
return;
}
const code = searchParams.get('code');
const state = searchParams.get('state');
const error = searchParams.get('error');
@@ -70,7 +63,7 @@ export default function GitHubOAuth() {
// No code or state parameters - redirect to Git settings
navigate('/settings/git');
}
}, [searchParams, handleCallback, toast, navigate, isInitialized]);
}, [searchParams, handleCallback, toast, navigate]);
return (
<div className="min-h-screen flex items-center justify-center p-4">
+41 -80
View File
@@ -1,25 +1,18 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, GitBranch, ArrowLeft, Trash2, ChevronDown } from 'lucide-react';
import { Check, GitBranch, ArrowLeft, Github, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Switch } from '@/components/ui/switch';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useGitSettings } from '@/hooks/useGitSettings';
import { useGitHubOAuth } from '@/hooks/useGitHubOAuth';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useNavigate } from 'react-router-dom';
import type { GitCredential } from '@/contexts/GitSettingsContext';
import { PasswordInput } from '@/components/ui/password-input';
import { ExternalFavicon } from '@/components/ExternalFavicon';
interface PresetProvider {
id: string;
@@ -56,7 +49,6 @@ export function GitSettings() {
const [customUsername, setCustomUsername] = useState('');
const [customPassword, setCustomPassword] = useState('');
const [presetTokens, setPresetTokens] = useState<Record<string, string>>({});
const [forceManualEntry, setForceManualEntry] = useState<Record<string, boolean>>({});
const handleAddPresetProvider = (preset: PresetProvider) => {
const token = presetTokens[preset.id] as string | undefined;
@@ -158,16 +150,24 @@ export function GitSettings() {
return (
<AccordionItem key={origin} value={origin} className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<ExternalFavicon
url={origin}
size={16}
fallback={<GitBranch size={16} />}
/>
<span className="font-medium">
{preset?.name || new URL(origin).hostname}
</span>
{isCustom && <Badge variant="outline">{t('custom')}</Badge>}
<div className="flex items-center justify-between w-full mr-3">
<div className="flex items-center gap-2">
<span className="font-medium">
{preset?.name || new URL(origin).hostname}
</span>
{isCustom && <Badge variant="outline">{t('custom')}</Badge>}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.stopPropagation();
handleRemoveCredential(origin);
}}
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
@@ -200,14 +200,6 @@ export function GitSettings() {
onChange={(e) => handleUpdateCredential(origin, { password: e.target.value })}
/>
</div>
<Button
variant="destructive"
size="sm"
onClick={() => handleRemoveCredential(origin)}
>
<Trash2 className="h-4 w-4 mr-2" />
{t('delete')}
</Button>
</div>
</AccordionContent>
</AccordionItem>
@@ -225,14 +217,7 @@ export function GitSettings() {
{availablePresets.map((preset) => (
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.origin}
size={16}
fallback={<GitBranch size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
<h5 className="font-medium">{preset.name}</h5>
{preset.tokenURL && (preset.id !== 'github' || !isOAuthConfigured) && (
<button
type="button"
@@ -246,52 +231,28 @@ export function GitSettings() {
{preset.id === 'github' ? (
// Special rendering for GitHub - OAuth button if configured, otherwise token input
isOAuthConfigured && !forceManualEntry[preset.id] ? (
isOAuthConfigured ? (
<div className="space-y-3">
<div className="flex gap-0">
<Button
onClick={initiateOAuth}
disabled={isOAuthLoading}
className="flex-1 rounded-r-none gap-2"
variant="default"
>
{isOAuthLoading ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
Connecting...
</>
) : (
<>
<ExternalFavicon
url="https://github.com"
size={16}
fallback={<GitBranch size={16} />}
/>
<span className="truncate text-ellipsis overflow-hidden">
Connect to GitHub
</span>
</>
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="default"
className="rounded-l-none border-l border-primary-foreground/20 px-2"
disabled={isOAuthLoading}
>
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => setForceManualEntry(prev => ({ ...prev, [preset.id]: true }))}
>
Enter API key
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<Button
onClick={initiateOAuth}
disabled={isOAuthLoading}
className="w-full max-w-full gap-2"
variant="default"
>
{isOAuthLoading ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
Connecting...
</>
) : (
<>
<Github className="h-4 w-4" />
<span className="truncate text-ellipsis overflow-hidden">
Connect to GitHub
</span>
</>
)}
</Button>
{oauthError && (
<p className="text-sm text-destructive">
{oauthError}
-86
View File
@@ -1,86 +0,0 @@
import { useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useNetlifyOAuth } from '@/hooks/useNetlifyOAuth';
import { useDeploySettings } from '@/hooks/useDeploySettings';
import { useToast } from '@/hooks/useToast';
import { Card, CardContent } from '@/components/ui/card';
export default function NetlifyOAuth() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { handleCallback } = useNetlifyOAuth();
const { isInitialized } = useDeploySettings();
const { toast } = useToast();
useEffect(() => {
// Wait for deploy settings to be initialized
if (!isInitialized) {
return;
}
const code = searchParams.get('code');
const state = searchParams.get('state');
const error = searchParams.get('error');
const errorDescription = searchParams.get('error_description');
const storedState = localStorage.getItem('netlify_oauth_state');
// Handle OAuth errors
if (error) {
toast({
title: "Netlify OAuth Error",
description: errorDescription || error,
variant: "destructive",
});
navigate('/settings/deploy');
return;
}
// Handle successful OAuth callback
if (code && state && storedState) {
handleCallback(code, state).then((success) => {
if (success) {
toast({
title: "Netlify Connected",
description: "Successfully connected to Netlify. You can now deploy your projects.",
});
} else {
toast({
title: "Connection Failed",
description: "Failed to connect to Netlify. Please try again.",
variant: "destructive",
});
}
// Always redirect to Deploy settings after handling the callback
navigate('/settings/deploy');
});
} else {
// No code or state parameters - redirect to Deploy settings
navigate('/settings/deploy');
}
}, [searchParams, handleCallback, toast, navigate, isInitialized]);
return (
<div className="min-h-screen flex items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardContent className="py-12 px-8 text-center">
<div className="space-y-6">
<div className="flex justify-center">
<svg className="h-12 w-12 text-primary" viewBox="0 0 24 24" fill="currentColor">
<path d="M16.934 8.519a1.044 1.044 0 0 1 .303.23l2.349 2.348a1 1 0 0 1 0 1.414l-2.348 2.349a1.044 1.044 0 0 1-.231.303 1.042 1.042 0 0 1-1.473-1.473l.527-.527H11a1 1 0 1 1 0-2h5.061l-.527-.527a1.042 1.042 0 0 1 1.4-1.517zM7.066 15.481a1.044 1.044 0 0 1-.303-.23l-2.349-2.348a1 1 0 0 1 0-1.414l2.348-2.349a1.044 1.044 0 0 1 .231-.303 1.042 1.042 0 0 1 1.473 1.473l-.527.527H13a1 1 0 0 1 0 2H7.939l.527.527a1.042 1.042 0 0 1-1.4 1.517z" />
</svg>
</div>
<div className="space-y-2">
<h1 className="text-xl font-semibold">Connecting to Netlify</h1>
<p className="text-muted-foreground">
Processing your Netlify authentication...
</p>
</div>
<div className="flex justify-center">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
+1 -23
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useParams, useSearchParams } from 'react-router-dom';
import { useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { type Project } from '@/lib/ProjectsManager';
import { useProjectsManager } from '@/hooks/useProjectsManager';
@@ -19,20 +19,16 @@ import { StarButton } from '@/components/StarButton';
import { useBuildProject } from '@/hooks/useBuildProject';
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
import { useConsoleError } from '@/hooks/useConsoleError';
import { webpm } from '@webpm/webpm';
import { useFS } from '@/hooks/useFS';
export function ProjectView() {
const { projectId } = useParams<{ projectId: string }>();
const { t } = useTranslation();
const { fs } = useFS();
const [project, setProject] = useState<Project | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [activeTab, setActiveTab] = useState<'preview' | 'code'>('preview');
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
const [isAILoading, setIsAILoading] = useState(false);
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
const [searchParams] = useSearchParams();
// Use console error state from provider
const { consoleError, dismissConsoleError, clearErrors } = useConsoleError();
@@ -116,24 +112,6 @@ export function ProjectView() {
navigate('/');
};
useEffect(() => {
(async () => {
if (project && searchParams.get('build')) {
const packageJson = await fs.readFile(`/projects/${project.id}/package.json`, 'utf8');
await webpm.installWithUntarHandler(JSON.parse(packageJson), {
onProgress: (e) => {
console.log(`Build progress:`, e.currentProgress);
},
onComplete: () => {
console.log('Build complete');
},
}, {
includeDevDependencies: false,
});
}
})();
}, [fs, project, searchParams]);
if (!project && !isLoading) {
return (
<div className="min-h-screen bg-background flex items-center justify-center">
+31 -31
View File
@@ -18,8 +18,8 @@ export function SystemSettings() {
const [projectTemplateInput, setProjectTemplateInput] = useState(config.projectTemplate);
const [esmUrlInput, setEsmUrlInput] = useState(config.esmUrl);
const [corsProxyInput, setCorsProxyInput] = useState(config.corsProxy);
const [faviconUrlInput, setFaviconUrlInput] = useState(config.faviconUrl);
const [previewDomainInput, setPreviewDomainInput] = useState(config.previewDomain);
const [deployServerInput, setDeployServerInput] = useState(config.deployServer);
const [showcaseModeratorInput, setShowcaseModeratorInput] = useState(config.showcaseModerator);
return (
@@ -120,36 +120,6 @@ export function SystemSettings() {
</AccordionItem>
</Accordion>
{/* Favicon URL Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="favicon-url" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">Favicon URL</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="favicon-url"
type="url"
placeholder="https://external-content.duckduckgo.com/ip3/{hostname}.ico"
value={faviconUrlInput}
onChange={(e) => {
const value = e.target.value;
setFaviconUrlInput(value);
updateConfig((current) => ({
...current,
faviconUrl: value,
}));
}}
/>
<p className="text-xs text-muted-foreground">
URL template for fetching favicons. Available variables: {'{hostname}'}, {'{origin}'}, {'{href}'}, {'{protocol}'}, {'{pathname}'}
</p>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
{/* JavaScript CDN Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="esm-url" className="border rounded-lg">
@@ -211,6 +181,36 @@ export function SystemSettings() {
</AccordionItem>
</Accordion>
{/* Deploy Server Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="deploy-server" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('deployServer')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="deploy-server"
type="text"
placeholder="shakespeare.wtf"
value={deployServerInput}
onChange={(e) => {
const value = e.target.value;
setDeployServerInput(value);
updateConfig((current) => ({
...current,
deployServer: value,
}));
}}
/>
<p className="text-xs text-muted-foreground">
{t('deployServerDescription')}
</p>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
{/* Showcase Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="showcase" className="border rounded-lg">
-86
View File
@@ -1,86 +0,0 @@
import { useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useVercelOAuth } from '@/hooks/useVercelOAuth';
import { useDeploySettings } from '@/hooks/useDeploySettings';
import { useToast } from '@/hooks/useToast';
import { Card, CardContent } from '@/components/ui/card';
export default function VercelOAuth() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { handleCallback } = useVercelOAuth();
const { isInitialized } = useDeploySettings();
const { toast } = useToast();
useEffect(() => {
// Wait for deploy settings to be initialized
if (!isInitialized) {
return;
}
const code = searchParams.get('code');
const state = searchParams.get('state');
const error = searchParams.get('error');
const errorDescription = searchParams.get('error_description');
const storedState = localStorage.getItem('vercel_oauth_state');
// Handle OAuth errors
if (error) {
toast({
title: "Vercel OAuth Error",
description: errorDescription || error,
variant: "destructive",
});
navigate('/settings/deploy');
return;
}
// Handle successful OAuth callback
if (code && state && storedState) {
handleCallback(code, state).then((success) => {
if (success) {
toast({
title: "Vercel Connected",
description: "Successfully connected to Vercel. You can now deploy your projects.",
});
} else {
toast({
title: "Connection Failed",
description: "Failed to connect to Vercel. Please try again.",
variant: "destructive",
});
}
// Always redirect to Deploy settings after handling the callback
navigate('/settings/deploy');
});
} else {
// No code or state parameters - redirect to Deploy settings
navigate('/settings/deploy');
}
}, [searchParams, handleCallback, toast, navigate, isInitialized]);
return (
<div className="min-h-screen flex items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardContent className="py-12 px-8 text-center">
<div className="space-y-6">
<div className="flex justify-center">
<svg className="h-12 w-12 text-primary" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 1.5L24 22.5H0L12 1.5z" />
</svg>
</div>
<div className="space-y-2">
<h1 className="text-xl font-semibold">Connecting to Vercel</h1>
<p className="text-muted-foreground">
Processing your Vercel authentication...
</p>
</div>
<div className="flex justify-center">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
+1 -1
View File
@@ -31,9 +31,9 @@ export function TestApp({ children }: TestAppProps) {
theme: 'light',
relayUrl: 'wss://relay.nostr.band',
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
deployServer: 'shakespeare.wtf',
esmUrl: 'https://esm.shakespeare.diy',
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
previewDomain: 'local-shakespeare.dev',
language: 'en',
showcaseEnabled: true,
-14
View File
@@ -2,7 +2,6 @@ import path from "node:path";
import react from "@vitejs/plugin-react-swc";
import { defineConfig } from "vitest/config";
import { nodePolyfills } from "vite-plugin-node-polyfills";
// https://vitejs.dev/config/
export default defineConfig(() => ({
@@ -11,16 +10,6 @@ export default defineConfig(() => ({
port: 8080,
},
plugins: [
nodePolyfills({
include: ["buffer", "process", "stream", "module"],
exclude: ["http", "https", "net", "tls", "child_process"],
globals: {
Buffer: true,
global: true,
process: true,
},
protocolImports: true,
}),
react(),
],
build: {
@@ -63,7 +52,4 @@ export default defineConfig(() => ({
"@": path.resolve(__dirname, "./src"),
},
},
optimizeDeps: {
include: ["tar-stream", "fflate"],
},
}));