mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 00:27:24 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2c5b1d81e | ||
|
|
a7d026e51a | ||
|
|
dd078ed17d | ||
|
|
695a697e88 | ||
|
|
7eab377b7f | ||
|
|
6da4b63a85 | ||
|
|
565ae93aed | ||
|
|
429dafce92 | ||
|
|
49889be240 | ||
|
|
c285dbcd05 | ||
|
|
b80205a942 | ||
|
|
50f85f232d | ||
|
|
c5605c9be8 | ||
|
|
33564842d0 | ||
|
|
0511976688 | ||
|
|
819813a000 | ||
|
|
2736f71687 | ||
|
|
0a2cbf4bca | ||
|
|
c359eda1d6 | ||
|
|
269047d742 | ||
|
|
d2673effd8 | ||
|
|
c49564e70d | ||
|
|
63671ea85b |
No files matched your search
@@ -77,6 +77,41 @@ AI filesystem access through tools (including shell commands via ShellTool) has
|
|||||||
- **Write operations**: Restricted to current project directory and `/tmp/` directory (including subdirectories)
|
- **Write operations**: Restricted to current project directory and `/tmp/` directory (including subdirectories)
|
||||||
- **Copy operations**: Can copy from any absolute path to relative paths or `/tmp/`, but cannot copy from relative to absolute paths outside allowed areas
|
- **Copy operations**: Can copy from any absolute path to relative paths or `/tmp/`, but cannot copy from relative to absolute paths outside allowed areas
|
||||||
|
|
||||||
|
#### Web Workers and Asset URLs
|
||||||
|
|
||||||
|
Shakespeare's esbuild-wasm build pipeline supports the Vite/webpack-compatible patterns for loading Web Workers and static assets:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// Module Worker (required: { type: 'module' })
|
||||||
|
const worker = new Worker(
|
||||||
|
new URL('./worker.ts', import.meta.url),
|
||||||
|
{ type: 'module' },
|
||||||
|
);
|
||||||
|
|
||||||
|
// SharedWorker, same pattern
|
||||||
|
const shared = new SharedWorker(
|
||||||
|
new URL('./shared.ts', import.meta.url),
|
||||||
|
{ type: 'module' },
|
||||||
|
);
|
||||||
|
|
||||||
|
// Static asset URL (images, wasm, fonts, audio, etc.)
|
||||||
|
const logoUrl = new URL('./logo.svg', import.meta.url);
|
||||||
|
```
|
||||||
|
|
||||||
|
**Supported:**
|
||||||
|
- `new Worker(new URL('<spec>', import.meta.url), { type: 'module' })`
|
||||||
|
- `new SharedWorker(new URL('<spec>', import.meta.url), { type: 'module' })`
|
||||||
|
- `new URL('<spec>', import.meta.url)` where `<spec>` resolves to a non-source file (images, wasm, audio, fonts, etc.)
|
||||||
|
- Relative (`./`, `../`), absolute (`/`), and alias (`@/`) specifiers
|
||||||
|
- String literals with any quote style, including backticks without interpolation
|
||||||
|
|
||||||
|
**Not supported (will emit a build error):**
|
||||||
|
- Classic (non-module) workers — `{ type: 'module' }` is required
|
||||||
|
- Dynamic specifiers — the first argument to `new URL()` must be a string literal
|
||||||
|
- `new URL(..., import.meta.url)` pointing at source files (`.ts/.tsx/.js/.jsx/.mjs/.cjs/.css`); use a regular import or the Worker pattern instead (emits a console warning, then leaves the expression untouched)
|
||||||
|
|
||||||
|
Workers are bundled as separate ESM chunks and can import from npm packages normally — the same ESM-CDN rewrites applied to the main bundle apply to workers. When any workers are emitted, the build also extends the output CSP's `worker-src` and `child-src` directives to permit loading the ESM CDN from within workers.
|
||||||
|
|
||||||
### Git Integration with isomorphic-git
|
### Git Integration with isomorphic-git
|
||||||
|
|
||||||
Shakespeare provides full Git functionality in the browser using `isomorphic-git` and `@isomorphic-git/lightning-fs`, with all data persisted in IndexedDB.
|
Shakespeare provides full Git functionality in the browser using `isomorphic-git` and `@isomorphic-git/lightning-fs`, with all data persisted in IndexedDB.
|
||||||
|
|||||||
@@ -1,5 +1,43 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## [9.12.0] - 2026-04-25
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Build support for module workers and static asset URLs — projects using `new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })`, `SharedWorker`, and `new URL('./logo.svg', import.meta.url)` now build and run correctly in the preview
|
||||||
|
- Preview pane grants microphone, ambient-light-sensor, and other device permissions so richer apps can run inside the preview
|
||||||
|
|
||||||
|
## [9.11.4] - 2026-04-17
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Preview pane no longer gets stuck on stale builds during rapid edits
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Reduce AI costs for Anthropic models via OpenRouter by caching tool definitions across turns
|
||||||
|
|
||||||
|
## [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
|
## [9.11.0] - 2026-04-03
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
Generated
+7
-6
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "shakespeare.diy",
|
"name": "shakespeare.diy",
|
||||||
"version": "9.10.4",
|
"version": "9.11.4",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "shakespeare.diy",
|
"name": "shakespeare.diy",
|
||||||
"version": "9.10.4",
|
"version": "9.11.4",
|
||||||
"license": "AGPL-3.0-or-later",
|
"license": "AGPL-3.0-or-later",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@capacitor/app": "^8.1.0",
|
"@capacitor/app": "^8.1.0",
|
||||||
@@ -57,6 +57,8 @@
|
|||||||
"@tanstack/react-query": "^5.56.2",
|
"@tanstack/react-query": "^5.56.2",
|
||||||
"@unhead/addons": "^2.0.10",
|
"@unhead/addons": "^2.0.10",
|
||||||
"@unhead/react": "^2.0.10",
|
"@unhead/react": "^2.0.10",
|
||||||
|
"acorn": "^8.16.0",
|
||||||
|
"acorn-jsx": "^5.3.2",
|
||||||
"buffer": "^6.0.3",
|
"buffer": "^6.0.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
@@ -6797,9 +6799,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/acorn": {
|
"node_modules/acorn": {
|
||||||
"version": "8.15.0",
|
"version": "8.16.0",
|
||||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
|
||||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"bin": {
|
"bin": {
|
||||||
"acorn": "bin/acorn"
|
"acorn": "bin/acorn"
|
||||||
@@ -6812,7 +6814,6 @@
|
|||||||
"version": "5.3.2",
|
"version": "5.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
|
"resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz",
|
||||||
"integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
|
"integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||||
|
|||||||
+3
-1
@@ -3,7 +3,7 @@
|
|||||||
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
|
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
|
||||||
"homepage": "https://shakespeare.diy",
|
"homepage": "https://shakespeare.diy",
|
||||||
"license": "AGPL-3.0-or-later",
|
"license": "AGPL-3.0-or-later",
|
||||||
"version": "9.11.0",
|
"version": "9.12.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "shakespeare.diy",
|
"name": "shakespeare.diy",
|
||||||
@@ -70,6 +70,8 @@
|
|||||||
"@tanstack/react-query": "^5.56.2",
|
"@tanstack/react-query": "^5.56.2",
|
||||||
"@unhead/addons": "^2.0.10",
|
"@unhead/addons": "^2.0.10",
|
||||||
"@unhead/react": "^2.0.10",
|
"@unhead/react": "^2.0.10",
|
||||||
|
"acorn": "^8.16.0",
|
||||||
|
"acorn-jsx": "^5.3.2",
|
||||||
"buffer": "^6.0.3",
|
"buffer": "^6.0.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
|||||||
@@ -1,5 +1,43 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## [9.12.0] - 2026-04-25
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Build support for module workers and static asset URLs — projects using `new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })`, `SharedWorker`, and `new URL('./logo.svg', import.meta.url)` now build and run correctly in the preview
|
||||||
|
- Preview pane grants microphone, ambient-light-sensor, and other device permissions so richer apps can run inside the preview
|
||||||
|
|
||||||
|
## [9.11.4] - 2026-04-17
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Preview pane no longer gets stuck on stale builds during rapid edits
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Reduce AI costs for Anthropic models via OpenRouter by caching tool definitions across turns
|
||||||
|
|
||||||
|
## [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
|
## [9.11.0] - 2026-04-03
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
@@ -138,18 +138,10 @@ self.addEventListener("fetch", (event) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Let iframe client system files be handled normally
|
// Let iframe client system files and common assets 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)
|
|
||||||
if (url.pathname.startsWith("/_iframe-client/") ||
|
if (url.pathname.startsWith("/_iframe-client/") ||
|
||||||
|
url.pathname === "/sw.js" ||
|
||||||
|
url.pathname === "/" ||
|
||||||
url.pathname === "/favicon.ico" ||
|
url.pathname === "/favicon.ico" ||
|
||||||
url.pathname === "/manifest.webmanifest") {
|
url.pathname === "/manifest.webmanifest") {
|
||||||
return;
|
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(), {
|
const { result } = renderHook(() => useAISettings(), {
|
||||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||||
});
|
});
|
||||||
|
|
||||||
await waitFor(() => {
|
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 () => {
|
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(), {
|
const { result } = renderHook(() => useAISettings(), {
|
||||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||||
});
|
});
|
||||||
@@ -65,6 +75,13 @@ describe('AISettingsProvider', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should move existing model to front when used again', async () => {
|
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(), {
|
const { result } = renderHook(() => useAISettings(), {
|
||||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||||
});
|
});
|
||||||
@@ -99,6 +116,13 @@ describe('AISettingsProvider', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should limit recently used models to 10 items', async () => {
|
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(), {
|
const { result } = renderHook(() => useAISettings(), {
|
||||||
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
wrapper: ({ children }) => <TestApp>{children}</TestApp>,
|
||||||
});
|
});
|
||||||
@@ -147,6 +171,13 @@ describe('AISettingsProvider', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should invalidate provider-models query when updateSettings is called with providers', async () => {
|
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
|
// Mock the QueryClient.invalidateQueries method
|
||||||
const mockInvalidateQueries = vi.fn();
|
const mockInvalidateQueries = vi.fn();
|
||||||
|
|
||||||
|
|||||||
@@ -4,33 +4,33 @@ import { AISettingsContext, type AISettings, type AIProvider, type MCPServer, ty
|
|||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||||
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
||||||
|
import { EMPTY_AI_SETTINGS, OPENCODE_DEFAULT_SETTINGS } from '@/lib/opencode-defaults';
|
||||||
|
|
||||||
interface AISettingsProviderProps {
|
interface AISettingsProviderProps {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
const DEFAULT_SETTINGS: AISettings = {
|
|
||||||
providers: [],
|
|
||||||
recentlyUsedModels: [],
|
|
||||||
mcpServers: {},
|
|
||||||
};
|
|
||||||
|
|
||||||
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { fs } = useFS();
|
const { fs } = useFS();
|
||||||
const { configPath } = useFSPaths();
|
const { configPath } = useFSPaths();
|
||||||
const [settings, setSettings] = useState<AISettings>(DEFAULT_SETTINGS);
|
const [settings, setSettings] = useState<AISettings>(EMPTY_AI_SETTINGS);
|
||||||
const [isInitialized, setIsInitialized] = useState(false);
|
const [isInitialized, setIsInitialized] = useState(false);
|
||||||
|
|
||||||
// Initialize settings from VFS on mount
|
// Initialize settings from VFS on mount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const initializeSettings = async () => {
|
const initializeSettings = async () => {
|
||||||
try {
|
try {
|
||||||
const settings = await readAISettings(fs, configPath);
|
const loaded = await readAISettings(fs, configPath);
|
||||||
setSettings(settings);
|
// 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) {
|
} catch (error) {
|
||||||
console.error('Failed to initialize AI settings:', error);
|
console.error('Failed to initialize AI settings:', error);
|
||||||
setSettings(DEFAULT_SETTINGS);
|
setSettings(EMPTY_AI_SETTINGS);
|
||||||
} finally {
|
} finally {
|
||||||
setIsInitialized(true);
|
setIsInitialized(true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -84,9 +84,9 @@ export function AddCustomProviderDialog({
|
|||||||
provider = {
|
provider = {
|
||||||
type: 'nsite',
|
type: 'nsite',
|
||||||
name: customName.trim(),
|
name: customName.trim(),
|
||||||
gateway: customGateway.trim() || 'nsite.lol',
|
gateway: customGateway.trim() || 'shakespeare.to',
|
||||||
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
|
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') {
|
} else if (customProviderType === 'netlify') {
|
||||||
if (!customApiKey.trim()) return;
|
if (!customApiKey.trim()) return;
|
||||||
@@ -252,7 +252,7 @@ export function AddCustomProviderDialog({
|
|||||||
<Label htmlFor="custom-gateway">Gateway</Label>
|
<Label htmlFor="custom-gateway">Gateway</Label>
|
||||||
<Input
|
<Input
|
||||||
id="custom-gateway"
|
id="custom-gateway"
|
||||||
placeholder="nsite.lol"
|
placeholder="shakespeare.to"
|
||||||
value={customGateway}
|
value={customGateway}
|
||||||
onChange={(e) => setCustomGateway(e.target.value)}
|
onChange={(e) => setCustomGateway(e.target.value)}
|
||||||
/>
|
/>
|
||||||
@@ -269,7 +269,7 @@ export function AddCustomProviderDialog({
|
|||||||
items={customBlossomServers}
|
items={customBlossomServers}
|
||||||
onChange={setCustomBlossomServers}
|
onChange={setCustomBlossomServers}
|
||||||
protocol="https"
|
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 { useFS } from '@/hooks/useFS';
|
||||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||||
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
|
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
|
||||||
|
import { DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
|
||||||
|
|
||||||
const DEFAULT_SETTINGS: DeploySettings = {
|
const DEFAULT_SETTINGS: DeploySettings = {
|
||||||
providers: [],
|
providers: [DEFAULT_NSITE_PROVIDER],
|
||||||
};
|
};
|
||||||
|
|
||||||
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
||||||
|
|||||||
@@ -134,7 +134,7 @@ export function ProviderConfigDialog({
|
|||||||
</Label>
|
</Label>
|
||||||
<Input
|
<Input
|
||||||
id="provider-gateway"
|
id="provider-gateway"
|
||||||
placeholder="nsite.lol"
|
placeholder="shakespeare.to"
|
||||||
value={localProvider.gateway || ''}
|
value={localProvider.gateway || ''}
|
||||||
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
|
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
|
||||||
/>
|
/>
|
||||||
@@ -152,7 +152,7 @@ export function ProviderConfigDialog({
|
|||||||
items={localProvider.blossomServers ?? []}
|
items={localProvider.blossomServers ?? []}
|
||||||
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
|
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
|
||||||
protocol="https"
|
protocol="https"
|
||||||
placeholder="blossom.primal.net"
|
placeholder="blossom.ditto.pub"
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { encodeBase64 } from '@std/encoding/base64';
|
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 { useTranslation } from 'react-i18next';
|
||||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
@@ -25,6 +25,8 @@ import { Terminal as TerminalComponent } from '@/components/Terminal';
|
|||||||
import { useSearchParams } from 'react-router-dom';
|
import { useSearchParams } from 'react-router-dom';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
import { isMediaFile } from '@/lib/fileUtils';
|
import { isMediaFile } from '@/lib/fileUtils';
|
||||||
|
import { deriveIframeSubdomain } from '@/lib/iframeSubdomain';
|
||||||
|
import { getPreviewInjectedScript } from '@/lib/previewInjectedScript';
|
||||||
|
|
||||||
interface PreviewPaneProps {
|
interface PreviewPaneProps {
|
||||||
projectId: string;
|
projectId: string;
|
||||||
@@ -67,6 +69,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { config } = useAppContext();
|
const { config } = useAppContext();
|
||||||
const { previewDomain } = config;
|
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 [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||||
const [fileContent, setFileContent] = useState<string>('');
|
const [fileContent, setFileContent] = useState<string>('');
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
@@ -82,6 +91,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||||
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
|
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
|
||||||
const [isLogsOpen, setIsLogsOpen] = useState(false);
|
const [isLogsOpen, setIsLogsOpen] = useState(false);
|
||||||
|
// Incremented to force a full remount of the preview iframe. Using a
|
||||||
|
// remount (via React key) is more reliable than sending a `refresh`
|
||||||
|
// JSON-RPC to the nested iframe.diy frames: messages can be silently
|
||||||
|
// dropped if the inner iframe is mid-reload, not yet mounted, or if
|
||||||
|
// the outer frame's handshake is still pending. A remount always works.
|
||||||
|
const [iframeReloadKey, setIframeReloadKey] = useState(0);
|
||||||
const previewContainerRef = useRef<HTMLDivElement>(null);
|
const previewContainerRef = useRef<HTMLDivElement>(null);
|
||||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||||
const iframePanelRef = useRef<ImperativePanelHandle>(null);
|
const iframePanelRef = useRef<ImperativePanelHandle>(null);
|
||||||
@@ -182,18 +197,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
|
|
||||||
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
||||||
if (iframeRef.current?.contentWindow) {
|
if (iframeRef.current?.contentWindow) {
|
||||||
|
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
|
||||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
|
||||||
}
|
}
|
||||||
}, [projectId, previewDomain]);
|
}, [previewOrigin]);
|
||||||
|
|
||||||
const sendError = useCallback((message: JSONRPCResponse) => {
|
const sendError = useCallback((message: JSONRPCResponse) => {
|
||||||
if (iframeRef.current?.contentWindow) {
|
if (iframeRef.current?.contentWindow) {
|
||||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
|
||||||
}
|
}
|
||||||
}, [projectId, previewDomain]);
|
}, [previewOrigin]);
|
||||||
|
|
||||||
const handleConsoleMessage = useCallback((message: {
|
const handleConsoleMessage = useCallback((message: {
|
||||||
jsonrpc: '2.0';
|
jsonrpc: '2.0';
|
||||||
@@ -248,6 +260,17 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
}
|
}
|
||||||
}, [historyIndex, navigationHistory]);
|
}, [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>) => {
|
const sendNavigationCommand = useCallback((method: string, params?: Record<string, unknown>) => {
|
||||||
if (iframeRef.current?.contentWindow) {
|
if (iframeRef.current?.contentWindow) {
|
||||||
const message = {
|
const message = {
|
||||||
@@ -256,10 +279,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
params: params || {},
|
params: params || {},
|
||||||
id: Date.now()
|
id: Date.now()
|
||||||
};
|
};
|
||||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
|
||||||
}
|
}
|
||||||
}, [projectId, previewDomain]);
|
}, [previewOrigin]);
|
||||||
|
|
||||||
const navigateIframe = useCallback((url: string) => {
|
const navigateIframe = useCallback((url: string) => {
|
||||||
// Send semantic path directly (e.g., "/about", "/contact")
|
// Send semantic path directly (e.g., "/about", "/contact")
|
||||||
@@ -268,13 +290,31 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
}, [sendNavigationCommand]);
|
}, [sendNavigationCommand]);
|
||||||
|
|
||||||
const refreshIframe = useCallback(() => {
|
const refreshIframe = useCallback(() => {
|
||||||
sendNavigationCommand('refresh');
|
// Force a full remount of the iframe rather than sending a `refresh`
|
||||||
}, [sendNavigationCommand]);
|
// JSON-RPC command. The RPC path is unreliable during rapid build
|
||||||
|
// cycles because the command has to traverse two iframes (outer
|
||||||
|
// iframe.diy frame → inner app iframe) and can be silently dropped
|
||||||
|
// if the inner iframe is mid-reload, not yet mounted, or the outer
|
||||||
|
// frame's handshake is still pending.
|
||||||
|
setIframeReloadKey((n) => n + 1);
|
||||||
|
}, []);
|
||||||
|
|
||||||
const toggleFullscreen = useCallback(() => {
|
const toggleFullscreen = useCallback(() => {
|
||||||
setIsFullscreen(prev => !prev);
|
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 handleFetch = useCallback(async (request: JSONRPCRequest) => {
|
||||||
const { params, id } = request;
|
const { params, id } = request;
|
||||||
const { request: fetchRequest } = params;
|
const { request: fetchRequest } = params;
|
||||||
@@ -282,16 +322,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
try {
|
try {
|
||||||
// Parse the URL and validate origin
|
// Parse the URL and validate origin
|
||||||
const url = new URL(fetchRequest.url);
|
const url = new URL(fetchRequest.url);
|
||||||
const expectedOrigin = `https://${projectId}.${previewDomain}`;
|
|
||||||
|
|
||||||
if (url.origin !== expectedOrigin) {
|
if (url.origin !== previewOrigin) {
|
||||||
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
|
console.log(`Invalid origin: ${url.origin}, expected: ${previewOrigin}`);
|
||||||
sendError({
|
sendError({
|
||||||
jsonrpc: '2.0',
|
jsonrpc: '2.0',
|
||||||
error: {
|
error: {
|
||||||
code: -32003,
|
code: -32003,
|
||||||
message: 'Invalid URL - origin mismatch',
|
message: 'Invalid URL - origin mismatch',
|
||||||
data: { url: fetchRequest.url, expectedOrigin }
|
data: { url: fetchRequest.url, expectedOrigin: previewOrigin }
|
||||||
},
|
},
|
||||||
id
|
id
|
||||||
});
|
});
|
||||||
@@ -301,24 +340,52 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
const path = url.pathname;
|
const path = url.pathname;
|
||||||
const filePath = path;
|
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)
|
// Skip SPA fallback for static assets (files with extensions)
|
||||||
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
|
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
|
||||||
|
|
||||||
// SPA routing: try to serve the exact file first
|
// SPA routing: try to serve the exact file first
|
||||||
try {
|
try {
|
||||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
|
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
|
||||||
|
const contentType = getContentType(filePath);
|
||||||
console.log(`Serving file: ${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({
|
sendResponse({
|
||||||
jsonrpc: '2.0',
|
jsonrpc: '2.0',
|
||||||
result: {
|
result: {
|
||||||
status: 200,
|
status: 200,
|
||||||
statusText: 'OK',
|
statusText: 'OK',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': getContentType(filePath),
|
'Content-Type': contentType,
|
||||||
'Cache-Control': 'no-cache',
|
'Cache-Control': 'no-cache',
|
||||||
},
|
},
|
||||||
body: encodeBase64(bytes),
|
body,
|
||||||
},
|
},
|
||||||
id
|
id
|
||||||
});
|
});
|
||||||
@@ -349,6 +416,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
|
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
|
||||||
console.log(`Serving index.html fallback for: ${path}`);
|
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({
|
sendResponse({
|
||||||
jsonrpc: '2.0',
|
jsonrpc: '2.0',
|
||||||
result: {
|
result: {
|
||||||
@@ -358,7 +429,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
'Content-Type': 'text/html',
|
'Content-Type': 'text/html',
|
||||||
'Cache-Control': 'no-cache',
|
'Cache-Control': 'no-cache',
|
||||||
},
|
},
|
||||||
body: encodeBase64(bytes),
|
body,
|
||||||
},
|
},
|
||||||
id
|
id
|
||||||
});
|
});
|
||||||
@@ -389,32 +460,37 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
id
|
id
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}, [projectId, projectsManager, sendResponse, sendError, previewDomain]);
|
}, [projectId, projectsManager, sendResponse, sendError, previewOrigin, injectScript]);
|
||||||
|
|
||||||
// Setup messaging protocol for iframe communication
|
// Setup messaging protocol for iframe communication
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleMessage = (event: MessageEvent) => {
|
const handleMessage = (event: MessageEvent) => {
|
||||||
// Verify origin for security
|
// Verify origin for security
|
||||||
const expectedOrigin = `https://${projectId}.${previewDomain}`;
|
if (event.origin !== previewOrigin) {
|
||||||
if (event.origin !== expectedOrigin) {
|
|
||||||
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = event.data;
|
const message = event.data;
|
||||||
console.log('Received message from iframe:', message);
|
if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0') return;
|
||||||
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
|
|
||||||
|
// Handle iframe.diy handshake: respond to "ready" with "init"
|
||||||
|
if (message.method === 'ready') {
|
||||||
|
sendNotification('init', { version: 1 });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message.method === 'fetch') {
|
||||||
handleFetch(message);
|
handleFetch(message);
|
||||||
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
|
} else if (message.method === 'console') {
|
||||||
handleConsoleMessage(message);
|
handleConsoleMessage(message);
|
||||||
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
|
} else if (message.method === 'updateNavigationState') {
|
||||||
handleUpdateNavigationState(message);
|
handleUpdateNavigationState(message);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
window.addEventListener('message', handleMessage);
|
window.addEventListener('message', handleMessage);
|
||||||
return () => window.removeEventListener('message', handleMessage);
|
return () => window.removeEventListener('message', handleMessage);
|
||||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
|
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, sendNotification, previewOrigin]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (selectedFile) {
|
if (selectedFile) {
|
||||||
@@ -645,12 +721,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
|||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<iframe
|
<iframe
|
||||||
key={projectId}
|
key={`${projectId}:${iframeReloadKey}`}
|
||||||
ref={iframeRef}
|
ref={iframeRef}
|
||||||
src={`https://${projectId}.${previewDomain}/`}
|
src={`${previewOrigin}/`}
|
||||||
className="w-full h-full border-0"
|
className="w-full h-full border-0"
|
||||||
title="Project Preview"
|
title="Project Preview"
|
||||||
sandbox="allow-scripts allow-same-origin allow-forms"
|
allow="microphone; camera; display-capture; geolocation; clipboard-read; clipboard-write; encrypted-media; fullscreen; autoplay; midi; accelerometer; gyroscope; magnetometer; ambient-light-sensor; payment; usb; xr-spatial-tracking"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -612,6 +612,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
<span className="font-medium">{nsiteVfsConfig.title}</span>
|
<span className="font-medium">{nsiteVfsConfig.title}</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
<span className="text-muted-foreground">Relays</span>
|
<span className="text-muted-foreground">Relays</span>
|
||||||
<span className="font-medium">{relayCount} configured</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" />
|
<ExternalLink className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex justify-end gap-2">
|
<div className="flex justify-end gap-2">
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ export interface AppConfig {
|
|||||||
faviconUrl: string;
|
faviconUrl: string;
|
||||||
/** Nostr Git web URL template (e.g., "https://nostrhub.io/{naddr}") */
|
/** Nostr Git web URL template (e.g., "https://nostrhub.io/{naddr}") */
|
||||||
ngitWebUrl: string;
|
ngitWebUrl: string;
|
||||||
/** Preview domain for iframe sandboxing (e.g., "local-shakespeare.dev") */
|
/** Preview domain for iframe sandboxing (e.g., "iframe.diy") */
|
||||||
previewDomain: string;
|
previewDomain: string;
|
||||||
/** Selected language */
|
/** Selected language */
|
||||||
language?: string;
|
language?: string;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query';
|
|||||||
import { nip19 } from 'nostr-tools';
|
import { nip19 } from 'nostr-tools';
|
||||||
import type { NostrEvent, NostrFilter, NRelay, NPool } from '@nostrify/nostrify';
|
import type { NostrEvent, NostrFilter, NRelay, NPool } from '@nostrify/nostrify';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
|
import { NostrURI } from '@/lib/NostrURI';
|
||||||
|
|
||||||
export interface AppSubmission extends NostrEvent {
|
export interface AppSubmission extends NostrEvent {
|
||||||
appName: string;
|
appName: string;
|
||||||
@@ -79,7 +80,7 @@ function repositoryUrlFromATag(aTagValue: string): string {
|
|||||||
const parts = aTagValue.split(':');
|
const parts = aTagValue.split(':');
|
||||||
if (parts.length < 3) return '';
|
if (parts.length < 3) return '';
|
||||||
const [, pubkey, identifier] = parts;
|
const [, pubkey, identifier] = parts;
|
||||||
return `nostr://${pubkey}/${identifier}`;
|
return new NostrURI({ pubkey, identifier }).toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAppSubmissions() {
|
export function useAppSubmissions() {
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ describe('useGenerateProjectInfo', () => {
|
|||||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||||
previewDomain: 'local-shakespeare.dev',
|
previewDomain: 'iframe.diy',
|
||||||
showcaseEnabled: true,
|
showcaseEnabled: true,
|
||||||
showcaseCurator: '',
|
showcaseCurator: '',
|
||||||
graspMetadata: {
|
graspMetadata: {
|
||||||
@@ -230,7 +230,7 @@ describe('useGenerateProjectInfo', () => {
|
|||||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||||
previewDomain: 'local-shakespeare.dev',
|
previewDomain: 'iframe.diy',
|
||||||
showcaseEnabled: true,
|
showcaseEnabled: true,
|
||||||
showcaseCurator: '',
|
showcaseCurator: '',
|
||||||
graspMetadata: {
|
graspMetadata: {
|
||||||
|
|||||||
@@ -14,8 +14,9 @@ export function useUploadFile() {
|
|||||||
|
|
||||||
const uploader = new BlossomUploader({
|
const uploader = new BlossomUploader({
|
||||||
servers: [
|
servers: [
|
||||||
'https://blossom.primal.net/',
|
|
||||||
'https://blossom.ditto.pub/',
|
'https://blossom.ditto.pub/',
|
||||||
|
'https://blossom.dreamith.to/',
|
||||||
|
'https://blossom.primal.net/',
|
||||||
],
|
],
|
||||||
signer: user.signer,
|
signer: user.signer,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ const testConfig: AppConfig = {
|
|||||||
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||||
previewDomain: 'local-shakespeare.dev',
|
previewDomain: 'iframe.diy',
|
||||||
language: 'en',
|
language: 'en',
|
||||||
showcaseEnabled: true,
|
showcaseEnabled: true,
|
||||||
showcaseCurator: '',
|
showcaseCurator: '',
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import type OpenAI from 'openai';
|
||||||
|
import { applyOpenRouterTransforms } from './ai-client';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper: minimal valid ChatCompletionCreateParams for transform tests.
|
||||||
|
*/
|
||||||
|
function makeBody(overrides: Partial<OpenAI.Chat.Completions.ChatCompletionCreateParams> = {})
|
||||||
|
: OpenAI.Chat.Completions.ChatCompletionCreateParams {
|
||||||
|
return {
|
||||||
|
model: 'anthropic/claude-opus-4.6',
|
||||||
|
messages: [
|
||||||
|
{ role: 'system', content: 'you are helpful' },
|
||||||
|
{ role: 'user', content: 'hello' },
|
||||||
|
],
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('applyOpenRouterTransforms', () => {
|
||||||
|
it('adds usage accounting to the body regardless of model', () => {
|
||||||
|
const body = makeBody({ model: 'openai/gpt-4' });
|
||||||
|
applyOpenRouterTransforms(body);
|
||||||
|
expect((body as { usage?: { include?: boolean } }).usage).toEqual({ include: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not apply cache_control for non-Anthropic models', () => {
|
||||||
|
const body = makeBody({
|
||||||
|
model: 'openai/gpt-4',
|
||||||
|
tools: [
|
||||||
|
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
applyOpenRouterTransforms(body);
|
||||||
|
// messages remain as plain strings (no normalization)
|
||||||
|
expect(body.messages[0].content).toBe('you are helpful');
|
||||||
|
// tools untouched
|
||||||
|
expect((body.tools![0] as { cache_control?: unknown }).cache_control).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('places cache_control on the last tool for Anthropic models', () => {
|
||||||
|
const body = makeBody({
|
||||||
|
tools: [
|
||||||
|
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
|
||||||
|
{ type: 'function', function: { name: 't2', description: '', parameters: { type: 'object' } } },
|
||||||
|
{ type: 'function', function: { name: 't3', description: '', parameters: { type: 'object' } } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
applyOpenRouterTransforms(body);
|
||||||
|
|
||||||
|
// Only the LAST tool gets cache_control — Anthropic caches everything
|
||||||
|
// up to and including the marked block, so marking the last tool is
|
||||||
|
// sufficient and we spend only one of the 4 breakpoints.
|
||||||
|
expect((body.tools![0] as { cache_control?: unknown }).cache_control).toBeUndefined();
|
||||||
|
expect((body.tools![1] as { cache_control?: unknown }).cache_control).toBeUndefined();
|
||||||
|
expect((body.tools![2] as { cache_control?: { type: string } }).cache_control)
|
||||||
|
.toEqual({ type: 'ephemeral' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('places cache_control on the system message and last two non-system messages', () => {
|
||||||
|
const body = makeBody({
|
||||||
|
messages: [
|
||||||
|
{ role: 'system', content: 'you are helpful' },
|
||||||
|
{ role: 'user', content: 'first' },
|
||||||
|
{ role: 'assistant', content: 'reply 1' },
|
||||||
|
{ role: 'user', content: 'second' },
|
||||||
|
{ role: 'assistant', content: 'reply 2' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
applyOpenRouterTransforms(body);
|
||||||
|
|
||||||
|
const hasCache = (m: OpenAI.Chat.Completions.ChatCompletionMessageParam): boolean => {
|
||||||
|
if (!Array.isArray(m.content)) return false;
|
||||||
|
return m.content.some((b) => {
|
||||||
|
const block = b as { cache_control?: unknown };
|
||||||
|
return block.cache_control !== undefined;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// System: cached
|
||||||
|
expect(hasCache(body.messages[0])).toBe(true);
|
||||||
|
// Old turns: not cached
|
||||||
|
expect(hasCache(body.messages[1])).toBe(false);
|
||||||
|
expect(hasCache(body.messages[2])).toBe(false);
|
||||||
|
// Last two non-system: cached
|
||||||
|
expect(hasCache(body.messages[3])).toBe(true);
|
||||||
|
expect(hasCache(body.messages[4])).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('normalizes string content to text block arrays for Anthropic', () => {
|
||||||
|
const body = makeBody();
|
||||||
|
applyOpenRouterTransforms(body);
|
||||||
|
// System and user both turned into arrays of text blocks
|
||||||
|
expect(Array.isArray(body.messages[0].content)).toBe(true);
|
||||||
|
expect(Array.isArray(body.messages[1].content)).toBe(true);
|
||||||
|
const sysBlocks = body.messages[0].content as Array<{ type: string; text: string }>;
|
||||||
|
expect(sysBlocks[0]).toEqual(
|
||||||
|
expect.objectContaining({ type: 'text', text: 'you are helpful' }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not crash when tools is undefined or empty', () => {
|
||||||
|
const a = makeBody();
|
||||||
|
expect(() => applyOpenRouterTransforms(a)).not.toThrow();
|
||||||
|
expect(a.tools).toBeUndefined();
|
||||||
|
|
||||||
|
const b = makeBody({ tools: [] });
|
||||||
|
expect(() => applyOpenRouterTransforms(b)).not.toThrow();
|
||||||
|
expect(b.tools).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not mutate the original tools array reference (uses structuredClone)', () => {
|
||||||
|
const originalTools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
|
||||||
|
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
|
||||||
|
];
|
||||||
|
const originalRef = originalTools;
|
||||||
|
const body = makeBody({ tools: originalTools });
|
||||||
|
applyOpenRouterTransforms(body);
|
||||||
|
|
||||||
|
// body.tools is now a clone, original array untouched
|
||||||
|
expect(body.tools).not.toBe(originalRef);
|
||||||
|
expect((originalTools[0] as { cache_control?: unknown }).cache_control).toBeUndefined();
|
||||||
|
// But body.tools has cache_control
|
||||||
|
expect((body.tools![0] as { cache_control?: { type: string } }).cache_control)
|
||||||
|
.toEqual({ type: 'ephemeral' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('produces byte-identical output across two calls with the same input (cache stability)', () => {
|
||||||
|
// This is the property the Anthropic cache relies on: the tools block
|
||||||
|
// hashes to the same value on every turn. If this test ever fails, tool
|
||||||
|
// caching will silently stop working.
|
||||||
|
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
|
||||||
|
{ type: 'function', function: { name: 'a', description: 'x', parameters: { type: 'object', properties: { foo: { type: 'string' } } } } },
|
||||||
|
{ type: 'function', function: { name: 'b', description: 'y', parameters: { type: 'object' } } },
|
||||||
|
];
|
||||||
|
|
||||||
|
const body1 = makeBody({ tools: structuredClone(tools) });
|
||||||
|
const body2 = makeBody({ tools: structuredClone(tools) });
|
||||||
|
applyOpenRouterTransforms(body1);
|
||||||
|
applyOpenRouterTransforms(body2);
|
||||||
|
|
||||||
|
expect(JSON.stringify(body1.tools)).toEqual(JSON.stringify(body2.tools));
|
||||||
|
});
|
||||||
|
});
|
||||||
+80
-28
@@ -36,6 +36,16 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
|||||||
request = new Request(request, { headers });
|
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 Nostr authentication is required and we have a user, use NIP-98
|
||||||
if (provider.nostr && user?.signer) {
|
if (provider.nostr && user?.signer) {
|
||||||
// Create the NIP98 token
|
// Create the NIP98 token
|
||||||
@@ -64,34 +74,7 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
|||||||
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
||||||
// OpenRouter-specific hacks
|
// OpenRouter-specific hacks
|
||||||
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
|
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
|
||||||
// Usage accounting field to get token usage and cost per request
|
applyOpenRouterTransforms(body);
|
||||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
|
||||||
(body as { usage?: { include?: boolean } }).usage = { include: true };
|
|
||||||
|
|
||||||
// Prompt caching for Claude models
|
|
||||||
// https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
|
|
||||||
if (body.model.startsWith("anthropic/")) {
|
|
||||||
// First normalize the message history to use content blocks
|
|
||||||
body.messages = structuredClone(body.messages);
|
|
||||||
body.messages = body.messages.map((m) => {
|
|
||||||
if (m.role !== "function" && typeof m.content === "string") {
|
|
||||||
return { ...m, content: [{ type: "text", text: m.content }] };
|
|
||||||
} else {
|
|
||||||
return m;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const systemMessage = body.messages.find((m) => m.role === "system");
|
|
||||||
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
|
|
||||||
const lastTwoMessages = nonSystemMessages.slice(-2);
|
|
||||||
|
|
||||||
if (systemMessage) {
|
|
||||||
addCacheControl(systemMessage);
|
|
||||||
}
|
|
||||||
for (const msg of lastTwoMessages) {
|
|
||||||
addCacheControl(msg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return createCompletion(body, options);
|
return createCompletion(body, options);
|
||||||
@@ -100,6 +83,75 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
|||||||
return openai;
|
return openai;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply OpenRouter-specific request body mutations: opt into usage accounting,
|
||||||
|
* and (for Anthropic models) place `cache_control` breakpoints so the tools
|
||||||
|
* array, system prompt, and last two messages get cached. Exported for tests.
|
||||||
|
*
|
||||||
|
* References:
|
||||||
|
* - OpenRouter prompt caching guide:
|
||||||
|
* https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
|
||||||
|
* - OpenRouter tool caching announcement: "gif-prompts-omni-search-tool-caching-and-byok-flags"
|
||||||
|
* - Anthropic prompt caching docs:
|
||||||
|
* https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
|
||||||
|
*
|
||||||
|
* Anthropic's cache hierarchy is `tools` → `system` → `messages`. We use all
|
||||||
|
* four breakpoints Anthropic allows per request:
|
||||||
|
* 1. last tool definition (caches the entire tools array)
|
||||||
|
* 2. system message (caches system prompt + AGENTS.md)
|
||||||
|
* 3. second-to-last non-system (caches most of conversation)
|
||||||
|
* 4. last non-system (caches everything including latest msg)
|
||||||
|
*/
|
||||||
|
export function applyOpenRouterTransforms(
|
||||||
|
body: OpenAI.Chat.Completions.ChatCompletionCreateParams,
|
||||||
|
): void {
|
||||||
|
// Usage accounting field to get token usage and cost per request.
|
||||||
|
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||||
|
(body as { usage?: { include?: boolean } }).usage = { include: true };
|
||||||
|
|
||||||
|
if (!body.model.startsWith("anthropic/")) return;
|
||||||
|
|
||||||
|
// Normalize the message history to use content blocks so we can attach
|
||||||
|
// cache_control to individual text parts.
|
||||||
|
body.messages = structuredClone(body.messages);
|
||||||
|
body.messages = body.messages.map((m) => {
|
||||||
|
if (m.role !== "function" && typeof m.content === "string") {
|
||||||
|
return { ...m, content: [{ type: "text", text: m.content }] };
|
||||||
|
} else {
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const systemMessage = body.messages.find((m) => m.role === "system");
|
||||||
|
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
|
||||||
|
const lastTwoMessages = nonSystemMessages.slice(-2);
|
||||||
|
|
||||||
|
if (systemMessage) {
|
||||||
|
addCacheControl(systemMessage);
|
||||||
|
}
|
||||||
|
for (const msg of lastTwoMessages) {
|
||||||
|
addCacheControl(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cache the tools array by marking the last tool with cache_control.
|
||||||
|
// Anthropic caches everything up to and including the marked block, so
|
||||||
|
// marking just the last tool caches the whole array. The tools array
|
||||||
|
// must be byte-stable across turns for cache hits — Shakespeare builds
|
||||||
|
// it once per session in `ChatPane`, so this holds as long as we don't
|
||||||
|
// mutate session.tools mid-session.
|
||||||
|
//
|
||||||
|
// Note: the OpenAI SDK serializes the body via plain `JSON.stringify`
|
||||||
|
// (see node_modules/openai/internal/request-options) and does not strip
|
||||||
|
// unknown fields, so the `cache_control` property survives the trip to
|
||||||
|
// OpenRouter.
|
||||||
|
if (body.tools && body.tools.length > 0) {
|
||||||
|
body.tools = structuredClone(body.tools);
|
||||||
|
const lastTool = body.tools[body.tools.length - 1];
|
||||||
|
(lastTool as { cache_control?: { type: "ephemeral" } })
|
||||||
|
.cache_control = { type: "ephemeral" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Mutate msg to add an Anthropic `cache_control` property to its last text block */
|
/** Mutate msg to add an Anthropic `cache_control` property to its last text block */
|
||||||
function addCacheControl(msg: OpenAI.Chat.Completions.ChatCompletionMessageParam) {
|
function addCacheControl(msg: OpenAI.Chat.Completions.ChatCompletionMessageParam) {
|
||||||
if (Array.isArray(msg.content)) {
|
if (Array.isArray(msg.content)) {
|
||||||
|
|||||||
+140
-76
@@ -3,6 +3,8 @@ import { join, dirname, extname } from "path-browserify";
|
|||||||
import type { Loader, Plugin } from "esbuild-wasm";
|
import type { Loader, Plugin } from "esbuild-wasm";
|
||||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||||
|
|
||||||
|
import { detectWorkersAndAssets, type WorkerMatch, type AssetMatch } from "./workerPlugin";
|
||||||
|
|
||||||
interface TsConfig {
|
interface TsConfig {
|
||||||
compilerOptions?: {
|
compilerOptions?: {
|
||||||
baseUrl?: string;
|
baseUrl?: string;
|
||||||
@@ -21,10 +23,17 @@ interface FsPluginOptions {
|
|||||||
cwd: string;
|
cwd: string;
|
||||||
tsconfig?: TsConfig;
|
tsconfig?: TsConfig;
|
||||||
packageJson?: PackageJson;
|
packageJson?: PackageJson;
|
||||||
|
/**
|
||||||
|
* Optional collectors populated when a source file contains
|
||||||
|
* `new Worker(new URL(...))` / `new SharedWorker(new URL(...))` /
|
||||||
|
* `new URL(..., import.meta.url)` patterns.
|
||||||
|
*/
|
||||||
|
collectWorkers?: WorkerMatch[];
|
||||||
|
collectAssets?: AssetMatch[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function fsPlugin(options: FsPluginOptions): Plugin {
|
export function fsPlugin(options: FsPluginOptions): Plugin {
|
||||||
const { fs, cwd, tsconfig, packageJson } = options;
|
const { fs, cwd, tsconfig, packageJson, collectWorkers, collectAssets } = options;
|
||||||
return {
|
return {
|
||||||
name: "fs",
|
name: "fs",
|
||||||
|
|
||||||
@@ -42,74 +51,17 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let resolved: string | undefined;
|
const resolved = await resolveFromImporter(args.path, args.importer, {
|
||||||
|
fs,
|
||||||
// Handle absolute paths
|
cwd,
|
||||||
if (args.path.startsWith("/")) {
|
tsconfig,
|
||||||
resolved = args.path;
|
packageJson,
|
||||||
}
|
});
|
||||||
// Handle @/ alias
|
|
||||||
else if (args.path.startsWith("@/")) {
|
|
||||||
resolved = join(cwd, "src", args.path.slice(2));
|
|
||||||
}
|
|
||||||
// Handle relative paths
|
|
||||||
else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
|
|
||||||
// Remove fs: prefix from importer if present
|
|
||||||
const importerPath = args.importer.replace(/^fs:/, '');
|
|
||||||
resolved = join(dirname(importerPath), args.path);
|
|
||||||
}
|
|
||||||
// Handle bare imports (e.g., "react", "@scope/package")
|
|
||||||
else if (args.path.match(/^[^./]/)) {
|
|
||||||
// Check if this is a file: dependency
|
|
||||||
const packageName = args.path.startsWith("@")
|
|
||||||
? args.path.split("/").slice(0, 2).join("/")
|
|
||||||
: args.path.split("/")[0];
|
|
||||||
|
|
||||||
const allDeps = {
|
|
||||||
...packageJson?.dependencies,
|
|
||||||
...packageJson?.devDependencies,
|
|
||||||
...packageJson?.peerDependencies,
|
|
||||||
};
|
|
||||||
|
|
||||||
const depVersion = allDeps[packageName];
|
|
||||||
|
|
||||||
if (depVersion && depVersion.startsWith("file:")) {
|
|
||||||
// Extract the file path (e.g., "file:./path" -> "./path")
|
|
||||||
const filePath = depVersion.slice(5); // Remove "file:" prefix
|
|
||||||
const packagePath = join(cwd, filePath);
|
|
||||||
|
|
||||||
// Get the subpath within the package (e.g., "package/subdir/file" -> "/subdir/file")
|
|
||||||
const subpath = args.path.slice(packageName.length);
|
|
||||||
|
|
||||||
resolved = join(packagePath, subpath);
|
|
||||||
} else {
|
|
||||||
return; // Let esmPlugin handle this
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Handle tsconfig baseUrl
|
|
||||||
else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
|
|
||||||
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
|
|
||||||
}
|
|
||||||
// Nothing matched, let other plugins handle it
|
|
||||||
else {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!resolved) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Vite query parameters https://vite.dev/guide/assets
|
if (!resolved) return;
|
||||||
const [cleaned, query] = resolved.split("?");
|
|
||||||
|
|
||||||
try {
|
|
||||||
resolved = await tryFileVariants(fs, cleaned);
|
|
||||||
} catch {
|
|
||||||
return; // Let other plugins handle this
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
path: resolved + (typeof query === "string" ? "?" + query : ""),
|
path: resolved,
|
||||||
namespace: "fs",
|
namespace: "fs",
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
@@ -138,8 +90,41 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let contents = await fs.readFile(path, "utf8");
|
||||||
|
|
||||||
|
// Run worker/asset detection on source-code files. This only
|
||||||
|
// does any real work if the file contains `new URL(`; the
|
||||||
|
// prefilter inside `detectWorkersAndAssets` bails early
|
||||||
|
// otherwise.
|
||||||
|
if (
|
||||||
|
(collectWorkers || collectAssets) &&
|
||||||
|
["ts", "tsx", "js", "jsx", "mjs", "cjs"].includes(ext)
|
||||||
|
) {
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source: contents,
|
||||||
|
filePath: path,
|
||||||
|
ext,
|
||||||
|
resolveSpec: async (spec, importerPath) => {
|
||||||
|
const resolved = await resolveFromImporter(spec, importerPath, {
|
||||||
|
fs,
|
||||||
|
cwd,
|
||||||
|
tsconfig,
|
||||||
|
packageJson,
|
||||||
|
});
|
||||||
|
if (!resolved) return undefined;
|
||||||
|
// Strip any ?query that made it onto the resolved path.
|
||||||
|
return resolved.split("?")[0];
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (result.workers.length || result.assets.length) {
|
||||||
|
contents = result.code;
|
||||||
|
if (collectWorkers) collectWorkers.push(...result.workers);
|
||||||
|
if (collectAssets) collectAssets.push(...result.assets);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
contents: await fs.readFile(path, "utf8"),
|
contents,
|
||||||
loader: ext as Loader,
|
loader: ext as Loader,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
@@ -148,6 +133,85 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ResolveContext {
|
||||||
|
fs: JSRuntimeFS;
|
||||||
|
cwd: string;
|
||||||
|
tsconfig?: TsConfig;
|
||||||
|
packageJson?: PackageJson;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a module specifier against an importer. This mirrors the
|
||||||
|
* resolution rules used by the fs plugin's onResolve handler so it
|
||||||
|
* can be reused by the worker/asset detection pass.
|
||||||
|
*/
|
||||||
|
export async function resolveFromImporter(
|
||||||
|
path: string,
|
||||||
|
importer: string | undefined,
|
||||||
|
ctx: ResolveContext,
|
||||||
|
): Promise<string | undefined> {
|
||||||
|
const { fs, cwd, tsconfig, packageJson } = ctx;
|
||||||
|
|
||||||
|
let resolved: string | undefined;
|
||||||
|
|
||||||
|
// Handle absolute paths
|
||||||
|
if (path.startsWith("/")) {
|
||||||
|
resolved = path;
|
||||||
|
}
|
||||||
|
// Handle @/ alias
|
||||||
|
else if (path.startsWith("@/")) {
|
||||||
|
resolved = join(cwd, "src", path.slice(2));
|
||||||
|
}
|
||||||
|
// Handle relative paths
|
||||||
|
else if (importer && (path.startsWith("./") || path.startsWith("../"))) {
|
||||||
|
const importerPath = importer.replace(/^fs:/, '');
|
||||||
|
resolved = join(dirname(importerPath), path);
|
||||||
|
}
|
||||||
|
// Handle bare imports (e.g., "react", "@scope/package")
|
||||||
|
else if (path.match(/^[^./]/)) {
|
||||||
|
const packageName = path.startsWith("@")
|
||||||
|
? path.split("/").slice(0, 2).join("/")
|
||||||
|
: path.split("/")[0];
|
||||||
|
|
||||||
|
const allDeps = {
|
||||||
|
...packageJson?.dependencies,
|
||||||
|
...packageJson?.devDependencies,
|
||||||
|
...packageJson?.peerDependencies,
|
||||||
|
};
|
||||||
|
|
||||||
|
const depVersion = allDeps[packageName];
|
||||||
|
|
||||||
|
if (depVersion && depVersion.startsWith("file:")) {
|
||||||
|
const filePath = depVersion.slice(5);
|
||||||
|
const packagePath = join(cwd, filePath);
|
||||||
|
const subpath = path.slice(packageName.length);
|
||||||
|
resolved = join(packagePath, subpath);
|
||||||
|
} else {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Handle tsconfig baseUrl
|
||||||
|
else if (importer && tsconfig?.compilerOptions?.baseUrl) {
|
||||||
|
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, path);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!resolved) return undefined;
|
||||||
|
|
||||||
|
// Vite query parameters https://vite.dev/guide/assets
|
||||||
|
const [cleaned, query] = resolved.split("?");
|
||||||
|
|
||||||
|
try {
|
||||||
|
resolved = await tryFileVariants(fs, cleaned);
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return resolved + (typeof query === "string" ? "?" + query : "");
|
||||||
|
}
|
||||||
|
|
||||||
async function tryFileVariants(
|
async function tryFileVariants(
|
||||||
fs: JSRuntimeFS,
|
fs: JSRuntimeFS,
|
||||||
basePath: string,
|
basePath: string,
|
||||||
@@ -167,23 +231,23 @@ async function tryFileVariants(
|
|||||||
const packageJsonPath = join(basePath, "package.json");
|
const packageJsonPath = join(basePath, "package.json");
|
||||||
const packageJsonText = await fs.readFile(packageJsonPath, "utf8");
|
const packageJsonText = await fs.readFile(packageJsonPath, "utf8");
|
||||||
const packageJson = JSON.parse(packageJsonText);
|
const packageJson = JSON.parse(packageJsonText);
|
||||||
|
|
||||||
// Check for various entry point fields
|
// Check for various entry point fields
|
||||||
const entryPoint = packageJson.exports?.['.']
|
const entryPoint = packageJson.exports?.['.']
|
||||||
|| packageJson.module
|
|| packageJson.module
|
||||||
|| packageJson.main
|
|| packageJson.main
|
||||||
|| 'index.js';
|
|| 'index.js';
|
||||||
|
|
||||||
// Resolve the entry point
|
// Resolve the entry point
|
||||||
const entryPath = typeof entryPoint === 'string'
|
const entryPath = typeof entryPoint === 'string'
|
||||||
? join(basePath, entryPoint)
|
? join(basePath, entryPoint)
|
||||||
: join(basePath, 'index.js');
|
: join(basePath, 'index.js');
|
||||||
|
|
||||||
const entryStat = await statSafe(fs, entryPath);
|
const entryStat = await statSafe(fs, entryPath);
|
||||||
if (entryStat.isFile()) {
|
if (entryStat.isFile()) {
|
||||||
return entryPath;
|
return entryPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try with different extensions if the entry point doesn't exist
|
// Try with different extensions if the entry point doesn't exist
|
||||||
for (const ext of extensions) {
|
for (const ext of extensions) {
|
||||||
const entryWithExt = entryPath.replace(/\.[^.]+$/, '') + ext;
|
const entryWithExt = entryPath.replace(/\.[^.]+$/, '') + ext;
|
||||||
@@ -195,7 +259,7 @@ async function tryFileVariants(
|
|||||||
} catch {
|
} catch {
|
||||||
// package.json doesn't exist or is invalid, fall through to index files
|
// package.json doesn't exist or is invalid, fall through to index files
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fall back to trying index files
|
// Fall back to trying index files
|
||||||
for (const ext of extensions) {
|
for (const ext of extensions) {
|
||||||
const indexFile = join(basePath, "index" + ext);
|
const indexFile = join(basePath, "index" + ext);
|
||||||
@@ -228,4 +292,4 @@ async function statSafe(fs: JSRuntimeFS, filePath: string): Promise<{ isFile():
|
|||||||
isDirectory: () => false,
|
isDirectory: () => false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
import { buildProject } from './index';
|
import { buildProject, updateCSPForEsmSh } from './index';
|
||||||
import { copyFiles } from '../copyFiles';
|
import { copyFiles } from '../copyFiles';
|
||||||
import type { JSRuntimeFS } from '../JSRuntime';
|
import type { JSRuntimeFS } from '../JSRuntime';
|
||||||
|
|
||||||
@@ -594,4 +594,38 @@ react@^18.0.0:
|
|||||||
// Verify package.json was read
|
// Verify package.json was read
|
||||||
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package.json', 'utf8');
|
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package.json', 'utf8');
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('updateCSPForEsmSh', () => {
|
||||||
|
const esmUrl = 'https://esm.shakespeare.diy';
|
||||||
|
|
||||||
|
it('extends the standard ESM directives with the CDN', () => {
|
||||||
|
const csp = "default-src 'self'; script-src 'self'; img-src 'self'";
|
||||||
|
const result = updateCSPForEsmSh(csp, esmUrl);
|
||||||
|
expect(result).toContain(`script-src 'self' ${esmUrl}`);
|
||||||
|
expect(result).toContain(`img-src 'self' ${esmUrl}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does NOT extend worker-src by default', () => {
|
||||||
|
const csp = "script-src 'self'; worker-src 'self'";
|
||||||
|
const result = updateCSPForEsmSh(csp, esmUrl);
|
||||||
|
// worker-src should remain untouched (still 'self' only).
|
||||||
|
expect(result).toContain("worker-src 'self'");
|
||||||
|
expect(result).not.toMatch(new RegExp(`worker-src[^;]*${esmUrl.replace(/[.]/g, '\\.')}`));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('extends worker-src and child-src when emittedWorkers is true', () => {
|
||||||
|
const csp = "script-src 'self'";
|
||||||
|
const result = updateCSPForEsmSh(csp, esmUrl, { emittedWorkers: true });
|
||||||
|
// The directives may be seeded with 'self' if absent; what matters
|
||||||
|
// is that the CDN is present in each.
|
||||||
|
expect(result).toMatch(new RegExp(`worker-src[^;]*${esmUrl.replace(/[.]/g, '\\.')}`));
|
||||||
|
expect(result).toMatch(new RegExp(`child-src[^;]*${esmUrl.replace(/[.]/g, '\\.')}`));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('extends existing worker-src directive without seeding when already present', () => {
|
||||||
|
const csp = "script-src 'self'; worker-src 'self' blob:";
|
||||||
|
const result = updateCSPForEsmSh(csp, esmUrl, { emittedWorkers: true });
|
||||||
|
expect(result).toMatch(new RegExp(`worker-src 'self' blob: ${esmUrl.replace(/[.]/g, '\\.')}`));
|
||||||
|
});
|
||||||
});
|
});
|
||||||
+230
-7
@@ -8,6 +8,7 @@ import { shakespearePlugin } from "./shakespearePlugin";
|
|||||||
import { esmPlugin } from "./esmPlugin";
|
import { esmPlugin } from "./esmPlugin";
|
||||||
import { fsPlugin } from "./fsPlugin";
|
import { fsPlugin } from "./fsPlugin";
|
||||||
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
|
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
|
||||||
|
import type { WorkerMatch, AssetMatch } from "./workerPlugin";
|
||||||
|
|
||||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||||
import type { Plugin } from 'esbuild-wasm';
|
import type { Plugin } from 'esbuild-wasm';
|
||||||
@@ -112,6 +113,23 @@ export async function readBuildContext(
|
|||||||
return { packageJson, packageLock, tsconfig };
|
return { packageJson, packageLock, tsconfig };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface CreatePluginsOptions {
|
||||||
|
/**
|
||||||
|
* When provided, the fs plugin will scan source files for
|
||||||
|
* `new Worker(new URL(..., import.meta.url))` patterns and push
|
||||||
|
* matches here so the caller can build them as additional entry
|
||||||
|
* points.
|
||||||
|
*/
|
||||||
|
collectWorkers?: WorkerMatch[];
|
||||||
|
/**
|
||||||
|
* When provided, the fs plugin will scan source files for
|
||||||
|
* `new URL(..., import.meta.url)` patterns referencing non-source
|
||||||
|
* assets and push matches here so the caller can copy them into
|
||||||
|
* the output.
|
||||||
|
*/
|
||||||
|
collectAssets?: AssetMatch[];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create the common esbuild plugins for both project and worker builds
|
* Create the common esbuild plugins for both project and worker builds
|
||||||
* Exported for use by deployment adapters that need to bundle workers
|
* Exported for use by deployment adapters that need to bundle workers
|
||||||
@@ -122,10 +140,18 @@ export function createPlugins(
|
|||||||
context: BuildContext,
|
context: BuildContext,
|
||||||
esmUrl: string,
|
esmUrl: string,
|
||||||
target?: string,
|
target?: string,
|
||||||
|
pluginOptions: CreatePluginsOptions = {},
|
||||||
): Plugin[] {
|
): Plugin[] {
|
||||||
return [
|
return [
|
||||||
shakespearePlugin({ esmUrl }),
|
shakespearePlugin({ esmUrl }),
|
||||||
fsPlugin({ fs, cwd: projectPath, tsconfig: context.tsconfig, packageJson: context.packageJson }),
|
fsPlugin({
|
||||||
|
fs,
|
||||||
|
cwd: projectPath,
|
||||||
|
tsconfig: context.tsconfig,
|
||||||
|
packageJson: context.packageJson,
|
||||||
|
collectWorkers: pluginOptions.collectWorkers,
|
||||||
|
collectAssets: pluginOptions.collectAssets,
|
||||||
|
}),
|
||||||
esmPlugin({ packageJson: context.packageJson, packageLock: context.packageLock, target, esmUrl }),
|
esmPlugin({ packageJson: context.packageJson, packageLock: context.packageLock, target, esmUrl }),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -175,6 +201,9 @@ async function bundle(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const collectedWorkers: WorkerMatch[] = [];
|
||||||
|
const collectedAssets: AssetMatch[] = [];
|
||||||
|
|
||||||
const results = await esbuild.build({
|
const results = await esbuild.build({
|
||||||
entryPoints,
|
entryPoints,
|
||||||
bundle: true,
|
bundle: true,
|
||||||
@@ -188,7 +217,10 @@ async function bundle(
|
|||||||
entryNames: "[name]-[hash]",
|
entryNames: "[name]-[hash]",
|
||||||
chunkNames: "[name]-[hash]",
|
chunkNames: "[name]-[hash]",
|
||||||
assetNames: "[name]-[hash]",
|
assetNames: "[name]-[hash]",
|
||||||
plugins: createPlugins(fs, projectPath, context, esmUrl, target),
|
plugins: createPlugins(fs, projectPath, context, esmUrl, target, {
|
||||||
|
collectWorkers: collectedWorkers,
|
||||||
|
collectAssets: collectedAssets,
|
||||||
|
}),
|
||||||
define: {
|
define: {
|
||||||
"import.meta.env": JSON.stringify({}),
|
"import.meta.env": JSON.stringify({}),
|
||||||
},
|
},
|
||||||
@@ -222,12 +254,140 @@ async function bundle(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse CSP and ensure ESM CDN is allowed for necessary directives
|
// Build each unique collected worker as its own ESM chunk, looping
|
||||||
|
// to pick up any nested workers / assets they themselves collect.
|
||||||
|
// Each iteration passes the same collector arrays so newly
|
||||||
|
// discovered entries feed the next iteration.
|
||||||
|
const placeholderToFilename = new Map<string, string>();
|
||||||
|
const workerQueue: WorkerMatch[] = [...collectedWorkers];
|
||||||
|
const seenWorkerPaths = new Set<string>();
|
||||||
|
|
||||||
|
while (workerQueue.length > 0) {
|
||||||
|
const nextBatch = workerQueue.splice(0, workerQueue.length);
|
||||||
|
for (const worker of nextBatch) {
|
||||||
|
if (seenWorkerPaths.has(worker.resolvedPath)) {
|
||||||
|
// Reuse the output from the prior build of this same worker.
|
||||||
|
const existing = findPlaceholderForPath(placeholderToFilename, worker.resolvedPath);
|
||||||
|
if (existing) {
|
||||||
|
placeholderToFilename.set(worker.placeholder, existing);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seenWorkerPaths.add(worker.resolvedPath);
|
||||||
|
|
||||||
|
const before = {
|
||||||
|
workers: collectedWorkers.length,
|
||||||
|
assets: collectedAssets.length,
|
||||||
|
};
|
||||||
|
|
||||||
|
const workerResult = await esbuild.build({
|
||||||
|
entryPoints: [worker.resolvedPath],
|
||||||
|
bundle: true,
|
||||||
|
write: false,
|
||||||
|
format: "esm",
|
||||||
|
target,
|
||||||
|
outdir: "/",
|
||||||
|
jsx: "automatic",
|
||||||
|
metafile: true,
|
||||||
|
sourcemap: true,
|
||||||
|
entryNames: "[name]-[hash]",
|
||||||
|
chunkNames: "[name]-[hash]",
|
||||||
|
assetNames: "[name]-[hash]",
|
||||||
|
plugins: createPlugins(fs, projectPath, context, esmUrl, target, {
|
||||||
|
collectWorkers: collectedWorkers,
|
||||||
|
collectAssets: collectedAssets,
|
||||||
|
}),
|
||||||
|
define: {
|
||||||
|
"import.meta.env": JSON.stringify({}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
let entryFilename: string | undefined;
|
||||||
|
for (const file of workerResult.outputFiles) {
|
||||||
|
const filename = file.path.slice(1);
|
||||||
|
dist[filename] = file.contents;
|
||||||
|
const outMeta = workerResult.metafile.outputs[filename];
|
||||||
|
if (outMeta?.entryPoint && !entryFilename && filename.endsWith(".js")) {
|
||||||
|
entryFilename = filename;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!entryFilename) {
|
||||||
|
// Fall back to the first .js output.
|
||||||
|
const firstJs = workerResult.outputFiles.find((f) => f.path.endsWith(".js"));
|
||||||
|
if (firstJs) entryFilename = firstJs.path.slice(1);
|
||||||
|
}
|
||||||
|
if (!entryFilename) {
|
||||||
|
throw new Error(`Failed to bundle worker: ${worker.resolvedPath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record placeholder -> "./<filename>" so main-bundle rewrites
|
||||||
|
// produce URLs that resolve correctly against import.meta.url
|
||||||
|
// of the main bundle (which lives at the same origin/dir).
|
||||||
|
placeholderToFilename.set(worker.placeholder, "./" + entryFilename);
|
||||||
|
// Record the file path -> filename mapping in a secondary index
|
||||||
|
// via the placeholder (so the dedup branch above can find it).
|
||||||
|
placeholderToFilename.set(`@path:${worker.resolvedPath}`, entryFilename);
|
||||||
|
|
||||||
|
// New workers / assets discovered during this sub-build get
|
||||||
|
// queued.
|
||||||
|
if (collectedWorkers.length > before.workers) {
|
||||||
|
workerQueue.push(...collectedWorkers.slice(before.workers));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy each unique collected asset into the output directory with
|
||||||
|
// a content-hashed filename.
|
||||||
|
const assetPathToFilename = new Map<string, string>();
|
||||||
|
for (const asset of collectedAssets) {
|
||||||
|
let outName = assetPathToFilename.get(asset.resolvedPath);
|
||||||
|
if (!outName) {
|
||||||
|
const bytes = await fs.readFile(asset.resolvedPath);
|
||||||
|
const data = bytes instanceof Uint8Array ? bytes : new TextEncoder().encode(String(bytes));
|
||||||
|
const hash = await shortContentHash(data);
|
||||||
|
const base = asset.resolvedPath.split("/").pop() ?? "asset";
|
||||||
|
const dot = base.lastIndexOf(".");
|
||||||
|
const stem = dot > 0 ? base.slice(0, dot) : base;
|
||||||
|
const ext = dot > 0 ? base.slice(dot) : "";
|
||||||
|
outName = `${stem}-${hash}${ext}`;
|
||||||
|
dist[outName] = data;
|
||||||
|
assetPathToFilename.set(asset.resolvedPath, outName);
|
||||||
|
}
|
||||||
|
placeholderToFilename.set(asset.placeholder, "./" + outName);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Substitute placeholders in every JS output file.
|
||||||
|
if (placeholderToFilename.size > 0) {
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
for (const [filename, contents] of Object.entries(dist)) {
|
||||||
|
if (!filename.endsWith(".js")) continue;
|
||||||
|
let text = decoder.decode(contents);
|
||||||
|
let changed = false;
|
||||||
|
for (const [placeholder, replacement] of placeholderToFilename) {
|
||||||
|
if (placeholder.startsWith("@path:")) continue;
|
||||||
|
if (text.includes(placeholder)) {
|
||||||
|
text = text.split(placeholder).join(replacement.startsWith("./") ? replacement.slice(2) : replacement);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
dist[filename] = encoder.encode(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse CSP and ensure ESM CDN is allowed for necessary directives.
|
||||||
|
// If any workers were emitted, also extend worker-src / child-src so
|
||||||
|
// the browser permits module workers and workers importing from the
|
||||||
|
// ESM CDN.
|
||||||
const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]");
|
const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]");
|
||||||
if (cspMeta) {
|
if (cspMeta) {
|
||||||
const cspContent = cspMeta.getAttribute("content");
|
const cspContent = cspMeta.getAttribute("content");
|
||||||
if (cspContent) {
|
if (cspContent) {
|
||||||
const updatedCSP = updateCSPForEsmSh(cspContent, esmUrl);
|
const updatedCSP = updateCSPForEsmSh(cspContent, esmUrl, {
|
||||||
|
emittedWorkers: collectedWorkers.length > 0,
|
||||||
|
});
|
||||||
cspMeta.setAttribute("content", updatedCSP);
|
cspMeta.setAttribute("content", updatedCSP);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -238,6 +398,42 @@ async function bundle(
|
|||||||
return dist;
|
return dist;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function findPlaceholderForPath(
|
||||||
|
placeholderToFilename: Map<string, string>,
|
||||||
|
resolvedPath: string,
|
||||||
|
): string | undefined {
|
||||||
|
const key = `@path:${resolvedPath}`;
|
||||||
|
const filename = placeholderToFilename.get(key);
|
||||||
|
return filename ? "./" + filename : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function shortContentHash(data: Uint8Array): Promise<string> {
|
||||||
|
// Use SubtleCrypto if available (browsers, modern Node via webcrypto
|
||||||
|
// global); fall back to a simple non-cryptographic hash for test
|
||||||
|
// environments that stub out crypto.
|
||||||
|
try {
|
||||||
|
const subtle = (globalThis as { crypto?: { subtle?: SubtleCrypto } }).crypto?.subtle;
|
||||||
|
if (subtle?.digest) {
|
||||||
|
const buf = await subtle.digest("SHA-256", data);
|
||||||
|
const bytes = new Uint8Array(buf);
|
||||||
|
let hex = "";
|
||||||
|
for (let i = 0; i < 8; i++) {
|
||||||
|
hex += bytes[i].toString(16).padStart(2, "0");
|
||||||
|
}
|
||||||
|
return hex;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// fall through
|
||||||
|
}
|
||||||
|
// FNV-1a-ish fallback (good enough for filename uniqueness).
|
||||||
|
let h = 0x811c9dc5;
|
||||||
|
for (let i = 0; i < data.length; i++) {
|
||||||
|
h ^= data[i];
|
||||||
|
h = Math.imul(h, 0x01000193);
|
||||||
|
}
|
||||||
|
return (h >>> 0).toString(16).padStart(8, "0");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build project and write output files to the filesystem
|
* Build project and write output files to the filesystem
|
||||||
*/
|
*/
|
||||||
@@ -328,15 +524,42 @@ async function fileExists(fs: JSRuntimeFS, path: string): Promise<boolean> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Updates CSP to allow ESM CDN for scripts, assets, fonts, and CSS */
|
/** Updates CSP to allow ESM CDN for scripts, assets, fonts, and CSS */
|
||||||
export function updateCSPForEsmSh(csp: string, esmUrl: string): string {
|
export function updateCSPForEsmSh(
|
||||||
|
csp: string,
|
||||||
|
esmUrl: string,
|
||||||
|
options: { emittedWorkers?: boolean } = {},
|
||||||
|
): string {
|
||||||
const esmDirectives = [
|
const esmDirectives = [
|
||||||
'script-src', // For JavaScript modules
|
'script-src', // For JavaScript modules
|
||||||
'img-src', // For images
|
'img-src', // For images
|
||||||
'media-src', // For video/audio
|
'media-src', // For video/audio
|
||||||
'font-src', // For fonts
|
'font-src', // For fonts
|
||||||
'style-src', // For CSS
|
'style-src', // For CSS
|
||||||
'connect-src' // For fetch/XHR requests to ESM CDN
|
'connect-src', // For fetch/XHR requests to ESM CDN
|
||||||
];
|
];
|
||||||
|
|
||||||
return addDomainToCSP(csp, esmUrl, esmDirectives);
|
let updated = addDomainToCSP(csp, esmUrl, esmDirectives);
|
||||||
|
|
||||||
|
if (options.emittedWorkers) {
|
||||||
|
// Module workers load from the same origin; when they import from
|
||||||
|
// the ESM CDN, worker-src (and child-src for older browsers) must
|
||||||
|
// list the CDN as well. These directives may not exist in the
|
||||||
|
// project's CSP, so seed them before extending.
|
||||||
|
updated = ensureDirective(updated, 'worker-src');
|
||||||
|
updated = ensureDirective(updated, 'child-src');
|
||||||
|
updated = addDomainToCSP(updated, esmUrl, ['worker-src', 'child-src']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure a CSP directive exists. If absent, seed it with `'self'` so
|
||||||
|
* subsequent `addDomainToCSP` calls have something to extend.
|
||||||
|
*/
|
||||||
|
function ensureDirective(csp: string, directive: string): string {
|
||||||
|
const re = new RegExp(`(^|;)\\s*${directive}\\s`);
|
||||||
|
if (re.test(csp)) return csp;
|
||||||
|
const trimmed = csp.trim().replace(/;\s*$/, '');
|
||||||
|
return trimmed ? `${trimmed}; ${directive} 'self'` : `${directive} 'self'`;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
import { describe, it, expect, vi } from "vitest";
|
||||||
|
|
||||||
|
// Mock getEsbuild so we can unit-test detection without the real wasm.
|
||||||
|
// The mock's transform is loader-aware: for "ts"/"tsx"/"jsx" it strips
|
||||||
|
// obvious TS/JSX constructs enough for acorn to parse. In practice, if
|
||||||
|
// the input is already valid JS, we just pass it through.
|
||||||
|
vi.mock("@/lib/esbuild", () => ({
|
||||||
|
getEsbuild: vi.fn(async () => ({
|
||||||
|
transform: vi.fn(async (source: string) => ({ code: source })),
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { detectWorkersAndAssets } from "./workerPlugin";
|
||||||
|
|
||||||
|
const identityResolver = async (spec: string, importer: string): Promise<string | undefined> => {
|
||||||
|
// A trivial resolver that pretends any relative/@ spec resolves to
|
||||||
|
// an absolute path. Extension determines whether it's a source file.
|
||||||
|
if (spec.startsWith("./") || spec.startsWith("../")) {
|
||||||
|
// Pretend to resolve by dropping the leading segment.
|
||||||
|
return importer.replace(/[^/]+$/, "") + spec.replace(/^\.\/?/, "");
|
||||||
|
}
|
||||||
|
if (spec.startsWith("@/")) {
|
||||||
|
return "/project/src/" + spec.slice(2);
|
||||||
|
}
|
||||||
|
if (spec.startsWith("/")) {
|
||||||
|
return spec;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("detectWorkersAndAssets", () => {
|
||||||
|
it("returns source unchanged when file contains no `new URL(`", async () => {
|
||||||
|
const source = `
|
||||||
|
import React from 'react';
|
||||||
|
export const x = 1;
|
||||||
|
`;
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
});
|
||||||
|
expect(result.code).toBe(source);
|
||||||
|
expect(result.workers).toEqual([]);
|
||||||
|
expect(result.assets).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("detects a module Worker with @/ alias specifier", async () => {
|
||||||
|
const source = [
|
||||||
|
"const w = new Worker(",
|
||||||
|
" new URL('@/workers/my-worker.ts', import.meta.url),",
|
||||||
|
" { type: 'module' },",
|
||||||
|
");",
|
||||||
|
].join("\n");
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
});
|
||||||
|
expect(result.workers).toHaveLength(1);
|
||||||
|
expect(result.workers[0].resolvedPath).toBe("/project/src/workers/my-worker.ts");
|
||||||
|
expect(result.workers[0].kind).toBe("Worker");
|
||||||
|
// Placeholder should appear in the rewritten code.
|
||||||
|
expect(result.code).toContain(result.workers[0].placeholder);
|
||||||
|
// Original spec string should be gone.
|
||||||
|
expect(result.code).not.toContain("@/workers/my-worker.ts");
|
||||||
|
// import.meta.url reference should be preserved.
|
||||||
|
expect(result.code).toContain("import.meta.url");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("detects a SharedWorker", async () => {
|
||||||
|
const source = `
|
||||||
|
const w = new SharedWorker(
|
||||||
|
new URL('./w.ts', import.meta.url),
|
||||||
|
{ type: 'module' },
|
||||||
|
);
|
||||||
|
`;
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
});
|
||||||
|
expect(result.workers).toHaveLength(1);
|
||||||
|
expect(result.workers[0].kind).toBe("SharedWorker");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("errors on classic (non-module) worker", async () => {
|
||||||
|
const source = `
|
||||||
|
const w = new Worker(new URL('./w.ts', import.meta.url));
|
||||||
|
`;
|
||||||
|
await expect(
|
||||||
|
detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(/type: 'module'/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("errors on non-literal worker specifier", async () => {
|
||||||
|
const source = `
|
||||||
|
const p = './dyn.ts';
|
||||||
|
const w = new Worker(new URL(p, import.meta.url), { type: 'module' });
|
||||||
|
`;
|
||||||
|
await expect(
|
||||||
|
detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(/string literal/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("errors when worker specifier does not resolve", async () => {
|
||||||
|
const source = `
|
||||||
|
const w = new Worker(new URL('./missing.ts', import.meta.url), { type: 'module' });
|
||||||
|
`;
|
||||||
|
await expect(
|
||||||
|
detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: async () => undefined,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(/could not resolve worker module/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("detects plain new URL() asset and rewrites it", async () => {
|
||||||
|
const source = `
|
||||||
|
const u = new URL('./logo.svg', import.meta.url);
|
||||||
|
console.log(u);
|
||||||
|
`;
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
});
|
||||||
|
expect(result.assets).toHaveLength(1);
|
||||||
|
expect(result.assets[0].resolvedPath).toBe("/project/src/logo.svg");
|
||||||
|
expect(result.code).toContain(result.assets[0].placeholder);
|
||||||
|
expect(result.code).not.toContain("./logo.svg");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not rewrite plain new URL() when target is a source file", async () => {
|
||||||
|
const source = `
|
||||||
|
const u = new URL('./thing.ts', import.meta.url);
|
||||||
|
`;
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
});
|
||||||
|
expect(result.assets).toEqual([]);
|
||||||
|
expect(result.code).toBe(source);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not rewrite new URL() with a non-literal first argument", async () => {
|
||||||
|
const source = `
|
||||||
|
const p = './thing.svg';
|
||||||
|
const u = new URL(p, import.meta.url);
|
||||||
|
`;
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
});
|
||||||
|
expect(result.assets).toEqual([]);
|
||||||
|
expect(result.workers).toEqual([]);
|
||||||
|
expect(result.code).toBe(source);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not rewrite new URL() with an absolute https:// spec", async () => {
|
||||||
|
const source = `
|
||||||
|
const u = new URL('https://example.com/x.png', import.meta.url);
|
||||||
|
`;
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
});
|
||||||
|
expect(result.assets).toEqual([]);
|
||||||
|
expect(result.code).toBe(source);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not double-rewrite the inner new URL() of a Worker", async () => {
|
||||||
|
const source = `
|
||||||
|
const w = new Worker(new URL('./w.ts', import.meta.url), { type: 'module' });
|
||||||
|
`;
|
||||||
|
// Resolver returns a non-source extension for './w.ts' would
|
||||||
|
// otherwise ambiguously pull the inner URL into the asset pass.
|
||||||
|
// Using ts extension makes it unambiguous: worker match only.
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
});
|
||||||
|
expect(result.workers).toHaveLength(1);
|
||||||
|
expect(result.assets).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("handles both workers and assets in the same file", async () => {
|
||||||
|
const source = `
|
||||||
|
const img = new URL('./logo.png', import.meta.url);
|
||||||
|
const w = new Worker(new URL('./w.ts', import.meta.url), { type: 'module' });
|
||||||
|
`;
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
});
|
||||||
|
expect(result.workers).toHaveLength(1);
|
||||||
|
expect(result.assets).toHaveLength(1);
|
||||||
|
expect(result.assets[0].resolvedPath).toBe("/project/src/logo.png");
|
||||||
|
expect(result.workers[0].resolvedPath).toBe("/project/src/w.ts");
|
||||||
|
// Both placeholders present.
|
||||||
|
expect(result.code).toContain(result.workers[0].placeholder);
|
||||||
|
expect(result.code).toContain(result.assets[0].placeholder);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not match patterns inside string literals", async () => {
|
||||||
|
const source = [
|
||||||
|
"const s = \"new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })\";",
|
||||||
|
].join("\n");
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
});
|
||||||
|
expect(result.workers).toEqual([]);
|
||||||
|
expect(result.assets).toEqual([]);
|
||||||
|
expect(result.code).toBe(source);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not match patterns inside line comments", async () => {
|
||||||
|
const source = [
|
||||||
|
"// const w = new Worker(new URL('./w.ts', import.meta.url), { type: 'module' });",
|
||||||
|
"export const x = 1;",
|
||||||
|
].join("\n");
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
});
|
||||||
|
expect(result.workers).toEqual([]);
|
||||||
|
expect(result.code).toBe(source);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("supports double-quoted specifiers", async () => {
|
||||||
|
const source = `
|
||||||
|
const w = new Worker(new URL("./w.ts", import.meta.url), { type: "module" });
|
||||||
|
`;
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
});
|
||||||
|
expect(result.workers).toHaveLength(1);
|
||||||
|
expect(result.code).toContain(result.workers[0].placeholder);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("supports backtick-quoted specifiers with no interpolation", async () => {
|
||||||
|
const source = [
|
||||||
|
"const w = new Worker(new URL(`./w.ts`, import.meta.url), { type: 'module' });",
|
||||||
|
].join("\n");
|
||||||
|
const result = await detectWorkersAndAssets({
|
||||||
|
source,
|
||||||
|
filePath: "/project/src/a.ts",
|
||||||
|
ext: "ts",
|
||||||
|
resolveSpec: identityResolver,
|
||||||
|
});
|
||||||
|
expect(result.workers).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,438 @@
|
|||||||
|
// Detection and rewriting for the Vite/webpack-compatible worker and
|
||||||
|
// asset URL patterns:
|
||||||
|
//
|
||||||
|
// new Worker(new URL("<spec>", import.meta.url), { type: "module" })
|
||||||
|
// new SharedWorker(new URL("<spec>", import.meta.url), { type: "module" })
|
||||||
|
// new URL("<spec>", import.meta.url) // for non-source assets
|
||||||
|
//
|
||||||
|
// esbuild-wasm exposes no onTransform/onParse hook, so we can't reuse
|
||||||
|
// esbuild's internal AST. To avoid parsing every source file a second
|
||||||
|
// time, we prefilter with a cheap regex and only invoke acorn on files
|
||||||
|
// that contain a relevant construct. TS/JSX files are stripped via
|
||||||
|
// esbuild.transform before being handed to acorn so we don't need a
|
||||||
|
// TypeScript-aware parser.
|
||||||
|
|
||||||
|
import * as acorn from "acorn";
|
||||||
|
import jsx from "acorn-jsx";
|
||||||
|
import { getEsbuild } from "@/lib/esbuild";
|
||||||
|
|
||||||
|
const ParserWithJsx = acorn.Parser.extend(jsx());
|
||||||
|
|
||||||
|
// Cheap prefilter: bail out for the 99% of files that contain no
|
||||||
|
// `new URL(` call at all.
|
||||||
|
const PREFILTER = /\bnew\s+URL\s*\(/;
|
||||||
|
|
||||||
|
export interface WorkerMatch {
|
||||||
|
/** Unique placeholder token written into the source in place of the spec string. */
|
||||||
|
placeholder: string;
|
||||||
|
/** Resolved absolute path of the worker entry in the VFS. */
|
||||||
|
resolvedPath: string;
|
||||||
|
/** "Worker" or "SharedWorker". */
|
||||||
|
kind: "Worker" | "SharedWorker";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AssetMatch {
|
||||||
|
/** Unique placeholder token written into the source in place of the spec string. */
|
||||||
|
placeholder: string;
|
||||||
|
/** Resolved absolute path of the asset in the VFS. */
|
||||||
|
resolvedPath: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DetectResult {
|
||||||
|
/** The (possibly) rewritten source text. */
|
||||||
|
code: string;
|
||||||
|
workers: WorkerMatch[];
|
||||||
|
assets: AssetMatch[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DetectOptions {
|
||||||
|
/** The original source text as stored in the VFS. */
|
||||||
|
source: string;
|
||||||
|
/** The path of the file being processed, for diagnostics. */
|
||||||
|
filePath: string;
|
||||||
|
/** Extension of the source ("ts", "tsx", "js", "jsx", "mjs", "cjs"). */
|
||||||
|
ext: string;
|
||||||
|
/**
|
||||||
|
* Resolve a module specifier relative to `filePath` against the VFS.
|
||||||
|
* Returns the resolved absolute path, or undefined if no file exists.
|
||||||
|
*/
|
||||||
|
resolveSpec: (spec: string, importerPath: string) => Promise<string | undefined>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Source-code extensions that must NOT be treated as plain asset URLs.
|
||||||
|
* These should go through a regular import or the Worker pattern.
|
||||||
|
*/
|
||||||
|
const SOURCE_EXTENSIONS = new Set([
|
||||||
|
"ts",
|
||||||
|
"tsx",
|
||||||
|
"js",
|
||||||
|
"jsx",
|
||||||
|
"mjs",
|
||||||
|
"cjs",
|
||||||
|
"css",
|
||||||
|
]);
|
||||||
|
|
||||||
|
let placeholderCounter = 0;
|
||||||
|
function nextPlaceholder(prefix: "WORKER" | "ASSET"): string {
|
||||||
|
placeholderCounter += 1;
|
||||||
|
return `__SHAKESPEARE_${prefix}_URL_${placeholderCounter.toString(36)}__`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scan a source file for Worker / SharedWorker / asset URL patterns.
|
||||||
|
* Returns the rewritten source along with the collected matches.
|
||||||
|
*
|
||||||
|
* Throws with a human-readable message when a problem is found that
|
||||||
|
* should fail the build (classic worker, non-literal specifier,
|
||||||
|
* unresolvable specifier).
|
||||||
|
*/
|
||||||
|
export async function detectWorkersAndAssets(
|
||||||
|
options: DetectOptions,
|
||||||
|
): Promise<DetectResult> {
|
||||||
|
const { source, filePath, ext, resolveSpec } = options;
|
||||||
|
|
||||||
|
// Fast path: no `new URL(` anywhere.
|
||||||
|
if (!PREFILTER.test(source)) {
|
||||||
|
return { code: source, workers: [], assets: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strip TS/JSX so acorn can parse it. We only reach this branch for
|
||||||
|
// files that contain `new URL(`, which is rare, so the transform
|
||||||
|
// cost is paid for very few files per build.
|
||||||
|
let jsSource = source;
|
||||||
|
const needsStrip = ext === "ts" || ext === "tsx" || ext === "jsx";
|
||||||
|
if (needsStrip) {
|
||||||
|
try {
|
||||||
|
const esbuild = await getEsbuild();
|
||||||
|
const result = await esbuild.transform(source, {
|
||||||
|
loader: ext === "ts" ? "ts" : ext === "tsx" ? "tsx" : "jsx",
|
||||||
|
sourcemap: false,
|
||||||
|
sourcefile: filePath,
|
||||||
|
// Preserve the shape of the source as much as possible; we're
|
||||||
|
// only using the output to parse, not to emit.
|
||||||
|
target: "esnext",
|
||||||
|
});
|
||||||
|
jsSource = result.code;
|
||||||
|
} catch {
|
||||||
|
// If the transform itself fails, skip worker detection; esbuild's
|
||||||
|
// main pass will surface the syntax error with a proper location.
|
||||||
|
return { code: source, workers: [], assets: [] };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse.
|
||||||
|
let ast: acorn.Node;
|
||||||
|
try {
|
||||||
|
ast = ParserWithJsx.parse(jsSource, {
|
||||||
|
ecmaVersion: "latest",
|
||||||
|
sourceType: "module",
|
||||||
|
allowHashBang: true,
|
||||||
|
allowAwaitOutsideFunction: true,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// If acorn can't parse (possibly because of syntax esbuild supports
|
||||||
|
// that acorn doesn't), skip detection and let the main build
|
||||||
|
// surface any real error.
|
||||||
|
return { code: source, workers: [], assets: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Walk the AST to find NewExpression nodes we care about.
|
||||||
|
// We operate on the stripped jsSource for position information, but
|
||||||
|
// the returned `code` must be the ORIGINAL source with rewrites
|
||||||
|
// applied. Since replacements are string-literal values (the first
|
||||||
|
// argument of `new URL`), we search for those literals in the
|
||||||
|
// original source to do the rewrite. This avoids any dependence on
|
||||||
|
// post-TS-strip positions.
|
||||||
|
const workers: WorkerMatch[] = [];
|
||||||
|
const assets: AssetMatch[] = [];
|
||||||
|
// Map spec -> list of { kind: "worker" | "asset", placeholder, resolvedPath }
|
||||||
|
// collected during the AST walk. We rewrite afterwards so that each
|
||||||
|
// *occurrence* of the spec in the original source that parses back
|
||||||
|
// to the same construct gets its own placeholder.
|
||||||
|
interface PendingRewrite {
|
||||||
|
spec: string;
|
||||||
|
kind: "worker" | "asset";
|
||||||
|
workerKind?: "Worker" | "SharedWorker";
|
||||||
|
resolvedPath: string;
|
||||||
|
}
|
||||||
|
const pending: PendingRewrite[] = [];
|
||||||
|
|
||||||
|
const seenUrlNodes = new WeakSet<acorn.Node>();
|
||||||
|
|
||||||
|
const walk = async (node: acorn.Node | null | undefined): Promise<void> => {
|
||||||
|
if (!node || typeof node !== "object") return;
|
||||||
|
// Process this node first (so Worker sees its inner new URL before
|
||||||
|
// the asset pass does).
|
||||||
|
await visit(node);
|
||||||
|
// Recurse into all child nodes.
|
||||||
|
for (const key of Object.keys(node)) {
|
||||||
|
if (key === "type" || key === "start" || key === "end" || key === "loc") continue;
|
||||||
|
const value = (node as unknown as Record<string, unknown>)[key];
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
for (const child of value) {
|
||||||
|
if (child && typeof child === "object" && "type" in child) {
|
||||||
|
await walk(child as acorn.Node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (value && typeof value === "object" && "type" in value) {
|
||||||
|
await walk(value as acorn.Node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const visit = async (node: acorn.Node): Promise<void> => {
|
||||||
|
if (node.type !== "NewExpression") return;
|
||||||
|
const newExpr = node as unknown as {
|
||||||
|
type: "NewExpression";
|
||||||
|
callee: { type: string; name?: string };
|
||||||
|
arguments: acorn.Node[];
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
};
|
||||||
|
const calleeName =
|
||||||
|
newExpr.callee.type === "Identifier" ? newExpr.callee.name : undefined;
|
||||||
|
|
||||||
|
if (calleeName === "Worker" || calleeName === "SharedWorker") {
|
||||||
|
// new Worker(new URL(<spec>, import.meta.url), <opts>?)
|
||||||
|
const [arg0, arg1] = newExpr.arguments;
|
||||||
|
if (!isNewUrlWithImportMeta(arg0)) {
|
||||||
|
// Not the Vite pattern — leave alone.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const urlNode = arg0 as unknown as {
|
||||||
|
type: "NewExpression";
|
||||||
|
arguments: acorn.Node[];
|
||||||
|
};
|
||||||
|
const specNode = urlNode.arguments[0];
|
||||||
|
if (!isStringLiteral(specNode)) {
|
||||||
|
throw new Error(
|
||||||
|
`${filePath}: new ${calleeName}(new URL(...)) requires a string literal as the first argument to new URL(). Dynamic specifiers are not supported.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Require { type: 'module' } as the second argument.
|
||||||
|
if (!hasTypeModuleOption(arg1)) {
|
||||||
|
throw new Error(
|
||||||
|
`${filePath}: new ${calleeName}(new URL(...)) must pass { type: 'module' } as its second argument. Shakespeare does not support classic workers.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const spec = readStringLiteral(specNode)!;
|
||||||
|
const resolvedPath = await resolveSpec(spec, filePath);
|
||||||
|
if (!resolvedPath) {
|
||||||
|
throw new Error(
|
||||||
|
`${filePath}: could not resolve worker module '${spec}'.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Mark the inner `new URL(...)` as "consumed" so the asset pass
|
||||||
|
// below doesn't also rewrite it.
|
||||||
|
seenUrlNodes.add(arg0);
|
||||||
|
pending.push({
|
||||||
|
spec,
|
||||||
|
kind: "worker",
|
||||||
|
workerKind: calleeName,
|
||||||
|
resolvedPath,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (calleeName === "URL") {
|
||||||
|
if (seenUrlNodes.has(node)) return;
|
||||||
|
if (!isNewUrlWithImportMeta(node)) return;
|
||||||
|
const specNode = newExpr.arguments[0];
|
||||||
|
if (!isStringLiteral(specNode)) {
|
||||||
|
// Non-literal `new URL(...)` is legal and common for runtime
|
||||||
|
// URL construction. Don't touch it.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const spec = readStringLiteral(specNode)!;
|
||||||
|
// Only rewrite specs that look like module-relative paths.
|
||||||
|
// Anything else (absolute https://, etc.) is almost certainly a
|
||||||
|
// runtime URL and not a bundle asset reference.
|
||||||
|
if (!isRelativeOrAliasSpec(spec)) return;
|
||||||
|
const resolvedPath = await resolveSpec(spec, filePath);
|
||||||
|
if (!resolvedPath) {
|
||||||
|
// Can't resolve — probably a runtime URL; leave alone.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Skip source files — these should go through normal imports or
|
||||||
|
// the Worker pattern.
|
||||||
|
const resolvedExt = resolvedPath.split(".").pop()?.toLowerCase() ?? "";
|
||||||
|
if (SOURCE_EXTENSIONS.has(resolvedExt)) {
|
||||||
|
// Emit a console warning but don't fail the build.
|
||||||
|
console.warn(
|
||||||
|
`${filePath}: new URL('${spec}', import.meta.url) references a source file. Shakespeare only rewrites non-source assets via this pattern. Use a regular import or new Worker() instead.`,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pending.push({ spec, kind: "asset", resolvedPath });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
await walk(ast);
|
||||||
|
|
||||||
|
if (pending.length === 0) {
|
||||||
|
return { code: source, workers: [], assets: [] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now apply the rewrites to the ORIGINAL source by replacing the
|
||||||
|
// string-literal spec. Each `pending` entry consumes the first
|
||||||
|
// remaining occurrence of its literal form so multiple identical
|
||||||
|
// specs each get their own placeholder.
|
||||||
|
//
|
||||||
|
// Match a quoted literal whose content equals `spec`. We match
|
||||||
|
// single quotes, double quotes, or backticks (template literal
|
||||||
|
// without interpolation) to cover all reasonable TS/JS source
|
||||||
|
// styles.
|
||||||
|
let code = source;
|
||||||
|
for (const entry of pending) {
|
||||||
|
const placeholder = nextPlaceholder(entry.kind === "worker" ? "WORKER" : "ASSET");
|
||||||
|
const { literal, index } = findNextSpecLiteral(code, entry.spec);
|
||||||
|
if (literal === null || index < 0) {
|
||||||
|
// Shouldn't normally happen (we parsed it); be defensive.
|
||||||
|
throw new Error(
|
||||||
|
`${filePath}: internal error rewriting new URL('${entry.spec}', ...); could not locate the literal in source.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const before = code.slice(0, index);
|
||||||
|
const after = code.slice(index + literal.length);
|
||||||
|
// Preserve the quote style of the original literal.
|
||||||
|
const quote = literal[0];
|
||||||
|
code = before + quote + placeholder + quote + after;
|
||||||
|
|
||||||
|
if (entry.kind === "worker") {
|
||||||
|
workers.push({
|
||||||
|
placeholder,
|
||||||
|
resolvedPath: entry.resolvedPath,
|
||||||
|
kind: entry.workerKind!,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
assets.push({ placeholder, resolvedPath: entry.resolvedPath });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { code, workers, assets };
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNewUrlWithImportMeta(node: acorn.Node | null | undefined): boolean {
|
||||||
|
if (!node || node.type !== "NewExpression") return false;
|
||||||
|
const n = node as unknown as {
|
||||||
|
callee: { type: string; name?: string };
|
||||||
|
arguments: acorn.Node[];
|
||||||
|
};
|
||||||
|
if (n.callee.type !== "Identifier" || n.callee.name !== "URL") return false;
|
||||||
|
if (n.arguments.length < 2) return false;
|
||||||
|
return isImportMetaUrl(n.arguments[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isImportMetaUrl(node: acorn.Node | undefined): boolean {
|
||||||
|
if (!node || node.type !== "MemberExpression") return false;
|
||||||
|
const m = node as unknown as {
|
||||||
|
object: { type: string; meta?: { name?: string }; property?: { name?: string } };
|
||||||
|
property: { type: string; name?: string };
|
||||||
|
computed: boolean;
|
||||||
|
};
|
||||||
|
if (m.computed) return false;
|
||||||
|
if (m.property.type !== "Identifier" || m.property.name !== "url") return false;
|
||||||
|
if (m.object.type !== "MetaProperty") return false;
|
||||||
|
if (m.object.meta?.name !== "import") return false;
|
||||||
|
if (m.object.property?.name !== "meta") return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isStringLiteral(node: acorn.Node | undefined): boolean {
|
||||||
|
return readStringLiteral(node) !== undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readStringLiteral(node: acorn.Node | undefined): string | undefined {
|
||||||
|
if (!node) return undefined;
|
||||||
|
if (node.type === "Literal") {
|
||||||
|
const v = (node as unknown as { value: unknown }).value;
|
||||||
|
return typeof v === "string" ? v : undefined;
|
||||||
|
}
|
||||||
|
if (node.type === "TemplateLiteral") {
|
||||||
|
const tl = node as unknown as {
|
||||||
|
expressions: unknown[];
|
||||||
|
quasis: Array<{ value: { cooked?: string } }>;
|
||||||
|
};
|
||||||
|
if (tl.expressions.length === 0 && tl.quasis.length === 1 &&
|
||||||
|
typeof tl.quasis[0].value.cooked === "string") {
|
||||||
|
return tl.quasis[0].value.cooked;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasTypeModuleOption(node: acorn.Node | undefined): boolean {
|
||||||
|
if (!node || node.type !== "ObjectExpression") return false;
|
||||||
|
const obj = node as unknown as {
|
||||||
|
properties: Array<{
|
||||||
|
type: string;
|
||||||
|
key: { type: string; name?: string; value?: unknown };
|
||||||
|
value: { type: string; value?: unknown };
|
||||||
|
computed: boolean;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
for (const prop of obj.properties) {
|
||||||
|
if (prop.type !== "Property" || prop.computed) continue;
|
||||||
|
let keyName: string | undefined;
|
||||||
|
if (prop.key.type === "Identifier") {
|
||||||
|
keyName = prop.key.name;
|
||||||
|
} else if (prop.key.type === "Literal" && typeof prop.key.value === "string") {
|
||||||
|
keyName = prop.key.value;
|
||||||
|
}
|
||||||
|
if (keyName !== "type") continue;
|
||||||
|
if (prop.value.type === "Literal" && prop.value.value === "module") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRelativeOrAliasSpec(spec: string): boolean {
|
||||||
|
return (
|
||||||
|
spec.startsWith("./") ||
|
||||||
|
spec.startsWith("../") ||
|
||||||
|
spec.startsWith("/") ||
|
||||||
|
spec.startsWith("@/")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the next occurrence of a string literal with the given content
|
||||||
|
* in `source`. Searches for `'spec'`, `"spec"`, and `` `spec` ``. The
|
||||||
|
* simplest, correct way: search for each possible quoted form and
|
||||||
|
* pick the earliest occurrence.
|
||||||
|
*/
|
||||||
|
function findNextSpecLiteral(
|
||||||
|
source: string,
|
||||||
|
spec: string,
|
||||||
|
): { literal: string | null; index: number } {
|
||||||
|
// Build the three possible source-text forms of the literal.
|
||||||
|
const candidates = [
|
||||||
|
encodeAsLiteral(spec, "'"),
|
||||||
|
encodeAsLiteral(spec, '"'),
|
||||||
|
encodeAsLiteral(spec, "`"),
|
||||||
|
];
|
||||||
|
|
||||||
|
let bestIdx = -1;
|
||||||
|
let best: string | null = null;
|
||||||
|
for (const lit of candidates) {
|
||||||
|
const idx = source.indexOf(lit);
|
||||||
|
if (idx >= 0 && (bestIdx < 0 || idx < bestIdx)) {
|
||||||
|
bestIdx = idx;
|
||||||
|
best = lit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { literal: best, index: bestIdx };
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeAsLiteral(value: string, quote: "'" | '"' | "`"): string {
|
||||||
|
// We don't do full JS escape handling — the spec is the parsed
|
||||||
|
// (decoded) value of a string literal, so the common case is that
|
||||||
|
// the literal appears in source verbatim as quote + value + quote.
|
||||||
|
// Escaped characters in the original source (e.g. \n) would
|
||||||
|
// de-encode to different bytes and won't match here, which means we
|
||||||
|
// fall through to the "internal error" case. In practice worker
|
||||||
|
// specs are paths with no escapes, so this is fine.
|
||||||
|
return quote + value + quote;
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
readDeploySettings,
|
readDeploySettings,
|
||||||
writeDeploySettings
|
writeDeploySettings
|
||||||
} from './configUtils';
|
} from './configUtils';
|
||||||
|
import { EMPTY_AI_SETTINGS } from './opencode-defaults';
|
||||||
import type { JSRuntimeFS } from './JSRuntime';
|
import type { JSRuntimeFS } from './JSRuntime';
|
||||||
import type { AISettings } from '@/contexts/AISettingsContext';
|
import type { AISettings } from '@/contexts/AISettingsContext';
|
||||||
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
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'));
|
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||||
mockLocalStorage.getItem.mockReturnValue(null);
|
mockLocalStorage.getItem.mockReturnValue(null);
|
||||||
|
|
||||||
const result = await readAISettings(mockFS);
|
const result = await readAISettings(mockFS);
|
||||||
|
|
||||||
expect(result).toEqual({
|
expect(result).toEqual(EMPTY_AI_SETTINGS);
|
||||||
providers: [],
|
|
||||||
recentlyUsedModels: [],
|
|
||||||
mcpServers: {},
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
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');
|
vi.mocked(mockFS.readFile).mockResolvedValue('invalid json');
|
||||||
mockLocalStorage.getItem.mockReturnValue(null);
|
mockLocalStorage.getItem.mockReturnValue(null);
|
||||||
|
|
||||||
const result = await readAISettings(mockFS);
|
const result = await readAISettings(mockFS);
|
||||||
|
|
||||||
expect(result).toEqual({
|
expect(result).toEqual(EMPTY_AI_SETTINGS);
|
||||||
providers: [],
|
|
||||||
recentlyUsedModels: [],
|
|
||||||
mcpServers: {},
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import z from 'zod';
|
import z from 'zod';
|
||||||
import { filteredArray } from '@/lib/schema';
|
import { filteredArray } from '@/lib/schema';
|
||||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||||
|
import { EMPTY_AI_SETTINGS } from '@/lib/opencode-defaults';
|
||||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||||
import type { AISettings, MCPServer } from '@/contexts/AISettingsContext';
|
import type { AISettings, MCPServer } from '@/contexts/AISettingsContext';
|
||||||
import type { GitSettings, GitCredential } from '@/contexts/GitSettingsContext';
|
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)
|
* @param configPath - Custom config path (default: /config)
|
||||||
*/
|
*/
|
||||||
export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): Promise<AISettings> {
|
export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): Promise<AISettings> {
|
||||||
const defaultSettings: AISettings = {
|
|
||||||
providers: [],
|
|
||||||
recentlyUsedModels: [],
|
|
||||||
mcpServers: {},
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const aiConfigPath = getAIConfigPath(configPath);
|
const aiConfigPath = getAIConfigPath(configPath);
|
||||||
const content = await fs.readFile(aiConfigPath, 'utf8');
|
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) {
|
if (error instanceof z.ZodError) {
|
||||||
console.error('AI settings parsing error:', error.issues);
|
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))}`;
|
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.
|
* Check whether a blob already exists on a Blossom server.
|
||||||
* Returns true if the server responds 2xx to a HEAD request.
|
* 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.
|
// no separate kind 10002 or kind 10063 events are published.
|
||||||
await relayClient.event(manifestEvent, { signal: AbortSignal.timeout(10_000) });
|
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({
|
const siteUrl = buildNsiteUrl({
|
||||||
pubkeyHex: pubkey,
|
pubkeyHex: pubkey,
|
||||||
npub,
|
npub,
|
||||||
@@ -335,8 +413,17 @@ export class NsiteAdapter implements DeployAdapter {
|
|||||||
siteIdentifier: this.siteIdentifier,
|
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 {
|
return {
|
||||||
url: siteUrl,
|
// Prefer the short vanity URL when confirmed by the gateway
|
||||||
|
url: vanityUrl ?? siteUrl,
|
||||||
metadata: {
|
metadata: {
|
||||||
pubkey,
|
pubkey,
|
||||||
npub,
|
npub,
|
||||||
@@ -344,6 +431,8 @@ export class NsiteAdapter implements DeployAdapter {
|
|||||||
provider: 'nsite',
|
provider: 'nsite',
|
||||||
siteIdentifier: this.siteIdentifier,
|
siteIdentifier: this.siteIdentifier,
|
||||||
manifestKind,
|
manifestKind,
|
||||||
|
vanityUrl,
|
||||||
|
canonicalUrl: siteUrl,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,27 @@
|
|||||||
|
import type { NsiteProvider } from '@/contexts/DeploySettingsContext';
|
||||||
import type { PresetDeployProvider } from './deploy/types';
|
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[] = [
|
export const PRESET_DEPLOY_PROVIDERS: PresetDeployProvider[] = [
|
||||||
{
|
{
|
||||||
id: 'shakespeare',
|
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'],
|
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
|
||||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||||
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
ngitWebUrl: 'https://nostrhub.io/{naddr}',
|
||||||
previewDomain: 'local-shakespeare.dev',
|
previewDomain: 'iframe.diy',
|
||||||
language: 'en',
|
language: 'en',
|
||||||
showcaseEnabled: true,
|
showcaseEnabled: true,
|
||||||
showcaseCurator: '',
|
showcaseCurator: '',
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ export class BlossomUploadTool implements Tool<BlossomUploadParams> {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const uploader = new BlossomUploader({
|
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,
|
signer: this.signer,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { useVercelOAuth } from '@/hooks/useVercelOAuth';
|
|||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
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 { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||||
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
|
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
|
||||||
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
|
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
|
||||||
@@ -202,24 +202,7 @@ export function DeploySettings() {
|
|||||||
...(preset.proxy && { proxy: true }),
|
...(preset.proxy && { proxy: true }),
|
||||||
};
|
};
|
||||||
} else if (preset.type === 'nsite') {
|
} else if (preset.type === 'nsite') {
|
||||||
newProvider = {
|
newProvider = { ...DEFAULT_NSITE_PROVIDER };
|
||||||
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',
|
|
||||||
],
|
|
||||||
};
|
|
||||||
} else if (preset.type === 'netlify') {
|
} else if (preset.type === 'netlify') {
|
||||||
newProvider = {
|
newProvider = {
|
||||||
id: preset.id, // Use preset ID for presets
|
id: preset.id, // Use preset ID for presets
|
||||||
|
|||||||
@@ -389,6 +389,11 @@ export function ProjectView() {
|
|||||||
open={deleteDialogOpen}
|
open={deleteDialogOpen}
|
||||||
onOpenChange={setDeleteDialogOpen}
|
onOpenChange={setDeleteDialogOpen}
|
||||||
/>
|
/>
|
||||||
|
<AppDialog
|
||||||
|
projectId={project.id}
|
||||||
|
open={appDialogOpen}
|
||||||
|
onOpenChange={setAppDialogOpen}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+1
-1
@@ -44,7 +44,7 @@ export default defineConfig(() => ({
|
|||||||
plugins: [
|
plugins: [
|
||||||
react(),
|
react(),
|
||||||
VitePWA({
|
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
|
manifest: false, // Use existing manifest.webmanifest from public folder
|
||||||
workbox: {
|
workbox: {
|
||||||
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2,wasm,mp3}'],
|
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2,wasm,mp3}'],
|
||||||
|
|||||||
Reference in new issue
Block a user