Skip to content

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

refactor(tooling): share compatible scanners and configuration (#824)

Mao Mra3591c3b2208
diff --git a/docs/audit/tooling-config-tests.md b/docs/audit/tooling-config-tests.md
index b5dc5b2c..27d04e6e 100644
--- a/docs/audit/tooling-config-tests.md
+++ b/docs/audit/tooling-config-tests.md
@@ -45,3 +45,13 @@ Also spotted, below the noise floor of the ranking (listed for completeness, no
## net: -496 lines, -0 deps possible.
> Lead 复核后修正:probe-wdio 实际 212 行(-251 → -212),故小计由 -535 修正为 -496。
+
+## 执行复核(2026-10-01)
+
+- **保留人工确认项**:probe-wdio 是明确保留的最小诊断通道;postcss.config.js 会被 Vite 隐式加载。没有作者删除确认,也不执行本地构建来替代确认,均不删除。
+- **配置**:三个 Vitest project 的执行环境、并发、初始化及超时并不相同,不引入配置工厂,不移动根专属覆盖率。只共享 Vite/根 Vitest/unit 的绝对路径别名,保留 project、收集与排除规则。
+- **类型检查**:合并根 TypeScript 配置与 node 配置,保留全部严格检查,将 scripts、根 *.config.ts 与 genapi*.ts 纳入 noEmit 检查。JS/MJS 保持原有未启用 checkJs 的边界;不扩张为包级构建配置迁移。
+- **测试契约**:共享仓库相对源码/语言读取器,删除六个单消费者 reader 包装;未证明同等 runtime 门禁的源码断言全部保留,独立字面量 oracle 不变。mask 的否定断言增加正向存在契约,避免不存在的层误判为通过。
+- **生成器**:七个扫描器共享私有参数化 quote/depth walker,保留 angle-only 泛型、忽略 angle 的 balanced/arrow、scalar depth 及既有箭头截断行为、反斜杠/反引号与跨行 union/intersection。未迁移 TypeScript AST,也未修改 schema/验证或生成协议;删除新严格检查发现的无用私有参数。19 项隔离夹具覆盖真实 config/parser/compiler/generate 和字节级输出,只抑制目的文件写入,没有重生成生产 API。
+- **验证**:扩展后的完整根 TypeScript 与变更文件 ESLint 通过;最终 12 文件/86 项集成回归按 7101/7202/7303/7404/7505 五个种子独立乱序均通过。反引号识别、共享 alias、SSH 排除与 locale key 变异均被独立 oracle 捕获并恢复。只读复核的两个类型门禁问题已修复;扫描器与原实现的 140,000 次差分比较一致,配置与读取契约无行为问题。
+- **环境边界**:本机全量 unit 在三个未改动 SSH suite 出现 16 项 Windows/POSIX/部署资源基线失败(2150 项通过),没有跳过、放宽或修补这些跨域用例;全量结果交由 CI 的既定 Ubuntu unit 环境验证。未运行插件构建或生产生成命令,没有改依赖或协议。
diff --git a/genapi.pipeline.ts b/genapi.pipeline.ts
index 204dfd01..0c8a4191 100644
--- a/genapi.pipeline.ts
+++ b/genapi.pipeline.ts
@@ -130,13 +130,11 @@ function operationName(method: string, segments: string[]): string {
: `${method}${toIdentifier(segments)}`
}
-function splitTopLevel(input: string): string[] {
- const parts: string[] = []
+function* scan(source: string, start: number, options: { open: string, close: string, stopOnClose?: boolean, stopOn?: (index: number) => boolean }): Generator<number, undefined> {
let depth = 0
- let start = 0
let quote: string | undefined
- for (let index = 0; index < input.length; index++) {
- const char = input[index]
+ for (let index = start; index < source.length; index++) {
+ const char = source[index]
if (quote) {
if (char === '\\') {
index++
@@ -150,22 +148,29 @@ function splitTopLevel(input: string): string[] {
quote = char
continue
}
- if (char === '{' || char === '[' || char === '(' || char === '<') {
+ if (options.open.includes(char)) {
depth++
continue
}
- if (char === '}' || char === ']' || char === ')' || char === '>') {
+ if (options.close.includes(char)) {
depth--
+ if (depth === 0 && options.stopOnClose)
+ yield index
continue
}
- if ((char === ';' || char === '|') && depth === 0) {
- parts.push(input.slice(start, index))
- start = index + 1
- }
+ if (depth === 0 && options.stopOn?.(index))
+ yield index
}
- const tail = input.slice(start)
- if (tail.trim().length > 0)
- parts.push(tail)
+}
+
+function splitTopLevel(input: string): string[] {
+ const parts: string[] = []
+ let start = 0
+ for (const index of scan(input, 0, { open: '{[(<', close: '}])>', stopOn: index => input[index] === ';' || input[index] === '|' })) {
+ parts.push(input.slice(start, index))
+ start = index + 1
+ }
+ parts.push(input.slice(start))
return parts.map(part => part.trim()).filter(Boolean)
}
@@ -180,37 +185,10 @@ function unwrap(input: string): string {
function splitMembers(input: string): string[] {
const parts: string[] = []
- let depth = 0
let start = 0
- let quote: string | undefined
- for (let index = 0; index < input.length; index++) {
- const char = input[index]
- if (quote) {
- if (char === '\\') {
- index++
- continue
- }
- if (char === quote)
- quote = undefined
- continue
- }
- if (char === '\'' || char === '"' || char === '`') {
- quote = char
- continue
- }
- if (char === '{' || char === '[' || char === '(' || char === '<') {
- depth++
- continue
- }
- if (char === '}' || char === ']' || char === ')' || char === '>') {
- depth--
- continue
- }
- const boundary = depth === 0 && (char === ';' || char === ',' || (char === '\n' && !/^\s*\|/.test(input.slice(index + 1))))
- if (boundary) {
- parts.push(input.slice(start, index))
- start = index + 1
- }
+ for (const index of scan(input, 0, { open: '{[(<', close: '}])>', stopOn: index => input[index] === ';' || input[index] === ',' || (input[index] === '\n' && !/^\s*\|/.test(input.slice(index + 1))) })) {
+ parts.push(input.slice(start, index))
+ start = index + 1
}
const tail = input.slice(start)
if (tail.trim().length > 0)
@@ -233,34 +211,8 @@ function genericArgs(input: string): string[] {
const start = input.indexOf('<')
if (start < 0)
return []
- let depth = 0
- let quote: string | undefined
- for (let index = start; index < input.length; index++) {
- const char = input[index]
- if (quote) {
- if (char === '\\') {
- index++
- continue
- }
- if (char === quote)
- quote = undefined
- continue
- }
- if (char === '\'' || char === '"' || char === '`') {
- quote = char
- continue
- }
- if (char === '<') {
- depth++
- continue
- }
- if (char === '>') {
- depth--
- if (depth === 0)
- return splitMembers(input.slice(start + 1, index))
- }
- }
- return []
+ const index = scan(input, start, { open: '<', close: '>', stopOnClose: true }).next().value
+ return index === undefined ? [] : splitMembers(input.slice(start + 1, index))
}
function genericOf(source: string, name: string): string | undefined {
@@ -268,99 +220,21 @@ function genericOf(source: string, name: string): string | undefined {
if (!found)
return undefined
const start = found.index + found[0].length
- let depth = 0
- let quote: string | undefined
- for (let index = start; index < source.length; index++) {
- const char = source[index]
- if (quote) {
- if (char === '\\') {
- index++
- continue
- }
- if (char === quote)
- quote = undefined
- continue
- }
- if (char === '\'' || char === '"' || char === '`') {
- quote = char
- continue
- }
- if (char === '<') {
- depth++
- continue
- }
- if (char === '>') {
- if (depth === 0)
- return source.slice(start, index).trim()
- depth--
- }
- }
- return undefined
+ const index = scan(source, start - 1, { open: '<', close: '>', stopOnClose: true }).next().value
+ return index === undefined ? undefined : source.slice(start, index).trim()
}
function sliceBalanced(source: string, openIndex: number): string | undefined {
- let depth = 0
- let quote: string | undefined
- for (let index = openIndex; index < source.length; index++) {
- const char = source[index]
- if (quote) {
- if (char === '\\') {
- index++
- continue
- }
- if (char === quote)
- quote = undefined
- continue
- }
- if (char === '\'' || char === '"' || char === '`') {
- quote = char
- continue
- }
- if (char === '{' || char === '[' || char === '(') {
- depth++
- continue
- }
- if (char === '}' || char === ']' || char === ')') {
- depth--
- if (depth === 0)
- return source.slice(openIndex + 1, index)
- }
- }
- return undefined
+ const index = scan(source, openIndex, { open: '{[(', close: '}])', stopOnClose: true }).next().value
+ return index === undefined ? undefined : source.slice(openIndex + 1, index)
}
function sliceDeclaration(source: string, start: number): string | undefined {
- let depth = 0
- let quote: string | undefined
- for (let index = start; index < source.length; index++) {
- const char = source[index]
- if (quote) {
- if (char === '\\') {
- index++
- continue
- }
- if (char === quote)
- quote = undefined
- continue
- }
- if (char === '\'' || char === '"' || char === '`') {
- quote = char
- continue
- }
- if (char === '{' || char === '[' || char === '(' || char === '<') {
- depth++
- continue
- }
- if (char === '}' || char === ']' || char === ')' || char === '>') {
- depth--
- continue
- }
- 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()
- }
+ for (const index of scan(source, start, { open: '{[(<', close: '}])>', stopOn: index => source[index] === '\n' })) {
+ 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()
}
@@ -670,7 +544,7 @@ function handlerParameters(source: string, operation: string, index: TypeIndex,
}
}
else {
- const schema = declaration ? parameterSchema(queryType, declaration, index, file, definitions, referenced) : { type: 'object', additionalProperties: { type: 'string' } }
+ const schema = declaration ? parameterSchema(queryType, declaration, index, definitions, referenced) : { type: 'object', additionalProperties: { type: 'string' } }
parameters.push({ name: 'query', location: 'query', required: false, schema })
}
}
@@ -684,14 +558,14 @@ function handlerParameters(source: string, operation: string, index: TypeIndex,
return parameters
}
const declaration = lookup(index, bodyType, file)
- const schema = declaration ? parameterSchema(bodyType, declaration, index, file, definitions, referenced) : { type: 'object', additionalProperties: { type: 'string' } }
+ const schema = declaration ? parameterSchema(bodyType, declaration, index, 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 {
+function parameterSchema(name: string, declaration: Declaration, index: TypeIndex, 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)
@@ -700,35 +574,8 @@ function parameterSchema(name: string, declaration: Declaration, index: TypeInde
}
function scanArrow(input: string): string | undefined {
- let depth = 0
- let quote: string | undefined
- for (let index = 0; index < input.length; index++) {
- const char = input[index]
- if (quote) {
- if (char === '\\') {
- index++
- continue
- }
- if (char === quote)
- quote = undefined
- continue
- }
- if (char === '\'' || char === '"' || char === '`') {
- quote = char
- continue
- }
- if (char === '{' || char === '[' || char === '(') {
- depth++
- continue
- }
- if (char === '}' || char === ']' || char === ')') {
- depth--
- continue
- }
- if (char === '=' && input[index + 1] === '>' && depth === 0)
- return input.slice(0, index).trim()
- }
- return undefined
+ const index = scan(input, 0, { open: '{[(', close: '}])', stopOn: index => input[index] === '=' && input[index + 1] === '>' }).next().value
+ return index === undefined ? undefined : input.slice(0, index).trim()
}
function unwrapPromise(value: string): string {
diff --git a/test/clipboard-image-bridge.test.ts b/test/clipboard-image-bridge.test.ts
index 6b5681d3..7c17dd61 100644
--- a/test/clipboard-image-bridge.test.ts
+++ b/test/clipboard-image-bridge.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
-import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
+import { readSource } from './setup/read-source'
/**
* 剪贴板图片回退桥的协议契约(issue #610)。
@@ -13,15 +13,11 @@ import { describe, expect, it } from 'vitest'
* 识别。回包若改用自定义 `source`,注入脚本仍按 `source` 过滤就会把回包丢掉,
* 贴图静默失败(0.15.5 的回归)。这些用例把两端的字面量与匹配方式锁在一起。
*/
-function readSource(relativePath: string): string {
- return readFileSync(new URL(relativePath, import.meta.url), 'utf8')
-}
-
const REPLY_TYPE = 'dsh://clipboard-image:reply'
describe('clipboard image bridge protocol', () => {
- const shim = readSource('../src-tauri/src/desktop/paste.rs')
- const iframe = readSource('../src/layout/components/iframe.tsx')
+ const shim = readSource('src-tauri/src/desktop/paste.rs')
+ const iframe = readSource('src/layout/components/iframe.tsx')
it('replies with the type the injected shim waits for', () => {
expect(shim).toContain(`var RES_TYPE = '${REPLY_TYPE}'`)
diff --git a/test/core-upgrade-profile.test.ts b/test/core-upgrade-profile.test.ts
index 85965981..282b970f 100644
--- a/test/core-upgrade-profile.test.ts
+++ b/test/core-upgrade-profile.test.ts
@@ -1,5 +1,5 @@
-import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
+import { readLocale, readSource } from './setup/read-source'
/**
* 「升级到更新的核心 → 请切换档案」链路的结构契约。
@@ -9,12 +9,12 @@ import { describe, expect, it } from 'vitest'
*
* 三个入口共用同一个守卫 hook:核心面板切换、更新提示 toast(桌面外壳)、调试页更新按钮。
*/
-const guardSource = (): string => readFileSync(new URL('../src/ui/config/hooks/use-core-profile-switch.tsx', import.meta.url), 'utf8')
-const coreSource = (): string => readFileSync(new URL('../src/ui/config/core.tsx', import.meta.url), 'utf8')
-const dialogSource = (): string => readFileSync(new URL('../src/ui/dialog/core-upgrade-profile.tsx', import.meta.url), 'utf8')
-const layoutSource = (): string => readFileSync(new URL('../src/layout/index.tsx', import.meta.url), 'utf8')
-const debugSource = (): string => readFileSync(new URL('../src/ui/config/debug.tsx', import.meta.url), 'utf8')
-const updaterSource = (): string => readFileSync(new URL('../src/store/modules/harness-updater/store.ts', import.meta.url), 'utf8')
+const guardSource = readSource('src/ui/config/hooks/use-core-profile-switch.tsx')
+const coreSource = readSource('src/ui/config/core.tsx')
+const dialogSource = readSource('src/ui/dialog/core-upgrade-profile.tsx')
+const layoutSource = readSource('src/layout/index.tsx')
+const debugSource = readSource('src/ui/config/debug.tsx')
+const updaterSource = readSource('src/store/modules/harness-updater/store.ts')
/** 取组件内某个顶层函数的函数体(到该函数自己的 `\n }` 为止,嵌套块缩进更深不会误截) */
function bodyOf(source: string, marker: string): string {
@@ -32,11 +32,11 @@ function updateBody(source: string): string {
describe('版本比对一律走本地数据', () => {
it('守卫不为比对联网重拉核心列表', () => {
- expect(guardSource()).not.toContain('\'get_cores\'')
+ expect(guardSource).not.toContain('\'get_cores\'')
})
it('「升级前」版本优先取现成的核心列表缓存,缺失才退回本地命令', () => {
- const body = bodyOf(guardSource(), 'async function localActiveVersion')
+ const body = bodyOf(guardSource, 'async function localActiveVersion')
expect(body).toContain('queryClient.getQueryData<HarnessCore[]>(queryKeys.cores)')
expect(body).toMatch(/cachedActive = cached\?\.find\(c => c\.active\)/)
@@ -44,7 +44,7 @@ describe('版本比对一律走本地数据', () => {
})
it('核心面板直接把列表里已加载的在用核心版本传进守卫', () => {
- const body = bodyOf(coreSource(), 'async function onActivate')
+ const body = bodyOf(coreSource, 'async function onActivate')
expect(body).toContain('cores.find(c => c.active)')
expect(body).toMatch(/guardCoreUpgrade\(coreVersionKey\(core\), activeCore \? coreVersionKey\(activeCore\) : ''\)/)
@@ -52,7 +52,7 @@ describe('版本比对一律走本地数据', () => {
})
it('任何更新的版本都判定为升级,默认档案名取目标版本号(含 patch,Core-x.y.z)', () => {
- const body = bodyOf(guardSource(), 'async function guardCoreUpgrade')
+ const body = bodyOf(guardSource, 'async function guardCoreUpgrade')
expect(body).toContain('isCoreUpgrade(from, toVersion)')
expect(body).toContain('coreProfileName(toVersion)')
@@ -62,7 +62,7 @@ describe('版本比对一律走本地数据', () => {
describe('核心面板:升级弹档案警告,不再叠加普通切换确认', () => {
it('取消档案警告即中止本次切换(不落档案、不切核心)', () => {
- const body = bodyOf(coreSource(), 'async function onActivate')
+ const body = bodyOf(coreSource, 'async function onActivate')
const guardIndex = body.indexOf('guardCoreUpgrade(')
const handledIndex = body.indexOf('if (!guard.handled)')
@@ -75,7 +75,7 @@ describe('核心面板:升级弹档案警告,不再叠加普通切换确认'
})
it('破坏性升级时改弹档案警告,普通确认只在未命中升级时出现', () => {
- const body = bodyOf(coreSource(), 'async function onActivate')
+ const body = bodyOf(coreSource, 'async function onActivate')
const handledIndex = body.indexOf('if (!guard.handled)')
expect(handledIndex).toBeGreaterThan(-1)
@@ -84,7 +84,7 @@ describe('核心面板:升级弹档案警告,不再叠加普通切换确认'
})
it('先落版本档案,再切核心,最后重启', () => {
- const body = bodyOf(coreSource(), 'async function onActivate')
+ const body = bodyOf(coreSource, 'async function onActivate')
const guardIndex = body.indexOf('await guardCoreUpgrade(')
const coreIndex = body.indexOf('activate.mutateAsync(core.id)')
const restartIndex = body.indexOf('store.harness.restart()')
@@ -96,7 +96,7 @@ describe('核心面板:升级弹档案警告,不再叠加普通切换确认'
})
it('核心切换失败时回滚到切换前的档案', () => {
- const body = bodyOf(coreSource(), 'async function onActivate')
+ const body = bodyOf(coreSource, 'async function onActivate')
const failureIndex = body.indexOf('core.switch_failed')
expect(failureIndex).toBeGreaterThan(-1)
@@ -107,7 +107,7 @@ describe('核心面板:升级弹档案警告,不再叠加普通切换确认'
describe('守卫:档案缺失才新建,已存在只切换,失败即中止', () => {
it('按后端归一化后的 id 匹配在用档案列表', () => {
- const body = bodyOf(guardSource(), 'async function guardCoreUpgrade')
+ const body = bodyOf(guardSource, 'async function guardCoreUpgrade')
expect(body).toContain('invoke<Profile[]>(\'get_profiles\')')
expect(body).toContain('normalizeProfileId(choice.name)')
@@ -115,7 +115,7 @@ describe('守卫:档案缺失才新建,已存在只切换,失败即中止'
})
it('已存在且在用时不重复切换,缺失时新建并切为使用中', () => {
- const body = bodyOf(guardSource(), 'async function guardCoreUpgrade')
+ const body = bodyOf(guardSource, 'async function guardCoreUpgrade')
expect(body).toMatch(/if \(!existing\.active\)\n\s*await invoke<Profile>\('set_active_profile', \{ id \}\)/)
expect(body).toContain('invoke<Profile>(\'create_profile\', { name: choice.name })')
@@ -123,7 +123,7 @@ describe('守卫:档案缺失才新建,已存在只切换,失败即中止'
})
it('档案切换失败时提示并中止(不切核心)', () => {
- const body = bodyOf(guardSource(), 'async function guardCoreUpgrade')
+ const body = bodyOf(guardSource, 'async function guardCoreUpgrade')
const failureIndex = body.indexOf('core.breaking_profile_failed')
expect(failureIndex).toBeGreaterThan(-1)
@@ -131,7 +131,7 @@ describe('守卫:档案缺失才新建,已存在只切换,失败即中止'
})
it('回滚切回原档案,失败只记日志,并始终失效档案查询', () => {
- const body = bodyOf(guardSource(), 'async function guardCoreUpgrade')
+ const body = bodyOf(guardSource, 'async function guardCoreUpgrade')
expect(body).toContain('previousId === switchedId')
expect(body).toContain('invoke<Profile>(\'set_active_profile\', { id: previousId })')
@@ -141,7 +141,7 @@ describe('守卫:档案缺失才新建,已存在只切换,失败即中止'
})
it('「无视风险切换」保持档案不变,只切核心', () => {
- const body = bodyOf(guardSource(), 'async function guardCoreUpgrade')
+ const body = bodyOf(guardSource, 'async function guardCoreUpgrade')
expect(body).toMatch(/if \(choice\.mode === 'ignore'\)\n\s*return \{ handled: true \}/)
// ignore 分支必须在读档案列表之前返回,避免无谓的档案请求
@@ -150,9 +150,9 @@ describe('守卫:档案缺失才新建,已存在只切换,失败即中止'
})
describe('更新提示入口(桌面外壳 / 调试页)走同一守卫', () => {
- for (const [name, source] of [['layout', layoutSource], ['debug', debugSource]] as [string, () => string][]) {
+ for (const [name, source] of [['layout', layoutSource], ['debug', debugSource]] as const) {
it(`${name}:「立即更新」先确认、再落档案、更新失败回滚`, () => {
- const body = updateBody(source())
+ const body = updateBody(source)
expect(body).toContain('confirmCoreBreaking(info.tag)')
expect(body).toContain('guardCoreUpgrade(info.tag)')
@@ -160,12 +160,12 @@ describe('更新提示入口(桌面外壳 / 调试页)走同一守卫', () =
expect(body).toContain('if (!(await store.harnessUpdater.handleUpdate()))')
expect(body).toContain('await guard.rollback?.()')
// 守卫的弹窗必须挂进渲染树,否则 useOverlay 的 holder 无处可渲染
- expect(source()).toContain('{coreProfileSwitchHolder}')
+ expect(source).toContain('{coreProfileSwitchHolder}')
})
}
it('handleUpdate 返回是否真的切到了新版本,供调用方决定是否回滚', () => {
- const source = updaterSource()
+ const source = updaterSource
expect(source).toMatch(/async handleUpdate\(\): Promise<boolean>/)
expect(source).toMatch(/return false/)
@@ -173,7 +173,7 @@ describe('更新提示入口(桌面外壳 / 调试页)走同一守卫', () =
})
it('已落盘的新版本即使随后启动失败也不报「没切换」(否则会回滚出旧档案配新核心)', () => {
- const source = updaterSource()
+ const source = updaterSource
// 安装结果记在 try 之外,catch 里回传它而不是一律 false
expect(source).toMatch(/let installed = false/)
@@ -184,7 +184,7 @@ describe('更新提示入口(桌面外壳 / 调试页)走同一守卫', () =
describe('警告对话框控件', () => {
it('档案名默认填目标版本号(含 patch)、可编辑,并用 InputGroup 组合而非自绘 Label + Input', () => {
- const source = dialogSource()
+ const source = dialogSource
expect(source).toMatch(/useState\(props\.defaultName\)/)
expect(source).toMatch(/value=\{name\}/)
@@ -198,7 +198,7 @@ describe('警告对话框控件', () => {
})
it('「无视风险切换」是 warning Chip,与取消/确认按钮同处一行的 footer', () => {
- const source = dialogSource()
+ const source = dialogSource
const footerStart = source.indexOf('<AlertDialog.Footer')
const footerEnd = source.indexOf('</AlertDialog.Footer>')
@@ -218,14 +218,14 @@ describe('警告对话框控件', () => {
})
it('归一化后为空的档案名禁止确认', () => {
- const source = dialogSource()
+ const source = dialogSource
expect(source).toMatch(/const profileId = normalizeProfileId\(name\)/)
expect(source).toMatch(/isDisabled=\{!profileId\}/)
})
it('danger 状态的 AlertDialog,警告文案同时给出源版本与目标版本', () => {
- const source = dialogSource()
+ const source = dialogSource
expect(source).toMatch(/status="danger"/)
expect(source).toMatch(/core\.breaking_desc', \{ from: props\.fromVersion, to: props\.toVersion \}/)
@@ -243,10 +243,10 @@ describe('i18n parity', () => {
for (const locale of ['zh-CN', 'en-US']) {
it(`includes all core.breaking* keys in ${locale}`, () => {
- const messages = JSON.parse(readFileSync(new URL(`../src/i18n/locales/${locale}.json`, import.meta.url), 'utf8')) as Record<string, unknown>
+ const messages = readLocale(locale)
for (const key of keys) {
expect(typeof messages[key], key).toBe('string')
- expect((messages[key] as string).length, key).toBeGreaterThan(0)
+ expect(messages[key].length, key).toBeGreaterThan(0)
}
})
}
diff --git a/test/genapi-pipeline.test.ts b/test/genapi-pipeline.test.ts
new file mode 100644
index 00000000..21f672a3
--- /dev/null
+++ b/test/genapi-pipeline.test.ts
@@ -0,0 +1,140 @@
+import type { ApiPipeline } from '@genapi/shared'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join, resolve } from 'node:path'
+import { config } from '@genapi/pipeline'
+import { context, inject } from '@genapi/shared'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { pluginPipeline } from '../genapi.pipeline'
+
+const stages = vi.hoisted(() => ({ original: undefined as unknown as (value: ApiPipeline.ConfigRead) => ApiPipeline.ConfigRead }))
+
+vi.mock('@genapi/pipeline', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@genapi/pipeline')>()
+ return {
+ ...actual,
+ default: (...steps: Parameters<typeof actual.default>) => {
+ stages.original = steps[1] as typeof stages.original
+ return actual.default(...steps)
+ },
+ dest: async () => {},
+ }
+})
+
+const roots: string[] = []
+
+afterEach(() => {
+ for (const key of Object.keys(context))
+ delete context[key]
+ for (const root of roots.splice(0)) {
+ if (dirname(root) !== resolve(tmpdir()) || !root.startsWith(join(resolve(tmpdir()), 'genapi-test-')))
+ throw new Error(`Unexpected fixture root: ${root}`)
+ rmSync(root, { recursive: true, force: true })
+ }
+})
+
+function fixture(files: Record<string, string>): ApiPipeline.Config {
+ const root = mkdtempSync(join(resolve(tmpdir()), 'genapi-test-'))
+ roots.push(root)
+ const routes = join(root, 'fixture', 'src/host/routes')
+ mkdirSync(routes, { recursive: true })
+ for (const [file, source] of Object.entries(files)) {
+ const target = join(root, 'fixture', 'src', file)
+ mkdirSync(dirname(target), { recursive: true })
+ writeFileSync(target, source)
+ }
+ return { input: routes, output: { main: 'fixture/api.ts', type: 'fixture/api.type.ts' }, meta: { baseURL: '"/fixture"', import: { http: 'dsh-tauri/client' } } }
+}
+
+function scan(files: Record<string, string>) {
+ return stages.original(config(fixture(files)))
+}
+
+function response(annotation: string) {
+ return scan({ 'host/routes/get.ts': `export default defineEventHandler((event): ${annotation} => undefined)` }).source
+}
+
+describe('generator scanner compatibility', () => {
+ it.each([
+ ['string | null', { type: 'string' }],
+ ['Array<string> | number', { type: 'number' }],
+ ['{ value: "a|b;c"; nested: { flag: boolean }; list: [number, string] }', { type: 'object', properties: { value: { type: 'string', enum: ['a|b;c'] }, nested: { type: 'object', properties: { flag: { type: 'boolean' } }, required: ['flag'] }, list: { type: 'array', items: { type: 'number' } } }, required: ['value', 'nested', 'list'] }],
+ ['{ label: `a}|b;c`; next: number }', { type: 'object', properties: { label: { type: 'string' }, next: { type: 'number' } }, required: ['label', 'next'] }],
+ ['{ callback: () => void; next: number }', { type: 'object', properties: { callback: { type: 'string' } }, required: ['callback'] }],
+ ['Promise<{ callback: () => void; next: number }>', { type: 'object', properties: { callback: { type: 'string' } }, required: ['callback'] }],
+ ])('return annotation %s preserves its schema', (annotation, schema) => {
+ expect(response(annotation)).toEqual({ swagger: '2.0', info: { title: 'fixture', version: '0.0.0' }, paths: { '': { get: { operationId: 'get', parameters: [], responses: { 200: { description: 'GET /', schema } } } } }, definitions: {} })
+ })
+
+ it('member newlines continue a leading union but split the next field', () => {
+ const result = response('{ mode: "a"\n | "b"\n count?: number, done: boolean; }')
+ expect(result.paths[''].get.responses[200].schema).toEqual({ type: 'object', properties: { mode: { type: 'string', enum: ['a', 'b'] }, count: { type: 'number' }, done: { type: 'boolean' } }, required: ['mode', 'done'] })
+ })
+
+ it('escaped quotes do not expose member delimiters', () => {
+ const result = response(String.raw`{ first: 'a\';|b'; second: "c\",;d"; third: number }`)
+ expect(result.paths[''].get.responses[200].schema).toEqual({ type: 'object', properties: { first: { type: 'string' }, second: { type: 'string' }, third: { type: 'number' } }, required: ['first', 'second', 'third'] })
+ })
+
+ it('nested generic arguments preserve value schemas and quoted angles', () => {
+ const result = response('{ values: Record<"a>b", Array<{ count: number }>>; flags: Map<string, boolean>; names: ReadonlyArray<string> }')
+ expect(result.paths[''].get.responses[200].schema).toEqual({ type: 'object', properties: { values: { type: 'object', additionalProperties: { type: 'array', items: { type: 'object', properties: { count: { type: 'number' } }, required: ['count'] } } }, flags: { type: 'object', additionalProperties: { type: 'boolean' } }, names: { type: 'array', items: { type: 'string' } } }, required: ['values', 'flags', 'names'] })
+ })
+
+ it('angle-only request scanning retains arrow truncation', () => {
+ const result = scan({ 'host/routes/post.ts': 'export default defineEventHandler((event) => { const body = readBody<{ callback: () => void; next: number }>(event) })' })
+ expect(result.source.paths[''].post.parameters).toEqual([{ name: 'body', in: 'body', required: true, schema: { $ref: '#/definitions/postBody' } }])
+ expect(result.source.definitions).toEqual({ postBody: { type: 'object', properties: { callback: { type: 'string' } }, required: ['callback'] } })
+ })
+
+ it('generic response arguments take precedence over arrow annotations', () => {
+ const result = scan({ 'host/routes/get.ts': 'export default defineEventHandler<EventHandlerRequest, Promise<{ value: "a>b" }>>((event): number => 1)' })
+ expect(result.source.paths[''].get.responses).toEqual({ 200: { description: 'GET /', schema: { type: 'object', properties: { value: { type: 'string', enum: ['a>b'] } }, required: ['value'] } } })
+ })
+
+ it('balanced parameter scanning ignores angles and quoted closing brackets', () => {
+ const result = scan({ 'host/routes/get.ts': 'export default defineEventHandler(async (event = { value: ")]}>", nested: [1] }): Promise<number[]> => [])' })
+ expect(result.source.paths[''].get.responses).toEqual({ 200: { description: 'GET /', schema: { type: 'array', items: { type: 'number' } } } })
+ })
+
+ it('missing balanced closing brackets omit response schemas', () => {
+ const result = scan({ 'host/routes/get.ts': 'export default defineEventHandler((event: { value: string }: number => 1' })
+ expect(result.source.paths[''].get.responses).toEqual({ 200: { description: 'GET /' } })
+ })
+
+ it('missing generic closing angles preserve fallback request schemas', () => {
+ const result = scan({ 'host/routes/post.ts': 'export default defineEventHandler((event) => readBody<{ value: string }(event))' })
+ expect(result.source.paths[''].post.parameters).toEqual([])
+ })
+
+ it('multiline aliases preserve union and intersection continuations verbatim', () => {
+ const result = scan({ 'host/types/contracts.ts': 'export type Result = { kind: "ok" }\n | { kind: "failed" } &\n { reason: string }\nexport type Unused = number\n', 'host/routes/get.ts': 'export default defineEventHandler((event): Result => undefined)' })
+ expect(result.graphs.scopes.type.typings).toEqual([{ name: 'Result', value: '{ kind: "ok" }\n | { kind: "failed" } &\n { reason: string }', export: true }])
+ expect(result.source.definitions).toEqual({})
+ })
+
+ it('named query inheritance and aliased imports retain field contracts', () => {
+ const result = scan({ 'shared/contracts.types.ts': 'export interface Base { id: string }\nexport interface Query extends Base { mode?: "a" | "b" }\n', 'host/routes/get.ts': 'import type { Query as LocalQuery, type Base } from "../../shared/contracts.types"\nexport default defineEventHandler((event): number => { getQuery<LocalQuery>(event) })' })
+ expect(result.source.paths[''].get.parameters).toEqual([{ type: 'string', name: 'id', in: 'query', required: true }, { type: 'string', enum: ['a', 'b'], name: 'mode', in: 'query', required: false }])
+ })
+
+ it('successive runs clear named typing state', () => {
+ scan({ 'host/routes/get.ts': 'type First = string\nexport default defineEventHandler((event): First => "")' })
+ const result = scan({ 'host/routes/get.ts': 'export default defineEventHandler((event): boolean => true)' })
+ expect(result.graphs.scopes.type.typings).toEqual([])
+ expect(result.source.paths[''].get.responses).toEqual({ 200: { description: 'GET /', schema: { type: 'boolean' } } })
+ })
+
+ it('missing route directories retain the generator rejection', () => {
+ const options = fixture({})
+ options.input = join(String(options.input), 'missing')
+ expect(() => stages.original(config(options))).toThrow(`genapi: 路由目录不存在 ${options.input},请检查 genapi.config.ts 的 input`)
+ })
+
+ it('the real compiler emits the literal client API and named type contract', async () => {
+ await pluginPipeline(fixture({ 'host/routes/item/post.ts': 'export type Result = { kind: "ok" | "failed" }\nexport default defineEventHandler(async (event): Promise<Result> => { const body = await readBody<{ name: string; count?: number }>(event); return { kind: "ok" } })' }))
+ const result = inject().configRead!
+ expect(result.outputs.find(output => output.type === 'main')!.code).toBe('/*\n * @title fixture\n * @swagger 2.0\n * @version 0.0.0\n */\n\nimport type { FetchOptions } from "dsh-tauri/client";\nimport { ofetch } from "dsh-tauri/client";\nimport type * as Types from "./api.type";\n\nexport const baseURL = "/fixture";\n\n/** @method post */\nexport function postItem(body: Types.PostItemBody, options?: FetchOptions) {\n return ofetch<Types.Result>("/item", { baseURL, method: "post", body, ...options });\n}\n')
+ expect(result.outputs.find(output => output.type === 'type')!.code).toBe('export type Result = { kind: "ok" | "failed" };\n\nexport interface PostItemBody {\n name: string;\n count?: number;\n}\n')
+ })
+})
diff --git a/test/menu-restart.test.ts b/test/menu-restart.test.ts
index 1250adbc..f2695e94 100644
--- a/test/menu-restart.test.ts
+++ b/test/menu-restart.test.ts
@@ -1,18 +1,9 @@
-import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
+import { readSource } from './setup/read-source'
-const builderSource = readFileSync(
- new URL('../src-tauri/src/desktop/builder.rs', import.meta.url),
- 'utf8',
-)
-const i18nSource = readFileSync(
- new URL('../src-tauri/src/config/i18n.rs', import.meta.url),
- 'utf8',
-)
-const navbarSource = readFileSync(
- new URL('../src/layout/components/navbar.tsx', import.meta.url),
- 'utf8',
-)
+const builderSource = readSource('src-tauri/src/desktop/builder.rs')
+const i18nSource = readSource('src-tauri/src/config/i18n.rs')
+const navbarSource = readSource('src/layout/components/navbar.tsx')
describe('menu restart backend contract', () => {
it('places desktop-restart menu item after run_logs in help submenu', () => {
diff --git a/test/navbar-mask-mirror.test.ts b/test/navbar-mask-mirror.test.ts
index 972bc1fe..d0eb1d93 100644
--- a/test/navbar-mask-mirror.test.ts
+++ b/test/navbar-mask-mirror.test.ts
@@ -7,13 +7,10 @@
* 该层必须始终带 iframe 上报的样式、且不得被写成穿透点击(dsh 有模态期间壳层不该可点)。
* 与 `menu-restart.test.ts` 同一姿势——node 环境无渲染器,用源码关系断言。
*/
-import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
+import { readSource } from './setup/read-source'
-const navbarSource = readFileSync(
- new URL('../src/layout/components/navbar.tsx', import.meta.url),
- 'utf8',
-)
+const navbarSource = readSource('src/layout/components/navbar.tsx')
const markedLayer = navbarSource.match(/<div className="absolute"[^>]*\/>/)?.[0] ?? ''
@@ -23,6 +20,7 @@ describe('navbar mask mirror layer', () => {
})
it('镜像层不在 dsh 弹模态期间放行点击', () => {
+ expect(markedLayer).toContain('style={dshStyle.marked || {}}')
expect(markedLayer).not.toContain('pointer-events-none')
})
})
diff --git a/test/navbar-maximize-icon.test.ts b/test/navbar-maximize-icon.test.ts
index e5d8ad95..0446d060 100644
--- a/test/navbar-maximize-icon.test.ts
+++ b/test/navbar-maximize-icon.test.ts
@@ -5,19 +5,10 @@
* 单方块。与 `menu-restart.test.ts` 同一姿势——壳层组件的契约以源码关系断言锁定,
* 因为 `unit` project 是 node 环境(无 DOM/渲染器),拿不到真实渲染结果。
*/
-import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
+import { readLocale, readSource } from './setup/read-source'
-const navbarSource = readFileSync(
- new URL('../src/layout/components/navbar.tsx', import.meta.url),
- 'utf8',
-)
-
-function readLocale(name: string): Record<string, string> {
- return JSON.parse(
- readFileSync(new URL(`../src/i18n/locales/${name}.json`, import.meta.url), 'utf8'),
- ) as Record<string, string>
-}
+const navbarSource = readSource('src/layout/components/navbar.tsx')
const zhCN = readLocale('zh-CN')
const enUS = readLocale('en-US')
diff --git a/test/navbar-run-menu.test.ts b/test/navbar-run-menu.test.ts
index f496cde8..b1724fe7 100644
--- a/test/navbar-run-menu.test.ts
+++ b/test/navbar-run-menu.test.ts
@@ -9,19 +9,10 @@
* 被菜单项的 `usePress` 当成「松手落在我身上」而补发一次 click,连带触发菜单项动作
* (弹出配置面板)。浏览器实测:去掉外层 pointerup 拦截后,点重启会同时打开「应用」面板。
*/
-import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
+import { readLocale, readSource } from './setup/read-source'
-const navbarSource = readFileSync(
- new URL('../src/layout/components/navbar.tsx', import.meta.url),
- 'utf8',
-)
-
-function readLocale(name: string): Record<string, string> {
- return JSON.parse(
- readFileSync(new URL(`../src/i18n/locales/${name}.json`, import.meta.url), 'utf8'),
- ) as Record<string, string>
-}
+const navbarSource = readSource('src/layout/components/navbar.tsx')
const zhCN = readLocale('zh-CN')
const enUS = readLocale('en-US')
diff --git a/test/pet-window-lifecycle.test.ts b/test/pet-window-lifecycle.test.ts
index 1f8343c7..bbbcd837 100644
--- a/test/pet-window-lifecycle.test.ts
+++ b/test/pet-window-lifecycle.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
-import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
+import { readSource } from './setup/read-source'
/**
* 桌宠窗口生命周期契约(issue #469)。
@@ -13,10 +13,6 @@ import { describe, expect, it } from 'vitest'
* 另一条不变量是**关闭必须持久**:关闭写 `enabled=false` 并落盘,重启后不得再自动拉起
* (用户报告:明明关了宠物,重开应用它又自己出来)。
*/
-function readSource(relativePath: string): string {
- return readFileSync(new URL(relativePath, import.meta.url), 'utf8')
-}
-
/** 截取指定函数体的源码(从 ` fn name` 起,到下一个顶层 `}` 后换行 + 空行为止)。 */
function functionBody(source: string, name: string): string {
const start = source.indexOf(`pub fn ${name}`)
@@ -27,7 +23,7 @@ function functionBody(source: string, name: string): string {
}
describe('pet window close (destroy, not hide)', () => {
- const petWindow = readSource('../src-tauri/src/desktop/pet.rs')
+ const petWindow = readSource('src-tauri/src/desktop/pet.rs')
it('destroys the pet webview window instead of hiding it', () => {
const body = functionBody(petWindow, 'set_pet_window_visible')
@@ -50,7 +46,7 @@ describe('pet window close (destroy, not hide)', () => {
})
describe('pet window lifecycle never runs on the main thread', () => {
- const bridge = readSource('../src-tauri/src/bridge/pet.rs')
+ const bridge = readSource('src-tauri/src/bridge/pet.rs')
it('defers every window visibility change off the command thread', () => {
// command handler 在主线程执行,而 tauri-runtime-wry 在主线程上:
@@ -74,8 +70,8 @@ describe('pet window lifecycle never runs on the main thread', () => {
})
describe('closing the pet persists (restart must not re-open it)', () => {
- const bridge = readSource('../src-tauri/src/bridge/pet.rs')
- const builder = readSource('../src-tauri/src/desktop/builder.rs')
+ const bridge = readSource('src-tauri/src/bridge/pet.rs')
+ const builder = readSource('src-tauri/src/desktop/builder.rs')
it('persists enabled=false and stops the host session stream together', () => {
const body = functionBody(bridge, 'set_pet_enabled')
@@ -101,7 +97,7 @@ describe('closing the pet persists (restart must not re-open it)', () => {
})
describe('recreated pet window keeps its mouse stream', () => {
- const mouse = readSource('../src-tauri/src/desktop/pet_mouse.rs')
+ const mouse = readSource('src-tauri/src/desktop/pet_mouse.rs')
it('rebinds the global mouse emitter to the window that just mounted', () => {
// 窗口销毁重建后旧句柄失效:若节流线程一直握着旧窗口,重建后的桌宠收不到
diff --git a/test/plugin-patch-targets.test.ts b/test/plugin-patch-targets.test.ts
index 6383024a..64ece621 100644
--- a/test/plugin-patch-targets.test.ts
+++ b/test/plugin-patch-targets.test.ts
@@ -1,5 +1,6 @@
-import { existsSync, readdirSync, readFileSync } from 'node:fs'
+import { existsSync, readdirSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
+import { readSource } from './setup/read-source'
/**
* issue #763:插件包内的 `cordis.patch.yml` 用顶层 `- id: <官方 id>` 关掉官方入口,
@@ -15,7 +16,7 @@ const OFFICIAL_ROW_DISABLES = ['dsh-tauri-model → ui-settings-models']
const PACKAGES_ROOT = new URL('../packages/', import.meta.url)
function readPatchLayer(pkg: string): string {
- return readFileSync(new URL(`${pkg}/cordis.patch.yml`, PACKAGES_ROOT), 'utf8')
+ return readSource(`packages/${pkg}/cordis.patch.yml`)
}
function packageNames(): string[] {
@@ -50,7 +51,7 @@ describe('插件 patch 层的官方目标', () => {
})
it('dsh-tauri-archive 的第三方声明不再声称禁用了官方入口', () => {
- const notices = readFileSync(new URL('../packages/dsh-tauri-archive/THIRD_PARTY_NOTICES.md', import.meta.url), 'utf8')
+ const notices = readSource('packages/dsh-tauri-archive/THIRD_PARTY_NOTICES.md')
expect(notices).not.toContain('ui-settings-unarchive-sessions')
expect(notices).not.toContain('Official row disabled')
diff --git a/test/setup/read-source.ts b/test/setup/read-source.ts
new file mode 100644
index 00000000..c6b72dab
--- /dev/null
+++ b/test/setup/read-source.ts
@@ -0,0 +1,9 @@
+import { readFileSync } from 'node:fs'
+
+export function readSource(relativePath: string): string {
+ return readFileSync(new URL(`../../${relativePath}`, import.meta.url), 'utf8')
+}
+
+export function readLocale(name: string): Record<string, string> {
+ return JSON.parse(readSource(`src/i18n/locales/${name}.json`)) as Record<string, string>
+}
diff --git a/test/shell-theme-alignment.test.ts b/test/shell-theme-alignment.test.ts
index 69bf9bac..1ce69f06 100644
--- a/test/shell-theme-alignment.test.ts
+++ b/test/shell-theme-alignment.test.ts
@@ -6,10 +6,10 @@
* `data-theme` 提供明暗两套取值,多写反而会让组件外观偏离官方。这里把「只改
* accent、其余语义变量一律不覆盖」钉死。取值同源:官方 design-platform.css。
*/
-import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
+import { readSource } from './setup/read-source'
-const css = readFileSync(new URL('../src/styles/main.css', import.meta.url), 'utf8')
+const css = readSource('src/styles/main.css')
const [darkTheme = '', lightTheme = ''] = css.split(/^html\[data-theme="light"\] \{/m)
const herouiSemanticTokens = [
@@ -66,7 +66,7 @@ describe('壳层主题对齐 dsh alias token', () => {
})
it('tailwind.config 把同名颜色指向 HeroUI 语义变量,业务蓝改走 info', () => {
- const config = readFileSync(new URL('../tailwind.config.js', import.meta.url), 'utf8')
+ const config = readSource('tailwind.config.js')
expect(config).toContain('\'muted\': \'var(--muted)\'')
expect(config).toContain('\'accent\': \'var(--accent)\'')
expect(config).toContain('\'danger\': \'var(--danger)\'')
diff --git a/test/tooling-config.test.ts b/test/tooling-config.test.ts
new file mode 100644
index 00000000..0b334fdc
--- /dev/null
+++ b/test/tooling-config.test.ts
@@ -0,0 +1,176 @@
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import ts from 'typescript'
+import { resolveConfig } from 'vite'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { createVitest } from 'vitest/node'
+import rootConfig from '../vitest.config'
+import desktopConfig from '../vitest.desktop.config'
+import pluginConfig from '../vitest.plugin.config'
+import unitConfig from '../vitest.unit.config'
+
+const root = fileURLToPath(new URL('../', import.meta.url))
+let runtime: Awaited<ReturnType<typeof createVitest>>
+
+beforeAll(async () => {
+ runtime = await createVitest('test', {
+ root,
+ config: path.join(root, 'vitest.config.ts'),
+ watch: false,
+ })
+})
+
+afterAll(async () => {
+ await runtime?.close()
+})
+
+describe('tooling configuration contracts', () => {
+ it('vite and both Vitest alias consumers resolve @ to the shell source directory', async () => {
+ const vite = await resolveConfig({ configFile: path.join(root, 'vite.config.ts') }, 'serve')
+ const source = path.join(root, 'src')
+ expect(vite.resolve.alias).toContainEqual({ find: '@', replacement: source })
+ for (const config of [rootConfig, unitConfig]) {
+ expect(config.resolve?.alias).toEqual({ '@': source })
+ }
+ const unit = runtime.projects.find(project => project.name === 'unit')!
+ const resolved = await unit.vite.pluginContainer.resolveId('@/config/query-keys')
+ expect(resolved?.id.replaceAll('\\', '/')).toBe(`${root.replaceAll('\\', '/')}src/config/query-keys.ts`)
+ })
+
+ it('each project retains its distinct setup, scheduling and timeout envelope', () => {
+ expect(unitConfig.test).toEqual({
+ name: 'unit',
+ include: ['packages/**/*.{test,spec}.{ts,tsx,js,mjs,cjs}', 'test/**/*.test.ts', 'src/**/*.test.ts'],
+ exclude: [
+ '**/node_modules/**',
+ 'test/archive/**',
+ 'archive/**',
+ 'packages/dsh-tauri-ssh/src/client/components/**',
+ 'packages/dsh-tauri-ssh/src/client/index.test.ts',
+ ],
+ setupFiles: ['./test/setup/tauri-runtime.ts'],
+ maxWorkers: 4,
+ testTimeout: 30_000,
+ hookTimeout: 30_000,
+ })
+ expect(pluginConfig.test).toEqual({
+ name: 'plugin',
+ include: ['test/e2e/plugins/**/*.e2e.ts'],
+ globalSetup: ['./test/e2e/setup-plugin.ts'],
+ environment: 'node',
+ fileParallelism: false,
+ testTimeout: 120_000,
+ hookTimeout: 120_000,
+ })
+ expect(desktopConfig.test).toEqual({
+ name: 'desktop',
+ include: ['test/e2e/desktop/*.e2e.ts'],
+ globalSetup: ['./test/e2e/setup-desktop.ts'],
+ environment: 'node',
+ fileParallelism: false,
+ testTimeout: 180_000,
+ hookTimeout: 180_000,
+ })
+ expect(runtime.projects.map(project => project.name)).toEqual(['unit', 'plugin', 'desktop'])
+ expect(runtime.projects.map(project => ({
+ name: project.name,
+ environment: project.config.environment,
+ maxWorkers: project.config.maxWorkers,
+ testTimeout: project.config.testTimeout,
+ hookTimeout: project.config.hookTimeout,
+ }))).toEqual([
+ { name: 'unit', environment: 'node', maxWorkers: 4, testTimeout: 30_000, hookTimeout: 30_000 },
+ { name: 'plugin', environment: 'node', maxWorkers: 1, testTimeout: 120_000, hookTimeout: 120_000 },
+ { name: 'desktop', environment: 'node', maxWorkers: 1, testTimeout: 180_000, hookTimeout: 180_000 },
+ ])
+ })
+
+ it('runtime collection routes unit and E2E files without admitting excluded paths', async () => {
+ const cases = [
+ ['test/tooling-config.test.ts', ['unit']],
+ ['src/layout/components/nav-bridge.test.ts', ['unit']],
+ ['packages/dsh-tauri/src/host/apply.test.ts', ['unit']],
+ ['test/e2e/plugins/dsh-tauri.e2e.ts', ['plugin']],
+ ['test/e2e/plugins/nested/contract.e2e.ts', ['plugin']],
+ ['test/e2e/desktop/boot.e2e.ts', ['desktop']],
+ ['test/e2e/desktop/nested/contract.e2e.ts', []],
+ ['test/archive/contract.test.ts', []],
+ ['archive/contract.test.ts', []],
+ ['source/contract.test.ts', []],
+ ['packages/dsh-tauri/node_modules/copy/index.test.ts', []],
+ ['packages/dsh-tauri-ssh/src/client/components/panel.test.tsx', []],
+ ['packages/dsh-tauri-ssh/src/client/index.test.ts', []],
+ ] as const
+ for (const [relative, projects] of cases) {
+ expect(runtime.projects.filter(project => project.matchesTestGlob(path.join(root, relative))).map(project => project.name), relative).toEqual(projects)
+ }
+ const specs = await runtime.globTestSpecifications()
+ expect(specs.filter(spec => spec.moduleId.endsWith('/test/tooling-config.test.ts')).map(spec => spec.project.name)).toEqual(['unit'])
+ expect(specs.filter(spec => spec.moduleId.endsWith('/test/e2e/desktop/boot.e2e.ts')).map(spec => spec.project.name)).toEqual(['desktop'])
+ expect(specs.filter(spec => spec.moduleId.endsWith('/test/e2e/plugins/dsh-tauri.e2e.ts')).map(spec => spec.project.name)).toEqual(['plugin'])
+ for (const spec of specs) {
+ const relative = path.relative(root, spec.moduleId).replaceAll('\\', '/')
+ expect(relative).not.toMatch(/(^|\/)node_modules\//)
+ expect(relative).not.toMatch(/^(?:archive|source|test\/archive)\//)
+ expect(relative).not.toMatch(/^packages\/dsh-tauri-ssh\/src\/client\/(?:components\/|index\.test\.ts$)/)
+ }
+ })
+
+ it('coverage remains root-only with all existing exclusions and no thresholds', () => {
+ expect(rootConfig.test?.projects).toEqual(['./vitest.unit.config.ts', './vitest.plugin.config.ts', './vitest.desktop.config.ts'])
+ expect(rootConfig.test?.coverage).toEqual({
+ provider: 'v8',
+ exclude: [
+ '**/node_modules/**',
+ '**/dist/**',
+ '**/.{idea,git,cache,output,temp}/**',
+ '**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*',
+ 'source/**',
+ 'archive/**',
+ 'test/archive/**',
+ 'src-tauri/**',
+ ],
+ })
+ expect(rootConfig.test).not.toHaveProperty('include')
+ for (const config of [unitConfig, pluginConfig, desktopConfig]) {
+ expect(config.test).not.toHaveProperty('coverage')
+ expect(config.test).not.toHaveProperty('globals')
+ }
+ })
+
+ it('the folded TypeScript project includes tooling without weakening compiler checks', () => {
+ const config = ts.readConfigFile(path.join(root, 'tsconfig.json'), ts.sys.readFile)
+ expect(config.error).toBeUndefined()
+ const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, root)
+ expect(parsed.errors).toEqual([])
+ expect(parsed.projectReferences).toBeUndefined()
+ expect(config.config).not.toHaveProperty('exclude')
+ expect(parsed.options).toMatchObject({
+ strict: true,
+ noUnusedLocals: true,
+ noUnusedParameters: true,
+ noFallthroughCasesInSwitch: true,
+ noEmit: true,
+ isolatedModules: true,
+ skipLibCheck: true,
+ })
+ const files = parsed.fileNames.map(file => path.relative(root, file).replaceAll('\\', '/'))
+ for (const file of [
+ 'vite.config.ts',
+ 'vitest.config.ts',
+ 'vitest.unit.config.ts',
+ 'vitest.plugin.config.ts',
+ 'vitest.desktop.config.ts',
+ 'tooling.config.ts',
+ 'bump.config.ts',
+ 'genapi.config.ts',
+ 'genapi.pipeline.ts',
+ 'scripts/build-debug.ts',
+ 'scripts/build-plugins.ts',
+ 'scripts/rebuild-macos-icon.ts',
+ 'packages/.test/test-utils.ts',
+ ]) {
+ expect(files, file).toContain(file)
+ }
+ })
+})
diff --git a/test/wdio-e2e-gate.test.ts b/test/wdio-e2e-gate.test.ts
index 46c696c9..0dd73663 100644
--- a/test/wdio-e2e-gate.test.ts
+++ b/test/wdio-e2e-gate.test.ts
@@ -1,8 +1,8 @@
-import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
+import { readSource } from './setup/read-source'
-const BUILDER = readFileSync(new URL('../src-tauri/src/desktop/builder.rs', import.meta.url), 'utf8')
-const SETTING = readFileSync(new URL('../src-tauri/src/config/setting.rs', import.meta.url), 'utf8')
+const BUILDER = readSource('src-tauri/src/desktop/builder.rs')
+const SETTING = readSource('src-tauri/src/config/setting.rs')
describe('embedded WebDriver plugin is registered for E2E runs only', () => {
it('registers tauri-plugin-wdio-webdriver inside the is_e2e_run guard', () => {
diff --git a/tooling.config.ts b/tooling.config.ts
new file mode 100644
index 00000000..df6f9cc0
--- /dev/null
+++ b/tooling.config.ts
@@ -0,0 +1,5 @@
+import { fileURLToPath } from 'node:url'
+
+export const SHARED_ALIAS = {
+ '@': fileURLToPath(new URL('./src', import.meta.url)),
+}
diff --git a/tsconfig.json b/tsconfig.json
index 64052e1a..57acdee4 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -22,7 +22,6 @@
"isolatedModules": true,
"skipLibCheck": true
},
- "references": [{ "path": "./tsconfig.node.json" }],
"include": [
"src",
"test",
@@ -30,6 +29,8 @@
"packages/*/scripts",
"types",
"packages/.test/test-utils.ts",
- "scripts/build-plugins.ts"
+ "scripts",
+ "*.config.ts",
+ "genapi*.ts"
]
}
diff --git a/tsconfig.node.json b/tsconfig.node.json
deleted file mode 100644
index 98f0facb..00000000
--- a/tsconfig.node.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "compilerOptions": {
- "composite": true,
- "module": "ESNext",
- "moduleResolution": "bundler",
- "allowSyntheticDefaultImports": true,
- "skipLibCheck": true
- },
- "include": ["vite.config.ts", "scripts/**/*"],
- "exclude": ["scripts/build-plugins.ts"]
-}
diff --git a/vite.config.ts b/vite.config.ts
index 80dc7147..4a74b561 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -2,6 +2,7 @@ import process from 'node:process'
import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
+import { SHARED_ALIAS } from './tooling.config'
const host = process.env.TAURI_DEV_HOST
@@ -27,9 +28,7 @@ export default defineConfig(async () => ({
},
resolve: {
- alias: {
- '@': '/src',
- },
+ alias: SHARED_ALIAS,
},
// Vite options tailored for Tauri development.
diff --git a/vitest.config.ts b/vitest.config.ts
index 4181fb43..859de2ea 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -1,24 +1,10 @@
-import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vitest/config'
+import { SHARED_ALIAS } from './tooling.config'
-/**
- * 根 Vitest 配置:只放「跨 project 的全局项」与 project 清单。
- *
- * Vitest 不把根配置本身当作 project(除非显式列出),因此这里不再写任何 include:
- * 用例归属由 `vitest.unit.config.ts`(单元)、`vitest.plugin.config.ts`(插件 L2)
- * 与 `vitest.desktop.config.ts`(桌面端 L3)各自声明。
- *
- * 注意 project 级配置**不继承**这里的 `resolve.alias`,各 project 需自行声明 `@/`。
- *
- * 仓库根还 vendored 了 dsh 核心源码(`source/` 与 `archive/`),其测试依赖 dsh 核心的
- * `@/` paths 解析(在插件 workspace 的 vitest 下不可用),故三个 project 都不纳入。
- */
export default defineConfig({
// 与 vite.config.ts 保持一致:src 内部统一用 `@/` 别名。
resolve: {
- alias: {
- '@': fileURLToPath(new URL('./src', import.meta.url)),
- },
+ alias: SHARED_ALIAS,
},
test: {
projects: [
diff --git a/vitest.unit.config.ts b/vitest.unit.config.ts
index 178862ca..ada08935 100644
--- a/vitest.unit.config.ts
+++ b/vitest.unit.config.ts
@@ -1,34 +1,9 @@
-import { fileURLToPath } from 'node:url'
import { defineProject } from 'vitest/config'
+import { SHARED_ALIAS } from './tooling.config'
-/**
- * `unit` project:单元测试。
- *
- * 两条来源:
- * 1. 内置插件(`packages/**`)——测试与其覆盖的源码同目录、同名(`*.test.ts`);
- * 2. 壳层自身的用例——`test/**` 与 `src/**` 下与逻辑同名的 `.test.ts`。
- *
- * `test/archive/**` 是历史用例的归档(只读参考,不参与任何 project)。
- *
- * 排除项必须显式带上 node_modules 的通配:Vitest 一旦收到自定义 `exclude` 就**不再**
- * 合并默认值,而各插件包的 node_modules 下装着彼此链接的副本——不排除会把同一个
- * `index.test.ts` 收编七八遍,既拖慢全量跑,又让重复的异步错误被计成 unhandled
- * 而判整轮失败。
- *
- * 别名:project 级配置不继承根 `vitest.config.ts` 的 `resolve.alias`,而壳层用例
- * 普遍 import `@/…`,因此这里必须重复声明一次。
- *
- * 并发与超时:worktree 插件会创建真实 git 仓库(clone/checkout/discard),全量并行时
- * 与其他文件的 git 操作竞争系统资源,偶发 5s 超时 flake;限制 maxWorkers 后单独复跑稳定通过。
- *
- * E2E 用例(`test/e2e/desktop` 与 `test/e2e/plugins` 下的 `.e2e.ts`)由
- * `vitest.desktop.config.ts` / `vitest.plugin.config.ts` 负责,本 project 不收。
- */
export default defineProject({
resolve: {
- alias: {
- '@': fileURLToPath(new URL('./src', import.meta.url)),
- },
+ alias: SHARED_ALIAS,
},
test: {
name: 'unit',