From 1d770454246ea4fa982086f57db09e411e33af72 Mon Sep 17 00:00:00 2001 From: "Tiago Siebler @ Siebly.io" Date: Wed, 2 Dec 2026 12:56:18 +0000 Subject: [PATCH] feat: index guide-linked Bybit client and type references --- README.md | 2 +- scripts/publish-search.mjs | 11 ++-- scripts/search-pages.mjs | 77 ++++++++++++++++++++++++--- scripts/search-pages.test.mjs | 34 +++++++++++- sdks/kraken/docs/guides/websockets.md | 2 +- 5 files changed, 113 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index a18f80ad..41878e67 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ npm run check:public ## Publishing -After a successful GitHub Pages deployment, the `search` job indexes the pages in the deployed sitemap that fall outside `/api/`. It converts the rendered article to Markdown so included examples match the page. Search results carry the GitHub Pages URL in `item.metadata.source_url`. The job skips unchanged documents and removes retired guides that it previously uploaded. +After a successful GitHub Pages deployment, the `search` job indexes the pages in the deployed sitemap outside `/api/`, plus the Bybit REST and WebSocket clients and the types named in Bybit guides or linked from the constructors and guide methods. It converts the rendered article to Markdown so included examples match the page. Search results carry the GitHub Pages URL in `item.metadata.source_url`. Bybit API references carry `doc_kind: api_reference`. For a reference-only lookup, pass `{"doc_kind":"api_reference"}` in `ai_search_options.retrieval.filters`. The instance defines `doc_kind` as a text metadata field. The job skips unchanged documents and removes retired pages that it previously uploaded. The `indexnow` job then waits until that published revision is live and submits documentation URLs to [IndexNow](https://www.indexnow.org/) so Bing can pick them up quickly. The build snapshots the live sitemap first, and the job submits new URLs plus any whose lastmod changed. The combined sitemap does not currently include lastmod, so the job falls back to the built sitemap, capped at 10,000 URLs, and skips the request if the list is empty. The ownership key is a public file at the docs root; IndexNow fetches it to verify the ping. A failed IndexNow request is logged and does not fail the deployment. diff --git a/scripts/publish-search.mjs b/scripts/publish-search.mjs index 374ae01f..6fc63644 100644 --- a/scripts/publish-search.mjs +++ b/scripts/publish-search.mjs @@ -7,6 +7,11 @@ const publisher = 'sieblyio/docs'; const prefix = 'siebly-docs__'; const submitted = new Set(['queued', 'running', 'completed']); +function matchesPage(item, page) { + return item?.metadata?.content_digest === page.digest && + item.metadata.source_url === page.url && item.metadata.doc_kind === page.docKind; +} + export async function sync(bundle, items) { const remote = await items.list(); const existing = new Map(remote.map(item => [item.key, item])); @@ -24,10 +29,10 @@ export async function sync(bundle, items) { for (const [key, page] of desired) { const old = existing.get(key); // A matching item that is still queued or running is already on its way. Uploading it again would restart its indexing. - if (submitted.has(old?.status) && old.next_action !== 'DELETE' && old.metadata?.content_digest === page.digest && old.metadata?.source_url === page.url) continue; + if (submitted.has(old?.status) && old.next_action !== 'DELETE' && matchesPage(old, page)) continue; const form = new FormData(); form.set('file', new Blob([page.text], { type: 'text/markdown' }), key); - form.set('metadata', JSON.stringify({ publisher, source_url: page.url, content_digest: page.digest })); + form.set('metadata', JSON.stringify({ publisher, source_url: page.url, content_digest: page.digest, doc_kind: page.docKind })); await items.upload(form); changed++; } @@ -39,7 +44,7 @@ export async function sync(bundle, items) { const item = indexed.get(key); if (item?.status === 'error' || item?.status === 'skipped') throw new Error(key + ': ' + (item.error || item.status)); if (item?.status !== 'completed' || item.next_action || !item.chunks_count || - item.metadata?.content_digest !== page.digest || item.metadata?.source_url !== page.url) pending.push(key); + !matchesPage(item, page)) pending.push(key); } if (!pending.length) break; if (Date.now() >= deadline) { diff --git a/scripts/search-pages.mjs b/scripts/search-pages.mjs index 4f53f95a..591e3aaf 100644 --- a/scripts/search-pages.mjs +++ b/scripts/search-pages.mjs @@ -3,11 +3,14 @@ import path from 'node:path'; import { pathToFileURL } from 'node:url'; import { parse } from 'node-html-parser'; import { NodeHtmlMarkdown } from 'node-html-markdown'; +import bybit from '../sdks/bybit/sdk.config.mjs'; const markdown = new NodeHtmlMarkdown(); -export function article(html, url) { - const doc = parse(html); +async function readArticle(dist, base, url) { + const route = url.pathname.slice(base.pathname.length); + const file = path.join(dist, !route || route.endsWith('/') ? route + 'index.html' : route); + const doc = parse(await readFile(file, 'utf8')); const main = doc.querySelector('main'); if (!main?.querySelector('h1') || doc.querySelector('link[rel=canonical]')?.getAttribute('href') !== url.href) { throw new Error('Missing article or incorrect canonical: ' + url.href); @@ -16,7 +19,63 @@ export function article(html, url) { for (const link of main.querySelectorAll('a[href]')) link.setAttribute('href', new URL(link.getAttribute('href'), url).href); // Syntax highlighting splits code across spans. Preserve the rendered code and line breaks. for (const code of main.querySelectorAll('pre code')) code.set_content(code.rawText); - return [doc.querySelector('title').text.trim(), url.href, '', markdown.translate(main.toString()), ''].join('\n'); + return { title: doc.querySelector('title').text.trim(), main }; +} + +function searchText(article, url, context = []) { + return [article.title, url.href, ...context, '', markdown.translate(article.main.toString()), ''].join('\n'); +} + +async function bybitReferences(dist, base, urls, guides) { + const api = new URL('bybit/api/', base); + const typePages = new Map(); + for (const url of urls) { + const match = /^(?:interfaces|type-aliases|enumerations)\/([^/]+)\.html$/.exec(url.href.slice(api.href.length)); + if (match) typePages.set(url.href, { symbol: match[1], usedBy: new Set() }); + } + const symbols = new Set(guides.match(/\b[A-Z][A-Za-z0-9_$]*\b/g)); + const methods = new Set(bybit.referenceHelp.map(({ client, method }) => client + '.' + method)); + // Keep the receiver inside its example. URLSearchParams.get() is unrelated to RestClientV5.get(). + for (const [, code] of guides.matchAll(/^```[^\n]*\n([\s\S]*?)^```/gm)) { + const clients = new Map(Array.from(code.matchAll(/\b(\w+)\s*=\s*new\s+(\w+)\s*\(/g), match => [match[1], match[2]])); + for (const [, receiver, method] of code.matchAll(/\b(\w+)\.(\w+)\s*\(/g)) { + if (clients.has(receiver)) methods.add(clients.get(receiver) + '.' + method); + } + } + const anchorLinks = new Set(Array.from(guides.matchAll(/\]\(([^()\s]+#[^()\s]+)\)/g), match => match[1])); + const pages = []; + for (const client of bybit.clients) { + const url = new URL('classes/' + client + '.html', api); + if (!urls.some(entry => entry.href === url.href)) throw new Error('Bybit client is missing from the sitemap: ' + client); + const article = await readArticle(dist, base, url); + // Follow types only in the constructor and methods used or linked by the guides. + for (const heading of article.main.querySelectorAll('h3')) { + const member = heading.text.trim().replace(/\(\)$/, ''); + if (heading.id !== 'constructor' && !methods.has(client + '.' + member) && !anchorLinks.has(url.href + '#' + heading.id)) continue; + for (let node = heading.nextElementSibling; node && !['H1', 'H2', 'H3'].includes(node.tagName); node = node.nextElementSibling) { + for (const link of node.querySelectorAll('a[href]')) { + const type = typePages.get(link.getAttribute('href').split('#')[0]); + if (type) type.usedBy.add(heading.id === 'constructor' ? 'new ' + client : client + '.' + member); + } + } + } + pages.push({ url: url.href, docKind: 'api_reference', text: searchText(article, url, [bybit.name + ' SDK API reference for ' + client]) }); + } + for (const [href, { symbol, usedBy }] of typePages) { + if (!usedBy.size && !symbols.has(symbol)) continue; + const url = new URL(href); + const article = await readArticle(dist, base, url); + const context = [bybit.name + ' SDK API reference for ' + symbol]; + if (usedBy.size) context.push('Used by ' + [...usedBy].sort().join(', ') + '.'); + const properties = article.main.querySelector('h2#properties')?.nextElementSibling; + if (properties?.tagName === 'TABLE' && properties.querySelector('th')?.text.trim() === 'Property') { + const fields = properties.querySelectorAll('tbody tr').map(row => row.querySelector('td')?.text.trim()); + const required = fields.filter(name => name && !name.endsWith('?')); + if (required.length) context.push('Required fields on ' + symbol + ': ' + required.join(', ') + '.'); + } + pages.push({ url: href, docKind: 'api_reference', text: searchText(article, url, context) }); + } + return pages; } export async function collectPages(dist) { @@ -25,14 +84,19 @@ export async function collectPages(dist) { const base = new URL(manifest.siteUrl); const sitemap = await readFile(path.join(dist, 'sitemap.xml'), 'utf8'); const pages = []; + const bybitApi = []; + const guides = []; for (const entry of parse(sitemap).querySelectorAll('loc')) { const url = new URL(entry.text); if (!url.href.startsWith(base.href) || url.search || url.hash) throw new Error('Unexpected sitemap URL: ' + url); const route = url.pathname.slice(base.pathname.length); + if (route.startsWith('bybit/api/')) bybitApi.push(url); if (route.split('/').includes('api')) continue; - const file = path.join(dist, !route || route.endsWith('/') ? route + 'index.html' : route); - pages.push({ url: url.href, text: article(await readFile(file, 'utf8'), url) }); + const text = searchText(await readArticle(dist, base, url), url); + pages.push({ url: url.href, text }); + if (route.startsWith('bybit/')) guides.push(text); } + if (bybitApi.length) pages.push(...await bybitReferences(dist, base, bybitApi, guides.join('\n'))); if (!pages.length || new Set(pages.map(p => p.url)).size !== pages.length) throw new Error('Empty or duplicate search pages.'); return { revision: manifest.documentationRevision, siteUrl: base.href, pages }; } @@ -40,5 +104,6 @@ export async function collectPages(dist) { if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { const bundle = await collectPages(process.argv[2]); await writeFile(process.argv[3], JSON.stringify(bundle)); - console.log('Prepared ' + bundle.pages.length + ' documentation pages for AI Search.'); + console.log('Prepared ' + bundle.pages.length + ' documentation pages for AI Search, including ' + + bundle.pages.filter(page => page.docKind === 'api_reference').length + ' Bybit API references.'); } diff --git a/scripts/search-pages.test.mjs b/scripts/search-pages.test.mjs index 1bcf21f4..0981c7bf 100644 --- a/scripts/search-pages.test.mjs +++ b/scripts/search-pages.test.mjs @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { mkdtemp, writeFile, rm } from 'node:fs/promises'; +import { mkdir, mkdtemp, writeFile, rm } from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import { collectPages } from './search-pages.mjs'; @@ -37,6 +37,9 @@ test('sync updates changed guides and prunes only its own retired pages after su await sync(bundle, items); await sync(bundle, items); assert.deepEqual(operations, ['upload', 'upload']); + bundle.pages[1].docKind = 'api_reference'; + await sync(bundle, items); + assert.equal(records.get('siebly-docs__bybit__.md').metadata.doc_kind, 'api_reference'); records.set('other', { id: 'other', source_id: 'builtin', key: 'other' }); bundle.pages.pop(); bundle.pages[0].text = 'updated'; @@ -44,7 +47,34 @@ test('sync updates changed guides and prunes only its own retired pages after su await assert.rejects(sync(bundle, failure), /rate limit/); assert.equal(records.size, 3); await sync(bundle, items); - assert.deepEqual(operations, ['upload', 'upload', 'upload', 'delete']); + assert.deepEqual(operations, ['upload', 'upload', 'upload', 'upload', 'delete']); assert.ok(records.has('other')); assert.equal(records.get('siebly-docs__home.md').metadata.source_url, base); }); + +test('Bybit references follow guide symbols and client signatures without crawling other types', async t => { + const dir = await mkdtemp(path.join(os.tmpdir(), 'search-refs-')); + t.after(() => rm(dir, { recursive: true, force: true })); + const files = new Map([ + ['bybit/guides/orders.html', '

Orders

client.submitOrder() returns NamedType.'], + ['bybit/api/classes/RestClientV5.html', '

RestClientV5

submitOrder()

params

unused()

params

'], + ['bybit/api/classes/WebsocketClient.html', '

WebsocketClient

'], + ['bybit/api/classes/WebsocketAPIClient.html', '

WebsocketAPIClient

'], + ['bybit/api/interfaces/OrderParamsV5.html', '

OrderParamsV5

Properties

Property
symbol
price?
Other'], + ['bybit/api/type-aliases/NamedType.html', '

NamedType

'], + ]); + const excluded = ['bybit/api/interfaces/Other.html', 'kraken/api/classes/WebsocketClient.html']; + const routes = [...files.keys(), ...excluded]; + await writeFile(path.join(dir, 'build-manifest.json'), JSON.stringify({ indexable: true, siteUrl: base, documentationRevision: '123' })); + await writeFile(path.join(dir, 'sitemap.xml'), '' + routes.map(route => '' + base + route + '').join('') + ''); + for (const [route, body] of files) { + await mkdir(path.dirname(path.join(dir, route)), { recursive: true }); + await writeFile(path.join(dir, route), 'Bybit
' + body + '
'); + } + const { pages } = await collectPages(dir); + assert.deepEqual(pages.map(page => page.url).sort(), [...files.keys()].map(route => base + route).sort()); + const reference = pages.find(page => page.url.endsWith('/OrderParamsV5.html')); + assert.ok(pages.filter(page => page.url.includes('/api/')).every(page => page.docKind === 'api_reference')); + assert.match(reference.text, /Used by RestClientV5.submitOrder\./); + assert.match(reference.text, /Required fields on OrderParamsV5: symbol\./); +}); diff --git a/sdks/kraken/docs/guides/websockets.md b/sdks/kraken/docs/guides/websockets.md index 81dc50b5..4cb121b8 100644 --- a/sdks/kraken/docs/guides/websockets.md +++ b/sdks/kraken/docs/guides/websockets.md @@ -5,7 +5,7 @@ description: "Subscribe to Kraken Spot ticker updates with automatic reconnects # Public streams (WebSocket) {#websocket-subscriptions} -`WebsocketClient` manages public and private subscriptions for Spot and Futures. This example subscribes to the public Spot v2 ticker for `BTC/USD`, without credentials. +`WebsocketClient` manages public and private subscriptions for Spot and Futures. To stream the Kraken Spot v2 ticker for `BTC/USD`, call `subscribe()` with `WS_KEY_MAP.spotPublicV2`. Call `closeAll()` to close the stream on shutdown. This public subscription works without credentials. ## Subscribe to a ticker