@capyclaw/browser-workbench 0.0.0-stage → 0.1.19
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/README.md +88 -2
- package/contract/browser-contract.json +1349 -0
- package/demo/form.html +112 -0
- package/lib/host.mjs +1 -0
- package/node_modules/@capyclaw/asset-service/README.md +48 -0
- package/node_modules/@capyclaw/asset-service/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/asset-service/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/asset-service/lib/host.mjs +14 -0
- package/node_modules/@capyclaw/asset-service/package.json +59 -0
- package/node_modules/@capyclaw/asset-service/src/index.mjs +304 -0
- package/node_modules/@capyclaw/document-workbench/README.md +125 -0
- package/node_modules/@capyclaw/document-workbench/package.json +44 -0
- package/node_modules/@capyclaw/document-workbench/src/bridge/index.mjs +321 -0
- package/node_modules/@capyclaw/document-workbench/src/client/index.mjs +625 -0
- package/node_modules/@capyclaw/document-workbench/src/client/screenshot.mjs +98 -0
- package/node_modules/@capyclaw/document-workbench/src/index.mjs +9 -0
- package/node_modules/@capyclaw/document-workbench/src/model/audit.mjs +101 -0
- package/node_modules/@capyclaw/document-workbench/src/model/conformance.mjs +92 -0
- package/node_modules/@capyclaw/document-workbench/src/model/ids.mjs +56 -0
- package/node_modules/@capyclaw/document-workbench/src/model/index.mjs +18 -0
- package/node_modules/@capyclaw/document-workbench/src/model/locate.mjs +118 -0
- package/node_modules/@capyclaw/document-workbench/src/model/manifest.mjs +148 -0
- package/node_modules/@capyclaw/document-workbench/src/model/ops.mjs +160 -0
- package/node_modules/@capyclaw/document-workbench/src/model/validate.mjs +72 -0
- package/node_modules/@capyclaw/document-workbench/src/ops/index.mjs +93 -0
- package/node_modules/@capyclaw/document-workbench/src/session/context.mjs +103 -0
- package/node_modules/@capyclaw/document-workbench/src/session/index.mjs +394 -0
- package/node_modules/@capyclaw/document-workbench/src/session/lease.mjs +105 -0
- package/node_modules/@capyclaw/document-workbench/src/session/mode.mjs +80 -0
- package/node_modules/@capyclaw/document-workbench/src/session/sanitize.mjs +107 -0
- package/node_modules/@capyclaw/document-workbench/src/session/state.mjs +159 -0
- package/node_modules/@capyclaw/document-workbench/src/session/watch.mjs +63 -0
- package/node_modules/@capyclaw/document-workbench/src/store/file-backend.mjs +158 -0
- package/node_modules/@capyclaw/document-workbench/src/testing/index.mjs +75 -0
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +58 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/node_modules/@capyclaw/service-host/README.md +86 -0
- package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
- package/node_modules/@capyclaw/service-host/package.json +60 -0
- package/node_modules/@capyclaw/service-host/src/index.mjs +571 -0
- package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
- package/node_modules/@capyclaw/tool-host/README.md +56 -0
- package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
- package/node_modules/@capyclaw/tool-host/lib/host.mjs +16 -0
- package/node_modules/@capyclaw/tool-host/package.json +59 -0
- package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
- package/node_modules/@capyclaw/tool-host/src/index.mjs +416 -0
- package/package.json +77 -4
- package/plugin.mjs +1 -0
- package/server/constants.mjs +16 -0
- package/server/contract-snapshots.mjs +81 -0
- package/server/contract.mjs +24 -0
- package/server/embedded-host.mjs +247 -0
- package/server/engine.mjs +2466 -0
- package/server/governor.mjs +189 -0
- package/server/http-utils.mjs +2 -0
- package/server/human.mjs +628 -0
- package/server/infra/http.mjs +2 -0
- package/server/infra/tuning.mjs +2 -0
- package/server/input.mjs +154 -0
- package/server/login-vault.mjs +109 -0
- package/server/mcp/handler.mjs +2 -0
- package/server/mcp/instructions.mjs +31 -0
- package/server/orphans.mjs +163 -0
- package/server/relay.mjs +198 -0
- package/server/routes/api.mjs +233 -0
- package/server/routes/assets.mjs +2 -0
- package/server/routes/mcp.mjs +17 -0
- package/server/routes/workbench.mjs +33 -0
- package/server/session-engines.mjs +223 -0
- package/server/shared/SHARED_MANIFEST.json +70 -0
- package/server/shared/asset-service.mjs +2 -0
- package/server/shared/editor-host.mjs +2 -0
- package/server/shared/kit/editor/lease.mjs +2 -0
- package/server/shared/kit/service/api.mjs +2 -0
- package/server/shared/kit/service/http.mjs +2 -0
- package/server/shared/kit/service/mcp-http.mjs +2 -0
- package/server/shared/kit/tools/validate.mjs +2 -0
- package/server/shared/kit/tuning.mjs +2 -0
- package/server/shared/kit/util/fs-lock.mjs +2 -0
- package/server/shared/service-host.mjs +2 -0
- package/server/shared/tool-host.mjs +2 -0
- package/server/shared/tuning.mjs +2 -0
- package/server/tools/capabilities/contract.mjs +55 -0
- package/server/tools/capabilities/evaluate.mjs +36 -0
- package/server/tools/capabilities/index.mjs +26 -0
- package/server/tools/capabilities/interaction.mjs +215 -0
- package/server/tools/capabilities/navigation.mjs +35 -0
- package/server/tools/capabilities/screenshot.mjs +50 -0
- package/server/tools/capabilities/session.mjs +81 -0
- package/server/tools/capabilities/snapshot.mjs +30 -0
- package/server/tools/capabilities/tabs.mjs +35 -0
- package/server/tools/index.mjs +12 -0
- package/server/tools/kernel/define.mjs +5 -0
- package/server/tools/kernel/output.mjs +30 -0
- package/server/tools/kernel/ports.mjs +59 -0
- package/server/tools/kernel/registry.mjs +17 -0
- package/server/tools.mjs +3 -0
- package/server/workbench-framework.mjs +305 -0
- package/ui/app.js +447 -0
- package/ui/index.html +46 -0
- package/ui/style.css +144 -0
package/demo/form.html
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="zh-CN">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>演示表单 · 离线练习页</title>
|
|
7
|
+
<style>
|
|
8
|
+
body { font: 15px/1.7 "Segoe UI", "Microsoft YaHei", sans-serif; max-width: 640px; margin: 32px auto; padding: 0 16px; color: #222; }
|
|
9
|
+
fieldset { border: 1px solid #ccd3e0; border-radius: 10px; margin-bottom: 20px; }
|
|
10
|
+
legend { padding: 0 8px; font-weight: 600; }
|
|
11
|
+
label { display: block; margin: 10px 0 4px; font-weight: 600; }
|
|
12
|
+
input[type="text"], input[type="password"], select, textarea {
|
|
13
|
+
width: 100%; padding: 8px 10px; border: 1px solid #ccd3e0; border-radius: 6px; font: inherit;
|
|
14
|
+
}
|
|
15
|
+
.row { display: flex; gap: 16px; align-items: center; margin: 10px 0; }
|
|
16
|
+
button { padding: 9px 18px; border-radius: 6px; border: 1px solid #3a6ee8; background: #3a6ee8; color: #fff; cursor: pointer; font-size: 15px; }
|
|
17
|
+
button.ghost { background: #fff; color: #3a6ee8; }
|
|
18
|
+
#results { background: #f4f7fd; border-radius: 8px; padding: 10px 14px; min-height: 48px; }
|
|
19
|
+
#results li { margin: 4px 0; }
|
|
20
|
+
#count { font-weight: 700; }
|
|
21
|
+
input[type="range"] { width: 60%; vertical-align: middle; }
|
|
22
|
+
.fake-btn { display: inline-block; padding: 9px 18px; border-radius: 6px; background: #eef2fc; color: #27448f; border: 1px dashed #7f9ce0; cursor: pointer; user-select: none; }
|
|
23
|
+
</style>
|
|
24
|
+
</head>
|
|
25
|
+
<body>
|
|
26
|
+
<h1>演示表单</h1>
|
|
27
|
+
<p>内置离线练习页:不依赖外网,供 AI 工具链(browser_navigate → browser_snapshot → browser_fill / browser_select / browser_click)演示与 e2e 冒烟使用。</p>
|
|
28
|
+
|
|
29
|
+
<form id="demo-form">
|
|
30
|
+
<fieldset>
|
|
31
|
+
<legend>注册信息</legend>
|
|
32
|
+
<label for="username">用户名</label>
|
|
33
|
+
<input type="text" id="username" name="username" placeholder="请输入用户名">
|
|
34
|
+
|
|
35
|
+
<label for="password">密码</label>
|
|
36
|
+
<input type="password" id="password" name="password" placeholder="密码会被快照掩码显示">
|
|
37
|
+
|
|
38
|
+
<label for="city">所在城市</label>
|
|
39
|
+
<select id="city" name="city">
|
|
40
|
+
<option value="">— 请选择 —</option>
|
|
41
|
+
<option value="beijing">北京</option>
|
|
42
|
+
<option value="shanghai">上海</option>
|
|
43
|
+
<option value="shenzhen">深圳</option>
|
|
44
|
+
</select>
|
|
45
|
+
|
|
46
|
+
<div class="row">
|
|
47
|
+
<label style="margin:0"><input type="checkbox" id="agree" name="agree"> 我已阅读并同意服务条款</label>
|
|
48
|
+
</div>
|
|
49
|
+
|
|
50
|
+
<label for="note">备注</label>
|
|
51
|
+
<textarea id="note" name="note" rows="3" placeholder="选填"></textarea>
|
|
52
|
+
|
|
53
|
+
<div class="row">
|
|
54
|
+
<button type="submit" id="submit">提交注册</button>
|
|
55
|
+
<button type="button" id="counter" class="ghost">点我计数:<span id="count">0</span></button>
|
|
56
|
+
</div>
|
|
57
|
+
</fieldset>
|
|
58
|
+
|
|
59
|
+
<fieldset>
|
|
60
|
+
<legend>进阶:拖拽 / 无 role 按钮</legend>
|
|
61
|
+
<label for="slider">滑块(用 browser_drag 拖到最右)</label>
|
|
62
|
+
<div class="row">
|
|
63
|
+
<input type="range" id="slider" name="slider" min="0" max="100" value="0" step="1">
|
|
64
|
+
<output id="slider-out">0</output>
|
|
65
|
+
</div>
|
|
66
|
+
|
|
67
|
+
<label>下面这个「下一步」是普通 div,没有 role/tabindex,快照里不会有 ref</label>
|
|
68
|
+
<div class="row">
|
|
69
|
+
<div id="fake-next" class="fake-btn">下一步</div>
|
|
70
|
+
</div>
|
|
71
|
+
</fieldset>
|
|
72
|
+
</form>
|
|
73
|
+
|
|
74
|
+
<h2>操作结果</h2>
|
|
75
|
+
<ul id="results" role="status">
|
|
76
|
+
<li>(还没有操作)</li>
|
|
77
|
+
</ul>
|
|
78
|
+
|
|
79
|
+
<script>
|
|
80
|
+
var results = document.getElementById('results')
|
|
81
|
+
var count = 0
|
|
82
|
+
function log(text) {
|
|
83
|
+
if (results.firstChild && results.firstChild.textContent === '(还没有操作)') results.innerHTML = ''
|
|
84
|
+
var li = document.createElement('li')
|
|
85
|
+
li.textContent = new Date().toLocaleTimeString() + ' — ' + text
|
|
86
|
+
results.insertBefore(li, results.firstChild)
|
|
87
|
+
}
|
|
88
|
+
document.getElementById('demo-form').addEventListener('submit', function (e) {
|
|
89
|
+
e.preventDefault()
|
|
90
|
+
log('已提交注册:username=' + (document.getElementById('username').value || '(空)') +
|
|
91
|
+
',city=' + (document.getElementById('city').value || '(未选)') +
|
|
92
|
+
',agree=' + (document.getElementById('agree').checked ? 'on' : 'off'))
|
|
93
|
+
})
|
|
94
|
+
document.getElementById('counter').addEventListener('click', function () {
|
|
95
|
+
count += 1
|
|
96
|
+
document.getElementById('count').textContent = count
|
|
97
|
+
log('计数按钮第 ' + count + ' 次被点击')
|
|
98
|
+
})
|
|
99
|
+
var slider = document.getElementById('slider')
|
|
100
|
+
var sliderOut = document.getElementById('slider-out')
|
|
101
|
+
slider.addEventListener('input', function () {
|
|
102
|
+
sliderOut.textContent = slider.value
|
|
103
|
+
})
|
|
104
|
+
slider.addEventListener('change', function () {
|
|
105
|
+
log('滑块拖到 ' + slider.value + '(' + (Number(slider.value) >= 100 ? '到最右' : '未到最右') + ')')
|
|
106
|
+
})
|
|
107
|
+
document.getElementById('fake-next').addEventListener('click', function () {
|
|
108
|
+
log('「下一步」(div 假按钮)被点击')
|
|
109
|
+
})
|
|
110
|
+
</script>
|
|
111
|
+
</body>
|
|
112
|
+
</html>
|
package/lib/host.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { name, apply } from '../server/embedded-host.mjs'
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# @capyclaw/asset-service
|
|
2
|
+
|
|
3
|
+
DSH 公共资产插件。功能插件通过 `ctx.assets` 获得统一的 sha256 对象仓库和 `/assets` 路由。
|
|
4
|
+
|
|
5
|
+
## 使用
|
|
6
|
+
|
|
7
|
+
```js
|
|
8
|
+
export const inject = ['assets']
|
|
9
|
+
|
|
10
|
+
export function apply(ctx) {
|
|
11
|
+
const app = ctx.serviceHost.createApp({ id: 'my-plugin' })
|
|
12
|
+
app.use(ctx.assets.routes())
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// 或在插件内部写入
|
|
16
|
+
const asset = await ctx.assets.put(buffer, 'image/png')
|
|
17
|
+
// { id, key, url: '/assets/<sha256>', size, contentType }
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
独立运行或测试:
|
|
21
|
+
|
|
22
|
+
```js
|
|
23
|
+
import { createFileAssetStore, createAssetRoutes } from '@capyclaw/asset-service/src'
|
|
24
|
+
const store = createFileAssetStore({ dir: './assets' })
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## 路由归属
|
|
28
|
+
|
|
29
|
+
多个插件共用一个 service-host app 时,用 `ctx.assets.mount(app)` 只挂一次 `/assets`:
|
|
30
|
+
|
|
31
|
+
```js
|
|
32
|
+
ctx.assets.mount(app, { store: assetStore })
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
重复 mount 会被忽略;不要再手写 `app.use(ctx.assets.routes())`。
|
|
36
|
+
|
|
37
|
+
## 提供什么
|
|
38
|
+
|
|
39
|
+
- `createWorkspaceAssetStore({ storeClient, workId })`:资产归当前 work
|
|
40
|
+
- `createFileAssetStore({ dir })`:本地目录后端
|
|
41
|
+
- `createAssetRoutes({ assetStore, basePath })`:GET/HEAD `/assets/<id>`、POST `<basePath>/assets`
|
|
42
|
+
- `ctx.assets.put/get`:默认 store 快捷方法
|
|
43
|
+
|
|
44
|
+
## 契约
|
|
45
|
+
|
|
46
|
+
- 资产按 sha256 去重,不可变
|
|
47
|
+
- url 固定为 `/assets/<id>`,可长期缓存
|
|
48
|
+
- 内容类型由上传方声明,读取时原样返回
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "../capyclaw-suite-kit/suite.schema.json",
|
|
3
|
+
"name": "dsh-asset-service-suite",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"title": "Asset Service",
|
|
6
|
+
"description": "通用对象资产:sha256 仓库、/assets 路由、上传。",
|
|
7
|
+
"packages": {
|
|
8
|
+
"@capyclaw/asset-service": {
|
|
9
|
+
"role": "provider",
|
|
10
|
+
"version": "^0.1.4",
|
|
11
|
+
"path": ".",
|
|
12
|
+
"provides": {
|
|
13
|
+
"services": [
|
|
14
|
+
"assets"
|
|
15
|
+
],
|
|
16
|
+
"capabilities": {
|
|
17
|
+
"assets.store": "1.0.0"
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"rows": [
|
|
23
|
+
{
|
|
24
|
+
"id": "asset-service",
|
|
25
|
+
"name": "@capyclaw/asset-service"
|
|
26
|
+
}
|
|
27
|
+
],
|
|
28
|
+
"checks": []
|
|
29
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** @capyclaw/asset-service 插件:向同进程插件提供 ctx.assets。 */
|
|
2
|
+
import { defineDriver } from '@capyclaw/foundation/abi'
|
|
3
|
+
import { createAssetHost } from '../src/index.mjs'
|
|
4
|
+
|
|
5
|
+
export const { name, inject, apply } = defineDriver({
|
|
6
|
+
name: 'asset-service',
|
|
7
|
+
service: 'assets',
|
|
8
|
+
apply(ctx, config = {}) {
|
|
9
|
+
const service = createAssetHost(config)
|
|
10
|
+
const dispose = ctx.provide('assets', service)
|
|
11
|
+
console.log('[asset-service] ready')
|
|
12
|
+
return () => { if (typeof dispose === 'function') dispose() }
|
|
13
|
+
},
|
|
14
|
+
})
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@capyclaw/asset-service",
|
|
3
|
+
"version": "0.1.4",
|
|
4
|
+
"description": "DSH 公共资产插件:sha256 对象仓库、/assets 路由、base64 上传与 content-type,向插件提供 ctx.assets。",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./lib/host.mjs",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./lib/host.mjs",
|
|
9
|
+
"./src": "./src/index.mjs",
|
|
10
|
+
"./package.json": "./package.json"
|
|
11
|
+
},
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=18",
|
|
14
|
+
"dsh": "^0.2.0-rc.2"
|
|
15
|
+
},
|
|
16
|
+
"publishConfig": {
|
|
17
|
+
"access": "public"
|
|
18
|
+
},
|
|
19
|
+
"dsh": {
|
|
20
|
+
"bundle": {
|
|
21
|
+
"patch": "./cordis.patch.yml"
|
|
22
|
+
},
|
|
23
|
+
"suite": "./dsh-suite.json",
|
|
24
|
+
"apiVersion": "1.0.0",
|
|
25
|
+
"category": "service",
|
|
26
|
+
"platform": "both",
|
|
27
|
+
"driver": {
|
|
28
|
+
"service": "assets"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"meta": {
|
|
32
|
+
"title": "公共资产服务",
|
|
33
|
+
"description": "sha256 对象仓库、/assets 路由、base64 上传与 content-type,向插件提供 ctx.assets"
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"lib/",
|
|
37
|
+
"src/",
|
|
38
|
+
"cordis.patch.yml",
|
|
39
|
+
"dsh-suite.json",
|
|
40
|
+
"README.md"
|
|
41
|
+
],
|
|
42
|
+
"license": "MIT",
|
|
43
|
+
"scripts": {
|
|
44
|
+
"test": "node --test test/*.test.mjs"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"@capyclaw/plugin-kit": "^0.2.0",
|
|
48
|
+
"@capyclaw/foundation": "^0.1.1"
|
|
49
|
+
},
|
|
50
|
+
"repository": {
|
|
51
|
+
"type": "git",
|
|
52
|
+
"url": "git+https://github.com/Maple496/capyclaw.git",
|
|
53
|
+
"directory": "C/packages/capyclaw-asset-service"
|
|
54
|
+
},
|
|
55
|
+
"bugs": {
|
|
56
|
+
"url": "https://github.com/Maple496/capyclaw/issues"
|
|
57
|
+
},
|
|
58
|
+
"homepage": "https://github.com/Maple496/capyclaw/tree/main/C/packages/capyclaw-asset-service#readme"
|
|
59
|
+
}
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @capyclaw/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
|
+
/** 删除单个对象(data + meta)。内容寻址仓库此前只增不删,磁盘无界增长。 */
|
|
111
|
+
async delete(id) {
|
|
112
|
+
if (!validId(id)) return false
|
|
113
|
+
const file = path.join(dir, path.basename(String(id)))
|
|
114
|
+
let existed = false
|
|
115
|
+
try {
|
|
116
|
+
existed = fs.existsSync(file)
|
|
117
|
+
fs.rmSync(file, { force: true })
|
|
118
|
+
fs.rmSync(file + '.meta.json', { force: true })
|
|
119
|
+
} catch { /* 尽力删除 */ }
|
|
120
|
+
return existed
|
|
121
|
+
},
|
|
122
|
+
/**
|
|
123
|
+
* 垃圾回收:清崩溃残留的孤儿 .tmp、按 mtime 龄淘汰、按总量 LRU 淘汰。
|
|
124
|
+
* keepIds 里的对象(仍被引用)永不删。返回 {removed, freedBytes, orphanTmpRemoved}。
|
|
125
|
+
*/
|
|
126
|
+
async gc({ maxAgeMs = 0, maxBytes = 0, keepIds = [] } = {}) {
|
|
127
|
+
const keep = new Set(keepIds)
|
|
128
|
+
const now = Date.now()
|
|
129
|
+
let removed = 0
|
|
130
|
+
let freedBytes = 0
|
|
131
|
+
let orphanTmpRemoved = 0
|
|
132
|
+
let names
|
|
133
|
+
try { names = fs.readdirSync(dir) } catch { return { removed, freedBytes, orphanTmpRemoved } }
|
|
134
|
+
/* 孤儿 tmp:put 中途崩溃留下的半成品,超过 1h 宽限才清(避免误删在途写入)。 */
|
|
135
|
+
for (const name of names) {
|
|
136
|
+
if (!name.includes('.tmp-')) continue
|
|
137
|
+
const full = path.join(dir, name)
|
|
138
|
+
try {
|
|
139
|
+
const st = fs.statSync(full)
|
|
140
|
+
if (now - st.mtimeMs > 3600000) { fs.rmSync(full, { force: true }); orphanTmpRemoved += 1 }
|
|
141
|
+
} catch { /* 忽略 */ }
|
|
142
|
+
}
|
|
143
|
+
const objects = []
|
|
144
|
+
for (const name of fs.readdirSync(dir)) {
|
|
145
|
+
if (!validId(name)) continue
|
|
146
|
+
const full = path.join(dir, name)
|
|
147
|
+
try { const st = fs.statSync(full); objects.push({ id: name, full, size: st.size, mtime: st.mtimeMs }) } catch { /* 忽略 */ }
|
|
148
|
+
}
|
|
149
|
+
const removeObject = (o) => {
|
|
150
|
+
try {
|
|
151
|
+
fs.rmSync(o.full, { force: true })
|
|
152
|
+
fs.rmSync(o.full + '.meta.json', { force: true })
|
|
153
|
+
removed += 1
|
|
154
|
+
freedBytes += o.size
|
|
155
|
+
} catch { /* 忽略 */ }
|
|
156
|
+
}
|
|
157
|
+
if (maxAgeMs > 0) {
|
|
158
|
+
for (const o of objects) {
|
|
159
|
+
if (!keep.has(o.id) && now - o.mtime > maxAgeMs) removeObject(o)
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (maxBytes > 0) {
|
|
163
|
+
const alive = objects.filter((o) => fs.existsSync(o.full)).sort((a, b) => a.mtime - b.mtime)
|
|
164
|
+
let total = alive.reduce((sum, o) => sum + o.size, 0)
|
|
165
|
+
for (const o of alive) {
|
|
166
|
+
if (total <= maxBytes) break
|
|
167
|
+
if (keep.has(o.id)) continue
|
|
168
|
+
removeObject(o)
|
|
169
|
+
total -= o.size
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return { removed, freedBytes, orphanTmpRemoved }
|
|
173
|
+
},
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** 防止 text/html / svg 在 loopback 同源执行脚本;图片仍按原 MIME 内联。
|
|
178
|
+
* 安全类型保留原始参数(charset 等),不再一刀切剥掉——否则文本资产 charset 丢失。 */
|
|
179
|
+
function safeContentType(type) {
|
|
180
|
+
const raw = String(type || '').replace(/[\r\n]/g, '').trim()
|
|
181
|
+
const base = raw.split(';')[0].trim().toLowerCase() || 'application/octet-stream'
|
|
182
|
+
if (base === 'text/html' || base === 'application/xhtml+xml' || base === 'image/svg+xml') {
|
|
183
|
+
return 'text/plain; charset=utf-8'
|
|
184
|
+
}
|
|
185
|
+
return raw || 'application/octet-stream'
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* service-host 兼容的资产路由。
|
|
190
|
+
* GET/HEAD `/assets/<id>`(同时兼容 `<basePath>/assets/<id>`);
|
|
191
|
+
* POST `/assets` 或 `<basePath>/assets`(JSON: { data: base64, contentType })。
|
|
192
|
+
*/
|
|
193
|
+
export function createAssetRoutes({ assetStore, basePath = '', maxUploadBytes = 10 * 1024 * 1024 } = {}) {
|
|
194
|
+
const prefix = basePath === '/' ? '' : String(basePath || '').replace(/\/+$/, '')
|
|
195
|
+
const getPrefixes = ['/assets/', prefix ? `${prefix}/assets/` : null].filter(Boolean)
|
|
196
|
+
const postPaths = new Set(['/assets', prefix ? `${prefix}/assets` : null].filter(Boolean))
|
|
197
|
+
return async function assetRoutes(req, res, u) {
|
|
198
|
+
const p = u.pathname
|
|
199
|
+
if (req.method === 'GET' || req.method === 'HEAD') {
|
|
200
|
+
const getPrefix = getPrefixes.find((candidate) => p.startsWith(candidate))
|
|
201
|
+
if (getPrefix) {
|
|
202
|
+
if (!assetStore) { send(req, res, 404, { error: 'asset store unavailable' }); return true }
|
|
203
|
+
const id = decodeURIComponent(p.slice(getPrefix.length))
|
|
204
|
+
if (!validId(id)) { send(req, res, 404, { error: 'asset not found' }); return true }
|
|
205
|
+
const asset = assetStore.get(id)
|
|
206
|
+
if (!asset) { send(req, res, 404, { error: 'asset not found' }); return true }
|
|
207
|
+
res.writeHead(200, {
|
|
208
|
+
'content-type': safeContentType(asset.contentType),
|
|
209
|
+
'content-length': asset.data.length,
|
|
210
|
+
'cache-control': 'public, max-age=31536000, immutable',
|
|
211
|
+
'x-content-type-options': 'nosniff',
|
|
212
|
+
'referrer-policy': 'no-referrer',
|
|
213
|
+
})
|
|
214
|
+
res.end(req.method === 'HEAD' ? undefined : asset.data)
|
|
215
|
+
return true
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (postPaths.has(p) && req.method === 'POST') {
|
|
219
|
+
if (!assetStore) { send(req, res, 503, { error: 'asset store unavailable' }); return true }
|
|
220
|
+
let body
|
|
221
|
+
try { body = await readBody(req, maxUploadBytes) } catch (error) {
|
|
222
|
+
const status = error?.code === 'BODY_TOO_LARGE' ? 413 : 400
|
|
223
|
+
send(req, res, status, { error: String(error.message || error) })
|
|
224
|
+
return true
|
|
225
|
+
}
|
|
226
|
+
if (!body || typeof body.data !== 'string' || !body.data) {
|
|
227
|
+
send(req, res, 400, { error: '缺少图片数据' })
|
|
228
|
+
return true
|
|
229
|
+
}
|
|
230
|
+
const buffer = Buffer.from(body.data, 'base64')
|
|
231
|
+
/* 严格 base64:非法字符 / 错误填充 / 非规范编码一律 400,不再宽松解码把损坏
|
|
232
|
+
* 字节静默入库(B 轴 P0-7)。round-trip 比对同时挡住非规范填充位。 */
|
|
233
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(body.data) || body.data.length % 4 !== 0 || buffer.toString('base64') !== body.data) {
|
|
234
|
+
send(req, res, 400, { error: '图片数据不是合法 base64' })
|
|
235
|
+
return true
|
|
236
|
+
}
|
|
237
|
+
if (!buffer.length) { send(req, res, 400, { error: '图片数据为空' }); return true }
|
|
238
|
+
const asset = await assetStore.put(buffer, body.contentType || 'application/octet-stream')
|
|
239
|
+
/* 回给与 GET 一致的 sanitized content-type(保留 charset、script 类转 text/plain)。 */
|
|
240
|
+
send(req, res, 200, { ok: true, ...asset, contentType: safeContentType(asset.contentType) })
|
|
241
|
+
return true
|
|
242
|
+
}
|
|
243
|
+
return false
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function createAssetHost(config = {}) {
|
|
248
|
+
const defaultStore = config.storeClient
|
|
249
|
+
? createWorkspaceAssetStore({ storeClient: config.storeClient, workId: config.workId })
|
|
250
|
+
: config.dir
|
|
251
|
+
? createFileAssetStore({ dir: config.dir })
|
|
252
|
+
: null
|
|
253
|
+
|
|
254
|
+
/* 能力标签如实申报:gc/delete 仅当底层 store 支持时才 advertise(file store 有,
|
|
255
|
+
* workspace store 无),避免「声明满足、活实例缺方法」。 */
|
|
256
|
+
const tags = ['workspace-store', 'file-store', 'routes', 'sha256', 'mount']
|
|
257
|
+
if (typeof defaultStore?.gc === 'function') tags.push('gc')
|
|
258
|
+
if (typeof defaultStore?.delete === 'function') tags.push('delete')
|
|
259
|
+
|
|
260
|
+
return {
|
|
261
|
+
api: createServiceApi('assets', '1.0.0', tags),
|
|
262
|
+
version: '0.1.0',
|
|
263
|
+
createStore: createWorkspaceAssetStore,
|
|
264
|
+
createFileStore: createFileAssetStore,
|
|
265
|
+
routes: createAssetRoutes,
|
|
266
|
+
store: defaultStore,
|
|
267
|
+
/**
|
|
268
|
+
* 每个 service-host app 只挂一次资产路由,避免多个插件重复争抢 /assets。
|
|
269
|
+
* @param {object} hostApp createServiceApp() 返回值
|
|
270
|
+
* @param {{ store?: object, basePath?: string }} options
|
|
271
|
+
*/
|
|
272
|
+
mount(hostApp, { store = defaultStore, basePath = '' } = {}) {
|
|
273
|
+
if (!hostApp || typeof hostApp.use !== 'function') throw new Error('assets.mount 需要 service-host app')
|
|
274
|
+
if (!store) throw new Error('assets.mount: 没有可用 store')
|
|
275
|
+
if (hostApp.__dshAssetsMounted) return () => {}
|
|
276
|
+
hostApp.__dshAssetsMounted = true
|
|
277
|
+
const unuse = hostApp.use(createAssetRoutes({ assetStore: store, basePath }))
|
|
278
|
+
let disposed = false
|
|
279
|
+
return () => {
|
|
280
|
+
if (disposed) return
|
|
281
|
+
disposed = true
|
|
282
|
+
/* 真正卸载路由;否则热重载后旧 store 仍会抢答 /assets。 */
|
|
283
|
+
if (typeof unuse === 'function') unuse()
|
|
284
|
+
hostApp.__dshAssetsMounted = false
|
|
285
|
+
}
|
|
286
|
+
},
|
|
287
|
+
async put(value, contentType) {
|
|
288
|
+
if (!defaultStore) throw new Error('asset-service: 未配置 storeClient/dir')
|
|
289
|
+
return defaultStore.put(value, contentType)
|
|
290
|
+
},
|
|
291
|
+
get(id) {
|
|
292
|
+
if (!defaultStore) throw new Error('asset-service: 未配置 storeClient/dir')
|
|
293
|
+
return defaultStore.get(id)
|
|
294
|
+
},
|
|
295
|
+
async delete(id) {
|
|
296
|
+
if (typeof defaultStore?.delete !== 'function') throw new Error('asset-service: 当前 store 不支持 delete')
|
|
297
|
+
return defaultStore.delete(id)
|
|
298
|
+
},
|
|
299
|
+
async gc(options) {
|
|
300
|
+
if (typeof defaultStore?.gc !== 'function') throw new Error('asset-service: 当前 store 不支持 gc')
|
|
301
|
+
return defaultStore.gc(options)
|
|
302
|
+
},
|
|
303
|
+
}
|
|
304
|
+
}
|