@mzzsfy/dsh-stock-assistant 0.0.0-stage → 0.3.2

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.
@@ -0,0 +1,81 @@
1
+ // 雪球公开行情接口适配器:quotes(沪深港美)。
2
+ // 与新浪/东财的差别:同一请求可混装多市场,且额外给出换手率/振幅/市值/总股本。
3
+ // 接口需要 xq_a_token cookie,匿名访问首页即可拿到,本适配器惰性获取并按 TTL 缓存。
4
+ import { normalizeQuote, parseQuoteTime, StockError } from '../market-model.mjs'
5
+ const ENDPOINT = 'https://stock.xueqiu.com/v5/stock/batch/quote.json'
6
+ const HOME = 'https://xueqiu.com/'
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
+ const TOKEN_TTL = 30 * 60 * 1000
10
+ let token = { value: null, until: 0 }
11
+ // 沪深用大写市场前缀, 港股与美股直接用代码本身(实测 HK00700 返回空, 00700 才有数据)
12
+ const symbolOf = security => (security.exchange === 'XSHG' ? 'SH' : security.exchange === 'XSHE' ? 'SZ' : '') + security.code
13
+ const PROBE_SECURITY = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA' }
14
+ const quote = value => { const n = Number(value); return Number.isFinite(n) ? n.toFixed(2) : null }
15
+
16
+ export const xueqiu = {
17
+ descriptor: { adapterId: 'xueqiu', capabilities: ['quotes'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '雪球公开接口:免凭据(匿名 token),沪深港美行情,可混装多市场,额外提供换手率与市值' },
18
+ async probe(request, ctx) {
19
+ const security = request.securities?.[0] || { exchange: request.market, code: PROBE_SECURITY[request.market] }
20
+ if (!security.code) throw new StockError('UNSUPPORTED_CAPABILITY', '雪球来源不提供该市场行情', 422)
21
+ const rows = await this.quotes({ ...request, securities: [security] }, ctx)
22
+ if (!rows.items.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
23
+ return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
24
+ },
25
+ async quotes(request, ctx) {
26
+ const symbols = new Map(request.securities.map(s => [symbolOf(s), s]))
27
+ let response
28
+ try {
29
+ response = await ctx.fetch(`${ENDPOINT}?symbol=${[...symbols.keys()].join(',')}`, { headers: { ...HEADERS, Cookie: await cookieOf(ctx), Referer: HOME }, signal: ctx.signal, redirect: 'error' })
30
+ // token 过期时来源返回 400/刷新一次重试, 让缓存失真自愈
31
+ if (response.status === 400) {
32
+ token = { value: null, until: 0 }
33
+ response = await ctx.fetch(`${ENDPOINT}?symbol=${[...symbols.keys()].join(',')}`, { headers: { ...HEADERS, Cookie: await cookieOf(ctx) }, signal: ctx.signal, redirect: 'error' })
34
+ }
35
+ } catch (e) {
36
+ if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
37
+ if (e instanceof StockError) throw e
38
+ throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
39
+ }
40
+ if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
41
+ const body = await response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
42
+ const items = body?.data?.items
43
+ if (!Array.isArray(items)) throw new StockError('BAD_PAYLOAD', '来源字段结构异常', 502)
44
+ const seen = new Set(), result = []
45
+ for (const entry of items) {
46
+ const row = entry?.quote
47
+ if (!row) continue
48
+ const security = symbols.get(String(row.symbol || ''))
49
+ if (!security) continue
50
+ if (seen.has(security.id)) throw new StockError('BAD_PAYLOAD', '报价身份冲突', 502)
51
+ seen.add(security.id)
52
+ // 雪球 volume 统一是股, amount 统一是元; 时间戳是毫秒 Unix
53
+ result.push(normalizeQuote({
54
+ securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'xueqiu', providerSymbol: row.symbol,
55
+ last: quote(row.current), previousClose: quote(row.last_close), open: quote(row.open), high: quote(row.high), low: quote(row.low),
56
+ volume: Number.isFinite(Number(row.volume)) ? String(Math.round(Number(row.volume))) : null, volumeUnit: 'share',
57
+ amount: Number.isFinite(Number(row.amount)) ? String(Math.round(Number(row.amount))) : null, amountUnit: String(row.currency || ''),
58
+ quoteAt: Number.isFinite(Number(row.timestamp)) ? new Date(Number(row.timestamp)).toISOString() : null, timestampKind: 'trade',
59
+ receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
60
+ turnoverRate: Number.isFinite(Number(row.turnover_rate)) ? Number(row.turnover_rate) : null,
61
+ marketCapital: Number.isFinite(Number(row.market_capital)) ? Math.round(Number(row.market_capital)) : null,
62
+ }))
63
+ }
64
+ return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items: result, errors: request.securities.filter(s => !seen.has(s.id)).map(s => ({ securityId: s.id, code: 'NO_DATA', message: '来源未返回此证券报价' })) }
65
+ },
66
+ }
67
+
68
+ async function cookieOf(ctx) {
69
+ if (token.value && token.until > ctx.now()) return token.value
70
+ let response
71
+ try { response = await ctx.fetch(HOME, { headers: HEADERS, signal: ctx.signal, redirect: 'follow' }) } catch (e) {
72
+ if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
73
+ if (e instanceof StockError) throw e
74
+ throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
75
+ }
76
+ const raw = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie() : []
77
+ const value = raw.map(c => c.split(';')[0]).filter(c => c.includes('=')).join('; ')
78
+ if (!value) throw new StockError('BAD_PAYLOAD', '来源未返回访问令牌', 502)
79
+ token = { value, until: ctx.now() + TOKEN_TTL }
80
+ return value
81
+ }
package/src/routes.mjs ADDED
@@ -0,0 +1,65 @@
1
+ import { z } from 'zod'
2
+ import { StockError, fail } from './market-model.mjs'
3
+ const PREFIX = '/api/stock-assistant'
4
+ const operationSchema = z.object({ operationId: z.uuid(), expectedRevision: z.number().int().nonnegative() })
5
+ async function body(req) {
6
+ const chunks = []; let size = 0
7
+ for await (const chunk of req) {
8
+ size += chunk.length
9
+ if (size > 64 * 1024) fail('BODY_TOO_LARGE', '请求内容过大', 413)
10
+ chunks.push(chunk)
11
+ }
12
+ try { return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') }
13
+ catch { fail('INVALID_JSON', '请求必须为JSON') }
14
+ }
15
+ function json(res, status, value) {
16
+ if (res.destroyed || res.writableEnded) return
17
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value))
18
+ }
19
+ export function registerRoutes(webServer, app) {
20
+ const handlers = {
21
+ snapshot: ['GET', () => app.snapshot()],
22
+ search: ['GET', async (input, signal) => await app.search(input.q || '', input.phase === 'remote' ? 'remote' : 'local', signal)],
23
+ browse: ['GET', input => app.browse(input)],
24
+ watchlist: ['POST', input => { operationSchema.parse(input); return app.watchlist(input) }],
25
+ preferences: ['POST', input => { operationSchema.parse(input); return app.preferences({ ...input, payload: input.patch }) }],
26
+ configuration: ['POST', input => { operationSchema.parse(input); return app.configuration({ ...input, payload: { providers: input.providers, routes: input.routes } }) }],
27
+ 'provider-check': ['POST', (input, signal) => app.providerCheck(input, signal)],
28
+ 'catalog-sync': ['POST', input => app.sync(input)],
29
+ 'route-selection': ['POST', (input, signal) => app.routeSelection(input, signal)],
30
+ refresh: ['POST', (input, signal) => app.refresh(input, signal)],
31
+ kline: ['GET', (input, signal) => app.kline(input, signal)],
32
+ }
33
+ const controllers = new Set(), disposers = []
34
+ let stopped = false
35
+ try {
36
+ for (const [name, [method, action]] of Object.entries(handlers)) disposers.push(webServer.register({ kind: 'exact', path: `${PREFIX}/${name}`, async handler(req, res) {
37
+ if (stopped) return json(res, 503, { ok: false, error: { code: 'STOPPED', message: '工具已停止' } })
38
+ if (req.method !== method) { res.setHeader('Allow', method); return json(res, 405, { ok: false, error: { code: 'METHOD_NOT_ALLOWED', message: '请求方法不支持' } }) }
39
+ const controller = new AbortController(); controllers.add(controller)
40
+ const onClose = () => { if (!res.writableEnded) controller.abort() }
41
+ res.on('close', onClose)
42
+ const timeout = name === 'provider-check' ? 60 * 1000 : name === 'catalog-sync' ? 120 * 1000 : 10 * 1000
43
+ let timer
44
+ try {
45
+ const input = method === 'GET' ? Object.fromEntries(new URL(req.url, 'http://local').searchParams) : await body(req)
46
+ if (method === 'POST' && (input === null || typeof input !== 'object' || Array.isArray(input))) fail('INVALID_REQUEST', '请求内容必须为JSON对象')
47
+ if (method === 'POST' && req.headers.origin) {
48
+ let same = false
49
+ try { same = new URL(req.headers.origin).host === req.headers.host } catch {}
50
+ if (!same) fail('CROSS_ORIGIN', '不接受跨源写请求', 403)
51
+ }
52
+ const data = await Promise.race([
53
+ Promise.resolve(action(input, controller.signal)),
54
+ new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(new StockError('TIMEOUT', '操作超时,请稍后重试', 504)) }, timeout) }),
55
+ new Promise((_, reject) => controller.signal.addEventListener('abort', () => reject(new StockError('CANCELLED', '操作已取消', stopped ? 503 : 504)), { once: true })),
56
+ ])
57
+ json(res, 200, { ok: true, data })
58
+ } catch (e) {
59
+ const error = e instanceof StockError ? e : new StockError('INVALID_REQUEST', e instanceof z.ZodError ? '请求参数格式错误' : '股票工具请求失败', e instanceof z.ZodError ? 400 : 500)
60
+ json(res, error.status, { ok: false, error: { code: error.code, message: error.message, retryable: error.retryable, retryAfterMs: error.retryAfterMs }, ...(error.revision === undefined ? {} : { revision: error.revision }), ...(e.snapshot ? { snapshot: e.snapshot } : {}) })
61
+ } finally { clearTimeout(timer); controllers.delete(controller); res.removeListener('close', onClose) }
62
+ } }))
63
+ } catch (e) { for (const dispose of disposers.reverse()) dispose(); throw e }
64
+ return () => { stopped = true; for (const dispose of disposers.reverse()) dispose(); for (const c of controllers) c.abort(); controllers.clear() }
65
+ }
@@ -0,0 +1,98 @@
1
+ import { z } from 'zod'
2
+ import { fail } from './market-model.mjs'
3
+ import { MARKET_META } from './market-model.mjs'
4
+ const id = z.string().regex(/^[a-z][a-z0-9-]{0,47}$/)
5
+ // 用户标在图上并参与盈亏计算的价格点位。kind 决定它在盈亏里扮演什么角色:
6
+ // cost 是持仓成本, target 是打算卖出的价
7
+ export const markSchema = z.strictObject({ id: z.string().min(1).max(40), price: z.number().positive(), kind: z.enum(['cost', 'target']) })
8
+ export const marksSchema = z.array(markSchema).max(12).default([]).superRefine((list, ctx) => {
9
+ if (new Set(list.map(mark => mark.id)).size !== list.length) ctx.addIssue({ code: 'custom', message: '价格标记 id 重复' })
10
+ if (new Set(list.map(mark => `${mark.kind}:${mark.price}`)).size !== list.length) ctx.addIssue({ code: 'custom', message: '同类型的价格不能重复' })
11
+ })
12
+ const rate = z.number().int().positive().max(100000)
13
+ export const capability = z.enum(['quotes', 'catalog', 'search', 'calendar', 'kline'])
14
+ export const marketSchema = z.enum(Object.keys(MARKET_META))
15
+ export const providerSchema = z.strictObject({
16
+ id, adapterId: id, enabled: z.boolean(), credentialEnv: z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).nullable(), quotaGroup: id,
17
+ budget: z.strictObject({ requestsPerMinute: rate.nullable(), dailyRequestLimit: rate.nullable(), billingUnit: z.enum(['request', 'symbol']), symbolCreditsPerMinute: rate.nullable(), capabilityLimits: z.partialRecord(capability, rate) }),
18
+ endpoints: z.record(z.string().url()).optional(),
19
+ // 上游出口代理(反代/正向代理统一走 URL): http(s)://[user:pass@]host:port, 凭据在 userinfo
20
+ proxy: z.string().url().refine(v => v.startsWith('http://') || v.startsWith('https://'), '代理仅支持 http(s) URL').optional(),
21
+ }).refine(p => p.credentialEnv !== null || p.budget.requestsPerMinute !== null, '免凭据来源必须声明保守预算')
22
+ export const routeSchema = z.strictObject({
23
+ id, capability, market: marketSchema, instrument: z.literal('equity'), primaryInstanceId: id,
24
+ fallbackInstanceIds: z.array(id).max(1), failoverMode: z.enum(['off', 'network']), maxDelaySeconds: z.number().nonnegative().nullable(), acceptUnknownDelay: z.boolean(),
25
+ })
26
+ // GET query 唯一入口: limit 为字符串形态需 coerce
27
+ export const klineQuerySchema = z.strictObject({
28
+ securityId: z.string().regex(/^[\w]+:equity:[\w.]{1,15}$/),
29
+ period: z.enum(['trend', '1d', '1w', '1M']),
30
+ limit: z.coerce.number().int().min(20).max(1000).default(250),
31
+ // 强制刷新:客户端详情页刷新走 ?force=1,服务端据此跳过缓存读;缺省按缓存
32
+ force: z.enum(['0', '1']).optional(),
33
+ })
34
+ // 路由上限: 八市场×(quotes/catalog/search/calendar/kline) 全开 40 条封顶
35
+ const configSchema = z.strictObject({ providers: z.array(providerSchema).max(8), routes: z.array(routeSchema).max(40) })
36
+ export const preferencesSchema = z.strictObject({ refreshSeconds: z.union([z.literal(15), z.literal(30), z.literal(60)]), colorMode: z.enum(['red-up', 'green-up']) })
37
+ export const securitySchema = z.object({ id: z.string(), exchange: marketSchema, code: z.string(), officialName: z.string().min(1).max(100), instrument: z.literal('equity'), currency: z.string(), timezone: z.string(), priceScale: z.number().int(), listingStatus: z.string() }).superRefine((s, ctx) => {
38
+ const meta = MARKET_META[s.exchange]
39
+ if (!meta || !meta.codePattern.test(s.code) || s.id !== `${s.exchange}:equity:${s.code}`) { ctx.addIssue({ code: 'custom', message: '证券身份不一致' }); return }
40
+ if (s.currency !== meta.currency || s.timezone !== meta.timezone || s.priceScale !== meta.priceScale) ctx.addIssue({ code: 'custom', message: '证券市场元数据与该市场不符' })
41
+ })
42
+ export function parseConfiguration(value) {
43
+ const result = configSchema.safeParse(value)
44
+ if (!result.success) fail('INVALID_CONFIGURATION', '数据源配置字段或格式无效', 422)
45
+ const config = result.data, seen = new Set(), providerIds = new Set()
46
+ for (const p of config.providers) {
47
+ if (providerIds.has(p.id)) fail('DUPLICATE_PROVIDER', '数据源实例名称重复', 422)
48
+ providerIds.add(p.id)
49
+ if (p.budget.billingUnit === 'symbol' && p.budget.symbolCreditsPerMinute === null) fail('INVALID_BUDGET', '按证券计费必须提供证券额度', 422)
50
+ const same = config.providers.filter(other => other.adapterId === p.adapterId && other.credentialEnv === p.credentialEnv)
51
+ if (same.some(other => other.quotaGroup !== p.quotaGroup)) fail('INVALID_BUDGET', '同账号引用必须共享额度组', 422)
52
+ }
53
+ const routeIds = new Set()
54
+ for (const r of config.routes) {
55
+ const key = `${r.capability}:${r.market}:${r.instrument}`
56
+ if (seen.has(key) || routeIds.has(r.id)) fail('DUPLICATE_ROUTE', '数据能力路由重复', 422)
57
+ seen.add(key); routeIds.add(r.id)
58
+ const targets = [r.primaryInstanceId, ...r.fallbackInstanceIds]
59
+ if (new Set(targets).size !== targets.length || targets.some(target => !config.providers.some(p => p.id === target && p.enabled))) fail('INVALID_ROUTE', '路由引用了不存在或禁用的数据源', 422)
60
+ if (!['quotes', 'kline'].includes(r.capability) && (r.failoverMode !== 'off' || r.fallbackInstanceIds.length)) fail('INVALID_ROUTE', '只有报价与K线支持备用源', 422)
61
+ if (r.failoverMode !== 'off' && !r.fallbackInstanceIds.length) fail('INVALID_ROUTE', '自动切换需要备用报价源', 422)
62
+ }
63
+ return config
64
+ }
65
+ export const controlSchema = z.object({ revision: z.number().int().nonnegative(), routingRevision: z.number().int().nonnegative(), watchlist: z.object({ order: z.array(z.string()).max(100), items: z.record(z.string(), securitySchema.safeExtend({ alias: z.string(), pinned: z.boolean(), marks: marksSchema, group: z.string().refine(s => [...s.trim()].length <= 12 && !/[\u0000-\u001f]/.test(s)).default('') })) }), preferences: preferencesSchema, providers: z.array(providerSchema), routes: z.array(routeSchema), operations: z.array(z.object({ id: z.uuid(), hash: z.string(), at: z.number(), result: z.object({ revision: z.number() }).passthrough(), action: z.string(), payload: z.unknown() })).max(256) }).superRefine((control, ctx) => {
66
+ const w = control.watchlist
67
+ if (new Set(w.order).size !== w.order.length || w.order.length !== Object.keys(w.items).length || w.order.some(id => w.items[id]?.id !== id)) ctx.addIssue({ code: 'custom', message: '自选序列与证券不一致' })
68
+ let unpinned = false
69
+ for (const id of w.order) { if (!w.items[id]?.pinned) unpinned = true; else if (unpinned) ctx.addIssue({ code: 'custom', message: '置顶序列混乱' }) }
70
+ try { parseConfiguration({ providers: control.providers, routes: control.routes }) } catch { ctx.addIssue({ code: 'custom', message: '来源配置不一致' }) }
71
+ })
72
+ export const domainSpec = { name: 'stock_assistant', version: 1, layout: 'single', tables: { control: { valueSchema: controlSchema }, cache: { valueSchema: z.object({ kind: z.string(), source: z.string(), fetchedAt: z.number(), payload: z.unknown() }) } } }
73
+ // 推荐配置:四个免凭据源,东财做八市场主力,其余按实测最强能力分派备份——公开源无SLA,能覆盖的市场都串上备源。
74
+ export const defaultConfig = () => {
75
+ const budget = (requestsPerMinute, capabilityLimits = {}) => ({ requestsPerMinute, dailyRequestLimit: null, billingUnit: 'request', symbolCreditsPerMinute: null, capabilityLimits })
76
+ const providers = [
77
+ { id: 'em-default', adapterId: 'eastmoney', enabled: true, credentialEnv: null, quotaGroup: 'free-quote', budget: budget(60, { kline: 30 }) },
78
+ { id: 'sn-backup', adapterId: 'sina', enabled: true, credentialEnv: null, quotaGroup: 'free-list', budget: budget(120, { catalog: 60 }) },
79
+ { id: 'tx-backup', adapterId: 'tencent', enabled: true, credentialEnv: null, quotaGroup: 'free-backup', budget: budget(60, { kline: 20 }) },
80
+ { id: 'xq-backup', adapterId: 'xueqiu', enabled: true, credentialEnv: null, quotaGroup: 'free-xq', budget: budget(60) },
81
+ ]
82
+ // 备用源只在探针可验证的组合上声明: 腾讯美股K线需先由搜索建立代码映射, 探针期必然不可用
83
+ const klineBackup = new Set(['XSHG', 'XSHE', 'XHKG'])
84
+ // 目录覆盖八市场: 东财 clist 的 fs 对日韩英同样有节点(日股 3752 / 韩股 2866 / 英股股票 4608), 全量翻页在 50 页上限内
85
+ const catalogCovered = new Set(['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS', 'XJPX', 'XKRX', 'XLON'])
86
+ // 报价备源按市场派: 沪深港走新浪(免cookie、单位已是股), 美股走雪球(时间戳是UTC毫秒, 与东财同口径)
87
+ const quoteBackupOf = market => (market === 'XNAS' || market === 'XNYS' ? 'xq-backup' : ['XSHG', 'XSHE', 'XHKG'].includes(market) ? 'sn-backup' : null)
88
+ const route = (market, capability, primary, fallback = null) => ({ id: `${market.toLowerCase()}-${capability}`, capability, market, instrument: 'equity', primaryInstanceId: primary, fallbackInstanceIds: fallback ? [fallback] : [], failoverMode: fallback ? 'network' : 'off', maxDelaySeconds: null, acceptUnknownDelay: true })
89
+ const routes = ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS', 'XJPX', 'XKRX', 'XLON'].flatMap(market => [
90
+ // 目录统一走东财: 一个源覆盖八个市场, 不必为沪深单开新浪分支;目录不支持备用源
91
+ ...(catalogCovered.has(market) ? [route(market, 'catalog', 'em-default')] : []),
92
+ route(market, 'search', 'em-default'),
93
+ route(market, 'quotes', 'em-default', quoteBackupOf(market)),
94
+ route(market, 'kline', 'em-default', klineBackup.has(market) ? 'tx-backup' : null),
95
+ ])
96
+ return { providers, routes }
97
+ }
98
+ export const initialControl = () => ({ revision: 0, routingRevision: 0, watchlist: { order: [], items: {} }, preferences: { refreshSeconds: 15, colorMode: 'red-up' }, ...defaultConfig(), operations: [] })
@@ -0,0 +1,22 @@
1
+ // vendor 静态服务: prefix 路由白名单单文件; 命中读盘 200, 未命中/读异常 404。
2
+ import { readFileSync, statSync } from 'node:fs'
3
+ import { join, dirname } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ export const VENDOR_FILE = 'lightweight-charts.standalone.production.js'
6
+ const VENDOR_PATH = join(dirname(fileURLToPath(import.meta.url)), '..', 'vendor', VENDOR_FILE)
7
+ export const VENDOR_PREFIX = '/plugins-vendor/dsh-stock-assistant'
8
+ const VENDOR_MAX_AGE = 24 * 60 * 60
9
+ // 预判定: 文件存在且非空才声明 vendorAvailable(先于应用构建, 随快照下发)
10
+ export function vendorReadable() {
11
+ statSync(VENDOR_PATH)
12
+ return readFileSync(VENDOR_PATH).length > 0
13
+ }
14
+ export function serveVendor(req, res) {
15
+ const target = new URL(req.url, 'http://local').pathname.slice(VENDOR_PREFIX.length).replace(/^\//, '')
16
+ if (target !== VENDOR_FILE) { res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('not found'); return }
17
+ try {
18
+ const body = readFileSync(VENDOR_PATH)
19
+ res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': `public, max-age=${VENDOR_MAX_AGE}`, 'Content-Length': body.length })
20
+ res.end(body)
21
+ } catch { res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('not found') }
22
+ }
@@ -0,0 +1,82 @@
1
+ import { z } from 'zod'
2
+ import { fail, parseSecurityId } from './market-model.mjs'
3
+ import { securitySchema, marksSchema } from './schemas.mjs'
4
+ // 自选身份八市场: parseSecurityId 是唯一事实源(市场/代码形态随 MARKET_META)
5
+ const securityId = z.string().refine(v => { try { parseSecurityId(v); return true } catch { return false } })
6
+ const payloads = {
7
+ add: z.strictObject({ securityId }), remove: z.strictObject({ securityId }),
8
+ restore: z.strictObject({ removeOperationId: z.uuid() }),
9
+ alias: z.strictObject({ securityId, alias: z.string().refine(s => [...s].length <= 30) }),
10
+ marks: z.strictObject({ securityId, marks: marksSchema }),
11
+ // 组名进来就是用户输入, 校验在入口做: 只靠 state 写入后的不变式兜底会把它报成 500 内部错误
12
+ group: z.strictObject({ securityIds: z.array(securityId).min(1), group: z.string().refine(s => { const t = s.trim(); return [...t].length <= 12 && !/[\u0000-\u001f]/.test(t) }, '分组名最长 12 字且不能含控制字符') }),
13
+ groupRename: z.strictObject({ from: z.string().min(1), to: z.string().refine(s => { const t = s.trim(); return t.length > 0 && [...t].length <= 12 && !/[\u0000-\u001f]/.test(t) }, '分组名最长 12 字且不能含控制字符') }),
14
+ groupRemove: z.strictObject({ group: z.string().min(1) }),
15
+ pin: z.strictObject({ securityId, pinned: z.boolean() }),
16
+ move: z.strictObject({ securityId, beforeId: securityId.nullable() }),
17
+ // 拖拽排序: 提交完整显示序, 前端算好顺序一次落库, 避免逐行 move 的中间态
18
+ reorder: z.strictObject({ order: z.array(securityId).min(1) }),
19
+ }
20
+ export function createWatchlistService(state, resolveSecurity, now = Date.now) {
21
+ return {
22
+ async execute(operation) {
23
+ const parsed = payloads[operation.action]?.safeParse(operation.payload)
24
+ if (!parsed?.success) fail('INVALID_OPERATION', '自选操作参数无效')
25
+ const p = parsed.data
26
+ return state.mutate(operation, control => {
27
+ const w = control.watchlist, item = w.items[p.securityId]
28
+ const insert = (id, beforeId) => { const index = w.order.indexOf(beforeId); w.order.splice(index < 0 ? w.order.length : index, 0, id) }
29
+ const regionEnd = pinned => w.order.find(id => w.items[id].pinned !== pinned && !w.items[id].pinned) || null
30
+ if (operation.action === 'reorder') {
31
+ const ids = p.order
32
+ if (ids.length !== w.order.length || new Set(ids).size !== ids.length || ids.some(id => !w.items[id])) fail('INVALID_ORDER', '排序参数无效')
33
+ // 置顶项必须连续占据最前段: 与渲染分段一致, 防止拖动把置顶项沉底
34
+ if (ids.some((id, index) => !w.items[id].pinned && ids.slice(index + 1).some(next => w.items[next].pinned))) fail('INVALID_ORDER', '置顶项必须保持在列表最前')
35
+ w.order = ids
36
+ return control
37
+ }
38
+ if (operation.action === 'add') {
39
+ if (item) return control
40
+ if (w.order.length >= 100) fail('LIMIT_REACHED', '最多添加100只自选', 422)
41
+ const security = resolveSecurity(p.securityId)
42
+ if (!security || !securitySchema.safeParse(security).success) fail('CANDIDATE_EXPIRED', '候选已过期,请重新搜索', 409)
43
+ w.items[p.securityId] = { ...security, alias: '', pinned: false, marks: [], group: '' }; w.order.push(p.securityId)
44
+ } else if (operation.action === 'restore') {
45
+ const deleted = control.operations.find(o => o.id === p.removeOperationId && o.action === 'remove')
46
+ const restore = deleted?.result.restore
47
+ if (!restore || now() - deleted.at > 8 * 1000) fail('RESTORE_EXPIRED', '撤销已过期,请重新添加', 409)
48
+ if (w.items[restore.item.id]) return control
49
+ if (w.order.length >= 100) fail('LIMIT_REACHED', '自选数量已达上限', 422)
50
+ const restored = restore.item; w.items[restored.id] = restored
51
+ const same = id => w.items[id]?.pinned === restored.pinned
52
+ if (restore.previousId && same(restore.previousId)) {
53
+ const after = w.order.indexOf(restore.previousId) + 1; w.order.splice(after, 0, restored.id)
54
+ } else if (restore.nextId && same(restore.nextId)) insert(restored.id, restore.nextId)
55
+ else insert(restored.id, restored.pinned ? regionEnd(true) : null)
56
+ } else if (operation.action === 'group') { for (const id of p.securityIds) { if (!w.items[id]) fail('NOT_FOUND', '证券已被移除', 404); w.items[id].group = p.group.trim() } }
57
+ else if (operation.action === 'groupRename') { if (!w.order.some(id => w.items[id].group === p.from)) fail('NOT_FOUND', '分组不存在', 404); for (const id of w.order) if (w.items[id].group === p.from) w.items[id].group = p.to.trim() }
58
+ else if (operation.action === 'groupRemove') { if (!w.order.some(id => w.items[id].group === p.group)) fail('NOT_FOUND', '分组不存在', 404); for (const id of w.order) if (w.items[id].group === p.group) w.items[id].group = '' }
59
+ else {
60
+ if (!item) fail('NOT_FOUND', '证券已被移除', 404)
61
+ if (operation.action === 'remove') {
62
+ const i = w.order.indexOf(p.securityId)
63
+ control.operationResult = { restore: { item, previousId: w.order[i - 1] || null, nextId: w.order[i + 1] || null } }
64
+ w.order.splice(i, 1); delete w.items[p.securityId]
65
+ } else if (operation.action === 'alias') item.alias = p.alias.trim()
66
+ else if (operation.action === 'marks') item.marks = p.marks
67
+ else if (operation.action === 'pin') {
68
+ if (item.pinned === p.pinned) return control
69
+ w.order = w.order.filter(id => id !== item.id); item.pinned = p.pinned
70
+ insert(item.id, item.pinned ? regionEnd(true) : null)
71
+ } else {
72
+ if (p.beforeId === item.id) return control
73
+ if (p.beforeId && (!w.items[p.beforeId] || w.items[p.beforeId].pinned !== item.pinned)) fail('INVALID_MOVE', '只能在同一置顶区域移动', 422)
74
+ w.order = w.order.filter(id => id !== item.id)
75
+ insert(item.id, p.beforeId || (item.pinned ? regionEnd(true) : null))
76
+ }
77
+ }
78
+ return control
79
+ })
80
+ },
81
+ }
82
+ }
package/src/state.mjs ADDED
@@ -0,0 +1,56 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { domainSpec, initialControl, controlSchema } from './schemas.mjs'
3
+ import { fail } from './market-model.mjs'
4
+ const DAY = 24 * 60 * 60 * 1000
5
+ export const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex')
6
+ export async function openState(storageDomain, changed = () => {}, now = Date.now) {
7
+ const domain = await storageDomain.open(domainSpec)
8
+ const table = domain.table('control'), cache = domain.table('cache')
9
+ try {
10
+ if (!table.get('root')) await table.put('root', initialControl())
11
+ controlSchema.parse(table.get('root'))
12
+ } catch (e) { await domain.close(); throw e }
13
+ let tail = Promise.resolve(), stopped = false
14
+ return {
15
+ get: () => structuredClone(table.get('root')),
16
+ cache,
17
+ replay(operation) {
18
+ const prior = table.get('root').operations.find(o => o.id === operation.operationId && now() - o.at < DAY)
19
+ if (!prior) return null
20
+ if (prior.hash !== digest({ action: operation.action, payload: operation.payload })) fail('OPERATION_REUSED', '操作标识已用于其他请求', 409)
21
+ return structuredClone(prior.result)
22
+ },
23
+ mutate(operation, transform) {
24
+ const run = async () => {
25
+ if (stopped) fail('STOPPED', '股票工具已停止', 503)
26
+ const current = table.get('root'), hash = digest({ action: operation.action, payload: operation.payload })
27
+ const existing = current.operations.find(o => o.id === operation.operationId && now() - o.at < DAY)
28
+ if (existing) {
29
+ if (existing.hash !== hash) fail('OPERATION_REUSED', '操作标识已用于其他请求', 409)
30
+ return structuredClone(existing.result)
31
+ }
32
+ if (operation.expectedRevision !== current.revision) fail('REVISION_CONFLICT', '数据已被其他页面修改,请重新确认', 409, { revision: current.revision })
33
+ const next = transform(structuredClone(current))
34
+ if (!next || JSON.stringify(next) === JSON.stringify(current)) return { revision: current.revision, unchanged: true }
35
+ next.revision = current.revision + 1
36
+ const result = { revision: next.revision, unchanged: false, ...(next.operationResult || {}) }
37
+ delete next.operationResult
38
+ next.operations = [...current.operations.filter(o => now() - o.at < DAY), { id: operation.operationId, hash, at: now(), result, action: operation.action, payload: operation.payload }].slice(-256)
39
+ try { controlSchema.parse(next) } catch (e) { fail('INVARIANT_VIOLATION', '写入结果违反内部不变式', 500, { cause: e }) }
40
+ try {
41
+ await table.update('root', stored => {
42
+ if (stored.revision !== current.revision) fail('REVISION_CONFLICT', '数据版本已变化', 409)
43
+ return next
44
+ })
45
+ } catch (e) {
46
+ if (e.code === 'REVISION_CONFLICT') throw e
47
+ fail('STORAGE_WRITE_FAILED', '保存失败,原数据未更改', 503)
48
+ }
49
+ changed()
50
+ return result
51
+ }
52
+ const job = tail.then(run); tail = job.catch(() => {}); return job
53
+ },
54
+ async close() { stopped = true; await tail; await domain.close() },
55
+ }
56
+ }