fix(python-runtime): serve BigInt stats from the SEA virtual filesystem

pkg's /snapshot VFS returned number-valued stats even for { bigint: true },
so dsh-fs-local and dsh-fs-sandbox failed with "Cannot mix BigInt and other
types" on every packaged path. In the Python SDK executable the read tool
could not open packaged skill files, and the dsh-doc skill root inside the
VFS left skill discovery incomplete.

The pkg patch converts VFS stats to BigIntStats fields for bigint callers in
the main and worker bootstraps.
This commit is contained in:
sjw1231 committed 2026-11-19 13:35:36 +08:00
1 parent c19f8fadfe
commit 4fbf99cc01
6 files changed
+210 -14

No files matched your search

@@ -12,8 +12,8 @@
en: a15c7c13f167e5ac
zh: 63bcc2ef60c2f344
/agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/packaging-route-yao-pkg-pkg-s-sea-mode:
en: f1c2b60e9474111d
zh: 5de398b5e8554429
en: da2d0e038a0cab9d
zh: 495c770640264c1d
/agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/the-serving-interface-is-a-plugin-inside-the-dsh-application:
en: 5fdde26e9e8c6108
zh: 629559d733c1f0c5
@@ -25,6 +25,8 @@ The exe is packaged with the **`--sea` (enhanced SEA) mode** of [@yao-pkg/pkg](h
The same patch makes the SEA bootstrap's native-addon extraction atomic. On the first `dlopen` of an addon inside the VFS, pkg's `patchDlopen` copies the addon's package tree to `$PKG_NATIVE_CACHE_PATH/pkg/<sha256 of the .node file>/` (default `~/.cache/pkg/...`), a per-user directory that every concurrent process of the same executable shares; upstream writes each file straight to its final path with `writeFileSync`, which truncates a file another process may already have mapped and lets that process's `existsSync`/hash check read a half-written file. Concurrent first starts therefore die with SIGBUS on Linux or fail with `ERR_DLOPEN_FAILED: Library not loaded` on sharp's libvips on macOS (#4664). The patch routes the three write sites through a same-directory temporary file and `renameSync`, so a cache path is either absent or complete, every process finishes its own copy pass before it loads, and concurrent renames of identical content need no lock. The cache location, hash keying, and per-file comparison are unchanged, so a consumer that isolates the cache per instance through `PKG_NATIVE_CACHE_PATH` keeps working; worker threads only define the hook and never install it. Measured (linux-x64, node24 target, pkg 6.21.0, a probe that loads sharp with its 18 MB libvips library, 16 concurrent first starts against one empty cache, five rounds): 39 of 80 processes died with SIGBUS before the change and 0 of 80 after it, with no temporary files left behind.
The same patch makes the VFS honor `{ bigint: true }` in `stat`, `lstat`, their synchronous forms, and `fs.promises`. Upstream returns the same number-valued stats whatever the options, while `dsh-fs-local` and `dsh-fs-sandbox` read VFS paths through BigInt stats, so every `ctx.fs` access to a packaged file failed with `Cannot mix BigInt and other types`: the `read` tool could not open a packaged skill file, and a `skill-filesystem` root inside the VFS made skill discovery incomplete. The patch converts a VFS entry's numbers to the `BigIntStats` fields, including nanosecond times derived from the millisecond values; paths outside the VFS keep Node's own results.
Terminology reminder: pkg's `/snapshot` VFS has nothing to do with this repo's testing-system "snapshot" (ACP replay expected outputs, `$DSH_SNAPSHOT`); this document says "VFS" for the former.
### The serving interface is a plugin inside the dsh application
@@ -25,6 +25,8 @@ exe 使用 [@yao-pkg/pkg](https://github.com/yao-pkg/pkg)(vercel/pkg 归档后
同一补丁还把 SEA bootstrap 的原生插件解包改成原子写入。VFS 内的插件首次 `dlopen` 时,pkg 的 `patchDlopen` 会把该插件所在的包目录整棵拷到 `$PKG_NATIVE_CACHE_PATH/pkg/<.node 文件的 sha256>/`(默认 `~/.cache/pkg/...`),这是同一个 exe 的所有并发进程共用的按用户目录;上游用 `writeFileSync` 直接写目标路径,会把另一个进程可能已经映射的文件截断,并让该进程的 `existsSync`/哈希比对读到写了一半的文件。因此并发首次启动在 Linux 上以 SIGBUS 崩溃,在 macOS 上对 sharp 的 libvips 报 `ERR_DLOPEN_FAILED: Library not loaded`(#4664)。补丁让三处写入都经过同目录临时文件加 `renameSync`,于是缓存路径要么不存在、要么完整,每个进程都在加载前走完自己的拷贝,相同内容的并发 rename 不需要锁。缓存位置、哈希键与逐文件比对均未改变,通过 `PKG_NATIVE_CACHE_PATH` 按实例隔离缓存的消费方照常工作;worker 线程只定义该钩子而从不安装。 实测(linux-x64、node24 构建目标、pkg 6.21.0,一个加载 sharp 及其 18 MB libvips 库的探针,16 个进程对同一个空缓存并发首次启动,跑五轮):改动前 80 个进程中 39 个以 SIGBUS 崩溃,改动后 80 个全部正常,且无残留临时文件。
同一补丁还让 VFS 的 `stat`、`lstat`、它们的同步形式以及 `fs.promises` 遵守 `{ bigint: true }`。上游无论选项如何都返回同一份数值型 stats,而 `dsh-fs-local` 与 `dsh-fs-sandbox` 通过 BigInt stats 读取 VFS 路径,因此经 `ctx.fs` 访问打包文件时都会以 `Cannot mix BigInt and other types` 失败:`read` 工具打不开打包的 skill 文件,位于 VFS 内的 `skill-filesystem` 根使 skill 发现不完整。补丁把 VFS 条目的数值转换为 `BigIntStats` 字段,其中纳秒时间由毫秒值换算;VFS 之外的路径仍使用 Node 自身的结果。
术语提醒:pkg 的 `/snapshot` VFS 与本仓库测试体系的「快照」(ACP(Agent Client Protocol)回放预期输出、`$DSH_SNAPSHOT`)无关,本文用「VFS」指前者。
### 对外服务接口是 dsh 应用中的插件
+107 -9
View File
@@ -1,5 +1,5 @@
diff --git a/lib-es5/sea-assets.js b/lib-es5/sea-assets.js
index a0cb0de8491d4eff37aba7eaaeeec5934f5a9985..f6bb9a35ce2c1978fb08a3400a36a86ce7a43c43 100644
index a0cb0de8491d4eff37aba7eaaeeec5934f5a9985..64007c35530e3affb26650c4a251c46d3e77b35c 100644
--- a/lib-es5/sea-assets.js
+++ b/lib-es5/sea-assets.js
@@ -69,7 +69,13 @@ function resolveCompressor(type) {
@@ -18,7 +18,7 @@ index a0cb0de8491d4eff37aba7eaaeeec5934f5a9985..f6bb9a35ce2c1978fb08a3400a36a86c
return (0, compress_type_1.getZstdCompressSync)();
default: {
diff --git a/prelude/sea-bootstrap.bundle.js b/prelude/sea-bootstrap.bundle.js
index ac14980e953134f2285e326a5111cf52de717cf5..272dbc51ccefb5ce1ab87ffcf5916fbd26225046 100644
index ac14980e953134f2285e326a5111cf52de717cf5..aa1606e738560389c220ef1a50111528e1f996f1 100644
--- a/prelude/sea-bootstrap.bundle.js
+++ b/prelude/sea-bootstrap.bundle.js
@@ -63,6 +63,25 @@ var require_bootstrap_shared = __commonJS({
@@ -69,7 +69,105 @@ index ac14980e953134f2285e326a5111cf52de717cf5..272dbc51ccefb5ce1ab87ffcf5916fbd
}
newPath = tmpModulePath;
}
@@ -5356,6 +5375,39 @@ var require_sea_vfs_setup = __commonJS({
@@ -2318,6 +2337,43 @@ var require_module_hooks = __commonJS({
}
return null;
}
+ // Node returns BigIntStats for { bigint: true }; VFS entries only carry numbers.
+ function vfsStatsForOptions(stats, options) {
+ if (options?.bigint !== true) return stats;
+ const big = (value) => BigInt(Math.trunc(value));
+ const nanos = (value) => BigInt(Math.trunc(value)) * 1000000n + BigInt(Math.round((value % 1) * 1e6));
+ return {
+ dev: big(stats.dev),
+ mode: big(stats.mode),
+ nlink: big(stats.nlink),
+ uid: big(stats.uid),
+ gid: big(stats.gid),
+ rdev: big(stats.rdev),
+ blksize: big(stats.blksize),
+ ino: big(stats.ino),
+ size: big(stats.size),
+ blocks: big(stats.blocks),
+ atimeMs: big(stats.atimeMs),
+ mtimeMs: big(stats.mtimeMs),
+ ctimeMs: big(stats.ctimeMs),
+ birthtimeMs: big(stats.birthtimeMs),
+ atimeNs: nanos(stats.atimeMs),
+ mtimeNs: nanos(stats.mtimeMs),
+ ctimeNs: nanos(stats.ctimeMs),
+ birthtimeNs: nanos(stats.birthtimeMs),
+ atime: stats.atime,
+ mtime: stats.mtime,
+ ctime: stats.ctime,
+ birthtime: stats.birthtime,
+ isFile: () => stats.isFile(),
+ isDirectory: () => stats.isDirectory(),
+ isSymbolicLink: () => stats.isSymbolicLink(),
+ isBlockDevice: () => stats.isBlockDevice(),
+ isCharacterDevice: () => stats.isCharacterDevice(),
+ isFIFO: () => stats.isFIFO(),
+ isSocket: () => stats.isSocket()
+ };
+ }
function findVFSForFsStat(filename) {
const normalized = normalizeVFSPath(filename);
for (let i = 0; i < activeVFSList.length; i++) {
@@ -3185,7 +3241,7 @@ var require_module_hooks = __commonJS({
if (typeof path2 === "string") {
const vfsResult = findVFSForFsStat(path2);
if (vfsResult !== null) {
- return vfsResult.stats;
+ return vfsStatsForOptions(vfsResult.stats, options);
}
}
return originalLstatSync.call(fs, path2, options);
@@ -3194,7 +3250,7 @@ var require_module_hooks = __commonJS({
if (typeof path2 === "string") {
const vfsResult = findVFSForFsStat(path2);
if (vfsResult !== null) {
- return vfsResult.stats;
+ return vfsStatsForOptions(vfsResult.stats, options);
}
}
return originalStatSync.call(fs, path2, options);
@@ -3268,7 +3324,7 @@ var require_module_hooks = __commonJS({
try {
const vfsResult = findVFSForFsStat(path2);
if (vfsResult !== null) {
- if (callback) process.nextTick(callback, null, vfsResult.stats);
+ if (callback) process.nextTick(callback, null, vfsStatsForOptions(vfsResult.stats, options));
return;
}
} catch (err) {
@@ -3288,7 +3344,7 @@ var require_module_hooks = __commonJS({
try {
const vfsResult = findVFSForFsStat(path2);
if (vfsResult !== null) {
- if (callback) process.nextTick(callback, null, vfsResult.stats);
+ if (callback) process.nextTick(callback, null, vfsStatsForOptions(vfsResult.stats, options));
return;
}
} catch (err) {
@@ -3432,7 +3488,7 @@ var require_module_hooks = __commonJS({
if (typeof path2 === "string") {
const vfsResult = findVFSForFsStat(path2);
if (vfsResult !== null) {
- return vfsResult.stats;
+ return vfsStatsForOptions(vfsResult.stats, options);
}
}
return origPStat.call(fs.promises, path2, options);
@@ -3442,7 +3498,7 @@ var require_module_hooks = __commonJS({
if (typeof path2 === "string") {
const vfsResult = findVFSForFsStat(path2);
if (vfsResult !== null) {
- return vfsResult.stats;
+ return vfsStatsForOptions(vfsResult.stats, options);
}
}
return origPLstat.call(fs.promises, path2, options);
@@ -5356,6 +5412,39 @@ var require_sea_vfs_setup = __commonJS({
}
};
}
@@ -109,7 +207,7 @@ index ac14980e953134f2285e326a5111cf52de717cf5..272dbc51ccefb5ce1ab87ffcf5916fbd
var SEAProvider = class extends MemoryProvider {
constructor(seaManifest) {
super();
@@ -5424,7 +5476,10 @@ var require_sea_vfs_setup = __commonJS({
@@ -5424,7 +5513,10 @@ var require_sea_vfs_setup = __commonJS({
"pkg: corrupt SEA manifest \u2014 missing or invalid stats.size for " + filePath
);
}
@@ -121,7 +219,7 @@ index ac14980e953134f2285e326a5111cf52de717cf5..272dbc51ccefb5ce1ab87ffcf5916fbd
this._fileCache.set(p, buf);
} else {
buf = slice;
@@ -5465,12 +5520,21 @@ var require_sea_vfs_setup = __commonJS({
@@ -5465,12 +5557,21 @@ var require_sea_vfs_setup = __commonJS({
}
return -2;
}
@@ -146,16 +244,16 @@ index ac14980e953134f2285e326a5111cf52de717cf5..272dbc51ccefb5ce1ab87ffcf5916fbd
}
existsSync(filePath) {
perf2.count("existsSync calls");
@@ -5542,7 +5606,7 @@ var require_sea_vfs_setup = __commonJS({
@@ -5542,7 +5643,7 @@ var require_sea_vfs_setup = __commonJS({
var require_worker_bootstrap_string = __commonJS({
"prelude/_worker-bootstrap-string.js"(exports2, module2) {
"use strict";
- module2.exports = '"use strict";\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __commonJS = (cb, mod) => function __require() {\n try {\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n } catch (e) {\n throw mod = 0, e;\n }\n};\n\n// prelude/bootstrap-shared.js\nvar require_bootstrap_shared = __commonJS({\n "prelude/bootstrap-shared.js"(exports2, module2) {\n "use strict";\n var childProcess = require("child_process");\n var { createHash } = require("crypto");\n var fs = require("fs");\n var path = require("path");\n var zlib = require("zlib");\n var { homedir } = require("os");\n var COMPRESS_NONE = 0;\n var COMPRESS_GZIP = 1;\n var COMPRESS_BROTLI = 2;\n var COMPRESS_ZSTD = 3;\n function zstdMissingError(symbol) {\n return new Error(\n "pkg: Zstd compression requires Node.js >= 22.15 (runtime missing zlib." + symbol + "). Re-package this binary with pkg >= the version that embeds Node 22.15+, or contact the distributor for a --compress Brotli/GZip build."\n );\n }\n function pickDecompressorSync(compression) {\n switch (compression) {\n case COMPRESS_NONE:\n return null;\n case COMPRESS_GZIP:\n return zlib.gunzipSync;\n case COMPRESS_BROTLI:\n return zlib.brotliDecompressSync;\n case COMPRESS_ZSTD:\n if (typeof zlib.zstdDecompressSync !== "function") {\n throw zstdMissingError("zstdDecompressSync");\n }\n return zlib.zstdDecompressSync;\n default:\n throw new Error(\n "pkg: unknown compression codec id " + compression + " in manifest"\n );\n }\n }\n function pickDecompressorAsync(compression) {\n switch (compression) {\n case COMPRESS_NONE:\n return null;\n case COMPRESS_GZIP:\n return zlib.gunzip;\n case COMPRESS_BROTLI:\n return zlib.brotliDecompress;\n case COMPRESS_ZSTD:\n if (typeof zlib.zstdDecompress !== "function") {\n throw zstdMissingError("zstdDecompress");\n }\n return zlib.zstdDecompress;\n default:\n throw new Error("pkg: unknown compression codec id " + compression);\n }\n }\n function cpRecursive(src, dest) {\n var st = fs.lstatSync(src);\n if (st.isSymbolicLink()) {\n var target = fs.readlinkSync(src);\n try {\n fs.unlinkSync(dest);\n } catch (_) {\n }\n try {\n fs.symlinkSync(target, dest);\n return;\n } catch (e) {\n if (e && (e.code === "EPERM" || e.code === "EACCES")) {\n var resolved = path.isAbsolute(target) ? target : path.join(path.dirname(src), target);\n cpRecursive(resolved, dest);\n return;\n }\n throw e;\n }\n }\n if (st.isDirectory()) {\n fs.mkdirSync(dest, { recursive: true });\n var entries = fs.readdirSync(src);\n for (var i = 0; i < entries.length; i++) {\n cpRecursive(path.join(src, entries[i]), path.join(dest, entries[i]));\n }\n return;\n }\n var srcContent = fs.readFileSync(src);\n if (fs.existsSync(dest)) {\n var destContent = fs.readFileSync(dest);\n var srcHash = createHash("sha256").update(srcContent).digest("hex");\n var destHash = createHash("sha256").update(destContent).digest("hex");\n if (srcHash === destHash) {\n return;\n }\n }\n fs.writeFileSync(dest, srcContent);\n }\n function patchDlopen(insideSnapshot) {\n var ancestor = process.dlopen;\n var PKG_NATIVE_CACHE_BASE = process.env.PKG_NATIVE_CACHE_PATH || path.join(homedir(), ".cache");\n function revertMakingLong(f) {\n if (/^\\\\\\\\\\?\\\\/.test(f)) return f.slice(4);\n return f;\n }\n process.dlopen = function dlopen() {\n var args = Array.prototype.slice.call(arguments);\n var modulePath = revertMakingLong(args[1]);\n var moduleBaseName = path.basename(modulePath);\n var moduleFolder = path.dirname(modulePath);\n if (insideSnapshot(modulePath)) {\n var moduleContent = fs.readFileSync(modulePath);\n var hash = createHash("sha256").update(moduleContent).digest("hex");\n var tmpFolder = path.join(PKG_NATIVE_CACHE_BASE, "pkg", hash);\n fs.mkdirSync(tmpFolder, { recursive: true });\n var parts = moduleFolder.split(path.sep);\n var mIndex = parts.lastIndexOf("node_modules") + 1;\n var newPath;\n if (mIndex > 0) {\n var modulePackagePath = parts.slice(mIndex).join(path.sep);\n var modulePkgFolder = parts.slice(0, mIndex + 1).join(path.sep);\n var destFolder = path.join(tmpFolder, path.basename(modulePkgFolder));\n cpRecursive(modulePkgFolder, dest Line truncated
+ module2.exports = '"use strict";\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __commonJS = (cb, mod) => function __require() {\n try {\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n } catch (e) {\n throw mod = 0, e;\n }\n};\n\n// prelude/bootstrap-shared.js\nvar require_bootstrap_shared = __commonJS({\n "prelude/bootstrap-shared.js"(exports2, module2) {\n "use strict";\n var childProcess = require("child_process");\n var { createHash } = require("crypto");\n var fs = require("fs");\n var path = require("path");\n var zlib = require("zlib");\n var { homedir } = require("os");\n var COMPRESS_NONE = 0;\n var COMPRESS_GZIP = 1;\n var COMPRESS_BROTLI = 2;\n var COMPRESS_ZSTD = 3;\n function zstdMissingError(symbol) {\n return new Error(\n "pkg: Zstd compression requires Node.js >= 22.15 (runtime missing zlib." + symbol + "). Re-package this binary with pkg >= the version that embeds Node 22.15+, or contact the distributor for a --compress Brotli/GZip build."\n );\n }\n function pickDecompressorSync(compression) {\n switch (compression) {\n case COMPRESS_NONE:\n return null;\n case COMPRESS_GZIP:\n return zlib.gunzipSync;\n case COMPRESS_BROTLI:\n return zlib.brotliDecompressSync;\n case COMPRESS_ZSTD:\n if (typeof zlib.zstdDecompressSync !== "function") {\n throw zstdMissingError("zstdDecompressSync");\n }\n return zlib.zstdDecompressSync;\n default:\n throw new Error(\n "pkg: unknown compression codec id " + compression + " in manifest"\n );\n }\n }\n function pickDecompressorAsync(compression) {\n switch (compression) {\n case COMPRESS_NONE:\n return null;\n case COMPRESS_GZIP:\n return zlib.gunzip;\n case COMPRESS_BROTLI:\n return zlib.brotliDecompress;\n case COMPRESS_ZSTD:\n if (typeof zlib.zstdDecompress !== "function") {\n throw zstdMissingError("zstdDecompress");\n }\n return zlib.zstdDecompress;\n default:\n throw new Error("pkg: unknown compression codec id " + compression);\n }\n }\n function cpRecursive(src, dest) {\n var st = fs.lstatSync(src);\n if (st.isSymbolicLink()) {\n var target = fs.readlinkSync(src);\n try {\n fs.unlinkSync(dest);\n } catch (_) {\n }\n try {\n fs.symlinkSync(target, dest);\n return;\n } catch (e) {\n if (e && (e.code === "EPERM" || e.code === "EACCES")) {\n var resolved = path.isAbsolute(target) ? target : path.join(path.dirname(src), target);\n cpRecursive(resolved, dest);\n return;\n }\n throw e;\n }\n }\n if (st.isDirectory()) {\n fs.mkdirSync(dest, { recursive: true });\n var entries = fs.readdirSync(src);\n for (var i = 0; i < entries.length; i++) {\n cpRecursive(path.join(src, entries[i]), path.join(dest, entries[i]));\n }\n return;\n }\n var srcContent = fs.readFileSync(src);\n if (fs.existsSync(dest)) {\n var destContent = fs.readFileSync(dest);\n var srcHash = createHash("sha256").update(srcContent).digest("hex");\n var destHash = createHash("sha256").update(destContent).digest("hex");\n if (srcHash === destHash) {\n return;\n }\n }\n fs.writeFileSync(dest, srcContent);\n }\n function patchDlopen(insideSnapshot) {\n var ancestor = process.dlopen;\n var PKG_NATIVE_CACHE_BASE = process.env.PKG_NATIVE_CACHE_PATH || path.join(homedir(), ".cache");\n function revertMakingLong(f) {\n if (/^\\\\\\\\\\?\\\\/.test(f)) return f.slice(4);\n return f;\n }\n process.dlopen = function dlopen() {\n var args = Array.prototype.slice.call(arguments);\n var modulePath = revertMakingLong(args[1]);\n var moduleBaseName = path.basename(modulePath);\n var moduleFolder = path.dirname(modulePath);\n if (insideSnapshot(modulePath)) {\n var moduleContent = fs.readFileSync(modulePath);\n var hash = createHash("sha256").update(moduleContent).digest("hex");\n var tmpFolder = path.join(PKG_NATIVE_CACHE_BASE, "pkg", hash);\n fs.mkdirSync(tmpFolder, { recursive: true });\n var parts = moduleFolder.split(path.sep);\n var mIndex = parts.lastIndexOf("node_modules") + 1;\n var newPath;\n if (mIndex > 0) {\n var modulePackagePath = parts.slice(mIndex).join(path.sep);\n var modulePkgFolder = parts.slice(0, mIndex + 1).join(path.sep);\n var destFolder = path.join(tmpFolder, path.basename(modulePkgFolder));\n cpRecursive(modulePkgFolder, dest Line truncated
+ module2.exports = '"use strict";\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __commonJS = (cb, mod) => function __require() {\n try {\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n } catch (e) {\n throw mod = 0, e;\n }\n};\n\n// prelude/bootstrap-shared.js\nvar require_bootstrap_shared = __commonJS({\n "prelude/bootstrap-shared.js"(exports2, module2) {\n "use strict";\n var childProcess = require("child_process");\n var { createHash } = require("crypto");\n var fs = require("fs");\n var path = require("path");\n var zlib = require("zlib");\n var { homedir } = require("os");\n var COMPRESS_NONE = 0;\n var COMPRESS_GZIP = 1;\n var COMPRESS_BROTLI = 2;\n var COMPRESS_ZSTD = 3;\n function zstdMissingError(symbol) {\n return new Error(\n "pkg: Zstd compression requires Node.js >= 22.15 (runtime missing zlib." + symbol + "). Re-package this binary with pkg >= the version that embeds Node 22.15+, or contact the distributor for a --compress Brotli/GZip build."\n );\n }\n function pickDecompressorSync(compression) {\n switch (compression) {\n case COMPRESS_NONE:\n return null;\n case COMPRESS_GZIP:\n return zlib.gunzipSync;\n case COMPRESS_BROTLI:\n return zlib.brotliDecompressSync;\n case COMPRESS_ZSTD:\n if (typeof zlib.zstdDecompressSync !== "function") {\n throw zstdMissingError("zstdDecompressSync");\n }\n return zlib.zstdDecompressSync;\n default:\n throw new Error(\n "pkg: unknown compression codec id " + compression + " in manifest"\n );\n }\n }\n function pickDecompressorAsync(compression) {\n switch (compression) {\n case COMPRESS_NONE:\n return null;\n case COMPRESS_GZIP:\n return zlib.gunzip;\n case COMPRESS_BROTLI:\n return zlib.brotliDecompress;\n case COMPRESS_ZSTD:\n if (typeof zlib.zstdDecompress !== "function") {\n throw zstdMissingError("zstdDecompress");\n }\n return zlib.zstdDecompress;\n default:\n throw new Error("pkg: unknown compression codec id " + compression);\n }\n }\n function cpRecursive(src, dest) {\n var st = fs.lstatSync(src);\n if (st.isSymbolicLink()) {\n var target = fs.readlinkSync(src);\n try {\n fs.unlinkSync(dest);\n } catch (_) {\n }\n try {\n fs.symlinkSync(target, dest);\n return;\n } catch (e) {\n if (e && (e.code === "EPERM" || e.code === "EACCES")) {\n var resolved = path.isAbsolute(target) ? target : path.join(path.dirname(src), target);\n cpRecursive(resolved, dest);\n return;\n }\n throw e;\n }\n }\n if (st.isDirectory()) {\n fs.mkdirSync(dest, { recursive: true });\n var entries = fs.readdirSync(src);\n for (var i = 0; i < entries.length; i++) {\n cpRecursive(path.join(src, entries[i]), path.join(dest, entries[i]));\n }\n return;\n }\n var srcContent = fs.readFileSync(src);\n if (fs.existsSync(dest)) {\n var destContent = fs.readFileSync(dest);\n var srcHash = createHash("sha256").update(srcContent).digest("hex");\n var destHash = createHash("sha256").update(destContent).digest("hex");\n if (srcHash === destHash) {\n return;\n }\n }\n fs.writeFileSync(dest, srcContent);\n }\n function patchDlopen(insideSnapshot) {\n var ancestor = process.dlopen;\n var PKG_NATIVE_CACHE_BASE = process.env.PKG_NATIVE_CACHE_PATH || path.join(homedir(), ".cache");\n function revertMakingLong(f) {\n if (/^\\\\\\\\\\?\\\\/.test(f)) return f.slice(4);\n return f;\n }\n process.dlopen = function dlopen() {\n var args = Array.prototype.slice.call(arguments);\n var modulePath = revertMakingLong(args[1]);\n var moduleBaseName = path.basename(modulePath);\n var moduleFolder = path.dirname(modulePath);\n if (insideSnapshot(modulePath)) {\n var moduleContent = fs.readFileSync(modulePath);\n var hash = createHash("sha256").update(moduleContent).digest("hex");\n var tmpFolder = path.join(PKG_NATIVE_CACHE_BASE, "pkg", hash);\n fs.mkdirSync(tmpFolder, { recursive: true });\n var parts = moduleFolder.split(path.sep);\n var mIndex = parts.lastIndexOf("node_modules") + 1;\n var newPath;\n if (mIndex > 0) {\n var modulePackagePath = parts.slice(mIndex).join(path.sep);\n var modulePkgFolder = parts.slice(0, mIndex + 1).join(path.sep);\n var destFolder = path.join(tmpFolder, path.basename(modulePkgFolder));\n cpRecursive(modulePkgFolder, dest Line truncated
}
});
@@ -5560,7 +5624,6 @@ var require_sea_bootstrap_core = __commonJS({
@@ -5560,7 +5661,6 @@ var require_sea_bootstrap_core = __commonJS({
var insideSnapshot = vfs.insideSnapshot;
var SNAPSHOT_PREFIX = vfs.SNAPSHOT_PREFIX;
shared.patchDlopen(insideSnapshot);
+3 -3
View File
@@ -15,7 +15,7 @@ patchedDependencies:
'@electron/[email protected]': 280e7b2816caf01423097d24e79107a66afeb563a348630ce9928ae8499a5861
'@fortune-sheet/[email protected]': 8791a230763dbf853fd65d627c68c31de37209992851377855e16cf08ea70532
'@fortune-sheet/[email protected]': 2932e52e79afcd4ced08cfa123b5eded786c85043da32f622f3e80af6fc96c37
'@yao-pkg/[email protected]': 6004ea831bf18a0272276f3308456b7799d5ac32a5e69c138008b6329c1bfb9f
'@yao-pkg/[email protected]': 5f86cdffd46809beef2ec11e8cd2b34b263568f49546c9fb27b8094db9cc3914
[email protected]: b70dc2a2a78ffabb80a4f14fafc7c103237f2b0a207e1f296fa1c1387ea29348
[email protected]: c1bf8ac8f319dab382f08e3a669b715e691d46c703ac5a4163eb383fbedd1d48
[email protected]: 54c4413db208cf234cb68c6a837f2523d3b319aa17911f1da385af08362e1356
@@ -206,7 +206,7 @@ importers:
version: 4.1.11([email protected])
'@yao-pkg/pkg':
specifier: 6.21.0
version: 6.21.0(patch_hash=6004ea831bf18a0272276f3308456b7799d5ac32a5e69c138008b6329c1bfb9f)([email protected])
version: 6.21.0(patch_hash=5f86cdffd46809beef2ec11e8cd2b34b263568f49546c9fb27b8094db9cc3914)([email protected])
'@yarnpkg/cli-dist':
specifier: 4.18.0
version: 4.18.0
@@ -31784,7 +31784,7 @@ snapshots:
- bare-buffer
- react-native-b4a
'@yao-pkg/[email protected](patch_hash=6004ea831bf18a0272276f3308456b7799d5ac32a5e69c138008b6329c1bfb9f)([email protected])':
'@yao-pkg/[email protected](patch_hash=5f86cdffd46809beef2ec11e8cd2b34b263568f49546c9fb27b8094db9cc3914)([email protected])':
dependencies:
'@babel/generator': 7.29.7
'@babel/parser': 7.29.7
+94
View File
@@ -0,0 +1,94 @@
/** Execute the shipped SEA VFS stat conversion that serves `{ bigint: true }` callers such as dsh-fs-local. */
import { createRequire } from 'node:module'
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { runInNewContext } from 'node:vm'
import ts from 'typescript'
import { describe, expect, it } from 'vitest'
const require = createRequire(import.meta.url)
const pkgRoot = dirname(require.resolve('@yao-pkg/pkg/package.json'))
const bundle = readFileSync(join(pkgRoot, 'prelude/sea-bootstrap.bundle.js'), 'utf8')
function declaration(source: string, kind: 'variable' | 'function', name: string): string {
const parsed = ts.createSourceFile('prelude.js', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS)
let text: string | undefined
const visit = (node: ts.Node): void => {
if (kind === 'variable' && ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === name) {
text = node.initializer?.getText(parsed)
}
if (kind === 'function' && ts.isFunctionDeclaration(node) && node.name?.text === name) text = node.getText(parsed)
ts.forEachChild(node, visit)
}
visit(parsed)
if (text === undefined) throw new Error(`pkg prelude is missing ${name}`)
return text
}
function commonJs(callbacks: Record<string, (exports: object, module: { exports: unknown }) => void>) {
return () => {
const exports = {}
const module: { exports: unknown } = { exports }
Object.values(callbacks)[0]!(exports, module)
return module.exports
}
}
const workerSource: unknown = runInNewContext(`(${declaration(bundle, 'variable', 'require_worker_bootstrap_string')})()`, { __commonJS: commonJs })
if (typeof workerSource !== 'string') throw new Error('pkg worker bootstrap must be JavaScript text')
/** The numeric fields every pkg VirtualStats carries. */
interface NumberStats {
dev: number
mode: number
nlink: number
uid: number
gid: number
rdev: number
blksize: number
ino: number
size: number
blocks: number
atimeMs: number
mtimeMs: number
ctimeMs: number
birthtimeMs: number
isFile(): boolean
isDirectory(): boolean
}
type Convert = (stats: NumberStats, options?: unknown) => Record<string, unknown> & { isFile(): boolean; isDirectory(): boolean }
function numberStats(): NumberStats {
return {
dev: 7, mode: 0o100644, nlink: 1, uid: 501, gid: 20, rdev: 0, blksize: 4096, ino: 9, size: 42, blocks: 1,
atimeMs: 1_700_000_000_000, mtimeMs: 1_700_000_000_123.5, ctimeMs: 1_700_000_000_456, birthtimeMs: 1_700_000_000_000,
isFile: () => true, isDirectory: () => false,
}
}
// The main bundle also embeds the worker bootstrap text, so it carries both copies of the six hooks.
describe.each([['main', bundle, 12], ['worker', workerSource, 6]] as const)('pkg VFS stats in %s', (_name, source, hooks) => {
const convert = runInNewContext(`(${declaration(source, 'function', 'vfsStatsForOptions')})`, { BigInt, Math }) as Convert
it('serves BigIntStats fields to bigint callers', () => {
const stats = convert(numberStats(), { bigint: true })
expect(stats).toMatchObject({
dev: 7n, mode: 0o100644n, ino: 9n, size: 42n, mtimeMs: 1_700_000_000_123n, mtimeNs: 1_700_000_000_123_500_000n,
})
expect((stats.mode as bigint) & 0o777n).toBe(0o644n)
expect(stats.isFile()).toBe(true)
expect(stats.isDirectory()).toBe(false)
})
it.each([undefined, {}, 'utf8'])('returns the VFS stats unchanged for options %j', (options) => {
const stats = numberStats()
expect(convert(stats, options)).toBe(stats)
})
it('routes every path stat hook through the conversion', () => {
expect(source).not.toMatch(/return vfsResult\.stats;|null, vfsResult\.stats\)/)
expect(source.match(/vfsStatsForOptions\(vfsResult\.stats, options\)/g)).toHaveLength(hooks)
})
})