;(function (global) { 'use strict' // 服务器地址测速(设置 → 生图服务 → 测速)。 // // 为什么需要 no-cors 兜底(2026-11-12,用户报「三个地址全是 ✗ 失败」): // 测速直连 provider 的 `GET {base}/models`。但这类 one-api / new-api 部署的 CORS // 只加在**预检 OPTIONS** 与生图 POST 上,`GET /models` 的真实响应**没有任何** // Access-Control-Allow-Origin ⇒ 浏览器一律 net::ERR_FAILED,UI 三行全红; // 而服务其实是好的(curl 直接访问 = 401 + 146ms)。 // ⇒ 先按普通请求打(服务端若配了 CORS 就能读到真实状态码),失败再退 `mode:'no-cors'`: // opaque 响应读不到状态码,但「连得上 + 耗时」足以排序选最快地址。 // 判据仍然是「**这条失败会不会让用户以为自己的服务坏了**」——全红就是坏。 const PING_TIMEOUT_MS = 6000 const MAX_URLS = 10 const modelsUrlOf = (base, normalizeEndpointBase) => { const raw = base == null ? '' : base const b = normalizeEndpointBase ? normalizeEndpointBase(raw) : String(raw).trim() const s = String(b == null ? '' : b).trim().replace(/\/+$/, '') return s ? s + '/models' : '' } const isAbort = (e) => !!e && (e.name === 'AbortError' || /abort/i.test(String((e && e.message) || ''))) const errText = (e, timeout) => { if (isAbort(e)) return '超时(' + timeout + 'ms)' return String((e && e.message) || e).slice(0, 80) } const fetchWithin = (url, init, timeoutMs) => { const ctrl = new AbortController() const timer = setTimeout(() => ctrl.abort(), timeoutMs) return fetch(url, Object.assign({}, init, { signal: ctrl.signal })).then( (r) => { clearTimeout(timer); return r }, (e) => { clearTimeout(timer); throw e }, ) } async function pingOne (base, opts) { const o = opts || {} const url = String(base == null ? '' : base).trim() const timeout = Number(o.timeoutMs) > 0 ? Number(o.timeoutMs) : PING_TIMEOUT_MS const target = modelsUrlOf(url, o.normalizeEndpointBase) if (!target) return { url, ok: false, ms: 0, error: '地址为空' } // ① 普通请求:服务端配了 CORS 时能读到真实状态码(信息量最大) const t0 = Date.now() try { const r = await fetchWithin(target, { method: 'GET' }, timeout) return { url, ok: true, ms: Date.now() - t0, status: r.status, cors: true } } catch (e) { if (isAbort(e)) return { url, ok: false, ms: Date.now() - t0, error: errText(e, timeout) } // 落到 ②:大概率是被 CORS 拦了(不是服务不通),换 no-cors 再试一次 } // ② CORS 兜底:读不到状态码,但能判断「连得上 + 大致延迟」 const t1 = Date.now() try { await fetchWithin(target, { method: 'GET', mode: 'no-cors' }, timeout) return { url, ok: true, ms: Date.now() - t1, status: 0, cors: false } } catch (e) { return { url, ok: false, ms: Date.now() - t1, error: errText(e, timeout) } } } async function pingAll (urls, opts) { const list = (Array.isArray(urls) ? urls : []).slice(0, MAX_URLS) const results = await Promise.all(list.map((u) => pingOne(u, opts).catch((e) => ({ url: String(u == null ? '' : u).trim(), ok: false, ms: 0, error: String((e && e.message) || e).slice(0, 80) })))) results.sort((a, b) => (a.ms - b.ms)) return { results } } global.IWBProviderPing = Object.freeze({ pingOne, pingAll, modelsUrlOf, PING_TIMEOUT_MS }) })(typeof window !== 'undefined' ? window : globalThis)