dsh-plugin-mesh 0.0.0-stage → 0.3.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1199 -2
  3. package/client/client.js +958 -0
  4. package/cordis.patch.yml +80 -0
  5. package/install.sh +142 -0
  6. package/lib/_rehearsal-peer.mjs +229 -0
  7. package/lib/_selftest-capabilities.mjs +631 -0
  8. package/lib/_selftest-client.mjs +249 -0
  9. package/lib/_selftest-discovery.mjs +51 -0
  10. package/lib/_selftest-newsession.mjs +124 -0
  11. package/lib/_selftest-prompt.mjs +97 -0
  12. package/lib/_selftest-tsnet-live.mjs +169 -0
  13. package/lib/_selftest-tsnet-tailnet.mjs +418 -0
  14. package/lib/_selftest-tsnet.mjs +647 -0
  15. package/lib/capabilities.js +786 -0
  16. package/lib/conversation.js +59 -0
  17. package/lib/discovery.js +744 -0
  18. package/lib/identity.js +136 -0
  19. package/lib/index.js +2079 -0
  20. package/lib/prompt.js +50 -0
  21. package/lib/scan.js +118 -0
  22. package/lib/tsnet/bridge.js +71 -0
  23. package/lib/tsnet/checksums.js +19 -0
  24. package/lib/tsnet/download.js +384 -0
  25. package/lib/tsnet/manager.js +655 -0
  26. package/package.json +118 -4
  27. package/scripts/__pycache__/mesh-tsnet-merge.cpython-312.pyc +0 -0
  28. package/scripts/_selftest-tsnet-merge.py +168 -0
  29. package/scripts/build-sidecar.sh +372 -0
  30. package/scripts/check-loadable.mjs +154 -0
  31. package/scripts/check-tarball.mjs +106 -0
  32. package/scripts/check-tdz.mjs +78 -0
  33. package/scripts/check-version.mjs +32 -0
  34. package/scripts/fix-android-tls-align.py +87 -0
  35. package/scripts/mesh-tsnet-merge.py +345 -0
  36. package/scripts/mesh-tsnet-onboarding.md +98 -0
  37. package/scripts/publish-assets.py +213 -0
  38. package/scripts/push-via-api.py +262 -0
  39. package/scripts/release-plugin.sh +129 -0
  40. package/scripts/restart-dsh.sh +308 -0
  41. package/scripts/submit-to-awesome.py +212 -0
  42. package/scripts/verify-lan-mirror.mjs +57 -0
  43. package/sidecar/androidbin_linux.go +39 -0
  44. package/sidecar/androidnet_linux.go +414 -0
  45. package/sidecar/androidnet_other.go +15 -0
  46. package/sidecar/go.mod +51 -0
  47. package/sidecar/go.sum +239 -0
  48. package/sidecar/main.go +850 -0
@@ -0,0 +1,262 @@
1
+ #!/usr/bin/env python3
2
+ """通过 GitHub REST API 推送 git 提交。
3
+
4
+ 为什么需要它:这台机器上 git-over-https 到 github.com 会被 Connection reset
5
+ (实测数次),SSH 密钥也没注册到账号;但 api.github.com 是通的(发布 release
6
+ 走的就是它)。
7
+
8
+ 关键在于**精确复刻**而不是"用文件内容新建一个提交":git 的 commit SHA 是
9
+ (tree, parents, author, committer, message) 的哈希,只要这些字段逐一相同,
10
+ API 造出来的 commit 就会得到**与本地完全一致的 SHA**。因此远端历史不会和
11
+ 本地分裂,之后 git fetch/push 恢复时不会冲突。
12
+
13
+ 每一步都会断言 SHA 与本地一致;对不上就中止、绝不更新远端 ref。
14
+
15
+ 用法:
16
+ scripts/push-via-api.py # 推送 origin/main..HEAD
17
+ scripts/push-via-api.py --dry-run # 只演练,不写远端
18
+ scripts/push-via-api.py --remote origin --branch main
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import base64
24
+ import datetime
25
+ import json
26
+ import os
27
+ import re
28
+ import subprocess
29
+ import sys
30
+ import urllib.error
31
+ import urllib.request
32
+
33
+ API = "https://api.github.com"
34
+
35
+
36
+ def die(msg: str) -> None:
37
+ print(f"✗ {msg}", file=sys.stderr)
38
+ sys.exit(1)
39
+
40
+
41
+ def git(*args: str, binary: bool = False, strip: bool = True):
42
+ """跑一条 git 命令并返回输出。
43
+
44
+ strip=False 时保留原始文本:commit 对象结尾的换行是内容的一部分,
45
+ 去掉它就会算出不同的 SHA。
46
+
47
+ 强制 `core.quotepath=false`:git 默认把非 ASCII 路径转义成
48
+ `"\\350\\256\\276..."` 这种形式输出,脚本再拿它去 cat-file / ls-tree
49
+ 就找不到文件了(实测挂在中文文件名上)。
50
+ """
51
+ proc = subprocess.run(["git", "-c", "core.quotepath=false", *args], capture_output=True)
52
+ if proc.returncode != 0:
53
+ die(f"git {' '.join(args)} 失败:{proc.stderr.decode('utf-8', 'replace').strip()}")
54
+ if binary:
55
+ return proc.stdout
56
+ text = proc.stdout.decode("utf-8", "replace")
57
+ return text.rstrip("\n") if strip else text
58
+
59
+
60
+ def read_token() -> str:
61
+ """从 ~/.git-credentials 取 github.com 的 token。"""
62
+ path = os.path.expanduser("~/.git-credentials")
63
+ if not os.path.exists(path):
64
+ die(f"找不到 {path}")
65
+ for line in open(path, encoding="utf-8"):
66
+ m = re.match(r"https://([^:]+):([^@]+)@github\.com\s*$", line.strip())
67
+ if m:
68
+ return m.group(2)
69
+ die("~/.git-credentials 里没有 github.com 的 https 凭证")
70
+
71
+
72
+ class Client:
73
+ def __init__(self, token: str, dry_run: bool = False):
74
+ self.token = token
75
+ self.dry_run = dry_run
76
+ self.calls = 0
77
+
78
+ def __call__(self, method: str, path: str, payload=None):
79
+ if self.dry_run and method != "GET":
80
+ print(f" [dry-run] {method} {path}")
81
+ return {}
82
+ url = path if path.startswith("http") else f"{API}{path}"
83
+ data = json.dumps(payload).encode("utf-8") if payload is not None else None
84
+ req = urllib.request.Request(url, data=data, method=method)
85
+ req.add_header("Authorization", f"token {self.token}")
86
+ req.add_header("Accept", "application/vnd.github+json")
87
+ if data:
88
+ req.add_header("Content-Type", "application/json")
89
+ self.calls += 1
90
+ try:
91
+ with urllib.request.urlopen(req, timeout=60) as resp:
92
+ body = resp.read().decode("utf-8")
93
+ return json.loads(body) if body.strip() else {}
94
+ except urllib.error.HTTPError as e:
95
+ detail = e.read().decode("utf-8", "replace")
96
+ die(f"{method} {path} → HTTP {e.code}\n{detail[:600]}")
97
+ except urllib.error.URLError as e:
98
+ die(f"{method} {path} → 网络错误 {e.reason}")
99
+
100
+
101
+ def parse_commit(sha: str) -> dict:
102
+ """把 git commit 对象拆成 API 需要的字段。"""
103
+ raw = git("cat-file", "commit", sha, strip=False)
104
+ head, _, message = raw.partition("\n\n")
105
+ out = {"tree": None, "parents": [], "author": None, "committer": None, "message": message}
106
+
107
+ ident = re.compile(r"^(.*) <(.*)> (\d+) ([+-]\d{4})$")
108
+ for line in head.split("\n"):
109
+ if line.startswith("tree "):
110
+ out["tree"] = line[5:].strip()
111
+ elif line.startswith("parent "):
112
+ out["parents"].append(line[7:].strip())
113
+ elif line.startswith("author "):
114
+ m = ident.match(line[7:].strip())
115
+ if not m:
116
+ die(f"看不懂 author 行:{line}")
117
+ out["author"] = {"name": m.group(1), "email": m.group(2), "date": f"{m.group(3)} {m.group(4)}"}
118
+ elif line.startswith("committer "):
119
+ m = ident.match(line[10:].strip())
120
+ if not m:
121
+ die(f"看不懂 committer 行:{line}")
122
+ out["committer"] = {"name": m.group(1), "email": m.group(2), "date": f"{m.group(3)} {m.group(4)}"}
123
+ if not out["tree"] or not out["author"] or not out["committer"]:
124
+ die(f"commit {sha} 缺少必要字段")
125
+ # API 的 date 要 ISO8601;git 给的是 "epoch +0800"
126
+ for key in ("author", "committer"):
127
+ epoch, tz = out[key]["date"].split(" ")
128
+ sign = 1 if tz[0] == "+" else -1
129
+ offset = f"{tz[0]}{tz[1:3]}:{tz[3:5]}"
130
+ iso = datetime.datetime.fromtimestamp(
131
+ int(epoch),
132
+ datetime.timezone(datetime.timedelta(hours=sign * int(tz[1:3]), minutes=sign * int(tz[3:5]))),
133
+ )
134
+ out[key]["date"] = iso.strftime("%Y-%m-%dT%H:%M:%S") + offset
135
+ return out
136
+
137
+
138
+ def changed_paths(parent: str, sha: str) -> list[tuple[str, str]]:
139
+ """返回 [(status, path)],status ∈ A/M/D/T。"""
140
+ raw = git("diff-tree", "-r", "--name-status", "--no-renames", parent, sha)
141
+ out = []
142
+ for line in raw.split("\n"):
143
+ if not line.strip():
144
+ continue
145
+ parts = line.split("\t")
146
+ out.append((parts[0][0], parts[-1]))
147
+ return out
148
+
149
+
150
+ def main() -> int:
151
+ ap = argparse.ArgumentParser()
152
+ ap.add_argument("--remote", default="origin")
153
+ ap.add_argument("--branch", default=None, help="默认取当前分支")
154
+ ap.add_argument("--dry-run", action="store_true")
155
+ args = ap.parse_args()
156
+
157
+ branch = args.branch or git("rev-parse", "--abbrev-ref", "HEAD")
158
+ head = git("rev-parse", "HEAD")
159
+
160
+ # 远端 URL → owner/repo
161
+ url = git("remote", "get-url", args.remote)
162
+ m = re.search(r"github\.com[:/]([^/]+)/([^/\s]+?)(?:\.git)?$", url)
163
+ if not m:
164
+ die(f"看不懂远端 URL:{url}")
165
+ owner, repo = m.group(1), m.group(2)
166
+ print(f"仓库 : {owner}/{repo}")
167
+ print(f"分支 : {branch}")
168
+
169
+ ref = Client(read_token(), args.dry_run)("GET", f"/repos/{owner}/{repo}/git/ref/heads/{branch}")
170
+ if not ref or "object" not in ref:
171
+ die(f"取不到远端 ref(分支 {branch} 是否已存在?)")
172
+ remote_head = ref["object"]["sha"]
173
+ print(f"远端头 : {remote_head[:12]}")
174
+ print(f"本地头 : {head[:12]}")
175
+
176
+ if remote_head == head:
177
+ print("✓ 已经一致,无需推送")
178
+ return 0
179
+
180
+ # 远端头必须是本地头的祖先,否则本地落后或有分叉 —— 先让用户自己处理
181
+ if subprocess.run(["git", "merge-base", "--is-ancestor", remote_head, head]).returncode != 0:
182
+ die("远端头不是本地头的祖先(历史分叉或本地落后)。请先 git fetch/reset 再试。")
183
+
184
+ commits = [c for c in git("rev-list", "--reverse", f"{remote_head}..{head}").split("\n") if c]
185
+ print(f"待推送 : {len(commits)} 个提交\n")
186
+
187
+ client = Client(read_token(), args.dry_run)
188
+ for idx, sha in enumerate(commits, 1):
189
+ info = parse_commit(sha)
190
+ subject = info["message"].split("\n", 1)[0]
191
+ print(f"[{idx}/{len(commits)}] {sha[:12]} {subject}")
192
+
193
+ parent = info["parents"][0] if info["parents"] else None
194
+ base_tree = git("rev-parse", f"{parent}^{{tree}}") if parent else None
195
+ if not parent:
196
+ die("不支持推送根提交(仓库应当已有历史)")
197
+
198
+ tree_entries = []
199
+ for status, path in changed_paths(parent, sha):
200
+ if status == "D":
201
+ tree_entries.append({"path": path, "mode": "100644", "type": "blob", "sha": None})
202
+ continue
203
+ blob = git("cat-file", "blob", f"{sha}:{path}", binary=True)
204
+ created = client("POST", f"/repos/{owner}/{repo}/git/blobs",
205
+ {"content": base64.b64encode(blob).decode("ascii"), "encoding": "base64"})
206
+ if not args.dry_run:
207
+ expect = git("rev-parse", f"{sha}:{path}")
208
+ if created.get("sha") != expect:
209
+ die(f"blob SHA 不一致:{path}\n API={created.get('sha')}\n 本地={expect}")
210
+ mode = git("ls-tree", sha, "--", path).split()[0] # "100644 blob <sha>\t<path>"
211
+ tree_entries.append({"path": path, "mode": mode, "type": "blob", "sha": created.get("sha")})
212
+ print(f" blob {path}")
213
+
214
+ new_tree = client("POST", f"/repos/{owner}/{repo}/git/trees", {"base_tree": base_tree, "tree": tree_entries})
215
+ if not args.dry_run and new_tree.get("sha") != info["tree"]:
216
+ die(f"tree SHA 不一致:\n API={new_tree.get('sha')}\n 本地={info['tree']}\n"
217
+ f"(可能是被 .gitignore 影响,或路径含特殊字符)")
218
+
219
+ created_commit = client("POST", f"/repos/{owner}/{repo}/git/commits", {
220
+ "message": info["message"],
221
+ "tree": new_tree.get("sha", info["tree"]),
222
+ "parents": info["parents"],
223
+ "author": info["author"],
224
+ "committer": info["committer"],
225
+ })
226
+ if not args.dry_run and created_commit.get("sha") != sha:
227
+ # 出问题时把 API 侧的 commit 拉回来逐字段对比,不让人瞎猜
228
+ got = client("GET", f"/repos/{owner}/{repo}/git/commits/{created_commit.get('sha')}")
229
+ print("\n 字段对比(本地 vs API):", file=sys.stderr)
230
+ pairs = (
231
+ ("tree", info["tree"], (got.get("tree") or {}).get("sha")),
232
+ ("parents", info["parents"], [p["sha"] for p in got.get("parents", [])]),
233
+ ("author.name", info["author"]["name"], (got.get("author") or {}).get("name")),
234
+ ("author.email", info["author"]["email"], (got.get("author") or {}).get("email")),
235
+ ("author.date", info["author"]["date"], (got.get("author") or {}).get("date")),
236
+ ("committer.name", info["committer"]["name"], (got.get("committer") or {}).get("name")),
237
+ ("committer.date", info["committer"]["date"], (got.get("committer") or {}).get("date")),
238
+ ("message", repr(info["message"][-60:]), repr((got.get("message") or "")[-60:])),
239
+ )
240
+ for label, local_v, api_v in pairs:
241
+ flag = " " if local_v == api_v else "≠ "
242
+ print(f" {flag}{label:16} 本地={local_v!r}", file=sys.stderr)
243
+ if local_v != api_v:
244
+ print(f" {'':16} API ={api_v!r}", file=sys.stderr)
245
+ die(f"commit SHA 不一致:\n API={created_commit.get('sha')}\n 本地={sha}")
246
+ print(f" commit 复刻一致 ✓")
247
+
248
+ if not args.dry_run:
249
+ client("PATCH", f"/repos/{owner}/{repo}/git/refs/heads/{branch}",
250
+ {"sha": created_commit["sha"], "force": False})
251
+
252
+ if not args.dry_run:
253
+ # 本地把远端跟踪 ref 对齐,这样 git status 立刻显示同步、不会误以为还要推
254
+ git("update-ref", f"refs/remotes/{args.remote}/{branch}", head)
255
+ print(f"\n✓ 已推送 {len(commits)} 个提交,并把 refs/remotes/{args.remote}/{branch} 对齐到 {head[:12]}")
256
+ else:
257
+ print("\n(dry-run,未写入远端)")
258
+ return 0
259
+
260
+
261
+ if __name__ == "__main__":
262
+ sys.exit(main())
@@ -0,0 +1,129 @@
1
+ #!/usr/bin/env bash
2
+ # 把插件源码打成 tar.gz 并发到 GitHub Release。
3
+ #
4
+ # 为什么需要它:本机(以及同一网络里的其他机器)git-over-https 到 github.com
5
+ # 会被 Connection reset,装插件常用的 `git clone` 走不通。而 release 资产可以
6
+ # 经国内镜像正常下载,所以给不能 clone 的机器留一条路:
7
+ #
8
+ # curl -L https://ghfast.top/<release 资产 URL> | tar xz -C <插件目录>
9
+ #
10
+ # sidecar 二进制走的是同一套思路(见 scripts/build-sidecar.sh),区别是这个包
11
+ # 只有约 100KB,随便下。
12
+ #
13
+ # 用法:
14
+ # scripts/release-plugin.sh # 只打包
15
+ # scripts/release-plugin.sh --publish # 打包并发布
16
+ set -euo pipefail
17
+
18
+ REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
19
+ REPO="peng456/dsh-plugin-mesh"
20
+ VERSION="$(node -p "require('$REPO_ROOT/package.json').version")"
21
+ TAG="plugin-v$VERSION"
22
+ ASSET="dsh-plugin-mesh-$VERSION.tar.gz"
23
+ DIST="$REPO_ROOT/dist"
24
+
25
+ PUBLISH=0
26
+ [ "${1:-}" = "--publish" ] && PUBLISH=1
27
+
28
+ echo "==> 打包插件 v$VERSION"
29
+ mkdir -p "$DIST"
30
+ rm -f "$DIST/$ASSET"
31
+ # sidecar 的 Go 源码要带上:用户可据此审计下载回来的二进制是用什么编出来的。
32
+ tar --exclude='.git' \
33
+ --exclude='dist' \
34
+ --exclude='node_modules' \
35
+ --exclude='.DS_Store' \
36
+ -czf "$DIST/$ASSET" \
37
+ -C "$REPO_ROOT" \
38
+ lib client sidecar scripts cordis.patch.yml package.json README.md LICENSE install.sh
39
+
40
+ echo " 产物: $DIST/$ASSET ($(du -h "$DIST/$ASSET" | cut -f1), $(tar -tzf "$DIST/$ASSET" | wc -l | tr -d ' ') 个条目)"
41
+ sha256sum "$DIST/$ASSET" 2>/dev/null || shasum -a 256 "$DIST/$ASSET"
42
+
43
+ if [ "$PUBLISH" -eq 0 ]; then
44
+ echo
45
+ echo "未发布。加 --publish 会创建 release $TAG 并上传。"
46
+ exit 0
47
+ fi
48
+
49
+ TOKEN="$(python3 - <<'PY'
50
+ import os, re
51
+ for line in open(os.path.expanduser("~/.git-credentials")):
52
+ m = re.match(r'https://([^:]+):([^@]+)@github\.com\s*$', line.strip())
53
+ if m:
54
+ print(m.group(2)); break
55
+ PY
56
+ )"
57
+ [ -n "$TOKEN" ] || { echo "找不到 github token" >&2; exit 1; }
58
+ API="https://api.github.com/repos/$REPO"
59
+
60
+ echo
61
+ echo "==> 发布到 GitHub release $TAG"
62
+ RELEASE_ID="$(curl -s -m 30 -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" \
63
+ | python3 -c 'import json,sys; print(json.load(sys.stdin).get("id",""))' 2>/dev/null)"
64
+ if [ -z "$RELEASE_ID" ]; then
65
+ RELEASE_ID="$(curl -s -m 30 -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
66
+ "$API/releases" \
67
+ -d "{\"tag_name\":\"$TAG\",\"name\":\"dsh-plugin-mesh v$VERSION\",\"body\":\"插件源码包。适合不能 git clone 的机器(github.com 的 git 端点在国内常被重置):\\n\\n\`\`\`\\ncurl -L https://ghfast.top/https://github.com/$REPO/releases/download/$TAG/$ASSET | tar xz -C ~/.dsh/profiles/<profile>/node_modules/dsh-plugin-mesh/\\n\`\`\`\"}" \
68
+ | python3 -c 'import json,sys; print(json.load(sys.stdin).get("id",""))' 2>/dev/null)"
69
+ echo " 已创建 release $TAG"
70
+ else
71
+ echo " 复用 release $TAG (id=$RELEASE_ID)"
72
+ fi
73
+ [ -n "$RELEASE_ID" ] || { echo "创建 release 失败" >&2; exit 1; }
74
+
75
+ # 同名资产先删,否则 API 报 already_exists
76
+ OLD_ID="$(curl -s -m 30 -H "Authorization: token $TOKEN" "$API/releases/$RELEASE_ID/assets" \
77
+ | python3 -c "
78
+ import json,sys
79
+ for a in json.load(sys.stdin):
80
+ if a.get('name')=='$ASSET': print(a.get('id')); break
81
+ " 2>/dev/null)"
82
+ [ -n "$OLD_ID" ] && curl -s -m 30 -X DELETE -H "Authorization: token $TOKEN" "$API/releases/assets/$OLD_ID" >/dev/null && echo " 替换已有资产"
83
+
84
+ curl -s -m 300 -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/octet-stream" \
85
+ --data-binary "@$DIST/$ASSET" \
86
+ "https://uploads.github.com/repos/$REPO/releases/$RELEASE_ID/assets?name=$ASSET" \
87
+ | python3 -c 'import json,sys; d=json.load(sys.stdin); print(" ✓", d.get("name"), d.get("size"), "字节") if d.get("id") else print(" ✗", d.get("message"))'
88
+
89
+ echo "✓ https://github.com/$REPO/releases/tag/$TAG"
90
+
91
+ # ── 同步到局域网镜像,并打印可直接粘贴的升级命令 ──
92
+ #
93
+ # 为什么这一步要自动化:不能 git clone 的机器(实测那台 Android)连 github.com /
94
+ # ghfast.top / gh-proxy.com 全都不通,唯一可用的通路就是同网段的镜像。以前每次
95
+ # 发版都要手工 `cp` 一次到镜像目录,忘了就会出现"release 发了但对端下不到"——
96
+ # 而且是**静默**的,对端只会报 404/超时。所以发完版顺手同步,并把命令打出来。
97
+ #
98
+ # 镜像目录可用 MESH_MIRROR_DIR 覆盖;目录不存在就跳过(不是每台机器都当镜子)。
99
+ MIRROR_DIR="${MESH_MIRROR_DIR:-/Users/peng/mesh-mirror-8791}"
100
+ if [ -d "$MIRROR_DIR" ]; then
101
+ cp "$DIST/$ASSET" "$MIRROR_DIR/" && echo "✓ 已同步到镜像 $MIRROR_DIR"
102
+ MIRROR_HOST="${MESH_MIRROR_HOST:-192.168.1.6:8791}"
103
+ cat <<EOF
104
+
105
+ ── 让对端升级(把 <PLUGIN> 换成它的插件目录)──────────────────
106
+ # ⚠ Android 上**没有 /tmp**(根文件系统只读),必须用 \$TMPDIR
107
+ T="\${TMPDIR:-\$HOME/tmp}"; mkdir -p "\$T"
108
+ curl -fL -o "\$T/mesh-$VERSION.tar.gz" http://$MIRROR_HOST/$ASSET
109
+ mkdir -p "\$T/mesh-new" && tar xzf "\$T/mesh-$VERSION.tar.gz" -C "\$T/mesh-new"
110
+ grep -m1 '"version"' "\$T/mesh-new/package.json" # 应显示 $VERSION
111
+
112
+ PLUGIN=<对端插件目录> # 例:\$HOME/.dsh/profiles/web/node_modules/dsh-plugin-mesh
113
+ cp -R "\$PLUGIN" "\$PLUGIN.bak-$VERSION"
114
+ rm -rf "\$PLUGIN/lib" "\$PLUGIN/client" "\$PLUGIN/scripts" "\$PLUGIN/sidecar"
115
+ cp -R "\$T/mesh-new/lib" "\$T/mesh-new/client" "\$T/mesh-new/scripts" "\$T/mesh-new/sidecar" "\$PLUGIN/"
116
+ cp "\$T/mesh-new/package.json" "\$T/mesh-new/cordis.patch.yml" "\$PLUGIN/"
117
+ grep -m1 '"version"' "\$PLUGIN/package.json" # 应显示 $VERSION
118
+
119
+ # ⚠ 重启前必须验「可加载」,光验"文件对得上"兜不住半态:新代码若新增了 import
120
+ # 而落盘漏了那个文件,文件级 cmp 全绿、node --check 也全绿,但重启时 DSH
121
+ # 加载插件会**当场崩**。只有真的 import 一次入口才复现得出来。
122
+ node -e "(async()=>{const m=await import('file://\$PLUGIN/lib/index.js');console.log('✓ 可加载',Object.keys(m).join(','))})().catch(e=>{console.error('✗ 不可加载,**不要重启**,先回滚:',e.code||e.message);process.exit(1)})"
123
+ # 退出码 0 才继续。回滚:rm -rf "\$PLUGIN" && mv "\$PLUGIN.bak-$VERSION" "\$PLUGIN"
124
+ # 然后**重启对端的 DSH** 才会加载新版本
125
+ ────────────────────────────────────────────────────────────
126
+ EOF
127
+ else
128
+ echo "(跳过镜像同步:$MIRROR_DIR 不存在)"
129
+ fi