@capyclaw/browser-workbench 0.0.0-stage → 0.1.0

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.
Files changed (52) hide show
  1. package/README.md +66 -2
  2. package/contract/browser-contract.json +890 -0
  3. package/cordis.patch.yml +25 -0
  4. package/demo/form.html +85 -0
  5. package/lib/host.mjs +68 -0
  6. package/package.json +61 -4
  7. package/server/constants.mjs +16 -0
  8. package/server/contract-snapshots.mjs +81 -0
  9. package/server/contract.mjs +24 -0
  10. package/server/engine.mjs +675 -0
  11. package/server/http-utils.mjs +2 -0
  12. package/server/infra/http.mjs +113 -0
  13. package/server/infra/tuning.mjs +82 -0
  14. package/server/mcp/handler.mjs +2 -0
  15. package/server/mcp/instructions.mjs +28 -0
  16. package/server/relay.mjs +226 -0
  17. package/server/routes/api.mjs +120 -0
  18. package/server/routes/assets.mjs +2 -0
  19. package/server/routes/mcp.mjs +17 -0
  20. package/server/routes/workbench.mjs +33 -0
  21. package/server/shared/SHARED_MANIFEST.json +47 -0
  22. package/server/shared/asset-service.mjs +217 -0
  23. package/server/shared/editor-host.mjs +125 -0
  24. package/server/shared/kit/editor/lease.mjs +139 -0
  25. package/server/shared/kit/service/api.mjs +45 -0
  26. package/server/shared/kit/service/http.mjs +113 -0
  27. package/server/shared/kit/service/mcp-http.mjs +142 -0
  28. package/server/shared/kit/tools/validate.mjs +115 -0
  29. package/server/shared/kit/tuning.mjs +82 -0
  30. package/server/shared/kit/util/fs-lock.mjs +132 -0
  31. package/server/shared/service-host.mjs +511 -0
  32. package/server/shared/state-service.mjs +249 -0
  33. package/server/shared/tool-host.mjs +341 -0
  34. package/server/shared/tuning.mjs +63 -0
  35. package/server/tools/capabilities/contract.mjs +35 -0
  36. package/server/tools/capabilities/evaluate.mjs +36 -0
  37. package/server/tools/capabilities/index.mjs +26 -0
  38. package/server/tools/capabilities/interaction.mjs +111 -0
  39. package/server/tools/capabilities/navigation.mjs +32 -0
  40. package/server/tools/capabilities/screenshot.mjs +33 -0
  41. package/server/tools/capabilities/session.mjs +75 -0
  42. package/server/tools/capabilities/snapshot.mjs +30 -0
  43. package/server/tools/capabilities/tabs.mjs +35 -0
  44. package/server/tools/index.mjs +12 -0
  45. package/server/tools/kernel/define.mjs +5 -0
  46. package/server/tools/kernel/output.mjs +22 -0
  47. package/server/tools/kernel/ports.mjs +54 -0
  48. package/server/tools/kernel/registry.mjs +17 -0
  49. package/server/tools.mjs +3 -0
  50. package/ui/app.js +157 -0
  51. package/ui/index.html +56 -0
  52. package/ui/style.css +76 -0
@@ -0,0 +1,217 @@
1
+ /**
2
+ * dsh-asset-service —— 通用对象资产仓库。
3
+ *
4
+ * 功能插件不再各自实现 `/assets/<sha256>`、base64 上传、content-type 与缓存头。
5
+ * 资产按 sha256 去重,url 为 `/assets/<id>`。
6
+ *
7
+ * 两种后端:
8
+ * - workspace:storeClient(ctx.workspace 的 scoped client),资产归当前 work;
9
+ * - file:本地目录,适合无 workspace 的独立运行/测试。
10
+ */
11
+ import crypto from 'node:crypto'
12
+ import fs from 'node:fs'
13
+ import path from 'node:path'
14
+ import { send, readBody } from '@capyclaw/plugin-kit/service/http'
15
+ import { createServiceApi } from '@capyclaw/plugin-kit/service/api'
16
+
17
+ function sha256(buffer) {
18
+ return crypto.createHash('sha256').update(buffer).digest('hex')
19
+ }
20
+
21
+ const ASSET_ID_RE = /^[a-f0-9]{64}$/
22
+
23
+ function validId(id) {
24
+ return ASSET_ID_RE.test(String(id || ''))
25
+ }
26
+
27
+ function normalizeBuffer(value) {
28
+ if (Buffer.isBuffer(value)) return value
29
+ if (value instanceof Uint8Array) return Buffer.from(value)
30
+ throw new Error('asset: 数据必须是 Buffer/Uint8Array')
31
+ }
32
+
33
+ /** 基于 ctx.workspace 的 scoped WorkspaceClient。 */
34
+ export function createWorkspaceAssetStore({ storeClient, workId = 'main' } = {}) {
35
+ if (!storeClient || typeof storeClient.put !== 'function') throw new Error('createWorkspaceAssetStore 需要 storeClient')
36
+ return {
37
+ kind: 'workspace',
38
+ async put(value, contentType = 'application/octet-stream') {
39
+ const buffer = normalizeBuffer(value)
40
+ const id = sha256(buffer)
41
+ const key = `assets/${id}`
42
+ storeClient.put(workId, key, buffer, { contentType })
43
+ return { id, key, url: `/assets/${id}`, size: buffer.length, contentType }
44
+ },
45
+ get(id) {
46
+ if (!validId(id)) return null
47
+ const key = `assets/${id}`
48
+ try {
49
+ const data = storeClient.get(workId, key)
50
+ if (!data) return null
51
+ const meta = storeClient.list(workId).find((item) => item.key === key)
52
+ return { data, contentType: meta?.contentType || 'application/octet-stream' }
53
+ } catch {
54
+ /* 缺失/权限错误按 404 处理,不能把 500 泄漏给资产路由。 */
55
+ return null
56
+ }
57
+ },
58
+ has(id) {
59
+ if (!validId(id)) return false
60
+ try { return !!storeClient.get(workId, `assets/${id}`) } catch { return false }
61
+ },
62
+ }
63
+ }
64
+
65
+ /** 本地目录后端:<dir>/<sha256> + <dir>/<sha256>.meta.json。 */
66
+ export function createFileAssetStore({ dir } = {}) {
67
+ if (!dir) throw new Error('createFileAssetStore 需要 dir')
68
+ fs.mkdirSync(dir, { recursive: true })
69
+ return {
70
+ kind: 'file',
71
+ async put(value, contentType = 'application/octet-stream') {
72
+ const buffer = normalizeBuffer(value)
73
+ const id = sha256(buffer)
74
+ const file = path.join(dir, id)
75
+ const metaFile = file + '.meta.json'
76
+ const existingOk = (() => {
77
+ try { return fs.statSync(file).size === buffer.length } catch { return false }
78
+ })()
79
+ if (!existingOk) {
80
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`
81
+ fs.writeFileSync(tmp, buffer)
82
+ fs.renameSync(tmp, file)
83
+ }
84
+ const metaTmp = `${metaFile}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`
85
+ fs.writeFileSync(metaTmp, JSON.stringify({ contentType, size: buffer.length }))
86
+ fs.renameSync(metaTmp, metaFile)
87
+ return { id, key: id, url: `/assets/${id}`, size: buffer.length, contentType }
88
+ },
89
+ get(id) {
90
+ if (!validId(id)) return null
91
+ const file = path.join(dir, path.basename(String(id)))
92
+ try {
93
+ const data = fs.readFileSync(file)
94
+ /* 内容寻址仓库必须复核 hash:截断/篡改的对象不能静默返回。 */
95
+ if (sha256(data) !== id) {
96
+ console.error(`[asset-service] 对象校验失败,拒绝返回: ${id}`)
97
+ return null
98
+ }
99
+ let contentType = 'application/octet-stream'
100
+ try { contentType = JSON.parse(fs.readFileSync(file + '.meta.json', 'utf8')).contentType || contentType } catch { /* 默认 */ }
101
+ return { data, contentType }
102
+ } catch {
103
+ return null
104
+ }
105
+ },
106
+ has(id) {
107
+ if (!validId(id)) return false
108
+ try { return fs.existsSync(path.join(dir, path.basename(String(id)))) } catch { return false }
109
+ },
110
+ }
111
+ }
112
+
113
+ /** 防止 text/html / svg 在 loopback 同源执行脚本;图片仍按原 MIME 内联。 */
114
+ function safeContentType(type) {
115
+ const base = String(type || '').split(';')[0].trim().toLowerCase() || 'application/octet-stream'
116
+ if (base === 'text/html' || base === 'application/xhtml+xml' || base === 'image/svg+xml') {
117
+ return 'text/plain; charset=utf-8'
118
+ }
119
+ return base
120
+ }
121
+
122
+ /**
123
+ * service-host 兼容的资产路由。
124
+ * GET/HEAD `/assets/<id>`(同时兼容 `<basePath>/assets/<id>`);
125
+ * POST `/assets` 或 `<basePath>/assets`(JSON: { data: base64, contentType })。
126
+ */
127
+ export function createAssetRoutes({ assetStore, basePath = '', maxUploadBytes = 10 * 1024 * 1024 } = {}) {
128
+ const prefix = basePath === '/' ? '' : String(basePath || '').replace(/\/+$/, '')
129
+ const getPrefixes = ['/assets/', prefix ? `${prefix}/assets/` : null].filter(Boolean)
130
+ const postPaths = new Set(['/assets', prefix ? `${prefix}/assets` : null].filter(Boolean))
131
+ return async function assetRoutes(req, res, u) {
132
+ const p = u.pathname
133
+ if (req.method === 'GET' || req.method === 'HEAD') {
134
+ const getPrefix = getPrefixes.find((candidate) => p.startsWith(candidate))
135
+ if (getPrefix) {
136
+ if (!assetStore) { send(req, res, 404, { error: 'asset store unavailable' }); return true }
137
+ const id = decodeURIComponent(p.slice(getPrefix.length))
138
+ if (!validId(id)) { send(req, res, 404, { error: 'asset not found' }); return true }
139
+ const asset = assetStore.get(id)
140
+ if (!asset) { send(req, res, 404, { error: 'asset not found' }); return true }
141
+ res.writeHead(200, {
142
+ 'content-type': safeContentType(asset.contentType),
143
+ 'content-length': asset.data.length,
144
+ 'cache-control': 'public, max-age=31536000, immutable',
145
+ 'x-content-type-options': 'nosniff',
146
+ 'referrer-policy': 'no-referrer',
147
+ })
148
+ res.end(req.method === 'HEAD' ? undefined : asset.data)
149
+ return true
150
+ }
151
+ }
152
+ if (postPaths.has(p) && req.method === 'POST') {
153
+ if (!assetStore) { send(req, res, 503, { error: 'asset store unavailable' }); return true }
154
+ let body
155
+ try { body = await readBody(req, maxUploadBytes) } catch (error) {
156
+ const status = error?.code === 'BODY_TOO_LARGE' ? 413 : 400
157
+ send(req, res, status, { error: String(error.message || error) })
158
+ return true
159
+ }
160
+ if (!body || typeof body.data !== 'string' || !body.data) {
161
+ send(req, res, 400, { error: '缺少图片数据' })
162
+ return true
163
+ }
164
+ const buffer = Buffer.from(body.data, 'base64')
165
+ if (!buffer.length) { send(req, res, 400, { error: '图片数据为空' }); return true }
166
+ const asset = await assetStore.put(buffer, body.contentType || 'application/octet-stream')
167
+ send(req, res, 200, { ok: true, ...asset })
168
+ return true
169
+ }
170
+ return false
171
+ }
172
+ }
173
+
174
+ export function createAssetHost(config = {}) {
175
+ const defaultStore = config.storeClient
176
+ ? createWorkspaceAssetStore({ storeClient: config.storeClient, workId: config.workId })
177
+ : config.dir
178
+ ? createFileAssetStore({ dir: config.dir })
179
+ : null
180
+
181
+ return {
182
+ api: createServiceApi('assets', '1.0.0', ['workspace-store', 'file-store', 'routes', 'sha256', 'mount']),
183
+ version: '0.1.0',
184
+ createStore: createWorkspaceAssetStore,
185
+ createFileStore: createFileAssetStore,
186
+ routes: createAssetRoutes,
187
+ store: defaultStore,
188
+ /**
189
+ * 每个 service-host app 只挂一次资产路由,避免多个插件重复争抢 /assets。
190
+ * @param {object} hostApp createServiceApp() 返回值
191
+ * @param {{ store?: object, basePath?: string }} options
192
+ */
193
+ mount(hostApp, { store = defaultStore, basePath = '' } = {}) {
194
+ if (!hostApp || typeof hostApp.use !== 'function') throw new Error('assets.mount 需要 service-host app')
195
+ if (!store) throw new Error('assets.mount: 没有可用 store')
196
+ if (hostApp.__dshAssetsMounted) return () => {}
197
+ hostApp.__dshAssetsMounted = true
198
+ const unuse = hostApp.use(createAssetRoutes({ assetStore: store, basePath }))
199
+ let disposed = false
200
+ return () => {
201
+ if (disposed) return
202
+ disposed = true
203
+ /* 真正卸载路由;否则热重载后旧 store 仍会抢答 /assets。 */
204
+ if (typeof unuse === 'function') unuse()
205
+ hostApp.__dshAssetsMounted = false
206
+ }
207
+ },
208
+ async put(value, contentType) {
209
+ if (!defaultStore) throw new Error('asset-service: 未配置 storeClient/dir')
210
+ return defaultStore.put(value, contentType)
211
+ },
212
+ get(id) {
213
+ if (!defaultStore) throw new Error('asset-service: 未配置 storeClient/dir')
214
+ return defaultStore.get(id)
215
+ },
216
+ }
217
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * dsh-editor-host —— 通用浏览器编辑器宿主。
3
+ *
4
+ * 功能插件只提供 editor/ 静态目录,不再自己写:
5
+ * - 静态文件路由 / content-type / 404
6
+ * - “显示即连接”的租约仲裁(后打开者抢占,旧窗口静默待命)
7
+ * - claim / release / status / heartbeat 端点
8
+ * - 连接状态供 /healthz 使用
9
+ *
10
+ * 浏览器端可直接使用 @capyclaw/plugin-kit 的 editor/lease.mjs(无 Node 依赖)。
11
+ */
12
+ import fs from 'node:fs'
13
+ import path from 'node:path'
14
+ import { createEditorLease } from '@capyclaw/plugin-kit/editor/lease'
15
+ import { send, readBody } from '@capyclaw/plugin-kit/service/http'
16
+ import { createServiceApi } from '@capyclaw/plugin-kit/service/api'
17
+
18
+ const MIME = {
19
+ '.html': 'text/html; charset=utf-8',
20
+ '.js': 'text/javascript; charset=utf-8',
21
+ '.mjs': 'text/javascript; charset=utf-8',
22
+ '.css': 'text/css; charset=utf-8',
23
+ '.json': 'application/json; charset=utf-8',
24
+ '.svg': 'image/svg+xml',
25
+ '.png': 'image/png',
26
+ '.jpg': 'image/jpeg',
27
+ '.jpeg': 'image/jpeg',
28
+ '.webp': 'image/webp',
29
+ '.woff2': 'font/woff2',
30
+ }
31
+
32
+ function safeJoin(root, rel) {
33
+ const target = path.resolve(root, `.${path.sep}${rel}`)
34
+ const base = path.resolve(root)
35
+ return target === base || target.startsWith(base + path.sep) ? target : null
36
+ }
37
+
38
+ function contentType(file) {
39
+ return MIME[path.extname(file).toLowerCase()] || 'application/octet-stream'
40
+ }
41
+
42
+ /**
43
+ * @param {{ id: string, dir: string, basePath?: string, index?: string, files?: Record<string,string|string[]> }} options
44
+ */
45
+ export function createEditorHost({ id, dir, basePath = '', index = 'index.html', files = null } = {}) {
46
+ if (!id) throw new Error('createEditorHost: id 必填')
47
+ const prefix = basePath === '/' ? '' : String(basePath || '').replace(/\/+$/, '')
48
+ const lease = createEditorLease()
49
+
50
+ const staticRoutes = async function editorStatic(req, res, u) {
51
+ if (req.method !== 'GET' && req.method !== 'HEAD') return false
52
+ if (prefix && u.pathname !== prefix && !u.pathname.startsWith(prefix + '/')) return false
53
+ const relRaw = prefix ? u.pathname.slice(prefix.length) : u.pathname
54
+ const rel = relRaw === '' || relRaw === '/' ? index : decodeURIComponent(relRaw.replace(/^\/+/, ''))
55
+ let file = null
56
+ if (files) {
57
+ const hit = files[relRaw === '' ? '/' : relRaw] || files[relRaw]
58
+ if (!hit) return false
59
+ const name = Array.isArray(hit) ? hit[0] : hit
60
+ file = safeJoin(dir, name)
61
+ } else {
62
+ file = safeJoin(dir, rel)
63
+ }
64
+ if (!file) return false
65
+ try {
66
+ const data = fs.readFileSync(file)
67
+ res.writeHead(200, {
68
+ 'content-type': contentType(file),
69
+ 'content-length': data.length,
70
+ 'x-content-type-options': 'nosniff',
71
+ 'referrer-policy': 'no-referrer',
72
+ 'cache-control': 'no-cache',
73
+ })
74
+ res.end(req.method === 'HEAD' ? undefined : data)
75
+ return true
76
+ } catch {
77
+ return false
78
+ }
79
+ }
80
+
81
+ const leaseRoutes = async function editorLeaseRoutes(req, res, u) {
82
+ const claimPath = `${prefix}/claim`
83
+ const releasePath = `${prefix}/release`
84
+ const statusPath = `${prefix}/status`
85
+ if (u.pathname === claimPath && req.method === 'POST') {
86
+ const body = await readBody(req)
87
+ const result = lease.claim(String(body.id || ''), !!body.force)
88
+ send(req, res, result.ok ? 200 : 409, result)
89
+ return true
90
+ }
91
+ if (u.pathname === releasePath && req.method === 'POST') {
92
+ const body = await readBody(req)
93
+ send(req, res, 200, lease.release(String(body.id || '')))
94
+ return true
95
+ }
96
+ if (u.pathname === statusPath && req.method === 'GET') {
97
+ send(req, res, 200, { ok: true, connected: lease.isLive(), lease: lease.status() })
98
+ return true
99
+ }
100
+ return false
101
+ }
102
+
103
+ return {
104
+ id,
105
+ lease,
106
+ routes() {
107
+ return [staticRoutes, leaseRoutes]
108
+ },
109
+ staticRoutes,
110
+ leaseRoutes,
111
+ status() {
112
+ return { connected: lease.isLive(), lease: lease.status() }
113
+ },
114
+ }
115
+ }
116
+
117
+ export function createEditorHostService(config = {}) {
118
+ return {
119
+ api: createServiceApi('editorHost', '1.0.0', ['static', 'lease', 'heartbeat', 'status']),
120
+ version: '0.1.0',
121
+ createEditorHost,
122
+ createLease: createEditorLease,
123
+ defaultHost: config.dir ? createEditorHost({ id: config.id || 'editor', ...config }) : null,
124
+ }
125
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * 「显示即连接」编辑器租约标准模块。
3
+ *
4
+ * 活动权(claim)只存在于内部仲裁;不要把它渲染成 UI 状态。
5
+ * 新打开的窗口强制抢占,旧窗口静默转入待命。
6
+ */
7
+ import { tuning } from '../tuning.mjs'
8
+
9
+ const DEFAULT_TTL = 15 // 秒
10
+ const DEFAULT_HEARTBEAT = 3 // 秒(心跳间隔应小于 TTL)
11
+
12
+ /**
13
+ * 创建编辑器租约仲裁器。
14
+ * @param {{ ttl?: number }} [opts]
15
+ */
16
+ export function createEditorLease(opts = {}) {
17
+ const ttl = Number(opts.ttl) || DEFAULT_TTL
18
+ let owner = null // { id, ts }
19
+
20
+ return {
21
+ claim(id, force = false) {
22
+ const now = Date.now() / 1000
23
+ if (force || !owner || owner.id === id || now - owner.ts > ttl) {
24
+ owner = { id, ts: now }
25
+ return { ok: true, owner: id }
26
+ }
27
+ return { ok: false, owner: owner.id }
28
+ },
29
+
30
+ release(id) {
31
+ if (owner && owner.id === id) owner = null
32
+ return { ok: true }
33
+ },
34
+
35
+ isLive() {
36
+ return !!owner && Date.now() / 1000 - owner.ts <= ttl
37
+ },
38
+
39
+ status() {
40
+ return owner
41
+ ? { owner: owner.id, age: Math.round((Date.now() / 1000 - owner.ts) * 100) / 100 }
42
+ : null
43
+ },
44
+
45
+ async wait(o = {}) {
46
+ const { leaseWaitPollMs: pollMs, leaseWaitTimeoutMs: defaultTimeoutMs } = tuning()
47
+ const deadline = Date.now() + (o.timeoutMs || defaultTimeoutMs)
48
+ while (true) {
49
+ if (this.isLive()) return this.status()
50
+ if (Date.now() >= deadline) {
51
+ const hint = o.openHint ? `(打开 ${o.openHint})` : ''
52
+ const panel = o.panelHint || '编辑器面板'
53
+ throw new Error(`${panel}尚未连接${hint}。页面加载后会自动连接,无需其他操作。`)
54
+ }
55
+ await new Promise((resolve) => setTimeout(resolve, pollMs))
56
+ }
57
+ },
58
+ }
59
+ }
60
+
61
+ /**
62
+ * 编辑器端自动挂接循环。
63
+ * 首次 claim 强制抢占(后打开者赢),之后静默心跳。
64
+ * @param {{
65
+ * clientId: string,
66
+ * claim: (force: boolean) => Promise<boolean>,
67
+ * release?: () => void,
68
+ * onActive?: () => void,
69
+ * onStandby?: () => void,
70
+ * retryMs?: number,
71
+ * heartbeatMs?: number,
72
+ * setInterval?: (cb: () => void) => any,
73
+ * clearInterval?: (handle: any) => void
74
+ * }} o
75
+ */
76
+ export function startAutoAttach(o) {
77
+ if (!o || !o.clientId) throw new Error('startAutoAttach: clientId 必填')
78
+ if (typeof o.claim !== 'function') throw new Error('startAutoAttach: claim 必须是函数')
79
+
80
+ const retryMs = o.retryMs || 1000
81
+ const heartbeatMs = o.heartbeatMs || DEFAULT_HEARTBEAT * 1000
82
+ const setI = o.setInterval || ((cb) => setInterval(cb, heartbeatMs))
83
+ const clearI = o.clearInterval || ((handle) => clearInterval(handle))
84
+
85
+ let active = false
86
+ let heartbeat = null
87
+ let disposed = false
88
+
89
+ async function tryClaim(force) {
90
+ try {
91
+ return await o.claim(force)
92
+ } catch {
93
+ return false
94
+ }
95
+ }
96
+
97
+ function goActive() {
98
+ if (active) return
99
+ active = true
100
+ try { o.onActive && o.onActive() } catch { /* 用户回调失败不阻塞挂接 */ }
101
+ heartbeat = setI(async () => {
102
+ if (disposed) return
103
+ const ok = await tryClaim(false)
104
+ if (!ok) goStandby()
105
+ })
106
+ }
107
+
108
+ function goStandby() {
109
+ if (!active) return
110
+ active = false
111
+ if (heartbeat != null) {
112
+ clearI(heartbeat)
113
+ heartbeat = null
114
+ }
115
+ try { o.onStandby && o.onStandby() } catch { /* 静默 */ }
116
+ }
117
+
118
+ ;(async () => {
119
+ let first = true
120
+ while (!disposed) {
121
+ const ok = await tryClaim(first)
122
+ first = false
123
+ if (ok) {
124
+ goActive()
125
+ return
126
+ }
127
+ await new Promise((resolve) => setTimeout(resolve, retryMs))
128
+ }
129
+ })()
130
+
131
+ return {
132
+ get active() { return active },
133
+ dispose() {
134
+ disposed = true
135
+ goStandby()
136
+ try { o.release && o.release() } catch { /* 释放失败不阻塞退出 */ }
137
+ },
138
+ }
139
+ }
@@ -0,0 +1,45 @@
1
+ /** 公共服务 API 契约:插件之间只通过这份描述判断兼容性。 */
2
+
3
+ /**
4
+ * @param {string} name 服务名(ctx.<name>)
5
+ * @param {string} version API 版本(semver;major 变化 = 不兼容)
6
+ * @param {string[]} capabilities 能力标签
7
+ */
8
+ export function createServiceApi(name, version = '1.0.0', capabilities = []) {
9
+ if (!name) throw new Error('createServiceApi 需要 name')
10
+ return Object.freeze({
11
+ name,
12
+ version,
13
+ capabilities: Object.freeze([...capabilities]),
14
+ })
15
+ }
16
+
17
+ /**
18
+ * 断言一个已注入的服务对象满足消费者要求。
19
+ * 缺失服务或 major 不一致时抛出明确错误,避免“看起来能跑”的静默不兼容。
20
+ * @param {object} service
21
+ * @param {{ name: string, major?: number|string, version?: string }} expected
22
+ */
23
+ export function assertServiceApi(service, expected = {}) {
24
+ const name = expected.name
25
+ if (!name) throw new Error('assertServiceApi 需要 expected.name')
26
+ const major = String(expected.major ?? String(expected.version || '1').split('.')[0])
27
+ if (!service) throw new Error(`缺少公共服务: ctx.${name}`)
28
+ const api = service.api
29
+ if (!api || typeof api !== 'object') {
30
+ throw new Error(`服务 ctx.${name} 没有声明 api 契约;请升级提供方插件`)
31
+ }
32
+ if (api.name !== name) {
33
+ throw new Error(`服务 ctx.${name} 的 api.name=${api.name},与消费者期望的 ${name} 不一致`)
34
+ }
35
+ const gotMajor = String(api.version || '').split('.')[0]
36
+ if (gotMajor !== major) {
37
+ throw new Error(`服务 ctx.${name} API major=${gotMajor},消费者要求 major=${major}(提供方版本 ${api.version})`)
38
+ }
39
+ return api
40
+ }
41
+
42
+ export function serviceApiSummary(service) {
43
+ const api = service?.api
44
+ return api ? { name: api.name, version: api.version, capabilities: [...(api.capabilities || [])] } : null
45
+ }
@@ -0,0 +1,113 @@
1
+ /** 本机插件 HTTP 传输:安全响应头、body 上限、查询解析、loopback 监听。 */
2
+ import http from 'node:http'
3
+ import { tuning } from '../tuning.mjs'
4
+
5
+ export const SECURITY_HEADERS = {
6
+ 'x-content-type-options': 'nosniff',
7
+ 'referrer-policy': 'no-referrer',
8
+ 'cache-control': 'no-store, no-cache, must-revalidate',
9
+ }
10
+
11
+ /** 客户端已断开时放弃写入:长请求(截图/长轮询)在 handler 完成前客户端超时
12
+ * 断连是常态,写已销毁的 socket 会触发无人监听的 'error' 事件打崩进程。 */
13
+ function resDead(res) {
14
+ return res.destroyed || res.writableEnded
15
+ }
16
+
17
+ export function send(req, res, code, obj, extraHeaders = {}) {
18
+ if (resDead(res)) return
19
+ const body = obj === undefined ? '' : JSON.stringify(obj)
20
+ try {
21
+ res.writeHead(code, {
22
+ 'content-type': 'application/json',
23
+ 'content-length': Buffer.byteLength(body),
24
+ ...SECURITY_HEADERS,
25
+ ...extraHeaders,
26
+ })
27
+ res.end(req.method === 'HEAD' ? undefined : body)
28
+ } catch { /* socket 已死:响应无人接收,静默放弃 */ }
29
+ }
30
+
31
+ export function sendText(req, res, code, text, contentType = 'text/plain; charset=utf-8', extraHeaders = {}) {
32
+ if (resDead(res)) return
33
+ const body = text === undefined || text === null ? '' : String(text)
34
+ try {
35
+ res.writeHead(code, {
36
+ 'content-type': contentType,
37
+ 'content-length': Buffer.byteLength(body),
38
+ ...SECURITY_HEADERS,
39
+ ...extraHeaders,
40
+ })
41
+ res.end(req.method === 'HEAD' ? undefined : body)
42
+ } catch { /* socket 已死:响应无人接收,静默放弃 */ }
43
+ }
44
+
45
+ function bodyError(code, message) {
46
+ const error = new Error(message)
47
+ error.code = code
48
+ return error
49
+ }
50
+
51
+ export function readBody(req, limit = 10 * 1024 * 1024) {
52
+ return new Promise((resolve, reject) => {
53
+ let size = 0
54
+ const chunks = []
55
+ let settled = false
56
+ const fail = (error) => {
57
+ if (settled) return
58
+ settled = true
59
+ reject(error)
60
+ }
61
+ req.on('data', (chunk) => {
62
+ if (settled) return
63
+ size += chunk.length
64
+ if (size > limit) {
65
+ /* 先让路由回 413;立即 destroy 会让客户端只看到 connection reset。 */
66
+ fail(bodyError('BODY_TOO_LARGE', 'body too large'))
67
+ req.resume()
68
+ return
69
+ }
70
+ chunks.push(chunk)
71
+ })
72
+ req.on('end', () => {
73
+ if (settled) return
74
+ settled = true
75
+ const raw = Buffer.concat(chunks).toString('utf8')
76
+ if (!raw) return resolve({})
77
+ try { resolve(JSON.parse(raw)) } catch { reject(bodyError('BAD_JSON', 'bad json')) }
78
+ })
79
+ req.on('error', (error) => fail(error))
80
+ /* 客户端中途断连且未触发 error/aborted 时(如 curl -m 超时),close 兜底,
81
+ 否则 promise 永远 pending,handler 泄漏。 */
82
+ req.on('close', () => {
83
+ if (!req.readableEnded) fail(bodyError('CLIENT_ABORTED', 'client aborted'))
84
+ })
85
+ })
86
+ }
87
+
88
+ export function intQ(url, name) {
89
+ const value = parseInt(url.searchParams.get(name) || '0', 10)
90
+ return Number.isFinite(value) && value >= 0 ? value : 0
91
+ }
92
+
93
+ export function listen(port, opts = {}) {
94
+ const defaults = tuning()
95
+ const {
96
+ host = '127.0.0.1',
97
+ requestTimeoutMs = defaults.requestTimeoutMs,
98
+ headersTimeoutMs = defaults.headersTimeoutMs,
99
+ keepAliveTimeoutMs = defaults.keepAliveTimeoutMs,
100
+ handler,
101
+ } = opts
102
+ return new Promise((resolve, reject) => {
103
+ const server = handler ? http.createServer(handler) : http.createServer()
104
+ server.requestTimeout = requestTimeoutMs
105
+ server.headersTimeout = headersTimeoutMs
106
+ server.keepAliveTimeout = keepAliveTimeoutMs
107
+ server.on('clientError', (error, socket) => {
108
+ if (socket.writable) socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
109
+ })
110
+ server.on('error', reject)
111
+ server.listen(port, host, () => resolve(server))
112
+ })
113
+ }