mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
429dafce92 | ||
|
|
49889be240 | ||
|
|
c285dbcd05 | ||
|
|
b80205a942 | ||
|
|
50f85f232d | ||
|
|
c5605c9be8 | ||
|
|
33564842d0 | ||
|
|
0511976688 | ||
|
|
819813a000 | ||
|
|
2736f71687 | ||
|
|
0a2cbf4bca | ||
|
|
c359eda1d6 | ||
|
|
269047d742 | ||
|
|
d2673effd8 | ||
|
|
c49564e70d | ||
|
|
63671ea85b |
No files matched your search
@@ -1,5 +1,29 @@
|
||||
# Changelog
|
||||
|
||||
## [9.11.3] - 2026-04-12
|
||||
|
||||
### Fixed
|
||||
- App publish dialog now appears on mobile devices
|
||||
- Changelog available offline via ServiceWorker precache
|
||||
|
||||
## [9.11.2] - 2026-04-06
|
||||
|
||||
### Fixed
|
||||
- Derive private preview subdomains with HMAC to prevent cross-project origin collisions on iframe.diy
|
||||
|
||||
## [9.11.1] - 2026-04-05
|
||||
|
||||
### Changed
|
||||
- Switch preview pane to iframe.diy for improved reliability and compatibility
|
||||
- New users start with OpenCode Zen pre-configured for a zero-setup first experience
|
||||
- Default nsite gateway changed to shakespeare.to with vanity subdomain support
|
||||
- Update default Blossom servers and relay lists across deployments and uploads
|
||||
|
||||
### Fixed
|
||||
- Default settings no longer override existing users' recently used models
|
||||
- Showcase card clone URLs now use proper Nostr URI encoding
|
||||
- Service worker no longer blocks SvelteKit nsite routes
|
||||
|
||||
## [9.11.0] - 2026-04-03
|
||||
|
||||
### Added
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "shakespeare.diy",
|
||||
"version": "9.10.4",
|
||||
"version": "9.11.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "shakespeare.diy",
|
||||
"version": "9.10.4",
|
||||
"version": "9.11.2",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@capacitor/app": "^8.1.0",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
|
||||
"homepage": "https://shakespeare.diy",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"version": "9.11.0",
|
||||
"version": "9.11.3",
|
||||
"type": "module",
|
||||
"author": {
|
||||
"name": "shakespeare.diy",
|
||||
|
||||
@@ -1,5 +1,29 @@
|
||||
# Changelog
|
||||
|
||||
## [9.11.3] - 2026-04-12
|
||||
|
||||
### Fixed
|
||||
- App publish dialog now appears on mobile devices
|
||||
- Changelog available offline via ServiceWorker precache
|
||||
|
||||
## [9.11.2] - 2026-04-06
|
||||
|
||||
### Fixed
|
||||
- Derive private preview subdomains with HMAC to prevent cross-project origin collisions on iframe.diy
|
||||
|
||||
## [9.11.1] - 2026-04-05
|
||||
|
||||
### Changed
|
||||
- Switch preview pane to iframe.diy for improved reliability and compatibility
|
||||
- New users start with OpenCode Zen pre-configured for a zero-setup first experience
|
||||
- Default nsite gateway changed to shakespeare.to with vanity subdomain support
|
||||
- Update default Blossom servers and relay lists across deployments and uploads
|
||||
|
||||
### Fixed
|
||||
- Default settings no longer override existing users' recently used models
|
||||
- Showcase card clone URLs now use proper Nostr URI encoding
|
||||
- Service worker no longer blocks SvelteKit nsite routes
|
||||
|
||||
## [9.11.0] - 2026-04-03
|
||||
|
||||
### Added
|
||||
|
||||
@@ -138,18 +138,10 @@ self.addEventListener("fetch", (event) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// Let iframe client system files be handled normally
|
||||
if (url.pathname.startsWith("/_") || url.pathname === "/sw.js") {
|
||||
return;
|
||||
}
|
||||
|
||||
// Let root path be handled normally (loads the iframe client page)
|
||||
if (url.pathname === "/") {
|
||||
return;
|
||||
}
|
||||
|
||||
// Let iframe client assets be handled normally (anything in _iframe-client directory and common assets)
|
||||
// Let iframe client system files and common assets be handled normally
|
||||
if (url.pathname.startsWith("/_iframe-client/") ||
|
||||
url.pathname === "/sw.js" ||
|
||||
url.pathname === "/" ||
|
||||
url.pathname === "/favicon.ico" ||
|
||||
url.pathname === "/manifest.webmanifest") {
|
||||
return;
|
||||
|
||||
@@ -36,17 +36,27 @@ describe('AISettingsProvider', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should initialize with empty recentlyUsedModels array', async () => {
|
||||
it('should initialize with OpenCode defaults for new users (no providers)', async () => {
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual([]);
|
||||
// New users with no providers get OPENCODE_DEFAULT_SETTINGS with big-pickle
|
||||
expect(result.current.settings.providers).toHaveLength(1);
|
||||
expect(result.current.settings.providers[0].id).toBe('opencode');
|
||||
expect(result.current.settings.recentlyUsedModels).toEqual(['opencode/big-pickle']);
|
||||
});
|
||||
});
|
||||
|
||||
it('should add recently used models correctly', async () => {
|
||||
// Simulate existing user with a provider configured
|
||||
const { readAISettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readAISettings).mockResolvedValue({
|
||||
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
@@ -65,6 +75,13 @@ describe('AISettingsProvider', () => {
|
||||
});
|
||||
|
||||
it('should move existing model to front when used again', async () => {
|
||||
// Simulate existing user with a provider configured
|
||||
const { readAISettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readAISettings).mockResolvedValue({
|
||||
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
@@ -99,6 +116,13 @@ describe('AISettingsProvider', () => {
|
||||
});
|
||||
|
||||
it('should limit recently used models to 10 items', async () => {
|
||||
// Simulate existing user with a provider configured
|
||||
const { readAISettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readAISettings).mockResolvedValue({
|
||||
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAISettings(), {
|
||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||
});
|
||||
@@ -147,6 +171,13 @@ describe('AISettingsProvider', () => {
|
||||
});
|
||||
|
||||
it('should invalidate provider-models query when updateSettings is called with providers', async () => {
|
||||
// Simulate existing user with a provider configured
|
||||
const { readAISettings } = await import('@/lib/configUtils');
|
||||
vi.mocked(readAISettings).mockResolvedValue({
|
||||
providers: [{ id: 'openrouter', name: 'OpenRouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' }],
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
|
||||
// Mock the QueryClient.invalidateQueries method
|
||||
const mockInvalidateQueries = vi.fn();
|
||||
|
||||
|
||||
@@ -4,33 +4,33 @@ import { AISettingsContext, type AISettings, type AIProvider, type MCPServer, ty
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
||||
import { EMPTY_AI_SETTINGS, OPENCODE_DEFAULT_SETTINGS } from '@/lib/opencode-defaults';
|
||||
|
||||
interface AISettingsProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: AISettings = {
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {},
|
||||
};
|
||||
|
||||
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { fs } = useFS();
|
||||
const { configPath } = useFSPaths();
|
||||
const [settings, setSettings] = useState<AISettings>(DEFAULT_SETTINGS);
|
||||
const [settings, setSettings] = useState<AISettings>(EMPTY_AI_SETTINGS);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
// Initialize settings from VFS on mount
|
||||
useEffect(() => {
|
||||
const initializeSettings = async () => {
|
||||
try {
|
||||
const settings = await readAISettings(fs, configPath);
|
||||
setSettings(settings);
|
||||
const loaded = await readAISettings(fs, configPath);
|
||||
// Only apply OpenCode defaults for genuinely new users (no providers configured)
|
||||
if (loaded.providers.length === 0) {
|
||||
setSettings(OPENCODE_DEFAULT_SETTINGS);
|
||||
} else {
|
||||
setSettings(loaded);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize AI settings:', error);
|
||||
setSettings(DEFAULT_SETTINGS);
|
||||
setSettings(EMPTY_AI_SETTINGS);
|
||||
} finally {
|
||||
setIsInitialized(true);
|
||||
}
|
||||
|
||||
@@ -84,9 +84,9 @@ export function AddCustomProviderDialog({
|
||||
provider = {
|
||||
type: 'nsite',
|
||||
name: customName.trim(),
|
||||
gateway: customGateway.trim() || 'nsite.lol',
|
||||
gateway: customGateway.trim() || 'shakespeare.to',
|
||||
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
|
||||
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.primal.net/'],
|
||||
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.ditto.pub/', 'https://blossom.dreamith.to/'],
|
||||
};
|
||||
} else if (customProviderType === 'netlify') {
|
||||
if (!customApiKey.trim()) return;
|
||||
@@ -252,7 +252,7 @@ export function AddCustomProviderDialog({
|
||||
<Label htmlFor="custom-gateway">Gateway</Label>
|
||||
<Input
|
||||
id="custom-gateway"
|
||||
placeholder="nsite.lol"
|
||||
placeholder="shakespeare.to"
|
||||
value={customGateway}
|
||||
onChange={(e) => setCustomGateway(e.target.value)}
|
||||
/>
|
||||
@@ -269,7 +269,7 @@ export function AddCustomProviderDialog({
|
||||
items={customBlossomServers}
|
||||
onChange={setCustomBlossomServers}
|
||||
protocol="https"
|
||||
placeholder="blossom.primal.net"
|
||||
placeholder="blossom.ditto.pub"
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
|
||||
@@ -3,9 +3,10 @@ import { DeploySettingsContext, type DeploySettings, type DeployProvider } from
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
|
||||
import { DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
|
||||
|
||||
const DEFAULT_SETTINGS: DeploySettings = {
|
||||
providers: [],
|
||||
providers: [DEFAULT_NSITE_PROVIDER],
|
||||
};
|
||||
|
||||
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
@@ -134,7 +134,7 @@ export function ProviderConfigDialog({
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-gateway"
|
||||
placeholder="nsite.lol"
|
||||
placeholder="shakespeare.to"
|
||||
value={localProvider.gateway || ''}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
|
||||
/>
|
||||
@@ -152,7 +152,7 @@ export function ProviderConfigDialog({
|
||||
items={localProvider.blossomServers ?? []}
|
||||
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
|
||||
protocol="https"
|
||||
placeholder="blossom.primal.net"
|
||||
placeholder="blossom.ditto.pub"
|
||||
required
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { encodeBase64 } from '@std/encoding/base64';
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
@@ -25,6 +25,8 @@ import { Terminal as TerminalComponent } from '@/components/Terminal';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { isMediaFile } from '@/lib/fileUtils';
|
||||
import { deriveIframeSubdomain } from '@/lib/iframeSubdomain';
|
||||
import { getPreviewInjectedScript } from '@/lib/previewInjectedScript';
|
||||
|
||||
interface PreviewPaneProps {
|
||||
projectId: string;
|
||||
@@ -67,6 +69,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
const { t } = useTranslation();
|
||||
const { config } = useAppContext();
|
||||
const { previewDomain } = config;
|
||||
|
||||
// Derive a private, stable subdomain from a device-local seed + the project ID.
|
||||
// This prevents malicious project names from colliding with another project's
|
||||
// origin on iframe.diy, protecting localStorage/IndexedDB isolation.
|
||||
const previewSubdomain = useMemo(() => deriveIframeSubdomain('preview', projectId), [projectId]);
|
||||
const previewOrigin = useMemo(() => `https://${previewSubdomain}.${previewDomain}`, [previewSubdomain, previewDomain]);
|
||||
|
||||
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||
const [fileContent, setFileContent] = useState<string>('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
@@ -182,18 +191,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
|
||||
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
|
||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [previewOrigin]);
|
||||
|
||||
const sendError = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [previewOrigin]);
|
||||
|
||||
const handleConsoleMessage = useCallback((message: {
|
||||
jsonrpc: '2.0';
|
||||
@@ -248,6 +254,17 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
}
|
||||
}, [historyIndex, navigationHistory]);
|
||||
|
||||
const sendNotification = useCallback((method: string, params?: Record<string, unknown>) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
const message = {
|
||||
jsonrpc: '2.0' as const,
|
||||
method,
|
||||
params: params || {},
|
||||
};
|
||||
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||
}
|
||||
}, [previewOrigin]);
|
||||
|
||||
const sendNavigationCommand = useCallback((method: string, params?: Record<string, unknown>) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
const message = {
|
||||
@@ -256,10 +273,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
params: params || {},
|
||||
id: Date.now()
|
||||
};
|
||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [previewOrigin]);
|
||||
|
||||
const navigateIframe = useCallback((url: string) => {
|
||||
// Send semantic path directly (e.g., "/about", "/contact")
|
||||
@@ -275,6 +291,18 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
setIsFullscreen(prev => !prev);
|
||||
}, []);
|
||||
|
||||
/** Virtual path where the injected preview script is served. */
|
||||
const INJECTED_SCRIPT_PATH = '/__injected__/preview.js';
|
||||
|
||||
/** Inject a script tag into an HTML string using DOMParser. */
|
||||
const injectScript = useCallback((html: string): string => {
|
||||
const doc = new DOMParser().parseFromString(html, 'text/html');
|
||||
const tag = doc.createElement('script');
|
||||
tag.src = INJECTED_SCRIPT_PATH;
|
||||
doc.head.insertBefore(tag, doc.head.firstChild);
|
||||
return '<!DOCTYPE html>\n' + doc.documentElement.outerHTML;
|
||||
}, []);
|
||||
|
||||
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
|
||||
const { params, id } = request;
|
||||
const { request: fetchRequest } = params;
|
||||
@@ -282,16 +310,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
try {
|
||||
// Parse the URL and validate origin
|
||||
const url = new URL(fetchRequest.url);
|
||||
const expectedOrigin = `https://${projectId}.${previewDomain}`;
|
||||
|
||||
if (url.origin !== expectedOrigin) {
|
||||
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
|
||||
if (url.origin !== previewOrigin) {
|
||||
console.log(`Invalid origin: ${url.origin}, expected: ${previewOrigin}`);
|
||||
sendError({
|
||||
jsonrpc: '2.0',
|
||||
error: {
|
||||
code: -32003,
|
||||
message: 'Invalid URL - origin mismatch',
|
||||
data: { url: fetchRequest.url, expectedOrigin }
|
||||
data: { url: fetchRequest.url, expectedOrigin: previewOrigin }
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -301,24 +328,52 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
const path = url.pathname;
|
||||
const filePath = path;
|
||||
|
||||
// Serve the injected preview script at its virtual path
|
||||
if (path === INJECTED_SCRIPT_PATH) {
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: {
|
||||
'Content-Type': 'application/javascript',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: encodeBase64(new TextEncoder().encode(getPreviewInjectedScript())),
|
||||
},
|
||||
id
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip SPA fallback for static assets (files with extensions)
|
||||
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
|
||||
|
||||
// SPA routing: try to serve the exact file first
|
||||
try {
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
|
||||
const contentType = getContentType(filePath);
|
||||
console.log(`Serving file: ${filePath}`);
|
||||
|
||||
// Inject preview script into HTML responses
|
||||
let body: string;
|
||||
if (contentType === 'text/html') {
|
||||
const html = new TextDecoder().decode(bytes);
|
||||
body = encodeBase64(new TextEncoder().encode(injectScript(html)));
|
||||
} else {
|
||||
body = encodeBase64(bytes);
|
||||
}
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: {
|
||||
'Content-Type': getContentType(filePath),
|
||||
'Content-Type': contentType,
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: encodeBase64(bytes),
|
||||
body,
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -349,6 +404,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
|
||||
console.log(`Serving index.html fallback for: ${path}`);
|
||||
|
||||
// Inject preview script into SPA fallback HTML
|
||||
const html = new TextDecoder().decode(bytes);
|
||||
const body = encodeBase64(new TextEncoder().encode(injectScript(html)));
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -358,7 +417,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
'Content-Type': 'text/html',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
body: encodeBase64(bytes),
|
||||
body,
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -389,32 +448,37 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
id
|
||||
});
|
||||
}
|
||||
}, [projectId, projectsManager, sendResponse, sendError, previewDomain]);
|
||||
}, [projectId, projectsManager, sendResponse, sendError, previewOrigin, injectScript]);
|
||||
|
||||
// Setup messaging protocol for iframe communication
|
||||
useEffect(() => {
|
||||
const handleMessage = (event: MessageEvent) => {
|
||||
// Verify origin for security
|
||||
const expectedOrigin = `https://${projectId}.${previewDomain}`;
|
||||
if (event.origin !== expectedOrigin) {
|
||||
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
|
||||
if (event.origin !== previewOrigin) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = event.data;
|
||||
console.log('Received message from iframe:', message);
|
||||
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
|
||||
if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0') return;
|
||||
|
||||
// Handle iframe.diy handshake: respond to "ready" with "init"
|
||||
if (message.method === 'ready') {
|
||||
sendNotification('init', { version: 1 });
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.method === 'fetch') {
|
||||
handleFetch(message);
|
||||
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
|
||||
} else if (message.method === 'console') {
|
||||
handleConsoleMessage(message);
|
||||
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
|
||||
} else if (message.method === 'updateNavigationState') {
|
||||
handleUpdateNavigationState(message);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleMessage);
|
||||
return () => window.removeEventListener('message', handleMessage);
|
||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
|
||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, sendNotification, previewOrigin]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedFile) {
|
||||
@@ -647,10 +711,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
<iframe
|
||||
key={projectId}
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${previewDomain}/`}
|
||||
src={`${previewOrigin}/`}
|
||||
className="w-full h-full border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin allow-forms"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
|
||||
@@ -612,6 +612,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
<span className="font-medium">{nsiteVfsConfig.title}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Relays</span>
|
||||
<span className="font-medium">{relayCount} configured</span>
|
||||
@@ -798,6 +799,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
|
||||
@@ -44,7 +44,7 @@ export interface AppConfig {
|
||||
faviconUrl: string;
|
||||
/** Nostr Git web URL template (e.g., "https://nostrhub.io/{naddr}") */
|
||||
ngitWebUrl: string;
|
||||
/** Preview domain for iframe sandboxing (e.g., "local-shakespeare.dev") */
|
||||
/** Preview domain for iframe sandboxing (e.g., "iframe.diy") */
|
||||
previewDomain: string;
|
||||
/** Selected language */
|
||||
language?: string;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { NostrEvent, NostrFilter, NRelay, NPool } from '@nostrify/nostrify';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
|
||||
export interface AppSubmission extends NostrEvent {
|
||||
appName: string;
|
||||
@@ -79,7 +80,7 @@ function repositoryUrlFromATag(aTagValue: string): string {
|
||||
const parts = aTagValue.split(':');
|
||||
if (parts.length < 3) return '';
|
||||
const [, pubkey, identifier] = parts;
|
||||
return `nostr://${pubkey}/${identifier}`;
|
||||
return new NostrURI({ pubkey, identifier }).toString();
|
||||
}
|
||||
|
||||
export function useAppSubmissions() {
|
||||
|
||||
@@ -66,7 +66,7 @@ describe('useGenerateProjectInfo', () => {
|
||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
previewDomain: 'iframe.diy',
|
||||
showcaseEnabled: true,
|
||||
showcaseCurator: '',
|
||||
graspMetadata: {
|
||||
@@ -230,7 +230,7 @@ describe('useGenerateProjectInfo', () => {
|
||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
previewDomain: 'iframe.diy',
|
||||
showcaseEnabled: true,
|
||||
showcaseCurator: '',
|
||||
graspMetadata: {
|
||||
|
||||
@@ -14,8 +14,9 @@ export function useUploadFile() {
|
||||
|
||||
const uploader = new BlossomUploader({
|
||||
servers: [
|
||||
'https://blossom.primal.net/',
|
||||
'https://blossom.ditto.pub/',
|
||||
'https://blossom.dreamith.to/',
|
||||
'https://blossom.primal.net/',
|
||||
],
|
||||
signer: user.signer,
|
||||
});
|
||||
|
||||
@@ -46,7 +46,7 @@ const testConfig: AppConfig = {
|
||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
previewDomain: 'iframe.diy',
|
||||
language: 'en',
|
||||
showcaseEnabled: true,
|
||||
showcaseCurator: '',
|
||||
|
||||
@@ -36,6 +36,16 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
||||
request = new Request(request, { headers });
|
||||
}
|
||||
|
||||
// Add OpenCode headers for higher rate limit
|
||||
if (provider.id === 'opencode' || provider.baseURL === 'https://opencode.ai/zen/v1') {
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('x-opencode-project', 'shakespeare');
|
||||
headers.set('x-opencode-session', 'shakespeare');
|
||||
headers.set('x-opencode-request', crypto.randomUUID());
|
||||
headers.set('x-opencode-client', 'shakespeare');
|
||||
request = new Request(request, { headers });
|
||||
}
|
||||
|
||||
// If Nostr authentication is required and we have a user, use NIP-98
|
||||
if (provider.nostr && user?.signer) {
|
||||
// Create the NIP98 token
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
readDeploySettings,
|
||||
writeDeploySettings
|
||||
} from './configUtils';
|
||||
import { EMPTY_AI_SETTINGS } from './opencode-defaults';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
import type { AISettings } from '@/contexts/AISettingsContext';
|
||||
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
||||
@@ -89,30 +90,22 @@ describe('configUtils', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should return default settings if file does not exist and no localStorage data', async () => {
|
||||
it('should return empty settings if file does not exist and no localStorage data', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
mockLocalStorage.getItem.mockReturnValue(null);
|
||||
|
||||
const result = await readAISettings(mockFS);
|
||||
|
||||
expect(result).toEqual({
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {},
|
||||
});
|
||||
expect(result).toEqual(EMPTY_AI_SETTINGS);
|
||||
});
|
||||
|
||||
it('should return default settings if JSON is invalid and no localStorage data', async () => {
|
||||
it('should return empty settings if JSON is invalid and no localStorage data', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue('invalid json');
|
||||
mockLocalStorage.getItem.mockReturnValue(null);
|
||||
|
||||
const result = await readAISettings(mockFS);
|
||||
|
||||
expect(result).toEqual({
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {},
|
||||
});
|
||||
expect(result).toEqual(EMPTY_AI_SETTINGS);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import z from 'zod';
|
||||
import { filteredArray } from '@/lib/schema';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
import { EMPTY_AI_SETTINGS } from '@/lib/opencode-defaults';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import type { AISettings, MCPServer } from '@/contexts/AISettingsContext';
|
||||
import type { GitSettings, GitCredential } from '@/contexts/GitSettingsContext';
|
||||
@@ -169,12 +170,6 @@ async function ensureConfigDir(fs: JSRuntimeFS, configPath = '/config'): Promise
|
||||
* @param configPath - Custom config path (default: /config)
|
||||
*/
|
||||
export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): Promise<AISettings> {
|
||||
const defaultSettings: AISettings = {
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {},
|
||||
};
|
||||
|
||||
try {
|
||||
const aiConfigPath = getAIConfigPath(configPath);
|
||||
const content = await fs.readFile(aiConfigPath, 'utf8');
|
||||
@@ -210,7 +205,7 @@ export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): P
|
||||
if (error instanceof z.ZodError) {
|
||||
console.error('AI settings parsing error:', error.issues);
|
||||
}
|
||||
return defaultSettings;
|
||||
return EMPTY_AI_SETTINGS;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,84 @@ async function createBatchUploadAuth(
|
||||
return `Nostr ${btoa(JSON.stringify(signed))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vanity subdomain name rules from VANITY.md:
|
||||
* - 1–49 characters long
|
||||
* - lowercase letters, digits, and hyphens only
|
||||
* - cannot start or end with a hyphen
|
||||
*/
|
||||
const VANITY_NAME_REGEX = /^[a-z0-9]([a-z0-9-]{0,47}[a-z0-9])?$/;
|
||||
|
||||
const VANITY_RESERVED_NAMES = new Set([
|
||||
'www', 'api', 'status', 'admin', 'mail', 'smtp', 'imap', 'pop', 'ftp',
|
||||
'ns1', 'ns2', 'ns3', 'ns4', 'localhost', 'autoconfig', 'autodiscover', '_dmarc',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Check whether a site identifier qualifies as a valid vanity name candidate.
|
||||
* This is a client-side pre-check — the gateway is the source of truth.
|
||||
*/
|
||||
function isVanityCandidate(name: string): boolean {
|
||||
return (
|
||||
name.length >= 1 &&
|
||||
name.length <= 49 &&
|
||||
VANITY_NAME_REGEX.test(name) &&
|
||||
!VANITY_RESERVED_NAMES.has(name)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* After a named-site deploy, probe the gateway to see if a vanity subdomain was
|
||||
* assigned. Not all gateways support vanity subdomains, so this is best-effort.
|
||||
*
|
||||
* Returns the vanity URL (e.g. "https://ditto.shakespeare.wtf") if the gateway
|
||||
* confirms the vanity name belongs to this pubkey, or `undefined` otherwise.
|
||||
*/
|
||||
async function probeVanityUrl(
|
||||
gateway: string,
|
||||
siteIdentifier: string,
|
||||
pubkey: string,
|
||||
): Promise<string | undefined> {
|
||||
// Quick client-side guard — skip the network request if the name is obviously invalid
|
||||
if (!isVanityCandidate(siteIdentifier)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const vanityOrigin = `https://${siteIdentifier}.${gateway}`;
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
const resp = await fetch(`${vanityOrigin}/`, {
|
||||
method: 'HEAD',
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
// Check for the X-Nsite-* headers that indicate vanity support
|
||||
const nsitePubkey = resp.headers.get('x-nsite-pubkey');
|
||||
const nsiteName = resp.headers.get('x-nsite-name');
|
||||
|
||||
// Vanity name is confirmed when the gateway returns the name header
|
||||
// AND the pubkey matches ours (i.e. we own this vanity name).
|
||||
if (nsiteName && nsitePubkey === pubkey) {
|
||||
return vanityOrigin;
|
||||
}
|
||||
|
||||
// If the response is a 404 with X-Nsite-Available: true, the name hasn't
|
||||
// been reserved yet. It will likely be claimed once the gateway processes
|
||||
// our manifest, but we can't confirm it right now — return undefined and
|
||||
// let the next deploy pick it up.
|
||||
return undefined;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
} catch {
|
||||
// Network error, gateway doesn't support vanity, CORS blocked, etc.
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a blob already exists on a Blossom server.
|
||||
* Returns true if the server responds 2xx to a HEAD request.
|
||||
@@ -327,7 +405,7 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
// no separate kind 10002 or kind 10063 events are published.
|
||||
await relayClient.event(manifestEvent, { signal: AbortSignal.timeout(10_000) });
|
||||
|
||||
// Build the deployed URL
|
||||
// Build the canonical deployed URL (always the long-form base36 or npub URL)
|
||||
const siteUrl = buildNsiteUrl({
|
||||
pubkeyHex: pubkey,
|
||||
npub,
|
||||
@@ -335,8 +413,17 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
siteIdentifier: this.siteIdentifier,
|
||||
});
|
||||
|
||||
// For named sites, probe whether the gateway assigned a vanity subdomain.
|
||||
// This is best-effort — if the gateway doesn't support vanity, we just
|
||||
// return the canonical URL and move on.
|
||||
let vanityUrl: string | undefined;
|
||||
if (isNamedSite && this.siteIdentifier) {
|
||||
vanityUrl = await probeVanityUrl(this.gateway, this.siteIdentifier, pubkey);
|
||||
}
|
||||
|
||||
return {
|
||||
url: siteUrl,
|
||||
// Prefer the short vanity URL when confirmed by the gateway
|
||||
url: vanityUrl ?? siteUrl,
|
||||
metadata: {
|
||||
pubkey,
|
||||
npub,
|
||||
@@ -344,6 +431,8 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
provider: 'nsite',
|
||||
siteIdentifier: this.siteIdentifier,
|
||||
manifestKind,
|
||||
vanityUrl,
|
||||
canonicalUrl: siteUrl,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,27 @@
|
||||
import type { NsiteProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from './deploy/types';
|
||||
|
||||
/** Default nsite provider configuration, pre-configured for new users. */
|
||||
export const DEFAULT_NSITE_PROVIDER: NsiteProvider = {
|
||||
id: 'nsite',
|
||||
name: 'nsite',
|
||||
type: 'nsite',
|
||||
gateway: 'shakespeare.to',
|
||||
relayUrls: [
|
||||
'wss://relay.ditto.pub',
|
||||
'wss://relay.dreamith.to',
|
||||
'wss://relay.nsite.lol',
|
||||
'wss://relay.nosto.re',
|
||||
'wss://relay.primal.net',
|
||||
],
|
||||
blossomServers: [
|
||||
'https://blossom.ditto.pub',
|
||||
'https://blossom.dreamith.to',
|
||||
'https://blossom.primal.net',
|
||||
'https://cdn.sovbit.host',
|
||||
],
|
||||
};
|
||||
|
||||
export const PRESET_DEPLOY_PROVIDERS: PresetDeployProvider[] = [
|
||||
{
|
||||
id: 'shakespeare',
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { hmac } from '@noble/hashes/hmac';
|
||||
import { sha256 } from '@noble/hashes/sha256';
|
||||
import { bytesToHex } from '@noble/hashes/utils';
|
||||
|
||||
const SEED_STORAGE_KEY = 'shakespeare:seed';
|
||||
|
||||
/**
|
||||
* Encode a hex string as a zero-padded 50-character base36 string.
|
||||
* Replicates the encoding used for nsite subdomains.
|
||||
*/
|
||||
function hexToBase36(hex: string): string {
|
||||
let n = 0n;
|
||||
for (let i = 0; i < hex.length; i++) {
|
||||
n = n * 16n + BigInt(parseInt(hex[i], 16));
|
||||
}
|
||||
return n.toString(36).padStart(50, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create a device-local random seed persisted in localStorage.
|
||||
* This is a general-purpose secret used to derive private identifiers
|
||||
* (e.g. iframe.diy subdomains) that must not be predictable by third parties.
|
||||
*/
|
||||
function getSeed(): string {
|
||||
const stored = localStorage.getItem(SEED_STORAGE_KEY);
|
||||
if (stored) return stored;
|
||||
|
||||
const seed = crypto.randomUUID();
|
||||
localStorage.setItem(SEED_STORAGE_KEY, seed);
|
||||
return seed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a stable, private subdomain label for an iframe.diy iframe.
|
||||
*
|
||||
* Uses HMAC-SHA256 with the device-local seed as the key and
|
||||
* `prefix|identifier` as the message. Because the seed is secret to
|
||||
* this device, a third party cannot predict or collide with another
|
||||
* app's subdomain, preventing cross-app localStorage/IndexedDB access
|
||||
* on iframe.diy.
|
||||
*
|
||||
* The `prefix` acts as a domain separator so that different use-cases
|
||||
* (e.g. "preview", "sandbox") produce distinct subdomains even for the
|
||||
* same identifier.
|
||||
*
|
||||
* The result is a 50-character base36 string (256 bits of entropy) that
|
||||
* fits within the 63-character subdomain label limit.
|
||||
*/
|
||||
export function deriveIframeSubdomain(prefix: string, identifier: string): string {
|
||||
const seed = getSeed();
|
||||
const enc = new TextEncoder();
|
||||
const mac = hmac(sha256, enc.encode(seed), enc.encode(`${prefix}|${identifier}`));
|
||||
return hexToBase36(bytesToHex(mac));
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { AISettings } from '@/contexts/AISettingsContext';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
|
||||
const opencodePreset = AI_PROVIDER_PRESETS.find((p) => p.id === 'opencode')!;
|
||||
|
||||
/** Empty AI settings used as initial state and error fallback. Won't overwrite user data. */
|
||||
export const EMPTY_AI_SETTINGS: AISettings = {
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {},
|
||||
};
|
||||
|
||||
/** Default AI settings with OpenCode Zen pre-configured and big-pickle selected. Only for genuinely new users. */
|
||||
export const OPENCODE_DEFAULT_SETTINGS: AISettings = {
|
||||
providers: [
|
||||
{
|
||||
id: opencodePreset.id,
|
||||
name: opencodePreset.name,
|
||||
baseURL: opencodePreset.baseURL,
|
||||
proxy: opencodePreset.proxy,
|
||||
},
|
||||
],
|
||||
recentlyUsedModels: ['opencode/big-pickle'],
|
||||
mcpServers: {},
|
||||
};
|
||||
@@ -0,0 +1,297 @@
|
||||
/**
|
||||
* Script injected into preview iframe HTML responses.
|
||||
*
|
||||
* When using iframe.diy as the preview domain, the outer frame handles
|
||||
* service worker registration and document loading. However, Shakespeare
|
||||
* needs additional capabilities inside the rendered app:
|
||||
*
|
||||
* 1. Console interception - forward console.log/warn/error/info/debug to parent
|
||||
* 2. Navigation handling - track SPA navigation and handle navigate/refresh commands
|
||||
* 3. Global error handlers - capture uncaught errors and unhandled rejections
|
||||
*
|
||||
* This script is injected into <head> of HTML responses served by the fetch handler.
|
||||
* It communicates with the parent via window.parent.postMessage using JSON-RPC 2.0.
|
||||
*
|
||||
* Note: In iframe.diy's architecture, the "parent" of the inner iframe is the
|
||||
* outer frame, which transparently relays non-runtime JSON-RPC messages to the
|
||||
* actual parent (Shakespeare). So posting to window.parent works correctly.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns the injectable script as a string.
|
||||
* This runs inside the inner iframe of iframe.diy.
|
||||
*/
|
||||
export function getPreviewInjectedScript(): string {
|
||||
return `(function() {
|
||||
'use strict';
|
||||
|
||||
// =========================================================================
|
||||
// Path normalization
|
||||
//
|
||||
// iframe.diy loads the inner iframe at /index.html. Normalize this to /
|
||||
// before any SPA router initializes, so React Router etc. see the correct
|
||||
// path.
|
||||
// =========================================================================
|
||||
|
||||
if (window.location.pathname === '/index.html') {
|
||||
history.replaceState(null, '', '/');
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// JSON-RPC ID generator
|
||||
//
|
||||
// iframe.diy's outer frame only relays JSON-RPC *requests* (messages with
|
||||
// an "id" field) between inner iframe and parent. Notifications (no "id")
|
||||
// are silently dropped. So all messages to the parent must include an id.
|
||||
// =========================================================================
|
||||
|
||||
function rpcId() {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Console Interceptor
|
||||
// =========================================================================
|
||||
|
||||
var originalConsole = {};
|
||||
var consoleMethods = ['log', 'warn', 'error', 'info', 'debug'];
|
||||
|
||||
consoleMethods.forEach(function(method) {
|
||||
if (typeof console[method] === 'function') {
|
||||
originalConsole[method] = console[method];
|
||||
|
||||
console[method] = function() {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
|
||||
// Call original method
|
||||
try {
|
||||
originalConsole[method].apply(console, args);
|
||||
} catch (e) {
|
||||
// Continue if original fails
|
||||
}
|
||||
|
||||
// Serialize arguments
|
||||
var message = args.map(function(arg) {
|
||||
if (arg === undefined) return 'undefined';
|
||||
if (arg === null) return 'null';
|
||||
if (typeof arg === 'object') {
|
||||
try {
|
||||
return JSON.stringify(arg, function(key, value) {
|
||||
if (value instanceof Error) {
|
||||
return {
|
||||
name: value.name,
|
||||
message: value.message,
|
||||
stack: value.stack
|
||||
};
|
||||
}
|
||||
return value;
|
||||
});
|
||||
} catch (e) {
|
||||
return String(arg);
|
||||
}
|
||||
}
|
||||
return String(arg);
|
||||
}).join(' ');
|
||||
|
||||
// Send to parent (must include id for iframe.diy relay)
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: '2.0',
|
||||
id: rpcId(),
|
||||
method: 'console',
|
||||
params: { level: method, message: message }
|
||||
}, '*');
|
||||
} catch (e) {
|
||||
// Ignore postMessage errors
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// =========================================================================
|
||||
// Navigation Handler
|
||||
// =========================================================================
|
||||
|
||||
var currentSemanticPath = '/';
|
||||
|
||||
// Try to restore initial path from sessionStorage (after refresh)
|
||||
try {
|
||||
var storedPath = sessionStorage.getItem('iframe_initial_path');
|
||||
if (storedPath) {
|
||||
currentSemanticPath = storedPath;
|
||||
sessionStorage.removeItem('iframe_initial_path');
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore sessionStorage errors
|
||||
}
|
||||
|
||||
function extractSemanticPath(urlOrString) {
|
||||
try {
|
||||
var url = typeof urlOrString === 'string'
|
||||
? new URL(urlOrString, window.location.origin)
|
||||
: urlOrString;
|
||||
return url.pathname + url.search + url.hash;
|
||||
} catch (e) {
|
||||
return window.location.pathname + window.location.search + window.location.hash;
|
||||
}
|
||||
}
|
||||
|
||||
function updateNavigationState() {
|
||||
var semanticPath = currentSemanticPath || extractSemanticPath(window.location);
|
||||
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: '2.0',
|
||||
id: ++rpcId,
|
||||
method: 'updateNavigationState',
|
||||
params: {
|
||||
currentUrl: semanticPath,
|
||||
canGoBack: false,
|
||||
canGoForward: false
|
||||
}
|
||||
}, '*');
|
||||
} catch (e) {
|
||||
// Ignore postMessage errors
|
||||
}
|
||||
}
|
||||
|
||||
function handleNavigate(url) {
|
||||
try {
|
||||
var targetUrl = new URL(url, window.location.origin);
|
||||
if (targetUrl.origin !== window.location.origin) {
|
||||
return;
|
||||
}
|
||||
|
||||
var semanticPath = extractSemanticPath(targetUrl);
|
||||
currentSemanticPath = semanticPath;
|
||||
updateNavigationState();
|
||||
|
||||
// Use the original pushState to trigger SPA navigation
|
||||
originalPushState.call(window.history, {}, '', semanticPath);
|
||||
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
|
||||
} catch (e) {
|
||||
// Ignore invalid URLs
|
||||
}
|
||||
}
|
||||
|
||||
function handleRefresh() {
|
||||
var path = currentSemanticPath || '/';
|
||||
try {
|
||||
sessionStorage.setItem('iframe_initial_path', path);
|
||||
} catch (e) {
|
||||
// Ignore sessionStorage errors
|
||||
}
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
// Listen for commands from parent (navigate, refresh)
|
||||
window.addEventListener('message', function(event) {
|
||||
// Only accept messages from parent window
|
||||
if (event.source !== window.parent) return;
|
||||
|
||||
var message = event.data;
|
||||
if (message && message.jsonrpc === '2.0') {
|
||||
switch (message.method) {
|
||||
case 'navigate':
|
||||
handleNavigate(message.params.url);
|
||||
break;
|
||||
case 'refresh':
|
||||
handleRefresh();
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for popstate events (back/forward navigation)
|
||||
window.addEventListener('popstate', function() {
|
||||
currentSemanticPath = extractSemanticPath(window.location);
|
||||
updateNavigationState();
|
||||
});
|
||||
|
||||
// Listen for hash changes
|
||||
window.addEventListener('hashchange', function() {
|
||||
currentSemanticPath = extractSemanticPath(window.location);
|
||||
updateNavigationState();
|
||||
});
|
||||
|
||||
// Override history.pushState and history.replaceState to detect SPA navigation
|
||||
var originalPushState = window.history.pushState;
|
||||
var originalReplaceState = window.history.replaceState;
|
||||
|
||||
window.history.pushState = function() {
|
||||
var result = originalPushState.apply(window.history, arguments);
|
||||
var semanticPath = arguments[2]
|
||||
? extractSemanticPath(arguments[2])
|
||||
: extractSemanticPath(window.location);
|
||||
currentSemanticPath = semanticPath;
|
||||
updateNavigationState();
|
||||
return result;
|
||||
};
|
||||
|
||||
window.history.replaceState = function() {
|
||||
var result = originalReplaceState.apply(window.history, arguments);
|
||||
var semanticPath = arguments[2]
|
||||
? extractSemanticPath(arguments[2])
|
||||
: extractSemanticPath(window.location);
|
||||
currentSemanticPath = semanticPath;
|
||||
updateNavigationState();
|
||||
return result;
|
||||
};
|
||||
|
||||
// Send initial navigation state
|
||||
updateNavigationState();
|
||||
|
||||
// After a short delay, navigate to initial path if needed (for refresh support)
|
||||
if (currentSemanticPath && currentSemanticPath !== '/') {
|
||||
setTimeout(function() {
|
||||
var current = window.location.pathname + window.location.search + window.location.hash;
|
||||
if (current !== currentSemanticPath) {
|
||||
handleNavigate(currentSemanticPath);
|
||||
}
|
||||
}, 150);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Global Error Handlers
|
||||
// =========================================================================
|
||||
|
||||
window.addEventListener('error', function(event) {
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: '2.0',
|
||||
id: ++rpcId,
|
||||
method: 'console',
|
||||
params: {
|
||||
level: 'error',
|
||||
message: 'Uncaught Error: ' + event.message,
|
||||
source: event.filename,
|
||||
lineno: event.lineno,
|
||||
colno: event.colno,
|
||||
stack: event.error ? event.error.stack : undefined
|
||||
}
|
||||
}, '*');
|
||||
} catch (e) {
|
||||
// Ignore postMessage errors
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener('unhandledrejection', function(event) {
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: '2.0',
|
||||
id: ++rpcId,
|
||||
method: 'console',
|
||||
params: {
|
||||
level: 'error',
|
||||
message: 'Unhandled Promise Rejection: ' + (event.reason ? (event.reason.message || String(event.reason)) : 'Unknown'),
|
||||
reason: event.reason,
|
||||
promise: event.promise ? 'Promise object' : 'No promise object'
|
||||
}
|
||||
}, '*');
|
||||
} catch (e) {
|
||||
// Ignore postMessage errors
|
||||
}
|
||||
});
|
||||
|
||||
})();`;
|
||||
}
|
||||
@@ -33,7 +33,7 @@ const testConfig: AppConfig = {
|
||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
previewDomain: 'iframe.diy',
|
||||
language: 'en',
|
||||
showcaseEnabled: true,
|
||||
showcaseCurator: '',
|
||||
|
||||
@@ -45,7 +45,7 @@ export class BlossomUploadTool implements Tool<BlossomUploadParams> {
|
||||
});
|
||||
|
||||
const uploader = new BlossomUploader({
|
||||
servers: ['https://blossom.primal.net/', 'https://blossom.ditto.pub/'],
|
||||
servers: ['https://blossom.ditto.pub/', 'https://blossom.dreamith.to/', 'https://blossom.primal.net/'],
|
||||
signer: this.signer,
|
||||
});
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { useVercelOAuth } from '@/hooks/useVercelOAuth';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||
import { PRESET_DEPLOY_PROVIDERS, DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
|
||||
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
|
||||
@@ -202,24 +202,7 @@ export function DeploySettings() {
|
||||
...(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.ditto.pub',
|
||||
'wss://relay.nsite.lol',
|
||||
'wss://relay.nosto.re',
|
||||
'wss://relay.primal.net',
|
||||
'wss://relay.damus.io',
|
||||
'wss://purplerelay.com',
|
||||
],
|
||||
blossomServers: [
|
||||
'https://blossom.primal.net',
|
||||
'https://cdn.sovbit.host',
|
||||
],
|
||||
};
|
||||
newProvider = { ...DEFAULT_NSITE_PROVIDER };
|
||||
} else if (preset.type === 'netlify') {
|
||||
newProvider = {
|
||||
id: preset.id, // Use preset ID for presets
|
||||
|
||||
@@ -389,6 +389,11 @@ export function ProjectView() {
|
||||
open={deleteDialogOpen}
|
||||
onOpenChange={setDeleteDialogOpen}
|
||||
/>
|
||||
<AppDialog
|
||||
projectId={project.id}
|
||||
open={appDialogOpen}
|
||||
onOpenChange={setAppDialogOpen}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ export default defineConfig(() => ({
|
||||
plugins: [
|
||||
react(),
|
||||
VitePWA({
|
||||
includeAssets: ['shakespeare.svg', 'shakespeare-192x192.png', 'shakespeare-512x512.png', 'sine.mp3'],
|
||||
includeAssets: ['shakespeare.svg', 'shakespeare-192x192.png', 'shakespeare-512x512.png', 'sine.mp3', 'CHANGELOG.md'],
|
||||
manifest: false, // Use existing manifest.webmanifest from public folder
|
||||
workbox: {
|
||||
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2,wasm,mp3}'],
|
||||
|
||||
Reference in new issue
Block a user