mirror of
https://github.com/Shu-Ying/noname-shuying.git
synced 2026-11-25 06:26:29 +08:00
fixed # 更改更新方式
This commit is contained in:
@@ -58,7 +58,7 @@ jobs:
|
||||
throw "extension.js 的版本号必须为 $version"
|
||||
}
|
||||
|
||||
# The updater reads raw tag paths, not release attachments.
|
||||
# The updater reads manifests from raw tag paths.
|
||||
# Never generate new manifests after the release tag already exists.
|
||||
python (Join-Path $stage 'tools/verify_manifest.py') `
|
||||
--root $stage `
|
||||
@@ -109,6 +109,11 @@ jobs:
|
||||
'@ | python - $stage $package
|
||||
if ($LASTEXITCODE -ne 0) { throw '打包失败' }
|
||||
|
||||
$partsDir = Join-Path $env:RUNNER_TEMP "mengsan-parts-$tag"
|
||||
python (Join-Path $stage 'tools/build_mengsan_archives.py') `
|
||||
--root $stage --out-dir $partsDir --tag $tag
|
||||
if ($LASTEXITCODE -ne 0) { throw '梦三分包失败' }
|
||||
|
||||
Write-Host "版本:$version"
|
||||
Write-Host "文件数:$($manifest.file_count)"
|
||||
Write-Host "安装包:$package"
|
||||
@@ -152,10 +157,18 @@ jobs:
|
||||
$releaseFiles = @($manifestPath)
|
||||
$releaseFiles += $moduleManifests
|
||||
$releaseFiles += $package
|
||||
$partsDir = Join-Path $env:RUNNER_TEMP "mengsan-parts-$tag"
|
||||
$releaseFiles += @(Get-ChildItem -LiteralPath $partsDir `
|
||||
-Filter '*.zip' -File | Sort-Object Name | ForEach-Object { $_.FullName })
|
||||
foreach ($file in $releaseFiles) {
|
||||
$attachment = if ($file -like '*.zip') {
|
||||
"attachment=@$file;type=application/zip"
|
||||
} else {
|
||||
"attachment=@$file"
|
||||
}
|
||||
curl.exe --fail --silent --show-error `
|
||||
-H "Authorization: token $env:GITEA_TOKEN" `
|
||||
-F "attachment=@$file" `
|
||||
-F $attachment `
|
||||
$assetApi | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "上传附件失败:$file"
|
||||
|
||||
@@ -185,6 +185,11 @@ jobs:
|
||||
'@ | python - $stage $package
|
||||
if ($LASTEXITCODE -ne 0) { throw '打包失败' }
|
||||
|
||||
$partsDir = Join-Path $env:RUNNER_TEMP "mengsan-parts-$tag"
|
||||
python (Join-Path $stage 'tools/build_mengsan_archives.py') `
|
||||
--root $stage --out-dir $partsDir --tag $tag
|
||||
if ($LASTEXITCODE -ne 0) { throw '梦三分包失败' }
|
||||
|
||||
Write-Host "版本:$version"
|
||||
Write-Host "文件数:$($manifest.file_count)"
|
||||
Write-Host "安装包:$package"
|
||||
@@ -222,7 +227,10 @@ jobs:
|
||||
-ContentType 'application/json' `
|
||||
-Body $body
|
||||
|
||||
foreach ($file in @($manifestPath, $package)) {
|
||||
$partsDir = Join-Path $env:RUNNER_TEMP "mengsan-parts-$tag"
|
||||
$partFiles = @(Get-ChildItem -LiteralPath $partsDir `
|
||||
-Filter '*.zip' -File | Sort-Object Name | ForEach-Object { $_.FullName })
|
||||
foreach ($file in (@($manifestPath, $package) + $partFiles)) {
|
||||
$name = [uri]::EscapeDataString([IO.Path]::GetFileName($file))
|
||||
$uploadUri = $release.upload_url.Split('{')[0] + "?name=$name"
|
||||
$contentType = if ($file -like '*.zip') {
|
||||
|
||||
@@ -17,6 +17,7 @@ tools/*.mjs
|
||||
|
||||
*.mjs
|
||||
*.cjs
|
||||
!/tools/test_mengsan_zip_install.mjs
|
||||
!/mengsan/tools/test-hud-status.cjs
|
||||
!/mengsan/tools/test-battle-hud.cjs
|
||||
!/mengsan/tools/import-status-icons.cjs
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# 梦三模式首次安装分包 Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal** 让梦三首次安装优先使用同源同版本的分包 ZIP,降低请求数并控制解包内存。
|
||||
|
||||
**Architecture** 两个发布工作流调用同一个 Python 打包脚本。客户端在现有暂存阶段串行处理附件,对剩余文件复用原有逐文件下载,全部暂存成功后继续执行现有安装事务。
|
||||
|
||||
**Tech Stack** Python 标准库 `zipfile` 和 `unittest`、PowerShell 发布工作流、宿主 JSZip 2.7、`DecompressionStream`、Electron HTTPS、Cordova `FileTransfer`、Node.js 测试运行器。
|
||||
|
||||
**Spec** `docs/superpowers/specs/2026-11-24-mengsan-zip-install-design.md`
|
||||
|
||||
## 全局约束
|
||||
|
||||
- GitHub 和 Gitea 发布同一标签对应的分包。客户端使用玩家已选的源和渠道。
|
||||
- 单次只处理一个独立 ZIP。路径、大小和 SHA-256 以标签的模块清单为准。全部暂存后才安装。
|
||||
- ZIP 不可用时从同源同标签补齐未完成文件。保留现有事务式安装、卸载与重启后重试。
|
||||
- 首版只覆盖梦三首次安装。日常差量更新、查漏补缺、旧安装迁移、常规武将与天书乱斗继续使用现有下载方式。
|
||||
- 实现和验证阶段通过临时测试配置打开 ZIP。两个源的实机验收通过后,再在正式配置默认启用。
|
||||
|
||||
## 审查重点
|
||||
|
||||
- GitHub 已推送标签,Release 仍在草稿或上传中。首次安装应使用同标签文件下载。
|
||||
- 一包失败或重试时,其他包已通过校验的暂存文件只安装一次。
|
||||
- 错误的标签、越界条目和错误字节不得导致正式目录写入未验证的文件。
|
||||
- 文件系统写入失败应进入现有恢复逻辑。同源回退只处理附件下载、解包或内容校验失败。
|
||||
- 重启后已知的新装可以重新使用 ZIP。旧版待修复记录和已有安装更新继续走原路径。
|
||||
|
||||
## 文件分工
|
||||
|
||||
- `tools/build_mengsan_archives.py` · 从正式梦三清单生成并验证分包。
|
||||
- `.github/workflows/release.yml` 和 `.gitea/workflows/release.yml` · 在现有 ZIP 构建和草稿上传步骤加入分包。
|
||||
- `update.js` · 查询附件、复用有字节上限的下载、在安装暂存阶段解包及补齐。
|
||||
- `tools/test_mengsan_archives.py` 和 `tools/test_mengsan_zip_install.mjs` · 覆盖生成规则、正常安装入口及故障分支。
|
||||
- `tools/UPDATE.md` · 记录附件格式和实机启用条件。
|
||||
|
||||
## 任务一 · 构建及核验分包
|
||||
|
||||
**接口** `build_archives(root: Path, output: Path, tag: str) -> list[Path]` 使用 `root/dist/modules/mengsan.json`,生成 `mengsan-<tag>-part-001.zip` 等附件。条目名为 `mengsan/…`,与模块清单路径逐字一致。
|
||||
|
||||
- [ ] 在 `tools/test_mengsan_archives.py` 写 `test_parts_cover_packable_files_once` 和 `test_reject_inconsistent_release`。用临时目录验证 `Counter(written_paths) == Counter(packable_paths)`、条目 SHA-256 与清单一致、超出 5 MiB 的单文件不入包。对清单版本不匹配、源文件变化和单个分包成品超过 6 MiB 分别断言生成失败。
|
||||
- [ ] 运行 `python -m unittest discover -s tools -p test_mengsan_archives.py`,确认因生成器尚缺而失败。
|
||||
- [ ] 实现生成器及 CLI `python tools/build_mengsan_archives.py --root <snapshot> --out-dir <output> --tag <tag>`。按清单路径排序,依次填入每包合计最多 5 MiB 的未压缩文件。使用 `ZIP_DEFLATED`、压缩级别 6。关闭 ZIP 后检查成品不超过 6 MiB,逐项校验路径、大小和 SHA-256,并检查各包合计覆盖所有可打包条目。两个上限是实测起点,调整时同步客户端和测试。
|
||||
- [ ] 重跑 Python 测试并确认通过。以当前分支生成的清单和导出快照运行 CLI,检查实际分包数、最大包大小和完整覆盖。使用发布工作流同样的标签快照校验命令 `python tools/verify_manifest.py --root <snapshot> --version <version>`。
|
||||
|
||||
## 任务二 · 接入两个发布工作流
|
||||
|
||||
**接口** 复用任务一的 CLI。每个工作流向现有草稿 Release 上传生成器在单独输出目录产生的所有 `mengsan-<tag>-part-*.zip`,ZIP 附件使用 `application/zip`。
|
||||
|
||||
- [ ] 在两个 `release.yml` 的快照验证后调用 Python 构建,并在取消草稿前上传分包。沿用原来生成、上传完整 ZIP 和清单的步骤。CI 继续使用标签快照内的脚本与清单。
|
||||
- [ ] 更新 `tools/UPDATE.md` 的发布步骤及分包命名。区分标签 raw 清单、梦三 Release 附件和完整离线包。
|
||||
- [ ] 准备可发布的测试标签后,在获准的测试发布中运行两个工作流。核对同一标签均包含完整 ZIP 和相同编号的分包,完整 ZIP 的原有目录结构保持可用。发版附件下载验证归任务四。
|
||||
|
||||
## 任务三 · 在梦三首次安装的暂存阶段接入 ZIP
|
||||
|
||||
**接口** `getMengsanReleaseParts(manifest, shuYing) -> Promise<Array<{name: string, url: string, size: number}>>` 返回已选源的同标签分包。`stageMengsanArchives(shuYing, manifest, operationRoot, remaining: Set<string>, stageVerified, progress) -> Promise<void>` 串行读取这些包。`stageVerified(file: string, bytes: Uint8Array) -> Promise<void>` 在写盘前记录尝试,写盘成功后才从 `remaining` 移除文件。
|
||||
|
||||
- [ ] 在 `tools/test_mengsan_zip_install.mjs` 用 `node:test` 从正常菜单入口 `manageMengsanModule` 触发安装。`fresh install stages from selected release` 对两个源分别断言附件查询标签正确、成功分包文件无 raw 请求、所有文件备齐前无正式路径写入。`falls back for missing or unusable release parts` 覆盖 Release 404、草稿、标签不匹配、超限响应、损坏 ZIP、越界条目和错误 SHA-256,断言 `rawRequests` 恰好等于未成功暂存文件。`retries the failed ZIP once` 覆盖单包下载异常后成功。`staging write errors preserve recovery` 断言写入失败后无后续 raw 请求。`installed updates and legacy repairs stay on raw` 从 `checkVersion`、`repairMissingFiles` 和旧修复记录分别验证无 Release 请求。至少一个解析用例使用宿主实际捆绑的 JSZip 2.7 和脚本生成的 ZIP。
|
||||
- [ ] 运行 `node --experimental-vm-modules --test tools/test_mengsan_zip_install.mjs` 并确认新增 ZIP 场景因当前只请求 raw 文件而失败。可通过 `vm.SourceTextModule` 和测试用 `SyntheticModule` 为 `../../noname.js` 注入宿主 API,无需从产品代码导出测试接口。
|
||||
- [ ] 在 `update.js` 实现附件查询和下载。两源均请求所选 `<repoApi>/releases/tags/<tag>`,要求 `tag_name` 匹配且 `draft` 为 `false`。仅接收与版本文件名匹配、`size` 为正整数且不超过 6 MiB 的附件。使用该源的 HTTPS `browser_download_url`。GitHub 现有附件链接与 CDN 实测缺少浏览器跨域响应头,因此 Electron 使用支持 HTTPS 重定向的原生请求,Cordova 使用 `FileTransfer` 下载到本次操作目录,校验文件大小后读取并清理。网页 Fetch 用尽该附件的网络重试后回退同源逐文件下载。
|
||||
- [ ] 使用 `get.zip` 获取 JSZip,逐包调用 `load` 读取目录和压缩字节。解包前检查文件名、清单归属、单条目声明大小和包内合计上限。用 `DecompressionStream("deflate-raw")` 解压到按清单大小分配的缓冲区并限制实际输出,随后调用 `verifyFile` 和 `stageVerified`。缺少流式解压能力的客户端直接逐文件下载。异常 ZIP 至多重新取一次再回退。校验、网络和解包错误记录包名及原因。写盘错误从暂存阶段直接抛出。
|
||||
- [ ] 在 `manageMengsanModule` 判定首次安装。无既有安装,或已明确清空的卸载记录进入全新安装;旧待修复记录按原路径。操作记录只在已知首次安装进入 `installing` 时标记 `freshInstall: true`,失败后该标记用于重新发起完整下载。通过 `installMengsanFiles` 把这个选择传给 `updateAllFiles` 的暂存阶段;本次已完成的文件更新原进度和清理集合,原文件池仅处理剩余项。将 ZIP 网络进度与已验证文件字节分开,避免回退时重复计数。保留现有正式路径落盘前复核及安装记录提交逻辑。
|
||||
- [ ] 运行 `node --check update.js` 和 Node 测试,确认通过。分别用清单对比正常 ZIP 和逐文件回退的最终目录及安装记录,确认每个新文件大小和 SHA-256 一致。
|
||||
|
||||
## 任务四 · 实机验收和默认启用
|
||||
|
||||
- [ ] 在同一台受支持手机上,用同一客户端版本、梦三标签、下载源和网络条件,对逐文件和分包的干净安装各测三次。每次从确认安装计时到校验完成。通过网络记录统计资源请求数,从应用及其 WebView 进程记录内存峰值,报告原始样本和中位数。先测 5 MiB 展开、6 MiB 下载上限,再按实测调整。
|
||||
- [ ] 在客户端真实窗口验证 GitHub 与 Gitea Release 的匿名下载、重定向和跨域行为,并分别验证 ZIP 不可用时回退到当前源的同标签文件。测试手机端强制退出后再点击安装。通过安装记录、清单校验和重启后进入梦三确认结果。另跑桌面端首次安装及差量更新一次。
|
||||
- [ ] 对照同环境逐文件基线检验收益。建议启用条件为手机端资源请求数和总耗时中位数下降,内存峰值无可重复的上升,两个源与回退均通过。记录采用的包大小、测试设备和结果,再启用默认 ZIP 路径。
|
||||
|
||||
## 资料
|
||||
|
||||
- [GitHub 按标签查询 Release](https://docs.github.com/en/rest/releases/releases#get-a-release-by-tag-name)
|
||||
- [GitHub Release 附件字段](https://docs.github.com/en/rest/releases/assets#get-a-release-asset)
|
||||
- [Gitea 按标签查询 Release](https://docs.gitea.com/api/1.25/operations/repo-get-release-by-tag/)
|
||||
@@ -0,0 +1,19 @@
|
||||
# 梦三模式首次安装分包设计
|
||||
|
||||
梦三模式首次安装目前会逐个下载模块清单文件。当前仓库按发布清单规则筛出的梦三模块有 846 个文件,约 143.5 MiB。分包的目标是减少首次安装的网络请求,在手机端控制单次解包的数据量,并保留逐文件校验和安装恢复能力。
|
||||
|
||||
## 方案选择
|
||||
|
||||
- 逐文件下载适合日常差量更新和少量补缺,继续沿用现有流程。
|
||||
- 单个 ZIP 请求最少。现有客户端会在内存中拼接完整响应,单个 ZIP 需要持有整个模块的压缩数据。
|
||||
- 首次安装使用多个有大小上限的独立 ZIP。每次只处理一包,下载失败时可以单独重试。首版覆盖梦三,常规武将和天书乱斗等实测后再决定。
|
||||
|
||||
## 发布与安装
|
||||
|
||||
GitHub 和 Gitea 的现有发布工作流使用各自同一发布标签的梦三清单生成分包,将分包与完整离线安装包一起上传为 Release 附件。客户端继续使用选定的源和渠道,先获得同一标签的模块清单,再查询该标签的 Release。首次安装每次下载和解开一包,每个文件按清单验证大小和 SHA-256 后写入现有暂存区。全部文件备齐后,现有安装流程再次验证暂存文件并负责替换、回滚和提交安装记录。
|
||||
|
||||
旧标签无 ZIP、附件暂不可用、解包失败或内容校验失败时,从同源同标签逐文件补齐。本次已校验并写入暂存区的文件可以继续用。暂存写入失败走现有安装失败处理。退出游戏后,安装按现有方式重新发起,部分下载进度只用于当前操作。已安装的模块更新、查漏补缺、卸载和旧安装迁移沿用现有行为。
|
||||
|
||||
## 启用条件
|
||||
|
||||
同一部手机、同一版本和同一下载源下,对比两种方式的请求数、总耗时和内存峰值。验证两个源的附件在游戏内均可下载,且 ZIP 不可用时均可从同源回退。手机实测确认有收益后再默认启用。具体分包上限由实测确定。
|
||||
+1
-1
@@ -6,7 +6,7 @@ import { configureDiagnostics } from "./diagnostics/index.js";
|
||||
|
||||
export const type = "extension";
|
||||
export let shuYing = new Object();
|
||||
const shuYingLocalVersion = "2.0.2.3-rc.8";
|
||||
const shuYingLocalVersion = "2.0.2.3-rc.9";
|
||||
|
||||
shuYing.name = "术樱包";
|
||||
shuYing.editable = false;
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
2. 在 `modules` 中维护可选模块的目录、入口和显示名。
|
||||
3. 发布工作流为每个模块生成独立清单,并将清单提交到发布标签。
|
||||
4. 完整 ZIP 安装包仍包含所有模块,供离线或整包安装使用。
|
||||
5. GitHub 和 Gitea 都从校验通过的标签快照生成 `mengsan-<tag>-part-001.zip` 等分包,随完整 ZIP 上传到同一 Release。分包内使用模块清单的 `mengsan/` 路径,供客户端首次安装使用。
|
||||
|
||||
修改 `extension.js` 中的 `shuYingLocalVersion`,提交并推送到 GitHub
|
||||
默认分支后,工作流会比较推送前后的版本号。版本号变化时自动生成和校验
|
||||
@@ -31,6 +32,21 @@ Gitea 保持接收同一发布标签后打包的流程;使用 Gitea 更新源
|
||||
`dist/manifest.json` 和 `dist/modules/*.json` 的同一标签;当前 Gitea 工作流
|
||||
会生成并上传附件,但不会改写触发它的标签。
|
||||
|
||||
## 分包安装试用
|
||||
|
||||
在测试客户端中将 `shuYing_mengsan_zip_trial` 设为 `true`,然后从扩展菜单首次安装梦三。在客户端的调试控制台执行以下代码,试用后将 `true` 改为 `false` 再执行一次。默认设置沿用逐文件下载,待手机实测通过后启用分包。
|
||||
|
||||
```js
|
||||
const { game } = await import(new URL("noname.js", document.baseURI).href);
|
||||
game.saveConfig("shuYing_mengsan_zip_trial", true);
|
||||
```
|
||||
|
||||
每包按 5 MiB 的展开数据量分组,压缩包最大 6 MiB。大于展开上限的单文件继续逐个下载。客户端顺序处理同源同标签的附件,已校验并暂存的文件可供本次安装复用。附件缺失或无法使用时,剩余文件从当前标签的 raw 路径补齐。
|
||||
|
||||
Electron 走原生 HTTPS,Cordova 使用 `FileTransfer` 下载一包到当前操作的临时目录,读取前核对大小,处理结束后清理。网页端走 Fetch,附件域不可读时回退。ZIP 解压需要支持 `DecompressionStream("deflate-raw")`,不支持的客户端继续逐文件下载。
|
||||
|
||||
实测应记录手机型号、客户端版本、标签、下载源、请求数、总耗时和内存峰值,并分别验证 GitHub 和 Gitea 在游戏内可以下载附件及回退到同源逐文件下载。
|
||||
|
||||
发布时生成器会把 `tools/legacy/mengsan-files.json`、上一次完整清单和当前模块
|
||||
文件合并,随新标签发布迁移路径清单。它用于接管旧安装中的梦三文件并清理
|
||||
不再属于新版本的文件。该文件由迁移时仓库内的梦三路径生成,作为冻结的旧版
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Build bounded ZIP attachments from the verified Mengsan release snapshot."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from generate_manifest import validate_relative_paths
|
||||
|
||||
MAX_UNCOMPRESSED_BYTES = 5 * 1024**2
|
||||
MAX_ARCHIVE_BYTES = 6 * 1024**2
|
||||
|
||||
|
||||
def write_part(root: Path, part: Path, files: list[str], manifest: dict) -> None:
|
||||
with zipfile.ZipFile(part, "w", zipfile.ZIP_DEFLATED, compresslevel=6, allowZip64=False) as archive:
|
||||
for name in files:
|
||||
source = (root / name).resolve()
|
||||
if not source.is_relative_to(root) or source.stat().st_size != manifest[name]["size"]:
|
||||
raise ValueError(f"Source size or path differs from manifest: {name}")
|
||||
archive.write(source, name)
|
||||
if part.stat().st_size > MAX_ARCHIVE_BYTES:
|
||||
raise ValueError(f"ZIP size exceeds download limit: {part.name}")
|
||||
with zipfile.ZipFile(part) as archive:
|
||||
if archive.namelist() != files:
|
||||
raise ValueError(f"Unexpected ZIP entries: {part.name}")
|
||||
for entry in archive.infolist():
|
||||
info = manifest[entry.filename]
|
||||
if entry.file_size != info["size"]:
|
||||
raise ValueError(f"ZIP entry size differs from manifest: {entry.filename}")
|
||||
if hashlib.sha256(archive.read(entry)).hexdigest() != info["sha256"]:
|
||||
raise ValueError(f"ZIP entry SHA-256 differs from manifest: {entry.filename}")
|
||||
|
||||
|
||||
def build_archives(root: Path, output: Path, tag: str) -> list[Path]:
|
||||
root = root.resolve()
|
||||
manifest = json.loads((root / "dist/modules/mengsan.json").read_text(encoding="utf-8"))
|
||||
if (not re.fullmatch(r"v\d+\.\d+\.\d+\.\d+(?:-rc\.\d+)?", tag)
|
||||
or manifest.get("version") != tag[1:] or manifest.get("module_id") != "mengsan"):
|
||||
raise ValueError("Mengsan manifest and release version do not match")
|
||||
files = manifest["files"]
|
||||
validate_relative_paths(list(files), "Mengsan manifest")
|
||||
groups: list[list[str]] = []
|
||||
group: list[str] = []
|
||||
group_bytes = 0
|
||||
for name, info in sorted(files.items()):
|
||||
size = info["size"]
|
||||
if not name.startswith("mengsan/") or "\\" in name or type(size) is not int or size < 0:
|
||||
raise ValueError(f"Invalid Mengsan manifest entry: {name}")
|
||||
if size > MAX_UNCOMPRESSED_BYTES:
|
||||
continue
|
||||
if group and group_bytes + size > MAX_UNCOMPRESSED_BYTES:
|
||||
groups.append(group)
|
||||
group = []
|
||||
group_bytes = 0
|
||||
group.append(name)
|
||||
group_bytes += size
|
||||
if group:
|
||||
groups.append(group)
|
||||
|
||||
output.mkdir(parents=True)
|
||||
parts = []
|
||||
for index, names in enumerate(groups, 1):
|
||||
part = output / f"mengsan-{tag}-part-{index:03}.zip"
|
||||
write_part(root, part, names, files)
|
||||
parts.append(part)
|
||||
return parts
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", required=True, type=Path)
|
||||
parser.add_argument("--out-dir", required=True, type=Path)
|
||||
parser.add_argument("--tag", required=True)
|
||||
args = parser.parse_args()
|
||||
parts = build_archives(args.root, args.out_dir, args.tag)
|
||||
print(f"Verified {len(parts)} Mengsan ZIP parts for {args.tag}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,61 @@
|
||||
import hashlib
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from build_mengsan_archives import build_archives
|
||||
|
||||
|
||||
class MengsanArchivesTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name) / "snapshot"
|
||||
self.output = Path(self.temp.name) / "archives"
|
||||
self.manifest = self.root / "dist/modules/mengsan.json"
|
||||
self.manifest.parent.mkdir(parents=True)
|
||||
|
||||
def write_snapshot(self, files):
|
||||
entries = {}
|
||||
for name, data in files.items():
|
||||
file = self.root / name
|
||||
file.parent.mkdir(parents=True, exist_ok=True)
|
||||
file.write_bytes(data)
|
||||
entries[name] = {"size": len(data), "sha256": hashlib.sha256(data).hexdigest()}
|
||||
self.manifest.write_text(json.dumps({
|
||||
"version": "2.0.2.3-rc.8", "module_id": "mengsan", "files": entries,
|
||||
}), encoding="utf-8")
|
||||
|
||||
def test_parts_cover_packable_files_once(self):
|
||||
first = b"a" * (3 * 1024**2)
|
||||
second = b"b" * (3 * 1024**2)
|
||||
self.write_snapshot({
|
||||
"mengsan/b": second,
|
||||
"mengsan/oversized": b"c" * (5 * 1024**2 + 1),
|
||||
"mengsan/a": first,
|
||||
})
|
||||
parts = build_archives(self.root, self.output, "v2.0.2.3-rc.8")
|
||||
self.assertEqual([part.name for part in parts], [
|
||||
"mengsan-v2.0.2.3-rc.8-part-001.zip", "mengsan-v2.0.2.3-rc.8-part-002.zip",
|
||||
])
|
||||
for part, name, data in zip(parts, ["mengsan/a", "mengsan/b"], [first, second], strict=True):
|
||||
with zipfile.ZipFile(part) as archive:
|
||||
self.assertEqual(archive.namelist(), [name])
|
||||
self.assertEqual(archive.read(name), data)
|
||||
|
||||
def test_reject_inconsistent_release(self):
|
||||
self.write_snapshot({"mengsan/a": b"a"})
|
||||
with self.assertRaisesRegex(ValueError, "version"):
|
||||
build_archives(self.root, self.output, "v2.0.2.3-rc.9")
|
||||
(self.root / "mengsan/a").write_bytes(b"b")
|
||||
with self.assertRaisesRegex(ValueError, "SHA-256"):
|
||||
build_archives(self.root, self.output, "v2.0.2.3-rc.8")
|
||||
|
||||
def test_reject_archive_over_download_limit(self):
|
||||
self.write_snapshot({"mengsan/a": b"a"})
|
||||
with patch("build_mengsan_archives.MAX_ARCHIVE_BYTES", 50):
|
||||
with self.assertRaisesRegex(ValueError, "ZIP size"):
|
||||
build_archives(self.root, self.output, "v2.0.2.3-rc.8")
|
||||
@@ -0,0 +1,352 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { createHash, webcrypto } from "node:crypto";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { resolve } from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
import { test } from "node:test";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { createContext, SourceTextModule, SyntheticModule } from "node:vm";
|
||||
|
||||
const engineRoot = process.env.NONAME_ROOT || fileURLToPath(new URL("../../../", import.meta.url));
|
||||
const { default: JSZip } = await import(pathToFileURL(resolve(engineRoot, "_virtual/index2.js")));
|
||||
const updaterSource = await readFile(new URL("../update.js", import.meta.url), "utf8");
|
||||
const version = "2.0.2.3";
|
||||
const tag = `v${version}`;
|
||||
const moduleEntry = "mengsan/register.js";
|
||||
const asset = "mengsan/assets/card.png";
|
||||
const assets = { [moduleEntry]: "export default 1;", [asset]: "card data" };
|
||||
const extensionRoot = "extension/术樱包/";
|
||||
const recordKey = "shuYing_mengsan_installation";
|
||||
|
||||
function info(text) {
|
||||
return { size: Buffer.byteLength(text), sha256: createHash("sha256").update(text).digest("hex") };
|
||||
}
|
||||
|
||||
function zip(files) {
|
||||
const archive = new JSZip();
|
||||
for (const [name, data] of Object.entries(files)) archive.file(name, data);
|
||||
return archive.generate({ type: "uint8array", compression: "DEFLATE" });
|
||||
}
|
||||
|
||||
async function setup({ source = "github", parts = [zip(assets)], releaseTag = tag,
|
||||
draft = false, failWrite = false, record, trial = true, transport = "browser",
|
||||
blocksBrowserAssets = false, canInflate = true, localVersion = version } = {}) {
|
||||
const github = source == "github";
|
||||
const api = github ? "https://api.github.com/repos/Shu-Ying/noname-shuying"
|
||||
: "https://gitea.diuse.work/api/v1/repos/Diuse/noname-shuying";
|
||||
const repository = github ? "https://github.com/Shu-Ying/noname-shuying"
|
||||
: "https://gitea.diuse.work/Diuse/noname-shuying";
|
||||
const raw = path => github
|
||||
? `https://raw.githubusercontent.com/Shu-Ying/noname-shuying/${tag}/${path}`
|
||||
: `${api}/raw/${path}?ref=${tag}`;
|
||||
const releaseUrl = `${api}/releases/tags/${tag}`;
|
||||
const requests = [];
|
||||
const writes = [];
|
||||
const alerts = [];
|
||||
const errors = [];
|
||||
const files = new Map();
|
||||
const config = { shuYing_update_source: source, shuYing_local_version: localVersion,
|
||||
shuYing_mengsan_zip_trial: trial, [recordKey]: record };
|
||||
const lib = { config, configprefix: "test_", node: {}, status: { reload: 0 } };
|
||||
const game = {
|
||||
checkFile(path, done) { done(files.has(path) ? 1 : -1); },
|
||||
createDir(path, done) { done(); },
|
||||
readFile(path, done, fail) {
|
||||
if (files.has(path)) done(files.get(path));
|
||||
else fail({ code: "ENOENT" });
|
||||
},
|
||||
writeFile(bytes, dir, name, done) {
|
||||
const path = `${dir}/${name}`;
|
||||
if (failWrite && path.includes("/new/mengsan/")) { done("disk is unwritable"); return; }
|
||||
writes.push({ path, afterRequests: requests.length });
|
||||
files.set(path, typeof bytes == "string" ? new TextEncoder().encode(bytes) : new Uint8Array(bytes));
|
||||
done();
|
||||
},
|
||||
removeFile(path, done) { files.delete(path); done(); },
|
||||
saveConfig(key, value) { config[key] = value; },
|
||||
reload2() {},
|
||||
};
|
||||
const modulePath = "dist/modules/mengsan.json";
|
||||
const rootManifest = { algorithm: "sha256", update_channels: true, version,
|
||||
files: { "extension.js": info("main") },
|
||||
modules: { mengsan: { entry: moduleEntry, manifest: modulePath } } };
|
||||
const moduleManifest = { algorithm: "sha256", module_id: "mengsan", version,
|
||||
files: Object.fromEntries(Object.entries(assets).map(([file, content]) => [file, info(content)])) };
|
||||
const attachments = parts?.map((part, index) => {
|
||||
const name = `mengsan-${tag}-part-${String(index + 1).padStart(3, "0")}.zip`;
|
||||
const url = `${repository}/releases/download/${tag}/${name}`;
|
||||
return { name, browser_download_url: url, size: part.size ?? (part.bytes?.length || part.length) };
|
||||
});
|
||||
const archiveAt = url => {
|
||||
const index = attachments?.findIndex(part => part.browser_download_url == url) ?? -1;
|
||||
return index < 0 ? null : parts[index].bytes || parts[index];
|
||||
};
|
||||
const window = {};
|
||||
const storage = new Map();
|
||||
const nativeRequests = [];
|
||||
if (transport == "node") {
|
||||
const redirect = "https://release-assets.githubusercontent.com/part.zip";
|
||||
window.require = name => {
|
||||
assert.equal(name, "https");
|
||||
return { get(url, callback) {
|
||||
const request = new EventEmitter();
|
||||
request.destroy = error => { if (error) request.emit("error", error); };
|
||||
queueMicrotask(() => {
|
||||
nativeRequests.push(String(url));
|
||||
const redirected = String(url) == redirect;
|
||||
const stream = Readable.from(redirected ? [archiveAt(attachments[0].browser_download_url)] : []);
|
||||
stream.statusCode = redirected ? 200 : 302;
|
||||
stream.headers = redirected ? {} : { location: redirect };
|
||||
callback(stream);
|
||||
stream.on("close", () => request.emit("close"));
|
||||
});
|
||||
return request;
|
||||
} };
|
||||
};
|
||||
}
|
||||
class TestFileReader {
|
||||
readAsArrayBuffer(file) { file.arrayBuffer().then(result => { this.result = result; this.onload(); }); }
|
||||
}
|
||||
if (transport == "cordova") {
|
||||
lib.device = "android";
|
||||
delete lib.node;
|
||||
storage.set("noname_inited", "file:///sandbox/");
|
||||
window.resolveLocalFileSystemURL = (root, done) => done({
|
||||
getFile(path, options, found, missing) {
|
||||
if (options.create && !files.has(path)) files.set(path, new Uint8Array());
|
||||
if (!files.has(path)) { missing({ code: 1 }); return; }
|
||||
found({ isFile: true, toURL: () => encodeURI(root + path),
|
||||
file: done => done(Object.assign(new Blob([files.get(path)]), { lastModified: 1 })),
|
||||
remove: done => { files.delete(path); done(); },
|
||||
createWriter(done) {
|
||||
done({ truncate() { this.onwriteend(); }, write(blob) {
|
||||
blob.arrayBuffer().then(bytes => {
|
||||
files.set(path, new Uint8Array(bytes));
|
||||
this.onwriteend();
|
||||
});
|
||||
} });
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
window.FileTransfer = class {
|
||||
download(url, target, done) {
|
||||
nativeRequests.push(url);
|
||||
const bytes = archiveAt(url);
|
||||
files.set(decodeURI(target).slice("file:///sandbox/".length), bytes);
|
||||
this.onprogress({ loaded: bytes.length });
|
||||
done();
|
||||
}
|
||||
abort() { throw new Error("Unexpected abort"); }
|
||||
};
|
||||
}
|
||||
const fetch = async url => {
|
||||
requests.push(url);
|
||||
if (url.startsWith(`${api}/tags?`)) return Response.json([{ name: tag }]);
|
||||
if (url == raw("dist/manifest.json")) return Response.json(rootManifest);
|
||||
if (url == raw(modulePath)) return Response.json(moduleManifest);
|
||||
if (url == releaseUrl) return parts ? Response.json({ tag_name: releaseTag, draft, assets: attachments })
|
||||
: new Response(null, { status: 404 });
|
||||
const partIndex = attachments?.findIndex(part => part.browser_download_url == url) ?? -1;
|
||||
if (partIndex >= 0) {
|
||||
if (blocksBrowserAssets) throw new TypeError("Failed to fetch");
|
||||
const part = parts[partIndex];
|
||||
if (part.retry && requests.filter(request => request == url).length == 1) {
|
||||
return new Response(null, { status: 503 });
|
||||
}
|
||||
return new Response(part.bytes || part);
|
||||
}
|
||||
for (const [file, content] of Object.entries({ ...assets, "extension.js": "main" })) {
|
||||
if (url == raw(file)) return new Response(content);
|
||||
}
|
||||
return new Response(null, { status: 404 });
|
||||
};
|
||||
const body = {
|
||||
appendChild(node) { node.parentNode = this; },
|
||||
removeChild(node) { node.parentNode = null; },
|
||||
};
|
||||
const context = createContext({
|
||||
AbortController, DecompressionStream: canInflate ? DecompressionStream : undefined,
|
||||
URL, TextDecoder, TextEncoder, Uint8Array, ArrayBuffer, setTimeout, clearTimeout,
|
||||
fetch, crypto: webcrypto, window, document: { body }, Blob, FileReader: TestFileReader,
|
||||
TypeError,
|
||||
localStorage: { getItem: key => storage.get(key), setItem: (key, value) => storage.set(key, value) },
|
||||
console: { error: error => errors.push(error), warn() {} },
|
||||
confirm: () => true, alert: message => alerts.push(message),
|
||||
});
|
||||
const engine = new SyntheticModule(["lib", "game", "get"], function () {
|
||||
this.setExport("lib", lib);
|
||||
this.setExport("game", game);
|
||||
this.setExport("get", { zip: callback => callback(new JSZip()) });
|
||||
}, { context });
|
||||
const module = new SourceTextModule(updaterSource, { context });
|
||||
await module.link(() => engine);
|
||||
await module.evaluate();
|
||||
const shuYing = { text: { style: {}, showPopover() {}, setAttribute() {}, matches: () => false } };
|
||||
return { updater: module.namespace.default, shuYing, requests, releaseUrl, raw, attachments, nativeRequests,
|
||||
writes, config, files, alerts, errors };
|
||||
}
|
||||
|
||||
async function install(options) {
|
||||
const result = await setup(options);
|
||||
await result.updater.manageMengsanModule(result.shuYing);
|
||||
return result;
|
||||
}
|
||||
|
||||
function assertInstalled(result) {
|
||||
assert.deepEqual(result.errors, []);
|
||||
assert.equal(result.config[recordKey]?.status, "installed", result.alerts.join("\n"));
|
||||
for (const [file, content] of Object.entries(assets)) {
|
||||
assert.equal(new TextDecoder().decode(result.files.get(extensionRoot + file)), content);
|
||||
}
|
||||
}
|
||||
|
||||
for (const source of ["github", "gitea"]) {
|
||||
test(`fresh install stages both parts from the selected ${source} release`, async () => {
|
||||
const result = await install({ source, parts: [zip({ [moduleEntry]: assets[moduleEntry] }), zip({ [asset]: assets[asset] })] });
|
||||
assertInstalled(result);
|
||||
const first = result.requests.indexOf(result.attachments[0].browser_download_url);
|
||||
const second = result.requests.indexOf(result.attachments[1].browser_download_url);
|
||||
assert.ok(first > result.requests.indexOf(result.releaseUrl));
|
||||
assert.ok(second > first);
|
||||
assert.ok(result.writes.find(write => write.path.endsWith(`/new/${moduleEntry}`)).afterRequests <= second);
|
||||
assert.ok(result.writes.find(write => write.path == extensionRoot + moduleEntry).afterRequests > second);
|
||||
assert.ok(!result.requests.includes(result.raw(moduleEntry)));
|
||||
assert.ok(!result.requests.includes(result.raw(asset)));
|
||||
});
|
||||
}
|
||||
|
||||
test("carries staged files through a hash mismatch and falls back within the same tag", async () => {
|
||||
const result = await install({ parts: [zip({ [moduleEntry]: assets[moduleEntry], [asset]: "bad! data" })] });
|
||||
assertInstalled(result);
|
||||
assert.equal(result.requests.filter(url => url == result.attachments[0].browser_download_url).length, 2);
|
||||
assert.ok(result.requests.includes(result.raw(asset)));
|
||||
assert.ok(!result.requests.includes(result.raw(moduleEntry)));
|
||||
});
|
||||
|
||||
test("retries a transient ZIP download error before using its contents", async () => {
|
||||
const result = await install({ parts: [{ bytes: zip(assets), retry: true }] });
|
||||
assertInstalled(result);
|
||||
assert.equal(result.requests.filter(url => url == result.attachments[0].browser_download_url).length, 2);
|
||||
assert.ok(!result.requests.includes(result.raw(asset)));
|
||||
});
|
||||
|
||||
for (const [description, options] of Object.entries({
|
||||
"missing release": { parts: null },
|
||||
"wrong release tag": { releaseTag: "v1.0.0.0" },
|
||||
"draft release": { draft: true },
|
||||
"invalid ZIP": { parts: [new Uint8Array([1, 2, 3])] },
|
||||
"ZIP contains unlisted entries": { parts: [zip({ ...assets, "../unexpected.js": "x" })] },
|
||||
"ZIP above the download budget": { parts: [new Uint8Array(6 * 1024**2 + 1)] },
|
||||
"response larger than its attachment metadata": { parts: [{ size: 1, bytes: zip(assets) }] },
|
||||
})) {
|
||||
test(`uses same-tag raw after ${description}`, async () => {
|
||||
const result = await install(options);
|
||||
assertInstalled(result);
|
||||
assert.ok(result.requests.includes(result.releaseUrl));
|
||||
assert.ok(result.requests.includes(result.raw(moduleEntry)));
|
||||
assert.ok(result.requests.includes(result.raw(asset)));
|
||||
assert.ok(!result.writes.some(write => write.path.includes("unexpected.js")));
|
||||
});
|
||||
}
|
||||
|
||||
test("a staging storage failure stops the ZIP install without raw retries", async () => {
|
||||
const result = await install({ failWrite: true });
|
||||
assert.equal(result.config[recordKey]?.status, "disabled");
|
||||
assert.match(result.alerts[0], /disk is unwritable/);
|
||||
assert.ok(result.requests.includes(result.attachments[0].browser_download_url));
|
||||
assert.ok(!result.requests.includes(result.raw(moduleEntry)));
|
||||
assert.ok(!result.files.has(extensionRoot + moduleEntry));
|
||||
});
|
||||
|
||||
test("restoring a legacy pending installation stays on raw", async () => {
|
||||
const result = await install({ record: { status: "repair", version, files: [moduleEntry, asset] } });
|
||||
assertInstalled(result);
|
||||
assert.ok(!result.requests.includes(result.releaseUrl));
|
||||
assert.ok(result.requests.includes(result.raw(asset)));
|
||||
});
|
||||
|
||||
test("restarts a known first installation using a fresh ZIP download", async () => {
|
||||
const result = await install({ record: { status: "installing", version, files: [moduleEntry, asset], freshInstall: true } });
|
||||
assertInstalled(result);
|
||||
assert.ok(result.requests.includes(result.attachments[0].browser_download_url));
|
||||
assert.ok(!result.requests.includes(result.raw(asset)));
|
||||
});
|
||||
|
||||
test("fresh install uses raw with the trial disabled", async () => {
|
||||
const result = await install({ trial: false });
|
||||
assertInstalled(result);
|
||||
assert.ok(!result.requests.includes(result.releaseUrl));
|
||||
assert.ok(result.requests.includes(result.raw(asset)));
|
||||
});
|
||||
|
||||
for (const transport of ["node", "cordova"]) {
|
||||
test(`uses ${transport} transfer for GitHub assets when browser Fetch cannot read them`, async () => {
|
||||
const result = await install({ transport, blocksBrowserAssets: true });
|
||||
assertInstalled(result);
|
||||
assert.equal(result.nativeRequests[0], result.attachments[0].browser_download_url);
|
||||
if (transport == "node") assert.equal(result.nativeRequests[1], "https://release-assets.githubusercontent.com/part.zip");
|
||||
assert.ok(!result.requests.includes(result.raw(asset)));
|
||||
assert.ok(!Array.from(result.files.keys()).some(path => path.endsWith(".zip")));
|
||||
});
|
||||
}
|
||||
|
||||
test("an unavailable browser attachment origin skips the remaining ZIP requests", async () => {
|
||||
const result = await install({ blocksBrowserAssets: true, parts: [zip(assets), zip(assets)] });
|
||||
assertInstalled(result);
|
||||
assert.ok(result.requests.includes(result.attachments[0].browser_download_url));
|
||||
assert.ok(!result.requests.includes(result.attachments[1].browser_download_url));
|
||||
assert.ok(result.requests.includes(result.raw(asset)));
|
||||
});
|
||||
|
||||
test("a WebView without streaming inflate uses raw before requesting ZIPs", async () => {
|
||||
const result = await install({ canInflate: false });
|
||||
assertInstalled(result);
|
||||
assert.ok(!result.requests.includes(result.releaseUrl));
|
||||
assert.ok(result.requests.includes(result.raw(asset)));
|
||||
});
|
||||
|
||||
test("downloads and extracts a ZIP generated by the release script", async () => {
|
||||
const temp = await mkdtemp(resolve(tmpdir(), "shuying-archive-test-"));
|
||||
try {
|
||||
const root = resolve(temp, "snapshot");
|
||||
const output = resolve(temp, "parts");
|
||||
const manifest = resolve(root, "dist/modules/mengsan.json");
|
||||
await mkdir(resolve(root, "dist/modules"), { recursive: true });
|
||||
await mkdir(resolve(root, "mengsan/assets"), { recursive: true });
|
||||
const fileInfo = {};
|
||||
for (const [file, content] of Object.entries(assets)) {
|
||||
await writeFile(resolve(root, file), content);
|
||||
fileInfo[file] = info(content);
|
||||
}
|
||||
await writeFile(manifest, JSON.stringify({ version, module_id: "mengsan", files: fileInfo }));
|
||||
const script = fileURLToPath(new URL("build_mengsan_archives.py", import.meta.url));
|
||||
execFileSync("python", ["-B", script, "--root", root, "--out-dir", output, "--tag", tag]);
|
||||
const bytes = await readFile(resolve(output, `mengsan-${tag}-part-001.zip`));
|
||||
const result = await install({ parts: [bytes] });
|
||||
assertInstalled(result);
|
||||
assert.ok(!result.requests.includes(result.raw(asset)));
|
||||
}
|
||||
finally { await rm(temp, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test("查漏补缺 of an installed module stays on raw with the trial enabled", async () => {
|
||||
const result = await setup({ record: { status: "installed", version, source: "github", files: [moduleEntry, asset] } });
|
||||
await result.updater.repairMissingFiles(result.shuYing);
|
||||
assertInstalled(result);
|
||||
assert.ok(result.requests.includes(result.raw(asset)));
|
||||
assert.ok(!result.requests.includes(result.releaseUrl));
|
||||
});
|
||||
|
||||
test("an installed module version update stays on raw with the trial enabled", async () => {
|
||||
const localVersion = "2.0.2.2";
|
||||
const result = await setup({ localVersion,
|
||||
record: { status: "installed", version: localVersion, source: "github", files: [moduleEntry, asset] } });
|
||||
await result.updater.checkVersion(result.shuYing);
|
||||
assertInstalled(result);
|
||||
assert.ok(result.requests.includes(result.raw(asset)));
|
||||
assert.ok(!result.requests.includes(result.releaseUrl));
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
import { lib, game } from "../../noname.js";
|
||||
import { lib, game, get } from "../../noname.js";
|
||||
|
||||
const giteaRepositoryApi = "https://gitea.diuse.work/api/v1/repos/Diuse/noname-shuying";
|
||||
const githubRepositoryApi = "https://api.github.com/repos/Shu-Ying/noname-shuying";
|
||||
const githubRawBase = "https://raw.githubusercontent.com/Shu-Ying/noname-shuying";
|
||||
const coreTempDir = "extension/术樱包/.update_tmp";
|
||||
const mengsanArchiveBytes = 6 * 1024 * 1024;
|
||||
const mengsanUncompressedBytes = 5 * 1024 * 1024;
|
||||
let fileMutationUncertain = false;
|
||||
const verifiedCacheKey = "shuYing_update_verified_files";
|
||||
const installedManifestKey = "shuYing_update_installation";
|
||||
@@ -472,6 +474,10 @@ async function waitForRetry(delay, signal) {
|
||||
}
|
||||
|
||||
async function fetchFile(path, tag, source, options = {}) {
|
||||
return fetchDownload(getRemoteUrl(tag, path, source), path, options);
|
||||
}
|
||||
|
||||
async function fetchDownload(url, label, options = {}) {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
if (options.signal?.aborted) throw options.signal.reason || new Error("下载已停止");
|
||||
const controller = new AbortController();
|
||||
@@ -480,22 +486,24 @@ async function fetchFile(path, tag, source, options = {}) {
|
||||
let timer, reader, timedOut = false;
|
||||
const resetTimeout = () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => { timedOut = true; controller.abort(new Error(`${path} 下载超时`)); }, 60000);
|
||||
timer = setTimeout(() => { timedOut = true; controller.abort(new Error(`${label} 下载超时`)); }, 60000);
|
||||
};
|
||||
options.onProgress?.(0, 0);
|
||||
try {
|
||||
resetTimeout();
|
||||
const response = await fetch(getRemoteUrl(tag, path, source), { signal: controller.signal });
|
||||
const response = await (options.request || fetch)(url, { signal: controller.signal });
|
||||
reader = response.body?.getReader?.();
|
||||
if (!response.ok) {
|
||||
const error = new Error(`${path} 下载失败:${response.status}`);
|
||||
const error = new Error(`${label} 下载失败:${response.status}`);
|
||||
error.status = response.status;
|
||||
error.retryable = [408, 429, 500, 502, 503, 504].includes(response.status);
|
||||
throw error;
|
||||
}
|
||||
if (!reader) {
|
||||
if (options.requireStream) throw new Error(`${label} 无法限制流式下载大小`);
|
||||
const data = await response.arrayBuffer();
|
||||
if (Number.isSafeInteger(options.size) && data.byteLength > options.size) {
|
||||
throw new Error(`${path} 下载数据超过清单大小`);
|
||||
throw new Error(`${label} 下载数据超过预期大小`);
|
||||
}
|
||||
options.onProgress?.(data.byteLength, data.byteLength);
|
||||
return data;
|
||||
@@ -507,7 +515,7 @@ async function fetchFile(path, tag, source, options = {}) {
|
||||
if (done) break;
|
||||
loaded += value.byteLength;
|
||||
if (Number.isSafeInteger(options.size) && loaded > options.size) {
|
||||
throw new Error(`${path} 下载数据超过清单大小`);
|
||||
throw new Error(`${label} 下载数据超过预期大小`);
|
||||
}
|
||||
chunks.push(value);
|
||||
options.onProgress?.(loaded, value.byteLength);
|
||||
@@ -521,7 +529,7 @@ async function fetchFile(path, tag, source, options = {}) {
|
||||
catch (error) {
|
||||
if (options.signal?.aborted || attempt >= 2
|
||||
|| !(timedOut || error?.retryable || error instanceof TypeError)) throw error;
|
||||
await addLog(options.shuYing, `下载重试 ${attempt + 1}/2:${path};${getErrorMessage(error)}`);
|
||||
await addLog(options.shuYing, `下载重试 ${attempt + 1}/2:${label};${getErrorMessage(error)}`);
|
||||
}
|
||||
finally {
|
||||
clearTimeout(timer);
|
||||
@@ -532,6 +540,215 @@ async function fetchFile(path, tag, source, options = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
async function getMengsanReleaseParts(manifest, shuYing) {
|
||||
const github = manifest.source == "github";
|
||||
const api = github ? githubRepositoryApi : giteaRepositoryApi;
|
||||
const downloadOrigin = github ? "https://github.com" : new URL(giteaRepositoryApi).origin;
|
||||
const tag = manifest.tag_name;
|
||||
const data = await fetchDownload(`${api}/releases/tags/${encodeURIComponent(tag)}`, "梦三发布附件列表",
|
||||
{ size: 1024 * 1024, requireStream: true, shuYing });
|
||||
const release = JSON.parse(new TextDecoder().decode(data));
|
||||
if (release.tag_name !== tag || release.draft !== false || !Array.isArray(release.assets)) {
|
||||
throw new Error("梦三发布附件列表与当前标签不符");
|
||||
}
|
||||
|
||||
const prefix = `mengsan-${tag}-part-`;
|
||||
const parts = [];
|
||||
for (const asset of release.assets) {
|
||||
const name = asset?.name;
|
||||
if (typeof name != "string" || !name.startsWith(prefix) || !/^\d{3,}\.zip$/.test(name.slice(prefix.length))
|
||||
|| !Number.isSafeInteger(asset.size) || asset.size <= 0 || asset.size > mengsanArchiveBytes) continue;
|
||||
try {
|
||||
const url = new URL(asset.browser_download_url);
|
||||
if (url.origin == downloadOrigin && !url.username && !url.password) {
|
||||
parts.push({ name, size: asset.size, url: url.href });
|
||||
}
|
||||
}
|
||||
catch {} // Ignore unusable attachment URLs.
|
||||
}
|
||||
return parts.sort((left, right) => left.name.localeCompare(right.name, "en", { numeric: true }));
|
||||
}
|
||||
|
||||
function requestNodeArchive(url, { signal }, redirects = 5) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = window.require("https").get(url, response => {
|
||||
const status = response.statusCode;
|
||||
if (status >= 300 && status < 400 && response.headers.location) {
|
||||
response.destroy();
|
||||
try {
|
||||
const next = new URL(response.headers.location, url);
|
||||
if (!redirects || next.protocol != "https:" || next.username || next.password) {
|
||||
throw new Error("梦三分包重定向无效");
|
||||
}
|
||||
resolve(requestNodeArchive(next.href, { signal }, redirects - 1));
|
||||
}
|
||||
catch (error) { reject(error); }
|
||||
return;
|
||||
}
|
||||
const iterator = response[Symbol.asyncIterator]();
|
||||
resolve({ status, ok: status >= 200 && status < 300, body: {
|
||||
getReader: () => ({
|
||||
async read() {
|
||||
try { return await iterator.next(); }
|
||||
catch (error) { error.retryable = true; throw error; }
|
||||
},
|
||||
async cancel() { response.destroy(); },
|
||||
}),
|
||||
} });
|
||||
});
|
||||
const abort = () => request.destroy(signal.reason);
|
||||
request.once("error", error => { error.retryable = true; reject(error); });
|
||||
request.once("close", () => signal.removeEventListener("abort", abort));
|
||||
if (signal.aborted) abort();
|
||||
else signal.addEventListener("abort", abort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
async function downloadCordovaArchive(part, target, onProgress, shuYing) {
|
||||
try {
|
||||
const entry = await cordovaEntry(target, true);
|
||||
const transfer = new window.FileTransfer();
|
||||
await new Promise((resolve, reject) => {
|
||||
let loaded = 0, timer, cancelError, settled = false;
|
||||
const finish = error => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
if (cancelError || error) reject(cancelError || operationError(error) || new Error("梦三分包下载失败"));
|
||||
else resolve();
|
||||
};
|
||||
const cancel = error => {
|
||||
clearTimeout(timer);
|
||||
cancelError = error;
|
||||
timer = setTimeout(() => finish(cancelError), 5000);
|
||||
try { transfer.abort(); }
|
||||
catch { finish(cancelError); }
|
||||
};
|
||||
const resetTimeout = () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => cancel(new Error("梦三分包下载超时")), 60000);
|
||||
};
|
||||
transfer.onprogress = event => {
|
||||
if (settled || cancelError) return;
|
||||
if (event.loaded > part.size) { cancel(new Error("梦三分包超过预期大小")); return; }
|
||||
onProgress(event.loaded, Math.max(0, event.loaded - loaded));
|
||||
loaded = event.loaded;
|
||||
resetTimeout();
|
||||
};
|
||||
resetTimeout();
|
||||
try { transfer.download(part.url, entry.toURL(), () => finish(), error => finish(error)); }
|
||||
catch (error) { finish(error); }
|
||||
});
|
||||
if ((await fileMetadata(target))?.size !== part.size) throw new Error("下载大小与发布附件不符");
|
||||
return await readFile(target);
|
||||
}
|
||||
finally {
|
||||
try { await removeFile(target); }
|
||||
catch (error) { addLog(shuYing, `梦三分包临时文件清理失败:${getErrorMessage(error)}`); }
|
||||
}
|
||||
}
|
||||
|
||||
async function readMengsanZipEntry(entry, size) {
|
||||
// JSZip 2.7 keeps the compressed entry lazy after load().
|
||||
const data = entry._data;
|
||||
const compressed = toUint8Array(data.getCompressedContent());
|
||||
if (data.compressionMethod == "\x00\x00") return compressed;
|
||||
if (data.compressionMethod != "\x08\x00") {
|
||||
throw new Error("当前环境不支持流式解压梦三分包");
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(size);
|
||||
const reader = new Blob([compressed]).stream().pipeThrough(new DecompressionStream("deflate-raw")).getReader();
|
||||
let offset = 0;
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (offset + value.byteLength > size) throw new Error("梦三 ZIP 条目超过清单大小");
|
||||
bytes.set(value, offset);
|
||||
offset += value.byteLength;
|
||||
}
|
||||
if (offset !== size) throw new Error("梦三 ZIP 条目未达到清单大小");
|
||||
return bytes;
|
||||
}
|
||||
finally { await reader.cancel().catch(() => {}); }
|
||||
}
|
||||
|
||||
async function unpackMengsanPart(data, manifest, remaining, stageVerified) {
|
||||
let entries, expandedSize = 0;
|
||||
try {
|
||||
get.zip(zip => { entries = Object.values(zip.load(data).files); });
|
||||
for (const entry of entries) {
|
||||
const size = entry._data?.uncompressedSize;
|
||||
if (entry.dir || !Object.hasOwn(manifest.files, entry.name) || size !== manifest.files[entry.name].size) {
|
||||
throw new Error(`梦三 ZIP 条目与清单不符:${entry.name}`);
|
||||
}
|
||||
expandedSize += size;
|
||||
}
|
||||
if (!entries.length || expandedSize > mengsanUncompressedBytes) throw new Error("梦三 ZIP 展开大小无效");
|
||||
}
|
||||
catch (error) { return error; }
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!remaining.has(entry.name)) continue;
|
||||
let bytes;
|
||||
try {
|
||||
bytes = await readMengsanZipEntry(entry, manifest.files[entry.name].size);
|
||||
await verifyFile(entry.name, bytes, manifest);
|
||||
}
|
||||
catch (error) { return error; }
|
||||
// A storage failure must reach the existing installation recovery path.
|
||||
await stageVerified(entry.name, bytes);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function stageMengsanArchives(shuYing, manifest, operationRoot, remaining, stageVerified, progress) {
|
||||
let parts;
|
||||
try { parts = await getMengsanReleaseParts(manifest, shuYing); }
|
||||
catch (error) {
|
||||
addLog(shuYing, `无法获取梦三分包,改为逐文件下载:${getErrorMessage(error)}`);
|
||||
return;
|
||||
}
|
||||
addLog(shuYing, `梦三分包:${manifest.source} ${manifest.tag_name},${parts.length} 包`);
|
||||
const nativeMobile = hasCordovaFiles() && typeof window.FileTransfer == "function";
|
||||
const request = lib.node && typeof window.require == "function" ? requestNodeArchive : null;
|
||||
for (const part of parts) {
|
||||
if (!remaining.size) break;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
let data;
|
||||
try {
|
||||
const onProgress = (loaded, delta) => progress.archive(part.name, delta);
|
||||
data = nativeMobile
|
||||
? await downloadCordovaArchive(part, `${operationRoot}/${part.name}`, onProgress, shuYing)
|
||||
: await fetchDownload(part.url, part.name, { size: part.size, requireStream: true,
|
||||
request, onProgress, shuYing });
|
||||
}
|
||||
catch (error) {
|
||||
addLog(shuYing, `梦三分包下载失败:${part.name};${getErrorMessage(error)}`);
|
||||
if (nativeMobile && !attempt) continue;
|
||||
if (error.status !== 404) return;
|
||||
break;
|
||||
}
|
||||
const error = data.byteLength === part.size
|
||||
? await unpackMengsanPart(data, manifest, remaining, stageVerified)
|
||||
: new Error("下载大小与发布附件不符");
|
||||
if (!error) break;
|
||||
const action = attempt ? "回退逐文件" : "重试分包";
|
||||
addLog(shuYing, `${action}:${part.name};${getErrorMessage(error)}`);
|
||||
}
|
||||
}
|
||||
if (remaining.size) addLog(shuYing, `梦三分包未覆盖 ${remaining.size} 个文件,继续逐文件下载`);
|
||||
}
|
||||
|
||||
function canUseMengsanArchives() {
|
||||
if (typeof get.zip != "function" || typeof Blob != "function" || typeof Blob.prototype.stream != "function"
|
||||
|| typeof DecompressionStream != "function") return false;
|
||||
try { new DecompressionStream("deflate-raw"); }
|
||||
catch { return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
function downloadProgress(shuYing, files, manifest) {
|
||||
const received = new Map();
|
||||
const totalBytes = files.reduce((sum, file) => sum + manifest.files[file].size, 0);
|
||||
@@ -550,6 +767,7 @@ function downloadProgress(shuYing, files, manifest) {
|
||||
transferred += delta;
|
||||
render(file);
|
||||
},
|
||||
archive(name, delta) { transferred += delta; render(name); },
|
||||
complete(file) { completed++; render(file, completed == files.length); },
|
||||
finish() { addLog(shuYing, `下载及准备完成:${files.length} 个文件,${formatBytes(totalBytes)},用时 ${((Date.now() - started) / 1000).toFixed(1)} 秒`); },
|
||||
};
|
||||
@@ -1311,7 +1529,7 @@ async function getPreviousMengsanManifest(rootManifest = null) {
|
||||
}
|
||||
|
||||
async function installMengsanFiles(shuYing, manifest, files, previousManifest = null,
|
||||
verifyAll = true) {
|
||||
verifyAll = true, freshInstall = false) {
|
||||
assertMutationReady();
|
||||
const previousRecord = getMengsanRecord();
|
||||
const currentFiles = getManifestFileKeys(manifest);
|
||||
@@ -1322,10 +1540,12 @@ async function installMengsanFiles(shuYing, manifest, files, previousManifest =
|
||||
files: uniqueManifestList([...oldFiles, ...currentFiles, ...getManifestRemoveFiles(manifest)]),
|
||||
recoveryDirectory: operationRoot,
|
||||
};
|
||||
if (freshInstall) pending.freshInstall = true;
|
||||
await saveMengsanRecord(pending); // Disable loading before the first filesystem mutation.
|
||||
let filesApplied = false;
|
||||
try {
|
||||
await updateAllFiles(shuYing, manifest, files, operationRoot);
|
||||
const useArchives = freshInstall && lib.config.shuYing_mengsan_zip_trial === true && canUseMengsanArchives();
|
||||
await updateAllFiles(shuYing, manifest, files, operationRoot, useArchives);
|
||||
filesApplied = true;
|
||||
const verification = verifyAll ? manifest : { ...manifest,
|
||||
files: Object.fromEntries(files.map(file => [file, manifest.files[file]])),
|
||||
@@ -1408,7 +1628,7 @@ function newOperationRoot() {
|
||||
return `${coreTempDir}/${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
}
|
||||
|
||||
async function updateAllFiles(shuYing, manifest, files, operationRoot = newOperationRoot()) {
|
||||
async function updateAllFiles(shuYing, manifest, files, operationRoot = newOperationRoot(), useArchives = false) {
|
||||
assertMutationReady();
|
||||
if (typeof game.writeFile != "function") {
|
||||
throw new Error("当前环境不支持写入文件");
|
||||
@@ -1433,7 +1653,19 @@ async function updateAllFiles(shuYing, manifest, files, operationRoot = newOpera
|
||||
await createFolders(`${oldRoot}/`, [...files, ...obsoleteFiles]);
|
||||
|
||||
const progress = downloadProgress(shuYing, files, manifest);
|
||||
await runFilePool(files, async (file, index, signal) => {
|
||||
let rawFiles = files;
|
||||
if (useArchives) {
|
||||
const remaining = new Set(files);
|
||||
await stageMengsanArchives(shuYing, manifest, operationRoot, remaining, async (file, bytes) => {
|
||||
staged.add(file);
|
||||
await writeTargetFile(bytes, `${newRoot}/${file}`);
|
||||
remaining.delete(file);
|
||||
progress.receive(file, bytes.byteLength, 0);
|
||||
progress.complete(file);
|
||||
}, progress);
|
||||
rawFiles = Array.from(remaining);
|
||||
}
|
||||
await runFilePool(rawFiles, async (file, index, signal) => {
|
||||
staged.add(file);
|
||||
await downloadFile(file, `${newRoot}/${file}`, manifest, {
|
||||
signal, shuYing, onProgress: (loaded, delta) => progress.receive(file, loaded, delta),
|
||||
@@ -1824,7 +2056,8 @@ async function manageMengsanModule(shuYing) {
|
||||
setProgress(shuYing, {
|
||||
title: "安装梦三模式", status: "准备下载", current: 0, total: files.length * 2,
|
||||
});
|
||||
await installMengsanFiles(shuYing, moduleManifest, files, previous);
|
||||
const freshInstall = !pendingInstall || record.freshInstall === true;
|
||||
await installMengsanFiles(shuYing, moduleManifest, files, previous, true, freshInstall);
|
||||
alert("梦三模式安装完成,请重启游戏生效。");
|
||||
}
|
||||
catch (error) {
|
||||
|
||||
Reference in New Issue
Block a user