dsh-plugin-testkit 0.0.0-stage → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-plugin-e2e contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,91 @@
1
- # Temporary Holding Version
1
+ # dsh-plugin-testkit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [简体中文](./README.zh-CN.md)
4
+
5
+ Unit-test the **client half** of a DSH plugin without booting DSH: evaluate the plugin's `client.js` in a `node:vm` sandbox with a fake `window.__ModuleLoader__` and a React stub, then assert on the slots it registered.
6
+
7
+ This is a **pure library** — no `bin`, no CLI. It covers client-side *logic* (does `apply` run, which slots get registered, what does it log). It does **not** replace end-to-end tests.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm i -D dsh-plugin-testkit
13
+ ```
14
+
15
+ - Node >= 22.15.0.
16
+ - No runtime dependencies.
17
+
18
+ ## Quick start
19
+
20
+ ```js
21
+ import { loadClientModule, applyAndListSlots, hasSlot } from 'dsh-plugin-testkit'
22
+ import { readFileSync } from 'node:fs'
23
+
24
+ const mod = loadClientModule(readFileSync('client.js', 'utf8'), { id: 'my-plugin' })
25
+
26
+ const slots = applyAndListSlots(mod)
27
+ // [{ name: 'conversation.composer.dock', id: 'my-plugin', order: 5 }]
28
+
29
+ if (!hasSlot(mod, 'conversation.composer.dock')) throw new Error('dock slot missing')
30
+ ```
31
+
32
+ ## API
33
+
34
+ All 3 exports.
35
+
36
+ | Export | Signature | Returns | Behavior |
37
+ |---|---|---|---|
38
+ | `loadClientModule` | `loadClientModule(source, { id = 'plugin', extraRequire = {} } = {})` | sandbox handle | Runs `source` in a fresh `node:vm` context and returns the captured module plus helpers. |
39
+ | `applyAndListSlots` | `applyAndListSlots(clientModule)` | `Array<{ name, id, order }>` | Runs one idempotent `apply()` and maps the registrations to plain descriptors. |
40
+ | `hasSlot` | `hasSlot(clientModule, name, slotId?)` | `boolean` | Whether the **latest** `apply()` registered `name`; when `slotId` is given, its `id` must match too. |
41
+
42
+ ### The handle returned by `loadClientModule`
43
+
44
+ | Field | Type | Meaning |
45
+ |---|---|---|
46
+ | `id` | `string` | The `id` you passed in. Used for the object and the vm filename only — it does **not** rewrite any slot or bundle id inside the source. |
47
+ | `module` | `object` | What the plugin's factory returned (must be an object with `apply(ctx)`). |
48
+ | `registrations` | `Array<{ def, comp }>` | Live list of `slots.register(def, comp)` calls. |
49
+ | `ctx` | `object` | The fake plugin context: `{ slots, logger, config: {}, on() {}, emit() {} }`. |
50
+ | `logs` | `Array` | Captured console calls as `['log' \| 'info' \| 'warn' \| 'error' \| 'debug', ...args]`. |
51
+ | `apply()` | `() => Array<{def, comp}>` | **Idempotent**: clears `registrations` first, then calls `module.apply(ctx)`. Repeated calls never accumulate duplicates. |
52
+
53
+ ### `extraRequire`
54
+
55
+ `require(name)` resolves in this order: `extraRequire[name]` → the built-in `react` stub → throw.
56
+
57
+ ```js
58
+ const mod = loadClientModule(src, {
59
+ id: 'my-plugin',
60
+ extraRequire: { '@dsh/ui': { Button: () => null } },
61
+ })
62
+ ```
63
+
64
+ An unresolved module throws `dsh-plugin-testkit: 未提供 require("<name>");用 extraRequire 传入`.
65
+
66
+ ### `loadClientModule` failures
67
+
68
+ It throws, rather than returning a half-built handle, when the source is not shaped like a DSH client module. All four are verified:
69
+
70
+ | Condition | Error |
71
+ |---|---|
72
+ | Never called `window.__ModuleLoader__.load(...)` | `dsh-plugin-testkit: 客户端未调用 window.__ModuleLoader__.load(...)` |
73
+ | The factory returned a non-object (e.g. `42`, `null`) | `dsh-plugin-testkit: factory 未返回模块对象` |
74
+ | The returned object has no `apply` function | `dsh-plugin-testkit: 模块对象缺少 apply(ctx) 方法` |
75
+ | `slots.register` called without a definition object | `dsh-plugin-testkit: slots.register 需要定义对象,收到 undefined` |
76
+
77
+ The object check is `typeof captured === 'object'`, so an array passes it and then fails on the missing `apply`.
78
+
79
+ ## Notes
80
+
81
+ - **Not a security boundary.** `node:vm` is a logic sandbox that can be escaped — run only **trusted test sources** in it, never third-party or user-supplied plugin code.
82
+ - **`window === globalThis`** (matching browser semantics), so code that writes `window.foo` or bare `foo` hits the same object.
83
+ - **`console` and timers are isolated stubs.** Logs land in `mod.logs` instead of the terminal; `setTimeout` / `setInterval` return `0` and never fire, so nothing can keep the host process alive.
84
+ - **`register` and `inject` both return disposers**, matching the real DSH contract. `register`'s disposer removes the record from `registrations`; `inject`'s is a no-op `() => {}` because `inject(name, fn)` simply invokes `fn()` when it is a function.
85
+ - **React hooks are simplified stubs.** `useState` / `useReducer` accept functional updates but never trigger a re-render; `useEffect` and `useLayoutEffect` are no-ops; `useMemo` runs the factory on every call; `useCallback` returns the function as-is; `memo` is identity. Components are never rendered — `createElement` just builds `{ type, props, children }`.
86
+ - **This tests the client half only.** Anything that depends on real rendering, effects, layout or DSH host wiring still needs an end-to-end test (`dsh-plugin-e2e`).
87
+ - The `document` stub is minimal (`createElement`, `addEventListener`, `querySelector` returning `null`); DOM-heavy code will need real browser coverage.
88
+
89
+ ## License
90
+
91
+ MIT
@@ -0,0 +1,91 @@
1
+ # dsh-plugin-testkit
2
+
3
+ [English](./README.md) | 简体中文
4
+
5
+ 不开 DSH 也能单测插件的**客户端半侧**:把插件的 `client.js` 放进 `node:vm` 沙箱,配一个假的 `window.__ModuleLoader__` 和 React 桩执行,然后对它注册的 slot 做断言。
6
+
7
+ 这是**纯库**——没有 `bin`,没有 CLI。它覆盖的是客户端**逻辑**(`apply` 跑没跑、注册了哪些 slot、打了什么日志),**不替代**端到端测试。
8
+
9
+ ## 安装
10
+
11
+ ```bash
12
+ npm i -D dsh-plugin-testkit
13
+ ```
14
+
15
+ - Node >= 22.15.0。
16
+ - 无运行时依赖。
17
+
18
+ ## 快速开始
19
+
20
+ ```js
21
+ import { loadClientModule, applyAndListSlots, hasSlot } from 'dsh-plugin-testkit'
22
+ import { readFileSync } from 'node:fs'
23
+
24
+ const mod = loadClientModule(readFileSync('client.js', 'utf8'), { id: 'my-plugin' })
25
+
26
+ const slots = applyAndListSlots(mod)
27
+ // [{ name: 'conversation.composer.dock', id: 'my-plugin', order: 5 }]
28
+
29
+ if (!hasSlot(mod, 'conversation.composer.dock')) throw new Error('dock slot 没注册')
30
+ ```
31
+
32
+ ## API
33
+
34
+ 共 3 个导出。
35
+
36
+ | 导出 | 签名 | 返回 | 行为 |
37
+ |---|---|---|---|
38
+ | `loadClientModule` | `loadClientModule(source, { id = 'plugin', extraRequire = {} } = {})` | 沙箱句柄 | 在全新的 `node:vm` 上下文里执行 `source`,返回抓到的模块与辅助方法。 |
39
+ | `applyAndListSlots` | `applyAndListSlots(clientModule)` | `Array<{ name, id, order }>` | 跑一次幂等的 `apply()`,把注册记录映射成纯描述对象。 |
40
+ | `hasSlot` | `hasSlot(clientModule, name, slotId?)` | `boolean` | **最近一次** `apply()` 是否注册了 `name`;给了 `slotId` 还要求 `id` 也匹配。 |
41
+
42
+ ### `loadClientModule` 返回的句柄
43
+
44
+ | 字段 | 类型 | 含义 |
45
+ |---|---|---|
46
+ | `id` | `string` | 你传进来的 `id`。只用于对象标识与 vm 文件名——**不会**改写源码里的任何 slot / bundle id。 |
47
+ | `module` | `object` | 插件 factory 返回的模块对象(必须是带 `apply(ctx)` 的对象)。 |
48
+ | `registrations` | `Array<{ def, comp }>` | `slots.register(def, comp)` 调用的实时列表。 |
49
+ | `ctx` | `object` | 假的插件上下文:`{ slots, logger, config: {}, on() {}, emit() {} }`。 |
50
+ | `logs` | `Array` | 捕获的 console 调用,形如 `['log' \| 'info' \| 'warn' \| 'error' \| 'debug', ...args]`。 |
51
+ | `apply()` | `() => Array<{def, comp}>` | **幂等**:先清空 `registrations`,再调 `module.apply(ctx)`。重复调用不会累加出重复注册。 |
52
+
53
+ ### `extraRequire`
54
+
55
+ `require(name)` 的解析顺序:`extraRequire[name]` → 内置 `react` 桩 → 抛错。
56
+
57
+ ```js
58
+ const mod = loadClientModule(src, {
59
+ id: 'my-plugin',
60
+ extraRequire: { '@dsh/ui': { Button: () => null } },
61
+ })
62
+ ```
63
+
64
+ 模块没提供会抛 `dsh-plugin-testkit: 未提供 require("<name>");用 extraRequire 传入`。
65
+
66
+ ### `loadClientModule` 的失败情形
67
+
68
+ 源码不像 DSH 客户端模块时它**直接抛错**,不会返回半成品句柄。四种情形均已实测:
69
+
70
+ | 情形 | 报错 |
71
+ |---|---|
72
+ | 始终没调 `window.__ModuleLoader__.load(...)` | `dsh-plugin-testkit: 客户端未调用 window.__ModuleLoader__.load(...)` |
73
+ | factory 返回的不是对象(如 `42`、`null`) | `dsh-plugin-testkit: factory 未返回模块对象` |
74
+ | 返回的对象没有 `apply` 函数 | `dsh-plugin-testkit: 模块对象缺少 apply(ctx) 方法` |
75
+ | `slots.register` 调用时没传定义对象 | `dsh-plugin-testkit: slots.register 需要定义对象,收到 undefined` |
76
+
77
+ 对象判断用的是 `typeof captured === 'object'`,所以数组能过这一关,随后卡在缺少 `apply` 上。
78
+
79
+ ## 注意事项
80
+
81
+ - **不是安全边界。** `node:vm` 只是逻辑沙箱,可以被逃逸——只能拿它跑**可信的测试源码**,绝不要用它执行第三方或用户提供的插件代码。
82
+ - **`window === globalThis`**(同浏览器语义),所以写 `window.foo` 和写裸 `foo` 落到同一个对象。
83
+ - **`console` 与定时器是隔离桩。** 日志进 `mod.logs` 而不打到终端;`setTimeout` / `setInterval` 返回 `0` 且永不触发,不会挂住宿主进程。
84
+ - **`register` 与 `inject` 都返回 disposer**,与真实 DSH 契约一致。`register` 的 disposer 把记录从 `registrations` 里摘掉;`inject` 的是个空操作 `() => {}`,因为 `inject(name, fn)` 只是在 `fn` 是函数时直接调 `fn()`。
85
+ - **React hook 是简化桩。** `useState` / `useReducer` 支持函数式更新但不触发重渲染;`useEffect` 与 `useLayoutEffect` 是空操作;`useMemo` 每次调用都跑工厂;`useCallback` 原样返回函数;`memo` 是恒等。组件从不真正渲染——`createElement` 只拼出 `{ type, props, children }`。
86
+ - **它只测客户端半侧。** 依赖真实渲染、副作用、布局或 DSH 宿主接线的部分,仍需端到端测试(`dsh-plugin-e2e`)。
87
+ - `document` 桩极其精简(`createElement`、`addEventListener`、`querySelector` 返回 `null`);重度操作 DOM 的代码需要真实浏览器覆盖。
88
+
89
+ ## 许可证
90
+
91
+ MIT
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "dsh-plugin-testkit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.3",
4
+ "private": false,
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "description": "Lightweight harness to unit-test a DSH plugin's client half: evaluate client.js in a sandbox with a fake window.__ModuleLoader__ + React stub, capture slot registrations, and assert.",
8
+ "exports": {
9
+ ".": "./src/index.mjs"
10
+ },
11
+ "files": [
12
+ "src/",
13
+ "README.md",
14
+ "README.zh-CN.md"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/metal-huang/dsh-devtools.git",
19
+ "directory": "packages/dsh-plugin-testkit"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "registry": "https://registry.npmjs.org/"
24
+ },
25
+ "engines": {
26
+ "dsh": ">=0.2.2-rc.5",
27
+ "node": ">=22.15.0"
28
+ },
29
+ "dshTestedOn": [
30
+ "0.2.2-rc.5",
31
+ "0.2.3-alpha.2"
32
+ ]
33
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,139 @@
1
+ // dsh-plugin-testkit:轻量沙箱跑「插件客户端半侧」,抓 slot 注册并断言——不需要起完整 DSH。
2
+ // 仅用于**可信测试源码**:node:vm 不是安全隔离,不要用它执行不可信代码。
3
+ import vm from 'node:vm'
4
+
5
+ function makeReactStub() {
6
+ const createElement = (type, props, ...children) => ({ type, props: props || {}, children })
7
+ return {
8
+ createElement,
9
+ Fragment: 'Fragment',
10
+ useState(initial) {
11
+ let v = typeof initial === 'function' ? initial() : initial
12
+ const set = (next) => {
13
+ v = typeof next === 'function' ? next(v) : next
14
+ }
15
+ return [v, set]
16
+ },
17
+ useReducer(reducer, init) {
18
+ let s = init
19
+ const dispatch = (action) => {
20
+ s = reducer(s, action)
21
+ }
22
+ return [s, dispatch]
23
+ },
24
+ useEffect() {},
25
+ useLayoutEffect() {},
26
+ useMemo(fn) {
27
+ return fn()
28
+ },
29
+ useCallback(fn) {
30
+ return fn
31
+ },
32
+ useRef(v) {
33
+ return { current: v }
34
+ },
35
+ memo(c) {
36
+ return c
37
+ },
38
+ }
39
+ }
40
+
41
+ /**
42
+ * @param {string} source 插件 client.js 源码
43
+ * @param {{id?:string, extraRequire?:Record<string,any>}} opts
44
+ */
45
+ export function loadClientModule(source, { id = 'plugin', extraRequire = {} } = {}) {
46
+ const registrations = []
47
+ const slots = {
48
+ inject(name, fn) {
49
+ if (typeof fn === 'function') fn()
50
+ return () => {}
51
+ },
52
+ register(def, comp) {
53
+ if (!def || typeof def !== 'object') {
54
+ throw new Error('dsh-plugin-testkit: slots.register 需要定义对象,收到 ' + String(def))
55
+ }
56
+ const rec = { def, comp }
57
+ registrations.push(rec)
58
+ // 与真实 API 一致:返回 disposer 函数
59
+ return () => {
60
+ const i = registrations.indexOf(rec)
61
+ if (i >= 0) registrations.splice(i, 1)
62
+ }
63
+ },
64
+ }
65
+ const logs = []
66
+ const fakeConsole = {
67
+ log: (...a) => logs.push(['log', ...a]),
68
+ info: (...a) => logs.push(['info', ...a]),
69
+ warn: (...a) => logs.push(['warn', ...a]),
70
+ error: (...a) => logs.push(['error', ...a]),
71
+ debug: (...a) => logs.push(['debug', ...a]),
72
+ }
73
+ const noopTimer = () => 0
74
+ const ctx = { slots, logger: fakeConsole, config: {}, on() {}, emit() {} }
75
+ const react = makeReactStub()
76
+ const fakeRequire = (n) => {
77
+ if (Object.prototype.hasOwnProperty.call(extraRequire, n)) return extraRequire[n]
78
+ if (n === 'react') return react
79
+ throw new Error('dsh-plugin-testkit: 未提供 require("' + n + '");用 extraRequire 传入')
80
+ }
81
+ let loaded = false
82
+ let captured = null
83
+ const docStub = {
84
+ createElement: () => ({ style: {}, appendChild() {}, setAttribute() {}, addEventListener() {} }),
85
+ addEventListener() {},
86
+ querySelector: () => null,
87
+ }
88
+ // window === globalThis(同浏览器语义);console/定时器用隔离桩,避免污染或挂住宿主进程。
89
+ const sandbox = {
90
+ console: fakeConsole,
91
+ document: docStub,
92
+ setTimeout: noopTimer,
93
+ clearTimeout() {},
94
+ setInterval: noopTimer,
95
+ clearInterval() {},
96
+ React: react,
97
+ }
98
+ sandbox.window = sandbox
99
+ sandbox.globalThis = sandbox
100
+ sandbox.__ModuleLoader__ = {
101
+ load({ id: lid, factory }) {
102
+ loaded = true
103
+ captured = factory(fakeRequire)
104
+ },
105
+ }
106
+ const context = vm.createContext(sandbox)
107
+ vm.runInContext(source, context, { filename: id + '.client.js' })
108
+ if (!loaded) throw new Error('dsh-plugin-testkit: 客户端未调用 window.__ModuleLoader__.load(...)')
109
+ if (!captured || typeof captured !== 'object') throw new Error('dsh-plugin-testkit: factory 未返回模块对象')
110
+ if (typeof captured.apply !== 'function') throw new Error('dsh-plugin-testkit: 模块对象缺少 apply(ctx) 方法')
111
+ return {
112
+ id,
113
+ module: captured,
114
+ registrations,
115
+ ctx,
116
+ logs,
117
+ // 幂等:每次 apply 先清空再执行,避免重复调用累加出重复注册
118
+ apply() {
119
+ registrations.length = 0
120
+ captured.apply(ctx)
121
+ return registrations
122
+ },
123
+ }
124
+ }
125
+
126
+ /** 跑一次 apply(幂等),返回 [{name,id,order}]。 */
127
+ export function applyAndListSlots(clientModule) {
128
+ clientModule.apply()
129
+ return clientModule.registrations.map((r) => ({
130
+ name: r.def && r.def.name,
131
+ id: r.def && r.def.id,
132
+ order: r.def && r.def.order,
133
+ }))
134
+ }
135
+
136
+ /** 是否注册了指定 slot(可选校验 id)。读取最近一次 apply 的结果。 */
137
+ export function hasSlot(clientModule, name, slotId) {
138
+ return clientModule.registrations.some((r) => r.def && r.def.name === name && (!slotId || r.def.id === slotId))
139
+ }