Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(webview): 为非 Windows WebKit 注入 ES2025 iterator helpers 垫片(fixes #539)

hairyf95735be56831
diff --git a/docs/AGENTS.desktop.md b/docs/AGENTS.desktop.md
index 83fe23e6..ef480776 100644
--- a/docs/AGENTS.desktop.md
+++ b/docs/AGENTS.desktop.md
@@ -349,6 +349,24 @@ export function FooComponent(props: FooProps) {
- pnpm 工作区多文档(issue #526):`$DSH_HOME/profiles/<档案>/pnpm-workspace.yaml` 被手工/工具拼接成多个 YAML 文档(`---` 分隔)时,pnpm(js-yaml `load`)与 serde_yaml **都只接受单文档流**(`expected a single document in the stream, but found more` / `deserializing from YAML containing more than one document is not supported`)。`service/profile/mod.rs::ensure_profile_pnpm_policy`(issue #222 的 zod release-age 例外)在插件安装前置步骤里解析该文件,于是整个启动卡在「Plugin installation」阶段,且原报错不含任何文件路径。修法:新增 `service/profile/mod.rs::parse_workspace_document(content)`,单文档正常返回;解析失败时逐文档尝试(`serde_yaml::Deserializer::from_str` 的 Iterator),**全部是映射**才按「后者覆盖前者」合并成一个映射并返回 `normalized = true`,否则保留原始解析错误(issue #49 的重复映射键不会被误当成多文档)。`ensure_profile_pnpm_policy` 与 `service/plugin/install/allowlist.rs::apply_allow_build_keys` 共用它,`normalized` 本身即视为需要落盘的改动,把文件自愈成 pnpm 也能读的单文档(日志 `PROFILE_WORKSPACE_MULTI_DOCUMENT`)。解析错误统一带路径便于定位:`PROFILE_WORKSPACE_INVALID_YAML: <路径>: <解析错误>`。
+- 旧版 WebKit 缺全局 `Iterator`(issue #539):dsh 内置插件 `@deepseek-ai/dsh-client-ui-sidebar-documentpreview`
+ 内联的 pdf.js 在模块顶层执行 `typeof Iterator.prototype.join !== 'function'`(pdf.js 自己补 `join` 是为了兼容旧引擎),
+ 而 `Iterator` 是 ES2025 iterator helpers 才引入的全局对象(Safari 18.4 / WebKit 2163 起)。
+ macOS 14 / 15.3 随附的系统 WebKit 没有它,该表达式直接抛 `Can't find variable: Iterator`,
+ 插件 import 失败,桌面端启动即报「Failed to load plugins: failed to import loader entry …」
+ (`service/plugin` 的错误页只给出「插件加载失败」,不含缺失的标识符,需对照上面这句才能定位)。
+ 修法:`src-tauri/src/desktop/compat.rs` 的 `ITERATOR_HELPERS_SHIM_JS`(脚本本体为同目录
+ `compat_iterator.js.inc`)随其它垫片一起经 `initialization_script_for_all_frames` 注入非 Windows 平台
+ 的**三个窗口**(`builder.rs` 主窗口与附加窗口、`pet.rs` 桌宠窗口),在真实的 %IteratorPrototype%
+ (由 `Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))` 取得)上补齐
+ join / toArray / forEach / some / every / find / reduce / map / filter / take / drop / flatMap 与
+ `Iterator.from`。两个要点:helper 必须挂在**共享的原型**上(pdf.js 的补丁正是假设 `Iterator.prototype`
+ 就是它,挂在自建对象上生成器仍解析不到);**只做加法**——`Iterator` 已存在(原生,或宿主页面自带
+ polyfill)时整体让位,每个 helper 也先按 `typeof` 判断,`typeof Iterator !== 'undefined'` 因此对第三方
+ 插件仍是可信的能力探测。Windows(WebView2,Chromium ≥ 122)原生支持,不注入(同 `AbortSignal.any` 的取舍)。
+ 回归测试 `test/compat-iterator.test.ts` 在 VM 里 `delete globalThis.Iterator` 并删掉原型上的原生 helper
+ 复现旧 WebKit,再把垫片行为与 Node/V8 原生 iterator helpers 做逐值差分(本机无法跑 macOS 14 的 WebKit)。
+
## Summary
- **API Import**: 直接 `import { invoke } from '@tauri-apps/api/core'`(本仓库没有 `@/apis` 层);类型就近定义在 hooks/组件文件中
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 9173bebd..2def1e8d 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -543,6 +543,7 @@ pub fn build_main_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::We
#[cfg(not(windows))]
let webview_builder = webview_builder
.initialization_script_for_all_frames(crate::desktop::compat::ABORT_SIGNAL_ANY_SHIM_JS)
+ .initialization_script_for_all_frames(crate::desktop::compat::ITERATOR_HELPERS_SHIM_JS)
.initialization_script_for_all_frames(crate::desktop::notification::NOTIFICATION_SHIM_JS)
.initialization_script_for_all_frames(crate::desktop::paste::PASTE_SHIM_JS)
.initialization_script_for_all_frames(crate::desktop::plugin_boot::PLUGIN_BOOT_RELOAD_JS);
@@ -615,6 +616,7 @@ pub fn build_extra_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::W
#[cfg(not(windows))]
let webview_builder = webview_builder
.initialization_script_for_all_frames(crate::desktop::compat::ABORT_SIGNAL_ANY_SHIM_JS)
+ .initialization_script_for_all_frames(crate::desktop::compat::ITERATOR_HELPERS_SHIM_JS)
.initialization_script_for_all_frames(crate::desktop::notification::NOTIFICATION_SHIM_JS)
.initialization_script_for_all_frames(crate::desktop::paste::PASTE_SHIM_JS)
.initialization_script_for_all_frames(crate::desktop::plugin_boot::PLUGIN_BOOT_RELOAD_JS);
diff --git a/src-tauri/src/desktop/compat.rs b/src-tauri/src/desktop/compat.rs
index c203d154..6a566999 100644
--- a/src-tauri/src/desktop/compat.rs
+++ b/src-tauri/src/desktop/compat.rs
@@ -74,3 +74,24 @@ pub(crate) const ABORT_SIGNAL_ANY_SHIM_JS: &str = r#"(function () {
} catch (_ignored) { /* 保留原生未定义的现状 */ }
}
})();"#;
+
+/// 注入 ES2025 iterator helpers 垫片(`Iterator` / `Iterator.prototype.*`,issue #539)。
+///
+/// 背景:dsh 内置插件 `dsh-client-ui-sidebar-documentpreview` 内联的 pdf.js 在模块顶层
+/// 读取 `Iterator.prototype.join`;`Iterator` 是 Safari 18.4 / WebKit 2163 才引入的全局对象,
+/// macOS 14 / 15.3 随附的系统 WebKit 缺失时插件 import 直接抛
+/// `Can't find variable: Iterator`,桌面端启动即报 “Failed to load plugins”。
+/// 修法只能是壳层补齐——该插件是 dsh 的上游 npm 产物,桌面端无法重建其构建目标。
+///
+/// 与 [`ABORT_SIGNAL_ANY_SHIM_JS`] 走同一套注入通道(Windows 在 FrameCreated →
+/// ContentLoading 时 ExecuteScript,其余平台 `initialization_script_for_all_frames`),
+/// 在页面脚本执行之前就位,主机框架与 iframe 每次重新加载都会自动重建。
+///
+/// 脚本本体放在 `compat_iterator.js.inc`:这一份体积远大于 `AbortSignal.any`,
+/// 且 `test/compat-iterator.test.ts` 需要直接读文件、在 VM 里删掉原生 `Iterator`
+/// 后做差分验证,单列文件比 Rust 字符串字面量更便于测试与阅读。
+///
+/// 仅在非 Windows 平台注入:Windows 用 WebView2(常青 Chromium ≥ 122)原生支持
+/// iterator helpers,故该常量不参与 Windows 构建(与 `AbortSignal.any` 的理由一致)。
+#[cfg(not(windows))]
+pub(crate) const ITERATOR_HELPERS_SHIM_JS: &str = include_str!("compat_iterator.js.inc");
diff --git a/src-tauri/src/desktop/compat_iterator.js.inc b/src-tauri/src/desktop/compat_iterator.js.inc
new file mode 100644
index 00000000..5bac7198
--- /dev/null
+++ b/src-tauri/src/desktop/compat_iterator.js.inc
@@ -0,0 +1,220 @@
+// 旧版 WebKit(没有全局 Iterator)下补齐 ES2025 iterator helpers。
+//
+// 背景(issue #539):dsh 内置插件 dsh-client-ui-sidebar-documentpreview 内联的 pdf.js
+// 在模块顶层执行 `typeof Iterator.prototype.join !== 'function'`。`Iterator` 是 ES2025
+// iterator helpers 才引入的全局对象(Safari 18.4 / WebKit 2163、Chrome 122 起),
+// macOS 14 / 15.3 随附的系统 WebKit 没有它,该表达式直接抛
+// `Can't find variable: Iterator`,插件 import 失败,桌面端启动即报
+// “Failed to load plugins: failed to import loader entry …”。
+//
+// 关键点:helper 必须挂在真实的 %IteratorPrototype%(生成器与 Array/Map/Set 迭代器
+// 原型链的共同祖先)上,否则调用方在生成器上直接 `.join(',')` 解析不到——pdf.js 的
+// 补丁正是假设 `Iterator.prototype` 就是那个共享原型。
+//
+// 只做「缺失才补」的加法:`Iterator` 已存在(原生,或宿主页面自带 polyfill)时整体让位;
+// 每个 helper 也先按 typeof 判断,绝不覆盖已有实现。幂等守卫
+// `window.__dsh_iterator_helpers__`,重复注入安全。
+//
+// 实现用生成器(ES2015)而不是 ES5 循环:本垫片必须返回真正的迭代器对象(原型链里有
+// %IteratorPrototype% 才能继续链式调用),而缺少 `Iterator` 的运行时(Safari 10+ /
+// WebKitGTK 2.6+)都支持生成器。
+(function () {
+ if (window.__dsh_iterator_helpers__) return
+ // typeof 对未声明的标识符不抛错:存在原生 Iterator 就让位。
+ if (typeof Iterator !== 'undefined') return
+ if (typeof Symbol === 'undefined' || !Symbol.iterator) return
+
+ var iteratorPrototype = null
+ try {
+ // 取 [Symbol.iterator]() 返回值(如 %ArrayIteratorPrototype%)的上一级原型。
+ iteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
+ }
+ catch (_) {}
+ if (!iteratorPrototype || typeof iteratorPrototype !== 'object') return
+
+ function define(name, helper) {
+ if (typeof iteratorPrototype[name] === 'function') return
+ try {
+ Object.defineProperty(iteratorPrototype, name, {
+ configurable: true,
+ writable: true,
+ value: helper,
+ })
+ }
+ catch (_) {}
+ }
+
+ function callable(fn, method) {
+ if (typeof fn !== 'function') {
+ throw new TypeError('Iterator.prototype.' + method + ' requires a callable argument')
+ }
+ return fn
+ }
+
+ // 取一个可迭代对象(或「裸迭代器」,即只有 next 的对象)的迭代器。
+ function iterableOf(value, message) {
+ if (typeof value[Symbol.iterator] === 'function') return value[Symbol.iterator]()
+ if (typeof value.next === 'function') return value
+ throw new TypeError(message)
+ }
+
+ // 与 pdf.js 内联的补丁同形([...this].join(separator)),改用显式 next() 循环。
+ define('join', function (separator) {
+ var values = []
+ for (var step = this.next(); !step.done; step = this.next()) values.push(step.value)
+ return values.join(separator)
+ })
+
+ define('toArray', function () {
+ var values = []
+ for (var step = this.next(); !step.done; step = this.next()) values.push(step.value)
+ return values
+ })
+
+ define('forEach', function (fn, thisArg) {
+ var callback = callable(fn, 'forEach')
+ var index = 0
+ for (var step = this.next(); !step.done; step = this.next()) {
+ callback.call(thisArg, step.value, index++)
+ }
+ })
+
+ define('some', function (predicate, thisArg) {
+ var fn = callable(predicate, 'some')
+ var index = 0
+ for (var step = this.next(); !step.done; step = this.next()) {
+ if (fn.call(thisArg, step.value, index++)) return true
+ }
+ return false
+ })
+
+ define('every', function (predicate, thisArg) {
+ var fn = callable(predicate, 'every')
+ var index = 0
+ for (var step = this.next(); !step.done; step = this.next()) {
+ if (!fn.call(thisArg, step.value, index++)) return false
+ }
+ return true
+ })
+
+ define('find', function (predicate, thisArg) {
+ var fn = callable(predicate, 'find')
+ var index = 0
+ for (var step = this.next(); !step.done; step = this.next()) {
+ if (fn.call(thisArg, step.value, index++)) return step.value
+ }
+ return undefined
+ })
+
+ define('reduce', function (reducer, initialValue) {
+ var fn = callable(reducer, 'reduce')
+ // arguments.length 区分「没有初值」与「初值为 undefined」。
+ var hasAccumulator = arguments.length > 1
+ var accumulator = initialValue
+ var index = 0
+ for (var step = this.next(); !step.done; step = this.next()) {
+ if (hasAccumulator) accumulator = fn(accumulator, step.value, index)
+ else {
+ accumulator = step.value
+ hasAccumulator = true
+ }
+ index++
+ }
+ if (!hasAccumulator) throw new TypeError('Reduce of empty iterator with no initial value')
+ return accumulator
+ })
+
+ define('map', function* (mapper) {
+ var fn = callable(mapper, 'map')
+ var index = 0
+ for (var step = this.next(); !step.done; step = this.next()) yield fn(step.value, index++)
+ })
+
+ define('filter', function* (predicate) {
+ var fn = callable(predicate, 'filter')
+ var index = 0
+ for (var step = this.next(); !step.done; step = this.next()) {
+ var value = step.value
+ if (fn(value, index++)) yield value
+ }
+ })
+
+ // take/drop 的 limit 语义与原生一致:ToNumber 后 NaN 或负值抛 RangeError。
+ function toLimit(limit, method) {
+ var message = 'Iterator.prototype.' + method + ' limit must be a non-negative number'
+ var number = Number(limit)
+ if (number !== number) throw new RangeError(message)
+ var integer = number === Infinity || number === -Infinity ? number : Math.trunc(number)
+ if (integer < 0) throw new RangeError(message)
+ return integer
+ }
+
+ define('take', function* (limit) {
+ var remaining = toLimit(limit, 'take')
+ for (var step = this.next(); !step.done && remaining > 0; step = this.next()) {
+ yield step.value
+ remaining--
+ }
+ })
+
+ define('drop', function* (limit) {
+ var remaining = toLimit(limit, 'drop')
+ for (var step = this.next(); !step.done; step = this.next()) {
+ if (remaining > 0) {
+ remaining--
+ continue
+ }
+ yield step.value
+ }
+ })
+
+ define('flatMap', function* (mapper) {
+ var fn = callable(mapper, 'flatMap')
+ var index = 0
+ for (var step = this.next(); !step.done; step = this.next()) {
+ var value = fn(step.value, index++)
+ // 与原生一致:mapper 的返回值必须是对象,且该对象必须可迭代
+ // (字符串原始值不展开——展开只发生在 `Object('ab')` 这类对象包装上)。
+ if (value === null || (typeof value !== 'object' && typeof value !== 'function')) {
+ throw new TypeError('Iterator.prototype.flatMap mapper must return an object')
+ }
+ var inner = iterableOf(value, 'Iterator.prototype.flatMap mapper must return an iterable')
+ for (var innerStep = inner.next(); !innerStep.done; innerStep = inner.next()) {
+ yield innerStep.value
+ }
+ }
+ })
+
+ // Iterator 本体:抽象类,只提供 `prototype`(指向真实 %IteratorPrototype%)与 `from`。
+ var IteratorConstructor = function Iterator() {
+ throw new TypeError('Abstract class Iterator not directly constructable')
+ }
+ IteratorConstructor.prototype = iteratorPrototype
+ IteratorConstructor.from = function (value) {
+ if (value === null || value === undefined) {
+ throw new TypeError('Iterator.from called on non-object')
+ }
+ // 已经是迭代器(自带 next)就原样返回,不再多包一层。
+ if (typeof value.next === 'function') return value
+ // 其余情况与原生一致:推迟到真正取下一个值时才判定是否可迭代。
+ return (function* () {
+ var inner = iterableOf(value, 'Iterator.from called on a non-iterable value')
+ for (var step = inner.next(); !step.done; step = inner.next()) yield step.value
+ })()
+ }
+
+ try {
+ Object.defineProperty(window, 'Iterator', {
+ configurable: true,
+ writable: true,
+ value: IteratorConstructor,
+ })
+ }
+ catch (_) {
+ try {
+ window.Iterator = IteratorConstructor
+ }
+ catch (_) {}
+ }
+ window.__dsh_iterator_helpers__ = true
+})()
diff --git a/src-tauri/src/desktop/pet.rs b/src-tauri/src/desktop/pet.rs
index 8297636c..cb2952c7 100644
--- a/src-tauri/src/desktop/pet.rs
+++ b/src-tauri/src/desktop/pet.rs
@@ -319,6 +319,7 @@ pub fn ensure_pet_window<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<Webvie
{
builder = builder
.initialization_script_for_all_frames(crate::desktop::compat::ABORT_SIGNAL_ANY_SHIM_JS)
+ .initialization_script_for_all_frames(crate::desktop::compat::ITERATOR_HELPERS_SHIM_JS)
.initialization_script_for_all_frames(
crate::desktop::notification::NOTIFICATION_SHIM_JS,
)
diff --git a/test/compat-iterator.test.ts b/test/compat-iterator.test.ts
new file mode 100644
index 00000000..bbd54456
--- /dev/null
+++ b/test/compat-iterator.test.ts
@@ -0,0 +1,141 @@
+import { readFileSync } from 'node:fs'
+import { runInNewContext } from 'node:vm'
+import { describe, expect, it } from 'vitest'
+
+/**
+ * issue #539:macOS 14 / 15.3 随附的系统 WebKit 没有全局 `Iterator`(ES2025 iterator
+ * helpers),dsh 内置插件 `@deepseek-ai/dsh-client-ui-sidebar-documentpreview` 内联的
+ * pdf.js 在模块顶层读取 `Iterator.prototype.join`,插件 import 直接抛
+ * `Can't find variable: Iterator`,桌面端启动即报 “Failed to load plugins”。
+ *
+ * 壳层垫片 `src-tauri/src/desktop/compat_iterator.js.inc` 在页面脚本前注入。
+ * 这里在 VM 里删掉原生 `Iterator` 与原型上的原生 helper 来模拟旧 WebKit,并把垫片的
+ * 行为与 Node(V8,原生 iterator helpers)做差分对照。
+ */
+const shim = readFileSync(
+ new URL('../src-tauri/src/desktop/compat_iterator.js.inc', import.meta.url),
+ 'utf8',
+)
+
+/** 旧 WebKit 现场:全局没有 Iterator,%IteratorPrototype% 上也没有任何 helper。 */
+const OLD_WEBKIT_SETUP = `
+delete globalThis.Iterator
+;['join', 'toArray', 'map', 'filter', 'take', 'drop', 'flatMap', 'reduce', 'forEach', 'some', 'every', 'find'].forEach(function (name) {
+ delete Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))[name]
+})
+`
+
+/** pdf.js 在模块顶层的原始写法(垫片生效前它就是 issue #539 的报错点)。 */
+const PDFJS_TOP_LEVEL_GUARD = `(function () { return typeof Iterator.prototype.join !== 'function' })()`
+
+/**
+ * 对照探针:返回 JSON 字符串,跨 realm 只比较字符串,避免原型差异干扰。
+ * 每个用例都用 capture 包住,断言值或错误构造器名。
+ */
+const PROBE = `(function () {
+ if (typeof Iterator.prototype.join !== 'function') {
+ Iterator.prototype.join = function (separator) { return [...this].join(separator) }
+ }
+ function capture(work) {
+ try { return { value: work() } }
+ catch (error) { return { error: error.constructor.name } }
+ }
+ function* letters() { yield 'a'; yield 'b' }
+ function* numbers() { yield 1; yield 2; yield 3 }
+ var out = {}
+ out.hasIterator = typeof Iterator !== 'undefined'
+ out.sharedPrototype = Iterator.prototype === Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
+ out.join = capture(function () { return letters().join('-') })
+ out.joinDefault = capture(function () { return letters().join() })
+ out.joinArrayIterator = capture(function () { return [1, 2].values().join('+') })
+ out.joinMapIterator = capture(function () { return new Map([['a', 1]]).keys().join(',') })
+ out.toArray = capture(function () { return numbers().toArray() })
+ out.map = capture(function () { return numbers().map(function (v) { return v * 2 }).toArray() })
+ out.mapIndex = capture(function () { return letters().map(function (v, i) { return i + v }).toArray() })
+ out.filter = capture(function () { return numbers().filter(function (v, i) { return i > 0 }).toArray() })
+ out.chain = capture(function () { return numbers().take(2).map(function (v) { return v + '!' }).filter(function () { return true }).toArray() })
+ out.forEach = capture(function () { var seen = []; numbers().forEach(function (v, i) { seen.push(i + ':' + v) }); return seen })
+ out.some = capture(function () { return [numbers().some(function (v) { return v > 2 }), numbers().some(function (v) { return v > 9 })] })
+ out.every = capture(function () { return [numbers().every(function (v) { return v > 0 }), numbers().every(function (v) { return v > 1 })] })
+ out.find = capture(function () { return numbers().find(function (v) { return v > 1 }) })
+ out.reduce = capture(function () { return numbers().reduce(function (a, b) { return a + b }) })
+ out.reduceInit = capture(function () { return numbers().reduce(function (a, b, i) { return a.concat(i + ':' + b) }, []) })
+ out.reduceNoInit = capture(function () { return numbers().reduce(function (a, b, i) { return a.concat(i + ':' + b) }) })
+ out.reduceEmpty = capture(function () { return (function* () {})().reduce(function (a, b) { return a }) })
+ out.take = capture(function () { return [numbers().take(2).toArray(), numbers().take(0).toArray(), numbers().take(2.7).toArray(), numbers().take(Infinity).toArray()] })
+ out.takeNegative = capture(function () { return numbers().take(-1).toArray() })
+ out.takeNegativeFraction = capture(function () { return numbers().take(-0.5).toArray() })
+ out.takeNaN = capture(function () { return numbers().take(NaN).toArray() })
+ out.takeUndefined = capture(function () { return numbers().take(undefined).toArray() })
+ out.drop = capture(function () { return [numbers().drop(1).toArray(), numbers().drop(1.9).toArray(), numbers().drop(Infinity).toArray(), numbers().drop(0).toArray()] })
+ out.dropNegative = capture(function () { return numbers().drop(-1).toArray() })
+ out.flatMap = capture(function () { return [numbers().flatMap(function (v) { return [v, v] }).toArray(), (function* () { yield 'ab' })().flatMap(function () { return Object('ab') }).toArray()] })
+ out.flatMapPrimitive = capture(function () { return numbers().flatMap(function (v) { return v }).toArray() })
+ out.flatMapPlainObject = capture(function () { return numbers().flatMap(function () { return {} }).toArray() })
+ out.mapNonCallable = capture(function () { return numbers().map(1).toArray() })
+ out.fromArray = capture(function () { return Iterator.from([1, 2]).toArray() })
+ out.fromString = capture(function () { return Iterator.from('ab').toArray() })
+ out.fromIterator = capture(function () { return Iterator.from(letters()).toArray() })
+ out.fromNull = capture(function () { return Iterator.from(null) })
+ out.fromPlainObject = capture(function () { return Iterator.from({}).toArray() })
+ out.construct = capture(function () { return new Iterator() })
+ return JSON.stringify(out)
+})()`
+
+function createSandbox(): Record<string, unknown> {
+ const sandbox: Record<string, unknown> = {}
+ // 浏览器语义:window 就是全局对象。
+ sandbox.window = sandbox
+ return sandbox
+}
+
+function runInSandbox(code: string, sandbox: Record<string, unknown>): string {
+ return runInNewContext(code, sandbox)
+}
+
+describe('iterator helpers shim (issue #539)', () => {
+ it('reproduces the plugin import failure when the global Iterator is missing', () => {
+ const sandbox = createSandbox()
+ expect(() => runInSandbox(`${OLD_WEBKIT_SETUP}\n;\n${PDFJS_TOP_LEVEL_GUARD}`, sandbox))
+ .toThrow(/Iterator is not defined/)
+ })
+
+ it('defines Iterator on the shared %IteratorPrototype% so iterator .join() resolves', () => {
+ const sandbox = createSandbox()
+ const result = JSON.parse(runInSandbox(`${OLD_WEBKIT_SETUP}\n;\n${shim}\n;\n${PROBE}`, sandbox)) as Record<string, unknown>
+
+ expect(result.hasIterator).toBe(true)
+ expect(result.sharedPrototype).toBe(true)
+ expect(result.join).toEqual({ value: 'a-b' })
+ expect(result.joinDefault).toEqual({ value: 'a,b' })
+ expect(result.joinArrayIterator).toEqual({ value: '1+2' })
+ expect(result.joinMapIterator).toEqual({ value: 'a' })
+ expect((sandbox.window as Record<string, unknown>).__dsh_iterator_helpers__).toBe(true)
+ })
+
+ it('matches the host engine native iterator helpers value for value', () => {
+ const oldWebKit = createSandbox()
+ const polyfilled = JSON.parse(runInSandbox(`${OLD_WEBKIT_SETUP}\n;\n${shim}\n;\n${PROBE}`, oldWebKit)) as Record<string, unknown>
+
+ // 同一探针跑在原生实现上(垫片检测到 Iterator 已存在会整体让位)作为基准。
+ const modern = createSandbox()
+ const native = JSON.parse(runInSandbox(`${shim}\n;\n${PROBE}`, modern)) as Record<string, unknown>
+
+ expect(polyfilled).toEqual(native)
+ })
+
+ it('yields to an existing Iterator and stays idempotent across injections', () => {
+ const modern = createSandbox()
+ runInSandbox(shim, modern)
+ // 原生已有 Iterator:不定义全局、不落幂等标记。
+ expect(modern.Iterator).toBeUndefined()
+ expect((modern.window as Record<string, unknown>).__dsh_iterator_helpers__).toBeUndefined()
+
+ const oldWebKit = createSandbox()
+ runInSandbox(`${OLD_WEBKIT_SETUP}\n;\n${shim}`, oldWebKit)
+ const firstJoin = (oldWebKit.Iterator as { prototype: { join: unknown } }).prototype.join
+ // 重复注入:整体让位,不重建原型方法。
+ runInSandbox(shim, oldWebKit)
+ expect((oldWebKit.Iterator as { prototype: { join: unknown } }).prototype.join).toBe(firstJoin)
+ })
+})
diff --git a/vitest.config.ts b/vitest.config.ts
index 0eda74e2..7631982e 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -30,6 +30,8 @@ export default defineConfig({
'test/pet-window-lifecycle.test.ts',
// issue #525:补丁层 YAML 语法错误的识别与信息提取(纯函数回归)。
'test/patch-layer.test.ts',
+ // issue #539:旧版 WebKit 缺全局 Iterator 导致插件加载失败,壳层兼容垫片回归。
+ 'test/compat-iterator.test.ts',
],
maxWorkers: 4,
testTimeout: 30_000,