From 86c1d964a3a56d5f19ce62f859e1fd62b9e821f4 Mon Sep 17 00:00:00 2001 From: yiling Date: Sun, 21 Jun 2026 20:14:26 +0800 Subject: [PATCH] feat(cli): add create-version command --- apps/cli/src/commands/commands.test.ts | 123 +++++++++++++++++++ apps/cli/src/commands/create-version.ts | 155 ++++++++++++++++++++++++ apps/cli/src/commands/upload.ts | 6 +- apps/cli/src/index.ts | 25 +++- 4 files changed, 301 insertions(+), 8 deletions(-) create mode 100644 apps/cli/src/commands/create-version.ts diff --git a/apps/cli/src/commands/commands.test.ts b/apps/cli/src/commands/commands.test.ts index 619e88e9..5abf1776 100644 --- a/apps/cli/src/commands/commands.test.ts +++ b/apps/cli/src/commands/commands.test.ts @@ -4,6 +4,7 @@ import { ls } from './ls' import { mkdir } from './mkdir' import { getClient } from '../client' import { upload } from './upload' +import { createVersion } from './create-version' import fs from 'node:fs' import http from 'node:http' @@ -238,4 +239,126 @@ describe('CLI Commands', () => { } }) }) + + describe('create-version', () => { + it('fails if local path is a directory', async () => { + const tempDir = 'temp-test-dir' + fs.mkdirSync(tempDir, { recursive: true }) + + await expect(createVersion(tempDir, 'file-123')).rejects.toThrow('process.exit(1)') + + try { + fs.rmdirSync(tempDir) + } catch { + // Ignore + } + }) + + it('fails if parent asset is not file or version_stack', async () => { + const tempFile = 'temp-test-file-ver.txt' + fs.writeFileSync(tempFile, 'hello ver') + + mockClient.api.folders[':folderId'].$get.mockResolvedValue({ + ok: true, + json: async () => ({ type: 'folder', projectId: 'p123' }), + // We use any here because we are mocking the hono client response shape in a unit test context + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any) + + await expect(createVersion(tempFile, 'folder-123')).rejects.toThrow('process.exit(1)') + + try { + fs.unlinkSync(tempFile) + } catch { + // Ignore + } + }) + + it('succeeds if parent asset is a file', async () => { + const tempFile = 'temp-test-file-ver.txt' + fs.writeFileSync(tempFile, 'hello ver') + + mockClient.api.folders[':folderId'].$get.mockResolvedValue({ + ok: true, + json: async () => ({ type: 'file', projectId: 'p123' }), + // We use any here because we are mocking the hono client response shape in a unit test context + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any) + + mockClient.api.projects[':projectId'].$get.mockResolvedValue({ + ok: true, + json: async () => ({ teamId: 't123' }), + // We use any here because we are mocking the hono client response shape in a unit test context + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any) + + mockClient.api.teams[':teamId'].upload.tasks.$post.mockImplementation( + async (req: unknown) => { + const rootNodeId = (req as { json: { files: { id: string }[] } }).json.files[0].id + return { + ok: true, + json: async () => ({ + taskId: 'task123', + presignedUrls: [ + { id: rootNodeId, fileId: 'file-123', url: 'http://localhost/upload' }, + ], + createdAssets: [{ tempId: rootNodeId, assetId: 'file-123' }], + }), + // We use any here because we are mocking the hono client response shape in a unit test context + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any + }, + ) + + mockClient.api.teams[':teamId'].upload.tasks[':taskId'].$patch.mockResolvedValue({ + ok: true, + // We use any here because we are mocking the hono client response shape in a unit test context + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any) + + const mockRes = { + statusCode: 200, + resume: vi.fn(), + } + let mockReqCallback: ((res: { statusCode: number; resume: () => void }) => void) | null = null + const mockReq = { + on: vi.fn().mockImplementation(() => { + return mockReq + }), + write: vi.fn(), + end: vi.fn().mockImplementation(() => { + if (mockReqCallback) { + mockReqCallback(mockRes) + } + }), + destroy: vi.fn(), + } + + vi.mocked(http.request).mockImplementation((( + _options: unknown, + callback: (res: { statusCode: number; resume: () => void }) => void, + ) => { + mockReqCallback = callback + return mockReq + // We use any here because we are mocking the http request function in a unit test context + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }) as any) + + await createVersion(tempFile, 'file-123') + + expect(mockClient.api.folders[':folderId'].$get).toHaveBeenCalledWith({ + param: { folderId: 'file-123' }, + }) + expect(mockClient.api.teams[':teamId'].upload.tasks.$post).toHaveBeenCalledWith({ + param: { teamId: 't123' }, + json: expect.objectContaining({ parentId: 'file-123' }), + }) + + try { + fs.unlinkSync(tempFile) + } catch { + // Ignore + } + }) + }) }) diff --git a/apps/cli/src/commands/create-version.ts b/apps/cli/src/commands/create-version.ts new file mode 100644 index 00000000..409014f5 --- /dev/null +++ b/apps/cli/src/commands/create-version.ts @@ -0,0 +1,155 @@ +import fs from 'node:fs' +import path from 'node:path' +import { ulid } from 'ulid' +import { getClient } from '../client' +import { getMediaType, ProgressTracker, uploadFileWithProgress } from './upload' + +export async function createVersion(localPath: string, parentId: string) { + if (!localPath) { + console.error('Error: Local file path is required.') + process.exit(1) + } + if (!parentId) { + console.error('Error: Parent ID (-p/--parent) is required.') + process.exit(1) + } + + const resolvedPath = path.resolve(localPath) + if (!fs.existsSync(resolvedPath)) { + console.error(`Error: Local path "${resolvedPath}" does not exist.`) + process.exit(1) + } + + const stat = fs.statSync(resolvedPath) + if (stat.isDirectory()) { + console.error( + `Error: Local path "${resolvedPath}" is a directory. create-version only supports uploading single files.`, + ) + process.exit(1) + } + + const client = getClient() + + try { + console.log(`Checking parent asset ${parentId}...`) + const assetRes = await client.api.folders[':folderId'].$get({ + param: { folderId: parentId }, + }) + + if (!assetRes.ok) { + const err = (await assetRes.json().catch(() => ({ error: 'Unknown error' }))) as { + error?: string + } + console.error(`Error fetching parent asset details: ${err.error || 'Failed'}`) + process.exit(1) + } + + const parentAsset = await assetRes.json() + if (parentAsset.type !== 'file' && parentAsset.type !== 'version_stack') { + console.error( + `Error: Parent asset must be a file or a version_stack (got "${parentAsset.type}").`, + ) + process.exit(1) + } + + const projectId = parentAsset.projectId + if (!projectId) { + console.error('Error: Parent asset does not belong to any project.') + process.exit(1) + } + + const projectRes = await client.api.projects[':projectId'].$get({ + param: { projectId }, + }) + if (!projectRes.ok) { + const err = (await projectRes.json().catch(() => ({ error: 'Unknown error' }))) as { + error?: string + } + console.error(`Error fetching project details: ${err.error || 'Failed'}`) + process.exit(1) + } + const project = await projectRes.json() + const teamId = project.teamId + + const name = path.basename(resolvedPath) + const mediaType = getMediaType(name) + + const fileNode = { + name, + id: ulid(), + size: stat.size, + children: [], + type: 'file', + mediaType, + } + + console.log(`Creating new version task...`) + + const taskRes = await client.api.teams[':teamId'].upload.tasks.$post({ + param: { teamId }, + json: { + parentId, + files: [fileNode], + }, + }) + + if (!taskRes.ok) { + const err = (await taskRes.json().catch(() => ({ error: 'Unknown error' }))) as { + error?: string + } + console.error(`Error creating version task: ${err.error || 'Failed'}`) + process.exit(1) + } + + const { taskId, presignedUrls, createdAssets } = await taskRes.json() + if (!presignedUrls || presignedUrls.length === 0) { + console.error('Error: Server did not return presigned upload URLs.') + process.exit(1) + } + + const urlObj = presignedUrls[0] + const progress = new ProgressTracker() + progress.addUpload(urlObj.id, name, stat.size) + + try { + await uploadFileWithProgress(urlObj.url, resolvedPath, mediaType, (bytes) => { + progress.updateProgress(urlObj.id, bytes) + }) + + const confirmRes = await client.api.teams[':teamId'].upload.tasks[':taskId'].$patch({ + param: { teamId, taskId }, + json: { fileId: urlObj.fileId }, + }) + + if (!confirmRes.ok) { + throw new Error('Failed to confirm upload') + } + } catch (err) { + console.error(`\nFailed to upload ${name}:`, err instanceof Error ? err.message : err) + await client.api.teams[':teamId'].upload.tasks[':taskId'] + .$patch({ + param: { teamId, taskId }, + json: { + fileId: urlObj.fileId, + errorMessage: err instanceof Error ? err.message : String(err), + }, + }) + .catch(() => {}) + process.exit(1) + } + + console.log('\nVersion upload completed!') + + if (createdAssets && createdAssets.length > 0) { + console.log('Created version asset ID:') + for (const asset of createdAssets) { + if (asset.tempId === fileNode.id) { + console.log(`- ${asset.assetId}`) + } + } + } + } catch (err) { + console.error('\nError connecting to API server:', err instanceof Error ? err.message : err) + process.exit(1) + } +} diff --git a/apps/cli/src/commands/upload.ts b/apps/cli/src/commands/upload.ts index 41b1dbef..925b15a1 100644 --- a/apps/cli/src/commands/upload.ts +++ b/apps/cli/src/commands/upload.ts @@ -15,7 +15,7 @@ interface CliFileNode { mediaType?: string } -function getMediaType(filename: string): string { +export function getMediaType(filename: string): string { const ext = path.extname(filename).toLowerCase() const mimeMap: Record = { '.png': 'image/png', @@ -79,7 +79,7 @@ async function buildFileTree( } } -class ProgressTracker { +export class ProgressTracker { private uploads = new Map() private isTty = process.stdout.isTTY private linesPrinted = 0 @@ -124,7 +124,7 @@ class ProgressTracker { } } -async function uploadFileWithProgress( +export async function uploadFileWithProgress( url: string, filePath: string, contentType: string, diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts index 689910e4..d503f784 100644 --- a/apps/cli/src/index.ts +++ b/apps/cli/src/index.ts @@ -2,19 +2,21 @@ import { projectLs } from './commands/project' import { ls } from './commands/ls' import { mkdir } from './commands/mkdir' import { upload } from './commands/upload' +import { createVersion } from './commands/create-version' function printHelp() { console.log(` Usage: shumai-cli [arguments] [options] Commands: - project ls List all projects (returns id, name, root folder id) - ls -p List direct children of a parent folder (returns id, name, type, size) - mkdir -p Create a new folder in a parent folder - upload -p Upload a local file or folder to a parent folder + project ls List all projects (returns id, name, root folder id) + ls -p List direct children of a parent folder (returns id, name, type, size) + mkdir -p Create a new folder in a parent folder + upload -p Upload a local file or folder to a parent folder + create-version -p Create a new version of an existing file or version stack Options: - -p, --parent The parent folder ID (required for ls, mkdir, upload) + -p, --parent The parent folder/asset ID (required for ls, mkdir, upload, create-version) -h, --help Show help details `) } @@ -77,6 +79,19 @@ async function main() { process.exit(1) } await upload(localPath, parentId) + } else if (cmd === 'create-version') { + const localPath = cleanArgs[1] + if (!localPath) { + console.error( + 'Error: Local file path is required. Usage: shumai-cli create-version -p ', + ) + process.exit(1) + } + if (!parentId) { + console.error('Error: Option -p/--parent is required.') + process.exit(1) + } + await createVersion(localPath, parentId) } else { console.error(`Error: Unknown command "${cmd}". Run "shumai-cli --help" for usage.`) process.exit(1)