mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 00:27:24 +00:00
Merge in from upstream and resolve conflicts
This commit is contained in:
commit
5e352e60e9
147 files changed
+10132
-3041
No files matched your search
+4
-48
@@ -28,17 +28,8 @@ describe('DotAI', () => {
|
||||
});
|
||||
|
||||
describe('readLastSessionHistory', () => {
|
||||
it('should return null when AI is not enabled', async () => {
|
||||
// Mock isEnabled to return false
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(false);
|
||||
|
||||
const result = await dotAI.readLastSessionHistory();
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null when history directory does not exist', async () => {
|
||||
// Mock isEnabled to return true but historyDirExists to return false
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
// Mock historyDirExists to return false
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
|
||||
|
||||
const result = await dotAI.readLastSessionHistory();
|
||||
@@ -46,8 +37,7 @@ describe('DotAI', () => {
|
||||
});
|
||||
|
||||
it('should return null when no session files exist', async () => {
|
||||
// Mock isEnabled and historyDirExists to return true
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
// Mock historyDirExists to return true
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
||||
|
||||
// Mock readdir to return empty array
|
||||
@@ -58,8 +48,7 @@ describe('DotAI', () => {
|
||||
});
|
||||
|
||||
it('should return messages and session name from most recent file', async () => {
|
||||
// Mock isEnabled and historyDirExists to return true
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
// Mock historyDirExists to return true
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
||||
|
||||
// Mock readdir to return session files
|
||||
@@ -84,8 +73,7 @@ describe('DotAI', () => {
|
||||
});
|
||||
|
||||
it('should handle malformed JSON lines gracefully', async () => {
|
||||
// Mock isEnabled and historyDirExists to return true
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
// Mock historyDirExists to return true
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
||||
|
||||
// Mock readdir to return session files
|
||||
@@ -107,24 +95,7 @@ invalid json line
|
||||
});
|
||||
|
||||
describe('setHistory', () => {
|
||||
it('should not save when AI is not enabled', async () => {
|
||||
// Mock isEnabled to return false
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(false);
|
||||
|
||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||
{ role: 'user', content: 'Hello' },
|
||||
{ role: 'assistant', content: 'Hi there!' }
|
||||
];
|
||||
|
||||
await dotAI.setHistory('test-session', messages);
|
||||
|
||||
// Verify writeFile was not called
|
||||
expect(mockFS.writeFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should create history directory if it does not exist', async () => {
|
||||
// Mock isEnabled to return true
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
// Mock historyDirExists to return false initially
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
|
||||
// Mock setupAiHistoryDir
|
||||
@@ -141,8 +112,6 @@ invalid json line
|
||||
});
|
||||
|
||||
it('should write messages as JSONL format', async () => {
|
||||
// Mock isEnabled to return true
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
// Mock historyDirExists to return true
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
||||
|
||||
@@ -161,8 +130,6 @@ invalid json line
|
||||
});
|
||||
|
||||
it('should handle empty messages array', async () => {
|
||||
// Mock isEnabled to return true
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
// Mock historyDirExists to return true
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
||||
|
||||
@@ -176,8 +143,6 @@ invalid json line
|
||||
});
|
||||
|
||||
it('should handle write errors gracefully', async () => {
|
||||
// Mock isEnabled to return true
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
// Mock historyDirExists to return true
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
||||
// Mock writeFile to throw an error
|
||||
@@ -190,9 +155,6 @@ invalid json line
|
||||
});
|
||||
|
||||
it('should validate tool messages have matching tool_call_id', async () => {
|
||||
// Mock isEnabled to return true
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
|
||||
const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||
{ role: 'user', content: 'Hello' },
|
||||
{
|
||||
@@ -249,9 +211,6 @@ invalid json line
|
||||
});
|
||||
|
||||
it('should validate multiple tool messages correctly', async () => {
|
||||
// Mock isEnabled to return true
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
|
||||
const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||
{ role: 'user', content: 'Hello' },
|
||||
{
|
||||
@@ -271,9 +230,6 @@ invalid json line
|
||||
});
|
||||
|
||||
it('should allow tool messages to reference tool calls from the most recent assistant message', async () => {
|
||||
// Mock isEnabled to return true
|
||||
vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true);
|
||||
|
||||
const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
|
||||
{ role: 'user', content: 'First request' },
|
||||
{
|
||||
|
||||
+10
-53
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type OpenAI from "openai";
|
||||
import type { JSRuntimeFS } from "./JSRuntime";
|
||||
|
||||
@@ -31,45 +31,7 @@ export class DotAI {
|
||||
return filename;
|
||||
}
|
||||
|
||||
/** Check if AI history should be enabled based on the new criteria */
|
||||
async isEnabled(): Promise<boolean> {
|
||||
// Check if .ai directory exists
|
||||
try {
|
||||
const stat = await this.fs.stat(join(this.workingDir, ".ai"));
|
||||
if (stat.isDirectory()) {
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// Continue to next check
|
||||
}
|
||||
|
||||
// Check if .ai/ or .ai is gitignored
|
||||
try {
|
||||
const gitignorePath = join(this.workingDir, ".gitignore");
|
||||
const gitignoreContent = await this.fs.readFile(gitignorePath, "utf8");
|
||||
const lines = gitignoreContent.split("\n").map((line) => line.trim());
|
||||
|
||||
// Check for .ai/ or .ai patterns (ignore comments and empty lines)
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("#") || line === "") {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check for various .ai patterns
|
||||
if (
|
||||
line === ".ai" || line === ".ai/" || line === "/.ai" ||
|
||||
line === "/.ai/" ||
|
||||
line === ".ai/*" || line === "/.ai/*"
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// .gitignore doesn't exist or can't be read
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Check if the history directory exists */
|
||||
async historyDirExists(): Promise<boolean> {
|
||||
@@ -89,11 +51,7 @@ export class DotAI {
|
||||
// Validate messages before saving
|
||||
this.validateMessages(messages);
|
||||
|
||||
// Only save if history should be enabled based on the new criteria
|
||||
if (!(await this.isEnabled())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Always create the .ai directory and write session history
|
||||
// Create the history directory if it doesn't exist
|
||||
if (!(await this.historyDirExists())) {
|
||||
await this.setupAiHistoryDir();
|
||||
@@ -205,6 +163,9 @@ export class DotAI {
|
||||
// Ensure .ai directory exists
|
||||
await this.fs.mkdir(aiDir, { recursive: true });
|
||||
|
||||
// Ensure .ai/ is gitignored
|
||||
await this.ensureAiGitignored();
|
||||
|
||||
// Write the model
|
||||
await this.fs.writeFile(modelPath, model.trim() + "\n");
|
||||
} catch (error) {
|
||||
@@ -245,13 +206,6 @@ export class DotAI {
|
||||
* Write parameters to .ai/PARAMETERS file
|
||||
*/
|
||||
async writeAiParameters(parameters: Record<string, string>): Promise<void> {
|
||||
// Check if we should create the .ai directory based on the same logic as MODEL
|
||||
const shouldCreate = await this.isEnabled();
|
||||
|
||||
if (!shouldCreate) {
|
||||
return;
|
||||
}
|
||||
|
||||
const aiDir = join(this.workingDir, ".ai");
|
||||
const parametersPath = join(aiDir, "PARAMETERS");
|
||||
|
||||
@@ -259,6 +213,9 @@ export class DotAI {
|
||||
// Ensure .ai directory exists
|
||||
await this.fs.mkdir(aiDir, { recursive: true });
|
||||
|
||||
// Ensure .ai/ is gitignored
|
||||
await this.ensureAiGitignored();
|
||||
|
||||
// Format parameters as key=value pairs
|
||||
const lines = Object.entries(parameters).map(([key, value]) =>
|
||||
`${key}=${value}`
|
||||
@@ -290,8 +247,8 @@ export class DotAI {
|
||||
sessionName: string;
|
||||
} | null> {
|
||||
try {
|
||||
// Check if AI history is enabled for this project
|
||||
if (!(await this.isEnabled()) || !(await this.historyDirExists())) {
|
||||
// Check if history directory exists
|
||||
if (!(await this.historyDirExists())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { ProjectsManager } from './ProjectsManager';
|
||||
import { JSRuntimeFS } from './JSRuntime';
|
||||
import { Git } from './git';
|
||||
import type { NPool } from '@nostrify/nostrify';
|
||||
|
||||
const createMockNostr = (): NPool => ({
|
||||
req: vi.fn(),
|
||||
query: vi.fn(),
|
||||
event: vi.fn(),
|
||||
group: vi.fn(),
|
||||
relay: vi.fn(),
|
||||
relays: new Map(),
|
||||
close: vi.fn(),
|
||||
}) as unknown as NPool;
|
||||
|
||||
// Mock JSZip
|
||||
vi.mock('jszip', () => ({
|
||||
@@ -23,10 +36,13 @@ vi.mock('jszip', () => ({
|
||||
}));
|
||||
|
||||
// Mock filesystem for testing
|
||||
class MockFS {
|
||||
class MockFS implements JSRuntimeFS {
|
||||
private files: Map<string, string | Uint8Array> = new Map();
|
||||
private dirs: Set<string> = new Set();
|
||||
|
||||
async readFile(path: string): Promise<Uint8Array>;
|
||||
async readFile(path: string, encoding: "utf8"): Promise<string>;
|
||||
async readFile(path: string, encoding: string): Promise<string | Uint8Array>;
|
||||
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
|
||||
const content = this.files.get(path);
|
||||
if (content === undefined) {
|
||||
@@ -34,10 +50,18 @@ class MockFS {
|
||||
error.code = 'ENOENT';
|
||||
throw error;
|
||||
}
|
||||
if (encoding === 'utf8' && typeof content === 'string') {
|
||||
return content;
|
||||
if (encoding === 'utf8') {
|
||||
if (typeof content === 'string') {
|
||||
return content;
|
||||
}
|
||||
// Convert Uint8Array to string
|
||||
return new TextDecoder('utf-8').decode(content as Uint8Array);
|
||||
}
|
||||
return content;
|
||||
if (typeof content === 'string') {
|
||||
// Convert string to Uint8Array
|
||||
return new TextEncoder().encode(content);
|
||||
}
|
||||
return content as Uint8Array;
|
||||
}
|
||||
|
||||
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
|
||||
@@ -49,7 +73,8 @@ class MockFS {
|
||||
}
|
||||
}
|
||||
|
||||
async readdir(path: string): Promise<string[]> {
|
||||
// @ts-expect-error I don't know how to type this properly
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
|
||||
if (!this.dirs.has(path)) {
|
||||
const error = new Error(`ENOENT: no such file or directory, scandir '${path}'`) as NodeJS.ErrnoException;
|
||||
error.code = 'ENOENT';
|
||||
@@ -72,7 +97,22 @@ class MockFS {
|
||||
}
|
||||
}
|
||||
|
||||
return [...new Set(entries)];
|
||||
const uniqueEntries = [...new Set(entries)];
|
||||
|
||||
if (options && options.withFileTypes) {
|
||||
// Provide a minimal DirectoryEntry mock
|
||||
return uniqueEntries.map(name => {
|
||||
const fullPath = path.endsWith('/') ? path + name : path + '/' + name;
|
||||
const isDir = this.dirs.has(fullPath);
|
||||
return {
|
||||
name,
|
||||
isDirectory: () => isDir,
|
||||
isFile: () => !isDir,
|
||||
} as unknown as DirectoryEntry;
|
||||
});
|
||||
}
|
||||
|
||||
return uniqueEntries;
|
||||
}
|
||||
|
||||
async mkdir(path: string): Promise<void> {
|
||||
@@ -106,15 +146,76 @@ class MockFS {
|
||||
async rmdir(path: string): Promise<void> {
|
||||
this.dirs.delete(path);
|
||||
}
|
||||
|
||||
async rename(oldPath: string, newPath: string): Promise<void> {
|
||||
// Handle both files and directories
|
||||
if (this.files.has(oldPath)) {
|
||||
const content = this.files.get(oldPath);
|
||||
this.files.delete(oldPath);
|
||||
this.files.set(newPath, content!);
|
||||
}
|
||||
|
||||
if (this.dirs.has(oldPath)) {
|
||||
this.dirs.delete(oldPath);
|
||||
this.dirs.add(newPath);
|
||||
|
||||
// Also move all subdirectories and files
|
||||
const itemsToMove: Array<{ oldPath: string; newPath: string; isDir: boolean }> = [];
|
||||
|
||||
// Collect directories to move
|
||||
for (const dir of this.dirs) {
|
||||
if (dir.startsWith(oldPath + '/')) {
|
||||
const relativePath = dir.slice(oldPath.length);
|
||||
itemsToMove.push({
|
||||
oldPath: dir,
|
||||
newPath: newPath + relativePath,
|
||||
isDir: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Collect files to move
|
||||
for (const file of this.files.keys()) {
|
||||
if (file.startsWith(oldPath + '/')) {
|
||||
const relativePath = file.slice(oldPath.length);
|
||||
itemsToMove.push({
|
||||
oldPath: file,
|
||||
newPath: newPath + relativePath,
|
||||
isDir: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Move all items
|
||||
for (const item of itemsToMove) {
|
||||
if (item.isDir) {
|
||||
this.dirs.delete(item.oldPath);
|
||||
this.dirs.add(item.newPath);
|
||||
} else {
|
||||
const content = this.files.get(item.oldPath);
|
||||
this.files.delete(item.oldPath);
|
||||
this.files.set(item.newPath, content!);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async lstat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean; mtimeMs?: number }> {
|
||||
return this.stat(path);
|
||||
}
|
||||
}
|
||||
|
||||
describe('ProjectsManager', () => {
|
||||
let fs: MockFS;
|
||||
let fs: JSRuntimeFS;
|
||||
let git: Git;
|
||||
let nostr: NPool;
|
||||
let projectsManager: ProjectsManager;
|
||||
|
||||
beforeEach(() => {
|
||||
fs = new MockFS();
|
||||
projectsManager = new ProjectsManager(fs as unknown as import('./JSRuntime').JSRuntimeFS);
|
||||
fs = new MockFS() as unknown as JSRuntimeFS;
|
||||
nostr = createMockNostr();
|
||||
git = new Git({ fs, nostr });
|
||||
projectsManager = new ProjectsManager({ fs, git });
|
||||
});
|
||||
|
||||
describe('getProjects', () => {
|
||||
@@ -261,4 +362,68 @@ describe('ProjectsManager', () => {
|
||||
expect(project.id).toBe('new-project');
|
||||
});
|
||||
});
|
||||
|
||||
describe('renameProject', () => {
|
||||
it('should rename a project directory', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create a project
|
||||
await fs.mkdir('/projects/old-name');
|
||||
await fs.writeFile('/projects/old-name/package.json', '{}');
|
||||
|
||||
// Verify the project exists
|
||||
const originalProject = await projectsManager.getProject('old-name');
|
||||
expect(originalProject).not.toBeNull();
|
||||
|
||||
// Rename the project
|
||||
const renamedProject = await projectsManager.renameProject('old-name', 'new-name');
|
||||
|
||||
// Verify the renamed project
|
||||
expect(renamedProject.id).toBe('new-name');
|
||||
expect(renamedProject.name).toBe('new-name');
|
||||
expect(renamedProject.path).toBe('/projects/new-name');
|
||||
|
||||
// Verify old project no longer exists
|
||||
const oldProject = await projectsManager.getProject('old-name');
|
||||
expect(oldProject).toBeNull();
|
||||
|
||||
// Verify new project exists
|
||||
const newProject = await projectsManager.getProject('new-name');
|
||||
expect(newProject).not.toBeNull();
|
||||
expect(newProject?.id).toBe('new-name');
|
||||
});
|
||||
|
||||
it('should throw error when old project does not exist', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
await expect(projectsManager.renameProject('non-existent', 'new-name'))
|
||||
.rejects.toThrow('Project with ID "non-existent" does not exist');
|
||||
});
|
||||
|
||||
it('should throw error when new project name already exists', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create two projects
|
||||
await fs.mkdir('/projects/project-1');
|
||||
await fs.mkdir('/projects/project-2');
|
||||
|
||||
await expect(projectsManager.renameProject('project-1', 'project-2'))
|
||||
.rejects.toThrow('Project with ID "project-2" already exists');
|
||||
});
|
||||
|
||||
it('should validate and normalize project names', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create a project
|
||||
await fs.mkdir('/projects/old-name');
|
||||
|
||||
// Try to rename with invalid characters
|
||||
await expect(projectsManager.renameProject('old-name', 'New Name With Spaces'))
|
||||
.rejects.toThrow('Project name must contain only lowercase letters, numbers, and hyphens');
|
||||
|
||||
// Try to rename with empty name
|
||||
await expect(projectsManager.renameProject('old-name', ''))
|
||||
.rejects.toThrow('Project name cannot be empty');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,6 @@ import JSZip from 'jszip';
|
||||
import { Git } from '@/lib/git';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
|
||||
|
||||
// Polyfill Buffer for browser
|
||||
if (typeof window !== 'undefined') {
|
||||
(window as { Buffer?: typeof Buffer }).Buffer = Buffer;
|
||||
@@ -19,14 +18,19 @@ export interface Project {
|
||||
lastModified: Date;
|
||||
}
|
||||
|
||||
export interface ProjectsManagerOptions {
|
||||
fs: JSRuntimeFS;
|
||||
git: Git;
|
||||
}
|
||||
|
||||
export class ProjectsManager {
|
||||
fs: JSRuntimeFS;
|
||||
git: Git;
|
||||
dir: string;
|
||||
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
this.fs = fs;
|
||||
this.git = new Git(fs, 'https://cors.isomorphic-git.org');
|
||||
constructor(options: ProjectsManagerOptions) {
|
||||
this.fs = options.fs;
|
||||
this.git = options.git;
|
||||
this.dir = '/projects';
|
||||
}
|
||||
|
||||
@@ -281,7 +285,7 @@ export class ProjectsManager {
|
||||
|
||||
await this.fs.mkdir(projectPath);
|
||||
|
||||
// Clone the repository
|
||||
// Clone the repository (Git class now handles Nostr URIs automatically)
|
||||
await this.git.clone({
|
||||
dir: projectPath,
|
||||
url: repoUrl,
|
||||
@@ -438,6 +442,50 @@ export class ProjectsManager {
|
||||
await this.deleteDirectory(projectPath);
|
||||
}
|
||||
|
||||
async renameProject(oldId: string, newId: string): Promise<Project> {
|
||||
// Validate that the old project exists
|
||||
const oldProject = await this.getProject(oldId);
|
||||
if (!oldProject) {
|
||||
throw new Error(`Project with ID "${oldId}" does not exist`);
|
||||
}
|
||||
|
||||
// Validate that the new ID doesn't already exist
|
||||
if (await this.projectExists(newId)) {
|
||||
throw new Error(`Project with ID "${newId}" already exists`);
|
||||
}
|
||||
|
||||
// Validate the new ID format (same rules as generateUniqueProjectId)
|
||||
const validatedNewId = newId
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
|
||||
if (validatedNewId !== newId) {
|
||||
throw new Error(`Project name must contain only lowercase letters, numbers, and hyphens`);
|
||||
}
|
||||
|
||||
if (!validatedNewId) {
|
||||
throw new Error(`Project name cannot be empty`);
|
||||
}
|
||||
|
||||
const oldPath = `${this.dir}/${oldId}`;
|
||||
const newPath = `${this.dir}/${newId}`;
|
||||
|
||||
// Rename the directory
|
||||
await this.fs.rename(oldPath, newPath);
|
||||
|
||||
// Return the updated project object
|
||||
const stats = await this.fs.stat(newPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
return {
|
||||
id: newId,
|
||||
name: this.formatProjectName(newId),
|
||||
path: newPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
private async deleteDirectory(dirPath: string): Promise<void> {
|
||||
const files = await this.fs.readdir(dirPath);
|
||||
|
||||
|
||||
@@ -25,12 +25,13 @@ const mockFS: JSRuntimeFS = {
|
||||
describe('SessionManager', () => {
|
||||
let sessionManager: SessionManager;
|
||||
const mockAISettings = {
|
||||
providers: {
|
||||
'test-provider': {
|
||||
providers: [
|
||||
{
|
||||
id: 'test-provider',
|
||||
baseURL: 'https://api.test.com',
|
||||
apiKey: 'test-key'
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
|
||||
+66
-27
@@ -5,6 +5,9 @@ import { parseProviderModel } from './parseProviderModel';
|
||||
import { createAIClient } from './ai-client';
|
||||
import type { Tool } from './tools/Tool';
|
||||
import type { NUser } from '@nostrify/react/login';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import { makeSystemPrompt } from './system';
|
||||
import { NostrMetadata } from '@nostrify/nostrify';
|
||||
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
||||
role: 'assistant';
|
||||
@@ -17,7 +20,6 @@ export interface SessionState {
|
||||
projectId: string;
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
customTools: Record<string, Tool<unknown>>;
|
||||
systemPrompt?: string;
|
||||
maxSteps?: number;
|
||||
messages: AIMessage[];
|
||||
streamingMessage?: {
|
||||
@@ -52,15 +54,15 @@ export class SessionManager {
|
||||
private sessions = new Map<string, SessionState>();
|
||||
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
|
||||
private fs: JSRuntimeFS;
|
||||
private aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string; nostr?: boolean }> };
|
||||
private aiSettings: { providers: AIProvider[] };
|
||||
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
|
||||
private getCurrentUser?: () => NUser | undefined;
|
||||
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
|
||||
|
||||
constructor(
|
||||
fs: JSRuntimeFS,
|
||||
aiSettings: { providers: Record<string, { baseURL: string; apiKey?: string; nostr?: boolean }> },
|
||||
aiSettings: { providers: AIProvider[] },
|
||||
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
|
||||
getCurrentUser?: () => NUser | undefined
|
||||
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
|
||||
) {
|
||||
this.fs = fs;
|
||||
this.aiSettings = aiSettings;
|
||||
@@ -75,7 +77,6 @@ export class SessionManager {
|
||||
projectId: string,
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>,
|
||||
customTools: Record<string, Tool<unknown>>,
|
||||
systemPrompt?: string,
|
||||
maxSteps?: number
|
||||
): Promise<SessionState> {
|
||||
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
||||
@@ -97,7 +98,6 @@ export class SessionManager {
|
||||
projectId,
|
||||
tools,
|
||||
customTools,
|
||||
systemPrompt,
|
||||
maxSteps,
|
||||
isLoading: false,
|
||||
lastActivity: new Date(),
|
||||
@@ -113,7 +113,6 @@ export class SessionManager {
|
||||
session.tools = tools;
|
||||
|
||||
session.customTools = customTools;
|
||||
session.systemPrompt = systemPrompt;
|
||||
session.maxSteps = maxSteps;
|
||||
|
||||
this.sessions.set(projectId, session);
|
||||
@@ -179,6 +178,7 @@ export class SessionManager {
|
||||
* Start AI generation for a session
|
||||
*/
|
||||
async startGeneration(projectId: string, providerModel: string): Promise<void> {
|
||||
console.log('Starting AI generation for project:', projectId, 'with model:', providerModel);
|
||||
let session = this.sessions.get(projectId);
|
||||
|
||||
if (!session) {
|
||||
@@ -202,12 +202,12 @@ export class SessionManager {
|
||||
try {
|
||||
// Parse provider and model
|
||||
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
|
||||
const connectionConfig = parsed.connection;
|
||||
const modelName = parsed.model;
|
||||
const provider = parsed.provider;
|
||||
const model = parsed.model;
|
||||
|
||||
// Initialize OpenAI client
|
||||
const currentUser = this.getCurrentUser?.();
|
||||
const openai = createAIClient(connectionConfig, currentUser);
|
||||
const { user, metadata } = this.getCurrentUser?.() ?? {};
|
||||
const openai = createAIClient(provider, user);
|
||||
|
||||
let stepCount = 0;
|
||||
const maxSteps = session.maxSteps || 50;
|
||||
@@ -229,14 +229,25 @@ export class SessionManager {
|
||||
tool_calls: undefined
|
||||
};
|
||||
|
||||
const systemPrompt = await makeSystemPrompt({
|
||||
cwd: `/projects/${projectId}`,
|
||||
fs: this.fs,
|
||||
mode: "agent",
|
||||
name: "Shakespeare",
|
||||
profession: "software extraordinaire",
|
||||
tools: Object.values(session.tools),
|
||||
user,
|
||||
metadata,
|
||||
});
|
||||
|
||||
// Prepare messages for AI
|
||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = session.systemPrompt
|
||||
? [{ role: 'system', content: session.systemPrompt }, ...session.messages]
|
||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = systemPrompt
|
||||
? [{ role: 'system', content: systemPrompt }, ...session.messages]
|
||||
: session.messages;
|
||||
|
||||
// Prepare completion options
|
||||
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||
model: modelName,
|
||||
model,
|
||||
messages,
|
||||
tools: session.tools && Object.keys(session.tools).length > 0 ? Object.values(session.tools) : undefined,
|
||||
tool_choice: session.tools && Object.keys(session.tools).length > 0 ? 'auto' : undefined,
|
||||
@@ -257,12 +268,12 @@ export class SessionManager {
|
||||
let finishReason: string | null = null;
|
||||
|
||||
// Process the stream
|
||||
let usage: { prompt_tokens: number; completion_tokens: number } | undefined;
|
||||
let usage: { prompt_tokens: number; completion_tokens: number; cost?: number } | undefined;
|
||||
for await (const chunk of stream) {
|
||||
// Check if session was cancelled
|
||||
if (!session.isLoading) break;
|
||||
|
||||
const delta = chunk.choices[0]?.delta;
|
||||
const delta = chunk.choices[0]?.delta as OpenAI.Chat.Completions.ChatCompletionChunk.Choice.Delta | undefined;
|
||||
|
||||
if (delta?.content) {
|
||||
accumulatedContent += delta.content;
|
||||
@@ -273,11 +284,18 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
// Handle reasoning content if present (some providers may include this)
|
||||
const deltaWithReasoning = delta as { reasoning_content?: string };
|
||||
if (deltaWithReasoning?.reasoning_content) {
|
||||
accumulatedReasoningContent += deltaWithReasoning.reasoning_content;
|
||||
let reasoningContent: string | undefined;
|
||||
// LiteLLM, Z.ai, etc. use 'reasoning_content'
|
||||
if (delta && 'reasoning_content' in delta && typeof delta.reasoning_content === 'string') {
|
||||
reasoningContent = delta.reasoning_content;
|
||||
// ollama uses 'reasoning'
|
||||
} else if (delta && 'reasoning' in delta && typeof delta.reasoning === 'string') {
|
||||
reasoningContent = delta.reasoning;
|
||||
}
|
||||
if (reasoningContent) {
|
||||
accumulatedReasoningContent += reasoningContent;
|
||||
if (session.streamingMessage) {
|
||||
session.streamingMessage.reasoning_content += deltaWithReasoning.reasoning_content;
|
||||
session.streamingMessage.reasoning_content += reasoningContent;
|
||||
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
|
||||
}
|
||||
}
|
||||
@@ -311,13 +329,25 @@ export class SessionManager {
|
||||
|
||||
// Capture usage data if available (some providers include it in the final chunk)
|
||||
if (chunk.usage) {
|
||||
const cost = 'cost' in chunk.usage && typeof chunk.usage.cost === 'number'
|
||||
? chunk.usage.cost
|
||||
: undefined;
|
||||
|
||||
usage = {
|
||||
prompt_tokens: chunk.usage.prompt_tokens || 0,
|
||||
completion_tokens: chunk.usage.completion_tokens || 0
|
||||
completion_tokens: chunk.usage.completion_tokens || 0,
|
||||
cost,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Fix tool calls with empty arguments
|
||||
for (const toolCall of accumulatedToolCalls) {
|
||||
if (toolCall.type === 'function') {
|
||||
toolCall.function.arguments = toolCall.function.arguments || '{}';
|
||||
}
|
||||
}
|
||||
|
||||
// Create final assistant message
|
||||
const assistantMessage: AIMessage = {
|
||||
role: 'assistant',
|
||||
@@ -375,7 +405,9 @@ export class SessionManager {
|
||||
console.error('AI generation error:', error);
|
||||
|
||||
// Handle different error types
|
||||
if (error?.name === 'AbortError') return; // User cancelled
|
||||
if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
|
||||
return; // User cancelled
|
||||
}
|
||||
|
||||
let errorMessage = 'Sorry, I encountered an unexpected error. Please try again.';
|
||||
const errorMsg = error?.message || '';
|
||||
@@ -453,20 +485,28 @@ export class SessionManager {
|
||||
/**
|
||||
* Update session cost and context usage based on usage data
|
||||
*/
|
||||
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number }, providerModel: string): void {
|
||||
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): void {
|
||||
if (!this.getProviderModels) return;
|
||||
|
||||
const session = this.sessions.get(projectId);
|
||||
if (!session) return;
|
||||
|
||||
// If provider gives direct cost, use it
|
||||
if (typeof usage.cost === 'number') {
|
||||
session.totalCost = (session.totalCost || 0) + usage.cost;
|
||||
this.emit('costUpdated', projectId, session.totalCost);
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, get the cost from the models endpoint
|
||||
try {
|
||||
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
|
||||
const modelName = parsed.model;
|
||||
const providerName = parsed.provider;
|
||||
const provider = parsed.provider;
|
||||
|
||||
// Find the model in provider models to get pricing and context length
|
||||
const models = this.getProviderModels();
|
||||
const model = models.find(m => m.id === modelName && m.provider === providerName);
|
||||
const model = models.find(m => m.id === modelName && m.provider === provider.id);
|
||||
|
||||
// Update input tokens for context usage tracking
|
||||
session.lastInputTokens = usage.prompt_tokens;
|
||||
@@ -483,7 +523,6 @@ export class SessionManager {
|
||||
|
||||
// Update session total cost
|
||||
session.totalCost = (session.totalCost || 0) + requestCost;
|
||||
|
||||
this.emit('costUpdated', projectId, session.totalCost);
|
||||
} catch (error) {
|
||||
console.warn('Failed to calculate session cost:', error);
|
||||
|
||||
+30
-8
@@ -1,30 +1,52 @@
|
||||
import OpenAI from 'openai';
|
||||
import { NIP98Client } from '@nostrify/nostrify';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
import type { NUser } from '@nostrify/react/login';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
/**
|
||||
* Create an OpenAI client instance with the appropriate configuration.
|
||||
* If the connection requires Nostr authentication (NIP-98), it will use
|
||||
* the NIP98Client for authenticated requests.
|
||||
*/
|
||||
export function createAIClient(connection: AIConnection, user?: NUser): OpenAI {
|
||||
export function createAIClient(provider: AIProvider, user?: NUser): OpenAI {
|
||||
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
|
||||
baseURL: connection.baseURL,
|
||||
apiKey: connection.apiKey ?? '',
|
||||
baseURL: provider.baseURL,
|
||||
apiKey: provider.apiKey ?? '',
|
||||
dangerouslyAllowBrowser: true,
|
||||
defaultHeaders: {
|
||||
// https://openrouter.ai/docs/app-attribution
|
||||
'HTTP-Referer': 'https://shakespeare.diy',
|
||||
'X-Title': 'Shakespeare',
|
||||
},
|
||||
};
|
||||
|
||||
let openai: OpenAI;
|
||||
|
||||
// If Nostr authentication is required and we have a user, use NIP-98
|
||||
if (connection.nostr && user?.signer) {
|
||||
if (provider.nostr && user?.signer) {
|
||||
const nip98Client = new NIP98Client({ signer: user.signer });
|
||||
|
||||
return new OpenAI({
|
||||
openai = new OpenAI({
|
||||
...baseConfig,
|
||||
fetch: (input, init) => nip98Client.fetch(input, init),
|
||||
});
|
||||
} else {
|
||||
// Standard OpenAI client
|
||||
openai = new OpenAI(baseConfig);
|
||||
}
|
||||
|
||||
// Standard OpenAI client
|
||||
return new OpenAI(baseConfig);
|
||||
const createCompletion: typeof openai.chat.completions.create
|
||||
= openai.chat.completions.create.bind(openai.chat.completions);
|
||||
|
||||
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
||||
// OpenRouter usage accounting
|
||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||
if (provider.id === 'openrouter') {
|
||||
(body as { usage?: { include?: boolean } }).usage = { include: true };
|
||||
}
|
||||
|
||||
return createCompletion(body, options);
|
||||
}) as typeof createCompletion;
|
||||
|
||||
return openai;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import OpenAI from "openai";
|
||||
|
||||
export function assistantContentEmpty(
|
||||
content: OpenAI.ChatCompletionAssistantMessageParam['content'],
|
||||
): boolean {
|
||||
if (!content) return true;
|
||||
const text: string[] = [];
|
||||
|
||||
if (typeof content === 'string') {
|
||||
text.push(content);
|
||||
} else if (Array.isArray(content)) {
|
||||
for (const part of content) {
|
||||
if (part.type === 'text') {
|
||||
text.push(part.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = text.join('\n\n');
|
||||
return !result.trim();
|
||||
}
|
||||
@@ -78,15 +78,16 @@ Change the current working directory.
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
cd # Go to project root
|
||||
cd # Stay in current directory
|
||||
cd src/ # Change to src directory
|
||||
cd .. # Go to parent directory
|
||||
cd . # Stay in current directory
|
||||
cd /projects/my-project # Change to absolute path
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Changes working directory for subsequent commands
|
||||
- Supports relative paths (., .., subdirectories)
|
||||
- Supports both relative and absolute paths
|
||||
- Validates target exists and is a directory
|
||||
- Updates shell working directory state
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -98,11 +98,25 @@ describe('CdCommand', () => {
|
||||
expect(result.stderr).toContain('Not a directory');
|
||||
});
|
||||
|
||||
it('should reject absolute paths', async () => {
|
||||
it('should handle absolute paths to non-existent directories', async () => {
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
|
||||
|
||||
const result = await cdCommand.execute(['/absolute/path'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('absolute paths are not supported');
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
});
|
||||
|
||||
it('should handle absolute paths to existing directories', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
});
|
||||
|
||||
const result = await cdCommand.execute(['/projects/my-project'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.newCwd).toBe('/projects/my-project');
|
||||
});
|
||||
|
||||
it('should reject too many arguments', async () => {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { join, resolve, dirname } from "@std/path";
|
||||
import { join, resolve, dirname } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
import { isAbsolutePath } from "../security";
|
||||
|
||||
/**
|
||||
* Implementation of the 'cd' command
|
||||
@@ -31,20 +32,19 @@ export class CdCommand implements ShellCommand {
|
||||
return createErrorResult(`${this.name}: too many arguments`);
|
||||
}
|
||||
|
||||
// Handle absolute paths
|
||||
if (targetPath.startsWith('/') || targetPath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(targetPath)) {
|
||||
return createErrorResult(`${this.name}: absolute paths are not supported: ${targetPath}`);
|
||||
}
|
||||
|
||||
// Resolve the new path
|
||||
// Handle both absolute and relative paths
|
||||
let newCwd: string;
|
||||
if (targetPath === '.') {
|
||||
|
||||
if (isAbsolutePath(targetPath)) {
|
||||
// Absolute path - use it directly
|
||||
newCwd = targetPath;
|
||||
} else if (targetPath === '.') {
|
||||
// Current directory
|
||||
newCwd = cwd;
|
||||
} else if (targetPath === '..') {
|
||||
// Parent directory
|
||||
const parentPath = dirname(cwd);
|
||||
// Don't allow going above the project root
|
||||
// Don't allow going above the filesystem root
|
||||
if (parentPath === cwd) {
|
||||
return createErrorResult(`${this.name}: cannot access parent directory: Permission denied`);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join, dirname, basename } from "@std/path";
|
||||
import { join, dirname, basename } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -76,7 +76,7 @@ describe('CurlCommand', () => {
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('Hello World');
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://corsproxy.io/?url=https%3A%2F%2Fexample.com%2F', expect.objectContaining({
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://proxy.shakespeare.diy/?url=https%3A%2F%2Fexample.com%2F', expect.objectContaining({
|
||||
method: 'GET',
|
||||
headers: expect.objectContaining({
|
||||
'User-Agent': 'curl/8.0.0 (compatible; JavaScript fetch)'
|
||||
@@ -103,7 +103,7 @@ describe('CurlCommand', () => {
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('{"success": true}');
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://corsproxy.io/?url=https%3A%2F%2Fexample.com%2Fapi', expect.objectContaining({
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://proxy.shakespeare.diy/?url=https%3A%2F%2Fexample.com%2Fapi', expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: '{"name": "test"}',
|
||||
headers: expect.objectContaining({
|
||||
@@ -131,7 +131,7 @@ describe('CurlCommand', () => {
|
||||
], '/test');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://corsproxy.io/?url=https%3A%2F%2Fexample.com%2F', expect.objectContaining({
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://proxy.shakespeare.diy/?url=https%3A%2F%2Fexample.com%2F', expect.objectContaining({
|
||||
headers: expect.objectContaining({
|
||||
'Authorization': 'Bearer token123',
|
||||
'Content-Type': 'application/json',
|
||||
@@ -245,7 +245,7 @@ describe('CurlCommand', () => {
|
||||
], '/test');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://corsproxy.io/?url=https%3A%2F%2Fexample.com%2F', expect.objectContaining({
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://proxy.shakespeare.diy/?url=https%3A%2F%2Fexample.com%2F', expect.objectContaining({
|
||||
method: 'DELETE',
|
||||
headers: expect.objectContaining({
|
||||
'User-Agent': 'curl/8.0.0 (compatible; JavaScript fetch)'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
@@ -62,7 +62,7 @@ export class CurlCommand implements ShellCommand {
|
||||
|
||||
// Proxy the URL through CorsProxy
|
||||
const originalUrl = url.toString();
|
||||
const proxiedUrl = `https://corsproxy.io/?url=${encodeURIComponent(originalUrl)}`;
|
||||
const proxiedUrl = `https://proxy.shakespeare.diy/?url=${encodeURIComponent(originalUrl)}`;
|
||||
|
||||
// Prepare request
|
||||
const requestInit: RequestInit = {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join, basename } from "@std/path";
|
||||
import { join, basename } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -40,7 +40,16 @@ describe('GitCommand', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
const git = new Git(mockFS);
|
||||
const mockNostr = {
|
||||
req: vi.fn(),
|
||||
query: vi.fn(),
|
||||
event: vi.fn(),
|
||||
group: vi.fn(),
|
||||
relay: vi.fn(),
|
||||
relays: new Map(),
|
||||
close: vi.fn(),
|
||||
} as unknown as import('@nostrify/nostrify').NPool;
|
||||
const git = new Git({ fs: mockFS, nostr: mockNostr });
|
||||
gitCommand = new GitCommand({ git, fs: mockFS, cwd: testCwd });
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../../JSRuntime";
|
||||
import type { ShellCommandResult } from "../ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "../ShellCommand";
|
||||
|
||||
@@ -138,7 +138,6 @@ export class GitConfigCommand implements GitSubcommand {
|
||||
private async setConfig(key: string, value: string, global: boolean): Promise<ShellCommandResult> {
|
||||
try {
|
||||
await this.git.setConfig({
|
||||
|
||||
dir: global ? undefined : this.pwd,
|
||||
path: key,
|
||||
value: value,
|
||||
|
||||
+177
-41
@@ -29,9 +29,12 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
|
||||
const { commits, paths } = this.parseArgs(args);
|
||||
const { commits, paths, options } = this.parseArgs(args);
|
||||
|
||||
if (commits.length === 0) {
|
||||
if (options.cached || options.staged) {
|
||||
// Show staged changes (index vs HEAD)
|
||||
return await this.showStagedDiff(paths);
|
||||
} else if (commits.length === 0) {
|
||||
// Show working directory changes vs index
|
||||
return await this.showWorkingDirectoryDiff(paths);
|
||||
} else if (commits.length === 1) {
|
||||
@@ -83,78 +86,110 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
try {
|
||||
// Get status to find changed files
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
// Filter for modified files in working directory
|
||||
const modifiedFiles = statusMatrix.filter(([filepath, headStatus, workdirStatus, stageStatus]) => {
|
||||
const isModified = workdirStatus === 1 && stageStatus === 1 && headStatus !== workdirStatus;
|
||||
// Filter for files with working directory changes
|
||||
// Status matrix: [filepath, headStatus, workdirStatus, stageStatus]
|
||||
// 0 = absent, 1 = present, 2 = modified
|
||||
const changedFiles = statusMatrix.filter(([filepath, _headStatus, workdirStatus, stageStatus]) => {
|
||||
// Show files that differ between index and working directory
|
||||
const hasWorkingDirChanges = stageStatus !== workdirStatus;
|
||||
|
||||
if (paths.length > 0) {
|
||||
return isModified && paths.some(path => filepath.includes(path));
|
||||
return hasWorkingDirChanges && paths.some(path => filepath.includes(path));
|
||||
}
|
||||
return isModified;
|
||||
return hasWorkingDirChanges;
|
||||
});
|
||||
|
||||
if (modifiedFiles.length === 0) {
|
||||
if (changedFiles.length === 0) {
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
const diffLines: string[] = [];
|
||||
|
||||
for (const [filepath] of modifiedFiles) {
|
||||
for (const [filepath, _headStatus, workdirStatus, stageStatus] of changedFiles) {
|
||||
try {
|
||||
// Get file content from HEAD
|
||||
let headContent = '';
|
||||
try {
|
||||
const headBlob = await this.git.readBlob({
|
||||
|
||||
dir: this.pwd,
|
||||
oid: 'HEAD',
|
||||
filepath,
|
||||
});
|
||||
headContent = new TextDecoder().decode(headBlob.blob);
|
||||
} catch {
|
||||
// File might be new
|
||||
// Get staged content (index)
|
||||
let stagedContent = '';
|
||||
if (stageStatus === 1) {
|
||||
try {
|
||||
// Try to read from HEAD first as a fallback for staged content
|
||||
const headBlob = await this.git.readBlob({
|
||||
dir: this.pwd,
|
||||
oid: 'HEAD',
|
||||
filepath,
|
||||
});
|
||||
stagedContent = new TextDecoder().decode(headBlob.blob);
|
||||
} catch {
|
||||
// File might be new
|
||||
stagedContent = '';
|
||||
}
|
||||
}
|
||||
|
||||
// Get file content from working directory
|
||||
// Get working directory content
|
||||
let workdirContent = '';
|
||||
try {
|
||||
workdirContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
|
||||
} catch {
|
||||
// File might be deleted
|
||||
if (workdirStatus === 1) {
|
||||
try {
|
||||
workdirContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
|
||||
} catch {
|
||||
// File might be deleted
|
||||
workdirContent = '';
|
||||
}
|
||||
}
|
||||
|
||||
// Simple diff representation
|
||||
diffLines.push(`diff --git a/${filepath} b/${filepath}`);
|
||||
diffLines.push(`index ${this.getShortHash(headContent)}..${this.getShortHash(workdirContent)} 100644`);
|
||||
diffLines.push(`--- a/${filepath}`);
|
||||
diffLines.push(`+++ b/${filepath}`);
|
||||
// Skip if contents are identical
|
||||
if (stagedContent === workdirContent) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Show a simplified diff
|
||||
const headLines = headContent.split('\n');
|
||||
// Generate diff header
|
||||
diffLines.push(`diff --git a/${filepath} b/${filepath}`);
|
||||
|
||||
if (stageStatus === 0 && workdirStatus === 1) {
|
||||
// New untracked file
|
||||
diffLines.push('new file mode 100644');
|
||||
diffLines.push(`index 0000000..${this.getShortHash(workdirContent)}`);
|
||||
diffLines.push('--- /dev/null');
|
||||
diffLines.push(`+++ b/${filepath}`);
|
||||
} else if (stageStatus === 1 && workdirStatus === 0) {
|
||||
// Deleted file
|
||||
diffLines.push('deleted file mode 100644');
|
||||
diffLines.push(`index ${this.getShortHash(stagedContent)}..0000000`);
|
||||
diffLines.push(`--- a/${filepath}`);
|
||||
diffLines.push('+++ /dev/null');
|
||||
} else {
|
||||
// Modified file
|
||||
diffLines.push(`index ${this.getShortHash(stagedContent)}..${this.getShortHash(workdirContent)} 100644`);
|
||||
diffLines.push(`--- a/${filepath}`);
|
||||
diffLines.push(`+++ b/${filepath}`);
|
||||
}
|
||||
|
||||
// Generate simple unified diff
|
||||
const stagedLines = stagedContent.split('\n');
|
||||
const workdirLines = workdirContent.split('\n');
|
||||
|
||||
diffLines.push(`@@ -1,${headLines.length} +1,${workdirLines.length} @@`);
|
||||
// Simple hunk header
|
||||
diffLines.push(`@@ -1,${stagedLines.length} +1,${workdirLines.length} @@`);
|
||||
|
||||
// Show removed lines
|
||||
for (const line of headLines) {
|
||||
if (!workdirLines.includes(line)) {
|
||||
// Show all old lines as removed
|
||||
for (const line of stagedLines) {
|
||||
if (line || stagedLines.length > 0) {
|
||||
diffLines.push(`-${line}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Show added lines
|
||||
// Show all new lines as added
|
||||
for (const line of workdirLines) {
|
||||
if (!headLines.includes(line)) {
|
||||
if (line || workdirLines.length > 0) {
|
||||
diffLines.push(`+${line}`);
|
||||
}
|
||||
}
|
||||
|
||||
diffLines.push('');
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// Skip files that can't be diffed
|
||||
console.warn(`Failed to diff ${filepath}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,6 +239,107 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
return createErrorResult('Commit range diff is not implemented in this git command');
|
||||
}
|
||||
|
||||
private async showStagedDiff(paths: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Get status to find staged files
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
// Filter for files with staged changes (index differs from HEAD)
|
||||
const stagedFiles = statusMatrix.filter(([filepath, headStatus, _workdirStatus, stageStatus]) => {
|
||||
const hasStagedChanges = headStatus !== stageStatus;
|
||||
|
||||
if (paths.length > 0) {
|
||||
return hasStagedChanges && paths.some(path => filepath.includes(path));
|
||||
}
|
||||
return hasStagedChanges;
|
||||
});
|
||||
|
||||
if (stagedFiles.length === 0) {
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
const diffLines: string[] = [];
|
||||
|
||||
for (const [filepath, headStatus, _workdirStatus, stageStatus] of stagedFiles) {
|
||||
try {
|
||||
// Get HEAD content
|
||||
let headContent = '';
|
||||
if (headStatus === 1) {
|
||||
try {
|
||||
const headBlob = await this.git.readBlob({
|
||||
dir: this.pwd,
|
||||
oid: 'HEAD',
|
||||
filepath,
|
||||
});
|
||||
headContent = new TextDecoder().decode(headBlob.blob);
|
||||
} catch {
|
||||
headContent = '';
|
||||
}
|
||||
}
|
||||
|
||||
// Get staged content (approximated by working directory for now)
|
||||
let stagedContent = '';
|
||||
if (stageStatus === 1) {
|
||||
try {
|
||||
stagedContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
|
||||
} catch {
|
||||
stagedContent = '';
|
||||
}
|
||||
}
|
||||
|
||||
// Generate diff header
|
||||
diffLines.push(`diff --git a/${filepath} b/${filepath}`);
|
||||
|
||||
if (headStatus === 0 && stageStatus === 1) {
|
||||
// New file staged
|
||||
diffLines.push('new file mode 100644');
|
||||
diffLines.push(`index 0000000..${this.getShortHash(stagedContent)}`);
|
||||
diffLines.push('--- /dev/null');
|
||||
diffLines.push(`+++ b/${filepath}`);
|
||||
} else if (headStatus === 1 && stageStatus === 0) {
|
||||
// File deleted from stage
|
||||
diffLines.push('deleted file mode 100644');
|
||||
diffLines.push(`index ${this.getShortHash(headContent)}..0000000`);
|
||||
diffLines.push(`--- a/${filepath}`);
|
||||
diffLines.push('+++ /dev/null');
|
||||
} else {
|
||||
// Modified file
|
||||
diffLines.push(`index ${this.getShortHash(headContent)}..${this.getShortHash(stagedContent)} 100644`);
|
||||
diffLines.push(`--- a/${filepath}`);
|
||||
diffLines.push(`+++ b/${filepath}`);
|
||||
}
|
||||
|
||||
// Generate unified diff
|
||||
const headLines = headContent.split('\n');
|
||||
const stagedLines = stagedContent.split('\n');
|
||||
|
||||
diffLines.push(`@@ -1,${headLines.length} +1,${stagedLines.length} @@`);
|
||||
|
||||
// Show removed lines
|
||||
for (const line of headLines) {
|
||||
diffLines.push(`-${line}`);
|
||||
}
|
||||
|
||||
// Show added lines
|
||||
for (const line of stagedLines) {
|
||||
diffLines.push(`+${line}`);
|
||||
}
|
||||
|
||||
diffLines.push('');
|
||||
} catch (error) {
|
||||
console.warn(`Failed to diff staged ${filepath}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return createSuccessResult(diffLines.join('\n'));
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`Failed to show staged diff: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private getShortHash(content: string): string {
|
||||
// Simple hash for demo purposes - not a real git hash
|
||||
let hash = 0;
|
||||
|
||||
@@ -65,15 +65,6 @@ export class GitPushCommand implements GitSubcommand {
|
||||
}
|
||||
|
||||
const settings = await readGitSettings(this.fs);
|
||||
const currentCredentials = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
|
||||
// Prepare authentication if credentials are available
|
||||
const authOptions = currentCredentials ? {
|
||||
onAuth: () => ({
|
||||
username: currentCredentials.username,
|
||||
password: currentCredentials.password,
|
||||
}),
|
||||
} : {};
|
||||
|
||||
try {
|
||||
await this.git.push({
|
||||
@@ -81,7 +72,7 @@ export class GitPushCommand implements GitSubcommand {
|
||||
remote: remote,
|
||||
ref: targetBranch,
|
||||
remoteRef: targetBranch,
|
||||
...authOptions,
|
||||
onAuth: (url) => findCredentialsForRepo(url, settings.credentials),
|
||||
});
|
||||
|
||||
return createSuccessResult(`To ${remoteUrl}\n ${targetBranch} -> ${targetBranch}\n`);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { HexdumpCommand } from './hexdump';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
lstat: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
rmdir: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
readlink: vi.fn(),
|
||||
symlink: vi.fn(),
|
||||
});
|
||||
|
||||
describe('HexdumpCommand', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let command: HexdumpCommand;
|
||||
const testCwd = '/test/dir';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
command = new HexdumpCommand(mockFS);
|
||||
});
|
||||
|
||||
it('should have correct name and description', () => {
|
||||
expect(command.name).toBe('hexdump');
|
||||
expect(command.description).toBe('Display file contents in hexadecimal format');
|
||||
expect(command.usage).toBe('hexdump [-C] [-n length] [-s skip] [file...]');
|
||||
});
|
||||
|
||||
it('should show error when no file is specified', async () => {
|
||||
const result = await command.execute([], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('missing file operand');
|
||||
});
|
||||
|
||||
it('should show error for non-existent file', async () => {
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
|
||||
|
||||
const result = await command.execute(['nonexistent.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
});
|
||||
|
||||
it('should show error for directory', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
});
|
||||
|
||||
const result = await command.execute(['testdir'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Is a directory');
|
||||
});
|
||||
|
||||
it('should display hexdump in default format', async () => {
|
||||
const content = 'Hello, World!\n';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
|
||||
|
||||
const result = await command.execute(['test.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('0000000');
|
||||
expect(result.stdout).toContain('000000e'); // Final offset
|
||||
});
|
||||
|
||||
it('should display hexdump in canonical format with -C', async () => {
|
||||
const content = 'Hello, World!\n';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
|
||||
|
||||
const result = await command.execute(['-C', 'test.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('00000000');
|
||||
expect(result.stdout).toContain('|Hello, World!');
|
||||
expect(result.stdout).toContain('|'); // Should have ASCII representation
|
||||
});
|
||||
|
||||
it('should handle -n length option', async () => {
|
||||
const content = 'Hello, World!\nThis is a longer line.';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
|
||||
|
||||
const result = await command.execute(['-C', '-n', '5', 'test.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('|Hello|');
|
||||
expect(result.stdout).not.toContain('World');
|
||||
});
|
||||
|
||||
it('should handle -s skip option', async () => {
|
||||
const content = 'Hello, World!\n';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
|
||||
|
||||
const result = await command.execute(['-C', '-s', '7', 'test.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('00000007');
|
||||
expect(result.stdout).toContain('|World!');
|
||||
expect(result.stdout).not.toContain('Hello');
|
||||
});
|
||||
|
||||
it('should handle -n and -s together', async () => {
|
||||
const content = 'Hello, World!\n';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
|
||||
|
||||
const result = await command.execute(['-C', '-s', '7', '-n', '5', 'test.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('00000007');
|
||||
expect(result.stdout).toContain('|World|');
|
||||
expect(result.stdout).not.toContain('Hello');
|
||||
expect(result.stdout).not.toContain('!');
|
||||
});
|
||||
|
||||
it('should show error for invalid -n value', async () => {
|
||||
const result = await command.execute(['-n', 'invalid'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('invalid length');
|
||||
});
|
||||
|
||||
it('should show error for invalid -s value', async () => {
|
||||
const result = await command.execute(['-s', 'invalid'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('invalid skip offset');
|
||||
});
|
||||
|
||||
it('should show error for missing -n argument', async () => {
|
||||
const result = await command.execute(['-n'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('option requires an argument -- n');
|
||||
});
|
||||
|
||||
it('should show error for missing -s argument', async () => {
|
||||
const result = await command.execute(['-s'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('option requires an argument -- s');
|
||||
});
|
||||
|
||||
it('should show error for invalid option', async () => {
|
||||
const result = await command.execute(['-x'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('invalid option -- x');
|
||||
});
|
||||
|
||||
it('should handle multiple files', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile)
|
||||
.mockResolvedValueOnce(Buffer.from('ABC'))
|
||||
.mockResolvedValueOnce(Buffer.from('XYZ'));
|
||||
|
||||
const result = await command.execute(['-C', 'file1.txt', 'file2.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('==> file1.txt <==');
|
||||
expect(result.stdout).toContain('==> file2.txt <==');
|
||||
expect(result.stdout).toContain('|ABC|');
|
||||
expect(result.stdout).toContain('|XYZ|');
|
||||
});
|
||||
|
||||
it('should handle piped input', async () => {
|
||||
const input = 'Hello, World!';
|
||||
const result = await command.execute(['-C'], testCwd, input);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('00000000');
|
||||
expect(result.stdout).toContain('|Hello, World!|');
|
||||
});
|
||||
|
||||
it('should handle binary data correctly', async () => {
|
||||
// Create binary data with non-printable characters
|
||||
const binaryData = Buffer.from([0x00, 0x01, 0x02, 0x7F, 0x80, 0xFF, 0x41, 0x42, 0x43]);
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(binaryData);
|
||||
|
||||
const result = await command.execute(['-C', 'binary.dat'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('00000000');
|
||||
expect(result.stdout).toContain('00 01 02 7f 80 ff 41 42 43');
|
||||
expect(result.stdout).toContain('|......ABC|'); // Non-printable chars shown as dots
|
||||
});
|
||||
|
||||
it('should handle empty file', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(''));
|
||||
|
||||
const result = await command.execute(['-C', 'empty.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe(''); // No output for empty file
|
||||
});
|
||||
|
||||
it('should handle skip beyond file length', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from('Hi'));
|
||||
|
||||
const result = await command.execute(['-C', '-s', '10', 'short.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe(''); // No output since skip is beyond file
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,272 @@
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
/**
|
||||
* Implementation of the 'hexdump' command
|
||||
* Display file contents in hexadecimal format
|
||||
*/
|
||||
export class HexdumpCommand implements ShellCommand {
|
||||
name = 'hexdump';
|
||||
description = 'Display file contents in hexadecimal format';
|
||||
usage = 'hexdump [-C] [-n length] [-s skip] [file...]';
|
||||
|
||||
private fs: JSRuntimeFS;
|
||||
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
this.fs = fs;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
|
||||
// Parse command line options
|
||||
const options = this.parseOptions(args);
|
||||
|
||||
if (options.error) {
|
||||
return createErrorResult(options.error);
|
||||
}
|
||||
|
||||
// If input is provided (from pipe), process it
|
||||
if (input !== undefined) {
|
||||
const buffer = Buffer.from(input, 'utf8');
|
||||
const output = this.formatHexdump(buffer, options);
|
||||
return createSuccessResult(output);
|
||||
}
|
||||
|
||||
// If no files specified, show usage
|
||||
if (options.files.length === 0) {
|
||||
return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const outputs: string[] = [];
|
||||
|
||||
for (const filePath of options.files) {
|
||||
try {
|
||||
// Handle both absolute and relative paths
|
||||
let absolutePath: string;
|
||||
|
||||
if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) {
|
||||
// It's an absolute path - use it directly
|
||||
absolutePath = filePath;
|
||||
} else {
|
||||
// It's a relative path - resolve it relative to the current working directory
|
||||
absolutePath = join(cwd, filePath);
|
||||
}
|
||||
|
||||
// Check if path exists and is a file
|
||||
const stats = await this.fs.stat(absolutePath);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
return createErrorResult(`${this.name}: ${filePath}: Is a directory`);
|
||||
}
|
||||
|
||||
// Read file content as binary
|
||||
const content = await this.fs.readFile(absolutePath);
|
||||
const buffer = Buffer.from(content);
|
||||
|
||||
// Format the hexdump
|
||||
const hexOutput = this.formatHexdump(buffer, options);
|
||||
|
||||
// Add filename header if multiple files
|
||||
if (options.files.length > 1) {
|
||||
outputs.push(`==> ${filePath} <==`);
|
||||
outputs.push(hexOutput);
|
||||
} else {
|
||||
outputs.push(hexOutput);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
// Handle file not found or permission errors
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
|
||||
return createErrorResult(`${this.name}: ${filePath}: No such file or directory`);
|
||||
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
|
||||
return createErrorResult(`${this.name}: ${filePath}: Permission denied`);
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
|
||||
}
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${filePath}: Unknown error`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = outputs.join('\n');
|
||||
return createSuccessResult(result);
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse command line options
|
||||
*/
|
||||
private parseOptions(args: string[]): {
|
||||
canonical: boolean;
|
||||
length?: number;
|
||||
skip: number;
|
||||
files: string[];
|
||||
error?: string;
|
||||
} {
|
||||
const options = {
|
||||
canonical: false,
|
||||
length: undefined as number | undefined,
|
||||
skip: 0,
|
||||
files: [] as string[],
|
||||
};
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
|
||||
if (arg === '-C') {
|
||||
options.canonical = true;
|
||||
} else if (arg === '-n') {
|
||||
// Next argument should be the length
|
||||
if (i + 1 >= args.length) {
|
||||
return { ...options, error: `${this.name}: option requires an argument -- n` };
|
||||
}
|
||||
const lengthStr = args[++i];
|
||||
const length = parseInt(lengthStr, 10);
|
||||
if (isNaN(length) || length < 0) {
|
||||
return { ...options, error: `${this.name}: invalid length: ${lengthStr}` };
|
||||
}
|
||||
options.length = length;
|
||||
} else if (arg === '-s') {
|
||||
// Next argument should be the skip offset
|
||||
if (i + 1 >= args.length) {
|
||||
return { ...options, error: `${this.name}: option requires an argument -- s` };
|
||||
}
|
||||
const skipStr = args[++i];
|
||||
const skip = parseInt(skipStr, 10);
|
||||
if (isNaN(skip) || skip < 0) {
|
||||
return { ...options, error: `${this.name}: invalid skip offset: ${skipStr}` };
|
||||
}
|
||||
options.skip = skip;
|
||||
} else if (arg.startsWith('-')) {
|
||||
return { ...options, error: `${this.name}: invalid option -- ${arg.slice(1)}` };
|
||||
} else {
|
||||
// It's a filename
|
||||
options.files.push(arg);
|
||||
}
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format buffer content as hexdump
|
||||
*/
|
||||
private formatHexdump(buffer: Buffer, options: {
|
||||
canonical: boolean;
|
||||
length?: number;
|
||||
skip: number;
|
||||
}): string {
|
||||
const lines: string[] = [];
|
||||
const bytesPerLine = 16;
|
||||
|
||||
// Apply skip offset
|
||||
const startOffset = options.skip;
|
||||
if (startOffset >= buffer.length) {
|
||||
return ''; // Nothing to display
|
||||
}
|
||||
|
||||
// Apply length limit
|
||||
let endOffset = buffer.length;
|
||||
if (options.length !== undefined) {
|
||||
endOffset = Math.min(startOffset + options.length, buffer.length);
|
||||
}
|
||||
|
||||
for (let offset = startOffset; offset < endOffset; offset += bytesPerLine) {
|
||||
const lineEnd = Math.min(offset + bytesPerLine, endOffset);
|
||||
const lineBytes = buffer.subarray(offset, lineEnd);
|
||||
|
||||
if (options.canonical) {
|
||||
// Canonical format (-C): address, hex bytes, ASCII
|
||||
lines.push(this.formatCanonicalLine(offset, lineBytes));
|
||||
} else {
|
||||
// Default format: address followed by 16-bit words in hex
|
||||
lines.push(this.formatDefaultLine(offset, lineBytes));
|
||||
}
|
||||
}
|
||||
|
||||
// Add final offset line if we have data
|
||||
if (endOffset > startOffset) {
|
||||
const finalOffset = endOffset;
|
||||
lines.push(this.formatOffsetLine(finalOffset));
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a line in canonical format (-C option)
|
||||
*/
|
||||
private formatCanonicalLine(offset: number, bytes: Buffer): string {
|
||||
const addressStr = offset.toString(16).padStart(8, '0');
|
||||
|
||||
// Format hex bytes (2 groups of 8 bytes each)
|
||||
const group1: string[] = [];
|
||||
const group2: string[] = [];
|
||||
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const hexByte = i < bytes.length
|
||||
? bytes[i].toString(16).padStart(2, '0')
|
||||
: ' ';
|
||||
|
||||
if (i < 8) {
|
||||
group1.push(hexByte);
|
||||
} else {
|
||||
group2.push(hexByte);
|
||||
}
|
||||
}
|
||||
|
||||
const hexStr = group1.join(' ') + ' ' + group2.join(' ');
|
||||
|
||||
// Format ASCII representation
|
||||
let asciiStr = '';
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
const byte = bytes[i];
|
||||
if (byte >= 32 && byte <= 126) {
|
||||
// Printable ASCII character
|
||||
asciiStr += String.fromCharCode(byte);
|
||||
} else {
|
||||
// Non-printable character
|
||||
asciiStr += '.';
|
||||
}
|
||||
}
|
||||
|
||||
return `${addressStr} ${hexStr} |${asciiStr}|`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a line in default format
|
||||
*/
|
||||
private formatDefaultLine(offset: number, bytes: Buffer): string {
|
||||
const addressStr = offset.toString(16).padStart(7, '0');
|
||||
|
||||
// Group bytes into 16-bit words (little-endian)
|
||||
const words: string[] = [];
|
||||
for (let i = 0; i < bytes.length; i += 2) {
|
||||
if (i + 1 < bytes.length) {
|
||||
// Full 16-bit word (little-endian)
|
||||
const word = (bytes[i + 1] << 8) | bytes[i];
|
||||
words.push(word.toString(16).padStart(4, '0'));
|
||||
} else {
|
||||
// Partial word (only one byte)
|
||||
const word = bytes[i];
|
||||
words.push(word.toString(16).padStart(2, '0') + ' ');
|
||||
}
|
||||
}
|
||||
|
||||
return `${addressStr} ${words.join(' ')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the final offset line
|
||||
*/
|
||||
private formatOffsetLine(offset: number): string {
|
||||
return offset.toString(16).padStart(7, '0');
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ export { FindCommand } from './find';
|
||||
export { GitCommand } from './git';
|
||||
export { GrepCommand } from './grep';
|
||||
export { HeadCommand } from './head';
|
||||
export { HexdumpCommand } from './hexdump';
|
||||
export { LsCommand } from './ls';
|
||||
export { MkdirCommand } from './mkdir';
|
||||
export { MvCommand } from './mv';
|
||||
@@ -25,4 +26,5 @@ export { TrCommand } from './tr';
|
||||
export { UniqCommand } from './uniq';
|
||||
export { WcCommand } from './wc';
|
||||
export { WhoamiCommand } from './whoami';
|
||||
export { WhichCommand } from './which';
|
||||
export { WhichCommand } from './which';
|
||||
export { UnzipCommand } from './unzip';
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join, basename } from "@std/path";
|
||||
import { join, basename } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join, dirname } from "@std/path";
|
||||
import { join, dirname } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join, dirname, basename } from "@std/path";
|
||||
import { join, dirname, basename } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join, dirname } from "@std/path";
|
||||
import { join, dirname } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import JSZip from 'jszip';
|
||||
import { UnzipCommand } from './unzip';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
lstat: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
rmdir: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
readlink: vi.fn(),
|
||||
symlink: vi.fn(),
|
||||
});
|
||||
|
||||
describe('UnzipCommand', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let command: UnzipCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
command = new UnzipCommand(mockFS);
|
||||
});
|
||||
|
||||
const createTestZip = async (files: Record<string, string | Uint8Array>): Promise<Uint8Array> => {
|
||||
const zip = new JSZip();
|
||||
|
||||
for (const [path, content] of Object.entries(files)) {
|
||||
if (path.endsWith('/')) {
|
||||
zip.folder(path.slice(0, -1));
|
||||
} else {
|
||||
zip.file(path, content);
|
||||
}
|
||||
}
|
||||
|
||||
return zip.generateAsync({ type: 'uint8array' });
|
||||
};
|
||||
|
||||
it('should show usage when no arguments provided', async () => {
|
||||
const result = await command.execute([], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('missing archive operand');
|
||||
expect(result.stderr).toContain('Usage:');
|
||||
});
|
||||
|
||||
it('should show error for invalid options', async () => {
|
||||
const result = await command.execute(['-x', 'test.zip'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("invalid option '-x'");
|
||||
});
|
||||
|
||||
it('should show error for non-existent archive', async () => {
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
|
||||
|
||||
const result = await command.execute(['nonexistent.zip'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
});
|
||||
|
||||
it('should show error when trying to unzip a directory', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
});
|
||||
|
||||
const result = await command.execute(['testdir'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Is a directory');
|
||||
});
|
||||
|
||||
it('should list archive contents with -l option', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'Hello World',
|
||||
'dir1/': '',
|
||||
'dir1/file2.txt': 'Test content'
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
|
||||
const result = await command.execute(['-l', 'test.zip'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Archive: test.zip');
|
||||
expect(result.stdout).toContain('file1.txt');
|
||||
expect(result.stdout).toContain('dir1/');
|
||||
expect(result.stdout).toContain('dir1/file2.txt');
|
||||
});
|
||||
|
||||
it('should extract files to current directory', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'Hello World'
|
||||
});
|
||||
|
||||
// Mock file operations - keep it simple
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
|
||||
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
const result = await command.execute(['test.zip'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Archive: test.zip');
|
||||
expect(result.stdout).toContain('inflating: file1.txt');
|
||||
|
||||
// Verify writeFile was called for extracted files
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array));
|
||||
});
|
||||
|
||||
it('should handle command line options correctly', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'Hello World'
|
||||
});
|
||||
|
||||
// Test -d option
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
|
||||
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
const result = await command.execute(['-d', 'extract', 'test.zip'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('inflating: file1.txt');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/extract/file1.txt', expect.any(Uint8Array));
|
||||
});
|
||||
|
||||
it('should handle overwrite option', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'New content'
|
||||
});
|
||||
|
||||
// Mock file exists scenario
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
// Without -o option, should fail
|
||||
const resultWithoutOverwrite = await command.execute(['test.zip'], '/home');
|
||||
expect(resultWithoutOverwrite.exitCode).toBe(1);
|
||||
expect(resultWithoutOverwrite.stderr).toContain('File exists (use -o to overwrite)');
|
||||
|
||||
// Reset mocks
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
// With -o option, should succeed
|
||||
const resultWithOverwrite = await command.execute(['-o', 'test.zip'], '/home');
|
||||
expect(resultWithOverwrite.exitCode).toBe(0);
|
||||
expect(resultWithOverwrite.stdout).toContain('inflating: file1.txt');
|
||||
});
|
||||
|
||||
it('should prevent extraction outside allowed directories', async () => {
|
||||
// Since JSZip normalizes paths during creation, we'll test the security logic
|
||||
// by mocking the internal zip.files object to simulate a malicious ZIP
|
||||
const zipData = await createTestZip({
|
||||
'normal.txt': 'safe content'
|
||||
});
|
||||
|
||||
// Mock the zip loading to return a ZIP with malicious paths
|
||||
const originalLoadAsync = JSZip.loadAsync;
|
||||
vi.spyOn(JSZip, 'loadAsync').mockImplementation(async () => {
|
||||
const zip = new JSZip();
|
||||
// Simulate malicious ZIP file entries that would escape the directory
|
||||
(zip as unknown as { files: Record<string, { name: string; dir: boolean; async: () => Promise<Uint8Array> }> }).files = {
|
||||
'../../../etc/passwd': {
|
||||
name: '../../../etc/passwd',
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3])),
|
||||
},
|
||||
'../../outside.txt': {
|
||||
name: '../../outside.txt',
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6])),
|
||||
},
|
||||
'normal.txt': {
|
||||
name: 'normal.txt',
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9])),
|
||||
}
|
||||
};
|
||||
return zip;
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
|
||||
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
const result = await command.execute(['test.zip'], '/home/user');
|
||||
|
||||
// Should return error because some files were skipped
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Path is outside allowed directories');
|
||||
expect(result.stderr).toContain('../../../etc/passwd');
|
||||
expect(result.stderr).toContain('../../outside.txt');
|
||||
|
||||
// Should only extract the safe file
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/user/normal.txt', expect.any(Uint8Array));
|
||||
expect(mockFS.writeFile).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Restore the original method
|
||||
JSZip.loadAsync = originalLoadAsync;
|
||||
});
|
||||
|
||||
it('should allow extraction to /tmp directory', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'Hello World'
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockRejectedValueOnce(new Error('ENOENT')) // extraction dir doesn't exist
|
||||
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
|
||||
const result = await command.execute(['-d', '/tmp', 'test.zip'], '/home/user');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('inflating: file1.txt');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/tmp/file1.txt', expect.any(Uint8Array));
|
||||
});
|
||||
|
||||
it('should reject extraction directory outside allowed paths', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'Hello World'
|
||||
});
|
||||
|
||||
// Mock that the archive exists and provide zip data
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
|
||||
const result = await command.execute(['-d', '/etc', 'test.zip'], '/home/user');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("extraction directory '/etc' is outside allowed paths");
|
||||
});
|
||||
|
||||
it('should support quiet mode with -q flag', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'Hello World',
|
||||
'dir1/': '',
|
||||
'dir1/file2.txt': 'Test content'
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
|
||||
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
|
||||
const result = await command.execute(['-q', 'test.zip'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
// In quiet mode, should not show archive header or extraction messages
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
// But files should still be extracted
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array));
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/dir1/file2.txt', expect.any(Uint8Array));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
import { join, dirname, normalize } from "path-browserify";
|
||||
import JSZip from "jszip";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
/**
|
||||
* Implementation of the 'unzip' command
|
||||
* Extract files from ZIP archives
|
||||
*/
|
||||
export class UnzipCommand implements ShellCommand {
|
||||
name = 'unzip';
|
||||
description = 'Extract files from ZIP archives';
|
||||
usage = 'unzip [-d directory] [-o] [-l] [-q] archive.zip';
|
||||
|
||||
private fs: JSRuntimeFS;
|
||||
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
this.fs = fs;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
if (args.length === 0) {
|
||||
return createErrorResult(`${this.name}: missing archive operand\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
let archivePath = '';
|
||||
let extractDir = cwd;
|
||||
let overwrite = false;
|
||||
let listOnly = false;
|
||||
let quiet = false;
|
||||
|
||||
// Parse command line options
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
|
||||
if (arg === '-d' && i + 1 < args.length) {
|
||||
// Extract to specific directory
|
||||
extractDir = args[i + 1];
|
||||
i++; // Skip next argument
|
||||
} else if (arg === '-o') {
|
||||
// Overwrite existing files
|
||||
overwrite = true;
|
||||
} else if (arg === '-l') {
|
||||
// List archive contents only
|
||||
listOnly = true;
|
||||
} else if (arg === '-q') {
|
||||
// Quiet mode - suppress output
|
||||
quiet = true;
|
||||
} else if (arg.startsWith('-')) {
|
||||
return createErrorResult(`${this.name}: invalid option '${arg}'\nUsage: ${this.usage}`);
|
||||
} else {
|
||||
// This should be the archive path
|
||||
archivePath = arg;
|
||||
}
|
||||
}
|
||||
|
||||
if (!archivePath) {
|
||||
return createErrorResult(`${this.name}: no archive specified\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
try {
|
||||
// Resolve archive path
|
||||
let absoluteArchivePath: string;
|
||||
if (archivePath.startsWith('/') || archivePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(archivePath)) {
|
||||
absoluteArchivePath = archivePath;
|
||||
} else {
|
||||
absoluteArchivePath = join(cwd, archivePath);
|
||||
}
|
||||
|
||||
// Check if archive exists
|
||||
try {
|
||||
const stats = await this.fs.stat(absoluteArchivePath);
|
||||
if (stats.isDirectory()) {
|
||||
return createErrorResult(`${this.name}: ${archivePath}: Is a directory`);
|
||||
}
|
||||
} catch {
|
||||
return createErrorResult(`${this.name}: ${archivePath}: No such file or directory`);
|
||||
}
|
||||
|
||||
// Read the ZIP file
|
||||
const zipData = await this.fs.readFile(absoluteArchivePath);
|
||||
const zip = await JSZip.loadAsync(zipData);
|
||||
|
||||
// Resolve extraction directory
|
||||
let absoluteExtractDir: string;
|
||||
if (extractDir.startsWith('/') || extractDir.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(extractDir)) {
|
||||
absoluteExtractDir = extractDir;
|
||||
} else {
|
||||
absoluteExtractDir = join(cwd, extractDir);
|
||||
}
|
||||
|
||||
// Security check: ensure extraction directory is within allowed paths
|
||||
if (!this.isPathAllowed(absoluteExtractDir, cwd)) {
|
||||
return createErrorResult(`${this.name}: extraction directory '${extractDir}' is outside allowed paths (cwd or /tmp)`);
|
||||
}
|
||||
|
||||
if (listOnly) {
|
||||
// List contents only
|
||||
const entries: string[] = [];
|
||||
zip.forEach((relativePath, file) => {
|
||||
const date = file.date || new Date();
|
||||
const type = file.dir ? 'd' : '-';
|
||||
const sizeStr = file.dir ? '0' : '?';
|
||||
|
||||
entries.push(`${type}rw-r--r-- 1 user user ${sizeStr.padStart(8)} ${date.toISOString().slice(0, 19).replace('T', ' ')} ${relativePath}`);
|
||||
});
|
||||
|
||||
return createSuccessResult(`Archive: ${archivePath}\n${entries.join('\n')}`);
|
||||
}
|
||||
|
||||
// Create extraction directory if it doesn't exist
|
||||
try {
|
||||
await this.fs.stat(absoluteExtractDir);
|
||||
} catch {
|
||||
await this.fs.mkdir(absoluteExtractDir, { recursive: true });
|
||||
}
|
||||
|
||||
const extractedFiles: string[] = [];
|
||||
const errors: string[] = [];
|
||||
|
||||
// Extract all files
|
||||
for (const [relativePath, file] of Object.entries(zip.files)) {
|
||||
const extractPath = join(absoluteExtractDir, relativePath);
|
||||
|
||||
// Security check: ensure each file path is within allowed directories
|
||||
if (!this.isPathAllowed(extractPath, cwd)) {
|
||||
errors.push(`${this.name}: ${relativePath}: Path is outside allowed directories (skipped for security)`);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
if (file.dir) {
|
||||
// Create directory
|
||||
await this.fs.mkdir(extractPath, { recursive: true });
|
||||
if (!quiet) {
|
||||
extractedFiles.push(` creating: ${relativePath}`);
|
||||
}
|
||||
} else {
|
||||
// Check if file exists and handle overwrite
|
||||
if (!overwrite) {
|
||||
try {
|
||||
await this.fs.stat(extractPath);
|
||||
errors.push(`${this.name}: ${relativePath}: File exists (use -o to overwrite)`);
|
||||
continue;
|
||||
} catch {
|
||||
// File doesn't exist, proceed with extraction
|
||||
}
|
||||
}
|
||||
|
||||
// Create parent directories if needed
|
||||
const parentDir = dirname(extractPath);
|
||||
try {
|
||||
await this.fs.stat(parentDir);
|
||||
} catch {
|
||||
await this.fs.mkdir(parentDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Extract file content
|
||||
const content = await file.async('uint8array');
|
||||
await this.fs.writeFile(extractPath, content);
|
||||
if (!quiet) {
|
||||
extractedFiles.push(` inflating: ${relativePath}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
errors.push(`${this.name}: ${relativePath}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
let output = '';
|
||||
if (!quiet) {
|
||||
output = `Archive: ${archivePath}\n`;
|
||||
if (extractedFiles.length > 0) {
|
||||
output += extractedFiles.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
if (!quiet && extractedFiles.length > 0) {
|
||||
output += '\n';
|
||||
}
|
||||
return createErrorResult(output + '\n' + errors.join('\n'));
|
||||
}
|
||||
|
||||
return createSuccessResult(output);
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('corrupted') || error.message.includes('invalid')) {
|
||||
return createErrorResult(`${this.name}: ${archivePath}: Archive is corrupted or invalid`);
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${archivePath}: ${error.message}`);
|
||||
}
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${archivePath}: Unknown error`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a path is within allowed extraction directories (cwd or /tmp and their subdirectories)
|
||||
*/
|
||||
private isPathAllowed(extractPath: string, cwd: string): boolean {
|
||||
// Normalize the paths without using resolve() since we're in browser environment
|
||||
const normalizedPath = normalize(extractPath);
|
||||
const normalizedCwd = normalize(cwd);
|
||||
const tmpPath = '/tmp';
|
||||
|
||||
// Ensure paths are absolute for comparison
|
||||
const absolutePath = normalizedPath.startsWith('/') ? normalizedPath : normalize(join(normalizedCwd, normalizedPath));
|
||||
const absoluteCwd = normalizedCwd.startsWith('/') ? normalizedCwd : '/' + normalizedCwd;
|
||||
|
||||
// Check if path is within cwd or /tmp
|
||||
return absolutePath.startsWith(absoluteCwd + '/') ||
|
||||
absolutePath === absoluteCwd ||
|
||||
absolutePath.startsWith(tmpPath + '/') ||
|
||||
absolutePath === tmpPath;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
@@ -54,12 +54,13 @@ describe('configUtils', () => {
|
||||
|
||||
describe('AI Settings', () => {
|
||||
const sampleAISettings: AISettings = {
|
||||
providers: {
|
||||
'openai': {
|
||||
providers: [
|
||||
{
|
||||
id: 'openai',
|
||||
baseURL: 'https://api.openai.com/v1',
|
||||
apiKey: 'sk-test123',
|
||||
},
|
||||
},
|
||||
],
|
||||
recentlyUsedModels: ['gpt-4', 'gpt-3.5-turbo'],
|
||||
};
|
||||
|
||||
@@ -80,7 +81,7 @@ describe('configUtils', () => {
|
||||
const result = await readAISettings(mockFS);
|
||||
|
||||
expect(result).toEqual({
|
||||
providers: {},
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
});
|
||||
@@ -92,7 +93,7 @@ describe('configUtils', () => {
|
||||
const result = await readAISettings(mockFS);
|
||||
|
||||
expect(result).toEqual({
|
||||
providers: {},
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
});
|
||||
@@ -184,7 +185,7 @@ describe('configUtils', () => {
|
||||
|
||||
expect(result).toEqual({
|
||||
credentials: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+43
-7
@@ -1,5 +1,5 @@
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import type { AISettings } from '@/contexts/AISettingsContext';
|
||||
import type { AISettings, AIProvider } from '@/contexts/AISettingsContext';
|
||||
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
||||
|
||||
const CONFIG_DIR = '/config';
|
||||
@@ -27,8 +27,22 @@ async function migrateAISettingsFromLocalStorage(fs: JSRuntimeFS): Promise<AISet
|
||||
try {
|
||||
const parsed = JSON.parse(stored);
|
||||
if (parsed && typeof parsed === 'object' && 'providers' in parsed) {
|
||||
// Handle migration from old map format to new array format
|
||||
let providers;
|
||||
if (Array.isArray(parsed.providers)) {
|
||||
providers = parsed.providers;
|
||||
} else if (parsed.providers && typeof parsed.providers === 'object') {
|
||||
// Convert map to array
|
||||
providers = Object.entries(parsed.providers).map(([id, connection]) => ({
|
||||
id,
|
||||
...(connection as Omit<AIProvider, 'id'>),
|
||||
}));
|
||||
} else {
|
||||
providers = [];
|
||||
}
|
||||
|
||||
const settings: AISettings = {
|
||||
providers: parsed.providers || {},
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
|
||||
@@ -51,7 +65,7 @@ async function migrateAISettingsFromLocalStorage(fs: JSRuntimeFS): Promise<AISet
|
||||
*/
|
||||
export async function readAISettings(fs: JSRuntimeFS): Promise<AISettings> {
|
||||
const defaultSettings: AISettings = {
|
||||
providers: {},
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
};
|
||||
|
||||
@@ -61,8 +75,30 @@ export async function readAISettings(fs: JSRuntimeFS): Promise<AISettings> {
|
||||
const parsed = JSON.parse(content);
|
||||
|
||||
if (parsed && typeof parsed === 'object' && 'providers' in parsed) {
|
||||
// Handle migration from old map format to new array format
|
||||
let providers;
|
||||
if (Array.isArray(parsed.providers)) {
|
||||
providers = parsed.providers;
|
||||
} else if (parsed.providers && typeof parsed.providers === 'object') {
|
||||
// Convert map to array
|
||||
providers = Object.entries(parsed.providers).map(([id, connection]) => ({
|
||||
id,
|
||||
...(connection as Omit<AIProvider, 'id'>),
|
||||
}));
|
||||
|
||||
// Write back the migrated format
|
||||
const migratedSettings: AISettings = {
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
await writeAISettings(fs, migratedSettings);
|
||||
return migratedSettings;
|
||||
} else {
|
||||
providers = [];
|
||||
}
|
||||
|
||||
return {
|
||||
providers: parsed.providers || {},
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
}
|
||||
@@ -99,7 +135,7 @@ async function migrateGitSettingsFromLocalStorage(fs: JSRuntimeFS): Promise<GitS
|
||||
if (parsed && typeof parsed === 'object' && 'credentials' in parsed) {
|
||||
const settings: GitSettings = {
|
||||
credentials: parsed.credentials || {},
|
||||
corsProxy: parsed.corsProxy || 'https://cors.isomorphic-git.org',
|
||||
corsProxy: parsed.corsProxy || 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
|
||||
// Write to VFS and remove from localStorage
|
||||
@@ -122,7 +158,7 @@ async function migrateGitSettingsFromLocalStorage(fs: JSRuntimeFS): Promise<GitS
|
||||
export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
|
||||
const defaultSettings: GitSettings = {
|
||||
credentials: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
|
||||
// Try to read from VFS first
|
||||
@@ -133,7 +169,7 @@ export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
|
||||
if (parsed && typeof parsed === 'object' && 'credentials' in parsed) {
|
||||
return {
|
||||
credentials: parsed.credentials || {},
|
||||
corsProxy: parsed.corsProxy || 'https://cors.isomorphic-git.org',
|
||||
corsProxy: parsed.corsProxy || 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { deployProject } from './deploy';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
import type { NostrSigner } from '@nostrify/nostrify';
|
||||
|
||||
// Mock JSZip
|
||||
vi.mock('jszip', () => {
|
||||
return {
|
||||
default: vi.fn().mockImplementation(() => ({
|
||||
folder: vi.fn().mockReturnValue({
|
||||
file: vi.fn(),
|
||||
}),
|
||||
file: vi.fn(),
|
||||
generateAsync: vi.fn().mockResolvedValue(new Blob()),
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
// Mock NIP98Client
|
||||
vi.mock('@nostrify/nostrify', () => ({
|
||||
NIP98Client: vi.fn().mockImplementation(() => ({
|
||||
fetch: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
}),
|
||||
})),
|
||||
}));
|
||||
|
||||
describe('deployProject', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let mockSigner: NostrSigner;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = {
|
||||
readFile: vi.fn().mockResolvedValue('mock file content'),
|
||||
readdir: vi.fn().mockResolvedValue([]),
|
||||
writeFile: vi.fn().mockResolvedValue(undefined),
|
||||
mkdir: vi.fn().mockResolvedValue(undefined),
|
||||
stat: vi.fn().mockResolvedValue({ isDirectory: () => false, isFile: () => true }),
|
||||
lstat: vi.fn().mockResolvedValue({ isDirectory: () => false, isFile: () => true }),
|
||||
unlink: vi.fn().mockResolvedValue(undefined),
|
||||
rmdir: vi.fn().mockResolvedValue(undefined),
|
||||
rename: vi.fn().mockResolvedValue(undefined),
|
||||
readlink: vi.fn().mockResolvedValue(''),
|
||||
symlink: vi.fn().mockResolvedValue(undefined),
|
||||
} as JSRuntimeFS;
|
||||
|
||||
mockSigner = {} as NostrSigner;
|
||||
});
|
||||
|
||||
it('should construct hostname from projectId and deployServer by default', async () => {
|
||||
const result = await deployProject({
|
||||
projectId: 'test-project',
|
||||
deployServer: 'shakespeare.wtf',
|
||||
fs: mockFS,
|
||||
projectPath: '/projects/test-project',
|
||||
signer: mockSigner,
|
||||
});
|
||||
|
||||
expect(result.hostname).toBe('test-project.shakespeare.wtf');
|
||||
expect(result.url).toBe('https://test-project.shakespeare.wtf');
|
||||
});
|
||||
|
||||
it('should use customHostname when provided', async () => {
|
||||
const result = await deployProject({
|
||||
projectId: 'test-project',
|
||||
deployServer: 'shakespeare.wtf',
|
||||
fs: mockFS,
|
||||
projectPath: '/projects/test-project',
|
||||
signer: mockSigner,
|
||||
customHostname: 'my-custom-domain.example.com',
|
||||
});
|
||||
|
||||
expect(result.hostname).toBe('my-custom-domain.example.com');
|
||||
expect(result.url).toBe('https://my-custom-domain.example.com');
|
||||
});
|
||||
|
||||
it('should handle custom subdomain with same deploy server', async () => {
|
||||
const result = await deployProject({
|
||||
projectId: 'original-id',
|
||||
deployServer: 'shakespeare.wtf',
|
||||
fs: mockFS,
|
||||
projectPath: '/projects/original-id',
|
||||
signer: mockSigner,
|
||||
customHostname: 'custom-name.shakespeare.wtf',
|
||||
});
|
||||
|
||||
expect(result.hostname).toBe('custom-name.shakespeare.wtf');
|
||||
expect(result.url).toBe('https://custom-name.shakespeare.wtf');
|
||||
});
|
||||
});
|
||||
+5
-3
@@ -14,6 +14,8 @@ export interface DeployOptions {
|
||||
projectPath: string;
|
||||
/** Nostr signer for NIP-98 authentication */
|
||||
signer: NostrSigner;
|
||||
/** Custom hostname to use instead of constructing from projectId.deployServer */
|
||||
customHostname?: string;
|
||||
}
|
||||
|
||||
export interface DeployResult {
|
||||
@@ -28,10 +30,10 @@ export interface DeployResult {
|
||||
* to the deployment server using NIP-98 authentication.
|
||||
*/
|
||||
export async function deployProject(options: DeployOptions): Promise<DeployResult> {
|
||||
const { projectId, deployServer, fs, projectPath, signer } = options;
|
||||
const { projectId, deployServer, fs, projectPath, signer, customHostname } = options;
|
||||
|
||||
// Construct hostname and URL
|
||||
const hostname = `${projectId}.${deployServer}`;
|
||||
// Use custom hostname if provided, otherwise construct from projectId.deployServer
|
||||
const hostname = customHostname || `${projectId}.${deployServer}`;
|
||||
const deployUrl = `https://${deployServer}/deploy`;
|
||||
const siteUrl = `https://${hostname}`;
|
||||
|
||||
|
||||
@@ -153,5 +153,43 @@ describe('fileUtils', () => {
|
||||
const savedContent = await mockFS.readFile('/tmp/test_1.txt', 'utf8');
|
||||
expect(savedContent).toBe(fileContent);
|
||||
});
|
||||
|
||||
it('should convert spaces to underscores in filename', async () => {
|
||||
const fileContent = 'Hello, world!';
|
||||
const arrayBuffer = new TextEncoder().encode(fileContent).buffer;
|
||||
|
||||
// Create a mock File object with spaces in the name
|
||||
const file = {
|
||||
name: 'my file with spaces.txt',
|
||||
arrayBuffer: async () => arrayBuffer
|
||||
} as File;
|
||||
|
||||
const savedPath = await saveFileToTmp(mockFS, file);
|
||||
|
||||
expect(savedPath).toBe('/tmp/my_file_with_spaces.txt');
|
||||
|
||||
// Verify file was actually saved with sanitized name
|
||||
const savedContent = await mockFS.readFile('/tmp/my_file_with_spaces.txt', 'utf8');
|
||||
expect(savedContent).toBe(fileContent);
|
||||
});
|
||||
|
||||
it('should convert multiple consecutive spaces to single underscore', async () => {
|
||||
const fileContent = 'test content';
|
||||
const arrayBuffer = new TextEncoder().encode(fileContent).buffer;
|
||||
|
||||
// Create a mock File object with multiple spaces
|
||||
const file = {
|
||||
name: 'file with multiple spaces.txt',
|
||||
arrayBuffer: async () => arrayBuffer
|
||||
} as File;
|
||||
|
||||
const savedPath = await saveFileToTmp(mockFS, file);
|
||||
|
||||
expect(savedPath).toBe('/tmp/file_with_multiple_spaces.txt');
|
||||
|
||||
// Verify file was actually saved
|
||||
const savedContent = await mockFS.readFile('/tmp/file_with_multiple_spaces.txt', 'utf8');
|
||||
expect(savedContent).toBe(fileContent);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -53,7 +53,9 @@ export async function generateUniqueFilename(
|
||||
*/
|
||||
export async function saveFileToTmp(fs: JSRuntimeFS, file: File): Promise<string> {
|
||||
const tmpDir = '/tmp';
|
||||
const uniqueFilename = await generateUniqueFilename(fs, tmpDir, file.name);
|
||||
// Convert spaces to underscores in the filename
|
||||
const sanitizedFilename = file.name.replace(/\s+/g, '_');
|
||||
const uniqueFilename = await generateUniqueFilename(fs, tmpDir, sanitizedFilename);
|
||||
const fullPath = `${tmpDir}/${uniqueFilename}`;
|
||||
|
||||
// Read file content as array buffer and convert to Uint8Array
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
import { Git } from './git';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
|
||||
/**
|
||||
* Example usage of the Git class
|
||||
*/
|
||||
export async function exampleGitUsage(fs: JSRuntimeFS) {
|
||||
// Create a Git instance with fs and optional CORS proxy
|
||||
const git = new Git(fs, 'https://cors.isomorphic-git.org');
|
||||
|
||||
// Initialize a new repository
|
||||
await git.init({
|
||||
dir: '/my-project',
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
|
||||
// Set up configuration
|
||||
await git.setConfig({
|
||||
dir: '/my-project',
|
||||
path: 'user.name',
|
||||
value: 'John Doe',
|
||||
});
|
||||
|
||||
await git.setConfig({
|
||||
dir: '/my-project',
|
||||
path: 'user.email',
|
||||
value: '[email protected]',
|
||||
});
|
||||
|
||||
// Add files to the index
|
||||
await git.add({
|
||||
dir: '/my-project',
|
||||
filepath: 'README.md',
|
||||
});
|
||||
|
||||
// Make a commit
|
||||
await git.commit({
|
||||
dir: '/my-project',
|
||||
message: 'Initial commit',
|
||||
author: {
|
||||
name: 'John Doe',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
|
||||
// Get repository status
|
||||
const statusMatrix = await git.statusMatrix({
|
||||
dir: '/my-project',
|
||||
});
|
||||
|
||||
// List branches
|
||||
const branches = await git.listBranches({
|
||||
dir: '/my-project',
|
||||
});
|
||||
|
||||
// Get commit log
|
||||
const commits = await git.log({
|
||||
dir: '/my-project',
|
||||
depth: 10,
|
||||
});
|
||||
|
||||
// Clone a repository
|
||||
await git.clone({
|
||||
dir: '/cloned-project',
|
||||
url: 'https://github.com/user/repo.git',
|
||||
singleBranch: true,
|
||||
depth: 1,
|
||||
});
|
||||
|
||||
// Add a remote
|
||||
await git.addRemote({
|
||||
dir: '/my-project',
|
||||
remote: 'origin',
|
||||
url: 'https://github.com/user/my-project.git',
|
||||
});
|
||||
|
||||
// Push to remote (requires authentication)
|
||||
try {
|
||||
await git.push({
|
||||
dir: '/my-project',
|
||||
remote: 'origin',
|
||||
ref: 'main',
|
||||
// onAuth would be needed for authentication
|
||||
});
|
||||
} catch (error) {
|
||||
console.log('Push failed (likely due to authentication):', error);
|
||||
}
|
||||
|
||||
return {
|
||||
statusMatrix,
|
||||
branches,
|
||||
commits,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Example for GitHub/GitLab repositories with CORS proxy
|
||||
*/
|
||||
export function createGitForGitHub(fs: JSRuntimeFS) {
|
||||
return new Git(fs, 'https://cors.isomorphic-git.org');
|
||||
}
|
||||
|
||||
/**
|
||||
* Example for self-hosted Git servers without CORS proxy
|
||||
*/
|
||||
export function createGitForSelfHosted(fs: JSRuntimeFS) {
|
||||
return new Git(fs); // No CORS proxy needed
|
||||
}
|
||||
+149
-17
@@ -1,26 +1,51 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { Git } from './git';
|
||||
import git from 'isomorphic-git';
|
||||
import type { NPool } from '@nostrify/nostrify';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Mock isomorphic-git
|
||||
vi.mock('isomorphic-git');
|
||||
vi.mock('isomorphic-git/http/web');
|
||||
vi.mock('nostr-tools', () => ({
|
||||
nip19: {
|
||||
decode: vi.fn(),
|
||||
naddrEncode: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('@nostrify/nostrify', () => ({
|
||||
NIP05: {
|
||||
lookup: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockGit = vi.mocked(git);
|
||||
|
||||
const createMockNostr = (): NPool => ({
|
||||
req: vi.fn(),
|
||||
query: vi.fn(),
|
||||
event: vi.fn(),
|
||||
group: vi.fn(),
|
||||
relay: vi.fn(),
|
||||
relays: new Map(),
|
||||
close: vi.fn(),
|
||||
}) as unknown as NPool;
|
||||
|
||||
describe('Git', () => {
|
||||
const mockFS = {} as JSRuntimeFS;
|
||||
const fs = {} as JSRuntimeFS;
|
||||
const nostr = createMockNostr();
|
||||
const corsProxy = 'https://cors.example.com';
|
||||
let gitInstance: Git;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
gitInstance = new Git(mockFS, 'https://cors.example.com');
|
||||
gitInstance = new Git({ fs, nostr, corsProxy });
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('creates instance with default regex when none provided', () => {
|
||||
const git = new Git(mockFS, 'https://cors.example.com');
|
||||
const git = new Git({ fs, nostr, corsProxy });
|
||||
expect(git).toBeInstanceOf(Git);
|
||||
});
|
||||
|
||||
@@ -39,9 +64,8 @@ describe('Git', () => {
|
||||
});
|
||||
|
||||
expect(mockGit.clone).toHaveBeenCalledWith({
|
||||
fs: mockFS,
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
dir: '/test',
|
||||
url: 'https://github.com/user/repo.git',
|
||||
});
|
||||
@@ -54,9 +78,8 @@ describe('Git', () => {
|
||||
});
|
||||
|
||||
expect(mockGit.clone).toHaveBeenCalledWith({
|
||||
fs: mockFS,
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
dir: '/test',
|
||||
url: 'https://gitlab.com/user/repo.git',
|
||||
});
|
||||
@@ -69,9 +92,8 @@ describe('Git', () => {
|
||||
});
|
||||
|
||||
expect(mockGit.clone).toHaveBeenCalledWith({
|
||||
fs: mockFS,
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
dir: '/test',
|
||||
url: 'https://custom.example.com/user/repo.git',
|
||||
});
|
||||
@@ -84,9 +106,8 @@ describe('Git', () => {
|
||||
});
|
||||
|
||||
expect(mockGit.clone).toHaveBeenCalledWith({
|
||||
fs: mockFS,
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
dir: '/test',
|
||||
url: 'http://github.com/user/repo.git',
|
||||
});
|
||||
@@ -105,7 +126,6 @@ describe('Git', () => {
|
||||
|
||||
expect(mockGit.getRemoteInfo).toHaveBeenCalledWith({
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
url: 'https://github.com/user/repo.git',
|
||||
});
|
||||
});
|
||||
@@ -117,7 +137,6 @@ describe('Git', () => {
|
||||
|
||||
expect(mockGit.getRemoteInfo).toHaveBeenCalledWith({
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
url: 'https://custom.example.com/user/repo.git',
|
||||
});
|
||||
});
|
||||
@@ -138,9 +157,8 @@ describe('Git', () => {
|
||||
});
|
||||
|
||||
expect(mockGit.fetch).toHaveBeenCalledWith({
|
||||
fs: mockFS,
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
dir: '/test',
|
||||
remote: 'origin',
|
||||
});
|
||||
@@ -153,12 +171,126 @@ describe('Git', () => {
|
||||
});
|
||||
|
||||
expect(mockGit.fetch).toHaveBeenCalledWith({
|
||||
fs: mockFS,
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
dir: '/test',
|
||||
url: 'https://gitlab.com/user/repo.git',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Nostr URI cloning', () => {
|
||||
beforeEach(() => {
|
||||
mockGit.clone = vi.fn().mockResolvedValue(undefined);
|
||||
mockGit.deleteRemote = vi.fn().mockResolvedValue(undefined);
|
||||
mockGit.addRemote = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
// Mock nip19 decode
|
||||
vi.mocked(nip19.decode).mockReturnValue({
|
||||
type: 'npub',
|
||||
data: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab'
|
||||
});
|
||||
|
||||
// Mock Nostr query to return a repository event
|
||||
const mockRelay = {
|
||||
query: vi.fn().mockResolvedValue([{
|
||||
id: 'event123',
|
||||
pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab',
|
||||
kind: 30617,
|
||||
content: '',
|
||||
tags: [
|
||||
['d', 'my-repo'],
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['clone', 'https://gitlab.com/user/repo.git']
|
||||
],
|
||||
created_at: Date.now(),
|
||||
sig: 'signature'
|
||||
}])
|
||||
};
|
||||
|
||||
nostr.group = vi.fn().mockReturnValue(mockRelay);
|
||||
nostr.relay = vi.fn().mockReturnValue(mockRelay);
|
||||
});
|
||||
|
||||
it('successfully clones from Nostr URI and updates origin remote', async () => {
|
||||
const nostrUrl = 'nostr://npub1abc123/my-repo';
|
||||
|
||||
await gitInstance.clone({
|
||||
dir: '/test',
|
||||
url: nostrUrl,
|
||||
});
|
||||
|
||||
// Should attempt to clone from the first URL
|
||||
expect(mockGit.clone).toHaveBeenCalledWith({
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
dir: '/test',
|
||||
url: 'https://github.com/user/repo.git',
|
||||
});
|
||||
|
||||
// Should delete the existing origin remote
|
||||
expect(mockGit.deleteRemote).toHaveBeenCalledWith({
|
||||
fs,
|
||||
dir: '/test',
|
||||
remote: 'origin',
|
||||
});
|
||||
|
||||
// Should add the Nostr URI as the new origin
|
||||
expect(mockGit.addRemote).toHaveBeenCalledWith({
|
||||
fs,
|
||||
dir: '/test',
|
||||
remote: 'origin',
|
||||
url: nostrUrl,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('setRemoteURL', () => {
|
||||
beforeEach(() => {
|
||||
mockGit.deleteRemote = vi.fn().mockResolvedValue(undefined);
|
||||
mockGit.addRemote = vi.fn().mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it('updates remote URL by deleting and re-adding remote', async () => {
|
||||
await gitInstance.setRemoteURL({
|
||||
dir: '/test',
|
||||
remote: 'origin',
|
||||
url: 'https://new-repo.com/user/repo.git',
|
||||
});
|
||||
|
||||
expect(mockGit.deleteRemote).toHaveBeenCalledWith({
|
||||
fs,
|
||||
dir: '/test',
|
||||
remote: 'origin',
|
||||
});
|
||||
|
||||
expect(mockGit.addRemote).toHaveBeenCalledWith({
|
||||
fs,
|
||||
dir: '/test',
|
||||
remote: 'origin',
|
||||
url: 'https://new-repo.com/user/repo.git',
|
||||
});
|
||||
});
|
||||
|
||||
it('works with any remote name', async () => {
|
||||
await gitInstance.setRemoteURL({
|
||||
dir: '/test',
|
||||
remote: 'upstream',
|
||||
url: 'nostr://npub1abc123/my-repo',
|
||||
});
|
||||
|
||||
expect(mockGit.deleteRemote).toHaveBeenCalledWith({
|
||||
fs,
|
||||
dir: '/test',
|
||||
remote: 'upstream',
|
||||
});
|
||||
|
||||
expect(mockGit.addRemote).toHaveBeenCalledWith({
|
||||
fs,
|
||||
dir: '/test',
|
||||
remote: 'upstream',
|
||||
url: 'nostr://npub1abc123/my-repo',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
+1225
-24
File diff suppressed because it is too large.
Load diff
@@ -64,17 +64,17 @@ describe('gitCredentials', () => {
|
||||
.toEqual({ username: 'git', password: 'github-token' });
|
||||
});
|
||||
|
||||
it('should return null when no credentials found', () => {
|
||||
it('should return undefined when no credentials found', () => {
|
||||
expect(findCredentialsForRepo('https://unknown.com/user/repo.git', mockCredentials))
|
||||
.toBe(null);
|
||||
|
||||
.toBe(undefined);
|
||||
|
||||
expect(findCredentialsForRepo('invalid-url', mockCredentials))
|
||||
.toBe(null);
|
||||
.toBe(undefined);
|
||||
});
|
||||
|
||||
it('should return null for empty credentials', () => {
|
||||
it('should return undefined for empty credentials', () => {
|
||||
expect(findCredentialsForRepo('https://github.com/user/repo.git', {}))
|
||||
.toBe(null);
|
||||
.toBe(undefined);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -31,9 +31,9 @@ export function extractGitOrigin(gitUrl: string): string | null {
|
||||
export function findCredentialsForRepo(
|
||||
repoUrl: string,
|
||||
credentials: Record<string, GitCredential>
|
||||
): GitCredential | null {
|
||||
): GitCredential | undefined {
|
||||
const repoOrigin = extractGitOrigin(repoUrl);
|
||||
if (!repoOrigin) return null;
|
||||
if (!repoOrigin) return;
|
||||
|
||||
// Direct match
|
||||
if (credentials[repoOrigin]) {
|
||||
@@ -57,8 +57,6 @@ export function findCredentialsForRepo(
|
||||
return credential;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+932
-9
File diff suppressed because it is too large.
Load diff
@@ -1,49 +1,65 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseProviderModel } from './parseProviderModel';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
describe('parseProviderModel', () => {
|
||||
const mockProviders: Record<string, AIConnection> = {
|
||||
openai: {
|
||||
const mockProviders: AIProvider[] = [
|
||||
{
|
||||
id: 'openai',
|
||||
baseURL: 'https://api.openai.com/v1',
|
||||
apiKey: 'sk-test-key',
|
||||
},
|
||||
openrouter: {
|
||||
{
|
||||
id: 'openrouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'sk-or-test-key',
|
||||
},
|
||||
anthropic: {
|
||||
{
|
||||
id: 'anthropic',
|
||||
baseURL: 'https://api.anthropic.com',
|
||||
apiKey: 'sk-ant-test-key',
|
||||
},
|
||||
unconfigured: {
|
||||
{
|
||||
id: 'unconfigured',
|
||||
baseURL: 'https://example.com/v1',
|
||||
apiKey: '',
|
||||
},
|
||||
};
|
||||
];
|
||||
|
||||
it('should parse simple provider/model format', () => {
|
||||
const result = parseProviderModel('openai/gpt-4o', mockProviders);
|
||||
|
||||
expect(result.provider).toBe('openai');
|
||||
expect(result.model).toBe('gpt-4o');
|
||||
expect(result.connection).toEqual(mockProviders.openai);
|
||||
expect(result.provider).toEqual({
|
||||
id: 'openai',
|
||||
baseURL: mockProviders[0].baseURL,
|
||||
apiKey: mockProviders[0].apiKey,
|
||||
nostr: mockProviders[0].nostr,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse complex model names with slashes', () => {
|
||||
const result = parseProviderModel('openrouter/anthropic/claude-sonnet-4', mockProviders);
|
||||
|
||||
expect(result.provider).toBe('openrouter');
|
||||
expect(result.model).toBe('anthropic/claude-sonnet-4');
|
||||
expect(result.connection).toEqual(mockProviders.openrouter);
|
||||
expect(result.provider).toEqual({
|
||||
id: 'openrouter',
|
||||
baseURL: mockProviders[1].baseURL,
|
||||
apiKey: mockProviders[1].apiKey,
|
||||
nostr: mockProviders[1].nostr,
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle model names with multiple slashes', () => {
|
||||
const result = parseProviderModel('openrouter/meta/llama-3.1-405b-instruct', mockProviders);
|
||||
|
||||
expect(result.provider).toBe('openrouter');
|
||||
expect(result.model).toBe('meta/llama-3.1-405b-instruct');
|
||||
expect(result.connection).toEqual(mockProviders.openrouter);
|
||||
expect(result.provider).toEqual({
|
||||
id: 'openrouter',
|
||||
baseURL: mockProviders[1].baseURL,
|
||||
apiKey: mockProviders[1].apiKey,
|
||||
nostr: mockProviders[1].nostr,
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw error for invalid format without slash', () => {
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
export interface ParsedProviderModel {
|
||||
provider: string;
|
||||
model: string;
|
||||
connection: AIConnection;
|
||||
provider: AIProvider;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -13,29 +12,28 @@ export interface ParsedProviderModel {
|
||||
*/
|
||||
export function parseProviderModel(
|
||||
providerModelString: string,
|
||||
providers: Record<string, AIConnection>
|
||||
providers: AIProvider[]
|
||||
): ParsedProviderModel {
|
||||
const firstSlashIndex = providerModelString.indexOf('/');
|
||||
|
||||
|
||||
if (firstSlashIndex === -1) {
|
||||
throw new Error('Invalid format. Use provider/model (e.g., "openai/gpt-4o")');
|
||||
}
|
||||
|
||||
const provider = providerModelString.substring(0, firstSlashIndex);
|
||||
|
||||
const providerId = providerModelString.substring(0, firstSlashIndex);
|
||||
const model = providerModelString.substring(firstSlashIndex + 1);
|
||||
|
||||
if (!provider || !model) {
|
||||
|
||||
if (!providerId || !model) {
|
||||
throw new Error('Invalid format. Both provider and model must be specified');
|
||||
}
|
||||
|
||||
const connection = providers[provider];
|
||||
if (!connection) {
|
||||
throw new Error(`Provider "${provider}" not found. Available providers: ${Object.keys(providers).join(', ')}`);
|
||||
|
||||
const provider = providers.find(p => p.id === providerId);
|
||||
if (!provider) {
|
||||
throw new Error(`Provider "${providerId}" not found. Available providers: ${providers.map(p => p.id).join(', ')}`);
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
provider,
|
||||
model,
|
||||
connection,
|
||||
provider,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import UriTemplate from 'uri-templates';
|
||||
|
||||
export function proxyUrl(template: string, url: string | URL): string {
|
||||
const u = new URL(url);
|
||||
return UriTemplate(template).fill({
|
||||
href: u.href,
|
||||
origin: u.origin,
|
||||
protocol: u.protocol,
|
||||
username: u.username,
|
||||
password: u.password,
|
||||
host: u.host,
|
||||
hostname: u.hostname,
|
||||
port: u.port,
|
||||
pathname: u.pathname,
|
||||
hash: u.hash,
|
||||
search: u.search,
|
||||
});
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
* Security utilities for path validation and access control
|
||||
*/
|
||||
|
||||
import { normalize } from "@std/path";
|
||||
import { normalize } from "path-browserify";
|
||||
|
||||
/**
|
||||
* Check if the given path is an absolute path
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import { NUser } from "@nostrify/react/login";
|
||||
import { NostrMetadata } from "@nostrify/nostrify";
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import OpenAI from "openai";
|
||||
import { nip19 } from "nostr-tools";
|
||||
import { JSRuntimeFS } from "./JSRuntime";
|
||||
@@ -46,7 +46,7 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<stri
|
||||
if (metadata?.nip05) userText += `\n- **NIP-05**: ${metadata.nip05}`;
|
||||
if (metadata?.lud16) userText += `\n- **Lightning Address**: ${metadata.lud16}`;
|
||||
|
||||
userText += `Since the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.`;
|
||||
userText += `\n\nSince the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.`;
|
||||
} else {
|
||||
userText = `The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to deploy their creations to public URLs and use Nostr-enabled AI providers.`;
|
||||
}
|
||||
|
||||
@@ -1,220 +0,0 @@
|
||||
/**
|
||||
* Example usage of the ShellTool
|
||||
*
|
||||
* This file demonstrates how to use the ShellTool to execute shell commands
|
||||
* in your application. The ShellTool provides a safe, sandboxed environment
|
||||
* for running basic file operations.
|
||||
*/
|
||||
|
||||
import { ShellTool } from './ShellTool';
|
||||
import { Git } from '../git';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
/**
|
||||
* Example function showing how to use ShellTool
|
||||
*/
|
||||
export async function exampleShellUsage(fs: JSRuntimeFS, projectRoot: string) {
|
||||
// Create a shell tool instance
|
||||
const shell = new ShellTool(fs, projectRoot, new Git(fs));
|
||||
|
||||
console.log('Available commands:', shell.getAvailableCommands());
|
||||
console.log('Current directory:', shell.getCurrentWorkingDirectory());
|
||||
|
||||
// Example 1: Display current directory
|
||||
console.log('\n--- Example 1: Show current directory ---');
|
||||
const pwdResult = await shell.execute({ command: 'pwd' });
|
||||
console.log(pwdResult);
|
||||
|
||||
// Example 2: List directory contents
|
||||
console.log('\n--- Example 2: List files ---');
|
||||
const lsResult = await shell.execute({ command: 'ls' });
|
||||
console.log(lsResult);
|
||||
|
||||
// Example 3: List with long format
|
||||
console.log('\n--- Example 3: List with details ---');
|
||||
const lsLongResult = await shell.execute({ command: 'ls -l' });
|
||||
console.log(lsLongResult);
|
||||
|
||||
// Example 4: Display a file
|
||||
console.log('\n--- Example 4: Display package.json ---');
|
||||
const catResult = await shell.execute({ command: 'cat package.json' });
|
||||
console.log(catResult);
|
||||
|
||||
// Example 5: Echo text
|
||||
console.log('\n--- Example 5: Echo message ---');
|
||||
const echoResult = await shell.execute({ command: 'echo Hello, World!' });
|
||||
console.log(echoResult);
|
||||
|
||||
// Example 6: Change directory
|
||||
console.log('\n--- Example 6: Change directory ---');
|
||||
const cdResult = await shell.execute({ command: 'cd src' });
|
||||
console.log(cdResult);
|
||||
console.log('New directory:', shell.getCurrentWorkingDirectory());
|
||||
|
||||
// Example 7: Handle errors gracefully
|
||||
console.log('\n--- Example 7: Handle non-existent file ---');
|
||||
const errorResult = await shell.execute({
|
||||
command: 'cat nonexistent-file.txt'
|
||||
});
|
||||
console.log(errorResult);
|
||||
|
||||
// Example 8: Try unknown command
|
||||
console.log('\n--- Example 8: Unknown command ---');
|
||||
const unknownResult = await shell.execute({
|
||||
command: 'unknown-command arg1 arg2'
|
||||
});
|
||||
console.log(unknownResult);
|
||||
|
||||
// Example 9: Compound commands with &&
|
||||
console.log('\n--- Example 9: Compound commands with && ---');
|
||||
const andResult = await shell.execute({
|
||||
command: 'pwd && echo "Current directory listed above"'
|
||||
});
|
||||
console.log(andResult);
|
||||
|
||||
// Example 10: Compound commands with ||
|
||||
console.log('\n--- Example 10: Compound commands with || ---');
|
||||
const orResult = await shell.execute({
|
||||
command: 'cat nonexistent.txt || echo "File not found, showing fallback message"'
|
||||
});
|
||||
console.log(orResult);
|
||||
|
||||
// Example 11: Sequential commands with ;
|
||||
console.log('\n--- Example 11: Sequential commands with ; ---');
|
||||
const sequentialResult = await shell.execute({
|
||||
command: 'echo "First command"; echo "Second command"; pwd'
|
||||
});
|
||||
console.log(sequentialResult);
|
||||
|
||||
// Example 12: Pipe commands
|
||||
console.log('\n--- Example 12: Pipe commands ---');
|
||||
const pipeResult = await shell.execute({
|
||||
command: 'echo "line1\nline2\nline3\nline4\nline5" | head -n 3'
|
||||
});
|
||||
console.log(pipeResult);
|
||||
|
||||
// Example 13: Complex pipe chain
|
||||
console.log('\n--- Example 13: Complex pipe chain ---');
|
||||
const complexPipeResult = await shell.execute({
|
||||
command: 'echo "apple\nbanana\napple\ncherry\nbanana\napple" | sort | uniq'
|
||||
});
|
||||
console.log(complexPipeResult);
|
||||
|
||||
// Example 14: Mixed compound operators
|
||||
console.log('\n--- Example 14: Mixed compound operators ---');
|
||||
const mixedResult = await shell.execute({
|
||||
command: 'echo "Processing..." && echo "data1\ndata2\ndata3" | wc -l && echo "Done!"'
|
||||
});
|
||||
console.log(mixedResult);
|
||||
}
|
||||
|
||||
/**
|
||||
* Example React hook for using ShellTool
|
||||
*/
|
||||
export function useShell(fs: JSRuntimeFS, cwd: string) {
|
||||
const shell = new ShellTool(fs, cwd, new Git(fs));
|
||||
|
||||
const executeCommand = async (command: string): Promise<string> => {
|
||||
try {
|
||||
return await shell.execute({ command });
|
||||
} catch (error) {
|
||||
return `Error: ${error instanceof Error ? error.message : 'Unknown error'}`;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
executeCommand,
|
||||
getCurrentDirectory: () => shell.getCurrentWorkingDirectory(),
|
||||
setCurrentDirectory: (newCwd: string) => shell.setCurrentWorkingDirectory(newCwd),
|
||||
getAvailableCommands: () => shell.getAvailableCommands(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Example integration with AI tools
|
||||
* Shows how the ShellTool can be used as part of an AI assistant
|
||||
*/
|
||||
export class AIShellIntegration {
|
||||
private shell: ShellTool;
|
||||
|
||||
constructor(fs: JSRuntimeFS, projectRoot: string) {
|
||||
this.shell = new ShellTool(fs, projectRoot, new Git(fs));
|
||||
}
|
||||
|
||||
/**
|
||||
* Process natural language requests and convert to shell commands
|
||||
*/
|
||||
async processNaturalLanguageRequest(request: string): Promise<string> {
|
||||
const lowerRequest = request.toLowerCase();
|
||||
|
||||
// Simple pattern matching for demonstration
|
||||
if (lowerRequest.includes('show me') && lowerRequest.includes('file')) {
|
||||
// Extract filename from request
|
||||
const fileMatch = request.match(/file\s+["']?([^"'\s]+)["']?/i);
|
||||
if (fileMatch) {
|
||||
const filename = fileMatch[1];
|
||||
return await this.shell.execute({ command: `cat ${filename}` });
|
||||
}
|
||||
}
|
||||
|
||||
if (lowerRequest.includes('list') && lowerRequest.includes('command')) {
|
||||
const commands = this.shell.getAvailableCommands();
|
||||
return commands.map(cmd => `${cmd.name}: ${cmd.description}`).join('\n');
|
||||
}
|
||||
|
||||
if (lowerRequest.includes('current') && lowerRequest.includes('directory')) {
|
||||
return `Current directory: ${this.shell.getCurrentWorkingDirectory()}`;
|
||||
}
|
||||
|
||||
return 'I can help you with file operations. Try asking me to "show me a file" or "list available commands".';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Example CLI-like interface
|
||||
*/
|
||||
export class SimpleCLI {
|
||||
private shell: ShellTool;
|
||||
private history: string[] = [];
|
||||
|
||||
constructor(fs: JSRuntimeFS, projectRoot: string) {
|
||||
this.shell = new ShellTool(fs, projectRoot, new Git(fs));
|
||||
}
|
||||
|
||||
async executeCommand(command: string): Promise<string> {
|
||||
this.history.push(command);
|
||||
|
||||
// Handle built-in commands
|
||||
if (command.trim() === 'help') {
|
||||
const commands = this.shell.getAvailableCommands();
|
||||
return [
|
||||
'Available commands:',
|
||||
...commands.map(cmd => ` ${cmd.usage} - ${cmd.description}`),
|
||||
'',
|
||||
'Built-in commands:',
|
||||
' help - Show this help message',
|
||||
' history - Show command history',
|
||||
' pwd - Show current directory',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
if (command.trim() === 'history') {
|
||||
return this.history.map((cmd, i) => `${i + 1}: ${cmd}`).join('\n');
|
||||
}
|
||||
|
||||
if (command.trim() === 'pwd') {
|
||||
return this.shell.getCurrentWorkingDirectory();
|
||||
}
|
||||
|
||||
// Execute through shell tool
|
||||
return await this.shell.execute({ command });
|
||||
}
|
||||
|
||||
getHistory(): string[] {
|
||||
return [...this.history];
|
||||
}
|
||||
|
||||
clearHistory(): void {
|
||||
this.history = [];
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { ShellTool } from './ShellTool';
|
||||
import { Git } from '../git';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import { NPool } from '@nostrify/nostrify';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
@@ -18,20 +19,32 @@ const createMockFS = (): JSRuntimeFS => ({
|
||||
symlink: vi.fn(),
|
||||
});
|
||||
|
||||
const createMockNostr = (): NPool => ({
|
||||
req: vi.fn(),
|
||||
query: vi.fn(),
|
||||
event: vi.fn(),
|
||||
group: vi.fn(),
|
||||
relay: vi.fn(),
|
||||
relays: new Map(),
|
||||
close: vi.fn(),
|
||||
}) as unknown as NPool;
|
||||
|
||||
describe('ShellTool', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let mockGit: Git;
|
||||
let mockNostr: NPool;
|
||||
let shellTool: ShellTool;
|
||||
const testCwd = '/test/dir';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
mockGit = new Git(mockFS);
|
||||
mockNostr = createMockNostr();
|
||||
mockGit = new Git({ fs: mockFS, nostr: mockNostr });
|
||||
shellTool = new ShellTool(mockFS, testCwd, mockGit);
|
||||
});
|
||||
|
||||
it('should have correct tool properties', () => {
|
||||
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators');
|
||||
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators');
|
||||
expect(shellTool.inputSchema).toBeDefined();
|
||||
});
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
GitCommand,
|
||||
GrepCommand,
|
||||
HeadCommand,
|
||||
HexdumpCommand,
|
||||
LsCommand,
|
||||
MkdirCommand,
|
||||
MvCommand,
|
||||
@@ -28,6 +29,7 @@ import {
|
||||
TouchCommand,
|
||||
TrCommand,
|
||||
UniqCommand,
|
||||
UnzipCommand,
|
||||
WcCommand,
|
||||
WhoamiCommand,
|
||||
WhichCommand
|
||||
@@ -46,7 +48,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
private git: Git;
|
||||
private commands: Map<string, ShellCommand>;
|
||||
|
||||
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators";
|
||||
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators";
|
||||
|
||||
readonly inputSchema = z.object({
|
||||
command: z.string().describe(
|
||||
@@ -75,6 +77,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
this.registerCommand(new GitCommand({ git: this.git, fs, cwd: this.cwd }));
|
||||
this.registerCommand(new GrepCommand(fs));
|
||||
this.registerCommand(new HeadCommand(fs));
|
||||
this.registerCommand(new HexdumpCommand(fs));
|
||||
this.registerCommand(new LsCommand(fs));
|
||||
this.registerCommand(new MkdirCommand(fs));
|
||||
this.registerCommand(new MvCommand(fs));
|
||||
@@ -85,6 +88,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
this.registerCommand(new TouchCommand(fs));
|
||||
this.registerCommand(new TrCommand(fs));
|
||||
this.registerCommand(new UniqCommand(fs));
|
||||
this.registerCommand(new UnzipCommand(fs));
|
||||
this.registerCommand(new WcCommand(fs));
|
||||
this.registerCommand(new WhoamiCommand());
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join } from "@std/path";
|
||||
import { join } from "path-browserify";
|
||||
import ignore from "ignore";
|
||||
import { z } from "zod";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { join, dirname } from "@std/path";
|
||||
import { join, dirname } from "path-browserify";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
|
||||
Reference in new issue
Block a user