mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-19 14:16:29 +00:00
feat(cli): generate shumai-cli commands from Operations with commander (#496)
Rebuild the CLI on commander. Commands for every cli-surface Operation (project ls, ls, mkdir, rename, move/mv, delete/rm) are generated from @shumai/operations: positionals, options, choices, numeric parsing and help text come from the Zod input schema. They call POST /api/ops/:name with x-shumai-client: cli. Existing invocations keep working. Adds --json, ls --type/--first/ --after, typo suggestions, and generated help. upload and create-version stay hand-written. Drops the unused @shumai/core dependency.
This commit is contained in:
@@ -19,6 +19,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Changed
|
||||
|
||||
* **cli**: `shumai-cli` has clearer help for every command (`shumai-cli <command> --help`), suggests the right command when you mistype one, and can print raw JSON with `--json`. `ls` can now filter by type and page through very large folders. Existing commands work as before; the npm package now needs Node.js 22.12 or later
|
||||
* **agent**: When the agent lists a folder's contents, large folders are now paged with a "next page" marker instead of page numbers, and items appear in the same order as in the file browser
|
||||
* **api-token**: API tokens are now stored securely, so they can no longer be read back from the database. A new token is shown only once when you create it, so copy it right away; the token list now shows just the last few characters. Existing tokens keep working without any changes.
|
||||
|
||||
|
||||
+17
-2
@@ -8,7 +8,7 @@ The CLI allows you to view projects, list folder contents, create folders, uploa
|
||||
|
||||
## Installation
|
||||
|
||||
The CLI package is bundled inside the Shumai workspace.
|
||||
The CLI package is bundled inside the Shumai workspace. The published npm package (`@shumai-one/shumai-cli`) requires Node.js 22.12 or later.
|
||||
|
||||
### Environment Setup
|
||||
|
||||
@@ -39,6 +39,14 @@ Run `shumai-cli` or query specific commands:
|
||||
shumai-cli <command> [arguments] [options]
|
||||
```
|
||||
|
||||
Run `shumai-cli --help` to list all commands, and `shumai-cli <command> --help` for a command's arguments and options.
|
||||
|
||||
### Global Options
|
||||
|
||||
- `--json`: Print the raw JSON result instead of human-friendly text, for scripts and tools like `jq`. Example: `shumai-cli ls -p <parentId> --json | jq '.data[].id'`.
|
||||
|
||||
When the output is piped instead of shown in a terminal, tables are printed as tab-separated values without headers.
|
||||
|
||||
### Commands
|
||||
|
||||
#### 1. List Projects
|
||||
@@ -51,7 +59,7 @@ shumai-cli project ls
|
||||
|
||||
#### 2. List Directory Contents
|
||||
|
||||
List direct children (folders and files) of a parent folder.
|
||||
List direct children (folders and files) of a parent folder. Folders are listed first.
|
||||
|
||||
```bash
|
||||
shumai-cli ls -p <parentId>
|
||||
@@ -59,6 +67,9 @@ shumai-cli ls -p <parentId>
|
||||
|
||||
- **Options:**
|
||||
- `-p`, `--parent <id>`: The parent folder ID (required).
|
||||
- `--type <type>`: Only list `file`, `folder`, or `all` (default).
|
||||
- `--first <n>`: Maximum number of items to list (default and maximum: 200).
|
||||
- `--after <cursor>`: Continue a long listing. When more items exist, `ls` prints the cursor to pass here.
|
||||
|
||||
#### 3. Create a New Folder
|
||||
|
||||
@@ -133,3 +144,7 @@ To run the CLI in development mode inside the repository source code:
|
||||
```bash
|
||||
bun run apps/cli/src/index.ts project ls
|
||||
```
|
||||
|
||||
### Adding Commands
|
||||
|
||||
Most commands are generated from the shared Operation definitions in `packages/operations` (see "Operations" in `AGENTS.md`). An Operation with the `cli` surface and a `cli` spec becomes a command automatically, with arguments, options, and help text derived from its input schema. It is also available to Shumai's built-in agent and MCP server. Only commands that stream local files (`upload`, `create-version`) are written by hand in `src/program.ts`.
|
||||
|
||||
@@ -8,10 +8,12 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@shumai/api": "workspace:*",
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@shumai/operations": "workspace:*",
|
||||
"@shumai/tableprinter": "workspace:*",
|
||||
"commander": "15.0.0",
|
||||
"hono": "4.13.5",
|
||||
"ulid": "3.0.2"
|
||||
"ulid": "3.0.2",
|
||||
"zod": "4.5.4"
|
||||
}
|
||||
}
|
||||
|
||||
+13
-1
@@ -1,7 +1,13 @@
|
||||
import { hc } from 'hono/client'
|
||||
import type { AppType } from '@shumai/api'
|
||||
|
||||
export function getClient() {
|
||||
export interface CliConfig {
|
||||
apiServer: string
|
||||
apiKey: string
|
||||
}
|
||||
|
||||
/** Reads the server URL and API token from the environment, exiting with guidance if missing. */
|
||||
export function getCliConfig(): CliConfig {
|
||||
const apiKey = process.env.SHUMAI_API_KEY
|
||||
const apiServer = process.env.SHUMAI_API_SERVER
|
||||
|
||||
@@ -17,6 +23,12 @@ export function getClient() {
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
return { apiServer: apiServer.replace(/\/+$/, ''), apiKey }
|
||||
}
|
||||
|
||||
/** Typed REST client, used by commands that are not Operations yet (upload, create-version). */
|
||||
export function getClient() {
|
||||
const { apiServer, apiKey } = getCliConfig()
|
||||
return hc<AppType>(apiServer, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { projectLs } from './project'
|
||||
import { ls } from './ls'
|
||||
import { mkdir } from './mkdir'
|
||||
import { getClient } from '../client'
|
||||
import { upload } from './upload'
|
||||
import { createVersion } from './create-version'
|
||||
import { rename } from './rename'
|
||||
import { move } from './move'
|
||||
import { deleteAsset } from './delete'
|
||||
import fs from 'node:fs'
|
||||
import http from 'node:http'
|
||||
|
||||
@@ -21,7 +15,7 @@ vi.mock('node:http', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
describe('CLI Commands', () => {
|
||||
describe('CLI upload commands', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let logSpy: any
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -103,72 +97,6 @@ describe('CLI Commands', () => {
|
||||
}
|
||||
})
|
||||
|
||||
describe('project ls', () => {
|
||||
it('prints list of projects correctly', async () => {
|
||||
mockClient.api.projects.$get.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: [
|
||||
{ id: 'p1', name: 'Proj 1', rootFolder: 'root1' },
|
||||
{ id: 'p2', name: 'Proj 2', rootFolder: 'root2' },
|
||||
],
|
||||
}),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
await projectLs()
|
||||
|
||||
expect(mockClient.api.projects.$get).toHaveBeenCalledWith({
|
||||
query: { first: '200' },
|
||||
})
|
||||
expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('Proj 1'))
|
||||
expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('Proj 2'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('ls', () => {
|
||||
it('queries folders and files and displays table', async () => {
|
||||
mockClient.api.folders[':folderId'].children.$get
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: [{ id: 'subfolder1', name: 'Sub 1', type: 'folder', sizeByte: 0 }],
|
||||
}),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: [{ id: 'file1', name: 'doc.pdf', type: 'file', sizeByte: 1024 }],
|
||||
}),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
await ls('parentId123')
|
||||
|
||||
expect(mockClient.api.folders[':folderId'].children.$get).toHaveBeenCalledTimes(2)
|
||||
expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('Sub 1'))
|
||||
expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('doc.pdf'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('mkdir', () => {
|
||||
it('calls POST /folders and prints the folder ID', async () => {
|
||||
mockClient.api.folders.$post.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'new_folder_ulid' }),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
|
||||
await mkdir('NewFolder', 'parent_ulid')
|
||||
|
||||
expect(mockClient.api.folders.$post).toHaveBeenCalledWith({
|
||||
json: { name: 'NewFolder', parentId: 'parent_ulid' },
|
||||
})
|
||||
expect(logSpy).toHaveBeenCalledWith('Created folder with ID: new_folder_ulid')
|
||||
})
|
||||
})
|
||||
|
||||
describe('upload', () => {
|
||||
it('uploads a file successfully and confirms the task', async () => {
|
||||
const tempFile = 'temp-test-file.txt'
|
||||
@@ -383,192 +311,4 @@ describe('CLI Commands', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('rename', () => {
|
||||
it('exits with error when assetId or newName is missing', async () => {
|
||||
await expect(rename('', 'new-name')).rejects.toThrow('process.exit(1)')
|
||||
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Asset ID is required'))
|
||||
|
||||
await expect(rename('asset-1', '')).rejects.toThrow('process.exit(1)')
|
||||
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('New name is required'))
|
||||
})
|
||||
|
||||
it('renames a folder when asset type is folder', async () => {
|
||||
mockClient.api.folders[':folderId'].$get.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'f-1', type: 'folder' }),
|
||||
} as unknown as Response)
|
||||
mockClient.api.folders[':folderId'].$put.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'f-1', name: 'Renamed Folder' }),
|
||||
} as unknown as Response)
|
||||
|
||||
await rename('f-1', 'Renamed Folder')
|
||||
|
||||
expect(mockClient.api.folders[':folderId'].$put).toHaveBeenCalledWith({
|
||||
param: { folderId: 'f-1' },
|
||||
json: { name: 'Renamed Folder' },
|
||||
})
|
||||
expect(logSpy).toHaveBeenCalledWith('Renamed asset f-1 to "Renamed Folder"')
|
||||
})
|
||||
|
||||
it('renames a file when asset type is file', async () => {
|
||||
mockClient.api.folders[':folderId'].$get.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'file-1', type: 'file' }),
|
||||
} as unknown as Response)
|
||||
mockClient.api.files[':fileId'].$put.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'file-1', name: 'new.mp4' }),
|
||||
} as unknown as Response)
|
||||
|
||||
await rename('file-1', 'new.mp4')
|
||||
|
||||
expect(mockClient.api.files[':fileId'].$put).toHaveBeenCalledWith({
|
||||
param: { fileId: 'file-1' },
|
||||
json: { name: 'new.mp4' },
|
||||
})
|
||||
expect(logSpy).toHaveBeenCalledWith('Renamed asset file-1 to "new.mp4"')
|
||||
})
|
||||
|
||||
it('exits with error when asset fetch fails', async () => {
|
||||
mockClient.api.folders[':folderId'].$get.mockResolvedValue({
|
||||
ok: false,
|
||||
json: async () => ({ error: 'Asset not found' }),
|
||||
} as unknown as Response)
|
||||
|
||||
await expect(rename('unknown-id', 'name')).rejects.toThrow('process.exit(1)')
|
||||
expect(errorSpy).toHaveBeenCalledWith('Error: Asset not found')
|
||||
})
|
||||
})
|
||||
|
||||
describe('move', () => {
|
||||
it('exits with error when assetIds or parentId is missing', async () => {
|
||||
await expect(move([], 'parent-1')).rejects.toThrow('process.exit(1)')
|
||||
expect(errorSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('At least one asset ID is required'),
|
||||
)
|
||||
|
||||
await expect(move(['a-1'], '')).rejects.toThrow('process.exit(1)')
|
||||
expect(errorSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Option -p/--parent <parentId> is required'),
|
||||
)
|
||||
})
|
||||
|
||||
it('successfully moves assets', async () => {
|
||||
mockClient.api.folders[':folderId'].$get.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'parent-1', projectId: 'proj-1' }),
|
||||
} as unknown as Response)
|
||||
mockClient.api.projects[':projectId'].reparent.$post.mockResolvedValue({
|
||||
ok: true,
|
||||
} as unknown as Response)
|
||||
|
||||
await move(['a-1', 'a-2'], 'parent-1')
|
||||
|
||||
expect(mockClient.api.projects[':projectId'].reparent.$post).toHaveBeenCalledWith({
|
||||
param: { projectId: 'proj-1' },
|
||||
json: {
|
||||
assetIds: ['a-1', 'a-2'],
|
||||
newParentId: 'parent-1',
|
||||
},
|
||||
})
|
||||
expect(logSpy).toHaveBeenCalledWith('Moved 2 asset(s) to parent parent-1')
|
||||
})
|
||||
|
||||
it('exits with error when destination parent is not found', async () => {
|
||||
mockClient.api.folders[':folderId'].$get.mockResolvedValue({
|
||||
ok: false,
|
||||
json: async () => ({ error: 'Folder not found' }),
|
||||
} as unknown as Response)
|
||||
|
||||
await expect(move(['a-1'], 'missing-parent')).rejects.toThrow('process.exit(1)')
|
||||
expect(errorSpy).toHaveBeenCalledWith('Error: Folder not found')
|
||||
})
|
||||
})
|
||||
|
||||
describe('deleteAsset', () => {
|
||||
it('exits with error when SHUMAI_ALLOW_DELETE is not set or not true', async () => {
|
||||
delete process.env.SHUMAI_ALLOW_DELETE
|
||||
await expect(deleteAsset(['a-1'])).rejects.toThrow('process.exit(1)')
|
||||
expect(errorSpy).toHaveBeenCalledWith(
|
||||
'Error: Asset deletion is disabled in this environment.',
|
||||
)
|
||||
})
|
||||
|
||||
it('exits with error when assetIds is empty', async () => {
|
||||
process.env.SHUMAI_ALLOW_DELETE = 'true'
|
||||
await expect(deleteAsset([])).rejects.toThrow('process.exit(1)')
|
||||
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Asset ID is required'))
|
||||
})
|
||||
|
||||
it('exits with error when more than one asset ID is passed', async () => {
|
||||
process.env.SHUMAI_ALLOW_DELETE = 'true'
|
||||
await expect(deleteAsset(['a-1', 'a-2'])).rejects.toThrow('process.exit(1)')
|
||||
expect(errorSpy).toHaveBeenCalledWith('Error: Can only delete one asset at a time.')
|
||||
})
|
||||
|
||||
it('exits with error when asset is not found', async () => {
|
||||
process.env.SHUMAI_ALLOW_DELETE = 'true'
|
||||
mockClient.api.folders[':folderId'].$get.mockResolvedValue({
|
||||
ok: false,
|
||||
json: async () => ({ error: 'Asset not found' }),
|
||||
} as unknown as Response)
|
||||
|
||||
await expect(deleteAsset(['a-1'])).rejects.toThrow('process.exit(1)')
|
||||
expect(errorSpy).toHaveBeenCalledWith('Error: Asset not found')
|
||||
})
|
||||
|
||||
it('successfully deletes a file when SHUMAI_ALLOW_DELETE is true', async () => {
|
||||
process.env.SHUMAI_ALLOW_DELETE = 'true'
|
||||
mockClient.api.folders[':folderId'].$get.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'a-1', type: 'file' }),
|
||||
} as unknown as Response)
|
||||
mockClient.api.files.$delete.mockResolvedValue({
|
||||
ok: true,
|
||||
} as unknown as Response)
|
||||
|
||||
await deleteAsset(['a-1'])
|
||||
|
||||
expect(mockClient.api.files.$delete).toHaveBeenCalledWith({
|
||||
json: { ids: ['a-1'] },
|
||||
})
|
||||
expect(mockClient.api.folders.$delete).not.toHaveBeenCalled()
|
||||
expect(logSpy).toHaveBeenCalledWith('Deleted asset a-1')
|
||||
})
|
||||
|
||||
it('successfully deletes a folder when SHUMAI_ALLOW_DELETE is 1', async () => {
|
||||
process.env.SHUMAI_ALLOW_DELETE = '1'
|
||||
mockClient.api.folders[':folderId'].$get.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'folder-1', type: 'folder' }),
|
||||
} as unknown as Response)
|
||||
mockClient.api.folders.$delete.mockResolvedValue({
|
||||
ok: true,
|
||||
} as unknown as Response)
|
||||
|
||||
await deleteAsset(['folder-1'])
|
||||
|
||||
expect(mockClient.api.folders.$delete).toHaveBeenCalledWith({
|
||||
json: { ids: ['folder-1'] },
|
||||
})
|
||||
expect(logSpy).toHaveBeenCalledWith('Deleted asset folder-1')
|
||||
})
|
||||
|
||||
it('exits with error when delete API returns an error', async () => {
|
||||
process.env.SHUMAI_ALLOW_DELETE = 'true'
|
||||
mockClient.api.folders[':folderId'].$get.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'a-1', type: 'file' }),
|
||||
} as unknown as Response)
|
||||
mockClient.api.files.$delete.mockResolvedValue({
|
||||
ok: false,
|
||||
json: async () => ({ error: 'Failed to delete' }),
|
||||
} as unknown as Response)
|
||||
|
||||
await expect(deleteAsset(['a-1'])).rejects.toThrow('process.exit(1)')
|
||||
expect(errorSpy).toHaveBeenCalledWith('Error: Failed to delete')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { getClient } from '../client'
|
||||
|
||||
export async function deleteAsset(assetIds: string[]) {
|
||||
const isAllowed =
|
||||
process.env.SHUMAI_ALLOW_DELETE === 'true' || process.env.SHUMAI_ALLOW_DELETE === '1'
|
||||
if (!isAllowed) {
|
||||
console.error('Error: Asset deletion is disabled in this environment.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (!assetIds || assetIds.length === 0) {
|
||||
console.error('Error: Asset ID is required. Usage: shumai-cli delete <assetId>')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (assetIds.length > 1) {
|
||||
console.error('Error: Can only delete one asset at a time.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const assetId = assetIds[0]
|
||||
const client = getClient()
|
||||
|
||||
try {
|
||||
// Inspect asset to determine whether it is a folder or file
|
||||
const getRes = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: assetId },
|
||||
})
|
||||
|
||||
if (!getRes.ok) {
|
||||
const err = (await getRes.json().catch(() => ({ error: 'Asset not found' }))) as {
|
||||
error?: string
|
||||
}
|
||||
console.error(`Error: ${err.error || 'Asset not found'}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const asset = await getRes.json()
|
||||
const isFolder = asset.type === 'folder'
|
||||
|
||||
const res = isFolder
|
||||
? await client.api.folders.$delete({
|
||||
json: { ids: [assetId] },
|
||||
})
|
||||
: await client.api.files.$delete({
|
||||
json: { ids: [assetId] },
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => ({ error: 'Failed to delete asset' }))) as {
|
||||
error?: string
|
||||
}
|
||||
console.error(`Error: ${err.error || 'Failed to delete asset'}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log(`Deleted asset ${assetId}`)
|
||||
} catch (err) {
|
||||
console.error('Error connecting to API server:', err instanceof Error ? err.message : err)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
import { newTablePrinter, withTruncate } from '@shumai/tableprinter'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { getClient } from '../client'
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes === 0) return '-'
|
||||
const k = 1024
|
||||
const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
export async function ls(parentId: string) {
|
||||
if (!parentId) {
|
||||
console.error('Error: Parent ID (-p/--parent) is required.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const client = getClient()
|
||||
|
||||
try {
|
||||
const [foldersRes, filesRes] = await Promise.all([
|
||||
client.api.folders[':folderId'].children.$get({
|
||||
param: { folderId: parentId },
|
||||
query: { assetType: 'folder', first: '200' },
|
||||
}),
|
||||
client.api.folders[':folderId'].children.$get({
|
||||
param: { folderId: parentId },
|
||||
query: { assetType: 'file', first: '200' },
|
||||
}),
|
||||
])
|
||||
|
||||
if (!foldersRes.ok) {
|
||||
const err = (await foldersRes.json().catch(() => ({ error: 'Unknown error' }))) as {
|
||||
error?: string
|
||||
}
|
||||
console.error(`Error: ${err.error || 'Failed to list folders'}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (!filesRes.ok) {
|
||||
const err = (await filesRes.json().catch(() => ({ error: 'Unknown error' }))) as {
|
||||
error?: string
|
||||
}
|
||||
console.error(`Error: ${err.error || 'Failed to list files'}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const foldersData = await foldersRes.json()
|
||||
const filesData = await filesRes.json()
|
||||
|
||||
const folders = foldersData.data || []
|
||||
const files = filesData.data || []
|
||||
|
||||
const items = [
|
||||
...folders.map((f: AssetInfo) => ({ ...f, typeDisplay: 'folder' as const })),
|
||||
...files.map((f: AssetInfo) => ({ ...f, typeDisplay: 'file' as const })),
|
||||
]
|
||||
|
||||
if (items.length === 0) {
|
||||
console.log('No assets found in this folder.')
|
||||
return
|
||||
}
|
||||
|
||||
const isTty = process.stdout.isTTY
|
||||
const maxWidth = process.stdout.columns || 80
|
||||
const tp = newTablePrinter(process.stdout, isTty, maxWidth)
|
||||
|
||||
tp.addHeader(['ID', 'Name', 'Type', 'Size'])
|
||||
|
||||
for (const item of items) {
|
||||
tp.addField(item.id || '', withTruncate(null))
|
||||
tp.addField(item.name || '')
|
||||
tp.addField(item.typeDisplay, withTruncate(null))
|
||||
tp.addField(
|
||||
item.typeDisplay === 'folder' ? '-' : formatSize(item.sizeByte || 0),
|
||||
withTruncate(null),
|
||||
)
|
||||
tp.endRow()
|
||||
}
|
||||
|
||||
tp.render()
|
||||
} catch (err) {
|
||||
console.error('Error connecting to API server:', err instanceof Error ? err.message : err)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import { getClient } from '../client'
|
||||
|
||||
export async function mkdir(name: string, parentId: string) {
|
||||
if (!name) {
|
||||
console.error('Error: Folder name is required.')
|
||||
process.exit(1)
|
||||
}
|
||||
if (!parentId) {
|
||||
console.error('Error: Parent ID (-p/--parent) is required.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const client = getClient()
|
||||
|
||||
try {
|
||||
const res = await client.api.folders.$post({
|
||||
json: { name, parentId },
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => ({ error: 'Unknown error' }))) as { error?: string }
|
||||
console.error(`Error: ${err.error || 'Failed to create folder'}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const created = await res.json()
|
||||
console.log(`Created folder with ID: ${created.id}`)
|
||||
} catch (err) {
|
||||
console.error('Error connecting to API server:', err instanceof Error ? err.message : err)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import { getClient } from '../client'
|
||||
|
||||
export async function move(assetIds: string[], parentId: string) {
|
||||
if (!assetIds || assetIds.length === 0) {
|
||||
console.error(
|
||||
'Error: At least one asset ID is required. Usage: shumai-cli move <assetId...> -p <parentId>',
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
if (!parentId) {
|
||||
console.error('Error: Option -p/--parent <parentId> is required.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const client = getClient()
|
||||
|
||||
try {
|
||||
// Fetch destination folder to get its projectId
|
||||
const parentRes = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: parentId },
|
||||
})
|
||||
|
||||
if (!parentRes.ok) {
|
||||
const err = (await parentRes.json().catch(() => ({ error: 'Parent folder not found' }))) as {
|
||||
error?: string
|
||||
}
|
||||
console.error(`Error: ${err.error || 'Parent folder not found'}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const parentInfo = await parentRes.json()
|
||||
const projectId = parentInfo.projectId
|
||||
if (!projectId) {
|
||||
console.error('Error: Destination parent folder is not associated with a project.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const res = await client.api.projects[':projectId'].reparent.$post({
|
||||
param: { projectId },
|
||||
json: {
|
||||
assetIds,
|
||||
newParentId: parentId,
|
||||
},
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => ({ error: 'Failed to move assets' }))) as {
|
||||
error?: string
|
||||
}
|
||||
console.error(`Error: ${err.error || 'Failed to move assets'}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log(`Moved ${assetIds.length} asset(s) to parent ${parentId}`)
|
||||
} catch (err) {
|
||||
console.error('Error connecting to API server:', err instanceof Error ? err.message : err)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import { newTablePrinter } from '@shumai/tableprinter'
|
||||
import { getClient } from '../client'
|
||||
|
||||
export async function projectLs() {
|
||||
const client = getClient()
|
||||
try {
|
||||
const res = await client.api.projects.$get({
|
||||
query: { first: '200' },
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => ({ error: 'Unknown error' }))) as { error?: string }
|
||||
console.error(`Error: ${err.error || 'Failed to list projects'}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const { data: projects } = await res.json()
|
||||
|
||||
if (projects.length === 0) {
|
||||
console.log('No projects found.')
|
||||
return
|
||||
}
|
||||
|
||||
const isTty = process.stdout.isTTY
|
||||
const maxWidth = process.stdout.columns || 80
|
||||
const tp = newTablePrinter(process.stdout, isTty, maxWidth)
|
||||
|
||||
tp.addHeader(['ID', 'Name', 'Root Folder ID'])
|
||||
|
||||
for (const p of projects) {
|
||||
tp.addField(p.id || '')
|
||||
tp.addField(p.name || '')
|
||||
tp.addField(p.rootFolder || '')
|
||||
tp.endRow()
|
||||
}
|
||||
|
||||
tp.render()
|
||||
} catch (err) {
|
||||
console.error('Error connecting to API server:', err instanceof Error ? err.message : err)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
import { getClient } from '../client'
|
||||
|
||||
export async function rename(assetId: string, newName: string) {
|
||||
if (!assetId) {
|
||||
console.error('Error: Asset ID is required. Usage: shumai-cli rename <assetId> <newName>')
|
||||
process.exit(1)
|
||||
}
|
||||
if (!newName) {
|
||||
console.error('Error: New name is required. Usage: shumai-cli rename <assetId> <newName>')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const client = getClient()
|
||||
|
||||
try {
|
||||
// Determine whether asset is a folder or a file
|
||||
const getRes = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: assetId },
|
||||
})
|
||||
|
||||
if (!getRes.ok) {
|
||||
const err = (await getRes.json().catch(() => ({ error: 'Asset not found' }))) as {
|
||||
error?: string
|
||||
}
|
||||
console.error(`Error: ${err.error || 'Asset not found'}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const asset = await getRes.json()
|
||||
const isFolder = asset.type === 'folder'
|
||||
|
||||
const updateRes = isFolder
|
||||
? await client.api.folders[':folderId'].$put({
|
||||
param: { folderId: assetId },
|
||||
json: { name: newName },
|
||||
})
|
||||
: await client.api.files[':fileId'].$put({
|
||||
param: { fileId: assetId },
|
||||
json: { name: newName },
|
||||
})
|
||||
|
||||
if (!updateRes.ok) {
|
||||
const err = (await updateRes.json().catch(() => ({ error: 'Failed to rename asset' }))) as {
|
||||
error?: string
|
||||
}
|
||||
console.error(`Error: ${err.error || 'Failed to rename asset'}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log(`Renamed asset ${assetId} to "${newName}"`)
|
||||
} catch (err) {
|
||||
console.error('Error connecting to API server:', err instanceof Error ? err.message : err)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
+7
-138
@@ -1,140 +1,9 @@
|
||||
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'
|
||||
import { rename } from './commands/rename'
|
||||
import { move } from './commands/move'
|
||||
import { deleteAsset } from './commands/delete'
|
||||
import { formatCliError } from './operations/errors'
|
||||
import { createProgram } from './program'
|
||||
|
||||
function printHelp() {
|
||||
console.log(`
|
||||
Usage: shumai-cli <command> [arguments] [options]
|
||||
|
||||
Commands:
|
||||
project ls List all projects (returns id, name, root folder id)
|
||||
ls -p <parentId> List direct children of a parent folder (returns id, name, type, size)
|
||||
mkdir <name> -p <parentId> Create a new folder in a parent folder
|
||||
upload <path> -p <parentId> Upload a local file or folder to a parent folder
|
||||
create-version <path> -p <id> Create a new version of an existing file or version stack
|
||||
rename <assetId> <newName> Rename an existing file or folder
|
||||
move <assetIds...> -p <target> Move one or more assets to a destination parent folder (alias: mv)
|
||||
delete <assetId> Delete a single file or folder (alias: rm)
|
||||
|
||||
Options:
|
||||
-p, --parent <id> The parent folder/asset ID (required for ls, mkdir, upload, create-version, move)
|
||||
-h, --help Show help details
|
||||
`)
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = process.argv.slice(2)
|
||||
if (args.length === 0 || args.includes('-h') || args.includes('--help')) {
|
||||
printHelp()
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const cmd = args[0]
|
||||
|
||||
let parentId = ''
|
||||
const parentIdx = args.findIndex((a) => a === '-p' || a === '--parent')
|
||||
if (parentIdx !== -1 && parentIdx + 1 < args.length) {
|
||||
parentId = args[parentIdx + 1]
|
||||
}
|
||||
|
||||
const cleanArgs: string[] = []
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === '-p' || args[i] === '--parent') {
|
||||
i++
|
||||
} else {
|
||||
cleanArgs.push(args[i])
|
||||
}
|
||||
}
|
||||
|
||||
if (cmd === 'project' && cleanArgs[1] === 'ls') {
|
||||
await projectLs()
|
||||
} else if (cmd === 'ls') {
|
||||
if (!parentId) {
|
||||
console.error('Error: Option -p/--parent <parentId> is required.')
|
||||
process.exit(1)
|
||||
}
|
||||
await ls(parentId)
|
||||
} else if (cmd === 'mkdir') {
|
||||
const name = cleanArgs[1]
|
||||
if (!name) {
|
||||
console.error(
|
||||
'Error: Folder name is required. Usage: shumai-cli mkdir <folderName> -p <parentId>',
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
if (!parentId) {
|
||||
console.error('Error: Option -p/--parent <parentId> is required.')
|
||||
process.exit(1)
|
||||
}
|
||||
await mkdir(name, parentId)
|
||||
} else if (cmd === 'upload') {
|
||||
const localPath = cleanArgs[1]
|
||||
if (!localPath) {
|
||||
console.error(
|
||||
'Error: File/folder path is required. Usage: shumai-cli upload <localPath> -p <parentId>',
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
if (!parentId) {
|
||||
console.error('Error: Option -p/--parent <parentId> is required.')
|
||||
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 <localPath> -p <parentAssetId>',
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
if (!parentId) {
|
||||
console.error('Error: Option -p/--parent <parentAssetId> is required.')
|
||||
process.exit(1)
|
||||
}
|
||||
await createVersion(localPath, parentId)
|
||||
} else if (cmd === 'rename') {
|
||||
const assetId = cleanArgs[1]
|
||||
const newName = cleanArgs[2]
|
||||
if (!assetId || !newName) {
|
||||
console.error(
|
||||
'Error: Asset ID and new name are required. Usage: shumai-cli rename <assetId> <newName>',
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
await rename(assetId, newName)
|
||||
} else if (cmd === 'move' || cmd === 'mv') {
|
||||
const assetIds = cleanArgs.slice(1)
|
||||
if (assetIds.length === 0) {
|
||||
console.error(
|
||||
'Error: At least one asset ID is required. Usage: shumai-cli move <assetId...> -p <parentId>',
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
if (!parentId) {
|
||||
console.error('Error: Option -p/--parent <parentId> is required.')
|
||||
process.exit(1)
|
||||
}
|
||||
await move(assetIds, parentId)
|
||||
} else if (cmd === 'delete' || cmd === 'rm') {
|
||||
const assetIds = cleanArgs.slice(1)
|
||||
if (assetIds.length === 0) {
|
||||
console.error('Error: Asset ID is required. Usage: shumai-cli delete <assetId>')
|
||||
process.exit(1)
|
||||
}
|
||||
await deleteAsset(assetIds)
|
||||
} else {
|
||||
console.error(`Error: Unknown command "${cmd}". Run "shumai-cli --help" for usage.`)
|
||||
createProgram()
|
||||
.parseAsync(process.argv)
|
||||
.catch((err: unknown) => {
|
||||
console.error(formatCliError(err))
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('Unexpected error:', err)
|
||||
process.exit(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createFolder, listProjects } from '@shumai/operations'
|
||||
import { callOperation } from './call-operation'
|
||||
import { CliError } from './errors'
|
||||
|
||||
describe('callOperation', () => {
|
||||
const env = { ...process.env }
|
||||
const fetchMock = vi.fn<typeof fetch>()
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.SHUMAI_API_SERVER = 'http://shumai.test/'
|
||||
process.env.SHUMAI_API_KEY = 'shumai_token'
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...env }
|
||||
vi.unstubAllGlobals()
|
||||
fetchMock.mockReset()
|
||||
})
|
||||
|
||||
const json = (body: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
it('posts the input to /api/ops/:name with the token and CLI attribution', async () => {
|
||||
const folder = { id: 'f1', name: 'Renders', type: 'folder', size: 0, projectId: 'p1' }
|
||||
fetchMock.mockResolvedValue(json(folder))
|
||||
|
||||
const output = await callOperation(createFolder, { parent: 'root', name: 'Renders' })
|
||||
|
||||
expect(output).toEqual(folder)
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(url).toBe('http://shumai.test/api/ops/create_folder')
|
||||
expect(init).toMatchObject({
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer shumai_token',
|
||||
'Content-Type': 'application/json',
|
||||
'x-shumai-client': 'cli',
|
||||
},
|
||||
body: JSON.stringify({ parent: 'root', name: 'Renders' }),
|
||||
})
|
||||
})
|
||||
|
||||
it('throws the server error message', async () => {
|
||||
fetchMock.mockResolvedValue(json({ error: 'User is not a member of the team' }, 403))
|
||||
|
||||
await expect(callOperation(listProjects, {})).rejects.toEqual(
|
||||
new CliError('User is not a member of the team'),
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to the status when the error body is not JSON', async () => {
|
||||
fetchMock.mockResolvedValue(new Response('Bad gateway', { status: 502 }))
|
||||
|
||||
await expect(callOperation(listProjects, {})).rejects.toThrow('Request failed with status 502')
|
||||
})
|
||||
|
||||
it('reports connection failures', async () => {
|
||||
fetchMock.mockRejectedValue(new TypeError('fetch failed'))
|
||||
|
||||
await expect(callOperation(listProjects, {})).rejects.toMatchObject({
|
||||
message: 'Error connecting to API server: fetch failed',
|
||||
prefixed: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects responses that do not match the output schema', async () => {
|
||||
fetchMock.mockResolvedValue(json({ unexpected: true }))
|
||||
|
||||
await expect(callOperation(listProjects, {})).rejects.toThrow(
|
||||
'Unexpected response from server for list_projects',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { z } from 'zod'
|
||||
import type { AnyOperationDefinition } from '@shumai/operations'
|
||||
import { getCliConfig } from '../client'
|
||||
import { CliError } from './errors'
|
||||
|
||||
/** Header that attributes invocations to the CLI (`via: cli`) in audit logs. */
|
||||
const CLIENT_HEADER = 'x-shumai-client'
|
||||
|
||||
/** Signature used by generated commands, which only see type-erased definitions. */
|
||||
export type CallOperation = (
|
||||
definition: AnyOperationDefinition,
|
||||
input: Record<string, unknown>,
|
||||
) => Promise<unknown>
|
||||
|
||||
/** Runs an Operation on the server via `POST /api/ops/:name`. */
|
||||
export async function callOperation<TDef extends AnyOperationDefinition>(
|
||||
definition: TDef,
|
||||
input: z.output<TDef['input']>,
|
||||
): Promise<z.output<TDef['output']>> {
|
||||
const { apiServer, apiKey } = getCliConfig()
|
||||
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch(`${apiServer}/api/ops/${definition.name}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
[CLIENT_HEADER]: 'cli',
|
||||
},
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
} catch (err) {
|
||||
throw new CliError(
|
||||
`Error connecting to API server: ${err instanceof Error ? err.message : String(err)}`,
|
||||
{ prefixed: true },
|
||||
)
|
||||
}
|
||||
|
||||
const body: unknown = await res.json().catch(() => undefined)
|
||||
if (!res.ok) {
|
||||
const message =
|
||||
body && typeof body === 'object' && 'error' in body && typeof body.error === 'string'
|
||||
? body.error
|
||||
: `Request failed with status ${res.status}`
|
||||
throw new CliError(message)
|
||||
}
|
||||
|
||||
const parsed = definition.output.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
throw new CliError(`Unexpected response from server for ${definition.name}`)
|
||||
}
|
||||
// safeParse on the generic schema type loses the concrete shape; the schema guarantees it.
|
||||
return parsed.data as z.output<TDef['output']>
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/** An expected failure, printed as `Error: <message>` with exit code 1. */
|
||||
export class CliError extends Error {
|
||||
/** When true, the message already carries its own prefix and is printed as-is. */
|
||||
readonly prefixed: boolean
|
||||
|
||||
constructor(message: string, options: { prefixed?: boolean } = {}) {
|
||||
super(message)
|
||||
this.name = 'CliError'
|
||||
this.prefixed = options.prefixed ?? false
|
||||
}
|
||||
}
|
||||
|
||||
export function formatCliError(err: unknown): string {
|
||||
if (err instanceof CliError) {
|
||||
return err.prefixed ? err.message : `Error: ${err.message}`
|
||||
}
|
||||
return `Unexpected error: ${err instanceof Error ? err.message : String(err)}`
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { Command, InvalidArgumentError, Option } from 'commander'
|
||||
import { z } from 'zod'
|
||||
import type { AnyOperationDefinition } from '@shumai/operations'
|
||||
import type { CallOperation } from './call-operation'
|
||||
import { CliError } from './errors'
|
||||
import { renderOutput, type Output } from './render'
|
||||
|
||||
export interface GenerateDeps {
|
||||
callOperation: CallOperation
|
||||
output: Output
|
||||
/** Whether destructive Operations are allowed (SHUMAI_ALLOW_DELETE). */
|
||||
allowDestructive: () => boolean
|
||||
}
|
||||
|
||||
type FieldKind =
|
||||
| { type: 'string' }
|
||||
| { type: 'number' }
|
||||
| { type: 'boolean' }
|
||||
| { type: 'enum'; values: string[] }
|
||||
| { type: 'array' }
|
||||
|
||||
interface FieldInfo {
|
||||
name: string
|
||||
kind: FieldKind
|
||||
required: boolean
|
||||
description: string
|
||||
}
|
||||
|
||||
/** Strip optional/nullable/default wrappers to find the field's base schema. */
|
||||
function unwrap(schema: z.ZodType): z.ZodType {
|
||||
let current = schema
|
||||
while (
|
||||
current instanceof z.ZodOptional ||
|
||||
current instanceof z.ZodNullable ||
|
||||
current instanceof z.ZodDefault
|
||||
) {
|
||||
current = current.unwrap() as z.ZodType
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
function describeField(definition: AnyOperationDefinition, name: string): FieldInfo {
|
||||
const schema = definition.input.shape[name] as z.ZodType
|
||||
const base = unwrap(schema)
|
||||
let kind: FieldKind
|
||||
if (base instanceof z.ZodNumber) kind = { type: 'number' }
|
||||
else if (base instanceof z.ZodBoolean) kind = { type: 'boolean' }
|
||||
else if (base instanceof z.ZodEnum) kind = { type: 'enum', values: base.options.map(String) }
|
||||
else if (base instanceof z.ZodArray) kind = { type: 'array' }
|
||||
else if (base instanceof z.ZodString) kind = { type: 'string' }
|
||||
else {
|
||||
throw new Error(`${definition.name}.${name}: unsupported input type for the CLI`)
|
||||
}
|
||||
return {
|
||||
name,
|
||||
kind,
|
||||
required: !schema.safeParse(undefined).success,
|
||||
description: schema.description ?? base.description ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
function parseNumber(value: string): number {
|
||||
const parsed = Number(value)
|
||||
if (value.trim() === '' || Number.isNaN(parsed)) {
|
||||
throw new InvalidArgumentError('Not a number.')
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
function kebab(name: string): string {
|
||||
return name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)
|
||||
}
|
||||
|
||||
/** Find or create the subcommand path, e.g. `project` for `project ls`. */
|
||||
function ensureParent(program: Command, path: readonly string[]): Command {
|
||||
let parent = program
|
||||
for (const segment of path) {
|
||||
parent =
|
||||
parent.commands.find((c) => c.name() === segment) ??
|
||||
parent.command(segment).description(`Manage ${segment}s.`)
|
||||
}
|
||||
return parent
|
||||
}
|
||||
|
||||
/** Registers one command for each definition with a `cli` spec. */
|
||||
export function registerOperationCommands(
|
||||
program: Command,
|
||||
definitions: readonly AnyOperationDefinition[],
|
||||
deps: GenerateDeps,
|
||||
): void {
|
||||
for (const definition of definitions) {
|
||||
const cli = definition.cli
|
||||
if (!cli || !definition.surfaces.includes('cli')) continue
|
||||
|
||||
const parent = ensureParent(program, cli.command.slice(0, -1))
|
||||
const cmd = parent
|
||||
.command(cli.command[cli.command.length - 1])
|
||||
.description(cli.description ?? definition.description)
|
||||
if (cli.aliases) cmd.aliases([...cli.aliases])
|
||||
|
||||
const positional = (cli.positional ?? []).map((name) => describeField(definition, name))
|
||||
for (const field of positional) {
|
||||
const placeholder = field.kind.type === 'array' ? `${field.name}...` : field.name
|
||||
cmd.argument(field.required ? `<${placeholder}>` : `[${placeholder}]`, field.description)
|
||||
}
|
||||
|
||||
const positionalNames = new Set(positional.map((f) => f.name))
|
||||
const options: Array<{ field: FieldInfo; option: Option }> = []
|
||||
for (const name of Object.keys(definition.input.shape)) {
|
||||
if (positionalNames.has(name)) continue
|
||||
const field = describeField(definition, name)
|
||||
const spellings = cli.flags?.[name] ?? [`--${kebab(name)}`]
|
||||
const valueHint =
|
||||
field.kind.type === 'boolean'
|
||||
? ''
|
||||
: field.kind.type === 'array'
|
||||
? ` <${name}...>`
|
||||
: ` <${name}>`
|
||||
const option = new Option(`${spellings.join(', ')}${valueHint}`, field.description)
|
||||
if (field.kind.type === 'number') option.argParser(parseNumber)
|
||||
if (field.kind.type === 'enum') option.choices(field.kind.values)
|
||||
if (field.required) option.makeOptionMandatory()
|
||||
const cliDefault = (cli.defaults as Record<string, unknown> | undefined)?.[name]
|
||||
if (cliDefault !== undefined) option.default(cliDefault)
|
||||
cmd.addOption(option)
|
||||
options.push({ field, option })
|
||||
}
|
||||
|
||||
cmd.action(async (...args: unknown[]) => {
|
||||
const command = args[args.length - 1] as Command
|
||||
const input: Record<string, unknown> = { ...cli.defaults }
|
||||
positional.forEach((field, i) => {
|
||||
if (args[i] !== undefined) input[field.name] = args[i]
|
||||
})
|
||||
const opts = command.opts()
|
||||
for (const { field, option } of options) {
|
||||
const value = opts[option.attributeName()]
|
||||
if (value !== undefined) input[field.name] = value
|
||||
}
|
||||
|
||||
if (definition.annotations.destructive && !deps.allowDestructive()) {
|
||||
throw new CliError(
|
||||
`${definition.title} is disabled in this environment. Set SHUMAI_ALLOW_DELETE=true to enable it.`,
|
||||
)
|
||||
}
|
||||
|
||||
const parsed = definition.input.safeParse(input)
|
||||
if (!parsed.success) {
|
||||
throw new CliError(z.prettifyError(parsed.error))
|
||||
}
|
||||
|
||||
const output = await deps.callOperation(definition, parsed.data)
|
||||
if (command.optsWithGlobals().json) {
|
||||
deps.output.out.write(`${JSON.stringify(output, null, 2)}\n`)
|
||||
} else {
|
||||
renderOutput(definition, output, deps.output)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { z } from 'zod'
|
||||
import { defineOperation, listAssets, renameAsset } from '@shumai/operations'
|
||||
import { formatSize, renderOutput, type Output } from './render'
|
||||
|
||||
function capture(isTty = true): Output & { text: () => string } {
|
||||
let text = ''
|
||||
return { out: { write: (s) => void (text += s) }, isTty, columns: 120, text: () => text }
|
||||
}
|
||||
|
||||
const page = {
|
||||
data: [{ id: 'd1', name: 'Renders', type: 'folder', size: 0, projectId: 'p' }],
|
||||
pageInfo: { hasNextPage: true, endCursor: 'CUR' },
|
||||
total: 2,
|
||||
}
|
||||
|
||||
describe('renderOutput', () => {
|
||||
it('shows the next-page cursor only on a terminal', () => {
|
||||
const tty = capture(true)
|
||||
renderOutput(listAssets, page, tty)
|
||||
expect(tty.text()).toContain('Next page: --after CUR')
|
||||
|
||||
const piped = capture(false)
|
||||
renderOutput(listAssets, page, piped)
|
||||
expect(piped.text()).toBe('d1\tRenders\tfolder\t-\n')
|
||||
})
|
||||
|
||||
it('uses the definition formatter when there is no table renderer', () => {
|
||||
const o = capture()
|
||||
renderOutput(renameAsset, { id: 'a1', name: 'new', type: 'file', size: 1, projectId: null }, o)
|
||||
expect(o.text()).toBe('Renamed asset a1 to "new"\n')
|
||||
})
|
||||
|
||||
it('falls back to tables for lists and key/value lines for objects', () => {
|
||||
const generic = defineOperation({
|
||||
name: 'generic_thing',
|
||||
title: 'Generic',
|
||||
description: 'Generic output.',
|
||||
input: z.object({}),
|
||||
output: z.unknown(),
|
||||
surfaces: ['agent'],
|
||||
annotations: { readOnly: true, destructive: false },
|
||||
})
|
||||
|
||||
const list = capture(false)
|
||||
renderOutput(generic, { data: [{ id: 'x', tags: ['a'] }] }, list)
|
||||
expect(list.text()).toBe('x\t["a"]\n')
|
||||
|
||||
const empty = capture()
|
||||
renderOutput(generic, [], empty)
|
||||
expect(empty.text()).toBe('No results.\n')
|
||||
|
||||
const object = capture()
|
||||
renderOutput(generic, { id: 'x', count: 2, note: null }, object)
|
||||
expect(object.text()).toBe('id: x\ncount: 2\nnote: \n')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatSize', () => {
|
||||
it.each([
|
||||
[0, '-'],
|
||||
[512, '512 B'],
|
||||
[1536, '1.5 KB'],
|
||||
[5 * 1024 * 1024, '5 MB'],
|
||||
])('formats %d bytes as %s', (bytes, expected) => {
|
||||
expect(formatSize(bytes)).toBe(expected)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,121 @@
|
||||
import { newTablePrinter, withTruncate, type Writer } from '@shumai/tableprinter'
|
||||
import type {
|
||||
AnyOperationDefinition,
|
||||
AssetSummary,
|
||||
PageInfo,
|
||||
ProjectSummary,
|
||||
} from '@shumai/operations'
|
||||
|
||||
export interface Output {
|
||||
out: Writer
|
||||
isTty: boolean
|
||||
columns: number
|
||||
}
|
||||
|
||||
export function formatSize(bytes: number): string {
|
||||
if (bytes === 0) return '-'
|
||||
const k = 1024
|
||||
const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
function renderAssets(output: { data: AssetSummary[]; pageInfo: PageInfo }, o: Output): void {
|
||||
if (output.data.length === 0) {
|
||||
o.out.write('No assets found in this folder.\n')
|
||||
return
|
||||
}
|
||||
// Folders first, as in the file browser's default listing
|
||||
const items = [...output.data].sort(
|
||||
(a, b) => Number(b.type === 'folder') - Number(a.type === 'folder'),
|
||||
)
|
||||
const tp = newTablePrinter(o.out, o.isTty, o.columns)
|
||||
tp.addHeader(['ID', 'Name', 'Type', 'Size'])
|
||||
for (const item of items) {
|
||||
const isFolder = item.type === 'folder'
|
||||
tp.addField(item.id, withTruncate(null))
|
||||
tp.addField(item.name)
|
||||
tp.addField(isFolder ? 'folder' : 'file', withTruncate(null))
|
||||
tp.addField(isFolder ? '-' : formatSize(item.size), withTruncate(null))
|
||||
tp.endRow()
|
||||
}
|
||||
tp.render()
|
||||
// Piped output is TSV for scripts (use --json for pagination metadata); keep it clean.
|
||||
if (o.isTty && output.pageInfo.hasNextPage && output.pageInfo.endCursor) {
|
||||
o.out.write(`\nMore assets available. Next page: --after ${output.pageInfo.endCursor}\n`)
|
||||
}
|
||||
}
|
||||
|
||||
function renderProjects(output: { data: ProjectSummary[] }, o: Output): void {
|
||||
if (output.data.length === 0) {
|
||||
o.out.write('No projects found.\n')
|
||||
return
|
||||
}
|
||||
const tp = newTablePrinter(o.out, o.isTty, o.columns)
|
||||
tp.addHeader(['ID', 'Name', 'Root Folder ID'])
|
||||
for (const p of output.data) {
|
||||
tp.addField(p.id)
|
||||
tp.addField(p.name)
|
||||
tp.addField(p.rootFolderId ?? '')
|
||||
tp.endRow()
|
||||
}
|
||||
tp.render()
|
||||
}
|
||||
|
||||
/** Table renderers for list Operations; other Operations use their `cli.format` or the fallback. */
|
||||
const tableRenderers = new Map<string, (output: never, o: Output) => void>([
|
||||
['list_assets', renderAssets],
|
||||
['list_projects', renderProjects],
|
||||
])
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function cell(value: unknown): string {
|
||||
if (value === null || value === undefined) return ''
|
||||
return typeof value === 'object' ? JSON.stringify(value) : String(value)
|
||||
}
|
||||
|
||||
/** Generic rendering: `{ data: [...] }` and arrays as tables, objects as `key: value` lines. */
|
||||
function renderFallback(output: unknown, o: Output): void {
|
||||
const rows = Array.isArray(output)
|
||||
? output
|
||||
: isRecord(output) && Array.isArray(output.data)
|
||||
? output.data
|
||||
: null
|
||||
if (rows) {
|
||||
if (rows.length === 0) {
|
||||
o.out.write('No results.\n')
|
||||
return
|
||||
}
|
||||
const keys = Object.keys(isRecord(rows[0]) ? rows[0] : { value: rows[0] })
|
||||
const tp = newTablePrinter(o.out, o.isTty, o.columns)
|
||||
tp.addHeader(keys)
|
||||
for (const row of rows) {
|
||||
for (const key of keys) tp.addField(cell(isRecord(row) ? row[key] : row))
|
||||
tp.endRow()
|
||||
}
|
||||
tp.render()
|
||||
return
|
||||
}
|
||||
if (isRecord(output)) {
|
||||
for (const [key, value] of Object.entries(output)) o.out.write(`${key}: ${cell(value)}\n`)
|
||||
return
|
||||
}
|
||||
o.out.write(`${cell(output)}\n`)
|
||||
}
|
||||
|
||||
/** Writes an Operation's output in human-friendly form. */
|
||||
export function renderOutput(definition: AnyOperationDefinition, output: unknown, o: Output): void {
|
||||
const table = tableRenderers.get(definition.name)
|
||||
if (table) {
|
||||
table(output as never, o)
|
||||
return
|
||||
}
|
||||
if (definition.cli?.format) {
|
||||
o.out.write(`${definition.cli.format(output)}\n`)
|
||||
return
|
||||
}
|
||||
renderFallback(output, o)
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Command } from 'commander'
|
||||
import {
|
||||
createFolder,
|
||||
deleteAsset,
|
||||
listAssets,
|
||||
listProjects,
|
||||
moveAssets,
|
||||
renameAsset,
|
||||
} from '@shumai/operations'
|
||||
import type { CallOperation } from './operations/call-operation'
|
||||
import { CliError, formatCliError } from './operations/errors'
|
||||
import { createProgram } from './program'
|
||||
|
||||
/** Runs the CLI with mocked Operation calls and captures stdout/stderr. */
|
||||
function setup() {
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
const callOperation = vi.fn<CallOperation>()
|
||||
const program = createProgram({
|
||||
callOperation,
|
||||
output: { out: { write: (s) => void (stdout += s) }, isTty: true, columns: 120 },
|
||||
})
|
||||
const configure = (cmd: Command) => {
|
||||
cmd.exitOverride().configureOutput({
|
||||
writeOut: (s) => void (stdout += s),
|
||||
writeErr: (s) => void (stderr += s),
|
||||
})
|
||||
cmd.commands.forEach(configure)
|
||||
}
|
||||
configure(program)
|
||||
return {
|
||||
callOperation,
|
||||
run: (...argv: string[]) => program.parseAsync(['node', 'shumai-cli', ...argv]),
|
||||
stdout: () => stdout,
|
||||
stderr: () => stderr,
|
||||
}
|
||||
}
|
||||
|
||||
const folder = { id: 'f-1', name: 'Renders', type: 'folder', size: 0, projectId: 'p-1' }
|
||||
|
||||
describe('shumai-cli', () => {
|
||||
const originalAllowDelete = process.env.SHUMAI_ALLOW_DELETE
|
||||
|
||||
afterEach(() => {
|
||||
if (originalAllowDelete === undefined) delete process.env.SHUMAI_ALLOW_DELETE
|
||||
else process.env.SHUMAI_ALLOW_DELETE = originalAllowDelete
|
||||
})
|
||||
|
||||
describe('project ls', () => {
|
||||
it('lists projects with their root folder', async () => {
|
||||
const cli = setup()
|
||||
cli.callOperation.mockResolvedValue({
|
||||
data: [
|
||||
{ id: 'p1', name: 'Proj 1', teamId: 't1', rootFolderId: 'root1' },
|
||||
{ id: 'p2', name: 'Proj 2', teamId: 't1', rootFolderId: 'root2' },
|
||||
],
|
||||
})
|
||||
|
||||
await cli.run('project', 'ls')
|
||||
|
||||
expect(cli.callOperation).toHaveBeenCalledWith(listProjects, {})
|
||||
expect(cli.stdout()).toContain('Root Folder ID')
|
||||
expect(cli.stdout()).toMatch(/p1\s+Proj 1\s+root1/)
|
||||
expect(cli.stdout()).toContain('Proj 2')
|
||||
})
|
||||
|
||||
it('reports when there are no projects', async () => {
|
||||
const cli = setup()
|
||||
cli.callOperation.mockResolvedValue({ data: [] })
|
||||
|
||||
await cli.run('project', 'ls')
|
||||
|
||||
expect(cli.stdout()).toBe('No projects found.\n')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ls', () => {
|
||||
it('lists a folder with the maximum page size, folders first', async () => {
|
||||
const cli = setup()
|
||||
cli.callOperation.mockResolvedValue({
|
||||
data: [
|
||||
{ id: 'file1', name: 'doc.pdf', type: 'file', size: 1024, projectId: 'p' },
|
||||
{ id: 'sub1', name: 'Sub 1', type: 'folder', size: 0, projectId: 'p' },
|
||||
],
|
||||
pageInfo: { hasNextPage: false, endCursor: null },
|
||||
total: 2,
|
||||
})
|
||||
|
||||
await cli.run('ls', '-p', 'parentId123')
|
||||
|
||||
expect(cli.callOperation).toHaveBeenCalledWith(listAssets, {
|
||||
parent: 'parentId123',
|
||||
first: 200,
|
||||
})
|
||||
const out = cli.stdout()
|
||||
expect(out.indexOf('Sub 1')).toBeLessThan(out.indexOf('doc.pdf'))
|
||||
expect(out).toMatch(/file1\s+doc\.pdf\s+file\s+1 KB/)
|
||||
expect(out).not.toContain('More assets available')
|
||||
})
|
||||
|
||||
it('passes pagination and type flags and prints the next-page cursor', async () => {
|
||||
const cli = setup()
|
||||
cli.callOperation.mockResolvedValue({
|
||||
data: [{ id: 'sub1', name: 'Sub 1', type: 'folder', size: 0, projectId: 'p' }],
|
||||
pageInfo: { hasNextPage: true, endCursor: 'cur-2' },
|
||||
total: 3,
|
||||
})
|
||||
|
||||
await cli.run('ls', '--parent', 'p1', '--type', 'folder', '--first', '1', '--after', 'cur-1')
|
||||
|
||||
expect(cli.callOperation).toHaveBeenCalledWith(listAssets, {
|
||||
parent: 'p1',
|
||||
type: 'folder',
|
||||
first: 1,
|
||||
after: 'cur-1',
|
||||
})
|
||||
expect(cli.stdout()).toContain('Next page: --after cur-2')
|
||||
})
|
||||
|
||||
it('requires the parent option', async () => {
|
||||
const cli = setup()
|
||||
|
||||
await expect(cli.run('ls')).rejects.toThrow()
|
||||
expect(cli.stderr()).toContain("required option '-p, --parent <parent>' not specified")
|
||||
expect(cli.callOperation).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an invalid type and a non-numeric page size', async () => {
|
||||
const cli = setup()
|
||||
|
||||
await expect(cli.run('ls', '-p', 'x', '--type', 'video')).rejects.toThrow()
|
||||
expect(cli.stderr()).toContain('Allowed choices are file, folder, all')
|
||||
|
||||
await expect(cli.run('ls', '-p', 'x', '--first', 'many')).rejects.toThrow()
|
||||
expect(cli.stderr()).toContain('Not a number')
|
||||
expect(cli.callOperation).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('mkdir', () => {
|
||||
it('creates a folder and prints its ID', async () => {
|
||||
const cli = setup()
|
||||
cli.callOperation.mockResolvedValue({ ...folder, id: 'new_folder_ulid' })
|
||||
|
||||
await cli.run('mkdir', 'NewFolder', '-p', 'parent_ulid')
|
||||
|
||||
expect(cli.callOperation).toHaveBeenCalledWith(createFolder, {
|
||||
name: 'NewFolder',
|
||||
parent: 'parent_ulid',
|
||||
})
|
||||
expect(cli.stdout()).toBe('Created folder with ID: new_folder_ulid\n')
|
||||
})
|
||||
|
||||
it('requires a folder name', async () => {
|
||||
const cli = setup()
|
||||
|
||||
await expect(cli.run('mkdir', '-p', 'parent_ulid')).rejects.toThrow()
|
||||
expect(cli.stderr()).toContain("missing required argument 'name'")
|
||||
})
|
||||
})
|
||||
|
||||
describe('rename', () => {
|
||||
it('renames an asset', async () => {
|
||||
const cli = setup()
|
||||
cli.callOperation.mockResolvedValue({ ...folder, name: 'Renamed Folder' })
|
||||
|
||||
await cli.run('rename', 'f-1', 'Renamed Folder')
|
||||
|
||||
expect(cli.callOperation).toHaveBeenCalledWith(renameAsset, {
|
||||
assetId: 'f-1',
|
||||
name: 'Renamed Folder',
|
||||
})
|
||||
expect(cli.stdout()).toBe('Renamed asset f-1 to "Renamed Folder"\n')
|
||||
})
|
||||
|
||||
it('requires both the asset ID and the new name', async () => {
|
||||
const cli = setup()
|
||||
|
||||
await expect(cli.run('rename', 'f-1')).rejects.toThrow()
|
||||
expect(cli.stderr()).toContain("missing required argument 'name'")
|
||||
})
|
||||
})
|
||||
|
||||
describe('move', () => {
|
||||
it.each(['move', 'mv'])('moves assets with %s', async (command) => {
|
||||
const cli = setup()
|
||||
cli.callOperation.mockResolvedValue({
|
||||
movedAssetIds: ['a-1', 'a-2'],
|
||||
newParentId: 'parent-1',
|
||||
})
|
||||
|
||||
await cli.run(command, 'a-1', 'a-2', '-p', 'parent-1')
|
||||
|
||||
expect(cli.callOperation).toHaveBeenCalledWith(moveAssets, {
|
||||
assetIds: ['a-1', 'a-2'],
|
||||
newParentId: 'parent-1',
|
||||
})
|
||||
expect(cli.stdout()).toBe('Moved 2 asset(s) to parent parent-1\n')
|
||||
})
|
||||
|
||||
it('requires at least one asset and a destination', async () => {
|
||||
const cli = setup()
|
||||
|
||||
await expect(cli.run('move', '-p', 'parent-1')).rejects.toThrow()
|
||||
expect(cli.stderr()).toContain("missing required argument 'assetIds'")
|
||||
|
||||
await expect(cli.run('move', 'a-1')).rejects.toThrow()
|
||||
expect(cli.stderr()).toContain("required option '-p, --parent <newParentId>' not specified")
|
||||
})
|
||||
})
|
||||
|
||||
describe('delete', () => {
|
||||
it.each([undefined, 'false'])(
|
||||
'refuses to delete when SHUMAI_ALLOW_DELETE is %s',
|
||||
async (value) => {
|
||||
if (value === undefined) delete process.env.SHUMAI_ALLOW_DELETE
|
||||
else process.env.SHUMAI_ALLOW_DELETE = value
|
||||
const cli = setup()
|
||||
|
||||
const error = await cli.run('delete', 'a-1').catch((err: unknown) => err)
|
||||
|
||||
expect(formatCliError(error)).toBe(
|
||||
'Error: Delete Asset is disabled in this environment. Set SHUMAI_ALLOW_DELETE=true to enable it.',
|
||||
)
|
||||
expect(cli.callOperation).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
['delete', 'true'],
|
||||
['rm', '1'],
|
||||
])('deletes with %s when SHUMAI_ALLOW_DELETE=%s', async (command, value) => {
|
||||
process.env.SHUMAI_ALLOW_DELETE = value
|
||||
const cli = setup()
|
||||
cli.callOperation.mockResolvedValue({ deletedAssetId: 'a-1' })
|
||||
|
||||
await cli.run(command, 'a-1')
|
||||
|
||||
expect(cli.callOperation).toHaveBeenCalledWith(deleteAsset, { assetId: 'a-1' })
|
||||
expect(cli.stdout()).toBe('Deleted asset a-1\n')
|
||||
})
|
||||
|
||||
it('deletes only one asset at a time', async () => {
|
||||
process.env.SHUMAI_ALLOW_DELETE = 'true'
|
||||
const cli = setup()
|
||||
|
||||
await expect(cli.run('delete', 'a-1', 'a-2')).rejects.toThrow()
|
||||
expect(cli.stderr()).toContain('too many arguments')
|
||||
expect(cli.callOperation).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('--json', () => {
|
||||
it('prints the raw Operation output', async () => {
|
||||
const cli = setup()
|
||||
cli.callOperation.mockResolvedValue(folder)
|
||||
|
||||
await cli.run('mkdir', 'Renders', '-p', 'root', '--json')
|
||||
|
||||
expect(JSON.parse(cli.stdout())).toEqual(folder)
|
||||
})
|
||||
|
||||
it('works before the command too', async () => {
|
||||
const cli = setup()
|
||||
cli.callOperation.mockResolvedValue({ data: [] })
|
||||
|
||||
await cli.run('--json', 'project', 'ls')
|
||||
|
||||
expect(JSON.parse(cli.stdout())).toEqual({ data: [] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('errors', () => {
|
||||
it('surfaces server errors for the entry point to print', async () => {
|
||||
const cli = setup()
|
||||
cli.callOperation.mockRejectedValue(new CliError('User is not a member of the team'))
|
||||
|
||||
const error = await cli.run('mkdir', 'x', '-p', 'root').catch((err: unknown) => err)
|
||||
|
||||
expect(formatCliError(error)).toBe('Error: User is not a member of the team')
|
||||
})
|
||||
|
||||
it('validates input against the Operation schema before calling the server', async () => {
|
||||
const cli = setup()
|
||||
|
||||
const error = await cli.run('mkdir', '', '-p', 'root').catch((err: unknown) => err)
|
||||
|
||||
expect(error).toBeInstanceOf(CliError)
|
||||
expect(cli.callOperation).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('suggests similar commands for typos', async () => {
|
||||
const cli = setup()
|
||||
|
||||
await expect(cli.run('mkidr', 'x')).rejects.toThrow()
|
||||
expect(cli.stderr()).toContain('Did you mean mkdir?')
|
||||
})
|
||||
})
|
||||
|
||||
describe('help', () => {
|
||||
it('lists every command, including generated ones', async () => {
|
||||
const cli = setup()
|
||||
|
||||
await expect(cli.run('--help')).rejects.toThrow()
|
||||
|
||||
const help = cli.stdout()
|
||||
for (const command of [
|
||||
'project',
|
||||
'ls',
|
||||
'mkdir',
|
||||
'rename',
|
||||
'move|mv',
|
||||
'delete|rm',
|
||||
'upload',
|
||||
'create-version',
|
||||
]) {
|
||||
expect(help).toContain(command)
|
||||
}
|
||||
expect(help).toContain('--json')
|
||||
})
|
||||
|
||||
it('documents generated options from the Operation schema', async () => {
|
||||
const cli = setup()
|
||||
|
||||
await expect(cli.run('ls', '--help')).rejects.toThrow()
|
||||
|
||||
const help = cli.stdout()
|
||||
expect(help).toContain('-p, --parent <parent>')
|
||||
expect(help).toContain('The parent folder ID to list assets from.')
|
||||
expect(help).toContain('--type <type>')
|
||||
expect(help).toContain('choices: "file", "folder", "all"')
|
||||
expect(help).toContain('(default: 200)')
|
||||
expect(help).toContain('List the files and folders inside a parent folder.')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatCliError', () => {
|
||||
beforeEach(() => vi.restoreAllMocks())
|
||||
|
||||
it('formats expected and unexpected errors', () => {
|
||||
expect(formatCliError(new CliError('boom'))).toBe('Error: boom')
|
||||
expect(
|
||||
formatCliError(new CliError('Error connecting to API server: x', { prefixed: true })),
|
||||
).toBe('Error connecting to API server: x')
|
||||
expect(formatCliError(new TypeError('bad'))).toBe('Unexpected error: bad')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Command } from 'commander'
|
||||
import { operationDefinitions } from '@shumai/operations'
|
||||
import { createVersion } from './commands/create-version'
|
||||
import { upload } from './commands/upload'
|
||||
import { callOperation, type CallOperation } from './operations/call-operation'
|
||||
import { registerOperationCommands } from './operations/generate'
|
||||
import type { Output } from './operations/render'
|
||||
|
||||
export interface ProgramOptions {
|
||||
callOperation?: CallOperation
|
||||
output?: Output
|
||||
}
|
||||
|
||||
function isDeleteAllowed(): boolean {
|
||||
const value = process.env.SHUMAI_ALLOW_DELETE
|
||||
return value === 'true' || value === '1'
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the `shumai-cli` program. Operation commands (ls, mkdir, rename, move, delete,
|
||||
* project ls, ...) are generated from `@shumai/operations`; upload and create-version stream
|
||||
* local files and are defined here.
|
||||
*/
|
||||
export function createProgram(options: ProgramOptions = {}): Command {
|
||||
const program = new Command()
|
||||
.name('shumai-cli')
|
||||
.description('Command line interface for the Shumai media workspace.')
|
||||
.option('--json', 'Print raw JSON output instead of human-friendly text')
|
||||
.showHelpAfterError()
|
||||
.showSuggestionAfterError()
|
||||
|
||||
registerOperationCommands(program, operationDefinitions, {
|
||||
callOperation: options.callOperation ?? callOperation,
|
||||
output: options.output ?? {
|
||||
out: process.stdout,
|
||||
isTty: Boolean(process.stdout.isTTY),
|
||||
columns: process.stdout.columns || 80,
|
||||
},
|
||||
allowDestructive: isDeleteAllowed,
|
||||
})
|
||||
|
||||
program
|
||||
.command('upload')
|
||||
.description('Upload a local file or folder to a parent folder.')
|
||||
.argument('<path>', 'Local file or folder to upload.')
|
||||
.requiredOption('-p, --parent <parentId>', 'The parent folder ID to upload into.')
|
||||
.action((localPath: string, opts: { parent: string }) => upload(localPath, opts.parent))
|
||||
|
||||
program
|
||||
.command('create-version')
|
||||
.description('Upload a local file as a new version of an existing file or version stack.')
|
||||
.argument('<path>', 'Local file to upload as the new version.')
|
||||
.requiredOption('-p, --parent <parentId>', 'The file or version stack ID to add a version to.')
|
||||
.action((localPath: string, opts: { parent: string }) => createVersion(localPath, opts.parent))
|
||||
|
||||
return program
|
||||
}
|
||||
@@ -50,11 +50,13 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@shumai/api": "workspace:*",
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@shumai/operations": "workspace:*",
|
||||
"@shumai/tableprinter": "workspace:*",
|
||||
"commander": "15.0.0",
|
||||
"hono": "4.13.5",
|
||||
"ulid": "3.0.2",
|
||||
"zod": "4.5.4",
|
||||
},
|
||||
},
|
||||
"apps/premiere-uxp": {
|
||||
@@ -1775,7 +1777,7 @@
|
||||
|
||||
"comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="],
|
||||
|
||||
"commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="],
|
||||
"commander": ["commander@15.0.0", "", {}, "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg=="],
|
||||
|
||||
"comment-json": ["comment-json@4.6.2", "", { "dependencies": { "array-timsort": "^1.0.3", "esprima": "^4.0.1" } }, "sha512-R2rze/hDX30uul4NZoIZ76ImSJLFxn/1/ZxtKC1L77y2X1k+yYu1joKbAtMA2Fg3hZrTOiw0I5mwVMo0cf250w=="],
|
||||
|
||||
@@ -3041,6 +3043,8 @@
|
||||
|
||||
"@grpc/grpc-js/@grpc/proto-loader": ["@grpc/proto-loader@0.8.1", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.5.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg=="],
|
||||
|
||||
"@inlang/paraglide-js/commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="],
|
||||
|
||||
"@inlang/sdk/@sinclair/typebox": ["@sinclair/typebox@0.31.30", "", {}, "sha512-MGsM7bVmHg3sUKCphlu3SGQ+T+5JTbygZWYArfKQCW5anJeACHeqLhcnf+R7XlCWZ+QR3C8JTBx3kCKJTN69ow=="],
|
||||
|
||||
"@isaacs/cliui/string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="],
|
||||
|
||||
@@ -20,7 +20,7 @@ export const listAssets = defineOperation({
|
||||
.min(1)
|
||||
.max(MAX_PAGE_SIZE)
|
||||
.optional()
|
||||
.describe(`Maximum number of assets to return. Default is 20, maximum ${MAX_PAGE_SIZE}.`),
|
||||
.describe(`Maximum number of assets to return (at most ${MAX_PAGE_SIZE}).`),
|
||||
after: z
|
||||
.string()
|
||||
.optional()
|
||||
@@ -35,6 +35,9 @@ export const listAssets = defineOperation({
|
||||
annotations: { readOnly: true, destructive: false, idempotent: true },
|
||||
cli: {
|
||||
command: ['ls'],
|
||||
description: 'List the files and folders inside a parent folder.',
|
||||
flags: { parent: ['-p', '--parent'] },
|
||||
// The CLI shows up to the maximum page by default; agents use the smaller default.
|
||||
defaults: { first: MAX_PAGE_SIZE },
|
||||
},
|
||||
})
|
||||
|
||||
@@ -73,5 +73,12 @@ describe('defineOperation', () => {
|
||||
cli: { command: ['get'], flags: { ['other' as 'id']: ['-o'] } },
|
||||
}),
|
||||
).toThrow('unknown input "other"')
|
||||
expect(() =>
|
||||
defineOperation({
|
||||
...baseDefinition(),
|
||||
surfaces: ['cli'],
|
||||
cli: { command: ['get'], defaults: { ['extra' as 'id']: 'x' } },
|
||||
}),
|
||||
).toThrow('unknown input "extra"')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -29,12 +29,16 @@ export interface OperationAnnotations {
|
||||
export interface CliSpec<TInput, TOutput> {
|
||||
/** Command path, e.g. `['mkdir']` or `['project', 'ls']`. */
|
||||
command: readonly string[]
|
||||
/** Help text for the command; defaults to the Operation description (which is written for LLMs). */
|
||||
description?: string
|
||||
/** Alternative names for the last command segment, e.g. `['mv']`. */
|
||||
aliases?: readonly string[]
|
||||
/** Input fields taken from positional arguments, in order. An array field must be last (variadic). */
|
||||
positional?: readonly (keyof TInput & string)[]
|
||||
/** Flag spellings for input fields, e.g. `{ parent: ['-p', '--parent'] }`. */
|
||||
flags?: { readonly [K in keyof TInput & string]?: readonly string[] }
|
||||
/** Input values the CLI uses when the user does not pass them (e.g. a larger page size). */
|
||||
defaults?: { readonly [K in keyof TInput & string]?: TInput[K] }
|
||||
/** Human-friendly rendering of the output; the CLI falls back to a generic renderer. */
|
||||
format?(output: TOutput): string
|
||||
}
|
||||
@@ -93,7 +97,11 @@ export function defineOperation<
|
||||
}
|
||||
if (def.cli) {
|
||||
const fields = new Set(Object.keys(def.input.shape))
|
||||
const referenced = [...(def.cli.positional ?? []), ...Object.keys(def.cli.flags ?? {})]
|
||||
const referenced = [
|
||||
...(def.cli.positional ?? []),
|
||||
...Object.keys(def.cli.flags ?? {}),
|
||||
...Object.keys(def.cli.defaults ?? {}),
|
||||
]
|
||||
for (const field of referenced) {
|
||||
if (!fields.has(field)) {
|
||||
throw new Error(`Operation "${def.name}" cli spec references unknown input "${field}"`)
|
||||
|
||||
@@ -24,5 +24,6 @@ export const listProjects = defineOperation({
|
||||
annotations: { readOnly: true, destructive: false, idempotent: true },
|
||||
cli: {
|
||||
command: ['project', 'ls'],
|
||||
description: 'List the projects you can access, with their root folder IDs.',
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user