@mzzsfy/dsh-stock-assistant 0.10.0 → 0.11.0

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.
@@ -1,5 +1,6 @@
1
1
  // 东财公开行情接口适配器:quotes/catalog/search/kline。非官方端点,无SLA;延迟未知,f124为来源秒级时间戳。
2
2
  import { normalizeQuote, makeSecurity, securityId, StockError, MARKET_META, sharesFromLots, zonedUnixSeconds } from '../market-model.mjs'
3
+ import { isUSExchange, marketMatchesUS, US_MARKET_EXCHANGE } from './us-markets.mjs'
3
4
  // 官方默认端点表(key 供 instance.endpoints 覆盖, 反代/镜像场景由 ctx.endpoints 提供同名 key)
4
5
  const DEFAULT_ENDPOINTS = {
5
6
  quotes: 'https://push2.eastmoney.com/api/qt/ulist.np/get',
@@ -11,23 +12,75 @@ const DEFAULT_ENDPOINTS = {
11
12
  const endpointOf = (ctx, key) => ctx.endpoints?.[key] || DEFAULT_ENDPOINTS[key]
12
13
  // suggest 接口的公开站点参数(不是本插件凭据), 两处调用必须同源
13
14
  const SUGGEST_TOKEN = 'D43BF722C8E33BDC906FB84D85E326E8'
14
- // 沪深市场代码(其余市场的 secid 前缀见 SECID_PREFIX)
15
- const MARKET = { XSHG: '1', XSHE: '0' }
16
- // 搜索联想 MktNum→交易所全集(实测: 1/0 沪深, 116 港, 105/106/107 美三大, 176/177/155 日韩英)
17
- const SEARCH_EXCHANGE = { 1: 'XSHG', 0: 'XSHE', 116: 'XHKG', 105: 'XNAS', 106: 'XNYS', 107: 'XNYS', 176: 'XJPX', 177: 'XKRX', 155: 'XLON' }
15
+ const QUOTE_INDEX_SECID = { 'XHKG:index:HSI': '100.HSI' }
16
+ const EXCHANGE_BY_PREFIX = { 1: 'XSHG', 0: 'XSHE', 116: 'XHKG', ...US_MARKET_EXCHANGE, 176: 'XJPX', 177: 'XKRX', 155: 'XLON' }
18
17
  const SECID_PREFIX = { XSHG: '1', XSHE: '0', XHKG: '116', XNAS: '105', XNYS: '106', XJPX: '176', XKRX: '177', XLON: '155' }
19
- // 美股三大市场号: 105 纳斯达克 / 106 纽约 / 107 美交所。secid 前缀必须精确匹配, 探针期据此逐个试探。
20
- const US_MKTNUMS = ['105', '106', '107']
21
- const isUSExchange = exchange => exchange === 'XNAS' || exchange === 'XNYS'
22
- // 美股 secid 前缀候选序: 搜索缓存 > 交易所静态前缀 > 其余美股市场号。XNYS 实横跨 106 与 107, 静态前缀只取其一。
23
- // 缓存只加速重复查询, 缺失或过期不改变正确性: 进程重启后 usSymbols 为空, 取报价不得依赖此前的搜索行为。
24
- const usSecidPrefixes = (security, ctx) => [...new Set([ctx.usSymbols?.get(`US:${security.code}`)?.mktNum, SECID_PREFIX[security.exchange], ...US_MKTNUMS].filter(mktNum => US_MKTNUMS.includes(mktNum)))]
18
+ const US_MKTNUMS = Object.keys(US_MARKET_EXCHANGE)
19
+ // 缓存只加速同交易所查询,未命中时优先用静态前缀。
20
+ function usSecidPrefixes(security, ctx) {
21
+ const cached = ctx.usSymbols?.get(`US:${security.code}`)?.mktNum
22
+ return [...new Set([cached, SECID_PREFIX[security.exchange], ...US_MKTNUMS].filter(mktNum => marketMatchesUS(security.exchange, mktNum)).map(String))]
23
+ }
25
24
  const secidFor = (security, ctx) => isUSExchange(security.exchange) ? `${usSecidPrefixes(security, ctx)[0]}.${security.code}` : `${SECID_PREFIX[security.exchange]}.${security.code}`
26
25
  // klt 周期映射(实测): 日101/周102/月103; trends2 无 klt。
27
26
  const KLT = { '1d': 101, '1w': 102, '1M': 103 }
28
27
  // 目录 fs 按市场给出; 英股 m:155 含债券与结构性产品, 加 t:1 只取股票; 日韩不支持 t: 细分, 全量即股票
29
28
  const LIST_FS = { XSHG: 'm:1+t:2,m:1+t:23', XSHE: 'm:0+t:6,m:0+t:80', XHKG: 'm:116+t:3,m:116+t:4', XNAS: 'm:105+t:1', XNYS: 'm:106+t:1,m:107+t:1', XJPX: 'm:176', XKRX: 'm:177', XLON: 'm:155+t:1' }
30
- const SYMBOL_PREFIX = { 1: 'XSHG', 0: 'XSHE', 116: 'XHKG', 105: 'XNAS', 106: 'XNYS', 107: 'XNYS', 176: 'XJPX', 177: 'XKRX', 155: 'XLON' }
29
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value)
30
+ const isCount = value => (typeof value === 'number' || typeof value === 'string' && /^\d+$/.test(value)) && Number.isSafeInteger(Number(value)) && Number(value) >= 0
31
+
32
+ function readDiff(data, label) {
33
+ const diff = data?.diff
34
+ if (isObject(data)) {
35
+ if (Array.isArray(diff)) return diff
36
+ if (isObject(diff) && Object.keys(diff).every(key => /^(0|[1-9]\d*)$/.test(key))) return Object.values(diff)
37
+ }
38
+ throw new StockError('BAD_PAYLOAD', `${label}字段结构异常`, 502)
39
+ }
40
+
41
+ function validateStatus(body) {
42
+ if (!isObject(body)) throw new StockError('BAD_PAYLOAD', '来源字段结构异常', 502)
43
+ if (!Object.hasOwn(body, 'rc')) return
44
+ const rc = body.rc
45
+ if (!(typeof rc === 'number' || typeof rc === 'string' && /^-?\d+$/.test(rc)) || !Number.isSafeInteger(Number(rc))) throw new StockError('BAD_PAYLOAD', '来源状态字段异常', 502)
46
+ if (Number(body.rc) !== 0) throw new StockError('NETWORK', '东财未能处理请求', 502, { retryable: true })
47
+ }
48
+
49
+ // 搜索仍收录 ETF。未提供 Classify 的来源沿用市场号及代码校验。
50
+ const isSearchInstrument = row => row.Classify == null || row.Classify === '' || typeof row.Classify === 'string' && /^(?:[a-z]*stock|[a-z]*etf[a-z]*|[a-z]*fund)$/i.test(row.Classify.trim())
51
+ function suggestRows(body) {
52
+ const table = body.QuotationCodeTable
53
+ if (table === null) return []
54
+ if (isObject(table)) {
55
+ if (table.Data === null) return []
56
+ if (Array.isArray(table.Data)) {
57
+ const rows = table.Data.filter(row => {
58
+ if (!isObject(row) || !isCount(row.MktNum) || typeof row.Code !== 'string' || !row.Code.trim() || typeof row.Name !== 'string' || !row.Name.trim()) return false
59
+ if (row.Classify != null && typeof row.Classify !== 'string') return false
60
+ const meta = MARKET_META[EXCHANGE_BY_PREFIX[row.MktNum]]
61
+ return !meta || !isSearchInstrument(row) || meta.codePattern.test(row.Code)
62
+ })
63
+ if (!table.Data.length || rows.length) return rows
64
+ }
65
+ }
66
+ throw new StockError('BAD_PAYLOAD', '搜索字段结构异常', 502)
67
+ }
68
+
69
+ function hasHistory(body, secid, field, label) {
70
+ const { data } = body
71
+ if (data === null) return false
72
+ if (!isObject(data)) throw new StockError('BAD_PAYLOAD', `${label}字段结构异常`, 502)
73
+ const dot = secid.indexOf('.')
74
+ const market = secid.slice(0, dot), code = secid.slice(dot + 1)
75
+ if (Object.hasOwn(data, 'code') && data.code !== code || Object.hasOwn(data, 'market') && String(data.market) !== market) {
76
+ throw new StockError('BAD_PAYLOAD', `${label}证券身份不匹配`, 502)
77
+ }
78
+ const rows = data[field]
79
+ if (rows === null) return false
80
+ if (!Array.isArray(rows) || rows.some(row => typeof row !== 'string')) throw new StockError('BAD_PAYLOAD', `${label}字段结构异常`, 502)
81
+ return rows.length > 0
82
+ }
83
+ const usSymbolOf = (row, at) => ({ mktNum: String(row.MktNum), jys: row.JYS || null, at })
31
84
  // 探针代表证券(实测可用的各市场流动性代表),quotes/kline 探针按市场取用。
32
85
  const PROBE_SECURITY = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA', XJPX: '7203', XKRX: '005930', XLON: 'SHEL' }
33
86
  // klines CSV 前 7 列固定语义(实测 fields2=f51-f57); f53=close 在 f54=high 前为东财原生序。
@@ -57,10 +110,12 @@ async function getJson(ctx, url) {
57
110
  }
58
111
  if (await challenged(response)) throw new StockError('CHALLENGE', '东财要求人机验证:用浏览器打开 www.eastmoney.com 完成验证后自动恢复', 502)
59
112
  if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
60
- return response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
113
+ const body = await response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
114
+ validateStatus(body)
115
+ return body
61
116
  }
62
117
  export const eastmoney = {
63
- descriptor: { adapterId: 'eastmoney', capabilities: ['quotes', 'catalog', 'search', 'kline', 'trend'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS', 'XJPX', 'XKRX', 'XLON'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '东方财富公开接口:免凭据,八市场目录,行情/K线/分时/搜索,非官方无SLA', endpointKeys: [{ key: 'quotes', label: '行情批量' }, { key: 'list', label: '证券目录' }, { key: 'search', label: '搜索联想' }, { key: 'kline', label: 'K线历史' }, { key: 'trend', label: '分时' }] },
118
+ descriptor: { adapterId: 'eastmoney', capabilities: ['quotes', 'catalog', 'search', 'kline', 'trend'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS', 'XJPX', 'XKRX', 'XLON'], instruments: ['equity'], maxQuoteBatch: 60, pagedCatalog: true, credential: 'none', description: '东方财富公开接口:免凭据,八市场目录,行情/K线/分时/搜索,非官方无SLA', endpointKeys: [{ key: 'quotes', label: '行情批量' }, { key: 'list', label: '证券目录' }, { key: 'search', label: '搜索联想' }, { key: 'kline', label: 'K线历史' }, { key: 'trend', label: '分时' }] },
64
119
  async probe(request, ctx) {
65
120
  if (request.capability === 'catalog' || request.capability === 'search') {
66
121
  // 探针词按市场用代表证券代码(茅台/平安只对沪深有效, 其他市场返回 0 项会误判 denied)。
@@ -87,14 +142,20 @@ export const eastmoney = {
87
142
  },
88
143
  async quotes(request, ctx) {
89
144
  const fields = 'f2,f3,f4,f5,f6,f8,f10,f12,f13,f14,f15,f16,f17,f18,f124'
90
- const seen = new Set(), items = []
145
+ const seen = new Set(), invalidPrices = new Set(), items = []
91
146
  // 一次请求取一批 secid;data:null 表示整批 secid 均无效(如整批退市),降级为逐证券缺失。
92
147
  const ingest = async symbols => {
93
148
  const body = await getJson(ctx, `${endpointOf(ctx, 'quotes')}?secids=${[...symbols.keys()].join(',')}&fields=${fields}&fltt=2&invt=2`)
94
- const rows = body?.data?.diff
95
- if (!Array.isArray(rows)) return
149
+ if (body.data === null) return
150
+ const rows = readDiff(body.data, '报价')
151
+ let hasIdentity = false
96
152
  for (const row of rows) {
97
- const security = symbols.get(`${row.f13}.${row.f12}`)
153
+ const exchange = EXCHANGE_BY_PREFIX[row?.f13]
154
+ const secid = `${row?.f13}.${row?.f12}`
155
+ const security = symbols.get(secid)
156
+ const knownIndex = security && QUOTE_INDEX_SECID[security.id] === secid
157
+ if (!knownIndex && !(typeof row?.f12 === 'string' && MARKET_META[exchange]?.codePattern.test(row.f12))) continue
158
+ hasIdentity = true
98
159
  if (!security) continue
99
160
  if (seen.has(security.id)) throw new StockError('BAD_PAYLOAD', '报价身份冲突', 502)
100
161
  seen.add(security.id)
@@ -102,49 +163,54 @@ export const eastmoney = {
102
163
  // f8 换手率(百分数原值)、f10 量比在沪深港美同义(实测 116.00700 与 105.AAPL 均可读)
103
164
  const quoteAt = Number.isFinite(row.f124) ? new Date(row.f124 * 1000).toISOString() : null
104
165
  const currency = MARKET_META[security.exchange]?.currency || 'CNY'
105
- items.push(normalizeQuote({
106
- securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'eastmoney', providerSymbol: `${row.f13}.${row.f12}`,
166
+ const quote = normalizeQuote({
167
+ securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'eastmoney', providerSymbol: secid,
107
168
  last: num(row.f2), previousClose: num(row.f18), open: num(row.f17), high: num(row.f15), low: num(row.f16),
108
169
  volume: sharesFromLots(num(row.f5), security.exchange), volumeUnit: 'share', amount: num(row.f6), amountUnit: currency,
109
170
  turnoverRate: rate(row.f8), volumeRatio: rate(row.f10),
110
171
  quoteAt, timestampKind: 'trade',
111
172
  receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
112
- }))
173
+ })
174
+ if (quote.last === null && row.f2 !== '-') invalidPrices.add(security.id)
175
+ else items.push(quote)
113
176
  }
177
+ if (rows.length && !hasIdentity) throw new StockError('BAD_PAYLOAD', '报价没有可校验的证券身份', 502)
114
178
  }
115
- await ingest(new Map(request.securities.map(s => [secidFor(s, ctx), s])))
116
- // 美股前缀兜底: 静态前缀只对应一个市场号,而交易所归属未必精确(实测 NYSE 的票分属 106/107)。
117
- // 只对首轮落空的美股补齐剩余候选,一次批量发完,不逐证券重试。
179
+ await ingest(new Map(request.securities.map(s => [QUOTE_INDEX_SECID[s.id] ?? secidFor(s, ctx), s])))
180
+ // 只对首轮落空的证券补齐同交易所候选,一次批量发完。
118
181
  const orphanUS = request.securities.filter(s => !seen.has(s.id) && isUSExchange(s.exchange))
119
182
  const altSymbols = new Map()
120
183
  for (const security of orphanUS) for (const mktNum of usSecidPrefixes(security, ctx).slice(1)) altSymbols.set(`${mktNum}.${security.code}`, security)
121
184
  if (altSymbols.size) await ingest(altSymbols)
122
- return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: request.securities.filter(s => !seen.has(s.id)).map(s => ({ securityId: s.id, code: 'NO_DATA', message: '来源未返回此证券报价' })) }
185
+ if (!items.length && invalidPrices.size) throw new StockError('BAD_PAYLOAD', '报价价格字段异常', 502)
186
+ return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: request.securities.filter(s => !seen.has(s.id) || invalidPrices.has(s.id)).map(s => ({ securityId: s.id, code: 'NO_DATA', message: '来源未返回此证券报价' })) }
123
187
  },
124
188
  async catalog(request, ctx) {
125
189
  const items = [], seen = new Set()
126
190
  const PAGE_SIZE = 100, MAX_PAGES = 50
127
191
  // 探针只拉一页: executor 单请求 8 秒预算内完成, 全量翻页是同步通道的职责
128
192
  const pages = request.probe ? 1 : MAX_PAGES
129
- let page = 1, complete = true
130
- while (page <= pages) {
193
+ let complete = false, total, hasDrift = false
194
+ for (let page = 1; page <= pages; page++) {
195
+ if (page > 1) await ctx.pauseForNextPage(0)
131
196
  const url = `${endpointOf(ctx, 'list')}?pn=${page}&pz=${PAGE_SIZE}&po=1&np=1&fltt=2&invt=2&fid=f12&fs=${LIST_FS[request.market]}&fields=f12,f13,f14`
132
197
  const body = await getJson(ctx, url)
133
- const diff = body?.data?.diff
134
- if (!Array.isArray(diff)) throw new StockError('BAD_PAYLOAD', '目录字段结构异常', 502)
135
- const total = Number(body.data.total)
136
- if (!Number.isFinite(total)) throw new StockError('BAD_PAYLOAD', '目录总数缺失', 502)
198
+ if (body.data === null) break
199
+ if (!isCount(body.data?.total)) throw new StockError('BAD_PAYLOAD', '目录总数异常', 502)
200
+ const reportedTotal = Number(body.data.total)
201
+ const diff = reportedTotal === 0 && body.data.diff === null ? [] : readDiff(body.data, '目录')
202
+ if (total !== undefined && total !== reportedTotal) hasDrift = true
203
+ total = Math.max(total ?? reportedTotal, reportedTotal)
137
204
  for (const row of diff) {
138
- const exchange = SYMBOL_PREFIX[row.f13]
139
- if (exchange !== request.market || typeof row.f12 !== 'string' || !MARKET_META[request.market].codePattern.test(row.f12) || typeof row.f14 !== 'string' || !row.f14) continue
205
+ const exchange = EXCHANGE_BY_PREFIX[row?.f13]
206
+ if (exchange !== request.market || typeof row.f12 !== 'string' || !MARKET_META[request.market].codePattern.test(row.f12) || typeof row.f14 !== 'string' || !row.f14.trim()) continue
140
207
  const id = securityId(exchange, row.f12)
141
208
  if (seen.has(id)) throw new StockError('BAD_PAYLOAD', '目录身份冲突', 502)
142
209
  seen.add(id)
143
210
  items.push(makeSecurity(exchange, row.f12, row.f14, { cnspell: '', catalogSource: request.providerInstanceId }))
144
211
  }
145
- if (total > MAX_PAGES * PAGE_SIZE) complete = false
146
- if (page * PAGE_SIZE >= total || diff.length === 0) break
147
- page++
212
+ if (items.length === total && !hasDrift) complete = true
213
+ if (items.length >= total || diff.length === 0) break
148
214
  }
149
215
  return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [], complete }
150
216
  },
@@ -153,16 +219,13 @@ export const eastmoney = {
153
219
  const count = request.market ? Math.min(20, request.limit || 10) : Math.min(50, (request.limit || 10) * 3)
154
220
  const url = `${endpointOf(ctx, 'search')}?input=${encodeURIComponent(request.q)}&type=14&token=${SUGGEST_TOKEN}&count=${count}`
155
221
  const body = await getJson(ctx, url)
156
- const rows = body?.QuotationCodeTable?.Data
157
- if (!Array.isArray(rows)) return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items: [], errors: [] }
158
222
  const items = []
159
- for (const row of rows) {
160
- const exchange = SEARCH_EXCHANGE[row.MktNum]
161
- if (!exchange || (request.market && exchange !== request.market)) continue
162
- // 美股候选写 usSymbols(代码→MktNum/JYS), kline 美股动态归属与腾讯 suffix 唯一数据来源
163
- if (isUSExchange(exchange) && ctx.usSymbols && US_MKTNUMS.includes(String(row.MktNum))) ctx.usSymbols.set(`US:${row.Code}`, { mktNum: row.MktNum, jys: row.JYS || null, at: ctx.now() })
223
+ for (const row of suggestRows(body)) {
224
+ const exchange = EXCHANGE_BY_PREFIX[row?.MktNum]
164
225
  const meta = MARKET_META[exchange]
165
- if (!meta || !meta.codePattern.test(row.Code)) continue
226
+ if (!meta || (request.market && exchange !== request.market) || !isSearchInstrument(row)) continue
227
+ if (typeof row.Code !== 'string' || !meta.codePattern.test(row.Code) || typeof row.Name !== 'string' || !row.Name.trim()) continue
228
+ if (isUSExchange(exchange)) ctx.usSymbols?.set(`US:${row.Code}`, usSymbolOf(row, ctx.now()))
166
229
  items.push(makeSecurity(exchange, row.Code, row.Name, { cnspell: typeof row.PinYin === 'string' ? row.PinYin.toLowerCase() : '', catalogSource: request.providerInstanceId }))
167
230
  }
168
231
  return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [] }
@@ -171,32 +234,34 @@ export const eastmoney = {
171
234
  secidOf(request, ctx) {
172
235
  return secidFor({ exchange: request.market, code: request.code }, ctx)
173
236
  },
174
- // 美股默认前缀猜错时经搜索联想解析真实 MktNum, 重试一次并缓存映射; K线与分时共用同一条兜底
175
- async withUsFallback(request, ctx, buildUrl, hasData, label) {
176
- let body = await getJson(ctx, buildUrl(this.secidOf(request, ctx)))
177
- if (hasData(body)) return body
237
+ // 默认前缀没有数据时,只允许搜索证明的同市场候选重试一次。
238
+ async withUsFallback(request, ctx, buildUrl, field, label) {
239
+ const secid = this.secidOf(request, ctx)
240
+ let body = await getJson(ctx, buildUrl(secid))
241
+ if (hasHistory(body, secid, field, label)) return body
178
242
  if (!isUSExchange(request.market)) throw new StockError('NO_DATA', `来源未返回此证券${label}`, 422)
179
243
  const resolved = await this.resolveUsSecid(request, ctx)
180
- if (!resolved) throw new StockError('NO_DATA', `来源未返回此证券${label}`, 422)
244
+ const alternate = resolved && `${resolved.mktNum}.${request.code}`
245
+ if (!alternate || alternate === secid) throw new StockError('NO_DATA', `来源未返回此证券${label}`, 422)
246
+ body = await getJson(ctx, buildUrl(alternate))
247
+ if (!hasHistory(body, alternate, field, label)) throw new StockError('NO_DATA', `来源未返回此证券${label}`, 422)
181
248
  ctx.usSymbols?.set(`US:${request.code}`, resolved)
182
- body = await getJson(ctx, buildUrl(`${resolved.mktNum}.${request.code}`))
183
- if (!hasData(body)) throw new StockError('NO_DATA', `来源未返回此证券${label}`, 422)
184
249
  return body
185
250
  },
186
251
  async kline(request, ctx) {
187
252
  const klt = KLT[request.period]
188
253
  if (!klt) throw new StockError('INVALID_PARAM', '东财 K 线只支持日/周/月,分时请走分时能力', 400)
189
- const body = await this.withUsFallback(request, ctx, secid => `${endpointOf(ctx, 'kline')}?secid=${secid}&fields1=f1,f2,f3&fields2=${KLINE_FIELDS}&klt=${klt}&fqt=1&end=20500101&lmt=${request.limit}`, body => !!body?.data?.klines, 'K线')
254
+ const body = await this.withUsFallback(request, ctx, secid => `${endpointOf(ctx, 'kline')}?secid=${secid}&fields1=f1,f2,f3&fields2=${KLINE_FIELDS}&klt=${klt}&fqt=1&end=20500101&lmt=${request.limit}`, 'klines', 'K线')
190
255
  return buildKlineResponse(request, body.data, ctx)
191
256
  },
192
257
  async resolveUsSecid(request, ctx) {
193
258
  const url = `${endpointOf(ctx, 'search')}?input=${encodeURIComponent(request.code)}&type=14&token=${SUGGEST_TOKEN}&count=5`
194
259
  const body = await getJson(ctx, url)
195
- const row = body?.QuotationCodeTable?.Data?.find(r => r.Code === request.code && /^10[567]$/.test(r.MktNum || ''))
196
- return row ? { mktNum: row.MktNum, jys: row.JYS || null, at: ctx.now() } : null
260
+ const row = suggestRows(body).find(r => r?.Code === request.code && marketMatchesUS(request.market, r.MktNum) && isSearchInstrument(r))
261
+ return row ? usSymbolOf(row, ctx.now()) : null
197
262
  },
198
263
  async trend(request, ctx) {
199
- const body = await this.withUsFallback(request, ctx, secid => `${endpointOf(ctx, 'trend')}?secid=${secid}&fields1=f1,f2,f3,f4,f5,f6,f7,f8&fields2=${TREND_FIELDS}&iscr=0&ndays=1`, body => !!body?.data?.trends, '分时')
264
+ const body = await this.withUsFallback(request, ctx, secid => `${endpointOf(ctx, 'trend')}?secid=${secid}&fields1=f1,f2,f3,f4,f5,f6,f7,f8&fields2=${TREND_FIELDS}&iscr=0&ndays=1`, 'trends', '分时')
200
265
  // 东财分时的时间戳一律按北京时间给出(八市场实测: 日股 08:00 对应东京 09:00 开盘, 英股 16:00 对应伦敦 08:00),
201
266
  // 不是市场本地时间; 之前按市场时区解释, 日韩英的横轴整体偏了几小时。
202
267
  const candles = body.data.trends.map(row => {
@@ -1,7 +1,7 @@
1
1
  // 新浪公开行情接口适配器:quotes(沪深港美)/catalog(沪深)。非官方端点,需Referer,无SLA;延迟未知,时间为来源快照时间。
2
2
  import { normalizeQuote, numberOrNull, parseQuoteTime, makeSecurity, securityId, StockError } from '../market-model.mjs'
3
3
  const ENDPOINT = 'https://hq.sinajs.cn/list='
4
- const LIST_ENDPOINT = 'https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData'
4
+ const CATALOG_ENDPOINT = 'https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.'
5
5
  const HEADERS = { Referer: 'https://finance.sina.com.cn/', 'User-Agent': 'Mozilla/5.0' }
6
6
  // 报价前缀与币种随市场派生(单一事实源);美股代码在来源侧是小写
7
7
  const BY_MARKET = {
@@ -18,9 +18,45 @@ const symbolOf = security => {
18
18
  }
19
19
  // 探针代表证券(各市场实测可达的流动性标的)
20
20
  const PROBE_SECURITY = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA' }
21
- // 新浪价格固定三位以上小数,A股最小变动0.01,裁剪到两位不损失精度;港美同理按分呈现
22
- const trim = value => /^\d+(\.\d+)?$/.test(value) ? Number(value).toFixed(2) : value
23
21
  const count = value => { const parsed = numberOrNull(value); return parsed === null ? null : String(Math.round(parsed)) }
22
+ const PAGE_SIZE = 80, MAX_PAGES = 100, PAGE_GAP = 600, SHORT_PAGE_BACKOFF = 3 * 1000
23
+ const CATALOG_NODES = { XSHG: { prefix: 'sh', node: 'sh_a' }, XSHE: { prefix: 'sz', node: 'sz_a' } }
24
+
25
+ async function fetchCatalogJson(path, ctx) {
26
+ let response
27
+ try {
28
+ response = await ctx.fetch(`${CATALOG_ENDPOINT}${path}`, { headers: HEADERS, signal: ctx.signal, redirect: 'error' })
29
+ } catch (e) {
30
+ if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
31
+ if (e instanceof StockError) throw e
32
+ throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
33
+ }
34
+ if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
35
+ return response.json().catch(e => {
36
+ if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
37
+ if (!(e instanceof SyntaxError)) throw new StockError('NETWORK', '无法读取目录响应', 502, { retryable: true })
38
+ throw new StockError('BAD_PAYLOAD', '目录响应不是JSON', 502)
39
+ })
40
+ }
41
+
42
+ async function fetchCatalogTotal(market, ctx) {
43
+ const { node } = CATALOG_NODES[market]
44
+ const body = await fetchCatalogJson(`getHQNodeStockCount?node=${node}`, ctx)
45
+ const total = Number(body)
46
+ if (!(typeof body === 'number' || typeof body === 'string' && /^\d+$/.test(body.trim())) || !Number.isSafeInteger(total) || total < 0) {
47
+ throw new StockError('BAD_PAYLOAD', '目录总数字段异常', 502)
48
+ }
49
+ return total
50
+ }
51
+
52
+ async function fetchCatalogPage(market, ctx, page, size) {
53
+ const { prefix, node } = CATALOG_NODES[market]
54
+ const rows = await fetchCatalogJson(`getHQNodeData?page=${page}&num=${size}&sort=symbol&asc=1&node=${node}`, ctx)
55
+ if (!Array.isArray(rows) || rows.length > size) throw new StockError('BAD_PAYLOAD', '目录字段结构异常', 502)
56
+ const valid = rows.filter(row => typeof row?.code === 'string' && /^\d{6}$/.test(row.code) && row.symbol === `${prefix}${row.code}` && typeof row.name === 'string' && row.name.trim())
57
+ if (rows.length && !valid.length) throw new StockError('BAD_PAYLOAD', '目录没有可校验的证券身份', 502)
58
+ return { rows: valid, size: rows.length }
59
+ }
24
60
  // 各市场字段位置:沪深34列、港股25列、美股36列,同一行内的列义由前缀决定
25
61
  const FIELD_MAP = {
26
62
  cn: f => ({ open: f[1], previousClose: f[2], last: f[3], high: f[4], low: f[5], volume: f[8], amount: f[9], quoteAt: `${f[30]} ${f[31]}` }),
@@ -30,14 +66,11 @@ const FIELD_MAP = {
30
66
  const kindOf = providerSymbol => providerSymbol.startsWith('rt_hk') ? 'hk' : providerSymbol.startsWith('gb_') ? 'us' : 'cn'
31
67
  const MIN_FIELDS = { cn: 32, hk: 20, us: 28 }
32
68
  export const sina = {
33
- descriptor: { adapterId: 'sina', capabilities: ['quotes', 'catalog'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '新浪公开接口:免凭据,沪深港美行情与沪深目录' },
69
+ descriptor: { adapterId: 'sina', capabilities: ['quotes', 'catalog'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 60, pagedCatalog: true, credential: 'none', description: '新浪公开接口:免凭据,沪深港美行情与沪深目录' },
34
70
  async probe(request, ctx) {
35
71
  if (request.capability === 'catalog') {
36
- // 探针只拉一页验证端点连通,不做全量分页。
37
- const response = await ctx.fetch(`${LIST_ENDPOINT}?page=1&num=5&sort=symbol&asc=1&node=${request.market === 'XSHG' ? 'sh_a' : 'sz_a'}`, { headers: HEADERS, signal: ctx.signal, redirect: 'error' })
38
- if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
39
- const rows = await response.json()
40
- if (!Array.isArray(rows) || !rows.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
72
+ const { rows } = await fetchCatalogPage(request.market, ctx, 1, 5)
73
+ if (!rows.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
41
74
  return { status: 'ready', capability: 'catalog', market: request.market, instrument: 'equity' }
42
75
  }
43
76
  const security = request.securities?.[0] || { exchange: request.market, code: PROBE_SECURITY[request.market] || '600519' }
@@ -46,43 +79,32 @@ export const sina = {
46
79
  return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
47
80
  },
48
81
  async catalog(request, ctx) {
49
- // 分市场节点sh_a/sz_a直接取本市场全量,分页间保持来源要求的节流间隔。
50
- const PAGE_SIZE = 80, MAX_PAGES = 100, PAGE_GAP = 600
51
- const prefix = request.market === 'XSHG' ? 'sh' : 'sz', node = request.market === 'XSHG' ? 'sh_a' : 'sz_a'
52
82
  const items = [], seen = new Set()
53
- let page = 1, complete = true, retriedShort = false
54
- while (page <= MAX_PAGES) {
55
- let rows
56
- try {
57
- const response = await ctx.fetch(`${LIST_ENDPOINT}?page=${page}&num=${PAGE_SIZE}&sort=symbol&asc=1&node=${node}`, { headers: HEADERS, signal: ctx.signal, redirect: 'error' })
58
- if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
59
- rows = await response.json()
60
- } catch (e) {
61
- if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
62
- if (e instanceof StockError) throw e
63
- throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
64
- }
65
- if (!Array.isArray(rows)) throw new StockError('BAD_PAYLOAD', '目录字段结构异常', 502)
66
- if (rows.length < PAGE_SIZE && !retriedShort) {
67
- // 连续请求过密时来源会降级返回短页,退避后重拉本页一次再终止。
68
- retriedShort = true
69
- await new Promise((resolve, reject) => { const t = setTimeout(resolve, 3 * 1000); ctx.signal.addEventListener('abort', () => { clearTimeout(t); reject(new StockError('CANCELLED', '请求已取消', 503)) }, { once: true }) })
70
- continue
83
+ const total = await fetchCatalogTotal(request.market, ctx)
84
+ const pages = Math.min(Math.ceil(total / PAGE_SIZE), MAX_PAGES)
85
+ let hasGap = false
86
+ for (let page = 1; page <= pages; page++) {
87
+ await ctx.pauseForNextPage(page === 1 ? 0 : PAGE_GAP)
88
+ const expected = Math.min(PAGE_SIZE, total - (page - 1) * PAGE_SIZE)
89
+ let current = await fetchCatalogPage(request.market, ctx, page, PAGE_SIZE)
90
+ if (current.size < expected) {
91
+ const first = current
92
+ await ctx.pauseForNextPage(SHORT_PAGE_BACKOFF)
93
+ current = await fetchCatalogPage(request.market, ctx, page, PAGE_SIZE)
94
+ // 重试即使补满,丢了已见身份也不能证明完整。
95
+ const confirmed = new Set(current.rows.map(row => row.code))
96
+ if (first.rows.some(row => !confirmed.has(row.code))) hasGap = true
97
+ if (first.rows.length > current.rows.length) current = first
71
98
  }
72
- retriedShort = false
73
- for (const row of rows) {
74
- if (typeof row.symbol !== 'string' || !row.symbol.startsWith(prefix) || !/^\d{6}$/.test(row.code || '') || typeof row.name !== 'string' || !row.name) continue
99
+ if (current.size !== expected || current.rows.length !== current.size) hasGap = true
100
+ for (const row of current.rows) {
75
101
  const id = securityId(request.market, row.code)
76
102
  if (seen.has(id)) throw new StockError('BAD_PAYLOAD', '目录身份冲突', 502)
77
103
  seen.add(id)
78
104
  items.push(makeSecurity(request.market, row.code, row.name, { cnspell: '', catalogSource: request.providerInstanceId }))
79
105
  }
80
- if (rows.length < PAGE_SIZE) break
81
- if (page === MAX_PAGES) complete = false
82
- page++
83
- await new Promise((resolve, reject) => { const t = setTimeout(resolve, PAGE_GAP); ctx.signal.addEventListener('abort', () => { clearTimeout(t); reject(new StockError('CANCELLED', '请求已取消', 503)) }, { once: true }) })
84
106
  }
85
- return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [], complete }
107
+ return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [], complete: !hasGap && total > 0 && items.length === total }
86
108
  },
87
109
  async quotes(request, ctx) {
88
110
  const symbols = new Map(request.securities.map(s => [symbolOf(s), s]))
@@ -112,7 +134,7 @@ export const sina = {
112
134
  const mapped = FIELD_MAP[kind](f)
113
135
  items.push(normalizeQuote({
114
136
  securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'sina', providerSymbol,
115
- last: trim(mapped.last), previousClose: trim(mapped.previousClose), open: trim(mapped.open), high: trim(mapped.high), low: trim(mapped.low),
137
+ last: mapped.last, previousClose: mapped.previousClose, open: mapped.open, high: mapped.high, low: mapped.low,
116
138
  volume: count(mapped.volume), volumeUnit: 'share', amount: count(mapped.amount), amountUnit: BY_MARKET[security.exchange].currency,
117
139
  quoteAt: parseQuoteTime(mapped.quoteAt), timestampKind: 'trade',
118
140
  receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
@@ -1,5 +1,6 @@
1
1
  // 腾讯公开行情接口适配器:quotes+kline+trend(备源)。非官方端点,无SLA,随时可能失效;延迟未知,行情时间戳为来源快照时间。
2
2
  import { normalizeQuote, parseQuoteTime, StockError, MARKET_META, sharesFromLots, amountFromWan, zonedUnixSeconds } from '../market-model.mjs'
3
+ import { isUSExchange, marketMatchesUS } from './us-markets.mjs'
3
4
  // 分时时间戳与东财同一基准: 腾讯给的是北京时间
4
5
  const SOURCE_ZONE = 'Asia/Shanghai'
5
6
  // 官方默认端点表(key 供 instance.endpoints 覆盖, 反代/镜像场景由 ctx.endpoints 提供同名 key)
@@ -13,9 +14,8 @@ const endpointOf = (ctx, key) => ctx.endpoints?.[key] || DEFAULT_ENDPOINTS[key]
13
14
  const SYMBOL_PREFIX = { XSHG: 'sh', XSHE: 'sz', XHKG: 'hk' }
14
15
  // 美股 symbol 后缀由搜索联想 JYS 字段映射(2026-10-30 实测: suggest 返回 JYS="NASDAQ"/"NYSE"/"AMEX";
15
16
  // 腾讯侧 .OQ/.N/裸代码同价有效, .A/.U 形态返回空数据——AMEX 走裸代码兜底)。
16
- const JYS_TO_SUFFIX = { NASDAQ: 'OQ', NYSE: 'N', AMEX: '' }
17
+ const US_KLINE_SYMBOL = { 105: { jys: 'NASDAQ', suffix: 'OQ' }, 106: { jys: 'NYSE', suffix: 'N' }, 107: { jys: 'AMEX', suffix: '' } }
17
18
  // 美股行情端点要 us 前缀(实测 usAAPL 有效, 裸 AAPL 返回空);K线另有 JYS 后缀逻辑, 不复用这张表。
18
- const isUSExchange = exchange => exchange === 'XNAS' || exchange === 'XNYS'
19
19
  const symbolOf = security => isUSExchange(security.exchange) ? `us${security.code}` : SYMBOL_PREFIX[security.exchange] ? `${SYMBOL_PREFIX[security.exchange]}${security.code}` : `${security.code}`
20
20
  // kline request 用 market 字段(exchange 是 security 形态的字段名); 港股 code 统一 5 位对齐腾讯 hk00700 实测形态。
21
21
  const klineSymbolOf = request => {
@@ -99,9 +99,10 @@ export const tencent = {
99
99
  },
100
100
  async kline(request, ctx) {
101
101
  let symbol = klineSymbolOf(request)
102
- if (request.market === 'XNAS' || request.market === 'XNYS') {
102
+ if (isUSExchange(request.market)) {
103
103
  const mapped = ctx.usSymbols?.get(`US:${request.code}`)
104
- const suffix = mapped ? JYS_TO_SUFFIX[mapped.jys] : undefined
104
+ const known = marketMatchesUS(request.market, mapped?.mktNum) ? US_KLINE_SYMBOL[mapped.mktNum] : undefined
105
+ const suffix = known && mapped.jys === known.jys ? known.suffix : undefined
105
106
  if (suffix === undefined) throw new StockError('UNSUPPORTED_CAPABILITY', '腾讯来源的美股K线需先经搜索建立代码映射', 422)
106
107
  symbol = suffix ? `us${request.code}.${suffix}` : `us${request.code}`
107
108
  }
@@ -0,0 +1,4 @@
1
+ // 东财市场号映射到插件的美股身份;插件在 XNYS 下同时收录 NYSE 和 AMEX。
2
+ export const US_MARKET_EXCHANGE = { 105: 'XNAS', 106: 'XNYS', 107: 'XNYS' }
3
+ export const isUSExchange = exchange => exchange === 'XNAS' || exchange === 'XNYS'
4
+ export const marketMatchesUS = (market, mktNum) => isUSExchange(market) && US_MARKET_EXCHANGE[mktNum] === market
@@ -1,18 +1,18 @@
1
1
  // 雪球公开行情接口适配器:quotes(沪深港美)。
2
2
  // 与新浪/东财的差别:同一请求可混装多市场,且额外给出换手率/振幅/市值/总股本。
3
3
  // 接口需要 xq_a_token cookie,匿名访问首页即可拿到,本适配器惰性获取并按 TTL 缓存。
4
- import { normalizeQuote, numberOrNull, parseQuoteTime, StockError } from '../market-model.mjs'
4
+ import { normalizeQuote, numberOrNull, StockError } from '../market-model.mjs'
5
5
  const ENDPOINT = 'https://stock.xueqiu.com/v5/stock/batch/quote.json'
6
- const HOME = 'https://xueqiu.com/'
6
+ const HOME = 'https://www.xueqiu.com/'
7
7
  const HEADERS = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' }
8
- // cookie 有效期远长于一次会话, 缓存到进程内并按 TTL 刷新, 避免每个请求都先访问首页
9
8
  const TOKEN_TTL = 30 * 60 * 1000
10
- let token = { value: null, until: 0 }
9
+ // 出口与其传输生命周期绑定,避免在直连和代理之间混用匿名凭据。
10
+ const tokenByEgress = new WeakMap()
11
+ const tokenRejected = response => response.status === 400 || response.status === 401
12
+ const cancelled = () => new StockError('CANCELLED', '请求已取消', 503)
11
13
  // 沪深用大写市场前缀, 港股与美股直接用代码本身(实测 HK00700 返回空, 00700 才有数据)
12
14
  const symbolOf = security => (security.exchange === 'XSHG' ? 'SH' : security.exchange === 'XSHE' ? 'SZ' : '') + security.code
13
15
  const PROBE_SECURITY = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA' }
14
- // 缺失(undefined/null/'')一律当缺失: Number(null) 是 0, 只比有限性会把「来源没给」显示成 0 价/0 量
15
- const quote = value => { const n = numberOrNull(value); return n === null ? null : n.toFixed(2) }
16
16
 
17
17
  export const xueqiu = {
18
18
  descriptor: { adapterId: 'xueqiu', capabilities: ['quotes'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '雪球公开接口:免凭据(匿名 token),沪深港美行情,可混装多市场,额外提供换手率与市值' },
@@ -25,20 +25,27 @@ export const xueqiu = {
25
25
  },
26
26
  async quotes(request, ctx) {
27
27
  const symbols = new Map(request.securities.map(s => [symbolOf(s), s]))
28
+ const key = ctx.egressKey ?? ctx.fetch
29
+ const requestQuotes = token => ctx.fetch(`${ENDPOINT}?symbol=${[...symbols.keys()].join(',')}`, { headers: { ...HEADERS, Cookie: token.value, Referer: HOME }, signal: ctx.signal, redirect: 'error' })
28
30
  let response
29
31
  try {
30
- response = await ctx.fetch(`${ENDPOINT}?symbol=${[...symbols.keys()].join(',')}`, { headers: { ...HEADERS, Cookie: await cookieOf(ctx), Referer: HOME }, signal: ctx.signal, redirect: 'error' })
31
- // token 过期时来源返回 400/刷新一次重试, 让缓存失真自愈
32
- if (response.status === 400) {
33
- token = { value: null, until: 0 }
34
- response = await ctx.fetch(`${ENDPOINT}?symbol=${[...symbols.keys()].join(',')}`, { headers: { ...HEADERS, Cookie: await cookieOf(ctx) }, signal: ctx.signal, redirect: 'error' })
32
+ let token = await tokenOf(ctx, key)
33
+ response = await requestQuotes(token)
34
+ if (tokenRejected(response)) {
35
+ response.body?.cancel().catch(() => {})
36
+ token = await tokenOf(ctx, key, token)
37
+ response = await requestQuotes(token)
38
+ if (tokenRejected(response) && tokenByEgress.get(key)?.token === token) tokenByEgress.delete(key)
35
39
  }
36
40
  } catch (e) {
37
- if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
41
+ if (ctx.signal.aborted) throw cancelled()
38
42
  if (e instanceof StockError) throw e
39
43
  throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
40
44
  }
41
- if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
45
+ if (!response.ok) {
46
+ response.body?.cancel().catch(() => {})
47
+ throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
48
+ }
42
49
  const body = await response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
43
50
  const items = body?.data?.items
44
51
  if (!Array.isArray(items)) throw new StockError('BAD_PAYLOAD', '来源字段结构异常', 502)
@@ -54,7 +61,7 @@ export const xueqiu = {
54
61
  const volume = numberOrNull(row.volume), amount = numberOrNull(row.amount), marketCapital = numberOrNull(row.market_capital), stamp = numberOrNull(row.timestamp)
55
62
  result.push(normalizeQuote({
56
63
  securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'xueqiu', providerSymbol: row.symbol,
57
- last: quote(row.current), previousClose: quote(row.last_close), open: quote(row.open), high: quote(row.high), low: quote(row.low),
64
+ last: row.current, previousClose: row.last_close, open: row.open, high: row.high, low: row.low,
58
65
  volume: volume === null ? null : String(Math.round(volume)), volumeUnit: 'share',
59
66
  amount: amount === null ? null : String(Math.round(amount)), amountUnit: String(row.currency || ''),
60
67
  quoteAt: stamp === null ? null : new Date(stamp).toISOString(), timestampKind: 'trade',
@@ -67,17 +74,49 @@ export const xueqiu = {
67
74
  },
68
75
  }
69
76
 
70
- async function cookieOf(ctx) {
71
- if (token.value && token.until > ctx.now()) return token.value
77
+ async function tokenOf(ctx, key, rejected) {
78
+ if (ctx.signal.aborted) throw cancelled()
79
+ const current = tokenByEgress.get(key)
80
+ if (current?.token !== rejected && current?.token?.until > ctx.now()) return current.token
81
+ if (current?.pending) {
82
+ // 等待者可独立取消,不关闭当前出口上共享的首页请求。
83
+ let onAbort
84
+ const aborted = new Promise((_, reject) => { onAbort = () => reject(cancelled()) })
85
+ ctx.signal.addEventListener('abort', onAbort, { once: true })
86
+ try {
87
+ return await Promise.race([current.pending, aborted])
88
+ } catch (error) {
89
+ // 本地配额和生命周期属于发起者,不属于出口。
90
+ if (ctx.signal.aborted || !(error.local || ['CANCELLED', 'RATE_LIMIT', 'BUDGET_UNKNOWN'].includes(error.code))) throw error
91
+ return tokenOf(ctx, key, rejected)
92
+ } finally {
93
+ ctx.signal.removeEventListener('abort', onAbort)
94
+ }
95
+ }
96
+ const pending = fetchToken(ctx)
97
+ tokenByEgress.set(key, { pending })
98
+ try {
99
+ const token = await pending
100
+ tokenByEgress.set(key, { token })
101
+ return token
102
+ } catch (error) {
103
+ tokenByEgress.delete(key)
104
+ throw error
105
+ }
106
+ }
107
+
108
+ async function fetchToken(ctx) {
72
109
  let response
73
- try { response = await ctx.fetch(HOME, { headers: HEADERS, signal: ctx.signal, redirect: 'follow' }) } catch (e) {
110
+ try {
111
+ response = await ctx.fetch(HOME, { headers: HEADERS, signal: ctx.signal, redirect: 'follow' })
112
+ } catch (error) {
74
113
  if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
75
- if (e instanceof StockError) throw e
76
- throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
114
+ throw error
77
115
  }
78
- const raw = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie() : []
79
- const value = raw.map(c => c.split(';')[0]).filter(c => c.includes('=')).join('; ')
116
+ response.body?.cancel().catch(() => {})
117
+ if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
118
+ const cookies = response.headers?.getSetCookie?.() ?? []
119
+ const value = cookies.map(cookie => cookie.split(';', 1)[0].trim()).find(cookie => /^xq_a_token=[^\s;]+$/.test(cookie))
80
120
  if (!value) throw new StockError('BAD_PAYLOAD', '来源未返回访问令牌', 502)
81
- token = { value, until: ctx.now() + TOKEN_TTL }
82
- return value
121
+ return { value, until: ctx.now() + TOKEN_TTL }
83
122
  }