Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

feat(tooling): drive genapi from route metadata and regenerate the API clients

hairyfff0ed54868ed
diff --git a/genapi.config.ts b/genapi.config.ts
index ef3d1c1e..ccdf9a39 100644
--- a/genapi.config.ts
+++ b/genapi.config.ts
@@ -10,12 +10,14 @@ const plugins = [
'dsh-tauri-worktree',
]
-const servers = plugins.map(plugin => ({
- output: { main: `packages/${plugin}/src/client/apis/index.ts` },
- server: { routes: `packages/${plugin}/src/host/routes`, plugin },
-}))
-
export default defineConfig({
preset: pluginPipeline,
- servers: servers as any[],
+ meta: { import: { http: 'dsh-tauri/client' } },
+ // worktree 的根级 routes/post.ts、routes/delete.ts 生成名是 `post` / 保留字 `delete`
+ patch: { operations: { delete: 'deleteWorktree', post: 'postWorktree' } },
+ servers: plugins.map(plugin => ({
+ input: `packages/${plugin}/src/host/routes`,
+ output: { main: `packages/${plugin}/src/client/apis/index.ts` },
+ meta: { baseURL: JSON.stringify(`/api/desktop/${plugin}`) },
+ })),
})
diff --git a/genapi.pipeline.ts b/genapi.pipeline.ts
index 4fce5c52..204dfd01 100644
--- a/genapi.pipeline.ts
+++ b/genapi.pipeline.ts
@@ -1,65 +1,88 @@
-import type { ApiPipeline, StatementField, StatementInterface } from '@genapi/shared'
+import type { ApiPipeline, StatementField } from '@genapi/shared'
+import type { Dirent } from 'node:fs'
import { existsSync, readdirSync, readFileSync } from 'node:fs'
-import { dirname, relative, resolve, sep } from 'node:path'
+import { basename, dirname, relative, resolve, sep } from 'node:path'
import process from 'node:process'
-import { createParser, parseMethodMetadata, parseMethodParameters, transformBodyStringify, transformFetchBody, transformHeaderOptions, transformParameters, transformQueryParams, transformUrlSyntax } from '@genapi/parser'
-import pipeline, { compiler, config as configure, dest, generate } from '@genapi/pipeline'
+import pipeline, { compiler, config, dest, generate } from '@genapi/pipeline'
+import { parser } from '@genapi/presets/swag-ofetch-ts'
/**
- * 自定义 genapi 管道:把每个插件 `src/host/routes/**` 的 handler 源码推导成 Swagger 2 规格,
- * 再走 genapi 既有 fetch/ts 流程生成 `src/client/apis/index.ts` 与 `index.type.ts`。
- *
- * 推导规则(文件路径 = URL 路径 = 函数名,与 PLUGIN_CLIENT.spec.md 一致):
- * `routes/session/archive/get.ts` → GET `${API_PREFIX}/session/archive` → `getSessionArchive`
- * - 目录名逐段进入路径与函数名;`get.ts` / `post.ts` 这类动词文件名只决定 method
- * - 请求参数取自 handler 的 `getQuery(event) as {...}` 与 `readBody<T>(event)`
- * - 响应类型取自 `defineEventHandler((event): Promise<T> => ...)` 的返回注解
- * - `src/client/types`、`src/shared/types`、`src/host/types` 里的类型声明递归展开进 definitions
+ * genapi 管道:唯一自定义步骤是 original —— 把插件 `src/host/routes/**` 的 handler 源码推导成 Swagger 2。
+ * `input` 即路由目录,文件路径 = URL 路径 = 函数名:`routes/session/archive/get.ts` → GET `/session/archive` → `getSessionArchive`;
+ * 请求参数取自 `getQuery(event) as {...}` / `readBody<T>(event)`,响应类型取自 `defineEventHandler(...)` 的返回注解。
+ * baseURL 与 fetch 导入一律来自 defineConfig 的 `meta`,管道内不做任何自定义解析。
*/
-export interface GenapiServerConfig {
- /** host 路由目录,相对仓库根:`packages/<plugin>/src/host/routes`。 */
- routes: string
- /** 插件 src 根,默认由 routes 反推(`routes/../../..`)。 */
- src?: string
- /** 输出:字符串等价于 `{ main }`;type 由 genapi 按 main 派生为 `index.type.ts`。 */
- output: string | { main?: string, type?: string | false }
- /** 线协议前缀,默认读 `src/shared/constants.ts` 里的 `*_API_PREFIX` / `API_PREFIX`。 */
- apiPrefix?: string
- /** 规格标题,默认取插件包名。 */
- plugin?: string
- /** fetch 导入方式:默认命名导入 `import { fetch }`;`default` 为 `import fetch`。 */
- fetchImport?: 'named' | 'default'
-}
-
const RE_HANDLER = /defineEventHandler\s*\(/
const RE_SKIP_FILE = /\.(?:test|spec)\.tsx?$|\.d\.ts$/
const RE_TS_FILE = /\.tsx?$/
const METHOD_FILES = new Set(['get', 'head', 'post', 'put', 'patch', 'delete', 'options'])
const reservedNames = new Set(['delete', 'new', 'await', 'yield', 'in', 'do', 'if', 'for', 'class', 'function', 'return', 'void', 'typeof', 'instanceof', 'switch', 'case', 'default', 'this', 'super', 'import', 'export', 'with'])
-const TYPE_ROOTS = ['client/types', 'shared/types', 'host/types']
+const RE_TYPES_FILE = /(?:\.types\.tsx?|[\\/]types[\\/][^\\/]+\.tsx?)$/
+const RE_OUTPUT_DIR = /[\\/]client[\\/]apis[\\/]/
+const NULLABLE_MEMBERS = new Set(['null', 'undefined'])
+/** 具名类型(原样 TS 别名):由 original 汇总后写回类型输出的 typings。 */
+const TYPINGS = new Map<string, string>()
+
+interface Schema {
+ $ref?: string
+ type?: string
+ enum?: string[]
+ items?: Schema
+ properties?: Record<string, Schema>
+ required?: string[]
+ additionalProperties?: Schema
+}
interface Declaration {
name: string
file: string
kind: 'interface' | 'alias'
body: string
- fields: StatementField[]
+ bases?: string[]
+}
+
+interface ImportBinding {
+ file: string
+ names: Map<string, string>
}
interface TypeIndex {
declarations: Map<string, Declaration[]>
- imports: Map<string, Map<string, { file: string, names: Map<string, string> }>>
+ imports: Map<string, Map<string, ImportBinding>>
}
interface HandlerParameter {
name: string
location: 'query' | 'body'
required: boolean
- schema: any
+ schema: Schema
+}
+
+type QueryParameter = Omit<Schema, 'required'> & {
+ name: string
+ in: 'query'
+ required: boolean
+}
+
+interface BodyParameter {
+ name: string
+ in: 'body'
+ required: boolean
+ schema: Schema
}
-function readIfExists(file: string): string | undefined {
- return existsSync(file) ? readFileSync(file, 'utf8') : undefined
+type OperationParameter = QueryParameter | BodyParameter
+
+interface Operation {
+ operationId: string
+ parameters: OperationParameter[]
+ responses: Record<string, { description: string, schema?: Schema }>
+}
+
+interface RouteFile {
+ segments: string[]
+ method: string
+ file: string
}
function toPosix(value: string): string {
@@ -71,7 +94,7 @@ function walkFiles(root: string, predicate: (file: string) => boolean): string[]
const stack = [root]
while (stack.length > 0) {
const current = stack.pop()!
- let entries
+ let entries: Dirent[]
try {
entries = readdirSync(current, { withFileTypes: true })
}
@@ -93,12 +116,6 @@ function walkFiles(root: string, predicate: (file: string) => boolean): string[]
return found.sort()
}
-function operationName(method: string, segments: string[]): string {
- return reservedNames.has(method)
- ? `${method}${toIdentifier(segments)}Root`
- : `${method}${toIdentifier(segments)}`
-}
-
function toIdentifier(segments: string[]): string {
return segments
.flatMap(segment => segment.split(/[^A-Z0-9]+/i))
@@ -107,44 +124,10 @@ function toIdentifier(segments: string[]): string {
.join('')
}
-function literalValue(source: string, expression: string): string | undefined {
- const known = new Map<string, string>()
- for (const match of source.matchAll(/export\s+const\s+([A-Za-z_$][\w$]*)\s*=\s*([^\n]+)/g))
- known.set(match[1], match[2].trim())
- let value = expression.trim()
- for (let round = 0; round < 6; round++) {
- const replaced = value.replace(/\$\{\s*([A-Z_$][\w$]*)\s*\}|([A-Z_$][\w$]*)/gi, (raw, inside, plain) => {
- const next = known.get(inside ?? plain)
- return next === undefined || next === raw ? raw : `(${next})`
- })
- if (replaced === value)
- break
- value = replaced
- }
- const template = value.trim()
- const unwrapped = template.startsWith('`') && template.endsWith('`') ? template.slice(1, -1) : template
- const candidate = unwrapped.replace(/[`'"]/g, '').trim()
- return /^\/[\w\-./]*$/.test(candidate) ? candidate : undefined
-}
-
-function resolveApiPrefix(constants: string | undefined, plugin: string, explicit?: string): string {
- if (explicit)
- return explicit.replace(/\/$/, '')
- if (constants !== undefined) {
- const declared = /export\s+const\s+\w*API_PREFIX\w*\s*=\s*([^\n]+)/.exec(constants)
- const value = declared ? literalValue(constants, declared[1]) : undefined
- if (value)
- return value.replace(/\/$/, '')
- const pathConstant = /export\s+const\s+\w+\s*=\s*(['"`]\/[^'"`\n]+['"`])/.exec(constants)
- const path = pathConstant ? literalValue(constants, pathConstant[1]) : undefined
- if (path) {
- const segments = path.split('/').filter(Boolean)
- if (segments.length >= 2 && segments[0] === 'api')
- return `/${segments.slice(0, 2).join('/')}`
- return `/${segments[0]}`
- }
- }
- return `/api/${plugin.replace(/^dsh-tauri-/, '')}`
+function operationName(method: string, segments: string[]): string {
+ return reservedNames.has(method)
+ ? `${method}${toIdentifier(segments)}Root`
+ : `${method}${toIdentifier(segments)}`
}
function splitTopLevel(input: string): string[] {
@@ -215,11 +198,11 @@ function splitMembers(input: string): string[] {
quote = char
continue
}
- if (char === '{' || char === '[' || char === '(') {
+ if (char === '{' || char === '[' || char === '(' || char === '<') {
depth++
continue
}
- if (char === '}' || char === ']' || char === ')') {
+ if (char === '}' || char === ']' || char === ')' || char === '>') {
depth--
continue
}
@@ -274,7 +257,7 @@ function genericArgs(input: string): string[] {
if (char === '>') {
depth--
if (depth === 0)
- return splitTopLevel(input.slice(start + 1, index))
+ return splitMembers(input.slice(start + 1, index))
}
}
return []
@@ -372,8 +355,12 @@ function sliceDeclaration(source: string, start: number): string | undefined {
depth--
continue
}
- if (char === '\n' && depth === 0)
- return source.slice(start, index).trim()
+ if (char === '\n' && depth === 0) {
+ const collected = source.slice(start, index).trimEnd()
+ const next = source.slice(index + 1).replace(/^\s+/, '')[0]
+ if (!/[|&]$/.test(collected) && next !== '|' && next !== '&')
+ return source.slice(start, index).trim()
+ }
}
return source.slice(start).trim()
}
@@ -384,21 +371,32 @@ function extractDeclarations(source: string, file: string, target: Map<string, D
list.push(declaration)
target.set(declaration.name, list)
}
- for (const match of source.matchAll(/(?:export\s+)?(?:declare\s+)?interface\s+(\w+)\s*\{/g)) {
- const body = sliceBalanced(source, match.index! + match[0].length - 1)
- if (body !== undefined)
- push({ name: match[1], file, kind: 'interface', body, fields: parseFields(body) })
+ for (const match of source.matchAll(/(?:export\s+)?(?:declare\s+)?interface\s+([\w$]+)/g)) {
+ const headStart = match.index + match[0].length
+ const open = source.indexOf('{', headStart)
+ if (open < 0)
+ continue
+ const head = source.slice(headStart, open)
+ if (head.length > 200 || head.includes(';') || head.includes('}'))
+ continue
+ const body = sliceBalanced(source, open)
+ if (body === undefined)
+ continue
+ const extendsAt = head.indexOf('extends')
+ const clause = extendsAt >= 0 ? head.slice(extendsAt + 'extends'.length).trim() : ''
+ const bases = clause.split(',').map(base => base.trim()).filter(Boolean)
+ push({ name: match[1], file, kind: 'interface', body, ...bases.length > 0 ? { bases } : {} })
}
for (const match of source.matchAll(/(?:export\s+)?(?:declare\s+)?type\s+(\w+)\s*=\s*/g)) {
- const body = sliceDeclaration(source, match.index! + match[0].length)
+ const body = sliceDeclaration(source, match.index + match[0].length)
if (body !== undefined)
- push({ name: match[1], file, kind: 'alias', body, fields: parseFields(body) })
+ push({ name: match[1], file, kind: 'alias', body })
}
}
function importNames(clause: string): Map<string, string> {
const names = new Map<string, string>()
- for (const raw of splitTopLevel(clause)) {
+ for (const raw of splitMembers(clause)) {
const part = raw.startsWith('type ') ? raw.slice(5).trim() : raw
const aliased = /^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/.exec(part)
if (aliased) {
@@ -420,8 +418,8 @@ function resolveSpecifier(file: string, specifier: string): string | undefined {
return undefined
}
-function collectImports(source: string, file: string): Map<string, { file: string, names: Map<string, string> }> {
- const map = new Map<string, { file: string, names: Map<string, string> }>()
+function collectImports(source: string, file: string): Map<string, ImportBinding> {
+ const map = new Map<string, ImportBinding>()
for (const statement of source.matchAll(/import[^\n]*?from\s*['"][^'"]+['"]/g)) {
const parts = /\bfrom\s*['"]([^'"]+)['"]\s*$/.exec(statement[0])
if (!parts)
@@ -448,26 +446,21 @@ function collectImports(source: string, file: string): Map<string, { file: strin
}
function typesRank(file: string): number {
- if (/[\\/]src[\\/]client[\\/]types[\\/]/.test(file))
+ if (/[\\/]src[\\/]host[\\/]/.test(file))
return 0
- if (/[\\/]src[\\/](?:shared|host)[\\/]types[\\/]/.test(file))
+ if (/[\\/]src[\\/]shared[\\/]/.test(file))
return 1
- if (/[\\/]types[\\/]/.test(file))
- return 2
- return 3
+ if (/[\\/]src[\\/]client[\\/]/.test(file))
+ return 3
+ return 2
}
function buildTypeIndex(src: string): TypeIndex {
const index: TypeIndex = { declarations: new Map(), imports: new Map() }
- for (const part of TYPE_ROOTS) {
- const root = resolve(src, part)
- if (!existsSync(root))
- continue
- for (const file of walkFiles(root, candidate => RE_TS_FILE.test(candidate) && !RE_SKIP_FILE.test(candidate))) {
- const source = readFileSync(file, 'utf8')
- index.imports.set(file, collectImports(source, file))
- extractDeclarations(source, file, index.declarations)
- }
+ for (const file of walkFiles(src, candidate => RE_TYPES_FILE.test(candidate) && RE_TS_FILE.test(candidate) && !RE_SKIP_FILE.test(candidate) && !RE_OUTPUT_DIR.test(candidate))) {
+ const source = readFileSync(file, 'utf8')
+ index.imports.set(file, collectImports(source, file))
+ extractDeclarations(source, file, index.declarations)
}
return index
}
@@ -475,13 +468,11 @@ function buildTypeIndex(src: string): TypeIndex {
function lookup(index: TypeIndex, name: string, file: string): Declaration | undefined {
const scope = index.imports.get(file)
const entry = scope ? [...scope.values()].find(candidate => candidate.names.has(name)) : undefined
- if (entry) {
- const original = entry.names.get(name)!
- const candidates = index.declarations.get(original) ?? []
- const preferred = candidates.find(candidate => candidate.file === entry.file) ?? candidates[0]
- if (preferred)
- return preferred
- }
+ const original = entry?.names.get(name)
+ const imported = original === undefined ? [] : index.declarations.get(original) ?? []
+ const preferred = imported.find(candidate => candidate.file === entry?.file) ?? imported[0]
+ if (preferred)
+ return preferred
const candidates = index.declarations.get(name) ?? []
const local = candidates.find(candidate => candidate.file === file)
if (local)
@@ -490,99 +481,169 @@ function lookup(index: TypeIndex, name: string, file: string): Declaration | und
return ranked[0]
}
-function toSchema(type: string, index: TypeIndex, file: string, definitions: Record<string, any>, referenced: Set<string>): any {
- const trimmed = type.trim()
- if (trimmed.length === 0)
+function toSchema(type: string, index: TypeIndex, file: string, definitions: Record<string, Schema>, referenced: Set<string>): Schema {
+ const trimmed = type.trim().replace(/^readonly\s+/, '')
+ if (trimmed.length === 0 || NULLABLE_MEMBERS.has(trimmed))
return { type: 'string' }
+ const parts = splitTopLevel(trimmed)
+ if (parts.length > 1)
+ return unionSchema(parts, index, file, definitions, referenced)
if (trimmed.startsWith('{'))
return objectSchema(trimmed, index, file, definitions, referenced)
if (trimmed.startsWith('[') && trimmed.endsWith(']'))
- return { type: 'array', items: toSchema(splitTopLevel(trimmed.slice(1, -1))[0] ?? 'unknown', index, file, definitions, referenced) }
+ return { type: 'array', items: toSchema(splitMembers(trimmed.slice(1, -1))[0] ?? 'string', index, file, definitions, referenced) }
+ if (trimmed.startsWith('(') && trimmed.endsWith(')'))
+ return toSchema(trimmed.slice(1, -1), index, file, definitions, referenced)
if (trimmed.includes('=>'))
return { type: 'string' }
- const parts = splitTopLevel(trimmed)
- if (parts.length > 1)
- return unionSchema(parts, index, file, definitions, referenced)
if (trimmed.endsWith('[]'))
return { type: 'array', items: toSchema(trimmed.slice(0, -2), index, file, definitions, referenced) }
const literal = /^['"]([^'"]*)['"]$/.exec(trimmed)
if (literal)
return { type: 'string', enum: [literal[1]] }
- if (trimmed === 'string' || trimmed === 'number' || trimmed === 'boolean')
- return { type: trimmed }
+ if (trimmed === 'string' || trimmed === 'number' || trimmed === 'boolean' || trimmed === 'true' || trimmed === 'false')
+ return { type: trimmed === 'true' || trimmed === 'false' ? 'boolean' : trimmed }
if (trimmed === 'unknown' || trimmed === 'any' || trimmed === 'object' || trimmed.startsWith('typeof '))
return { type: 'string' }
const generic = /^([A-Z_$][\w$.]*)\s*</i.exec(trimmed)
if (generic) {
const args = genericArgs(trimmed)
if (generic[1] === 'Record')
- return { type: 'object', additionalProperties: toSchema(args[1] ?? 'unknown', index, file, definitions, referenced) }
+ return { type: 'object', additionalProperties: toSchema(args[1] ?? 'string', index, file, definitions, referenced) }
+ if (generic[1] === 'Map')
+ return { type: 'object', additionalProperties: toSchema(args[1] ?? 'string', index, file, definitions, referenced) }
if (generic[1] === 'Array' || generic[1] === 'ReadonlyArray' || generic[1] === 'Set')
- return { type: 'array', items: toSchema(args[0] ?? 'unknown', index, file, definitions, referenced) }
+ return { type: 'array', items: toSchema(args[0] ?? 'string', index, file, definitions, referenced) }
if (['Partial', 'Required', 'Readonly', 'NonNullable', 'Promise'].includes(generic[1]))
- return toSchema(args[0] ?? 'unknown', index, file, definitions, referenced)
+ return toSchema(args[0] ?? 'string', index, file, definitions, referenced)
return { type: 'object', additionalProperties: { type: 'string' } }
}
const reference = /^([A-Z_$][\w$]*)$/i.exec(trimmed)
if (reference) {
const declaration = lookup(index, reference[1], file)
- if (declaration) {
- ensureDefinition(declaration, reference[1], index, definitions, referenced)
- return { $ref: `#/definitions/${reference[1]}` }
- }
+ if (declaration)
+ return namedSchema(reference[1], declaration, index)
}
return { type: 'string' }
}
-function unionSchema(parts: string[], index: TypeIndex, file: string, definitions: Record<string, any>, referenced: Set<string>): any {
- const members = parts.map(part => toSchema(part, index, file, definitions, referenced))
- const nonNull = members.filter(member => member.type !== 'null')
- if (nonNull.length === 0)
- return { type: 'null' }
- const nullable = members.length !== nonNull.length
- if (nonNull.length === 1 && nullable)
- return { ...nonNull[0], nullable: true }
- if (nonNull.every(member => typeof member.enum?.[0] === 'string'))
- return { type: 'string', enum: nonNull.map(member => member.enum[0]), ...nullable ? { nullable: true } : {} }
- if (nonNull.every(member => member.type === 'boolean'))
- return { type: 'boolean', ...nullable ? { nullable: true } : {} }
- if (nonNull.every(member => member.type === 'number'))
- return { type: 'number', ...nullable ? { nullable: true } : {} }
- if (nonNull.every(member => member.type === 'string'))
- return { type: 'string', ...nullable ? { nullable: true } : {} }
- return nullable ? { ...nonNull[0], nullable: true } : {}
-}
-
-function objectSchema(type: string, index: TypeIndex, file: string, definitions: Record<string, any>, referenced: Set<string>): any {
- const fields = parseFields(unwrap(type))
+/** 联合成员里可合并的对象形态:内联对象直接取 properties,`$ref` 取已解析定义的 properties。 */
+function objectMember(schema: Schema, definitions: Record<string, Schema>): Record<string, Schema> | undefined {
+ if (schema.$ref !== undefined) {
+ const name = schema.$ref.split('/').pop() ?? ''
+ const target = definitions[name]
+ return target?.properties
+ }
+ return schema.properties
+}
+
+function unionSchema(parts: string[], index: TypeIndex, file: string, definitions: Record<string, Schema>, referenced: Set<string>): Schema {
+ const members = parts.filter(part => !NULLABLE_MEMBERS.has(part.trim())).map(part => toSchema(part, index, file, definitions, referenced))
+ if (members.length === 0)
+ return { type: 'string' }
+ if (members.length === 1)
+ return members[0]
+ if (members.every(member => typeof member.enum?.[0] === 'string'))
+ return { type: 'string', enum: members.map(member => member.enum?.[0] ?? '') }
+ if (members.every(member => member.type === members[0].type) && members[0].properties === undefined && members[0].additionalProperties === undefined && members[0].type !== undefined)
+ return { type: members[0].type }
+ const shapes = members.map(member => objectMember(member, definitions))
+ if (shapes.every(shape => shape !== undefined)) {
+ const properties: Record<string, Schema> = {}
+ const counts = new Map<string, number>()
+ for (const shape of shapes) {
+ for (const [name, schema] of Object.entries(shape ?? {})) {
+ properties[name] ??= schema
+ counts.set(name, (counts.get(name) ?? 0) + 1)
+ }
+ }
+ if (Object.keys(properties).length === 0)
+ return { type: 'object', additionalProperties: { type: 'string' } }
+ const required = [...counts.entries()].filter(([, count]) => count === shapes.length).map(([name]) => name)
+ return required.length > 0 ? { type: 'object', properties, required } : { type: 'object', properties }
+ }
+ const concrete = members.find(member => member.$ref !== undefined || member.properties !== undefined || member.type !== undefined)
+ return concrete ?? { type: 'string' }
+}
+
+function fieldsSchema(fields: StatementField[], index: TypeIndex, file: string, definitions: Record<string, Schema>, referenced: Set<string>): Schema {
if (fields.length === 0)
return { type: 'object', additionalProperties: { type: 'string' } }
- const properties: Record<string, any> = {}
+ const properties: Record<string, Schema> = {}
const required: string[] = []
for (const field of fields) {
- properties[field.name] = toSchema(field.type === 'unknown' ? 'string' : field.type ?? 'string', index, file, definitions, referenced)
+ properties[field.name] = toSchema(field.type ?? 'string', index, file, definitions, referenced)
if (field.required)
required.push(field.name)
}
return required.length > 0 ? { type: 'object', properties, required } : { type: 'object', properties }
}
-function ensureDefinition(declaration: Declaration, name: string, index: TypeIndex, definitions: Record<string, any>, referenced: Set<string>): any {
- if (definitions[name] !== undefined)
- return definitions[name]
- if (referenced.has(name))
- return undefined
+function objectSchema(type: string, index: TypeIndex, file: string, definitions: Record<string, Schema>, referenced: Set<string>): Schema {
+ return fieldsSchema(parseFields(unwrap(type)), index, file, definitions, referenced)
+}
+
+/** 接口字段:自身字段 + `extends` 基类字段(递归解析,遇到环即停)。 */
+function interfaceFields(declaration: Declaration, index: TypeIndex, seen: Set<string>): StatementField[] {
+ const name = declaration.name ?? ''
+ if (seen.has(name))
+ return []
+ seen.add(name)
+ const bases = (declaration.bases ?? []).flatMap((base) => {
+ const resolved = lookup(index, base, declaration.file)
+ return resolved ? interfaceFields(resolved, index, seen) : []
+ })
+ return [...bases, ...parseFields(unwrap(`{${declaration.body}}`))]
+}
+
+/**
+ * 具名类型的 schema:原样登记为 `type` 别名(schema 表达不了字面量联合/可空/泛型,
+ * 逐字段近似会让 UI 端的判别联合类型失配),返回 `$ref` 供解析器引用。
+ * 请求体/查询参数的顶层具名类型仍走 definition(函数签名需要 `Types.` 命名空间前缀)。
+ */
+function namedSchema(name: string, declaration: Declaration, index: TypeIndex): Schema {
+ ensureTyping(name, declaration, index)
+ return { $ref: `#/definitions/${name}` }
+}
+
+const BUILTIN_TYPE_RE = new Set(['Array', 'ReadonlyArray', 'Record', 'Map', 'Set', 'WeakMap', 'WeakSet', 'Promise', 'Partial', 'Required', 'Readonly', 'NonNullable', 'Omit', 'Pick', 'Exclude', 'Extract', 'Date', 'Error', 'RegExp', 'RequestInit', 'BodyInit', 'FormData', 'AbortSignal', 'Uint8Array'])
+
+function declarationBody(declaration: Declaration): string {
+ if (declaration.kind === 'alias')
+ return declaration.body.trim()
+ const object = `{${declaration.body}}`
+ return declaration.bases && declaration.bases.length > 0 ? `${declaration.bases.join(' & ')} & ${object}` : object
+}
+
+/** 把具名声明连同它引用的同仓类型一起登记为 type 别名(导入别名按引用名登记,避免悬空标识符)。 */
+function ensureTyping(name: string, declaration: Declaration, index: TypeIndex): void {
+ if (TYPINGS.has(name))
+ return
+ const body = declarationBody(declaration)
+ TYPINGS.set(name, body)
+ for (const match of body.matchAll(/\b([A-Z_$][\w$]*)\b/g)) {
+ const reference = match[1]
+ if (BUILTIN_TYPE_RE.has(reference) || TYPINGS.has(reference))
+ continue
+ const dependency = lookup(index, reference, declaration.file)
+ if (dependency)
+ ensureTyping(reference, dependency, index)
+ }
+}
+
+function ensureDefinition(declaration: Declaration, name: string, index: TypeIndex, definitions: Record<string, Schema>, referenced: Set<string>): void {
+ if (definitions[name] !== undefined || referenced.has(name))
+ return
referenced.add(name)
- const target: any = {}
+ const target: Schema = {}
definitions[name] = target
const resolved = declaration.kind === 'interface'
- ? objectSchema(`{${declaration.body}}`, index, declaration.file, definitions, referenced)
+ ? fieldsSchema(interfaceFields(declaration, index, new Set()), index, declaration.file, definitions, referenced)
: toSchema(declaration.body, index, declaration.file, definitions, referenced)
Object.assign(target, resolved)
- return target
}
-function handlerParameters(source: string, operation: string, index: TypeIndex, file: string, definitions: Record<string, any>, referenced: Set<string>): HandlerParameter[] {
+function handlerParameters(source: string, operation: string, index: TypeIndex, file: string, definitions: Record<string, Schema>, referenced: Set<string>): HandlerParameter[] {
const parameters: HandlerParameter[] = []
const queryCast = /getQuery\s*\([^)]*\)\s*as\s*(\{[\s\S]*?\})\s*[;)\n]/.exec(source)
const queryType = genericOf(source, 'getQuery')
@@ -592,14 +653,25 @@ function handlerParameters(source: string, operation: string, index: TypeIndex,
name: field.name,
location: 'query',
required: field.required === true,
- schema: toSchema(field.type === 'unknown' ? 'string' : field.type ?? 'string', index, file, definitions, referenced),
+ schema: toSchema(field.type ?? 'string', index, file, definitions, referenced),
})
}
if (queryFields.length === 0 && queryType && !queryType.startsWith('{')) {
+ // 具名查询契约拆成逐字段 query 参数:解析器会据此合成 `<Operation>Query`,避免 `query: X` 自引用
const declaration = lookup(index, queryType, file)
- if (declaration) {
- ensureDefinition(declaration, queryType, index, definitions, referenced)
- parameters.push({ name: 'query', location: 'query', required: true, schema: { $ref: `#/definitions/${queryType}` } })
+ if (declaration && declaration.kind === 'interface') {
+ for (const field of interfaceFields(declaration, index, new Set())) {
+ parameters.push({
+ name: field.name,
+ location: 'query',
+ required: field.required === true,
+ schema: toSchema(field.type ?? 'string', index, declaration.file, definitions, referenced),
+ })
+ }
+ }
+ else {
+ const schema = declaration ? parameterSchema(queryType, declaration, index, file, definitions, referenced) : { type: 'object', additionalProperties: { type: 'string' } }
+ parameters.push({ name: 'query', location: 'query', required: false, schema })
}
}
const bodyType = genericOf(source, 'readBody')
@@ -612,13 +684,21 @@ function handlerParameters(source: string, operation: string, index: TypeIndex,
return parameters
}
const declaration = lookup(index, bodyType, file)
- if (declaration)
- ensureDefinition(declaration, bodyType, index, definitions, referenced)
- parameters.push({ name: 'body', location: 'body', required: true, schema: { $ref: `#/definitions/${bodyType}` } })
+ const schema = declaration ? parameterSchema(bodyType, declaration, index, file, definitions, referenced) : { type: 'object', additionalProperties: { type: 'string' } }
+ parameters.push({ name: 'body', location: 'body', required: true, schema })
}
return parameters
}
+/** 请求体/查询参数的顶层具名类型:登记为 definition(函数签名需要 `Types.` 前缀)。 */
+function parameterSchema(name: string, declaration: Declaration, index: TypeIndex, file: string, definitions: Record<string, Schema>, referenced: Set<string>): Schema {
+ const objectLike = declaration.kind === 'interface' || declaration.body.trim().startsWith('{')
+ if (!objectLike)
+ return toSchema(declaration.body, index, declaration.file, definitions, referenced)
+ ensureDefinition(declaration, name, index, definitions, referenced)
+ return { $ref: `#/definitions/${name}` }
+}
+
function scanArrow(input: string): string | undefined {
let depth = 0
let quote: string | undefined
@@ -660,6 +740,20 @@ function unwrapPromise(value: string): string {
return value.slice(open + 1, -1).trim()
}
+/** 响应契约:优先取 `defineEventHandler<EventHandlerRequest, X>` 的第二个类型实参,回退到箭头返回注解。 */
+function handlerResponseType(source: string): string | undefined {
+ const generic = genericOf(source, 'defineEventHandler')
+ if (generic !== undefined) {
+ const parts = splitMembers(generic)
+ if (parts.length > 1) {
+ const response = parts[parts.length - 1].trim()
+ if (response.length > 0)
+ return unwrapPromise(response)
+ }
+ }
+ return handlerReturnAnnotation(source)
+}
+
function handlerReturnAnnotation(source: string): string | undefined {
const start = RE_HANDLER.exec(source)
if (!start)
@@ -684,18 +778,16 @@ function handlerReturnAnnotation(source: string): string | undefined {
return annotation ? unwrapPromise(annotation) : undefined
}
-function operationResponse(source: string, index: TypeIndex, file: string, definitions: Record<string, any>, referenced: Set<string>): any {
- const annotation = handlerReturnAnnotation(source)
+function operationResponse(source: string, index: TypeIndex, file: string, definitions: Record<string, Schema>, referenced: Set<string>): Schema | undefined {
+ const annotation = handlerResponseType(source)
if (!annotation)
return undefined
const candidates = splitTopLevel(annotation)
const named = candidates.find(candidate => /^[A-Z_$][\w$]*$/i.test(candidate.trim()))
if (named) {
const declaration = lookup(index, named.trim(), file)
- if (declaration) {
- ensureDefinition(declaration, named.trim(), index, definitions, referenced)
- return { $ref: `#/definitions/${named.trim()}` }
- }
+ if (declaration)
+ return namedSchema(named.trim(), declaration, index)
}
const primitive = candidates.find(candidate => /^(?:string|number|boolean|string\[\]|number\[\]|boolean\[\])$/.test(candidate.trim()))
if (primitive) {
@@ -708,12 +800,6 @@ function operationResponse(source: string, index: TypeIndex, file: string, defin
return undefined
}
-interface RouteFile {
- segments: string[]
- method: string
- file: string
-}
-
function collectRouteFiles(routesDir: string): RouteFile[] {
const found: RouteFile[] = []
for (const file of walkFiles(routesDir, candidate => RE_TS_FILE.test(candidate) && !RE_SKIP_FILE.test(candidate))) {
@@ -728,75 +814,59 @@ function collectRouteFiles(routesDir: string): RouteFile[] {
return found
}
-function resolveSrc(cwd: string, server: GenapiServerConfig, routesDir: string): string {
- if (server.src)
- return resolve(cwd, server.src)
- const candidates = [
- resolve(routesDir, '..', '..'),
- resolve(routesDir, '..', '..', '..'),
- resolve(routesDir, '..', '..', '..', '..'),
- ]
- for (const candidate of candidates) {
- if (existsSync(resolve(candidate, 'shared')) || existsSync(resolve(candidate, 'client')) || existsSync(resolve(candidate, 'host')))
- return candidate
+function original(configRead: ApiPipeline.ConfigRead): ApiPipeline.ConfigRead {
+ const routesDir = resolve(process.cwd(), configRead.inputs.uri ?? '')
+ if (!existsSync(routesDir))
+ throw new Error(`genapi: 路由目录不存在 ${routesDir},请检查 genapi.config.ts 的 input`)
+ const src = resolve(routesDir, '..', '..')
+
+ // 请求客户端同样只认 defineConfig 的 meta:ofetch 实例 + 其选项类型
+ const http = configRead.config.meta?.import?.http
+ if (http !== undefined) {
+ configRead.graphs.scopes.main?.imports.unshift(
+ { names: ['FetchOptions'], value: http, type: true },
+ { names: ['ofetch'], value: http },
+ )
}
- return resolve(routesDir, '..', '..', '..')
-}
-
-function buildSource(configRead: ApiPipeline.ConfigRead, server: GenapiServerConfig): ApiPipeline.ConfigRead {
- const cwd = process.cwd()
- const routesDir = resolve(cwd, server.routes)
- const src = resolveSrc(cwd, server, routesDir)
- const plugin = server.plugin ?? toPosix(relative(cwd, src)).split('/')[1] ?? 'plugin'
- const apiPrefix = resolveApiPrefix(readIfExists(resolve(src, 'shared/constants.ts')), plugin, server.apiPrefix)
- configRead.config.meta ??= {}
- configRead.config.meta.baseURL = `"${apiPrefix}"`
- configRead.config.meta.import ??= {}
- configRead.config.meta.import.http ??= 'dsh-tauri/client'
- configRead.graphs.scopes.main ??= { comments: [], functions: [], imports: [], variables: [], typings: [], interfaces: [] }
- configRead.graphs.scopes.main.imports ??= []
- const httpImport = configRead.config.meta.import.http
- const imports = configRead.graphs.scopes.main.imports
- const kept = imports.filter(item => item.value !== httpImport)
- kept.unshift(server.fetchImport === 'default' ? { name: 'fetch', value: httpImport } : { names: ['fetch'], value: httpImport })
- configRead.graphs.scopes.main.imports = kept
+
const index = buildTypeIndex(src)
- const definitions: Record<string, any> = {}
+ TYPINGS.clear()
+ const definitions: Record<string, Schema> = {}
const referenced = new Set<string>()
- const paths: Record<string, any> = {}
+ const paths: Record<string, Record<string, Operation>> = {}
for (const route of collectRouteFiles(routesDir)) {
const source = readFileSync(route.file, 'utf8')
index.imports.set(route.file, collectImports(source, route.file))
extractDeclarations(source, route.file, index.declarations)
- const url = `${apiPrefix}${route.segments.length > 0 ? `/${route.segments.join('/')}` : ''}`
- const specPath = route.segments.length > 0 ? `/${route.segments.join('/')}` : '/'
+ // 根级路由文件(如 routes/post.ts)对应 baseURL 本身:空路径让 transformUrlSyntax 只产出 `${baseURL}`
+ const specPath = route.segments.length > 0 ? `/${route.segments.join('/')}` : ''
const operation = operationName(route.method, route.segments)
- const parameters = handlerParameters(source, operation, index, route.file, definitions, referenced).map((parameter) => {
- const { name, location, required, schema } = parameter
- return location === 'body'
- ? { name, in: 'body', required, schema }
- : { name, in: 'query', required, ...schema }
- })
- const responseSchema = operationResponse(source, index, route.file, definitions, referenced)
+ const parameters = handlerParameters(source, operation, index, route.file, definitions, referenced).map<OperationParameter>(parameter => parameter.location === 'body'
+ ? { name: parameter.name, in: 'body', required: parameter.required, schema: parameter.schema }
+ : { ...parameter.schema, name: parameter.name, in: 'query', required: parameter.required })
+ const schema = operationResponse(source, index, route.file, definitions, referenced)
+ const description = `${route.method.toUpperCase()} ${specPath.length > 0 ? specPath : '/'}`
paths[specPath] ??= {}
paths[specPath][route.method] = {
operationId: operation,
parameters,
- responses: { 200: responseSchema ? { description: `${route.method.toUpperCase()} ${url}`, schema: responseSchema } : { description: `${route.method.toUpperCase()} ${url}` } },
+ responses: { 200: schema ? { description, schema } : { description } },
}
}
+
const reachable = new Set<string>()
- const walk = (schema: any) => {
- if (Array.isArray(schema)) {
- for (const item of schema)
+ const walk = (node: unknown): void => {
+ if (Array.isArray(node)) {
+ for (const item of node)
walk(item)
return
}
- if (!schema || typeof schema !== 'object')
+ if (typeof node !== 'object' || node === null)
return
+ const schema = node as Schema
if (typeof schema.$ref === 'string') {
- const name = schema.$ref.split('/').pop()!
- if (!reachable.has(name)) {
+ const name = schema.$ref.split('/').pop()
+ if (name !== undefined && !reachable.has(name)) {
reachable.add(name)
walk(definitions[name])
}
@@ -807,102 +877,28 @@ function buildSource(configRead: ApiPipeline.ConfigRead, server: GenapiServerCon
}
for (const methods of Object.values(paths))
walk(methods)
- const pruned: Record<string, any> = {}
+
+ const pruned: Record<string, Schema> = {}
for (const name of reachable) {
- if (definitions[name] !== undefined)
- pruned[name] = definitions[name]
+ const definition = definitions[name]
+ if (definition !== undefined)
+ pruned[name] = definition
}
+
configRead.source = {
swagger: '2.0',
- info: { title: plugin, version: '0.0.0' },
+ info: { title: basename(dirname(src)), version: '0.0.0' },
paths,
definitions: pruned,
}
- return configRead
-}
-
-const routeParser = createParser((config, { configRead, functions, interfaces }) => {
- const { parameters, interfaces: attached, options } = parseMethodParameters(config as any)
- const meta = parseMethodMetadata(config as any)
- attached.forEach(item => interfaces.add('type', item as StatementInterface))
- parameters.push({ name: 'config', type: 'RequestInit', required: false })
- if (config.method.toLowerCase() !== 'get')
- options.unshift(['method', `"${config.method}"`])
- transformHeaderOptions('body', { options, parameters })
- options.push(['...', 'config'])
- const { spaceResponseType } = transformParameters(parameters, {
- syntax: 'typescript',
- configRead,
- description: meta.description,
- interfaces: interfaces.all(),
- responseType: meta.responseType,
- } as any)
- transformBodyStringify('body', { options, parameters })
- const url = transformQueryParams('query', { body: meta.body, options, url: meta.url })
- const requestUrl = transformUrlSyntax(url, { baseURL: configRead.config.meta?.baseURL })
- const name = reservedNames.has(meta.name) ? `${meta.name}Root` : meta.name
- functions.add('main', {
- export: true,
- async: true,
- name,
- description: meta.description,
- parameters,
- body: [...(meta.body ?? []), ...transformFetchBody(requestUrl, options as any, spaceResponseType)],
- })
-})
-
-const written = new Set<string>()
-const MARKER = '@generated by genapi'
-const BANNER = `/**
- * 禁止修改 — ${MARKER}
- *
- * 本文件由 \`pnpm genapi\` 依据插件 host 路由(\`src/host/routes/**\`)自动生成,
- * 任何手工改动都会在下次生成时被覆盖;缺少本标记的文件会被生成器拒绝覆盖。
- * 需要调整接口请改 host 路由后重新运行 \`pnpm genapi\`。
- */
-
-`
-
-function guardWrites(configRead: ApiPipeline.ConfigRead, force: boolean): void {
- for (const output of configRead.outputs) {
- if (written.has(output.path))
- throw new Error(`genapi: 输出路径重复,请为每个 server 指定不同的 output:${output.path}`)
- written.add(output.path)
- if (force || !existsSync(output.path))
- continue
- const current = readFileSync(output.path, 'utf8')
- if (current.trim().length === 0 || current.includes(MARKER))
- continue
- throw new Error(`genapi: 拒绝覆盖手写文件 ${relative(process.cwd(), output.path)}(缺少 "${MARKER}" 标记)。确认要重新生成请设置 GENAPI_FORCE=1。`)
- }
-}
-
-function markOutputs(configRead: ApiPipeline.ConfigRead): ApiPipeline.ConfigRead {
- for (const output of configRead.outputs) {
- if (!output.code || output.code.includes(MARKER))
- continue
- output.code = BANNER + output.code
+ // 字面量联合以 `type` 别名补进类型输出(schema 表达不了,否则会退化成 string)
+ const typeScope = configRead.graphs.scopes.type
+ if (typeScope !== undefined && TYPINGS.size > 0) {
+ typeScope.typings ??= []
+ for (const [name, value] of TYPINGS)
+ typeScope.typings.push({ name, value, export: true })
}
return configRead
}
-export function pluginPipeline(userConfig: ApiPipeline.Config): Promise<void> {
- const force = process.env.GENAPI_FORCE === '1'
- return pipeline(
- (config: ApiPipeline.Config) => {
- const configRead = configure(config)
- guardWrites(configRead, force)
- return configRead
- },
- (configRead: ApiPipeline.ConfigRead) => {
- const server = (configRead.config as ApiPipeline.Config & { server?: GenapiServerConfig }).server
- return server ? buildSource(configRead, server) : configRead
- },
- routeParser,
- compiler,
- generate,
- (configRead: ApiPipeline.ConfigRead) => {
- const marked = markOutputs(configRead)
- return dest(marked) as unknown as void
- },
- )(userConfig) as unknown as Promise<void>
-}
+
+export const pluginPipeline: ApiPipeline.Pipeline = pipeline(config, original, parser, compiler, generate, dest)
diff --git a/packages/dsh-tauri-panel-extension/src/client/apis/index.ts b/packages/dsh-tauri-panel-extension/src/client/apis/index.ts
index eee84cb6..0016f7a7 100644
--- a/packages/dsh-tauri-panel-extension/src/client/apis/index.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/apis/index.ts
@@ -1,69 +1,106 @@
-import type * as Types from './index.type'
-import { fetch } from 'dsh-tauri/client'
-import { API_PREFIX } from '../../shared/constants'
+/*
+ * @title dsh-tauri-panel-extension
+ * @swagger 2.0
+ * @version 0.0.0
+ */
-export const baseURL = API_PREFIX
+import type { FetchOptions } from "dsh-tauri/client";
+import { ofetch } from "dsh-tauri/client";
+import type * as Types from "./index.type";
-export function getSkills(): Promise<Types.SkillsResponse> {
- return fetch(`${baseURL}/skills`)
+export const baseURL = "/api/desktop/dsh-tauri-panel-extension";
+
+/** @method post */
+export function postHostRestart(options?: FetchOptions) {
+ return ofetch<void>("/host/restart", { baseURL, method: "post", ...options });
+}
+
+/** @method post */
+export function postImportApply(body: Types.McpImportApplyBody, options?: FetchOptions) {
+ return ofetch<Types.McpApplyImportResponse>("/import/apply", { baseURL, method: "post", body, ...options });
+}
+
+/** @method get */
+export function getImportScan(options?: FetchOptions) {
+ return ofetch<Types.McpImportScanResponse>("/import/scan", { baseURL, method: "get", ...options });
+}
+
+/** @method post */
+export function postMcpCheck(body: Types.McpCheckBody, options?: FetchOptions) {
+ return ofetch<Types.McpCheckResult>("/mcp/check", { baseURL, method: "post", body, ...options });
}
-export function postSkillsRefresh(): Promise<Types.SkillsResponse> {
- return fetch(`${baseURL}/skills/refresh`, { method: 'POST', body: {} })
+/** @method post */
+export function postMcpCopy(body: Types.McpCopyBody, options?: FetchOptions) {
+ return ofetch<void>("/mcp/copy", { baseURL, method: "post", body, ...options });
}
-export function getSkill(name: string): Promise<Types.SkillContentResponse> {
- return fetch(`${baseURL}/skill?name=${encodeURIComponent(name)}`)
+/** @method get */
+export function getMcp(options?: FetchOptions) {
+ return ofetch<Types.McpListResponse>("/mcp", { baseURL, method: "get", ...options });
}
-export function postSkillSave(body: Types.PostSkillSaveBody): Promise<Types.ActionResult> {
- return fetch(`${baseURL}/skill/save`, { method: 'POST', body })
+/** @method post */
+export function postMcp(body: Types.McpSaveBody, options?: FetchOptions) {
+ return ofetch<Types.McpSaveResponse>("/mcp", { baseURL, method: "post", body, ...options });
}
-export function postSkillDelete(body: Types.PostSkillDeleteBody): Promise<Types.ActionResult> {
- return fetch(`${baseURL}/skill/delete`, { method: 'POST', body })
+/** @method delete */
+export function deleteMcp(body: Types.McpRemoveBody, options?: FetchOptions) {
+ return ofetch<Types.McpActionResult>("/mcp", { baseURL, method: "delete", body, ...options });
}
-export function postSkillPolicy(body: Types.PostSkillPolicyBody): Promise<Types.ActionResult> {
- return fetch(`${baseURL}/skill/policy`, { method: 'POST', body })
+/** @method post */
+export function postMcpToggle(body: Types.McpToggleBody, options?: FetchOptions) {
+ return ofetch<Types.McpActionResult>("/mcp/toggle", { baseURL, method: "post", body, ...options });
}
-export function postOpen(target: { target: 'user-skills' | 'skill', name?: string }): Promise<Types.ActionResult> {
- return fetch(`${baseURL}/open`, { method: 'POST', body: target })
+/** @method post */
+export function postOpenDir(body: Types.SkillOpenBody, options?: FetchOptions) {
+ return ofetch<Types.ActionResult>("/open/dir", { baseURL, method: "post", body, ...options });
}
-export function postRootsAdd(url: string): Promise<Types.ActionResult> {
- return fetch(`${baseURL}/roots/add`, { method: 'POST', body: { kind: 'git', url } })
+/** @method get */
+export function getRoots(options?: FetchOptions) {
+ return ofetch<void>("/roots", { baseURL, method: "get", ...options });
}
-export function getMcp(): Promise<Types.McpListResponse> {
- return fetch(`${baseURL}/mcp`)
+/** @method post */
+export function postRoots(body: Types.RootAddBody, options?: FetchOptions) {
+ return ofetch<Types.RootAddResponse>("/roots", { baseURL, method: "post", body, ...options });
}
-export function postMcpSave(body: Record<string, unknown>): Promise<Types.McpSaveResponse> {
- return fetch(`${baseURL}/mcp/save`, { method: 'POST', body })
+/** @method delete */
+export function deleteRoots(body: Types.RootRemoveBody, options?: FetchOptions) {
+ return ofetch<Types.ActionResult>("/roots", { baseURL, method: "delete", body, ...options });
}
-export function postMcpCheck(body: { id: string }): Promise<Types.McpConnectivityResponse> {
- return fetch(`${baseURL}/mcp/check`, { method: 'POST', body })
+/** @method get */
+export function getSkill(params?: Types.GetSkillQuery, options?: FetchOptions) {
+ return ofetch<Types.SkillContentResponse>("/skill", { baseURL, method: "get", params, ...options });
}
-export function postMcpToggle(body: Types.PostMcpToggleBody): Promise<Types.ActionResult> {
- return fetch(`${baseURL}/mcp/toggle`, { method: 'POST', body })
+/** @method post */
+export function postSkill(body: Types.SkillSaveBody, options?: FetchOptions) {
+ return ofetch<Types.ActionResult>("/skill", { baseURL, method: "post", body, ...options });
}
-export function postMcpRemove(body: Types.PostMcpRemoveBody): Promise<Types.ActionResult> {
- return fetch(`${baseURL}/mcp/remove`, { method: 'POST', body })
+/** @method delete */
+export function deleteSkill(body: Types.SkillDeleteBody, options?: FetchOptions) {
+ return ofetch<Types.ActionResult>("/skill", { baseURL, method: "delete", body, ...options });
}
-export function getMcpImportScan(): Promise<Types.McpImportScanResponse> {
- return fetch(`${baseURL}/import/scan`)
+/** @method post */
+export function postSkillPolicy(body: Types.SkillPolicyBody, options?: FetchOptions) {
+ return ofetch<Types.ActionResult>("/skill/policy", { baseURL, method: "post", body, ...options });
}
-export function postMcpImportApply(body: Types.PostMcpApplyImportBody): Promise<Types.McpApplyImportResponse> {
- return fetch(`${baseURL}/import/apply`, { method: 'POST', body })
+/** @method get */
+export function getSkills(options?: FetchOptions) {
+ return ofetch<Types.SkillsResponse>("/skills", { baseURL, method: "get", ...options });
}
-export function postRestart(): Promise<unknown> {
- return fetch(`${baseURL}/restart`, { method: 'POST', body: {} })
+/** @method post */
+export function postSkillsRefresh(options?: FetchOptions) {
+ return ofetch<Types.SkillsResponse>("/skills/refresh", { baseURL, method: "post", ...options });
}
diff --git a/packages/dsh-tauri-panel-extension/src/client/apis/index.type.ts b/packages/dsh-tauri-panel-extension/src/client/apis/index.type.ts
index 941459a5..9c4fbbf8 100644
--- a/packages/dsh-tauri-panel-extension/src/client/apis/index.type.ts
+++ b/packages/dsh-tauri-panel-extension/src/client/apis/index.type.ts
@@ -1,111 +1,164 @@
-export interface McpRow {
- id: string
- layer?: 'global' | 'profile'
- shadowed?: boolean
- globalError?: string
- scope?: 'global' | 'profile'
- serverName: string
- transport: 'stdio' | 'streamable-http'
- disabled: boolean
- command?: string
- args?: string[]
- env?: Record<string, string>
- cwd?: string
- url?: string
- headers?: Record<string, string>
-}
-
-export interface ImportedServerView {
- agent: 'claude-code' | 'codex' | 'cursor' | 'gemini'
- name: string
- transport: 'stdio' | 'streamable-http'
- command?: string
- args?: string[]
- env?: Record<string, string>
- url?: string
- headers?: Record<string, string>
-}
-
-export interface SkillRepositoryView {
- id: string
- label: string
- kind: 'local' | 'git'
- githubUrl?: string
-}
-
-export interface SkillRowView {
- name: string
- description: string
- whenToUse?: string
- invocation: { modelInvocable: boolean, userInvocable: boolean }
- source: string
- editable: boolean
- removable: boolean
- dir?: string
- policyEditable: boolean
- repository?: SkillRepositoryView
-}
-
-export interface SkillsResponse {
- skills: SkillRowView[]
-}
-
-export interface SkillContentResponse {
- content: string
-}
-
-export interface ActionResult {
- ok: boolean
- error?: string
-}
-
-export interface McpSaveResponse {
- ok: boolean
- id: string
-}
-
-export interface McpListResponse {
- servers: McpRow[]
- global?: McpRow[]
- profile?: McpRow[]
-}
-
-export interface McpConnectivityResponse {
- ok: boolean
- latencyMs?: number
- error?: string
-}
-
-export interface McpImportScanResponse {
- servers: ImportedServerView[]
- existing: string[]
-}
-
-export interface McpApplyImportResponse {
- ok: boolean
- results: Array<{ name: string, ok: boolean, error?: string }>
-}
-
-export type PostSkillSaveBody = Record<string, unknown>
-
-export interface PostSkillDeleteBody {
- name: string
-}
-
-export interface PostSkillPolicyBody {
- name: string
- enabled: boolean
-}
-
-export interface PostMcpToggleBody {
- id: string
- disabled: boolean
-}
-
-export interface PostMcpRemoveBody {
- id: string
-}
-
-export interface PostMcpApplyImportBody {
- items: Array<{ agent: string, name: string }>
+export type McpApplyImportResponse = {
+ ok: boolean;
+ results: Array<{ name: string; ok: boolean; error?: string }>;
+ restartNeeded: boolean;
+};
+export type McpImportScanResponse = {
+ servers: ImportedServerView[];
+ existing: string[];
+};
+export type ImportedServerView = {
+ agent: "claude-code" | "codex" | "cursor" | "gemini";
+ name: string;
+ transport: "stdio" | "streamable-http";
+ command?: string;
+ args?: string[];
+ env?: Record<string, string>;
+ url?: string;
+ headers?: Record<string, string>;
+};
+export type McpCheckResult = {
+ ok: boolean;
+ detail?: string;
+};
+export type McpActionResult = {
+ ok: boolean;
+ restartNeeded: boolean;
+};
+export type McpListResponse = {
+ servers: McpRowView[];
+ globalError?: string;
+ restartNeeded: boolean;
+};
+export type McpRowView = {
+ id: string;
+ layer?: "global" | "profile";
+ shadowed?: boolean;
+ scope?: "global" | "profile";
+ serverName: string;
+ transport: "stdio" | "streamable-http";
+ disabled: boolean;
+ command?: string;
+ args?: string[];
+ env?: Record<string, string>;
+ cwd?: string;
+ url?: string;
+ headers?: Record<string, string>;
+};
+export type McpSaveResponse = {
+ ok: boolean;
+ id: string;
+ restartNeeded: boolean;
+};
+export type ActionResult = {
+ ok: boolean;
+ error?: string;
+};
+export type RootAddResponse = {
+ ok: boolean;
+ root: SkillSourceView;
+};
+export type SkillSourceView = {
+ id: string;
+ kind: "local" | "git";
+ label: string;
+ url?: string;
+ ref?: string;
+ path?: string;
+ roots: string[];
+ materialDir?: string;
+ addedAt: number;
+ live: boolean;
+};
+export type SkillContentResponse = {
+ name: string;
+ content: string;
+};
+export type SkillsResponse = {
+ skills: SkillRowView[];
+};
+export type SkillRowView = {
+ name: string;
+ description: string;
+ whenToUse?: string;
+ invocation: { modelInvocable: boolean; userInvocable: boolean };
+ source: string;
+ provider: string;
+ editable: boolean;
+ removable: boolean;
+ dir?: string;
+ policyEditable: boolean;
+ repository?: SkillRepositoryView;
+};
+export type SkillRepositoryView = {
+ id: string;
+ label: string;
+ kind: "local" | "git";
+ githubUrl?: string;
+};
+
+export interface McpImportApplyBody {
+ items: { agent: string; name: string }[];
+ scope?: string;
+}
+export interface McpCheckBody {
+ id: string;
+ scope?: string;
+}
+export interface McpCopyBody {
+ id?: string;
+ scope?: string;
+ toScope?: string;
+}
+export interface McpRemoveBody {
+ id: string;
+ scope?: string;
+}
+export interface McpSaveBody {
+ id: string;
+ serverName: string;
+ transport: string;
+ command?: string;
+ args?: string[];
+ env?: Record<string, string>;
+ cwd?: string;
+ url?: string;
+ headers?: Record<string, string>;
+ scope?: string;
+}
+export interface McpToggleBody {
+ id: string;
+ disabled: boolean;
+ scope?: string;
+}
+export interface SkillOpenBody {
+ target: string;
+ name?: string;
+ id?: string;
+}
+export interface RootRemoveBody {
+ id: string;
+}
+export interface RootAddBody {
+ kind: string;
+ path?: string;
+ url?: string;
+}
+export interface SkillDeleteBody {
+ name: string;
+}
+export interface SkillSaveBody {
+ name: string;
+ description: string;
+ whenToUse?: string;
+ modelInvocable?: boolean;
+ userInvocable?: boolean;
+ content: string;
+}
+export interface SkillPolicyBody {
+ name: string;
+ enabled: boolean;
+}
+export interface GetSkillQuery {
+ name?: string;
}
diff --git a/packages/dsh-tauri-panel-scheduler/src/client/apis/index.ts b/packages/dsh-tauri-panel-scheduler/src/client/apis/index.ts
index 11cd1091..eb92a352 100644
--- a/packages/dsh-tauri-panel-scheduler/src/client/apis/index.ts
+++ b/packages/dsh-tauri-panel-scheduler/src/client/apis/index.ts
@@ -1,45 +1,61 @@
-import type * as Types from './index.type'
-import { fetch } from 'dsh-tauri/client'
-import { API_PREFIX } from '../constants'
+/*
+ * @title dsh-tauri-panel-scheduler
+ * @swagger 2.0
+ * @version 0.0.0
+ */
-const baseURL = API_PREFIX
+import type { FetchOptions } from "dsh-tauri/client";
+import { ofetch } from "dsh-tauri/client";
+import type * as Types from "./index.type";
-export function getTasks(query?: Types.GetTasksQuery): Promise<Types.TasksResponse> {
- return fetch(`${baseURL}/tasks${query?.search ? `?search=${encodeURIComponent(query.search)}` : ''}`)
+export const baseURL = "/api/desktop/dsh-tauri-panel-scheduler";
+
+/** @method get */
+export function getHistory(params?: Types.GetHistoryQuery, options?: FetchOptions) {
+ return ofetch<Types.RunListResponse>("/history", { baseURL, method: "get", params, ...options });
}
-export function postTasksCreate(body: Types.PostTasksCreateBody): Promise<Types.TaskActionResult> {
- return fetch(`${baseURL}/tasks/create`, { method: 'POST', body })
+/** @method delete */
+export function deleteHistory(body: Types.IdBody, options?: FetchOptions) {
+ return ofetch<Types.ActionResult>("/history", { baseURL, method: "delete", body, ...options });
}
-export function postTasksUpdate(body: Types.PostTasksUpdateBody): Promise<Types.TaskActionResult> {
- return fetch(`${baseURL}/tasks/update`, { method: 'POST', body: { id: body.id, ...body.input } })
+/** @method get */
+export function getOptions(options?: FetchOptions) {
+ return ofetch<Types.SchedulerOptions>("/options", { baseURL, method: "get", ...options });
}
-export function postTasksToggle(body: Types.PostTasksToggleBody): Promise<Types.TaskActionResult> {
- return fetch(`${baseURL}/tasks/toggle`, { method: 'POST', body })
+/** @method post */
+export function postRunsRecover(options?: FetchOptions) {
+ return ofetch<Types.ActionResult>("/runs/recover", { baseURL, method: "post", ...options });
}
-export function postTasksDelete(body: Types.PostIdBody): Promise<Types.SimpleActionResult> {
- return fetch(`${baseURL}/tasks/delete`, { method: 'POST', body })
+/** @method get */
+export function getTasks(params?: Types.GetTasksQuery, options?: FetchOptions) {
+ return ofetch<Types.TaskListResponse>("/tasks", { baseURL, method: "get", params, ...options });
}
-export function postTasksRun(body: Types.PostIdBody): Promise<Types.SimpleActionResult> {
- return fetch(`${baseURL}/tasks/run`, { method: 'POST', body })
+/** @method put */
+export function putTasks(body: Types.TaskUpdateBody, options?: FetchOptions) {
+ return ofetch<Types.TaskActionResult>("/tasks", { baseURL, method: "put", body, ...options });
}
-export function getHistory(query?: Types.GetHistoryQuery): Promise<Types.RunsResponse> {
- return fetch(`${baseURL}/history${query?.taskId ? `?taskId=${encodeURIComponent(query.taskId)}` : ''}`)
+/** @method post */
+export function postTasks(body: Types.TaskCreateBody, options?: FetchOptions) {
+ return ofetch<Types.TaskActionResult>("/tasks", { baseURL, method: "post", body, ...options });
}
-export function postHistoryDelete(body: Types.PostIdBody): Promise<Types.SimpleActionResult> {
- return fetch(`${baseURL}/history/delete`, { method: 'POST', body })
+/** @method delete */
+export function deleteTasks(body: Types.IdBody, options?: FetchOptions) {
+ return ofetch<Types.ActionResult>("/tasks", { baseURL, method: "delete", body, ...options });
}
-export function getOptions(): Promise<Types.SchedulerOptions> {
- return fetch(`${baseURL}/options`)
+/** @method post */
+export function postTasksRun(body: Types.IdBody, options?: FetchOptions) {
+ return ofetch<Types.ActionResult>("/tasks/run", { baseURL, method: "post", body, ...options });
}
-export function postRecover(): Promise<unknown> {
- return fetch(`${baseURL}/recover`, { method: 'POST', body: {} })
+/** @method post */
+export function postTasksToggle(body: Types.TaskToggleBody, options?: FetchOptions) {
+ return ofetch<Types.TaskActionResult>("/tasks/toggle", { baseURL, method: "post", body, ...options });
}
diff --git a/packages/dsh-tauri-panel-scheduler/src/client/apis/index.type.ts b/packages/dsh-tauri-panel-scheduler/src/client/apis/index.type.ts
index c783ba4c..ca9a7b23 100644
--- a/packages/dsh-tauri-panel-scheduler/src/client/apis/index.type.ts
+++ b/packages/dsh-tauri-panel-scheduler/src/client/apis/index.type.ts
@@ -1,56 +1,170 @@
-import type { RunView, SchedulerOptions, TaskInput, TaskView } from '../types'
+export type ActionResult = {
+ ok?: boolean;
+ error?: string;
+};
+export type RunListResponse = {
+ runs: SchedulerRun[];
+};
+export type SchedulerRun = {
+ id: string;
+ taskId: string;
+ taskName: string;
+ trigger: RunTrigger;
+ status: RunStatus;
+ scheduledFor: string;
+ startedAt: string;
+ finishedAt?: string;
+ sessionId?: string;
+ error?: string;
+};
+export type RunTrigger = "schedule" | "manual";
+export type RunStatus = "queued" | "running" | "succeeded" | "failed" | "interrupted" | "skipped" | "cancelled";
+export type SchedulerOptions = {
+ workspaces: Array<{ id: string; path: string; title: string }>;
+ permissions: Array<PermissionOption>;
+ defaultPermission: string;
+ models: Array<ModelOption>;
+ failures: Array<ModelCatalogFailure>;
+ defaultModel: ModelOption | null;
+};
+export type PermissionOption = {
+ value: string;
+ name: string;
+ description?: string;
+};
+export type ModelOption = {
+ provider: string;
+ providerLabel: string;
+ model: string;
+ label: string;
+ description?: string;
+ reasoning?: ModelReasoning;
+};
+export type ModelReasoning = {
+ efforts: Array<ModelReasoningEffort>;
+ defaultEffort?: string;
+};
+export type ModelReasoningEffort = {
+ id: string;
+ name: string;
+ description?: string;
+};
+export type ModelCatalogFailure = {
+ provider: string;
+ providerLabel: string;
+ message: string;
+};
+export type TaskListResponse = {
+ tasks: SchedulerTask[];
+};
+export type SchedulerTask = {
+ id: string;
+ name: string;
+ schedule: SchedulerSchedule;
+ prompt: string;
+ recommendationId?: string;
+ workspaceId?: string;
+ permission?: string;
+ provider?: string;
+ model?: string;
+ reasoningEffort?: string;
+ module?: string;
+ agentPreset?: string;
+ enabled: boolean;
+ createdAt: string;
+ updatedAt: string;
+ lastRunAt?: string;
+ nextRunAt?: string;
+};
+export type SchedulerSchedule = OnceSchedule | HourlySchedule | DailySchedule | IntervalSchedule | WorkdaysSchedule | WeeklySchedule | MonthlySchedule | CustomSchedule;
+export type OnceSchedule = {
+ kind: "once";
+ at: string;
+ timeZone: string;
+};
+export type HourlySchedule = {
+ kind: "hourly";
+ minute: number;
+ timeZone: string;
+};
+export type DailySchedule = {
+ kind: "daily";
+ time: string;
+ timeZone: string;
+};
+export type IntervalSchedule = {
+ kind: "interval";
+ everyMinutes: number;
+ anchor?: string;
+ timeZone: string;
+};
+export type WorkdaysSchedule = {
+ kind: "workdays";
+ time: string;
+ timeZone: string;
+};
+export type WeeklySchedule = {
+ kind: "weekly";
+ weekdays: Weekday[];
+ time: string;
+ timeZone: string;
+};
+export type Weekday = "MO" | "TU" | "WE" | "TH" | "FR" | "SA" | "SU";
+export type MonthlySchedule = {
+ kind: "monthly";
+ day: number;
+ time: string;
+ timeZone: string;
+};
+export type CustomSchedule = {
+ kind: "custom";
+ everyDays: number;
+ anchor: string;
+ time: string;
+ timeZone: string;
+};
+export type SchedulerScheduleInput = { kind: "once"; at: string; timeZone?: string } | { kind: "hourly"; minute: number; timeZone?: string } | { kind: "daily"; time: string; timeZone?: string } | { kind: "interval"; everyMinutes: number; anchor?: string; timeZone?: string } | { kind: "workdays"; time: string; timeZone?: string } | { kind: "weekly"; weekdays: readonly Weekday[]; time: string; timeZone?: string } | { kind: "monthly"; day: number; time: string; timeZone?: string } | { kind: "custom"; everyDays: number; anchor?: string; time: string; timeZone?: string };
+export type TaskActionResult = {
+ ok?: boolean;
+ task?: SchedulerTask;
+ error?: string;
+};
-export type { RunView, SchedulerOptions, TaskView }
-
-/** GET /tasks 响应。 */
-export interface TasksResponse {
- tasks: TaskView[]
-}
-
-/** GET /history 响应。 */
-export interface RunsResponse {
- runs: RunView[]
+export interface IdBody {
+ id: string;
}
-
-/** 任务变更结果(create/update/toggle 携带最新任务视图)。 */
-export interface TaskActionResult {
- ok: boolean
- task?: TaskView
- error?: string
+export interface TaskCreateBody {
+ name: string;
+ schedule: SchedulerScheduleInput;
+ prompt: string;
+ recommendationId?: string;
+ workspaceId?: string;
+ permission?: string;
+ provider?: string;
+ model?: string;
+ reasoningEffort?: string;
+ enabled?: boolean;
}
-
-/** 简单动作结果(delete/run/history delete)。 */
-export interface SimpleActionResult {
- ok: boolean
- error?: string
+export interface TaskUpdateBody {
+ id: string;
+ name?: string;
+ schedule?: SchedulerScheduleInput;
+ prompt?: string;
+ recommendationId?: string;
+ workspaceId?: string;
+ permission?: string;
+ provider?: string;
+ model?: string;
+ reasoningEffort?: string;
+ enabled?: boolean;
}
-
-/** GET /tasks 查询参数。 */
-export interface GetTasksQuery {
- search?: string
+export interface TaskToggleBody {
+ id: string;
+ enabled: boolean;
}
-
-/** GET /history 查询参数。 */
export interface GetHistoryQuery {
- taskId?: string
+ taskId?: string;
}
-
-/** POST /tasks/create 请求体(宿主任务表单字段平铺)。 */
-export type PostTasksCreateBody = TaskInput
-
-/** POST /tasks/update 请求体(id 不可被 input 覆盖)。 */
-export interface PostTasksUpdateBody {
- id: string
- input: TaskInput
-}
-
-/** POST /tasks/toggle 请求体。 */
-export interface PostTasksToggleBody {
- id: string
- enabled: boolean
-}
-
-/** POST /tasks/delete、/tasks/run、/history/delete 请求体。 */
-export interface PostIdBody {
- id: string
+export interface GetTasksQuery {
+ search?: string;
}
diff --git a/packages/dsh-tauri-rightclick/src/client/apis/index.ts b/packages/dsh-tauri-rightclick/src/client/apis/index.ts
index a24cbe2e..9417f092 100644
--- a/packages/dsh-tauri-rightclick/src/client/apis/index.ts
+++ b/packages/dsh-tauri-rightclick/src/client/apis/index.ts
@@ -1,13 +1,21 @@
-import type * as Types from './index.type'
-import { fetch } from 'dsh-tauri/client'
-import { OPEN_PATH_ROUTE, OPEN_URL_ROUTE } from '../constants'
+/*
+ * @title dsh-tauri-rightclick
+ * @swagger 2.0
+ * @version 0.0.0
+ */
-/** @method post 用系统默认浏览器打开外链。 */
-export function postOpenUrl(body: Types.OpenUrlPayload): Promise<Types.ActionResult> {
- return fetch(OPEN_URL_ROUTE, { method: 'POST', body })
+import type { FetchOptions } from "dsh-tauri/client";
+import { ofetch } from "dsh-tauri/client";
+import type * as Types from "./index.type";
+
+export const baseURL = "/api/desktop/dsh-tauri-rightclick";
+
+/** @method post */
+export function postOpenPath(body: Types.PostOpenPathBody, options?: FetchOptions) {
+ return ofetch<Types.OperationResult>("/open/path", { baseURL, method: "post", body, ...options });
}
-/** @method post 在系统文件管理器中打开目录。 */
-export function postOpenPath(body: Types.OpenPathPayload): Promise<Types.ActionResult> {
- return fetch(OPEN_PATH_ROUTE, { method: 'POST', body })
+/** @method post */
+export function postOpenUrl(body: Types.PostOpenUrlBody, options?: FetchOptions) {
+ return ofetch<Types.OperationResult>("/open/url", { baseURL, method: "post", body, ...options });
}
diff --git a/packages/dsh-tauri-rightclick/src/client/apis/index.type.ts b/packages/dsh-tauri-rightclick/src/client/apis/index.type.ts
index cbf9e53d..dad7f19c 100644
--- a/packages/dsh-tauri-rightclick/src/client/apis/index.type.ts
+++ b/packages/dsh-tauri-rightclick/src/client/apis/index.type.ts
@@ -1,15 +1,11 @@
-/** 宿主动作路由的统一结果体(200 时宿主返回;error 字段为宿主侧诊断文案)。 */
-export interface ActionResult {
- ok?: boolean
- error?: string
-}
+export type OperationResult = {
+ ok: boolean;
+ error?: string;
+};
-/** POST /open-url 请求体。 */
-export interface OpenUrlPayload {
- url: string
+export interface PostOpenPathBody {
+ path?: string;
}
-
-/** POST /open-path 请求体。 */
-export interface OpenPathPayload {
- path: string
+export interface PostOpenUrlBody {
+ url?: string;
}
diff --git a/packages/dsh-tauri-session/src/client/apis/index.ts b/packages/dsh-tauri-session/src/client/apis/index.ts
index bb082c94..ae0d8a93 100644
--- a/packages/dsh-tauri-session/src/client/apis/index.ts
+++ b/packages/dsh-tauri-session/src/client/apis/index.ts
@@ -1,40 +1,51 @@
-import type * as Types from './index.type'
-import { fetch } from 'dsh-tauri/client'
-import { SESSION_API_PREFIX } from '../../shared/constants'
+/*
+ * @title dsh-tauri-session
+ * @swagger 2.0
+ * @version 0.0.0
+ */
-export const baseURL = SESSION_API_PREFIX
+import type { FetchOptions } from "dsh-tauri/client";
+import { ofetch } from "dsh-tauri/client";
+import type * as Types from "./index.type";
-const SESSION_ARCHIVE = `${baseURL}/session/archive`
-const SESSION_WORKSPACE_ARCHIVE = `${baseURL}/session/workspace/archive`
+export const baseURL = "/api/desktop/dsh-tauri-session";
-export function getArchive(): Promise<Types.ArchivedListPayload> {
- return fetch(SESSION_ARCHIVE)
+/** @method post */
+export function postSessionArchiveClear(options?: FetchOptions) {
+ return ofetch<void>("/session/archive/clear", { baseURL, method: "post", ...options });
}
-export function postArchive(body: Types.PostSessionIdBody): Promise<Types.ArchivedListPayload> {
- return fetch(SESSION_ARCHIVE, { method: 'POST', body })
+/** @method get */
+export function getSessionArchive(options?: FetchOptions) {
+ return ofetch<Types.ArchivedListPayload>("/session/archive", { baseURL, method: "get", ...options });
}
-export function deleteArchive(body: Types.PostSessionIdBody): Promise<Types.ActionResult> {
- return fetch(SESSION_ARCHIVE, { method: 'DELETE', body })
+/** @method post */
+export function postSessionArchive(body: Types.SessionIdBody, options?: FetchOptions) {
+ return ofetch<void>("/session/archive", { baseURL, method: "post", body, ...options });
}
-export function postArchiveClear(): Promise<Types.ActionResult> {
- return fetch(`${SESSION_ARCHIVE}/clear`, { method: 'POST', body: {} })
+/** @method delete */
+export function deleteSessionArchive(body: Types.SessionIdBody, options?: FetchOptions) {
+ return ofetch<void>("/session/archive", { baseURL, method: "delete", body, ...options });
}
-export function postArchiveWorkspace(body: Types.PostArchiveWorkspaceBody): Promise<Types.ArchivedListPayload> {
- return fetch(SESSION_WORKSPACE_ARCHIVE, { method: 'POST', body })
+/** @method post */
+export function postSessionArchiveRestore(body: Types.SessionIdBody, options?: FetchOptions) {
+ return ofetch<void>("/session/archive/restore", { baseURL, method: "post", body, ...options });
}
-export function deleteArchiveWorkspace(body: Types.PostDeleteWorkspaceBody): Promise<Types.ActionResult> {
- return fetch(SESSION_WORKSPACE_ARCHIVE, { method: 'DELETE', body })
+/** @method post */
+export function postSessionOpenPath(body: Types.SessionIdBody, options?: FetchOptions) {
+ return ofetch<Types.OpenSessionDirResult>("/session/open/path", { baseURL, method: "post", body, ...options });
}
-export function postUnarchive(body: Types.PostSessionIdBody): Promise<Types.ActionResult> {
- return fetch(`${baseURL}/session/unarchive`, { method: 'POST', body })
+/** @method post */
+export function postSessionWorkspaceArchive(body: Types.WorkspaceArchiveBody, options?: FetchOptions) {
+ return ofetch<void>("/session/workspace/archive", { baseURL, method: "post", body, ...options });
}
-export function postOpenSessionDir(body: Types.PostSessionIdBody): Promise<Types.ActionResult> {
- return fetch(`${baseURL}/session/open-path`, { method: 'POST', body })
+/** @method delete */
+export function deleteSessionWorkspaceArchive(body: Types.SessionIdsBody, options?: FetchOptions) {
+ return ofetch<void>("/session/workspace/archive", { baseURL, method: "delete", body, ...options });
}
diff --git a/packages/dsh-tauri-session/src/client/apis/index.type.ts b/packages/dsh-tauri-session/src/client/apis/index.type.ts
index 31e7e473..18fb3cf7 100644
--- a/packages/dsh-tauri-session/src/client/apis/index.type.ts
+++ b/packages/dsh-tauri-session/src/client/apis/index.type.ts
@@ -1,28 +1,19 @@
-/** GET /session/archive 响应:归档会话 id 集 + 创建元数据。 */
-export interface ArchivedListPayload {
- archivedSessionIds: string[]
- /** Per archived session, creation metadata read from the host session header. */
- meta: Record<string, { createdAt?: number, cwd?: string, title?: string }>
-}
+export type ArchivedListPayload = {
+ archivedSessionIds: string[];
+ meta: Record<string, { createdAt?: number; cwd?: string; title?: string }>;
+};
+export type OpenSessionDirResult = {
+ ok: boolean;
+ error?: string;
+};
-/** 变更类动作的宿主结果体(200 返回;error 为宿主侧诊断文案)。 */
-export interface ActionResult {
- ok: boolean
- error?: string
+export interface SessionIdBody {
+ sessionId: string;
}
-
-/** POST /session/archive、/session/unarchive、/session/open-path、DELETE /session/archive 请求体。 */
-export interface PostSessionIdBody {
- sessionId: string
+export interface SessionIdsBody {
+ sessionIds: string[];
}
-
-/** POST /session/workspace/archive 请求体。 */
-export interface PostArchiveWorkspaceBody {
- workspaceId: string
- sessionIds: readonly string[]
-}
-
-/** DELETE /session/workspace/archive 请求体。 */
-export interface PostDeleteWorkspaceBody {
- sessionIds: readonly string[]
+export interface WorkspaceArchiveBody {
+ sessionIds: string[];
+ workspaceId?: string;
}
diff --git a/packages/dsh-tauri-turnrewind/src/client/apis/index.ts b/packages/dsh-tauri-turnrewind/src/client/apis/index.ts
index 4720a410..ed7ac160 100644
--- a/packages/dsh-tauri-turnrewind/src/client/apis/index.ts
+++ b/packages/dsh-tauri-turnrewind/src/client/apis/index.ts
@@ -1,37 +1,26 @@
-/**
- * client/apis/index.ts — 客户端 HTTP 面(同源 fetch,唯一入口 dsh-tauri/client 的 fetch)。
- *
- * URL 与宿主资源路径逐段一致(`routes/session/<子资源>/<方法>.ts` ↔
- * `${baseURL}/session/<子资源>`),改任一侧必须同步另一侧。
- *
- * 撤销失败(409 冲突等)必须把响应体读出来展示,因此 undo 用 `fetch.raw` +
- * `ignoreResponseError`:自己判状态码,而不是让统一错误归一丢掉冲突清单。
+/*
+ * @title dsh-tauri-turnrewind
+ * @swagger 2.0
+ * @version 0.0.0
*/
-import type { LiveSnapshot, SessionSummary, UndoResponse } from '../types'
-import type { PostUndoBody } from './index.type'
-import { fetch } from 'dsh-tauri/client'
-import { TURNREWIND_API_PREFIX } from '../../shared/constants'
+import type { FetchOptions } from "dsh-tauri/client";
+import { ofetch } from "dsh-tauri/client";
+import type * as Types from "./index.type";
-export const baseURL = TURNREWIND_API_PREFIX
+export const baseURL = "/api/desktop/dsh-tauri-turnrewind";
-/** 读取某会话的 turn 变更摘要。 */
-export function getSummary(sessionId: string): Promise<SessionSummary> {
- return fetch(`${baseURL}/session/summary?sessionId=${encodeURIComponent(sessionId)}`)
+/** @method get */
+export function getLive(params?: Types.GetLiveQuery, options?: FetchOptions) {
+ return ofetch<Types.LiveSnapshot>("/live", { baseURL, method: "get", params, ...options });
}
-/** 读取某会话「运行中」的实时读数(宿主定时刷新的缓存值)。 */
-export function getLive(sessionId: string): Promise<LiveSnapshot> {
- return fetch(`${baseURL}/session/live?sessionId=${encodeURIComponent(sessionId)}`)
+/** @method get */
+export function getSummary(params?: Types.GetSummaryQuery, options?: FetchOptions) {
+ return ofetch<Types.SummaryPayload>("/summary", { baseURL, method: "get", params, ...options });
}
-/** 撤销某个 turn 的文件改动;返回状态码与响应体(含冲突清单)。 */
-export async function postUndo(body: PostUndoBody): Promise<{ status: number, data: UndoResponse }> {
- const response = await fetch.raw<UndoResponse>(`${baseURL}/session/undo`, {
- method: 'POST',
- body,
- ignoreResponseError: true,
- })
- const data = (response._data ?? {}) as UndoResponse
- return { status: response.status, data }
+/** @method post */
+export function postTurnsUndo(body: Types.UndoBody, options?: FetchOptions) {
+ return ofetch<Types.UndoResponse>("/turns/undo", { baseURL, method: "post", body, ...options });
}
diff --git a/packages/dsh-tauri-turnrewind/src/client/apis/index.type.ts b/packages/dsh-tauri-turnrewind/src/client/apis/index.type.ts
index ff456d7c..17b13a68 100644
--- a/packages/dsh-tauri-turnrewind/src/client/apis/index.type.ts
+++ b/packages/dsh-tauri-turnrewind/src/client/apis/index.type.ts
@@ -1,11 +1,62 @@
-/**
- * client/apis/index.type.ts — 客户端 RPC 的请求/响应类型。
- */
+export type LiveSnapshot = {
+ active: boolean;
+ turn: number | null;
+ fileCount: number;
+ insertions: number;
+ deletions: number;
+};
+export type SummaryPayload = {
+ sessionId: string;
+ isGit: boolean;
+ workspaceRoot: string | null;
+ unavailableReason: string | null;
+ turns: Array<{
+ turn: number;
+ fileCount: number;
+ insertions: number;
+ deletions: number;
+ undoneAt: number | null;
+ unavailable: string | null;
+ /**
+ * 该轮是否建立过 before/after 快照(refs 是否留下)。与 `unavailable` 配合区分两种失败:
+ * 连基线都没有 = 这一轮从没有过可撤销的东西;基线在而 after 结算失败 = 承诺过的撤销落空了。
+ */
+ hasBaseline: boolean;
+ truncated: boolean;
+ files: TurnFileChange[];
+ skippedOversized: string[];
+ skippedNestedRepos: string[];
+ }>;
+};
+export type TurnFileChange = {
+ /** 相对 worktree 根的路径。 */
+ path: string;
+ /** A=本 turn 新增,M=修改,D=删除。 */
+ status: TurnFileStatus;
+ /** 文本行新增数;二进制为 null。 */
+ insertions: number | null;
+ /** 文本行删除数;二进制为 null。 */
+ deletions: number | null;
+ /** 是否为二进制差异。 */
+ binary: boolean;
+};
+export type TurnFileStatus = "A" | "M" | "D";
+export type UndoResponse = {
+ ok?: boolean;
+ restored?: string[];
+ removed?: string[];
+ failed?: Array<{ path: string; reason: string }>;
+ error?: string;
+ conflicts?: Array<{ path: string; reason: string }>;
+};
-export type { LiveSnapshot, SessionSummary, TurnFileChange, TurnSummary, UndoResponse } from '../types'
-
-/** 撤销请求体。 */
-export interface PostUndoBody {
- sessionId: string
- turn: number
+export interface UndoBody {
+ sessionId?: string;
+ turn?: number;
+}
+export interface GetLiveQuery {
+ sessionId?: string;
+}
+export interface GetSummaryQuery {
+ sessionId?: string;
}
diff --git a/packages/dsh-tauri-worktree/src/client/apis/index.ts b/packages/dsh-tauri-worktree/src/client/apis/index.ts
index c9dbdd0f..8f02eab1 100644
--- a/packages/dsh-tauri-worktree/src/client/apis/index.ts
+++ b/packages/dsh-tauri-worktree/src/client/apis/index.ts
@@ -1,30 +1,41 @@
-import type * as Types from './index.type'
-import { fetch } from 'dsh-tauri/client'
-import { WORKTREE_API_PREFIX } from '../../shared/constants'
+/*
+ * @title dsh-tauri-worktree
+ * @swagger 2.0
+ * @version 0.0.0
+ */
-export const baseURL = WORKTREE_API_PREFIX
+import type { FetchOptions } from "dsh-tauri/client";
+import { ofetch } from "dsh-tauri/client";
+import type * as Types from "./index.type";
-export function getBindings(): Promise<Types.WorktreeBindings> {
- return fetch(`${baseURL}/bindings`)
+export const baseURL = "/api/desktop/dsh-tauri-worktree";
+
+/** @method get */
+export function getBindings(options?: FetchOptions) {
+ return ofetch<Types.WorktreeBindings>("/bindings", { baseURL, method: "get", ...options });
}
-export function getStatus(query: Types.GetStatusQuery): Promise<Types.WorktreeStatus> {
- const jobId = query.jobId ? `&jobId=${encodeURIComponent(query.jobId)}` : ''
- return fetch(`${baseURL}/status?sessionId=${encodeURIComponent(query.sessionId)}${jobId}`)
+/** @method post */
+export function postBindings(body: Types.AttachBody, options?: FetchOptions) {
+ return ofetch<Types.WorktreeAttach>("/bindings", { baseURL, method: "post", body, ...options });
}
-export function postCreate(body: Types.PostCreateBody): Promise<Types.WorktreeCreate> {
- return fetch(baseURL, { method: 'POST', body })
+/** @method post */
+export function postCheckouts(body: Types.CheckoutBody, options?: FetchOptions) {
+ return ofetch<Types.WorktreeCheckout>("/checkouts", { baseURL, method: "post", body, ...options });
}
-export function postAttach(body: Types.PostAttachBody): Promise<{ ok: boolean, workspaceId: string }> {
- return fetch(`${baseURL}/attach`, { method: 'POST', body })
+/** @method post */
+export function postWorktree(body: Types.CreateBody, options?: FetchOptions) {
+ return ofetch<Types.WorktreeCreate>("", { baseURL, method: "post", body, ...options });
}
-export function postCheckout(body: Types.PostCheckoutBody): Promise<Types.WorktreeCheckout> {
- return fetch(`${baseURL}/checkout`, { method: 'POST', body })
+/** @method delete */
+export function deleteWorktree(body: Types.DiscardBody, options?: FetchOptions) {
+ return ofetch<Types.WorktreeDiscard>("", { baseURL, method: "delete", body, ...options });
}
-export function deleteDiscard(body: Types.PostDiscardBody): Promise<Types.WorktreeDiscard> {
- return fetch(baseURL, { method: 'DELETE', body })
+/** @method get */
+export function getStatus(params?: Types.GetStatusQuery, options?: FetchOptions) {
+ return ofetch<Types.WorktreeStatus>("/status", { baseURL, method: "get", params, ...options });
}
diff --git a/packages/dsh-tauri-worktree/src/client/apis/index.type.ts b/packages/dsh-tauri-worktree/src/client/apis/index.type.ts
index a4409581..036dc06b 100644
--- a/packages/dsh-tauri-worktree/src/client/apis/index.type.ts
+++ b/packages/dsh-tauri-worktree/src/client/apis/index.type.ts
@@ -1,91 +1,89 @@
-export interface WorktreeBindingSummary {
- sessionId: string
- sourceSessionId: string
- hash: string
- dirname: string
- worktreeKey: string
- worktreePath: string
- projectPath: string
- log: string[]
-}
+export type WorktreeBindings = {
+ bindings: WorktreeBindingSummary[];
+ jobs: WorktreeDiscardJobSummary[];
+};
+export type WorktreeBindingSummary = {
+ sessionId: string;
+ sourceSessionId: string;
+ hash: string;
+ dirname: string;
+ worktreeKey: string;
+ worktreePath: string;
+ projectPath: string;
+ log: string[];
+};
+export type WorktreeDiscardJobSummary = {
+ sessionId: string;
+ jobId: string;
+ state: string;
+ error?: string;
+ worktreeKey: string;
+ worktreePath?: string;
+};
+export type WorktreeAttach = {
+ ok?: boolean;
+ workspaceId?: string;
+ error?: string;
+};
+export type WorktreeCheckout = {
+ ok?: boolean;
+ branch?: string;
+ projectPath?: string;
+ targetSessionId?: string;
+ error?: string;
+};
+export type WorktreeDiscard = {
+ ok?: boolean;
+ jobId?: string;
+ error?: string;
+};
+export type WorktreeCreate = {
+ ok?: boolean;
+ error?: string;
+ hash?: string;
+ dirname?: string;
+ worktreeKey?: string;
+ worktreePath?: string;
+ projectPath?: string;
+ sourceSessionId?: string;
+ log?: string[];
+ existed?: boolean;
+ inherited?: boolean;
+};
+export type WorktreeStatus = {
+ mode?: string;
+ jobId?: string;
+ error?: string;
+ hash?: string;
+ dirname?: string;
+ worktreeKey?: string;
+ worktreePath?: string;
+ projectPath?: string;
+ sourceSessionId?: string;
+ log?: string[];
+ isGit?: boolean | null;
+};
-export interface WorktreeDiscardJobSummary {
- sessionId: string
- jobId: string
- state: 'deleting' | 'failed'
- error?: string
- worktreeKey: string
- worktreePath?: string
+export interface AttachBody {
+ sessionId?: string;
}
-
-export interface WorktreeBindings {
- bindings: WorktreeBindingSummary[]
- jobs: WorktreeDiscardJobSummary[]
+export interface CheckoutBody {
+ sessionId?: string;
+ worktreeHashDirname?: string;
+ branchName?: string;
+ carryStaged?: boolean;
}
-
-export interface WorktreeDiscard {
- ok: boolean
- jobId?: string
- error?: string
+export interface DiscardBody {
+ sessionId?: string;
+ worktreeHashDirname?: string;
}
-
-export interface WorktreeStatus {
- mode: 'local' | 'worktree' | 'deleting' | 'failed'
- jobId?: string
- error?: string
- worktreeKey?: string
- worktreePath?: string
- projectPath?: string
- hash?: string
- dirname?: string
- sourceSessionId?: string
- log?: string[]
- isGit?: boolean | null
+export interface CreateBody {
+ sessionId?: string;
+ sourceSessionId?: string;
+ carryStaged?: boolean;
+ inherit?: boolean;
}
-
-export interface WorktreeCreate {
- ok: boolean
- hash: string
- dirname: string
- worktreeKey: string
- worktreePath: string
- projectPath: string
- sourceSessionId: string
- log: string[]
- existed: boolean
- inherited: boolean
-}
-
-export interface WorktreeCheckout {
- ok: boolean
- branch: string
- projectPath?: string
- targetSessionId?: string
- warning?: string
-}
-
export interface GetStatusQuery {
- sessionId: string
- jobId?: string
-}
-
-export interface PostCreateBody {
- sessionId: string
- sourceSessionId: string
- inherit: boolean
-}
-
-export interface PostAttachBody {
- sessionId: string
-}
-
-export interface PostCheckoutBody {
- sessionId: string
- worktreeHashDirname: string
- branchName: string
-}
-
-export interface PostDiscardBody {
- sessionId: string
- worktreeHashDirname: string
+ sessionId?: string;
+ jobId?: string;
}
diff --git a/packages/dsh-tauri/src/client/request/index.ts b/packages/dsh-tauri/src/client/request/index.ts
index 5147efe2..b6448286 100644
--- a/packages/dsh-tauri/src/client/request/index.ts
+++ b/packages/dsh-tauri/src/client/request/index.ts
@@ -7,9 +7,13 @@
* 在此,调用方无需关心错误格式、无需自封装 requestJson/createJsonClient。
*/
+import type { FetchOptions as OfetchOptions } from 'ofetch'
import { createFetch } from 'ofetch'
import { defaultErrorMessage, parseJsonResponse } from './index.utils'
+/** 实例的选项类型:JSON 解码路径(与 `ofetch` 实例签名一致,供生成客户端直接引用)。 */
+export type FetchOptions = OfetchOptions<'json'>
+
/** 全局 JSON fetch:同源 API 请求唯一入口(错误解析统一在此)。 */
export const fetch = createFetch({
defaults: {
@@ -20,3 +24,6 @@ export const fetch = createFetch({
},
},
})
+
+/** 同一实例的别名:genapi 的 ofetch 预设按 `ofetch` 标识符生成调用。 */
+export const ofetch = fetch
diff --git a/packages/dsh-tauri/src/host/modules/h3.ts b/packages/dsh-tauri/src/host/modules/h3.ts
index ba0468db..1ef58e03 100644
--- a/packages/dsh-tauri/src/host/modules/h3.ts
+++ b/packages/dsh-tauri/src/host/modules/h3.ts
@@ -1,2 +1,2 @@
export { bodyLimit, defineEventHandler, EventStream, getQuery, HTTPError, readBody, readRawBody } from 'h3'
-export type { EventHandler, EventStreamMessage, EventStreamOptions, H3Event } from 'h3'
+export type { EventHandler, EventHandlerRequest, EventStreamMessage, EventStreamOptions, H3Event } from 'h3'