chore(hygiene): 删死代码(plugin-archive 206 行 / image-preview-derive 449 行 / isTransientApiError)+ e2e 已知红清单与对照脚本
This commit is contained in:
1 parent
0566be9b79
commit
1839a7460a
19 files changed
+135
-1092
No files matched your search
+21
-1
@@ -1,6 +1,6 @@
|
||||
# 待办清单(BACKLOG)
|
||||
|
||||
> **最后更新:2026-11-16** · **线上(正式站与测试站)均为 `v3.24.85+7df9dc4`**
|
||||
> **最后更新:2026-11-24** · **线上 `v3.26.65`(桌面端,三平台清单分别维护)**
|
||||
> (v3.24.85 = 代码体检收口:棘轮收回 Workbench 3090→2998(上限降到 3030)+ 图库索引 4 条绕过锁的写路径收口到 `mutate` + 文档数字校准。
|
||||
> 三地址一致 + `IWB_VERIFY_STRICT=1` 通过,`stable` / `stable-v3.24.85` / `stable-verified-2026-11-16` 均指向 `7df9dc4`;
|
||||
> 上一版 v3.24.84 = 生图节点连 3 条上游只出 1 个任务 ⇒ 任务身份改用 `ownerNodeId`=直接上游节点,连几条线就几个任务,`relay` 仍归约到真实文本来源(`stable-v3.24.84`→`c8b7543`);
|
||||
@@ -37,6 +37,26 @@
|
||||
|
||||
## 1. P0 — 低风险、可立即做
|
||||
|
||||
|
||||
### 1.2 预览产物按需解码(**重做**,2026-11-24 立)
|
||||
|
||||
> **为什么重做**:v3.87.x 的「W2-A 预览产物模块」当时记为「✅ 已接入构建」,但 2026-11-24 复核发现
|
||||
> `wPreviewUrlOf` 是**恒等函数**(`app.js:4825 return v`),模块从未被调用;模块 + 单测已于 **v3.26.65 删除**
|
||||
> (见 commit `docs(analysis)` 之后的清理提交,以及 `docs/standards/engineering-rulebook.md` §13.34.6 的更正)。
|
||||
> 原计划:`docs/archive/plans/opentu-parity-image-memory.md` §W2-A。
|
||||
|
||||
- **目标**:预览用图按 1024 长边解码(`createImageBitmap(blob,{resizeWidth})`),用后 `close()`,降低大图预览的峰值内存
|
||||
- **关键难点**:`wPreviewUrlOf` 是同步返回 URL 的,接线需要异步化(objectURL 生命周期 + 组件卸载释放),
|
||||
不是「加一行调用」;先量出收益(预览场景峰值内存)再动手
|
||||
- **验收**:`tests/_perf-baseline.spec.js` 的预览场景峰值下降 ≥20%,且无 objectURL 泄漏(复用现有回收计数探针)
|
||||
|
||||
### 1.3 死代码判定口径(**教训**,2026-11-24)
|
||||
|
||||
- **「有单测」不等于「有消费者」**:本轮删掉的两个模块(206 + 449 行)都有绿色单测,但生产代码零调用
|
||||
⇒ 覆盖率虚高。新增模块必须在**同一个 PR 里**接到调用点,否则不合并
|
||||
- `deadTokens`(32 个)**不要按名字批量删**:其中 `--iwb-plugin-*` 13 个是插件主题契约、`--fs-*`/`--sp-*`/`--rd-*`/`--tr-*` 是 legacy 别名,
|
||||
`--iwb-surface` 被 ai-chat 插件、`--fs-xs` 被 style-source 插件引用(跨仓)。判死前先 grep 外仓
|
||||
|
||||
> **⚠️ 当前 P0 无待办项。** 唯一一条(1.1 钉点还债)已于 2026-10-31 核准**收口暂停**,理由见下。
|
||||
> 本节保留是为了记住「为什么停下」,不是还欠着活。
|
||||
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ build esbuild 打包到 dist/(单 dist/app.js = src/ 模块按序
|
||||
node --check app.js 与 dist/app.js 语法
|
||||
check-dist.js 产物体检
|
||||
lint ESLint(src/ + app.js,正确性规则)
|
||||
test:unit 126 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
|
||||
test:unit 124 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
|
||||
test relay-task-graph-fixture + iwb-v32-web-test
|
||||
test:facts 事实基线守门(见 §5)
|
||||
typecheck 渐进类型检查(tsc --noEmit;范围 = src/*.js,不含 app.js)
|
||||
|
||||
@@ -3616,9 +3616,6 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
|
||||
return { cls: 'other', tag: '其他' }
|
||||
}
|
||||
|
||||
function isTransientApiError(e) {
|
||||
return ['limit', 'server', 'network', 'timeout'].includes(e && e.iwbType)
|
||||
}
|
||||
function apiErrorMessage(e) {
|
||||
return String((e && e.message) || e || '生成失败')
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
**已经做得好的(不要再提)**:token 三层体系 + 三方一致性守卫、单测孤儿门禁、三条行数棘轮、
|
||||
插件市场 sha256 全量校验、备份密钥 `__KEEP__` 脱敏、e2e 只挂 PR(省 CI 额度)、文档数字自动同步。
|
||||
|
||||
## 1. 死代码与"假绿"
|
||||
## 1. 死代码与"假绿"(**已在 v3.26.65 处置**)
|
||||
|
||||
| # | 问题 | 证据 | 建议 |
|
||||
|---|---|---|---|
|
||||
@@ -31,6 +31,16 @@
|
||||
|
||||
> 共性风险:**测试覆盖了死代码 ⇒ 覆盖率虚高**。建议在门禁里加一条"零消费模块清单",新增即红。
|
||||
|
||||
**处置结果(v3.26.65)**:
|
||||
- `src/plugin-archive.js`(206 行)+ 测试 → **删除**(插件 zip 安装已由 `src/runtime-plugin-market.js` 覆盖)
|
||||
- `src/image-preview-derive.js`(449 行)+ 测试 → **删除**;同时更正 `engineering-rulebook §13.34.6`、
|
||||
`project-engineering-standards §11.2`、`archive/plans/opentu-parity-image-memory` 里「已接入」的假记录,
|
||||
重做项登记到 `BACKLOG §1.2`(含难点:`wPreviewUrlOf` 是同步恒等函数,接线需异步化)
|
||||
- `isTransientApiError` → **删除**(做生图重试时再加回来)
|
||||
- `deadTokens 32` → **实测后判定不删**:`--iwb-plugin-*` 13 个是插件主题契约、`--fs-*`/`--sp-*`/`--rd-*`/`--tr-*` 是 legacy 别名,
|
||||
`--iwb-surface`(ai-chat)、`--fs-xs`(style-source)被外仓插件引用;判死口径已写入 `BACKLOG §1.3`
|
||||
- 已知红清单也一并落地:`tests/fixtures/e2e-known-red.json` + `npm run e2e:known-red`(新增红才非零退出)
|
||||
|
||||
## 2. 错误可见性
|
||||
|
||||
| # | 问题 | 证据 | 建议 |
|
||||
|
||||
@@ -79,7 +79,7 @@
|
||||
| **E 复制/快照去 JSON 深拷贝** | ✅ 已上线 | v3.87.45(`86d0076`) |
|
||||
| **C1 跨域缩略图 + 负缓存** | ✅ 已上线 | v3.87.46(`67e91c1`) |
|
||||
| 小步:ref 图 lazy/async + 预览传原图 | ✅ 已上线 | v3.87.47(`42c34f9`) |
|
||||
| **W2-A 预览产物模块**(解码即缩放) | ✅ 已接入构建 | `image-preview-derive.js` 32/32 单测,`1fab0c0` |
|
||||
| **W2-A 预览产物模块**(解码即缩放) | ⚠️ **实际未接线**(2026-11-24 复核:`wPreviewUrlOf` 是恒等函数,模块零消费)→ 模块与单测已于 v3.26.65 删除 | 重做见 BACKLOG「预览产物按需解码」 |
|
||||
| W2-B e2e 契约 | 🔄 子 agent 进行中 | — |
|
||||
| **C6 参考图节点走显示缩略图** | ✅ 已上线 | v3.87.51(`549f3b0`) |
|
||||
| **C5 objectURL 生命周期收口** | ✅ 已上线 | v3.87.52(`63be3da`) |
|
||||
@@ -211,7 +211,7 @@ function wPreviewUrlOf(v) {
|
||||
|
||||
## 12. 验收状态(Round 24 更新)
|
||||
**实现层:全部完成并在生产取证** ✓(线上 `v3.87.58+584a3ce`,三地址一致)
|
||||
- 生产产物核验:`wPreviewUrlOf`×5(1 定义 + 4 接入)· `src/image-preview-derive.js` HTTP 200 且 `resizeWidth/resizeQuality/close` 就位 · `wAwaitCacheWrites`/`wMigrateIdbRef`/`imgblob_`/`wResolveRefArgs`/`wResolveImagesForExport`/`wRegisterBlobUrl` 全部在产物中 · 探针与深拷贝残留 **0**
|
||||
- 生产产物核验:`wPreviewUrlOf`×5(1 定义 + 4 接入,**均为恒等透传**)· ~~`src/image-preview-derive.js`~~ 已于 v3.26.65 删除(从未被调用) · `wAwaitCacheWrites`/`wMigrateIdbRef`/`imgblob_`/`wResolveRefArgs`/`wResolveImagesForExport`/`wRegisterBlobUrl` 全部在产物中 · 探针与深拷贝残留 **0**
|
||||
- 门禁:单测 **617 / 0 新增失败 / 5 已知** + e2e **81 passed** + `verify:release` 三地址一致
|
||||
|
||||
**Round 26/27 追加修复(均已在线上 `v3.87.62+86ae725`)**
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
- 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob_<hash>_<len>`** (A) `app.js:2143`;`{__cache}`(Cache Storage)为兜底;\`ref_\`(`app.js` 内定义的 `IDB_REF_PREFIX = 'ref_'`)为 legacy 形态 (A)。
|
||||
- 大图判定:`isBigDataUrl` = `data:` 且 `length > 3000` (A) `app.js:2018`;**画布保存保留阈值** `< 16384` 才原样保留 (A) `app.js:2182`。**两处阈值并存,含义不同**。
|
||||
- 单测是**源码契约测试**:`tests/` 目录共 **493** 处源码文本钉点(`source.includes` / `source.indexOf` / `/re/.test(source)`),分布在 **20** 个文件(其中 `iwb-v32-web-test.js` 一个就占 **407**)→ **结构性重构会先打红测试**。**该数字已由 `tests/source-text-ratchet-test.js` 的「只减不增」棘轮守门**(2026-10-20 起守卫范围从 1 个文件扩到全目录:新增任何一处源码文本钉点都会打红)。**2026-11-12 复算**(`npm run audit:pins`,v3.24.76):二分 STRUCT **417** / NAME **76**;形态 **POS 403 / NEG 87 / COUNT 3**;难度 **易 62 / 中 316 / 难 115**。钉点减法第一批(v3.24.72)把 **537 → 505**:8 条探针钉点改为「门禁内 spec 是否真的读该计数器」、5 条改为运行时断言(生产态 `window` 上无探针)、10 条改为 DOM 断言(质量档位禁用 / 传输页无三模式按钮 / 模型项 title)、4 条改为运行时对象断言(健康检查两域、策略对象冻结)、其余 9 条有同文件 DOM 等价断言或仅剩 NEG。第二批(v3.24.76)把 **505 → 493**:94-5~7 三条「多标签释放语义」(10 处正则)换成 `tests/iwb-tabs-release.spec.js` 的 3 条真 e2e,剩 1 条「消费方契约」(断言该 spec 在门禁内且 spec 源码真的读两个探针);另 2 条 `wPurgeIntent.add` 钉点改为读 `src/workspace-purge.js`。**这一批一换就查出 3 个真缺陷**(objectURL 从未释放 / 彻底删除留孤儿标签 · session / 刷新后误回收打开标签的图)—— 见 CHANGELOG v3.24.76。
|
||||
- `app.js` = 单 IIFE **9,105 行**(**双层预算**:绝对上限 9,105 / 占总源码 ≤ 40%,现 **30.0%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **3,044 行**(上限 **3,046**,余量 2;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **109** 个模块 / 21,290 行,`sourceModules` 109 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。
|
||||
- `app.js` = 单 IIFE **9,102 行**(**双层预算**:绝对上限 9,105 / 占总源码 ≤ 40%,现 **30.6%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **3,044 行**(上限 **3,046**,余量 2;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **107** 个模块 / 20,633 行,`sourceModules` 107 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。
|
||||
- 门禁:`npm run verify` = `verify:ci`(`build` → `node --check app.js` → `node --check dist/app.js` → `check-dist.js` → `lint`(ESLint 正确性规则,`src/` + `app.js`,P4-16a)→ `test:unit` → `test` → `test:facts`)+ `test:e2e` (A) `package.json`。
|
||||
|
||||
## 2. 门禁与环境现状
|
||||
@@ -167,7 +167,7 @@
|
||||
- 同一张图被 3 个节点引用、hydrate 成 3 个不同 objectURL 时,preview/display 缓存各自 miss → 重复解码(与 F2 相邻)。
|
||||
- **F10|`refs.genScheduler` 是桩** (A) → 未接线,暂无运行时影响(P3)。
|
||||
- **F11|已建但未接线的模块层(2026-10-17 接线审计;2026-10-18 复核更正)** (A)
|
||||
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**109 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
|
||||
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**107 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
|
||||
- **仅被测试引用(9 模块 + 2 导出)**:`canvas-domain`、`generation-retry`、`generation-service`、`runtime-recovery-runner`、`runtime-state-bridge`、`runtime-store`、`storage-reconcile`、`storage-result`、`workspace-service`;导出 `IWBStorageHealthFactory`、`IWBPluginHostFactory`。(`storage-result` 是**存储层共享结果类型**,被 6 个存储模块读取,**非死代码**;`runtime-store` 为状态模型 epic 地基。)
|
||||
- **app.js 零引用(1 模块 + 3 导出)**:模块 `generation-controller`;导出 `IWBRuntimeMetricsFactory`、`IWBStorageRuntimeFactory`、`IWBUIComponents`。`canvas-relations` 已随 `06cf211` 删除(本文档早前把它列为"唯一可删者",实际已删)。零引用证据 = `grep -rn "<名字>" .`(排除 `node_modules|dist|vendor|test-results`)**只命中其自身赋值行**。
|
||||
- **半接线 / 未接线**:`IWBRuntimeStateBridge` **无 app.js 引用(仅测试)**;`IWBRuntimeRunContext` **已接线**(`runNode` 读取运行上下文);`IWBGenerationController` 是完整但**从未被调用**的工厂;`ModularWorkspaceStore`(`app.js` 内)是 `storage-workspace` 的**预留接线 seam**(当前无下游使用,保留);`window.IWBImageFolder` 自注册后读回(装载路径)。
|
||||
@@ -183,7 +183,7 @@
|
||||
| `storage-reconcile` | 存储对账(`createReconciler`/`check`) | 内联对账 | 存储层收口 |
|
||||
| `runtime-recovery-runner` | 执行恢复候选(`candidate`/`valid`/`run`) | 内联恢复 | 断点恢复 |
|
||||
| `canvas-domain` | 画布域模型(`commit`/`updateNode`/`deleteNodes`…) | `CanvasStore` 那一套 | Workbench 解耦(P2-9) |
|
||||
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**88** 项)与 `sourceModules` 顺序(**109** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
|
||||
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**88** 项)与 `sourceModules` 顺序(**107** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
|
||||
|
||||
## 12. 易踩的坑
|
||||
|
||||
@@ -254,7 +254,7 @@
|
||||
|
||||
**信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。
|
||||
|
||||
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**88** 项)与 `sourceModules` 顺序(**109** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。
|
||||
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**88** 项)与 `sourceModules` 顺序(**107** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。
|
||||
|
||||
**关键陷阱**:`normalizeNodes`(现位于 `src/canvas-normalize.js`)会**静默丢弃**不在 `NODE_H` 里的节点类型 ⇒ 新增节点类型必须先登记 `NODE_H`,否则节点一刷新就消失(§13.27 规则三的同一失败模式)。
|
||||
|
||||
|
||||
@@ -505,7 +505,7 @@ LRU 上限 + 切画板/离开画布/卸载时回收;`revokeAll()` 幂等。
|
||||
| 内容 | 位置 |
|
||||
|---|---|
|
||||
| 完整执行文档与复盘(§0–§13,含被推翻推断的留档、踩坑清单、验收表) | `docs/archive/plans/opentu-parity-image-memory.md` |
|
||||
| 预览产物生成器(解码即缩放 + `close()` + objectURL 回收) | `src/image-preview-derive.js`(32/32 单测) |
|
||||
| ~~预览产物生成器(解码即缩放 + `close()` + objectURL 回收)~~ **已于 v3.26.65 删除**:交付时只做到「模块 + 单测」,从未接到 `wPreviewUrlOf`(实际是恒等函数)—— 属"假绿",重做见 BACKLOG | — |
|
||||
| 图片字节 Blob 仓库(内容寻址去重) | `src/image-blob-store.js`(9/9 单测) |
|
||||
| 同源图片代理(跨域取字节唯一通道) | `functions/api/img.js` |
|
||||
| 内存行为契约 | `tests/iwb-image-memory-parity.spec.js` |
|
||||
|
||||
@@ -298,7 +298,7 @@ dist/ += favicon.svg / _headers / THIRD_PARTY_NOTICES.md
|
||||
| 生成流水线 | `generation-*` | 请求体归一(size-policy / request-shape)、调度、重试、状态、服务、控制器 |
|
||||
| 画布域 | `canvas-*` | 域对象、节点工厂、动作、关系、store |
|
||||
| 工作台 / 图库 | `workspace-service`、`gallery-*` | 工作台装配、图库查询与水合 |
|
||||
| 图片管道 | `image-blob-store`、`image-preview-derive` | Blob 仓库、派生预览(canvas 解码) |
|
||||
| 图片管道 | `image-blob-store`、`image-compress`、`image-format` | Blob 仓库、压缩(Worker)、格式判定与 SVG 光栅化 |
|
||||
| UI 组件 | `ui-components` | 通用 UI 片段 |
|
||||
|
||||
### 11.3 边界硬规则
|
||||
@@ -308,7 +308,7 @@ dist/ += favicon.svg / _headers / THIRD_PARTY_NOTICES.md
|
||||
- **大图只走存储契约**:新写入主通道 `{__blob}`(IndexedDB),`{__cache}` 兜底;**localStorage 只放轻量索引,绝不放放大 base64**(见 §8 与事实基线 §5)。
|
||||
- **契约测试锁结构**:`tests/*.js` 多为**源码契约测试**(断言 `app.js`/`src/*.js` 原文片段)——改函数签名、移动代码块、增删调用点前**先查是否被断言钉住**;结构性重构会先打红测试。
|
||||
- **新增模块**:须遵循既有前缀命名,并登记进 `scripts/build.js` 的 `sourceModules` **且顺序正确**。
|
||||
- 模块按需触碰宿主能力(如 `storage-*` 碰 IndexedDB/localStorage、`image-preview-derive` 碰 canvas、`runtime-crash-log` 碰 window)**属于该层职责**。
|
||||
- 模块按需触碰宿主能力(如 `storage-*` 碰 IndexedDB/localStorage、`image-compress` 碰 Worker/canvas、`runtime-crash-log` 碰 window)**属于该层职责**。
|
||||
- **权威写入点唯一**:业务状态与画布 DOM 的**权威**读写只在 `Workbench()` 作用域(`app.js`);`src/*.js` 只经 `window.IWB*` 读写状态。**允许**把**无状态 UI 组件**放进 `src/ui-*.js`(`React` / `el` 从 `global` 解析,仅经 `props` 收数据与回调)——但**禁止**在模块里持有业务状态的权威副本,也**禁止**模块直接查询 / 写画布 DOM。
|
||||
|
||||
## 12. 交互与状态契约
|
||||
|
||||
+2
-1
@@ -10,7 +10,7 @@
|
||||
"app:build": "tauri build",
|
||||
"lint": "eslint src app.js",
|
||||
"test": "node tests/relay-task-graph-fixture-test.js && node tests/plugin-style-node-test.js && node tests/inherit-text-test.js",
|
||||
"test:unit": "node tests/plugin-archive-test.js && node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js",
|
||||
"test:unit": "node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js",
|
||||
"test:diagnostics": "node tests/runtime-diagnostics-hotpath-test.js",
|
||||
"test:facts": "node tests/architecture-facts-guard-test.js && node tests/release-records-test.js",
|
||||
"plugins:gc": "node scripts/plugins-publish.mjs --gc",
|
||||
@@ -24,6 +24,7 @@
|
||||
"test:visual:update": "npx playwright test _visual-tokens --update-snapshots",
|
||||
"test:e2e": "npm run build && node scripts/serve-test.js",
|
||||
"test:e2e:local": "node scripts/serve-test.js",
|
||||
"e2e:known-red": "node scripts/e2e-known-red-report.js",
|
||||
"verify:ci": "npm run build && node --check app.js && node --check dist/app.js && node scripts/check-dist.js && npm run tokens:check && npm run lint:tokens && npm run lint && npm run typecheck && npm run test:unit && npm test && npm run test:facts",
|
||||
"verify": "npm run verify:ci && npm run test:e2e",
|
||||
"verify:release": "node scripts/verify-release.js",
|
||||
|
||||
@@ -39,7 +39,6 @@ const sourceModules = [
|
||||
'clipboard-native.js',
|
||||
'generation-size-policy.js',
|
||||
'generation-request-shape.js',
|
||||
'image-preview-derive.js',
|
||||
'canvas-actions.js',
|
||||
'canvas-node-factory.js',
|
||||
'storage-contract.js',
|
||||
@@ -69,7 +68,6 @@ const sourceModules = [
|
||||
'storage-outputs.js',
|
||||
'storage-backup.js',
|
||||
'storage-zip.js',
|
||||
'plugin-archive.js',
|
||||
'plugin-promptlib-backup.js',
|
||||
'runtime-constants.js',
|
||||
'canvas-store.js',
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
'use strict'
|
||||
/* e2e 已知红报告(2026-11-24)
|
||||
*
|
||||
* 为什么需要:57 个 spec 里有 16 条长期红(环境性 8 + 真缺陷 8),
|
||||
* 没有清单时「全绿」和「红了」都不可信 —— 新红会被旧红淹没。
|
||||
*
|
||||
* 用法:先起测试服,然后
|
||||
* node scripts/e2e-known-red-report.js 只跑清单内的 spec
|
||||
* node scripts/e2e-known-red-report.js --all 跑全部 spec(慢,谨慎)
|
||||
*
|
||||
* 退出码:0 = 失败数不超过清单(或更少);1 = 出现**新增**失败(需要人看)。
|
||||
* 注意:本脚本不进 verify:ci(e2e 只在 PR 跑,省 CI 额度)。
|
||||
*/
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const { execFileSync } = require('child_process')
|
||||
|
||||
const root = path.resolve(__dirname, '..')
|
||||
const list = JSON.parse(fs.readFileSync(path.join(root, 'tests', 'fixtures', 'e2e-known-red.json'), 'utf8'))
|
||||
const only = process.argv.includes('--all') ? null : list.entries.map((e) => e.spec)
|
||||
|
||||
function runSpec (spec) {
|
||||
const args = ['test', spec, '--reporter=line']
|
||||
try {
|
||||
const out = execFileSync('npx', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
|
||||
return { failed: 0, tail: out.trim().split('\n').slice(-2).join(' | ') }
|
||||
} catch (e) {
|
||||
const out = String((e && e.stdout) || '') + String((e && e.stderr) || '')
|
||||
const m = /(\d+) failed/.exec(out)
|
||||
return { failed: m ? Number(m[1]) : -1, tail: out.trim().split('\n').slice(-2).join(' | ') }
|
||||
}
|
||||
}
|
||||
|
||||
let worst = 0
|
||||
const rows = []
|
||||
const targets = only || fs.readdirSync(path.join(root, 'tests')).filter((f) => f.endsWith('.spec.js')).map((f) => 'tests/' + f)
|
||||
for (const spec of targets) {
|
||||
const known = list.entries.find((e) => e.spec === spec)
|
||||
const r = runSpec(spec)
|
||||
const allowed = known ? known.knownFailures : 0
|
||||
const delta = r.failed - allowed
|
||||
if (delta > 0) worst = Math.max(worst, delta)
|
||||
rows.push({ spec, failed: r.failed, allowed, delta, kind: known ? known.kind : 'unlisted' })
|
||||
}
|
||||
|
||||
console.log('\ne2e 已知红对照(基线 ' + list.measuredVersion + ' · ' + list.measuredAt + ')\n')
|
||||
console.log('spec'.padEnd(46) + 'now'.padEnd(6) + 'known'.padEnd(7) + 'delta')
|
||||
for (const r of rows) {
|
||||
const mark = r.delta > 0 ? ' ← 新增红' : (r.failed === 0 && r.allowed > 0 ? ' ← 已修复,可移出清单' : '')
|
||||
console.log(r.spec.padEnd(46) + String(r.failed).padEnd(6) + String(r.allowed).padEnd(7) + (r.delta > 0 ? '+' + r.delta : String(r.delta)) + mark)
|
||||
}
|
||||
|
||||
if (worst > 0) {
|
||||
console.log('\n有新增失败:请判断是回归还是清单过期(修好后记得删条目)。')
|
||||
process.exit(1)
|
||||
}
|
||||
console.log('\n没有新增失败。')
|
||||
@@ -1,449 +0,0 @@
|
||||
/* 预览产物生成器(画布只渲染小预览的关键一环:**解码即缩放**)
|
||||
*
|
||||
* 目标:为"画布只渲染小预览"提供派生小图,绝不产出 2160×3840 这类全尺寸位图。
|
||||
* - 优先 createImageBitmap(blob, { resizeWidth, resizeHeight, resizeQuality:'high' })
|
||||
* ⇒ 解码阶段就完成重采样,堆里不会出现全尺寸位图。
|
||||
* 为能传入等比目标尺寸,先读图片头部(PNG/JPEG/GIF/WebP/BMP)拿到原始宽高,
|
||||
* 或用调用方直接给的 opts.srcWidth/srcHeight。
|
||||
* - 老浏览器不支持 resizeWidth:退回 createImageBitmap(blob)(或 <img> 全尺寸解码)
|
||||
* 再由 canvas 缩放;此时 decode 出的位图仍会被 close(),不驻留。
|
||||
* - 跨域 URL:不保证能直接 fetch(CORS 会失败)⇒ 调用方通过 opts.viaUrl 传同源代理;
|
||||
* fetch 失败一律返回 { ok:false, error },绝不抛出。
|
||||
* - 生命周期:deriveUrl 产出的 objectURL 由 revokeAll() 统一回收(幂等);
|
||||
* bitmap.close?.() 与内部临时 objectURL 的 revoke 都在 finally 里。
|
||||
*
|
||||
* 纯 UMD 全局脚本(无 ESM、无打包器);**加载期不碰 DOM/canvas**,
|
||||
* 因此 Node 下可直接 eval/require 而不报错(只有调用 derive 时才可能因缺能力失败)。
|
||||
*/
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
|
||||
const DEFAULT_MAX_EDGE = 1024
|
||||
const DEFAULT_QUALITY = 0.82
|
||||
const HEADER_BYTES = 65536 // 头部解析只读前 64KB,避免为量尺寸而整块读入
|
||||
|
||||
const g = (global && typeof global === 'object') ? global : {}
|
||||
|
||||
// ---- 能力探测(全部惰性;沙箱里 global 参数可能是注入的 box,裸标识符才是真 global)----
|
||||
function pickCreateImageBitmap() {
|
||||
try { if (typeof g.createImageBitmap === 'function') return g.createImageBitmap } catch (e) { /* ignore */ }
|
||||
try { if (typeof createImageBitmap === 'function') return createImageBitmap } catch (e) { /* ignore */ }
|
||||
return null
|
||||
}
|
||||
function pickOffscreenCanvas() {
|
||||
try { if (typeof g.OffscreenCanvas === 'function') return g.OffscreenCanvas } catch (e) { /* ignore */ }
|
||||
try { if (typeof OffscreenCanvas === 'function') return OffscreenCanvas } catch (e) { /* ignore */ }
|
||||
return null
|
||||
}
|
||||
function pickDocument() {
|
||||
try { if (g.document && typeof g.document.createElement === 'function') return g.document } catch (e) { /* ignore */ }
|
||||
try { if (typeof document !== 'undefined' && document && typeof document.createElement === 'function') return document } catch (e) { /* ignore */ }
|
||||
return null
|
||||
}
|
||||
function pickImage() {
|
||||
try { if (typeof g.Image === 'function') return g.Image } catch (e) { /* ignore */ }
|
||||
try { if (typeof Image === 'function') return Image } catch (e) { /* ignore */ }
|
||||
return null
|
||||
}
|
||||
function pickFetch() {
|
||||
try { if (typeof g.fetch === 'function') return g.fetch } catch (e) { /* ignore */ }
|
||||
try { if (typeof fetch === 'function') return fetch } catch (e) { /* ignore */ }
|
||||
return null
|
||||
}
|
||||
function pickUrl() {
|
||||
try { if (g.URL && typeof g.URL.createObjectURL === 'function') return g.URL } catch (e) { /* ignore */ }
|
||||
try { if (typeof URL !== 'undefined' && URL && typeof URL.createObjectURL === 'function') return URL } catch (e) { /* ignore */ }
|
||||
return null
|
||||
}
|
||||
|
||||
// ---- 基础工具(无 DOM 依赖,Node 下可用)----
|
||||
function dataUrlToBlob(dataUrl) {
|
||||
const s = String(dataUrl || '')
|
||||
const m = /^data:([^;,]+)?(;base64)?,/.exec(s)
|
||||
if (!m) return null
|
||||
const mime = m[1] || 'application/octet-stream'
|
||||
const body = s.slice(m[0].length)
|
||||
let bytes
|
||||
if (m[2]) {
|
||||
let bin = ''
|
||||
try { bin = (typeof atob === 'function') ? atob(body) : Buffer.from(body, 'base64').toString('binary') } catch (e) { return null }
|
||||
bytes = new Uint8Array(bin.length)
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
|
||||
} else {
|
||||
let txt = body
|
||||
try { txt = decodeURIComponent(body) } catch (e) { /* 已经是明文 */ }
|
||||
bytes = new Uint8Array(txt.length)
|
||||
for (let i = 0; i < txt.length; i++) bytes[i] = txt.charCodeAt(i) & 0xff
|
||||
}
|
||||
return new Blob([bytes], { type: mime })
|
||||
}
|
||||
|
||||
async function blobToDataUrl(blob) {
|
||||
const mime = (blob && blob.type) || 'application/octet-stream'
|
||||
const buf = new Uint8Array(await blob.arrayBuffer())
|
||||
let bin = ''
|
||||
const CH = 0x8000
|
||||
for (let i = 0; i < buf.length; i += CH) bin += String.fromCharCode.apply(null, buf.subarray(i, i + CH))
|
||||
const b64 = (typeof btoa === 'function') ? btoa(bin) : Buffer.from(buf).toString('base64')
|
||||
return 'data:' + mime + ';base64,' + b64
|
||||
}
|
||||
|
||||
// 从图片头部字节读原始宽高(不触发解码)。识别不了返回 null。
|
||||
function imageSizeFromBytes(bytes) {
|
||||
const b = bytes
|
||||
if (!b || b.length < 16) return null
|
||||
const u8 = (i) => b[i] & 0xff
|
||||
const u16be = (i) => ((b[i] & 0xff) << 8) | (b[i + 1] & 0xff)
|
||||
const u32be = (i) => (((b[i] & 0xff) << 24) | ((b[i + 1] & 0xff) << 16) | ((b[i + 2] & 0xff) << 8) | (b[i + 3] & 0xff)) >>> 0
|
||||
const u16le = (i) => (b[i] & 0xff) | ((b[i + 1] & 0xff) << 8)
|
||||
const u32le = (i) => ((b[i] & 0xff) | ((b[i + 1] & 0xff) << 8) | ((b[i + 2] & 0xff) << 16) | ((b[i + 3] & 0xff) << 24)) >>> 0
|
||||
// PNG:签名 89 50 4E 47,IHDR 宽高在 16/20
|
||||
if (u8(0) === 0x89 && u8(1) === 0x50 && u8(2) === 0x4e && u8(3) === 0x47) {
|
||||
if (b.length < 24) return null
|
||||
const w = u32be(16), h = u32be(20)
|
||||
return (w && h) ? { width: w, height: h } : null
|
||||
}
|
||||
// GIF:GIF87a / GIF89a,宽高小端
|
||||
if (u8(0) === 0x47 && u8(1) === 0x49 && u8(2) === 0x46) {
|
||||
if (b.length < 10) return null
|
||||
const w = u16le(6), h = u16le(8)
|
||||
return (w && h) ? { width: w, height: h } : null
|
||||
}
|
||||
// BMP:'BM',宽高 int32 小端(高可为负)
|
||||
if (u8(0) === 0x42 && u8(1) === 0x4d && b.length >= 26) {
|
||||
const w = Math.abs(u32le(18) | 0), h = Math.abs(u32le(22) | 0)
|
||||
return (w && h) ? { width: w, height: h } : null
|
||||
}
|
||||
// WebP:RIFF....WEBP
|
||||
if (b.length >= 30 && u8(0) === 0x52 && u8(1) === 0x49 && u8(2) === 0x46 && u8(3) === 0x46 &&
|
||||
u8(8) === 0x57 && u8(9) === 0x45 && u8(10) === 0x42 && u8(11) === 0x50) {
|
||||
const fourcc = String.fromCharCode(u8(12), u8(13), u8(14), u8(15))
|
||||
if (fourcc === 'VP8X') {
|
||||
const w = 1 + (u8(24) | (u8(25) << 8) | (u8(26) << 16))
|
||||
const h = 1 + (u8(27) | (u8(28) << 8) | (u8(29) << 16))
|
||||
return (w && h) ? { width: w, height: h } : null
|
||||
}
|
||||
if (fourcc === 'VP8 ') {
|
||||
const w = u16le(26) & 0x3fff, h = u16le(28) & 0x3fff
|
||||
return (w && h) ? { width: w, height: h } : null
|
||||
}
|
||||
if (fourcc === 'VP8L' && u8(20) === 0x2f) {
|
||||
const bits = (u8(21) | (u8(22) << 8) | (u8(23) << 16) | (u8(24) << 24)) >>> 0
|
||||
const w = 1 + (bits & 0x3fff)
|
||||
const h = 1 + ((bits >>> 14) & 0x3fff)
|
||||
return (w && h) ? { width: w, height: h } : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
// JPEG:FF D8 后扫 SOFn
|
||||
if (u8(0) === 0xff && u8(1) === 0xd8) {
|
||||
let i = 2
|
||||
while (i + 9 < b.length) {
|
||||
if (u8(i) !== 0xff) { i++; continue }
|
||||
const marker = u8(i + 1)
|
||||
if (marker === 0xff) { i++; continue }
|
||||
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9)) { i += 2; continue }
|
||||
const len = u16be(i + 2)
|
||||
if (len < 2) break
|
||||
const isSOF = (marker >= 0xc0 && marker <= 0xcf) && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc
|
||||
if (isSOF) {
|
||||
const h = u16be(i + 5), w = u16be(i + 7)
|
||||
return (w && h) ? { width: w, height: h } : null
|
||||
}
|
||||
if (marker === 0xda) break // SOS:后面是压缩数据
|
||||
i += 2 + len
|
||||
}
|
||||
return null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// 等比目标尺寸:只缩小不放大,长边 ≤ maxEdge
|
||||
function targetSize(width, height, maxEdge) {
|
||||
const W = Math.max(1, Math.round(Number(width) || 0))
|
||||
const H = Math.max(1, Math.round(Number(height) || 0))
|
||||
const M = Math.max(1, Math.round(Number(maxEdge) || DEFAULT_MAX_EDGE))
|
||||
const long = Math.max(W, H)
|
||||
if (!(long > M)) return { width: W, height: H, scaled: false }
|
||||
const scale = M / long
|
||||
return { width: Math.max(1, Math.round(W * scale)), height: Math.max(1, Math.round(H * scale)), scaled: true }
|
||||
}
|
||||
|
||||
function normMaxEdge(o) {
|
||||
const v = Math.round(Number(o && o.maxEdge))
|
||||
return (v > 0) ? v : DEFAULT_MAX_EDGE
|
||||
}
|
||||
function normQuality(o) {
|
||||
const v = Number(o && o.quality)
|
||||
return (v > 0 && v <= 1) ? v : DEFAULT_QUALITY
|
||||
}
|
||||
function closeBitmap(b) {
|
||||
try { if (b && typeof b.close === 'function') b.close() } catch (e) { /* ignore */ }
|
||||
}
|
||||
function safeRevoke(u) {
|
||||
if (!u) return
|
||||
const U = pickUrl()
|
||||
try { if (U && typeof U.revokeObjectURL === 'function') U.revokeObjectURL(u) } catch (e) { /* ignore */ }
|
||||
}
|
||||
async function readHeaderDims(blob) {
|
||||
try {
|
||||
const head = (blob && typeof blob.slice === 'function') ? blob.slice(0, HEADER_BYTES) : blob
|
||||
if (!head || typeof head.arrayBuffer !== 'function') return null
|
||||
return imageSizeFromBytes(new Uint8Array(await head.arrayBuffer()))
|
||||
} catch (e) { return null }
|
||||
}
|
||||
function makeCanvas(w, h) {
|
||||
const OC = pickOffscreenCanvas()
|
||||
if (OC) {
|
||||
let c = null
|
||||
try { c = new OC(w, h) } catch (e) { try { c = new OC() } catch (e2) { c = null } }
|
||||
if (c) {
|
||||
try { c.width = w; c.height = h } catch (e) { /* ignore */ }
|
||||
const ctx = (typeof c.getContext === 'function') ? c.getContext('2d') : null
|
||||
if (ctx) return { canvas: c, ctx: ctx }
|
||||
}
|
||||
}
|
||||
const doc = pickDocument()
|
||||
if (doc) {
|
||||
try {
|
||||
const c = doc.createElement('canvas')
|
||||
c.width = w; c.height = h
|
||||
const ctx = (typeof c.getContext === 'function') ? c.getContext('2d') : null
|
||||
if (ctx) return { canvas: c, ctx: ctx }
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
return null
|
||||
}
|
||||
function canvasToBlob(canvas, type, quality) {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false
|
||||
const done = (b) => { if (!settled) { settled = true; resolve(b || null) } }
|
||||
try {
|
||||
if (canvas && typeof canvas.convertToBlob === 'function') {
|
||||
canvas.convertToBlob({ type: type, quality: quality }).then((b) => done(b), () => done(null))
|
||||
return
|
||||
}
|
||||
if (canvas && typeof canvas.toBlob === 'function') { canvas.toBlob((b) => done(b), type, quality); return }
|
||||
if (canvas && typeof canvas.toDataURL === 'function') { done(dataUrlToBlob(canvas.toDataURL(type, quality))); return }
|
||||
} catch (e) { done(null); return }
|
||||
done(null)
|
||||
})
|
||||
}
|
||||
function loadImage(src) {
|
||||
return new Promise((resolve) => {
|
||||
const Img = pickImage()
|
||||
if (!Img) { resolve(null); return }
|
||||
try {
|
||||
const img = new Img()
|
||||
let settled = false
|
||||
const done = (v) => { if (!settled) { settled = true; resolve(v) } }
|
||||
img.onload = () => done(img)
|
||||
img.onerror = () => done(null)
|
||||
img.src = src
|
||||
const timer = setTimeout(() => done(null), 30000)
|
||||
const _t = /** @type {any} */ (timer); if (_t && typeof _t.unref === 'function') _t.unref()
|
||||
} catch (e) { resolve(null) }
|
||||
})
|
||||
}
|
||||
|
||||
function create(options) {
|
||||
const cfg = options || {}
|
||||
const urls = new Set() // 已创建、未回收的 objectURL(deriveUrl 产出)
|
||||
const stats = { created: 0, revoked: 0, live: 0, failed: 0 }
|
||||
|
||||
function registerUrl(u) { urls.add(u); stats.created++; stats.live = urls.size }
|
||||
function revokeOne(u) {
|
||||
if (!u || !urls.has(u)) return false
|
||||
safeRevoke(u)
|
||||
urls.delete(u)
|
||||
stats.revoked++
|
||||
stats.live = urls.size
|
||||
return true
|
||||
}
|
||||
// 回收本实例创建的全部 objectURL;幂等(重复调用不会重复计数、不会抛)
|
||||
function revokeAll() {
|
||||
let n = 0
|
||||
urls.forEach((u) => { safeRevoke(u); n++ })
|
||||
urls.clear()
|
||||
stats.revoked += n
|
||||
stats.live = 0
|
||||
return n
|
||||
}
|
||||
function statsOf() { return { created: stats.created, revoked: stats.revoked, live: stats.live, failed: stats.failed } }
|
||||
|
||||
// 入参归一 → { ok, blob?, src?, mime? };错误只回 { ok:false, error }
|
||||
async function resolveInput(input, o) {
|
||||
if (input == null) return { ok: false, error: 'bad-input' }
|
||||
if (typeof input === 'object') {
|
||||
if (typeof input.size === 'number' && typeof input.arrayBuffer === 'function') {
|
||||
return { ok: true, blob: input, mime: input.type || '', via: 'blob' }
|
||||
}
|
||||
if (typeof input.dataUrl === 'string') return resolveInput(input.dataUrl, o)
|
||||
if (typeof input.url === 'string') input = input.url
|
||||
else if (typeof input.src === 'string') input = input.src
|
||||
else return { ok: false, error: 'bad-input' }
|
||||
}
|
||||
const s = String(input || '')
|
||||
if (!s) return { ok: false, error: 'bad-input' }
|
||||
if (s.indexOf('data:') === 0) {
|
||||
if (s.indexOf('data:image/') !== 0) return { ok: false, error: 'not-an-image' }
|
||||
const blob = dataUrlToBlob(s)
|
||||
return blob ? { ok: true, blob: blob, mime: blob.type || '', via: 'data' } : { ok: false, error: 'bad-data-url' }
|
||||
}
|
||||
if (/^https?:\/\//i.test(s)) {
|
||||
// 跨域直连必失败 → 调用方用 opts.viaUrl 给同源代理;失败不抛,回 { ok:false }
|
||||
const target = (o && typeof o.viaUrl === 'string' && o.viaUrl) ? o.viaUrl : s
|
||||
const f = pickFetch()
|
||||
if (!f) return { ok: false, error: 'no-fetch' }
|
||||
try {
|
||||
const res = await f(target)
|
||||
if (!res || (typeof res.ok === 'boolean' && !res.ok)) return { ok: false, error: 'fetch-failed' }
|
||||
const blob = await res.blob()
|
||||
if (!blob || typeof blob.size !== 'number') return { ok: false, error: 'fetch-no-blob' }
|
||||
return { ok: true, blob: blob, mime: blob.type || '', via: 'url', url: target }
|
||||
} catch (e) { return { ok: false, error: 'fetch-failed' } }
|
||||
}
|
||||
if (/^(blob:|\/|\.\/|\.\.\/)/i.test(s)) return { ok: true, src: s, via: 'src' } // 交给 <img> 兜底
|
||||
return { ok: false, error: 'unsupported-input' }
|
||||
}
|
||||
|
||||
// 解码(优先缩放发生在解码阶段)。返回 { bitmap } 或 { bitmap:null };不抛。
|
||||
async function decodeBitmap(blob, o) {
|
||||
const cib = pickCreateImageBitmap()
|
||||
if (!cib || !blob) return { bitmap: null }
|
||||
const maxEdge = normMaxEdge(o)
|
||||
let dim = null
|
||||
if (o && Number(o.srcWidth) > 0 && Number(o.srcHeight) > 0) {
|
||||
dim = { width: Number(o.srcWidth), height: Number(o.srcHeight) }
|
||||
} else {
|
||||
dim = await readHeaderDims(blob)
|
||||
}
|
||||
if (dim && dim.width > 0 && dim.height > 0) {
|
||||
const t = targetSize(dim.width, dim.height, maxEdge)
|
||||
try {
|
||||
const bmp = await cib(blob, { resizeWidth: t.width, resizeHeight: t.height, resizeQuality: 'high' })
|
||||
if (bmp) return { bitmap: bmp, resizedAtDecode: true }
|
||||
} catch (e) { /* 个别实现不接受 resize 选项 → 退回不带选项 */ }
|
||||
}
|
||||
try {
|
||||
const bmp = await cib(blob)
|
||||
return { bitmap: bmp || null, resizedAtDecode: false }
|
||||
} catch (e) { return { bitmap: null } }
|
||||
}
|
||||
|
||||
// 编码:把(可能已缩放的)位图画进目标尺寸 canvas → toBlob
|
||||
async function encodeFromSource(source, w, h, srcMime, o) {
|
||||
const made = makeCanvas(w, h)
|
||||
if (!made) return { error: 'no-canvas' }
|
||||
if (!made.ctx || typeof made.ctx.drawImage !== 'function') return { error: 'no-2d-context' }
|
||||
try {
|
||||
made.ctx.drawImage(source, 0, 0, w, h)
|
||||
const keep = (o && o.format === 'keep')
|
||||
let outMime = keep ? ((srcMime && /^image\//i.test(srcMime)) ? srcMime : 'image/png') : 'image/jpeg'
|
||||
const q = normQuality(o)
|
||||
let blob = await canvasToBlob(made.canvas, outMime, q)
|
||||
if (!blob && outMime !== 'image/png' && outMime !== 'image/jpeg') {
|
||||
outMime = 'image/png' // canvas 不支持的 MIME(如 image/webp)→ 保底 PNG
|
||||
blob = await canvasToBlob(made.canvas, outMime, q)
|
||||
}
|
||||
if (!blob) return { error: 'encode-failed' }
|
||||
let out = blob
|
||||
if (!out.type) { try { out = new Blob([await blob.arrayBuffer()], { type: outMime }) } catch (e) { /* ignore */ } }
|
||||
return { blob: out, mime: outMime }
|
||||
} catch (e) { return { error: 'draw-failed' } }
|
||||
}
|
||||
|
||||
async function derive(input, opts) {
|
||||
const o = Object.assign({}, cfg, opts || {})
|
||||
const t0 = Date.now()
|
||||
let bitmap = null
|
||||
let tempUrl = ''
|
||||
try {
|
||||
const resolved = await resolveInput(input, o)
|
||||
if (!resolved.ok) { stats.failed++; return { ok: false, error: resolved.error } }
|
||||
|
||||
if (resolved.blob) {
|
||||
const dec = await decodeBitmap(resolved.blob, o)
|
||||
bitmap = dec.bitmap || null
|
||||
}
|
||||
// 兜底:无 createImageBitmap / 解码失败 / 只有 src → <img> 全尺寸解码,再由 canvas 缩放
|
||||
if (!bitmap) {
|
||||
let src = resolved.src || ''
|
||||
if (!src && resolved.blob) {
|
||||
const U = pickUrl()
|
||||
if (U && typeof U.createObjectURL === 'function') {
|
||||
try { src = U.createObjectURL(resolved.blob); tempUrl = src } catch (e) { src = '' }
|
||||
}
|
||||
}
|
||||
if (src) {
|
||||
const img = await loadImage(src)
|
||||
if (img) bitmap = img
|
||||
}
|
||||
}
|
||||
if (!bitmap) { stats.failed++; return { ok: false, error: resolved.blob ? 'decode-failed' : 'no-decoder' } }
|
||||
|
||||
const bw = Number(bitmap.width) || 1
|
||||
const bh = Number(bitmap.height) || 1
|
||||
const t = targetSize(bw, bh, normMaxEdge(o)) // 已解码缩放时为恒等;老环境在此把全尺寸缩下来
|
||||
const srcMime = resolved.mime || (resolved.blob && resolved.blob.type) || ''
|
||||
const enc = await encodeFromSource(bitmap, t.width, t.height, srcMime, o)
|
||||
if (!enc || enc.error) { stats.failed++; return { ok: false, error: (enc && enc.error) || 'encode-failed' } }
|
||||
|
||||
const out = {
|
||||
ok: true,
|
||||
blob: enc.blob,
|
||||
width: t.width,
|
||||
height: t.height,
|
||||
bytes: (typeof enc.blob.size === 'number') ? enc.blob.size : 0,
|
||||
ms: Date.now() - t0,
|
||||
}
|
||||
if (o.returnDataUrl !== false && o.dataUrl !== false) {
|
||||
try { out.dataUrl = await blobToDataUrl(enc.blob) } catch (e) { /* 无 base64 能力时不强求 */ }
|
||||
}
|
||||
return out
|
||||
} catch (e) {
|
||||
stats.failed++
|
||||
return { ok: false, error: (e && e.message) ? String(e.message) : 'derive-throw' }
|
||||
} finally {
|
||||
closeBitmap(bitmap) // 无论成功失败都释放解码位图
|
||||
if (tempUrl) safeRevoke(tempUrl) // 内部临时 objectURL 立即回收
|
||||
}
|
||||
}
|
||||
|
||||
// 产出一个可直接喂给 <img src> 的 objectURL;返回 { ok, url, revoke, width, height, bytes, ms }
|
||||
async function deriveUrl(input, opts) {
|
||||
const o = Object.assign({}, cfg, opts || {}, { returnDataUrl: false }) // 只要 URL,不必再转 base64
|
||||
const r = await derive(input, o)
|
||||
if (!r.ok) return { ok: false, error: r.error }
|
||||
const U = pickUrl()
|
||||
if (!U || typeof U.createObjectURL !== 'function') {
|
||||
stats.failed++
|
||||
return { ok: false, error: 'no-object-url' }
|
||||
}
|
||||
let url = ''
|
||||
try { url = U.createObjectURL(r.blob) } catch (e) { stats.failed++; return { ok: false, error: 'object-url-failed' } }
|
||||
registerUrl(url)
|
||||
return {
|
||||
ok: true,
|
||||
url: url,
|
||||
revoke: () => revokeOne(url),
|
||||
width: r.width,
|
||||
height: r.height,
|
||||
bytes: r.bytes,
|
||||
ms: r.ms,
|
||||
}
|
||||
}
|
||||
|
||||
return { derive, deriveUrl, revokeAll, stats: statsOf }
|
||||
}
|
||||
|
||||
global.IWBImagePreviewDerive = Object.freeze({
|
||||
create,
|
||||
dataUrlToBlob,
|
||||
blobToDataUrl,
|
||||
imageSizeFromBytes,
|
||||
targetSize,
|
||||
DEFAULT_MAX_EDGE,
|
||||
DEFAULT_QUALITY,
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -1,206 +0,0 @@
|
||||
/* plugin-archive.js —— 插件包 ZIP 打包/解包(浏览器侧)
|
||||
*
|
||||
* 为什么要有这一层:
|
||||
* - 插件包是**外部输入**:ZIP 里可能藏 ../、绝对路径、反斜杠、超限条目(zip 炸弹)。
|
||||
* 直接把它交给 storage-zip 读写,会把「能不能解」和「该不该解」混在一起;
|
||||
* 本模块只做准入判断,ZIP 编解码仍全部复用 src/storage-zip.js。
|
||||
* - 打包与解包共用同一套校验,避免「写的时候放行、读的时候才拦」造成半成品包。
|
||||
*
|
||||
* 插件包布局(只允许这几种路径):
|
||||
* - data.json / meta.json 顶层元数据
|
||||
* - images/<name>.(jpg|jpeg|png|webp) 图片资源(images/ 下不再允许子目录)
|
||||
*
|
||||
* ⚠️ 重名检测不能只看 wOpenZipBlob 的 files 映射:它是普通对象,同名条目会被
|
||||
* 后一个静默覆盖。所以先用 wZipParseEntries 读中央目录做名字/声明大小/重名预检,
|
||||
* 再用 wOpenZipBlob 逐条读字节并复核**实际**大小(声明大小可伪造,不能当唯一防线)。
|
||||
*/
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
|
||||
const MAX_FILES = 500
|
||||
const MAX_FILE_BYTES = 16 * 1024 * 1024
|
||||
const MAX_TOTAL_BYTES = 64 * 1024 * 1024
|
||||
// 名字过长会写坏 ZIP 的 16 位名称长度字段,也超出常见文件系统上限,直接拒绝。
|
||||
// 名字被白名单限制为 ASCII,所以字符数即字节数。
|
||||
const MAX_NAME_LENGTH = 255
|
||||
const SAFE_NAME_RE = /^[A-Za-z0-9._/-]+$/
|
||||
const IMAGE_EXT_RE = /\.(?:jpe?g|png|webp)$/i
|
||||
const IMAGE_DIR = 'images/'
|
||||
const TOP_FILES = ['data.json', 'meta.json']
|
||||
|
||||
// 上限必须可被调用方/测试读取:这些数字就是信任边界,散落在函数里容易被改错。
|
||||
const limits = Object.freeze({
|
||||
maxFiles: MAX_FILES,
|
||||
maxFileBytes: MAX_FILE_BYTES,
|
||||
maxTotalBytes: MAX_TOTAL_BYTES,
|
||||
})
|
||||
|
||||
function isDirectory (name) {
|
||||
return name.charAt(name.length - 1) === '/'
|
||||
}
|
||||
|
||||
// 名字是唯一进入 ZIP 的路径,按「明显穿越 → 字符 → 路径段 → 白名单前缀」顺序校验。
|
||||
// 顺序是刻意的:先报「反斜杠 / .. / 绝对路径」,错误消息才能指向真正原因,
|
||||
// 而不是笼统地报一句"含非法字符"。
|
||||
function validateName (name) {
|
||||
if (typeof name !== 'string' || name.length === 0) throw new Error('文件名必须是非空字符串')
|
||||
if (name.indexOf('\\') !== -1) throw new Error('文件名不能包含反斜杠:' + name)
|
||||
for (let i = 0; i < name.length; i++) {
|
||||
const code = name.charCodeAt(i)
|
||||
if (code < 0x20 || code === 0x7f) throw new Error('文件名不能包含控制字符:' + JSON.stringify(name))
|
||||
}
|
||||
if (name.charAt(0) === '/') throw new Error('文件名不能是绝对路径:' + name)
|
||||
if (!SAFE_NAME_RE.test(name)) throw new Error('文件名含非法字符(只允许字母数字、-、_、.、/):' + name)
|
||||
if (name.length > MAX_NAME_LENGTH) {
|
||||
throw new Error('文件名过长(最多 ' + MAX_NAME_LENGTH + ' 个字符):' + name.slice(0, 64) + '...')
|
||||
}
|
||||
const dir = isDirectory(name)
|
||||
const body = dir ? name.slice(0, -1) : name
|
||||
if (body.length === 0) throw new Error('文件名不能为空:' + name)
|
||||
for (const part of body.split('/')) {
|
||||
if (part === '..') throw new Error('文件名不能包含 .. 路径段:' + name)
|
||||
if (part === '.' || part === '') throw new Error('文件名包含非法路径段:' + name)
|
||||
}
|
||||
if (dir) {
|
||||
// 只接受 images/ 这一种目录条目;其余目录没有业务含义,放行只会扩大攻击面。
|
||||
if (body !== 'images') throw new Error('ZIP 只允许 images/ 目录条目:' + name)
|
||||
return { name, dir: true }
|
||||
}
|
||||
if (TOP_FILES.indexOf(name) !== -1) return { name, dir: false }
|
||||
if (name.indexOf(IMAGE_DIR) !== 0) throw new Error('文件名不在允许的路径内(仅 data.json、meta.json、images/):' + name)
|
||||
const rest = name.slice(IMAGE_DIR.length)
|
||||
if (rest.indexOf('/') !== -1) throw new Error('images/ 下不允许再建子目录:' + name)
|
||||
if (!IMAGE_EXT_RE.test(rest)) throw new Error('图片只允许 .jpg/.jpeg/.png/.webp 后缀:' + name)
|
||||
return { name, dir: false }
|
||||
}
|
||||
|
||||
function encodeData (data, name) {
|
||||
if (typeof data === 'string') return new global.TextEncoder().encode(data)
|
||||
// 用 brand check 而不是 instanceof:模块可能被放在 iframe/vm 等不同 realm 里,
|
||||
// 跨 realm 的 Uint8Array 用 instanceof 判断会误杀正常输入。
|
||||
if (Object.prototype.toString.call(data) === '[object Uint8Array]') {
|
||||
return new global.Uint8Array(data.buffer, data.byteOffset, data.byteLength)
|
||||
}
|
||||
throw new Error('文件内容必须是 Uint8Array 或 string:' + name)
|
||||
}
|
||||
|
||||
function storage () {
|
||||
const S = global.IWBStorageZip
|
||||
if (!S) throw new Error('ZIP 能力不可用(IWBStorageZip 未加载)')
|
||||
return S
|
||||
}
|
||||
|
||||
function assertBlob (blob) {
|
||||
if (!blob || typeof blob.arrayBuffer !== 'function' || typeof blob.size !== 'number') {
|
||||
throw new Error('解包输入必须是 Blob')
|
||||
}
|
||||
}
|
||||
|
||||
async function zip (files) {
|
||||
if (!Array.isArray(files)) throw new Error('打包输入必须是文件数组')
|
||||
if (files.length > MAX_FILES) throw new Error('文件数超过上限(最多 ' + MAX_FILES + ' 个):' + files.length)
|
||||
const seen = new Set()
|
||||
const items = []
|
||||
let total = 0
|
||||
// 先把整批文件校验完再动写入器:校验失败时不要留下写了一半的 ZIP。
|
||||
for (const f of files) {
|
||||
if (!f || typeof f !== 'object') throw new Error('文件项必须是 { name, data } 对象')
|
||||
const checked = validateName(f.name)
|
||||
if (checked.dir) throw new Error('打包列表不能包含目录条目:' + checked.name)
|
||||
if (seen.has(checked.name)) throw new Error('ZIP 中存在重名条目:' + checked.name)
|
||||
seen.add(checked.name)
|
||||
const bytes = encodeData(f.data, checked.name)
|
||||
if (bytes.byteLength > MAX_FILE_BYTES) throw new Error('单个文件超过上限(16MB):' + checked.name)
|
||||
total += bytes.byteLength
|
||||
if (total > MAX_TOTAL_BYTES) throw new Error('文件总大小超过上限(64MB):' + checked.name)
|
||||
items.push({ name: checked.name, bytes })
|
||||
}
|
||||
const S = storage()
|
||||
if (typeof S.wCreateStoreZip !== 'function') throw new Error('ZIP 写入能力不可用(IWBStorageZip.wCreateStoreZip 缺失)')
|
||||
const zw = S.wCreateStoreZip()
|
||||
if (!zw || typeof zw.add !== 'function' || typeof zw.finish !== 'function') throw new Error('ZIP 写入器不可用')
|
||||
for (const item of items) {
|
||||
// 每个文件单独一个 Blob:storage-zip 会把 Blob 原样作为 ZIP part,字节不必堆进 JS 堆。
|
||||
await zw.add(item.name, new global.Blob([item.bytes]))
|
||||
}
|
||||
const blob = zw.finish()
|
||||
if (!blob || typeof blob.arrayBuffer !== 'function') throw new Error('ZIP 写入失败:没有产出 Blob')
|
||||
return blob
|
||||
}
|
||||
|
||||
// 中央目录预检。返回 null 表示当前客户端没有 wZipParseEntries ——
|
||||
// 此时只能退化为 files 映射校验(该映射会吞掉重名,属于已知降级)。
|
||||
async function scanEntries (S, blob) {
|
||||
if (typeof S.wZipParseEntries !== 'function') return null
|
||||
let parsed
|
||||
try {
|
||||
parsed = S.wZipParseEntries(await blob.arrayBuffer())
|
||||
} catch (e) {
|
||||
throw new Error('ZIP 解析失败:' + ((e && e.message) || e))
|
||||
}
|
||||
const entries = (parsed && parsed.entries) || []
|
||||
if (entries.length > MAX_FILES) {
|
||||
throw new Error('ZIP 条目数超过上限(最多 ' + MAX_FILES + ' 个):' + entries.length)
|
||||
}
|
||||
const names = []
|
||||
const seen = new Set()
|
||||
let declaredTotal = 0
|
||||
for (const e of entries) {
|
||||
const checked = validateName(e && e.name)
|
||||
if (checked.dir) continue
|
||||
// 声明大小先卡一道:明显超限的炸弹包不必等读出全部字节才报错。
|
||||
const rawSize = Number(e.rawSize) || 0
|
||||
if (rawSize > MAX_FILE_BYTES) throw new Error('解包后单个文件超过上限(16MB):' + checked.name)
|
||||
declaredTotal += rawSize
|
||||
if (declaredTotal > MAX_TOTAL_BYTES) throw new Error('解包后总大小超过上限(64MB):' + checked.name)
|
||||
if (seen.has(checked.name)) throw new Error('ZIP 中存在重名条目:' + checked.name)
|
||||
seen.add(checked.name)
|
||||
names.push(checked.name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
async function unzip (blob) {
|
||||
assertBlob(blob)
|
||||
const S = storage()
|
||||
if (typeof S.wOpenZipBlob !== 'function') throw new Error('ZIP 读取能力不可用(IWBStorageZip.wOpenZipBlob 缺失)')
|
||||
const parsedNames = await scanEntries(S, blob)
|
||||
let opened
|
||||
try {
|
||||
opened = await S.wOpenZipBlob(blob)
|
||||
} catch (e) {
|
||||
throw new Error('ZIP 解析失败:' + ((e && e.message) || e))
|
||||
}
|
||||
const map = opened && opened.files
|
||||
if (!map || typeof map !== 'object') throw new Error('ZIP 打开失败:没有文件表')
|
||||
let names = parsedNames
|
||||
if (!names) {
|
||||
// 降级路径:没有中央目录解析能力时,只能按 files 映射的键校验。
|
||||
names = Object.keys(map)
|
||||
if (names.length > MAX_FILES) throw new Error('ZIP 条目数超过上限(最多 ' + MAX_FILES + ' 个):' + names.length)
|
||||
for (const name of names) validateName(name)
|
||||
}
|
||||
const out = []
|
||||
let total = 0
|
||||
for (const name of names) {
|
||||
const entry = (typeof opened.file === 'function') ? opened.file(name) : map[name]
|
||||
if (!entry || typeof entry.async !== 'function') throw new Error('ZIP 条目读取失败:' + name)
|
||||
let bytes
|
||||
try {
|
||||
bytes = await entry.async('uint8array')
|
||||
} catch (e) {
|
||||
throw new Error('ZIP 条目解压失败(' + name + '):' + ((e && e.message) || e))
|
||||
}
|
||||
if (!bytes || typeof bytes.byteLength !== 'number') throw new Error('ZIP 条目内容非法:' + name)
|
||||
// 中央目录里的 rawSize 可以伪造,真实字节数必须再复核一次(zip 炸弹的最终防线)。
|
||||
if (bytes.byteLength > MAX_FILE_BYTES) throw new Error('解包后单个文件超过上限(16MB):' + name)
|
||||
total += bytes.byteLength
|
||||
if (total > MAX_TOTAL_BYTES) throw new Error('解包后总大小超过上限(64MB):' + name)
|
||||
// 复制一份再交付,避免返回值与 ZIP 内部大 buffer 长期共享(也防止调用方改写源字节)。
|
||||
out.push({ name, data: new global.Uint8Array(bytes) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
global.IWBPluginArchive = Object.freeze({ zip, unzip, limits })
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -236,7 +236,7 @@ console.log('8) 加载期跨模块依赖顺序')
|
||||
// 判据用**行首缩进**,不用括号深度:本仓 src 模块格式高度统一
|
||||
// (`;(function (global) {` 开头、顶层语句恰好 2 空格、函数体与对象字面量内部 ≥ 4 空格),
|
||||
// 缩进判据不需要解析字符串 / 正则 / 模板串。
|
||||
// 曾用「括号深度 ≤ 1」实现,结果被 src/image-preview-derive.js:306 的
|
||||
// 曾用「括号深度 ≤ 1」实现,结果被模板字符串里的花括号干扰(历史案例)
|
||||
// `/^(blob:|\/|\.\.\/)/i` 正则字面量算错平衡(depth = −1)—— 说明按字符扫括号在这类文件上不可靠。
|
||||
// 已知代价:顶层对象字面量**内部**的加载期读取(缩进 4)不计入;实测当前 0 处,
|
||||
// 且漏判只会少守一条,不会误红。
|
||||
|
||||
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"$comment": "e2e 已知失败清单(2026-11-24 立)。用途:把「长期红」与「新红」分开,避免门禁信号被噪声淹没。维护:修好一条就删一条;新红由 scripts/e2e-known-red-report.js 报出来。",
|
||||
"measuredAt": "2026-11-24",
|
||||
"measuredVersion": "3.26.64",
|
||||
"baseUrl": {
|
||||
"clipboard-audit": "http://127.0.0.1:8799",
|
||||
"default": "http://127.0.0.1:8787"
|
||||
},
|
||||
"entries": [
|
||||
{
|
||||
"spec": "tests/clipboard-audit.spec.js",
|
||||
"knownFailures": 8,
|
||||
"reason": "无头浏览器剪贴板权限受限(navigator.clipboard 读图像需真实前台窗口);用例本身在人工环境可通过",
|
||||
"kind": "environment",
|
||||
"since": "2026-11-24 实测"
|
||||
},
|
||||
{
|
||||
"spec": "tests/iwb-close-flush.spec.js",
|
||||
"knownFailures": 3,
|
||||
"reason": "flush 语义用例超时;已用 git stash 在改动前复跑,失败数相同 ⇒ 与本轮修复无关,待单独排查",
|
||||
"kind": "defect",
|
||||
"since": "2026-11-24 实测"
|
||||
},
|
||||
{
|
||||
"spec": "tests/iwb-stability.spec.js",
|
||||
"knownFailures": 5,
|
||||
"reason": "资源中心入口 / 拖拽 / Prompt 刷新等用例选择器或时序失效;与本地图片链路无关",
|
||||
"kind": "defect",
|
||||
"since": "2026-11-24 实测"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -11,7 +11,6 @@
|
||||
"clipboard-native.js",
|
||||
"generation-size-policy.js",
|
||||
"generation-request-shape.js",
|
||||
"image-preview-derive.js",
|
||||
"canvas-actions.js",
|
||||
"canvas-node-factory.js",
|
||||
"storage-contract.js",
|
||||
@@ -41,7 +40,6 @@
|
||||
"storage-outputs.js",
|
||||
"storage-backup.js",
|
||||
"storage-zip.js",
|
||||
"plugin-archive.js",
|
||||
"plugin-promptlib-backup.js",
|
||||
"runtime-constants.js",
|
||||
"canvas-store.js",
|
||||
|
||||
@@ -7,7 +7,7 @@ const path = require('path')
|
||||
const root = path.join(__dirname, '..')
|
||||
const SRC = fs.readFileSync(path.join(root, 'src/image-format.js'), 'utf8')
|
||||
const box = {}
|
||||
new Function('window', 'globalThis', SRC)(box, box) // 与 image-preview-derive-test.js 相同的沙箱加载方式
|
||||
new Function('window', 'globalThis', SRC)(box, box) // 沙箱加载:只注入 window/globalThis,模块不得依赖宿主其它全局
|
||||
const F = box.IWBImageFormat
|
||||
let pass = 0, fail = 0
|
||||
const ok = (name, cond) => { if (cond) { pass++; console.log(' ✅ ' + name) } else { fail++; console.log(' ❌ ' + name) } }
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
// 预览产物生成器(src/image-preview-derive.js)行为测试 —— 独立文件,可异步
|
||||
// 关键断言:解码阶段就传 resizeWidth/resizeHeight(绝不产全尺寸位图)、bitmap.close 无泄漏、
|
||||
// revokeAll 幂等、跨域走 opts.viaUrl、失败只回 { ok:false } 不抛。
|
||||
'use strict'
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const root = path.join(__dirname, '..')
|
||||
const src = fs.readFileSync(path.join(root, 'src/image-preview-derive.js'), 'utf8')
|
||||
const box = {}
|
||||
new Function('window', 'globalThis', src)(box, box) // 与 image-blob-store-test.js 相同的沙箱加载方式
|
||||
const M = box.IWBImagePreviewDerive
|
||||
let pass = 0, fail = 0
|
||||
const ok = (name, cond) => { if (cond) { pass++; console.log(' ✅ ' + name) } else { fail++; console.log(' ❌ ' + name) } }
|
||||
|
||||
// ---- 构造带真实头部的假 PNG(只给头部,不需要可解码的像素数据)----
|
||||
function pngHeaderBytes(w, h) {
|
||||
const b = Buffer.alloc(33)
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(b, 0)
|
||||
b.writeUInt32BE(13, 8)
|
||||
b.write('IHDR', 12, 'ascii')
|
||||
b.writeUInt32BE(w, 16)
|
||||
b.writeUInt32BE(h, 20)
|
||||
b[24] = 8; b[25] = 6; b[26] = 0; b[27] = 0; b[28] = 0
|
||||
return b
|
||||
}
|
||||
const pngDataUrl = (w, h) => 'data:image/png;base64,' + pngHeaderBytes(w, h).toString('base64')
|
||||
|
||||
// ---- 假解码 / 假 canvas(不产真图)----
|
||||
const saved = {
|
||||
cib: globalThis.createImageBitmap,
|
||||
fetch: globalThis.fetch,
|
||||
doc: globalThis.document,
|
||||
oc: globalThis.OffscreenCanvas,
|
||||
img: globalThis.Image,
|
||||
revoke: URL.revokeObjectURL,
|
||||
}
|
||||
let cibCalls = []
|
||||
let lastBitmap = null
|
||||
let canvasCalls = []
|
||||
let lastCanvas = null
|
||||
let revokedUrls = []
|
||||
|
||||
function installFakeDecode() {
|
||||
cibCalls = []
|
||||
globalThis.createImageBitmap = async (blob, opts) => {
|
||||
cibCalls.push({ blob: blob, opts: opts || null })
|
||||
const w = (opts && Number(opts.resizeWidth)) || 4000
|
||||
const h = (opts && Number(opts.resizeHeight)) || 6000
|
||||
const bmp = { width: w, height: h, closed: false, close: function () { this.closed = true } }
|
||||
lastBitmap = bmp
|
||||
return bmp
|
||||
}
|
||||
}
|
||||
function installFakeCanvas() {
|
||||
canvasCalls = []
|
||||
delete globalThis.OffscreenCanvas
|
||||
const mk = () => {
|
||||
const canvas = {
|
||||
width: 0, height: 0, type: '', quality: 0,
|
||||
getContext: () => ({ drawImage: () => { canvas.drawn = true } }),
|
||||
toBlob: (cb, type, quality) => {
|
||||
canvas.type = type; canvas.quality = quality
|
||||
canvasCalls.push({ width: canvas.width, height: canvas.height, type: type, quality: quality })
|
||||
cb(new Blob([new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])], { type: type }))
|
||||
},
|
||||
}
|
||||
lastCanvas = canvas
|
||||
return canvas
|
||||
}
|
||||
globalThis.document = { createElement: (tag) => (tag === 'canvas' ? mk() : {}) }
|
||||
}
|
||||
function restoreEnv() {
|
||||
const put = (k, v) => { if (v === undefined) { try { delete globalThis[k] } catch (e) { globalThis[k] = undefined } } else globalThis[k] = v }
|
||||
put('createImageBitmap', saved.cib)
|
||||
put('fetch', saved.fetch)
|
||||
put('document', saved.doc)
|
||||
put('OffscreenCanvas', saved.oc)
|
||||
put('Image', saved.img)
|
||||
URL.revokeObjectURL = saved.revoke
|
||||
}
|
||||
|
||||
const d = M.create({})
|
||||
let r1 = null, rKeep = null, rUrl1 = null, rUrl2 = null, rBig = null
|
||||
|
||||
async function main() {
|
||||
// 1) 模块加载 / 导出
|
||||
ok('模块加载并导出 IWBImagePreviewDerive', !!M && typeof M === 'object')
|
||||
ok('导出 { create }', typeof M.create === 'function')
|
||||
const api = M.create({})
|
||||
ok('create() 返回完整 API(derive/deriveUrl/revokeAll/stats)',
|
||||
['derive', 'deriveUrl', 'revokeAll', 'stats'].every((k) => typeof api[k] === 'function'))
|
||||
ok('初始 stats 为 {created:0,revoked:0,live:0,failed:0}',
|
||||
api.stats().created === 0 && api.stats().revoked === 0 && api.stats().live === 0 && api.stats().failed === 0)
|
||||
|
||||
// 2) 解码即缩放:传入等比且长边 ≤ maxEdge 的 resizeWidth/resizeHeight
|
||||
installFakeDecode(); installFakeCanvas()
|
||||
r1 = await d.derive(pngDataUrl(4000, 6000), { maxEdge: 1024 })
|
||||
const call = cibCalls[0]
|
||||
ok('createImageBitmap 收到 resizeWidth/resizeHeight',
|
||||
!!(call && call.opts && typeof call.opts.resizeWidth === 'number' && typeof call.opts.resizeHeight === 'number'))
|
||||
ok('resizeQuality = high', !!(call && call.opts && call.opts.resizeQuality === 'high'))
|
||||
const rw = call && call.opts ? call.opts.resizeWidth : 0
|
||||
const rh = call && call.opts ? call.opts.resizeHeight : 0
|
||||
ok('长边 ≤ maxEdge(' + rw + '×' + rh + ' ≤ 1024)', Math.max(rw, rh) <= 1024)
|
||||
ok('等比缩放(4000:6000 比例保持)', Math.abs((rw / rh) - (4000 / 6000)) < 0.01)
|
||||
ok('未按全尺寸解码(2160×3840 类全尺寸位图不会产生)', rw < 4000 && rh < 6000)
|
||||
ok('derive 返回 ok + blob + width/height/bytes/ms',
|
||||
r1.ok === true && !!r1.blob && r1.width === rw && r1.height === rh && r1.bytes > 0 && typeof r1.ms === 'number')
|
||||
|
||||
// 3) 无泄漏:bitmap.close 必须被调用
|
||||
ok('bitmap.close() 被调用(解码位图已释放)', !!lastBitmap && lastBitmap.closed === true)
|
||||
|
||||
// 4) format='keep' + PNG 输入 ⇒ 输出 MIME 保持 image/png
|
||||
rKeep = await d.derive(pngDataUrl(800, 600), { format: 'keep', maxEdge: 1024 })
|
||||
ok("format='keep' 输出 blob MIME = image/png",
|
||||
rKeep.ok === true && !!rKeep.blob && rKeep.blob.type === 'image/png')
|
||||
ok('canvas.toBlob 收到 image/png', !!(lastCanvas && lastCanvas.type === 'image/png'))
|
||||
ok('dataURL 前缀为 data:image/png', typeof rKeep.dataUrl === 'string' && rKeep.dataUrl.indexOf('data:image/png') === 0)
|
||||
|
||||
// 5) fetch 失败 ⇒ { ok:false, error },不抛
|
||||
const failedBefore = d.stats().failed
|
||||
globalThis.fetch = async () => { throw new Error('network down') }
|
||||
let threw = false
|
||||
let rFail = null
|
||||
try { rFail = await d.derive('https://cdn.example.com/blocked.png', { maxEdge: 512 }) } catch (e) { threw = true }
|
||||
ok('fetch 抛错 ⇒ 返回 { ok:false, error } 而非抛出', threw === false && !!rFail && rFail.ok === false && typeof rFail.error === 'string')
|
||||
ok('失败计入 stats().failed', d.stats().failed === failedBefore + 1)
|
||||
|
||||
// 7) http URL 使用 opts.viaUrl(同源代理)
|
||||
const fetched = []
|
||||
globalThis.fetch = async (url) => {
|
||||
fetched.push(url)
|
||||
return { ok: true, status: 200, blob: async () => new Blob([pngHeaderBytes(1200, 900)], { type: 'image/png' }) }
|
||||
}
|
||||
const rVia = await d.derive('https://cdn.example.com/orig.png', { viaUrl: 'https://proxy.example.com/?u=orig.png', maxEdge: 600 })
|
||||
ok('http 输入使用 opts.viaUrl 作为 fetch 目标',
|
||||
fetched.length === 1 && fetched[0] === 'https://proxy.example.com/?u=orig.png')
|
||||
ok('经代理派生结果长边 ≤ maxEdge', rVia.ok === true && Math.max(rVia.width, rVia.height) <= 600)
|
||||
|
||||
// 8) 超大图 4000×6000 派生结果 ≤ maxEdge
|
||||
rBig = await d.derive(pngDataUrl(4000, 6000), { maxEdge: 1024, format: 'jpeg' })
|
||||
ok('超大图(4000×6000)派生结果 width/height ≤ maxEdge',
|
||||
rBig.ok === true && rBig.width <= 1024 && rBig.height <= 1024)
|
||||
ok('超大图长边正好压到 maxEdge(height = 1024)', rBig.height === 1024)
|
||||
ok('默认 format='+"'jpeg'"+' 时 canvas 收到 image/jpeg', !!(lastCanvas && lastCanvas.type === 'image/jpeg'))
|
||||
|
||||
// 6) deriveUrl + revokeAll 幂等
|
||||
URL.revokeObjectURL = (u) => { revokedUrls.push(u) }
|
||||
const dUrl = M.create({})
|
||||
rUrl1 = await dUrl.deriveUrl(pngDataUrl(1000, 500), { maxEdge: 256 })
|
||||
rUrl2 = await dUrl.deriveUrl(pngDataUrl(1000, 500), { maxEdge: 256 })
|
||||
ok('deriveUrl 产出 blob: objectURL(含 revoke 句柄)',
|
||||
rUrl1.ok === true && typeof rUrl1.url === 'string' && rUrl1.url.indexOf('blob:') === 0 && typeof rUrl1.revoke === 'function')
|
||||
ok('objectURL 已登记(stats().live === 2)', dUrl.stats().live === 2 && dUrl.stats().created === 2)
|
||||
let revokeThrew = false
|
||||
try { dUrl.revokeAll(); dUrl.revokeAll() } catch (e) { revokeThrew = true }
|
||||
ok('revokeAll() 幂等:连续两次不抛', revokeThrew === false)
|
||||
ok('revokeAll() 后 stats().live === 0', dUrl.stats().live === 0)
|
||||
ok('revoked 计数为 2(第二次不重复计数)', dUrl.stats().revoked === 2)
|
||||
ok('URL.revokeObjectURL 真的被调用到两个 URL', revokedUrls.length === 2)
|
||||
ok('单独 revoke() 幂等且不抛', rUrl1.revoke() === false && dUrl.stats().live === 0)
|
||||
|
||||
// 附加:无解码器/无 canvas 环境 ⇒ 只回失败,不抛
|
||||
const dNo = M.create({})
|
||||
delete globalThis.createImageBitmap
|
||||
delete globalThis.document
|
||||
delete globalThis.Image
|
||||
delete globalThis.OffscreenCanvas
|
||||
let noThrew = false
|
||||
let rNo = null
|
||||
try { rNo = await dNo.derive(pngDataUrl(4000, 6000), { maxEdge: 256 }) } catch (e) { noThrew = true }
|
||||
ok('无解码器/无 canvas ⇒ { ok:false } 不抛', noThrew === false && !!rNo && rNo.ok === false && typeof rNo.error === 'string')
|
||||
ok('失败计入该实例的 stats().failed', dNo.stats().failed === 1 && dNo.stats().live === 0)
|
||||
|
||||
// 附加:dataURL 非图片 / 非法输入 ⇒ 优雅失败
|
||||
installFakeDecode(); installFakeCanvas()
|
||||
const rBad = await d.derive('data:text/plain;base64,' + Buffer.from('hi').toString('base64'), {})
|
||||
ok('非图片 dataURL ⇒ { ok:false, error }', rBad.ok === false && typeof rBad.error === 'string')
|
||||
|
||||
// 附加:Blob 输入形态
|
||||
const rBlob = await d.derive(new Blob([pngHeaderBytes(2000, 1000)], { type: 'image/png' }), { maxEdge: 500, format: 'keep' })
|
||||
ok('支持 Blob 输入(保持 MIME 且长边 ≤ maxEdge)',
|
||||
rBlob.ok === true && rBlob.blob.type === 'image/png' && Math.max(rBlob.width, rBlob.height) === 500 && rBlob.width === 500)
|
||||
|
||||
restoreEnv()
|
||||
console.log('\n===== image-preview-derive:' + pass + ' 通过 / ' + fail + ' 失败 =====')
|
||||
process.exit(fail ? 1 : 0)
|
||||
}
|
||||
main().catch((e) => { console.error('❌ 测试异常:', e && e.stack || e); process.exit(1) })
|
||||
@@ -1,226 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
// src/plugin-archive.js 的行为测试。
|
||||
//
|
||||
// 为什么测试要这么细:插件包来自外部,ZIP 解包是这个功能的**信任边界**。
|
||||
// 路径穿越、非法后缀、重名条目、超限条目(zip 炸弹)只要漏一个,
|
||||
// 用户点一次"导入插件"就可能把文件写到插件目录之外,或把内存/磁盘打爆。
|
||||
//
|
||||
// 用 vm 加载真实模块(IIFE 挂 window),并先加载 src/storage-zip.js ——
|
||||
// 测试不 mock ZIP 编解码,测的就是线上真实走的那条链路。
|
||||
// ⚠️ 跨 realm:模块在 vm 里创建对象/数组,原型与本文件不同,
|
||||
// 所以内容比较统一走 JSON,不能用 deepStrictEqual。
|
||||
|
||||
const assert = require('assert')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const vm = require('vm')
|
||||
const root = path.resolve(__dirname, '..')
|
||||
|
||||
const sandbox = {
|
||||
console: { log() {}, warn() {}, error() {} },
|
||||
TextEncoder, TextDecoder, Blob, DataView, Uint8Array, Uint32Array,
|
||||
Response, DecompressionStream, Date, Error, Math, String, Number, Array, Object, JSON, Promise, Set, Map, Boolean, isNaN, parseInt,
|
||||
}
|
||||
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'storage-zip.js'), 'utf8'), sandbox)
|
||||
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'plugin-archive.js'), 'utf8'), sandbox)
|
||||
|
||||
const Z = sandbox.IWBStorageZip
|
||||
const A = sandbox.IWBPluginArchive
|
||||
assert.ok(Z, '应加载 IWBStorageZip(storage-zip.js 是被测模块的真实依赖)')
|
||||
assert.ok(A, '应导出 IWBPluginArchive')
|
||||
|
||||
const eqJson = (a, b, msg) => assert.strictEqual(JSON.stringify(a), JSON.stringify(b), msg)
|
||||
const eqBytes = (a, b, msg) => eqJson(Array.from(a), Array.from(b), msg)
|
||||
|
||||
// 绕过 IWBPluginArchive.zip 的校验,直接用底层写入器造"恶意 ZIP":
|
||||
// 只有这样才能验证 unzip 自身的防线(真实攻击者也不会经过我们的 zip())。
|
||||
const rawZip = async (entries) => {
|
||||
const w = Z.wCreateStoreZip()
|
||||
for (const [name, data] of entries) await w.add(name, new Blob([data]))
|
||||
return w.finish()
|
||||
}
|
||||
|
||||
const expectReject = async (fn, pattern, label) => {
|
||||
let err = null
|
||||
try { await fn() } catch (e) { err = e }
|
||||
assert.ok(err, label + ':应 reject,实际却成功了')
|
||||
assert.ok(pattern.test(String(err && err.message)),
|
||||
label + ':错误消息应匹配 ' + pattern + ',实际:' + (err && err.message))
|
||||
}
|
||||
|
||||
// 篡改中央目录里的"原始大小"字段:用一个几字节的小 ZIP 模拟声明 16MB/64MB 的炸弹包。
|
||||
// 这类包不需要真的把大字节读进内存,正好用来单独验证上限判断。
|
||||
const patchCentralRawSize = async (blob, size) => {
|
||||
const buf = await blob.arrayBuffer()
|
||||
const dv = new DataView(buf)
|
||||
const u8 = new Uint8Array(buf)
|
||||
const eocd = u8.length - 22
|
||||
const count = dv.getUint16(eocd + 10, true)
|
||||
let p = dv.getUint32(eocd + 16, true)
|
||||
for (let i = 0; i < count; i++) {
|
||||
assert.strictEqual(dv.getUint32(p, true), 0x02014b50, '中央目录签名应正确')
|
||||
dv.setUint32(p + 24, size, true) // 中央目录条目 +24 = 原始大小
|
||||
const nameLen = dv.getUint16(p + 28, true)
|
||||
const extraLen = dv.getUint16(p + 30, true)
|
||||
const commentLen = dv.getUint16(p + 32, true)
|
||||
p += 46 + nameLen + extraLen + commentLen
|
||||
}
|
||||
return new Blob([buf])
|
||||
}
|
||||
|
||||
;(async () => {
|
||||
// ── 1. 导出面与上限常量 ────────────────────────────────────────────────
|
||||
{
|
||||
assert.strictEqual(typeof A.zip, 'function', '应导出 zip')
|
||||
assert.strictEqual(typeof A.unzip, 'function', '应导出 unzip')
|
||||
assert.ok(A.limits && Object.isFrozen(A.limits), 'limits 应是冻结对象,防止运行期被改松')
|
||||
assert.strictEqual(A.limits.maxFiles, 500, '条目上限应为 500')
|
||||
assert.strictEqual(A.limits.maxFileBytes, 16 * 1024 * 1024, '单文件上限应为 16MB')
|
||||
assert.strictEqual(A.limits.maxTotalBytes, 64 * 1024 * 1024, '总大小上限应为 64MB')
|
||||
}
|
||||
|
||||
// ── 2. 往返:zip → unzip,字节逐一致(含中文内容)────────────────────
|
||||
{
|
||||
const binary = new Uint8Array(256)
|
||||
for (let i = 0; i < binary.length; i++) binary[i] = i
|
||||
const blob = await A.zip([
|
||||
{ name: 'data.json', data: JSON.stringify({ title: '中文标题', n: 1 }) },
|
||||
{ name: 'meta.json', data: '{"version":1}' },
|
||||
{ name: 'images/a.jpg', data: binary },
|
||||
])
|
||||
assert.ok(blob && typeof blob.arrayBuffer === 'function', '应产出 Blob')
|
||||
assert.strictEqual(blob.type, 'application/zip', 'ZIP 的 MIME 应为 application/zip')
|
||||
|
||||
const out = await A.unzip(blob)
|
||||
eqJson(out.map((x) => x.name), ['data.json', 'meta.json', 'images/a.jpg'], '条目名与顺序应保持')
|
||||
assert.strictEqual(new TextDecoder().decode(out[0].data), '{"title":"中文标题","n":1}',
|
||||
'字符串内容按 UTF-8 写入、应原样读回(中文不能乱码)')
|
||||
eqBytes(out[2].data, binary, '二进制内容应逐字节一致')
|
||||
assert.strictEqual(Object.prototype.toString.call(out[0].data), '[object Uint8Array]', 'data 应是 Uint8Array')
|
||||
}
|
||||
|
||||
// ── 3. 路径穿越 / 绝对路径 / 反斜杠:打包与解包都必须拒绝 ─────────────
|
||||
{
|
||||
const cases = [
|
||||
['../evil.js', /\.\.|路径段/],
|
||||
['/abs', /绝对路径/],
|
||||
['images/../../x', /\.\.|路径段/],
|
||||
['images\\a.jpg', /反斜杠/],
|
||||
]
|
||||
for (const [name, pattern] of cases) {
|
||||
await expectReject(
|
||||
() => A.zip([{ name, data: new Uint8Array([1]) }]),
|
||||
pattern, 'zip 应拒绝 ' + name
|
||||
)
|
||||
await expectReject(
|
||||
async () => A.unzip(await rawZip([[name, new Uint8Array([1])]])),
|
||||
pattern, 'unzip 应拒绝 ' + name
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ── 4. 非法后缀 / 非白名单路径 / 中文文件名 ───────────────────────────
|
||||
// 白名单只允许 ASCII 字母数字与 - _ . /,所以中文文件名也应被拒绝
|
||||
// (中文可以出现在 data.json 的**内容**里,但不能出现在路径里)。
|
||||
{
|
||||
await expectReject(
|
||||
() => A.zip([{ name: 'images/a.gif', data: new Uint8Array([1]) }]),
|
||||
/后缀.*images\/a\.gif/, 'zip 应拒绝 .gif'
|
||||
)
|
||||
await expectReject(
|
||||
async () => A.unzip(await rawZip([['images/a.gif', new Uint8Array([1])]])),
|
||||
/后缀.*images\/a\.gif/, 'unzip 应拒绝 .gif'
|
||||
)
|
||||
for (const name of ['other/a.jpg', 'data.json.bak', 'images/nested/a.jpg', 'images/中文.jpg', 'images/a']) {
|
||||
await expectReject(
|
||||
() => A.zip([{ name, data: new Uint8Array([1]) }]),
|
||||
/允许的|子目录|后缀|非法字符/, 'zip 应拒绝白名单外名字 ' + name
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ── 5. 重名条目:不能让后一个静默覆盖前一个 ───────────────────────────
|
||||
// wOpenZipBlob 内部用普通对象存 files,重名会覆盖;所以 unzip 必须先用
|
||||
// 中央目录预检。这条测试就是防止以后有人把预检"优化"掉。
|
||||
{
|
||||
await expectReject(
|
||||
() => A.zip([
|
||||
{ name: 'images/dup.jpg', data: new Uint8Array([1]) },
|
||||
{ name: 'images/dup.jpg', data: new Uint8Array([2]) },
|
||||
]),
|
||||
/重名.*images\/dup\.jpg/, 'zip 应拒绝重名'
|
||||
)
|
||||
const dup = await rawZip([
|
||||
['images/dup.jpg', new Uint8Array([1])],
|
||||
['images/dup.jpg', new Uint8Array([2])],
|
||||
])
|
||||
await expectReject(() => A.unzip(dup), /重名.*images\/dup\.jpg/, 'unzip 应拒绝重名条目')
|
||||
}
|
||||
|
||||
// ── 6. 条目数 > 500(打包与解包)──────────────────────────────────────
|
||||
{
|
||||
const tooMany = []
|
||||
for (let i = 0; i < 501; i++) tooMany.push({ name: 'images/n' + i + '.jpg', data: new Uint8Array([1]) })
|
||||
await expectReject(() => A.zip(tooMany), /500|文件数/, 'zip 应拒绝 501 个文件')
|
||||
|
||||
const tooManyRaw = []
|
||||
for (let i = 0; i < 501; i++) tooManyRaw.push(['images/n' + i + '.jpg', new Uint8Array([1])])
|
||||
await expectReject(
|
||||
async () => A.unzip(await rawZip(tooManyRaw)),
|
||||
/条目数.*500/, 'unzip 应拒绝 501 个条目'
|
||||
)
|
||||
}
|
||||
|
||||
// ── 7. 单文件 > 16MB:打包侧用真实长度;解包侧用伪造的声明长度 ─────────
|
||||
{
|
||||
const oversized = new Uint8Array(A.limits.maxFileBytes + 1)
|
||||
await expectReject(
|
||||
() => A.zip([{ name: 'images/big.jpg', data: oversized }]),
|
||||
/16MB.*images\/big\.jpg/, 'zip 应拒绝 >16MB 的单文件'
|
||||
)
|
||||
|
||||
const one = await rawZip([['images/a.jpg', new Uint8Array([1, 2, 3])]])
|
||||
const fakeSingle = await patchCentralRawSize(one, A.limits.maxFileBytes + 1)
|
||||
await expectReject(
|
||||
async () => A.unzip(fakeSingle),
|
||||
/16MB.*images\/a\.jpg/, 'unzip 应按声明大小拒绝 >16MB 的单条目(防 zip 炸弹)'
|
||||
)
|
||||
}
|
||||
|
||||
// ── 8. 总解压 > 64MB(声明值伪造,避免测试真的分配 64MB)─────────────
|
||||
{
|
||||
const five = []
|
||||
for (let i = 0; i < 5; i++) five.push(['images/t' + i + '.jpg', new Uint8Array([1])])
|
||||
const blob = await rawZip(five)
|
||||
// 5 × 13MB = 65MB:每个都在 16MB 以内,只有总和超限 → 专门打总大小那条判断。
|
||||
const fakeTotal = await patchCentralRawSize(blob, 13 * 1024 * 1024)
|
||||
await expectReject(() => A.unzip(fakeTotal), /总大小.*64MB/, 'unzip 应拒绝解压后总大小 >64MB')
|
||||
}
|
||||
|
||||
// ── 9. 合法目录条目被跳过;非法输入/类型要显式报错 ───────────────────
|
||||
{
|
||||
const withDir = await rawZip([
|
||||
['images/', new Uint8Array(0)],
|
||||
['images/a.png', new Uint8Array([7, 8])],
|
||||
])
|
||||
const out = await A.unzip(withDir)
|
||||
eqJson(out.map((x) => x.name), ['images/a.png'], 'images/ 目录条目应被跳过,不计入文件')
|
||||
eqBytes(out[0].data, new Uint8Array([7, 8]), '目录后的文件内容应正常读出')
|
||||
|
||||
await expectReject(() => A.zip('not-an-array'), /数组/, 'zip 应拒绝非数组输入')
|
||||
await expectReject(
|
||||
() => A.zip([{ name: 'data.json', data: 123 }]),
|
||||
/Uint8Array 或 string/, 'zip 应拒绝非 Uint8Array/string 的内容'
|
||||
)
|
||||
await expectReject(() => A.unzip('not-a-blob'), /Blob/, 'unzip 应拒绝非 Blob 输入')
|
||||
await expectReject(() => A.unzip(new Blob([new Uint8Array(32)])), /ZIP/, 'unzip 应拒绝非 ZIP 字节')
|
||||
}
|
||||
|
||||
console.log('plugin archive checks passed(往返 + 路径穿越 + 白名单后缀 + 重名 + 条目数/单文件/总大小上限)')
|
||||
// ⚠️ 显式退出:vm/Blob 可能让事件循环挂着(沿用 storage-zip-test 的处理)。
|
||||
process.exit(0)
|
||||
})().catch((e) => {
|
||||
console.error('plugin archive checks FAILED:', e && e.message)
|
||||
process.exit(1)
|
||||
})
|
||||
Reference in new issue
Block a user