Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions packages/api-reference/src/api-page-meta.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { apiPageMeta, endpointList, wsCommandList } from './openapi-markdown'

const raw = readFileSync(fileURLToPath(new URL('../../../openapi.yaml', import.meta.url)), 'utf8')
const LOCALES = ['en', 'zh-CN', 'zh-HK'] as const
const eps = new Map(endpointList(raw).map((e) => [e.operationId, e]))
const ws = new Map(wsCommandList(raw).map((c) => [c.id, c]))

describe('apiPageMeta', () => {
it.each(LOCALES)('%s:REST 页标题和描述带方法与路径,WS 页带 WebSocket cmd', (locale) => {
for (const m of apiPageMeta(raw, locale)) {
const ep = eps.get(m.id)
const label = ep ? `${ep.method} ${ep.path}` : `WebSocket cmd ${ws.get(m.id)!.cmd}`
expect(m.title.endsWith(` (${label})`), m.id).toBe(true)
expect(m.description.startsWith(`${label} — `), m.id).toBe(true)
}
})

it.each(LOCALES)('%s:描述不超过 160 字符,超出时以省略号收尾', (locale) => {
for (const m of apiPageMeta(raw, locale)) {
expect(m.description.length, m.id).toBeLessThanOrEqual(160)
if (m.description.length === 160) expect(m.description.endsWith('…'), m.id).toBe(true)
}
})

it.each(LOCALES)('%s:同语言 API 页之间标题、描述都不重复', (locale) => {
const meta = apiPageMeta(raw, locale)
expect(new Set(meta.map((m) => m.title)).size).toBe(meta.length)
expect(new Set(meta.map((m) => m.description)).size).toBe(meta.length)
})

it('样例:Top Movers 和 Intraday', () => {
const en = new Map(apiPageMeta(raw, 'en').map((m) => [m.id, m]))
const topMovers = eps.get('top_movers')!
expect(en.get('top_movers')!.title).toBe(`Top Movers (${topMovers.method} ${topMovers.path})`)
expect(en.get('ws-intraday')!.title).toBe(`Intraday (WebSocket cmd ${ws.get('ws-intraday')!.cmd})`)
})
})
34 changes: 26 additions & 8 deletions packages/api-reference/src/openapi-markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,9 @@ export function wsCommandList(
return allWsCommands(rawYaml).map((c) => ({ id: c.id, name: c.name, cmd: c.cmd, direction: c.direction }))
}

/** 描述的首段纯文本,去掉 Markdown 标记并截到 160 字符以内,用作 meta description。`:::` 提示块(如账户限制)跳过,没有其他正文时才退回用它。 */
function metaDescription(md: string): string {
/** 描述的首段纯文本,去掉 Markdown 标记并截到 160 字符以内,用作 meta description。`:::` 提示块(如账户限制)跳过,没有其他正文时才退回用它。
* `prefix`(接口方法和路径)放在最前面、计入 160 字符,截断时保留它,保证和同名文档页的描述不同。 */
function metaDescription(md: string, prefix = ''): string {
const body = md.replace(/^:::[^\n]*\n[\s\S]*?^:::[ \t]*$/gm, '').trim() || md.replace(/^:::.*$/gm, '').trim()
const para = body.split(/\n\s*\n/)[0] ?? ''
const text = para
Expand All @@ -196,10 +197,22 @@ function metaDescription(md: string): string {
.replace(/[`*_>#]/g, '')
.replace(/\s+/g, ' ')
.trim()
return text.length > 160 ? text.slice(0, 159) + '…' : text
const full = prefix ? `${prefix} — ${text}` : text
return full.length > 160 ? full.slice(0, 159) + '…' : full
}

/** 每个 API 单页(REST 接口与 WS 命令)的本地化标题与描述,给 /docs/api/<id> 静态页用。 */
/** REST 接口写「方法 路径」,WebSocket 写「WebSocket 路径」或「WebSocket cmd N」。 */
function endpointLabel(method: string, path: string): string {
return `${method.toUpperCase() === 'WEBSOCKET' ? 'WebSocket' : method.toUpperCase()} ${path}`
}

function wsCommandLabel(c: WsCommandItem): string {
return c.cmd != null ? `WebSocket cmd ${c.cmd}` : 'WebSocket'
}

/** 每个 API 单页(REST 接口与 WS 命令)的本地化标题与描述,给 /docs/api/<id> 静态页用。
* API 单页和同一接口的分类文档页(如 /docs/market/top-movers)标题、首段描述相同,搜索引擎会当成重复页只收一份。
* 这里给标题和描述都带上接口方法和路径(WebSocket 命令带 cmd 编号),和文档页区分开。 */
export function apiPageMeta(rawYaml: string, locale: Locale): Array<{ id: string; title: string; description: string }> {
const { groups } = parseSpec(rawYaml)
const out: Array<{ id: string; title: string; description: string }> = []
Expand All @@ -209,18 +222,23 @@ export function apiPageMeta(rawYaml: string, locale: Locale): Array<{ id: string
const op = ep.operation
if (seen.has(op.operationId)) continue
seen.add(op.operationId)
const label = endpointLabel(ep.method, ep.path)
out.push({
id: op.operationId,
title: pickLocale(op.summary, op['x-summary-zh'], op['x-summary-zh-hk'], locale),
description: metaDescription(pickLocale(op.description, op['x-description-zh'], op['x-description-zh-hk'], locale)),
title: `${pickLocale(op.summary, op['x-summary-zh'], op['x-summary-zh-hk'], locale)} (${label})`,
description: metaDescription(
pickLocale(op.description, op['x-description-zh'], op['x-description-zh-hk'], locale),
label
),
})
}
}
for (const c of allWsCommands(rawYaml)) {
const label = wsCommandLabel(c)
out.push({
id: c.id,
title: pickLocale(c.name, c.nameZh, c.nameZhHk, locale),
description: metaDescription(pickLocale(c.description, c.descriptionZh, c.descriptionZhHk, locale)),
title: `${pickLocale(c.name, c.nameZh, c.nameZhHk, locale)} (${label})`,
description: metaDescription(pickLocale(c.description, c.descriptionZh, c.descriptionZhHk, locale), label),
})
}
return out
Expand Down
34 changes: 34 additions & 0 deletions src/lib/api-page-urls.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { describe, expect, it } from 'vitest'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { apiPageUrls } from './api-page-urls'
import { buildSeoLinks } from './page-meta'

const HOST = 'https://open.longbridge.com'
const raw = readFileSync(fileURLToPath(new URL('../../openapi.yaml', import.meta.url)), 'utf8')
const urls = apiPageUrls(raw)

describe('apiPageUrls', () => {
it('三种语言各一份,和 /docs/api/[op] 路由一致', () => {
const en = urls.filter((u) => u.startsWith('/docs/api/'))
expect(en.length).toBeGreaterThan(0)
expect(urls.filter((u) => u.startsWith('/zh-CN/docs/api/')).length).toBe(en.length)
expect(urls.filter((u) => u.startsWith('/zh-HK/docs/api/')).length).toBe(en.length)
expect(new Set(urls).size).toBe(urls.length)
})

it('API 单页拿到三语 hreflang 和 x-default,三个语言版本互指同一组地址', () => {
const published = new Set(urls)
const en = buildSeoLinks('/docs/api/top_movers.html', HOST, published)
expect(en.canonical).toBe(`${HOST}/docs/api/top_movers`)
expect(en.alternates.map((a) => [a.hreflang, a.href])).toEqual([
['en', `${HOST}/docs/api/top_movers`],
['zh-Hans', `${HOST}/zh-CN/docs/api/top_movers`],
['zh-Hant', `${HOST}/zh-HK/docs/api/top_movers`],
['x-default', `${HOST}/docs/api/top_movers`],
])
const hk = buildSeoLinks('/zh-HK/docs/api/top_movers.html', HOST, published)
expect(hk.canonical).toBe(`${HOST}/zh-HK/docs/api/top_movers`)
expect(hk.alternates).toEqual(en.alternates)
})
})
16 changes: 16 additions & 0 deletions src/lib/api-page-urls.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { Locale } from '@longbridge/openapi-utils'
import { apiPageMeta } from '@longbridge/openapi-api-reference/markdown'

/** 与 src/pages/docs/api/[op].astro、src/pages/[locale]/docs/api/[op].astro 生成的路由一一对应。 */
const API_PAGE_LOCALES: ReadonlyArray<readonly [Locale, string]> = [
['en', ''],
['zh-CN', '/zh-CN'],
['zh-HK', '/zh-HK'],
]

/** API Reference 单页的 URL(`/docs/api/<id>`、`/zh-CN/docs/api/<id>`、`/zh-HK/docs/api/<id>`)。 */
export function apiPageUrls(rawYaml: string): string[] {
return API_PAGE_LOCALES.flatMap(([locale, prefix]) =>
apiPageMeta(rawYaml, locale).map((m) => `${prefix}/docs/api/${m.id}`)
)
}
9 changes: 7 additions & 2 deletions src/lib/published-urls.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import { getCollection } from 'astro:content'
import { currentRegion, includedInRegion, resolveUrl } from '@longbridge/openapi-utils'
import { apiPageUrls } from './api-page-urls'
import rawYaml from '../../openapi.yaml?raw'

let cache: Promise<ReadonlySet<string>> | undefined

async function load(): Promise<ReadonlySet<string>> {
const region = currentRegion()
const entries = await getCollection('docs')
return new Set(entries.map((e) => resolveUrl(e)).filter((url: string) => includedInRegion(url, region)))
const docs = entries.map((e) => resolveUrl(e)).filter((url: string) => includedInRegion(url, region))
// API Reference 单页不在 docs 集合里,但三种语言都会生成(路由不按 region 过滤),
// 不加进来的话这些页拿不到 hreflang。
return new Set([...docs, ...apiPageUrls(rawYaml)])
}

/** 当前 region 下真实生成的页面 URL(`/`、`/docs`、`/zh-CN/docs/x`),整个构建只算一次。 */
/** 当前 region 下真实生成的页面 URL(`/`、`/docs`、`/zh-CN/docs/x`、`/docs/api/<id>`),整个构建只算一次。 */
export function getPublishedUrls(): Promise<ReadonlySet<string>> {
if (!cache) cache = load()
return cache
Expand Down