mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cbf55c9117 | ||
|
|
d87700e731 |
No files matched your search
@@ -108,6 +108,99 @@ Shakespeare provides full Git functionality in the browser using `isomorphic-git
|
||||
|
||||
Git operations happen transparently in the background, providing professional version control without requiring Git knowledge from users.
|
||||
|
||||
## Build System
|
||||
|
||||
Shakespeare includes a browser-based build system that compiles projects entirely in the browser using esbuild-wasm. The build system supports multiple project types and automatically detects the appropriate build strategy.
|
||||
|
||||
### Supported Project Types
|
||||
|
||||
#### React/Vite Projects
|
||||
- **Detection**: Projects with `index.html` at the root
|
||||
- **Entry Point**: Script tags in `index.html` with `type="module"`
|
||||
- **Static Assets**: Files in `public/` directory
|
||||
- **Build Output**: Bundled JavaScript, CSS, and HTML in `dist/` directory
|
||||
|
||||
#### SvelteKit Projects
|
||||
- **Detection**: Projects with `src/app.html` or `svelte.config.js`/`svelte.config.ts`
|
||||
- **Entry Point**: Svelte components in `src/routes/`
|
||||
- **Static Assets**: Files in `static/` directory
|
||||
- **Build Output**: Compiled Svelte components with client-side rendering
|
||||
|
||||
### Build System Architecture
|
||||
|
||||
The build system is located in `src/lib/build/` and consists of several plugins:
|
||||
|
||||
- **esmPlugin**: Resolves npm packages from esm.sh CDN, handles package-lock.json and yarn.lock
|
||||
- **fsPlugin**: Provides filesystem access for imports, handles path aliases like `@/`
|
||||
- **sveltePlugin**: Compiles `.svelte` files using the Svelte compiler from CDN
|
||||
- **shakespearePlugin**: Provides polyfills and workarounds for browser compatibility
|
||||
|
||||
### Project Detection
|
||||
|
||||
The build system automatically detects project type using the following logic:
|
||||
|
||||
```typescript
|
||||
// A project is considered SvelteKit if:
|
||||
// 1. It has src/app.html OR svelte.config.js/ts, AND
|
||||
// 2. It does NOT have a root index.html (which indicates React/Vite)
|
||||
|
||||
// Otherwise, it's treated as a React/Vite project
|
||||
```
|
||||
|
||||
This detection is used in two places:
|
||||
- `buildProject()` in `src/lib/build/index.ts` - for building projects
|
||||
- `useIsProjectPreviewable()` in `src/hooks/useIsProjectPreviewable.ts` - for determining if preview is available
|
||||
|
||||
### Building Projects
|
||||
|
||||
Projects can be built using the `BuildProjectTool` or by calling `buildProject()` directly:
|
||||
|
||||
```typescript
|
||||
const result = await buildProject({
|
||||
fs, // Virtual filesystem
|
||||
projectPath, // Project directory path
|
||||
domParser, // DOMParser instance
|
||||
target: "esnext", // ECMAScript target
|
||||
esmUrl, // ESM CDN URL
|
||||
outputPath, // Optional output directory
|
||||
});
|
||||
```
|
||||
|
||||
The build process:
|
||||
1. Detects project type (React/Vite or SvelteKit)
|
||||
2. Reads package.json, tsconfig.json, and lock files
|
||||
3. Bundles code with esbuild and appropriate plugins
|
||||
4. Processes HTML template (index.html or app.html)
|
||||
5. Copies static assets from public/ or static/
|
||||
6. Writes output to dist/ directory
|
||||
7. Emits `buildComplete` event for preview refresh
|
||||
|
||||
### SvelteKit-Specific Features
|
||||
|
||||
When building SvelteKit projects:
|
||||
- Compiles `.svelte` components using Svelte 5 compiler from esm.sh
|
||||
- Replaces SvelteKit placeholders in app.html:
|
||||
- `%sveltekit.head%` - Replaced with script/style tags
|
||||
- `%sveltekit.body%` - Replaced with `<div id="svelte"></div>`
|
||||
- `%sveltekit.assets%` - Replaced with empty string
|
||||
- `%sveltekit.nonce%` - Replaced with empty string
|
||||
- Looks for entry points in `src/routes/` directory
|
||||
- Copies static assets from `static/` instead of `public/`
|
||||
|
||||
### Preview System
|
||||
|
||||
The preview system uses `useIsProjectPreviewable()` to determine if a project can be previewed:
|
||||
|
||||
- Returns `true` for React/Vite projects with `index.html` and `package.json`
|
||||
- Returns `true` for SvelteKit projects with (`src/app.html` OR `svelte.config.*`) and `package.json`
|
||||
- Returns `false` otherwise
|
||||
|
||||
When a project is previewable, the PreviewPane component shows:
|
||||
- Build button to trigger compilation
|
||||
- Live preview iframe with the built application
|
||||
- Console output and error messages
|
||||
- Browser-like address bar
|
||||
|
||||
## AI Message Format
|
||||
|
||||
Shakespeare uses OpenAI-compatible messages for communication between users and AI assistants. The message format follows these conventions:
|
||||
@@ -198,7 +291,9 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `useNWCContext`: Access NWC context provider
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound, ProjectView, Settings pages)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/lib/build/`: Project build system with esbuild integration (esmPlugin, fsPlugin)
|
||||
- `/src/lib/build/`: Project build system with esbuild integration (esmPlugin, fsPlugin, sveltePlugin)
|
||||
- Supports both React/Vite projects and SvelteKit projects
|
||||
- Automatic project type detection based on file structure
|
||||
- `/src/lib/commands/`: Shell command implementations for virtual filesystem
|
||||
- `/src/lib/commands/git/`: Git command implementations (add, commit, push, pull, etc.)
|
||||
- Unix-style commands: `cat`, `cd`, `cp`, `find`, `grep`, `ls`, `mkdir`, `mv`, `rm`, etc.
|
||||
|
||||
Generated
+109
@@ -114,6 +114,7 @@
|
||||
"globals": "^15.9.0",
|
||||
"jsdom": "^26.1.0",
|
||||
"postcss": "^8.4.47",
|
||||
"svelte": "^5.40.1",
|
||||
"tailwindcss": "^3.4.11",
|
||||
"typescript": "^5.5.3",
|
||||
"typescript-eslint": "^8.0.1",
|
||||
@@ -1249,6 +1250,17 @@
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/remapping": {
|
||||
"version": "2.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
|
||||
"integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/gen-mapping": "^0.3.5",
|
||||
"@jridgewell/trace-mapping": "^0.3.24"
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/resolve-uri": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
|
||||
@@ -3250,6 +3262,16 @@
|
||||
"resolved": "https://npm.jsr.io/~/11/@jsr/std__encoding/1.0.10.tgz",
|
||||
"integrity": "sha512-WK2njnDTyKefroRNk2Ooq7GStp6Y0ccAvr4To+Z/zecRAGe7+OSvH9DbiaHpAKwEi2KQbmpWMOYsdNt+TsdmSw=="
|
||||
},
|
||||
"node_modules/@sveltejs/acorn-typescript": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.6.tgz",
|
||||
"integrity": "sha512-4awhxtMh4cx9blePWl10HRHj8Iivtqj+2QdDCSMDzxG+XKa9+VCNupQuCuvzEhYPzZSrX+0gC+0lHA/0fFKKQQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"acorn": "^8.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/core": {
|
||||
"version": "1.11.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",
|
||||
@@ -4465,6 +4487,16 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/axobject-query": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
|
||||
"integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/bail": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz",
|
||||
@@ -5672,6 +5704,13 @@
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/esm-env": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz",
|
||||
"integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/espree": {
|
||||
"version": "10.4.0",
|
||||
"resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz",
|
||||
@@ -5703,6 +5742,16 @@
|
||||
"node": ">=0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/esrap": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.1.0.tgz",
|
||||
"integrity": "sha512-yzmPNpl7TBbMRC5Lj2JlJZNPml0tzqoqP5B1JXycNUwtqma9AKCO0M2wHrdgsHcy1WRW7S9rJknAMtByg3usgA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/sourcemap-codec": "^1.4.15"
|
||||
}
|
||||
},
|
||||
"node_modules/esrecurse": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz",
|
||||
@@ -6706,6 +6755,16 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/is-reference": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz",
|
||||
"integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/estree": "^1.0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/is-typed-array": {
|
||||
"version": "1.1.15",
|
||||
"resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz",
|
||||
@@ -7044,6 +7103,13 @@
|
||||
"integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/locate-character": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz",
|
||||
"integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/locate-path": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
|
||||
@@ -10055,6 +10121,42 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/svelte": {
|
||||
"version": "5.40.1",
|
||||
"resolved": "https://registry.npmjs.org/svelte/-/svelte-5.40.1.tgz",
|
||||
"integrity": "sha512-0R3t2oiLxJNJb2buz61MNfPdkjeyj2qTCM7TtIv/4ZfF12zD7Ig8iIo+C8febroy+9S4QJ7qfijtearSdO/1ww==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/remapping": "^2.3.4",
|
||||
"@jridgewell/sourcemap-codec": "^1.5.0",
|
||||
"@sveltejs/acorn-typescript": "^1.0.5",
|
||||
"@types/estree": "^1.0.5",
|
||||
"acorn": "^8.12.1",
|
||||
"aria-query": "^5.3.1",
|
||||
"axobject-query": "^4.1.0",
|
||||
"clsx": "^2.1.1",
|
||||
"esm-env": "^1.2.1",
|
||||
"esrap": "^2.1.0",
|
||||
"is-reference": "^3.0.3",
|
||||
"locate-character": "^3.0.0",
|
||||
"magic-string": "^0.30.11",
|
||||
"zimmerframe": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/svelte/node_modules/aria-query": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz",
|
||||
"integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/symbol-tree": {
|
||||
"version": "3.2.4",
|
||||
"resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
|
||||
@@ -11485,6 +11587,13 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/zimmerframe": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",
|
||||
"integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "3.25.76",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
|
||||
|
||||
@@ -117,6 +117,7 @@
|
||||
"globals": "^15.9.0",
|
||||
"jsdom": "^26.1.0",
|
||||
"postcss": "^8.4.47",
|
||||
"svelte": "^5.40.1",
|
||||
"tailwindcss": "^3.4.11",
|
||||
"typescript": "^5.5.3",
|
||||
"typescript-eslint": "^8.0.1",
|
||||
|
||||
@@ -33,9 +33,12 @@ describe('useIsProjectPreviewable', () => {
|
||||
expect(mockFileExists).toHaveBeenCalledWith('test-project', 'package.json');
|
||||
});
|
||||
|
||||
it('returns false when index.html is missing', async () => {
|
||||
it('returns false when index.html is missing and not a SvelteKit project', async () => {
|
||||
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
|
||||
if (filePath === 'index.html') return Promise.resolve(false);
|
||||
if (filePath === 'src/app.html') return Promise.resolve(false);
|
||||
if (filePath === 'svelte.config.js') return Promise.resolve(false);
|
||||
if (filePath === 'svelte.config.ts') return Promise.resolve(false);
|
||||
return Promise.resolve(true);
|
||||
});
|
||||
|
||||
@@ -51,6 +54,66 @@ describe('useIsProjectPreviewable', () => {
|
||||
expect(result.current.data).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true for SvelteKit project with src/app.html', async () => {
|
||||
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
|
||||
if (filePath === 'package.json') return Promise.resolve(true);
|
||||
if (filePath === 'index.html') return Promise.resolve(false);
|
||||
if (filePath === 'src/app.html') return Promise.resolve(true);
|
||||
return Promise.resolve(false);
|
||||
});
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useIsProjectPreviewable('test-project'),
|
||||
{ wrapper: TestApp }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true for SvelteKit project with svelte.config.js', async () => {
|
||||
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
|
||||
if (filePath === 'package.json') return Promise.resolve(true);
|
||||
if (filePath === 'index.html') return Promise.resolve(false);
|
||||
if (filePath === 'svelte.config.js') return Promise.resolve(true);
|
||||
return Promise.resolve(false);
|
||||
});
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useIsProjectPreviewable('test-project'),
|
||||
{ wrapper: TestApp }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true for SvelteKit project with svelte.config.ts', async () => {
|
||||
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
|
||||
if (filePath === 'package.json') return Promise.resolve(true);
|
||||
if (filePath === 'index.html') return Promise.resolve(false);
|
||||
if (filePath === 'svelte.config.ts') return Promise.resolve(true);
|
||||
return Promise.resolve(false);
|
||||
});
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useIsProjectPreviewable('test-project'),
|
||||
{ wrapper: TestApp }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when package.json is missing', async () => {
|
||||
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
|
||||
if (filePath === 'package.json') return Promise.resolve(false);
|
||||
|
||||
@@ -3,7 +3,9 @@ import { useProjectsManager } from './useProjectsManager';
|
||||
|
||||
/**
|
||||
* Hook to check if a project is previewable
|
||||
* A project is previewable if it has index.html and package.json
|
||||
* A project is previewable if it's either:
|
||||
* 1. A React/Vite project (has index.html and package.json)
|
||||
* 2. A SvelteKit project (has src/app.html or svelte.config.js/ts and package.json)
|
||||
*/
|
||||
export function useIsProjectPreviewable(projectId: string) {
|
||||
const projectsManager = useProjectsManager();
|
||||
@@ -12,13 +14,24 @@ export function useIsProjectPreviewable(projectId: string) {
|
||||
queryKey: ['project-previewable', projectId],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
// Check for required files
|
||||
const [hasIndexHtml, hasPackageJson] = await Promise.all([
|
||||
projectsManager.fileExists(projectId, 'index.html'),
|
||||
projectsManager.fileExists(projectId, 'package.json'),
|
||||
// Check for package.json (required for all projects)
|
||||
const hasPackageJson = await projectsManager.fileExists(projectId, 'package.json');
|
||||
if (!hasPackageJson) return false;
|
||||
|
||||
// Check for React/Vite project (index.html at root)
|
||||
const hasIndexHtml = await projectsManager.fileExists(projectId, 'index.html');
|
||||
if (hasIndexHtml) return true;
|
||||
|
||||
// Check for SvelteKit project
|
||||
const [hasAppHtml, hasSvelteConfigJs, hasSvelteConfigTs] = await Promise.all([
|
||||
projectsManager.fileExists(projectId, 'src/app.html'),
|
||||
projectsManager.fileExists(projectId, 'svelte.config.js'),
|
||||
projectsManager.fileExists(projectId, 'svelte.config.ts'),
|
||||
]);
|
||||
|
||||
return hasIndexHtml && hasPackageJson;
|
||||
// SvelteKit project if it has app.html or svelte.config
|
||||
const isSvelteKit = hasAppHtml || hasSvelteConfigJs || hasSvelteConfigTs;
|
||||
return isSvelteKit;
|
||||
} catch (error) {
|
||||
console.error('Failed to check if project is previewable:', error);
|
||||
return false;
|
||||
|
||||
@@ -222,6 +222,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
|
||||
switch (moduleName) {
|
||||
case "buffer":
|
||||
case "events":
|
||||
return {
|
||||
path: `${esmUrl}/${moduleName}?target=${target ?? "esnext"}`,
|
||||
namespace: "esm",
|
||||
@@ -324,7 +325,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
? `${cdnName}@${version}${packagePath}`
|
||||
: `${cdnName}${packagePath}`;
|
||||
|
||||
const url = new URL(`${esmUrl}/*${specifier}`);
|
||||
const url = new URL(`${esmUrl}/${specifier}`);
|
||||
if (target) url.searchParams.set("target", target);
|
||||
if (childLockPath) url.searchParams.set("lp", encodeURIComponent(childLockPath));
|
||||
|
||||
|
||||
@@ -35,16 +35,69 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
|
||||
return;
|
||||
}
|
||||
|
||||
let resolved: string;
|
||||
let resolved: string | undefined;
|
||||
|
||||
// 1. Absolute paths from CSS files should be treated as external (public assets)
|
||||
if (args.path.startsWith("/")) {
|
||||
// Check if the importer is a CSS file
|
||||
const importerExt = args.importer ? extname(args.importer).slice(1) : '';
|
||||
if (importerExt === 'css') {
|
||||
// CSS imports of absolute paths are public assets (fonts, images, etc.)
|
||||
return {
|
||||
path: args.path,
|
||||
external: true,
|
||||
};
|
||||
}
|
||||
resolved = args.path;
|
||||
} else if (args.path.startsWith("@/")) {
|
||||
}
|
||||
// 2. Built-in @/ alias (always points to src/)
|
||||
else if (args.path.startsWith("@/")) {
|
||||
resolved = join(cwd, "src", args.path.slice(2));
|
||||
} else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
|
||||
}
|
||||
// 3. Relative paths
|
||||
else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
|
||||
resolved = join(dirname(args.importer), args.path);
|
||||
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
|
||||
}
|
||||
// 4. Try tsconfig paths
|
||||
else if (tsconfig?.compilerOptions?.paths) {
|
||||
const paths = tsconfig.compilerOptions.paths;
|
||||
const baseUrl = tsconfig.compilerOptions.baseUrl || ".";
|
||||
|
||||
// Try to match against tsconfig paths
|
||||
for (const [pattern, mappings] of Object.entries(paths)) {
|
||||
// Handle exact matches
|
||||
if (pattern === args.path) {
|
||||
const mapping = mappings[0];
|
||||
if (mapping) {
|
||||
resolved = join(cwd, baseUrl, mapping);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle wildcard patterns (e.g., "$lib/*": ["src/lib/*"])
|
||||
if (pattern.endsWith('/*')) {
|
||||
const prefix = pattern.slice(0, -2);
|
||||
if (args.path.startsWith(prefix + '/') || args.path === prefix) {
|
||||
const suffix = args.path.slice(prefix.length);
|
||||
const mapping = mappings[0];
|
||||
if (mapping) {
|
||||
// Replace the * in the mapping with the suffix
|
||||
const resolvedMapping = mapping.replace('*', suffix.slice(1) || '');
|
||||
resolved = join(cwd, baseUrl, resolvedMapping);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Try baseUrl as fallback
|
||||
if (!resolved && args.importer && tsconfig?.compilerOptions?.baseUrl) {
|
||||
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
|
||||
} else {
|
||||
}
|
||||
|
||||
// If still not resolved, let other plugins handle it
|
||||
if (!resolved) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+379
-20
@@ -7,7 +7,9 @@ import { addDomainToCSP } from "@/lib/csp";
|
||||
import { shakespearePlugin } from "./shakespearePlugin";
|
||||
import { esmPlugin } from "./esmPlugin";
|
||||
import { fsPlugin } from "./fsPlugin";
|
||||
import { sveltePlugin } from "./sveltePlugin";
|
||||
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
|
||||
import { convertPnpmLockToPackageLock } from "./pnpmLockConverter";
|
||||
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
|
||||
@@ -20,6 +22,270 @@ export interface BuildProjectOptions {
|
||||
esmUrl: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bundle a SvelteKit project
|
||||
*/
|
||||
async function bundleSvelteKit(
|
||||
options: BuildProjectOptions,
|
||||
): Promise<Record<string, Uint8Array>> {
|
||||
const { fs, projectPath, domParser, target = "esnext", esmUrl } = options;
|
||||
const esbuild = await getEsbuild(esmUrl);
|
||||
|
||||
// Read app.html template
|
||||
const appHtmlText = await fs.readFile(
|
||||
`${projectPath}/src/app.html`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
// Read package.json
|
||||
const packageJsonText = await fs.readFile(
|
||||
`${projectPath}/package.json`,
|
||||
"utf8",
|
||||
);
|
||||
const packageJson = JSON.parse(packageJsonText);
|
||||
|
||||
// Try to read tsconfig.json
|
||||
let tsconfig;
|
||||
try {
|
||||
const tsconfigText = await fs.readFile(
|
||||
`${projectPath}/tsconfig.json`,
|
||||
"utf8",
|
||||
);
|
||||
tsconfig = JSONC.parse(tsconfigText);
|
||||
} catch {
|
||||
tsconfig = undefined;
|
||||
}
|
||||
|
||||
// Extract aliases from svelte.config.js and merge with tsconfig paths
|
||||
const svelteAliases = await extractSvelteAliases(fs, projectPath);
|
||||
|
||||
// Always add default SvelteKit $lib alias
|
||||
const defaultSvelteAliases: Record<string, string> = {
|
||||
'$lib': 'src/lib',
|
||||
'$lib/*': 'src/lib/*',
|
||||
};
|
||||
|
||||
const allSvelteAliases = { ...defaultSvelteAliases, ...svelteAliases };
|
||||
|
||||
if (Object.keys(allSvelteAliases).length > 0) {
|
||||
// Convert Svelte aliases to tsconfig paths format
|
||||
const pathsFromAliases: Record<string, string[]> = {};
|
||||
|
||||
for (const [alias, path] of Object.entries(allSvelteAliases)) {
|
||||
// Handle different alias formats:
|
||||
// 'my-file' -> 'path/to/file.js' becomes 'my-file': ['path/to/file.js']
|
||||
// 'my-dir' -> 'path/to/dir' becomes 'my-dir/*': ['path/to/dir/*']
|
||||
// 'my-dir/*' -> 'path/to/dir/*' stays as is
|
||||
|
||||
if (alias.endsWith('/*')) {
|
||||
pathsFromAliases[alias] = [path];
|
||||
} else if (path.includes('.')) {
|
||||
// Likely a file
|
||||
pathsFromAliases[alias] = [path];
|
||||
} else {
|
||||
// Likely a directory - add /* for directory resolution
|
||||
pathsFromAliases[`${alias}/*`] = [`${path}/*`];
|
||||
// Also add exact match for the directory itself
|
||||
pathsFromAliases[alias] = [path];
|
||||
}
|
||||
}
|
||||
|
||||
// Merge with existing tsconfig paths
|
||||
if (!tsconfig) {
|
||||
tsconfig = { compilerOptions: {} };
|
||||
}
|
||||
if (!tsconfig.compilerOptions) {
|
||||
tsconfig.compilerOptions = {};
|
||||
}
|
||||
|
||||
tsconfig.compilerOptions.paths = {
|
||||
...pathsFromAliases,
|
||||
...tsconfig.compilerOptions.paths, // tsconfig paths take precedence
|
||||
};
|
||||
|
||||
console.log('Merged Svelte aliases into tsconfig paths:', tsconfig.compilerOptions.paths);
|
||||
}
|
||||
|
||||
// Try to read package-lock.json first, fall back to yarn.lock, then pnpm-lock.yaml
|
||||
let packageLock;
|
||||
let buildMode: string;
|
||||
try {
|
||||
const packageLockText = await fs.readFile(
|
||||
`${projectPath}/package-lock.json`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = JSON.parse(packageLockText);
|
||||
buildMode = "npm (package-lock.json)";
|
||||
} catch {
|
||||
try {
|
||||
const yarnLockText = await fs.readFile(
|
||||
`${projectPath}/yarn.lock`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = convertYarnLockToPackageLock(yarnLockText);
|
||||
buildMode = "yarn (yarn.lock)";
|
||||
} catch {
|
||||
try {
|
||||
const pnpmLockText = await fs.readFile(
|
||||
`${projectPath}/pnpm-lock.yaml`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = convertPnpmLockToPackageLock(pnpmLockText);
|
||||
buildMode = "pnpm (pnpm-lock.yaml)";
|
||||
} catch {
|
||||
packageLock = { packages: {} };
|
||||
buildMode = "package.json only (no lock file)";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Building SvelteKit project with ${buildMode}`);
|
||||
|
||||
// Find entry point - typically src/routes/+page.svelte or a layout
|
||||
const entryPoints: string[] = [];
|
||||
|
||||
// Check for common SvelteKit entry points
|
||||
const possibleEntries = [
|
||||
join(projectPath, "src", "routes", "+layout.svelte"),
|
||||
join(projectPath, "src", "routes", "+page.svelte"),
|
||||
];
|
||||
|
||||
for (const entry of possibleEntries) {
|
||||
if (await fileExists(fs, entry)) {
|
||||
entryPoints.push(entry);
|
||||
break; // Use the first one found
|
||||
}
|
||||
}
|
||||
|
||||
// If no entry found, scan the routes directory
|
||||
if (entryPoints.length === 0) {
|
||||
try {
|
||||
const routesPath = join(projectPath, "src", "routes");
|
||||
const routes = await fs.readdir(routesPath);
|
||||
|
||||
for (const route of routes) {
|
||||
if (route.endsWith(".svelte")) {
|
||||
entryPoints.push(join(routesPath, route));
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
throw new Error("Could not find SvelteKit entry point in src/routes/");
|
||||
}
|
||||
}
|
||||
|
||||
// Build with esbuild
|
||||
const results = await esbuild.build({
|
||||
entryPoints,
|
||||
bundle: true,
|
||||
write: false,
|
||||
format: "esm",
|
||||
target,
|
||||
outdir: "/",
|
||||
metafile: true,
|
||||
sourcemap: true,
|
||||
entryNames: "[name]-[hash]",
|
||||
chunkNames: "[name]-[hash]",
|
||||
assetNames: "[name]-[hash]",
|
||||
plugins: [
|
||||
shakespearePlugin({ esmUrl }),
|
||||
sveltePlugin({ fs, projectPath }),
|
||||
fsPlugin({ fs, cwd: projectPath, tsconfig }),
|
||||
esmPlugin({ packageJson, packageLock, target, esmUrl }),
|
||||
],
|
||||
define: {
|
||||
"import.meta.env": JSON.stringify({}),
|
||||
},
|
||||
});
|
||||
|
||||
const dist: Record<string, Uint8Array> = {};
|
||||
const doc = domParser.parseFromString(appHtmlText, "text/html");
|
||||
|
||||
// Track the main component file for mounting
|
||||
let mainComponentPath: string | undefined;
|
||||
|
||||
// Process output files
|
||||
for (const file of results.outputFiles) {
|
||||
const ext = file.path.split('.').pop();
|
||||
const filename = `${file.path.slice(1)}`;
|
||||
const entryPoint = results.metafile.outputs[filename]?.entryPoint?.replace(/^fs:/, '');
|
||||
|
||||
if (ext === "js") {
|
||||
// Track the main component for mounting
|
||||
if (entryPoint && entryPoints.includes(entryPoint)) {
|
||||
mainComponentPath = "/" + filename;
|
||||
}
|
||||
|
||||
dist[filename] = file.contents;
|
||||
} else if (ext === "css") {
|
||||
const style = doc.createElement("link");
|
||||
style.rel = "stylesheet";
|
||||
style.href = "/" + filename;
|
||||
|
||||
if (doc.head.textContent?.includes("%sveltekit.head%")) {
|
||||
doc.head.innerHTML = doc.head.innerHTML.replace("%sveltekit.head%", style.outerHTML);
|
||||
} else {
|
||||
doc.head.appendChild(style);
|
||||
}
|
||||
|
||||
dist[filename] = file.contents;
|
||||
} else {
|
||||
dist[filename] = file.contents;
|
||||
}
|
||||
}
|
||||
|
||||
// Create a mounting script for the Svelte component
|
||||
if (mainComponentPath) {
|
||||
// Get svelte version from package.json
|
||||
const svelteVersion = packageJson.dependencies?.svelte ||
|
||||
packageJson.devDependencies?.svelte ||
|
||||
'5';
|
||||
|
||||
const mountScript = `
|
||||
import Component from '${mainComponentPath}';
|
||||
import { mount } from '${esmUrl}/svelte@${svelteVersion}';
|
||||
|
||||
// Mount the component to the target element
|
||||
const target = document.getElementById('svelte') || document.body;
|
||||
mount(Component, { target });
|
||||
`;
|
||||
|
||||
const mountScriptHash = Math.random().toString(36).substring(7);
|
||||
const mountScriptFilename = `mount-${mountScriptHash}.js`;
|
||||
dist[mountScriptFilename] = new TextEncoder().encode(mountScript);
|
||||
|
||||
// Add the mount script to the HTML
|
||||
const script = document.createElement("script");
|
||||
script.type = "module";
|
||||
script.src = "/" + mountScriptFilename;
|
||||
doc.head.appendChild(script);
|
||||
}
|
||||
|
||||
// Replace SvelteKit placeholders
|
||||
let htmlContent = doc.documentElement.outerHTML;
|
||||
|
||||
// Replace common placeholders
|
||||
htmlContent = htmlContent.replace(/%sveltekit\.head%/g, "");
|
||||
htmlContent = htmlContent.replace(/%sveltekit\.body%/g, '<div id="svelte"></div>');
|
||||
htmlContent = htmlContent.replace(/%sveltekit\.assets%/g, "");
|
||||
htmlContent = htmlContent.replace(/%sveltekit\.nonce%/g, "");
|
||||
|
||||
// Parse CSP and ensure ESM CDN is allowed
|
||||
const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]");
|
||||
if (cspMeta) {
|
||||
const cspContent = cspMeta.getAttribute("content");
|
||||
if (cspContent) {
|
||||
const updatedCSP = updateCSPForEsmSh(cspContent, esmUrl);
|
||||
htmlContent = htmlContent.replace(cspContent, updatedCSP);
|
||||
}
|
||||
}
|
||||
|
||||
const updatedHtml = "<!DOCTYPE html>\n" + htmlContent;
|
||||
dist["index.html"] = new TextEncoder().encode(updatedHtml);
|
||||
|
||||
return dist;
|
||||
}
|
||||
|
||||
async function bundle(
|
||||
options: BuildProjectOptions,
|
||||
): Promise<Record<string, Uint8Array>> {
|
||||
@@ -51,7 +317,7 @@ async function bundle(
|
||||
tsconfig = undefined;
|
||||
}
|
||||
|
||||
// Try to read package-lock.json first, fall back to yarn.lock
|
||||
// Try to read package-lock.json first, fall back to yarn.lock, then pnpm-lock.yaml
|
||||
let packageLock;
|
||||
let buildMode: string;
|
||||
try {
|
||||
@@ -71,9 +337,19 @@ async function bundle(
|
||||
packageLock = convertYarnLockToPackageLock(yarnLockText);
|
||||
buildMode = "yarn (yarn.lock)";
|
||||
} catch {
|
||||
// If neither exists, use empty packages object
|
||||
packageLock = { packages: {} };
|
||||
buildMode = "package.json only (no lock file)";
|
||||
// If yarn.lock doesn't exist, try pnpm-lock.yaml
|
||||
try {
|
||||
const pnpmLockText = await fs.readFile(
|
||||
`${projectPath}/pnpm-lock.yaml`,
|
||||
"utf8",
|
||||
);
|
||||
packageLock = convertPnpmLockToPackageLock(pnpmLockText);
|
||||
buildMode = "pnpm (pnpm-lock.yaml)";
|
||||
} catch {
|
||||
// If no lock file exists, use empty packages object
|
||||
packageLock = { packages: {} };
|
||||
buildMode = "package.json only (no lock file)";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,15 +470,32 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
|
||||
throw new Error(`❌ Could not find package.json at ${projectPath}. Make sure you're in a valid project directory.`);
|
||||
}
|
||||
|
||||
// Check if index.html exists
|
||||
try {
|
||||
await fs.readFile(`${projectPath}/index.html`, "utf8");
|
||||
} catch {
|
||||
throw new Error(`❌ Could not find index.html at ${projectPath}. This is required for building the project.`);
|
||||
}
|
||||
// Detect if this is a SvelteKit project
|
||||
const isSvelteKit = await isSvelteKitProject(fs, projectPath);
|
||||
|
||||
// Run the build
|
||||
const dist = await bundle(options);
|
||||
let dist: Record<string, Uint8Array>;
|
||||
|
||||
if (isSvelteKit) {
|
||||
// Check for src/app.html (required for SvelteKit)
|
||||
try {
|
||||
await fs.readFile(`${projectPath}/src/app.html`, "utf8");
|
||||
} catch {
|
||||
throw new Error(`❌ Could not find src/app.html at ${projectPath}. This is required for building SvelteKit projects.`);
|
||||
}
|
||||
|
||||
console.log("🎭 Detected SvelteKit project");
|
||||
dist = await bundleSvelteKit(options);
|
||||
} else {
|
||||
// Check if index.html exists (required for React/Vite projects)
|
||||
try {
|
||||
await fs.readFile(`${projectPath}/index.html`, "utf8");
|
||||
} catch {
|
||||
throw new Error(`❌ Could not find index.html at ${projectPath}. This is required for building the project.`);
|
||||
}
|
||||
|
||||
// Run the standard build
|
||||
dist = await bundle(options);
|
||||
}
|
||||
|
||||
// Delete all existing files in output directory
|
||||
try {
|
||||
@@ -222,15 +515,19 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
|
||||
await fs.writeFile(`${outputPath}/${path}`, contents);
|
||||
}
|
||||
|
||||
// Copy files from public directory if it exists
|
||||
try {
|
||||
const publicPath = `${projectPath}/public`;
|
||||
const stat = await fs.stat(publicPath);
|
||||
if (stat.isDirectory()) {
|
||||
await copyFiles(fs, fs, publicPath, outputPath);
|
||||
// Copy files from public directory (React/Vite) or static directory (SvelteKit)
|
||||
const staticDirs = isSvelteKit ? ["static"] : ["public"];
|
||||
|
||||
for (const dirName of staticDirs) {
|
||||
try {
|
||||
const staticPath = `${projectPath}/${dirName}`;
|
||||
const stat = await fs.stat(staticPath);
|
||||
if (stat.isDirectory()) {
|
||||
await copyFiles(fs, fs, staticPath, outputPath);
|
||||
}
|
||||
} catch {
|
||||
// Static directory doesn't exist, which is fine
|
||||
}
|
||||
} catch {
|
||||
// Public directory doesn't exist, which is fine
|
||||
}
|
||||
|
||||
// Extract project ID from the project path
|
||||
@@ -261,6 +558,68 @@ async function fileExists(fs: JSRuntimeFS, path: string): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract aliases from svelte.config.js
|
||||
*/
|
||||
async function extractSvelteAliases(fs: JSRuntimeFS, projectPath: string): Promise<Record<string, string> | undefined> {
|
||||
try {
|
||||
// Try to read svelte.config.js
|
||||
let configPath: string | undefined;
|
||||
if (await fileExists(fs, join(projectPath, "svelte.config.js"))) {
|
||||
configPath = join(projectPath, "svelte.config.js");
|
||||
} else if (await fileExists(fs, join(projectPath, "svelte.config.ts"))) {
|
||||
configPath = join(projectPath, "svelte.config.ts");
|
||||
}
|
||||
|
||||
if (!configPath) return undefined;
|
||||
|
||||
const configText = await fs.readFile(configPath, "utf8");
|
||||
|
||||
// Try to extract alias object using regex
|
||||
// Look for: alias: { ... }
|
||||
const aliasMatch = configText.match(/alias\s*:\s*\{([^}]+)\}/s);
|
||||
if (!aliasMatch) return undefined;
|
||||
|
||||
const aliasContent = aliasMatch[1];
|
||||
const aliases: Record<string, string> = {};
|
||||
|
||||
// Parse each alias line: 'key': 'value' or "key": "value"
|
||||
const aliasPattern = /['"]([^'"]+)['"]\s*:\s*['"]([^'"]+)['"]/g;
|
||||
let match;
|
||||
|
||||
while ((match = aliasPattern.exec(aliasContent)) !== null) {
|
||||
const [, key, value] = match;
|
||||
aliases[key] = value;
|
||||
}
|
||||
|
||||
return Object.keys(aliases).length > 0 ? aliases : undefined;
|
||||
} catch (error) {
|
||||
console.warn('Failed to extract Svelte aliases:', error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect if a project is a SvelteKit project
|
||||
*/
|
||||
async function isSvelteKitProject(fs: JSRuntimeFS, projectPath: string): Promise<boolean> {
|
||||
// Check for src/app.html (required for SvelteKit)
|
||||
const hasAppHtml = await fileExists(fs, join(projectPath, "src", "app.html"));
|
||||
|
||||
// Check for svelte.config.js or svelte.config.ts
|
||||
const hasSvelteConfig =
|
||||
await fileExists(fs, join(projectPath, "svelte.config.js")) ||
|
||||
await fileExists(fs, join(projectPath, "svelte.config.ts"));
|
||||
|
||||
// Check if index.html exists at root (indicates React/Vite project, not SvelteKit)
|
||||
const hasRootIndexHtml = await fileExists(fs, join(projectPath, "index.html"));
|
||||
|
||||
// A project is considered SvelteKit if:
|
||||
// 1. It has app.html or svelte.config, AND
|
||||
// 2. It does NOT have a root index.html (which would indicate React/Vite)
|
||||
return (hasAppHtml || hasSvelteConfig) && !hasRootIndexHtml;
|
||||
}
|
||||
|
||||
/** Updates CSP to allow ESM CDN for scripts, assets, fonts, and CSS */
|
||||
export function updateCSPForEsmSh(csp: string, esmUrl: string): string {
|
||||
const esmDirectives = [
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { convertPnpmLockToPackageLock } from './pnpmLockConverter';
|
||||
|
||||
describe('convertPnpmLockToPackageLock', () => {
|
||||
it('should convert a simple pnpm-lock.yaml entry', () => {
|
||||
const pnpmLock = `
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
packages:
|
||||
|
||||
/[email protected]:
|
||||
version: 18.2.0
|
||||
resolution: {integrity: sha512-...}
|
||||
`;
|
||||
|
||||
const result = convertPnpmLockToPackageLock(pnpmLock);
|
||||
|
||||
expect(result.packages['node_modules/react']).toEqual({
|
||||
name: 'react',
|
||||
version: '18.2.0',
|
||||
});
|
||||
});
|
||||
|
||||
it('should convert scoped packages', () => {
|
||||
const pnpmLock = `
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
packages:
|
||||
|
||||
/@babel/[email protected]:
|
||||
version: 7.23.0
|
||||
resolution: {integrity: sha512-...}
|
||||
`;
|
||||
|
||||
const result = convertPnpmLockToPackageLock(pnpmLock);
|
||||
|
||||
expect(result.packages['node_modules/@babel/core']).toEqual({
|
||||
name: '@babel/core',
|
||||
version: '7.23.0',
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse dependencies', () => {
|
||||
const pnpmLock = `
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
packages:
|
||||
|
||||
/[email protected]([email protected]):
|
||||
version: 18.2.0
|
||||
resolution: {integrity: sha512-...}
|
||||
dependencies:
|
||||
loose-envify: 1.4.0
|
||||
scheduler: 0.23.0
|
||||
peerDependencies:
|
||||
react: ^18.2.0
|
||||
`;
|
||||
|
||||
const result = convertPnpmLockToPackageLock(pnpmLock);
|
||||
|
||||
expect(result.packages['node_modules/react-dom']).toEqual({
|
||||
name: 'react-dom',
|
||||
version: '18.2.0',
|
||||
dependencies: {
|
||||
'loose-envify': '1.4.0',
|
||||
'scheduler': '0.23.0',
|
||||
},
|
||||
peerDependencies: {
|
||||
'react': '^18.2.0',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse peer dependencies', () => {
|
||||
const pnpmLock = `
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
packages:
|
||||
|
||||
/@testing-library/[email protected]([email protected])([email protected]):
|
||||
version: 14.0.0
|
||||
resolution: {integrity: sha512-...}
|
||||
peerDependencies:
|
||||
react: ^18.0.0
|
||||
react-dom: ^18.0.0
|
||||
`;
|
||||
|
||||
const result = convertPnpmLockToPackageLock(pnpmLock);
|
||||
|
||||
expect(result.packages['node_modules/@testing-library/react']).toEqual({
|
||||
name: '@testing-library/react',
|
||||
version: '14.0.0',
|
||||
peerDependencies: {
|
||||
react: '^18.0.0',
|
||||
'react-dom': '^18.0.0',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle multiple packages', () => {
|
||||
const pnpmLock = `
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
packages:
|
||||
|
||||
/[email protected]:
|
||||
version: 18.2.0
|
||||
resolution: {integrity: sha512-...}
|
||||
|
||||
/[email protected]([email protected]):
|
||||
version: 18.2.0
|
||||
resolution: {integrity: sha512-...}
|
||||
dependencies:
|
||||
react: 18.2.0
|
||||
`;
|
||||
|
||||
const result = convertPnpmLockToPackageLock(pnpmLock);
|
||||
|
||||
expect(result.packages['node_modules/react']).toEqual({
|
||||
name: 'react',
|
||||
version: '18.2.0',
|
||||
});
|
||||
|
||||
expect(result.packages['node_modules/react-dom']).toEqual({
|
||||
name: 'react-dom',
|
||||
version: '18.2.0',
|
||||
dependencies: {
|
||||
react: '18.2.0',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should skip entries without version', () => {
|
||||
const pnpmLock = `
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
packages:
|
||||
|
||||
/[email protected]:
|
||||
resolution: {integrity: sha512-...}
|
||||
|
||||
/[email protected]:
|
||||
version: 1.0.0
|
||||
resolution: {integrity: sha512-...}
|
||||
`;
|
||||
|
||||
const result = convertPnpmLockToPackageLock(pnpmLock);
|
||||
|
||||
expect(result.packages['node_modules/invalid-entry']).toBeUndefined();
|
||||
expect(result.packages['node_modules/valid-entry']).toEqual({
|
||||
name: 'valid-entry',
|
||||
version: '1.0.0',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle empty pnpm-lock.yaml', () => {
|
||||
const pnpmLock = `
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
packages:
|
||||
`;
|
||||
|
||||
const result = convertPnpmLockToPackageLock(pnpmLock);
|
||||
|
||||
expect(result.packages).toEqual({});
|
||||
});
|
||||
|
||||
it('should handle packages with peer dependency specifiers in key', () => {
|
||||
const pnpmLock = `
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
packages:
|
||||
|
||||
/[email protected]([email protected])([email protected]):
|
||||
version: 6.0.0
|
||||
resolution: {integrity: sha512-...}
|
||||
dependencies:
|
||||
some-dep: 1.0.0
|
||||
peerDependencies:
|
||||
react: '>= 16.8.0'
|
||||
react-dom: '>= 16.8.0'
|
||||
`;
|
||||
|
||||
const result = convertPnpmLockToPackageLock(pnpmLock);
|
||||
|
||||
expect(result.packages['node_modules/styled-components']).toEqual({
|
||||
name: 'styled-components',
|
||||
version: '6.0.0',
|
||||
dependencies: {
|
||||
'some-dep': '1.0.0',
|
||||
},
|
||||
peerDependencies: {
|
||||
react: '>= 16.8.0',
|
||||
'react-dom': '>= 16.8.0',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should stop parsing after packages section ends', () => {
|
||||
const pnpmLock = `
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
packages:
|
||||
|
||||
/[email protected]:
|
||||
version: 18.2.0
|
||||
resolution: {integrity: sha512-...}
|
||||
|
||||
snapshots:
|
||||
/[email protected]:
|
||||
dependencies:
|
||||
loose-envify: 1.4.0
|
||||
`;
|
||||
|
||||
const result = convertPnpmLockToPackageLock(pnpmLock);
|
||||
|
||||
// Should only have the package from packages section, not from snapshots
|
||||
expect(result.packages['node_modules/react']).toEqual({
|
||||
name: 'react',
|
||||
version: '18.2.0',
|
||||
});
|
||||
expect(Object.keys(result.packages).length).toBe(1);
|
||||
});
|
||||
|
||||
it('should handle multiple installations of same package@version with different peer deps', () => {
|
||||
const pnpmLock = `
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
packages:
|
||||
|
||||
/[email protected]([email protected])([email protected]):
|
||||
version: 3.9.3
|
||||
resolution: {integrity: sha512-...}
|
||||
peerDependencies:
|
||||
eslint: ^8.0.0 || ^9.0.0
|
||||
svelte: ^4.0.0 || ^5.0.0
|
||||
|
||||
/[email protected]([email protected])([email protected]):
|
||||
version: 3.9.3
|
||||
resolution: {integrity: sha512-...}
|
||||
peerDependencies:
|
||||
eslint: ^8.0.0 || ^9.0.0
|
||||
svelte: ^4.0.0 || ^5.0.0
|
||||
`;
|
||||
|
||||
const result = convertPnpmLockToPackageLock(pnpmLock);
|
||||
|
||||
// First installation should use simple path
|
||||
expect(result.packages['node_modules/eslint-plugin-svelte']).toEqual({
|
||||
name: 'eslint-plugin-svelte',
|
||||
version: '3.9.3',
|
||||
peerDependencies: {
|
||||
eslint: '^8.0.0 || ^9.0.0',
|
||||
svelte: '^4.0.0 || ^5.0.0',
|
||||
},
|
||||
});
|
||||
|
||||
// Second installation should use nested path
|
||||
expect(result.packages['node_modules/.pnpm/eslint-plugin-svelte_1']).toEqual({
|
||||
name: 'eslint-plugin-svelte',
|
||||
version: '3.9.3',
|
||||
peerDependencies: {
|
||||
eslint: '^8.0.0 || ^9.0.0',
|
||||
svelte: '^4.0.0 || ^5.0.0',
|
||||
},
|
||||
});
|
||||
|
||||
expect(Object.keys(result.packages).length).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* Converts pnpm-lock.yaml format to package-lock.json format for use with esmPlugin.
|
||||
* This is a simplified converter that extracts enough information for dependency resolution.
|
||||
*/
|
||||
|
||||
interface PnpmLockPackage {
|
||||
version?: string;
|
||||
dependencies?: Record<string, string>;
|
||||
peerDependencies?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface PackageLockPackage {
|
||||
name?: string;
|
||||
version: string;
|
||||
dependencies?: Record<string, string>;
|
||||
peerDependencies?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface PackageLock {
|
||||
packages: {
|
||||
[key: string]: PackageLockPackage;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a pnpm-lock.yaml file and convert it to package-lock.json format
|
||||
*/
|
||||
export function convertPnpmLockToPackageLock(pnpmLockContent: string): PackageLock {
|
||||
const packages: Record<string, PackageLockPackage> = {};
|
||||
|
||||
// Parse pnpm-lock.yaml entries
|
||||
const entries = parsePnpmLock(pnpmLockContent);
|
||||
|
||||
// Track which package@version combinations we've seen to handle duplicates
|
||||
const seenVersions = new Map<string, number>();
|
||||
|
||||
for (const [key, entry] of Object.entries(entries)) {
|
||||
if (!entry.version) continue;
|
||||
|
||||
const packageName = extractPackageName(key);
|
||||
if (!packageName) continue;
|
||||
|
||||
const versionKey = `${packageName}@${entry.version}`;
|
||||
const count = seenVersions.get(versionKey) || 0;
|
||||
seenVersions.set(versionKey, count + 1);
|
||||
|
||||
// Determine the lock path
|
||||
let lockPath: string;
|
||||
|
||||
if (count === 0) {
|
||||
// First occurrence - use simple node_modules path
|
||||
lockPath = `node_modules/${packageName}`;
|
||||
} else {
|
||||
// Subsequent occurrences - create unique nested paths
|
||||
// This handles cases where the same package@version is installed
|
||||
// multiple times with different peer dependencies
|
||||
lockPath = `node_modules/.pnpm/${packageName}_${count}`;
|
||||
}
|
||||
|
||||
packages[lockPath] = {
|
||||
name: packageName,
|
||||
version: entry.version,
|
||||
dependencies: entry.dependencies,
|
||||
peerDependencies: entry.peerDependencies,
|
||||
};
|
||||
}
|
||||
|
||||
return { packages };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse pnpm-lock.yaml content into a map of entries
|
||||
* This is a simple YAML parser focused on the packages section
|
||||
*/
|
||||
function parsePnpmLock(content: string): Record<string, PnpmLockPackage> {
|
||||
const entries: Record<string, PnpmLockPackage> = {};
|
||||
const lines = content.split('\n');
|
||||
|
||||
let inPackagesSection = false;
|
||||
let currentKey: string | null = null;
|
||||
let currentEntry: Partial<PnpmLockPackage> = {};
|
||||
let inDependencies = false;
|
||||
let inPeerDependencies = false;
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
|
||||
// Skip comments and empty lines
|
||||
if (line.trim().startsWith('#') || line.trim() === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Detect the packages section
|
||||
if (line.match(/^packages:/)) {
|
||||
inPackagesSection = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Exit packages section when we hit another top-level key
|
||||
if (inPackagesSection && line.match(/^[a-zA-Z]/)) {
|
||||
inPackagesSection = false;
|
||||
// Save last entry before exiting
|
||||
if (currentKey && currentEntry.version) {
|
||||
entries[currentKey] = currentEntry as PnpmLockPackage;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (!inPackagesSection) continue;
|
||||
|
||||
// Get indentation level
|
||||
const indent = line.search(/\S/);
|
||||
if (indent === -1) continue;
|
||||
|
||||
// Package entry (2-space indent from packages:)
|
||||
// Example: " /@babel/[email protected]:"
|
||||
const packageMatch = line.match(/^ {2}(\/[^:]+):\s*$/);
|
||||
if (packageMatch) {
|
||||
// Save previous entry
|
||||
if (currentKey && currentEntry.version) {
|
||||
entries[currentKey] = currentEntry as PnpmLockPackage;
|
||||
}
|
||||
|
||||
// Start new entry
|
||||
currentKey = packageMatch[1];
|
||||
currentEntry = {};
|
||||
inDependencies = false;
|
||||
inPeerDependencies = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip if we don't have a current package
|
||||
if (!currentKey) continue;
|
||||
|
||||
// Property lines (4-space indent from package key)
|
||||
const propertyMatch = line.match(/^ {4}([a-zA-Z]+):\s*$/);
|
||||
const valueMatch = line.match(/^ {4}([a-zA-Z]+):\s*(.+)\s*$/);
|
||||
const depMatch = line.match(/^ {6}([^:]+):\s*(.+)\s*$/);
|
||||
|
||||
if (propertyMatch) {
|
||||
const [, key] = propertyMatch;
|
||||
|
||||
if (key === 'dependencies') {
|
||||
inDependencies = true;
|
||||
inPeerDependencies = false;
|
||||
currentEntry.dependencies = {};
|
||||
} else if (key === 'peerDependencies') {
|
||||
inPeerDependencies = true;
|
||||
inDependencies = false;
|
||||
currentEntry.peerDependencies = {};
|
||||
} else {
|
||||
inDependencies = false;
|
||||
inPeerDependencies = false;
|
||||
}
|
||||
} else if (valueMatch && !inDependencies && !inPeerDependencies) {
|
||||
const [, key, value] = valueMatch;
|
||||
|
||||
if (key === 'version') {
|
||||
currentEntry.version = value.trim();
|
||||
}
|
||||
} else if (depMatch) {
|
||||
const [, key, value] = depMatch;
|
||||
const cleanKey = key.trim();
|
||||
// Remove quotes from value if present
|
||||
const cleanValue = value.trim().replace(/^['"]|['"]$/g, '');
|
||||
|
||||
if (inDependencies && currentEntry.dependencies) {
|
||||
currentEntry.dependencies[cleanKey] = cleanValue;
|
||||
} else if (inPeerDependencies && currentEntry.peerDependencies) {
|
||||
currentEntry.peerDependencies[cleanKey] = cleanValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Save last entry
|
||||
if (currentKey && currentEntry.version) {
|
||||
entries[currentKey] = currentEntry as PnpmLockPackage;
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the package name from a pnpm-lock.yaml key
|
||||
* Examples:
|
||||
* "/@babel/[email protected]" -> "@babel/core"
|
||||
* "/[email protected]" -> "react"
|
||||
* "/[email protected]([email protected])" -> "react-dom"
|
||||
*/
|
||||
function extractPackageName(key: string): string | null {
|
||||
// Remove leading slash
|
||||
let cleaned = key.startsWith('/') ? key.slice(1) : key;
|
||||
|
||||
// Remove peer dependency specifications in parentheses
|
||||
// Example: "[email protected]([email protected])" -> "[email protected]"
|
||||
cleaned = cleaned.replace(/\([^)]*\)$/, '');
|
||||
|
||||
// Handle scoped packages: "@scope/package@version"
|
||||
if (cleaned.startsWith('@')) {
|
||||
const parts = cleaned.split('@');
|
||||
// parts will be: ['', 'scope/package', 'version']
|
||||
if (parts.length >= 2) {
|
||||
return `@${parts[1]}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle regular packages: "package@version"
|
||||
const atIndex = cleaned.indexOf('@');
|
||||
if (atIndex > 0) {
|
||||
return cleaned.substring(0, atIndex);
|
||||
}
|
||||
|
||||
// If no @ found, return the whole string
|
||||
return cleaned || null;
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import type { Plugin } from "esbuild-wasm";
|
||||
import type { JSRuntimeFS } from "@/lib/JSRuntime";
|
||||
import { compile } from "svelte/compiler";
|
||||
|
||||
interface SveltePluginOptions {
|
||||
fs: JSRuntimeFS;
|
||||
projectPath: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Svelte plugin for esbuild to compile .svelte files in the browser.
|
||||
* This is a basic implementation that transforms Svelte components to JavaScript.
|
||||
*/
|
||||
export function sveltePlugin(options: SveltePluginOptions): Plugin {
|
||||
const { fs } = options;
|
||||
|
||||
return {
|
||||
name: "svelte",
|
||||
|
||||
setup(build) {
|
||||
// Stub SvelteKit $app modules
|
||||
build.onResolve({ filter: /^\$app\// }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "sveltekit-stub",
|
||||
};
|
||||
});
|
||||
|
||||
build.onLoad({ filter: /.*/, namespace: "sveltekit-stub" }, (args) => {
|
||||
const module = args.path;
|
||||
|
||||
// $app/environment
|
||||
if (module === "$app/environment") {
|
||||
return {
|
||||
contents: `
|
||||
export const browser = true;
|
||||
export const building = false;
|
||||
export const dev = true;
|
||||
export const version = "stub";
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
}
|
||||
|
||||
// $app/navigation
|
||||
if (module === "$app/navigation") {
|
||||
return {
|
||||
contents: `
|
||||
export function afterNavigate(callback) {
|
||||
// Stub: no-op in browser build
|
||||
}
|
||||
|
||||
export function beforeNavigate(callback) {
|
||||
// Stub: no-op in browser build
|
||||
}
|
||||
|
||||
export function disableScrollHandling() {
|
||||
// Stub: no-op in browser build
|
||||
}
|
||||
|
||||
export function goto(url, opts) {
|
||||
console.warn('[SvelteKit Stub] goto() called with:', url, opts);
|
||||
window.location.href = typeof url === 'string' ? url : url.toString();
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
export function invalidate(url) {
|
||||
console.warn('[SvelteKit Stub] invalidate() called');
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
export function invalidateAll() {
|
||||
console.warn('[SvelteKit Stub] invalidateAll() called');
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
export function onNavigate(callback) {
|
||||
// Stub: no-op in browser build
|
||||
}
|
||||
|
||||
export function preloadCode(...args) {
|
||||
console.warn('[SvelteKit Stub] preloadCode() called');
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
export function preloadData(url) {
|
||||
console.warn('[SvelteKit Stub] preloadData() called');
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
export function pushState(url, state) {
|
||||
console.warn('[SvelteKit Stub] pushState() called');
|
||||
window.history.pushState(state, '', url);
|
||||
}
|
||||
|
||||
export function replaceState(url, state) {
|
||||
console.warn('[SvelteKit Stub] replaceState() called');
|
||||
window.history.replaceState(state, '', url);
|
||||
}
|
||||
|
||||
export function refreshAll() {
|
||||
console.warn('[SvelteKit Stub] refreshAll() called');
|
||||
window.location.reload();
|
||||
return Promise.resolve();
|
||||
}
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
}
|
||||
|
||||
// $app/stores
|
||||
if (module === "$app/stores") {
|
||||
return {
|
||||
contents: `
|
||||
import { writable, readable } from 'svelte/store';
|
||||
|
||||
export const page = readable({
|
||||
url: new URL(window.location.href),
|
||||
params: {},
|
||||
route: { id: null },
|
||||
status: 200,
|
||||
error: null,
|
||||
data: {},
|
||||
form: null,
|
||||
state: {}
|
||||
});
|
||||
|
||||
export const navigating = readable(null);
|
||||
|
||||
export const updated = Object.assign(
|
||||
readable(false),
|
||||
{ check: () => Promise.resolve(false) }
|
||||
);
|
||||
|
||||
export function getStores() {
|
||||
return { page, navigating, updated };
|
||||
}
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
}
|
||||
|
||||
// $app/paths
|
||||
if (module === "$app/paths") {
|
||||
return {
|
||||
contents: `
|
||||
export const base = '';
|
||||
export const assets = '';
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
}
|
||||
|
||||
// $app/forms (for form actions)
|
||||
if (module === "$app/forms") {
|
||||
return {
|
||||
contents: `
|
||||
export function enhance(form, submit) {
|
||||
console.warn('[SvelteKit Stub] enhance() called - form actions not supported in browser build');
|
||||
return { destroy() {} };
|
||||
}
|
||||
|
||||
export function applyAction(result) {
|
||||
console.warn('[SvelteKit Stub] applyAction() called');
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
export function deserialize(result) {
|
||||
console.warn('[SvelteKit Stub] deserialize() called');
|
||||
return result;
|
||||
}
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
}
|
||||
|
||||
// Unknown $app module
|
||||
return {
|
||||
contents: `
|
||||
console.error('[SvelteKit Stub] Unknown module: ${module}');
|
||||
export default {};
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
|
||||
// Handle .svelte file imports
|
||||
build.onLoad({ filter: /\.svelte$/ }, async (args) => {
|
||||
try {
|
||||
const source = await fs.readFile(args.path, "utf8");
|
||||
|
||||
// Compile the Svelte component
|
||||
const result = compile(source, {
|
||||
filename: args.path,
|
||||
generate: "client", // Svelte 5 uses "client" instead of "dom"
|
||||
css: "injected", // Inject CSS into the component
|
||||
});
|
||||
|
||||
// Return the compiled JavaScript
|
||||
return {
|
||||
contents: result.js.code,
|
||||
loader: "js",
|
||||
warnings: result.warnings?.map((warning) => ({
|
||||
text: warning.message,
|
||||
location: warning.start ? {
|
||||
file: args.path,
|
||||
line: warning.start.line,
|
||||
column: warning.start.column,
|
||||
} : undefined,
|
||||
})) || [],
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
errors: [{
|
||||
text: error instanceof Error ? error.message : String(error),
|
||||
location: { file: args.path },
|
||||
}],
|
||||
};
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user