From 7151cf89128d6abc6ca2b968335d496c4737a976 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 11:31:20 +0000 Subject: [PATCH 01/43] feat(llms): add OpenAPI spec index for agent Markdown Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- package.json | 2 + plugins/llms-markdown/api/spec-index.js | 132 +++++++++++++++++++ plugins/llms-markdown/api/spec-index.test.js | 64 +++++++++ 3 files changed, 198 insertions(+) create mode 100644 plugins/llms-markdown/api/spec-index.js create mode 100644 plugins/llms-markdown/api/spec-index.test.js diff --git a/package.json b/package.json index 652cf673..ba5bf4fc 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "write-translations": "docusaurus write-translations", "write-heading-ids": "docusaurus write-heading-ids", "typecheck": "tsc", + "test": "node --test \"plugins/**/*.test.js\"", "gen:api": "docusaurus gen-api-docs all", "clean:api": "docusaurus clean-api-docs all" }, @@ -27,6 +28,7 @@ "docusaurus-plugin-openapi-docs": "^5.1.3", "docusaurus-plugin-sass": "^0.2.5", "docusaurus-theme-openapi-docs": "^5.1.3", + "js-yaml": "^4.1.1", "prism-react-renderer": "^2.4.1", "raw-loader": "^4.0.2", "react": "^18.2.0", diff --git a/plugins/llms-markdown/api/spec-index.js b/plugins/llms-markdown/api/spec-index.js new file mode 100644 index 00000000..9b5c3e30 --- /dev/null +++ b/plugins/llms-markdown/api/spec-index.js @@ -0,0 +1,132 @@ +// Shared OpenAPI loader: indexes every operation of both API specs so the +// agent Markdown generators can look operations up by "METHOD /path". + +const fs = require("fs"); +const path = require("path"); +const yaml = require("js-yaml"); + +const SITE_URL = "https://docs.absmartly.com"; +const METHODS = ["get", "put", "post", "delete", "patch"]; + +const SPECS = [ + { + key: "collector", + source: "api-spec.yaml", + publishedUrl: `${SITE_URL}/openapi/collector-api.yaml`, + docsDir: "/docs/APIs-and-SDKs/SDK-API", + }, + { + key: "webConsole", + source: "node_modules/@absmartly/api-mocks/openapi/openapi.bundle.yaml", + publishedUrl: `${SITE_URL}/openapi/web-console-api.yaml`, + docsDir: "/docs/APIs-and-SDKs/Web-Console-API", + }, +]; + +function readSpec(siteDir, spec) { + return yaml.load(fs.readFileSync(path.resolve(siteDir, spec.source), "utf8")); +} + +function loadRawSpecsSync(siteDir) { + return new Map(SPECS.map((spec) => [spec.key, readSpec(siteDir, spec)])); +} + +function listOperations(rawSpecs) { + const ops = []; + for (const { key } of SPECS) { + const doc = rawSpecs.get(key); + for (const [p, item] of Object.entries((doc && doc.paths) || {})) { + for (const m of METHODS) { + const op = item[m]; + if (!op) continue; + ops.push({ + specKey: key, + method: m.toUpperCase(), + path: p, + operationId: op.operationId, + summary: op.summary, + description: op.description, + op, + }); + } + } + } + return ops; +} + +// The dereferenced result may contain object cycles (circular refs). +async function loadDereferencedSpecs(siteDir) { + const { dereference } = await import("@apidevtools/json-schema-ref-parser"); + const specs = new Map(); + for (const spec of SPECS) { + specs.set( + spec.key, + await dereference(readSpec(siteDir, spec), { dereference: { circular: true } }), + ); + } + return specs; +} + +function buildOperationIndex(derefSpecs) { + const index = new Map(); + for (const o of listOperations(derefSpecs)) { + const key = `${o.method} ${o.path}`; + if (index.has(key)) throw new Error(`Duplicate operation ${key}`); + const spec = SPECS.find((s) => s.key === o.specKey); + index.set(key, { + ...o, + publishedUrl: spec.publishedUrl, + pageUrl: undefined, + title: undefined, + }); + } + return index; +} + +let loadedIndex = null; + +function setLoadedIndex(index) { + loadedIndex = index; +} + +function getLoadedIndex() { + if (!loadedIndex) throw new Error("API spec index not loaded"); + return loadedIndex; +} + +function normaliseEndpointPath(displayPath) { + return displayPath.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, "{$1}"); +} + +function attachPageUrls(index, siteDir) { + for (const spec of SPECS) { + const dir = path.join(siteDir, spec.docsDir); + for (const file of fs.readdirSync(dir)) { + if (!file.endsWith(".api.mdx")) continue; + const text = fs.readFileSync(path.join(dir, file), "utf8"); + const id = (text.match(/^id:\s*["']?([^"'\n]+?)["']?\s*$/m) || [])[1]; + const method = (text.match(/method=\{"([a-z]+)"\}/) || [])[1]; + const p = (text.match(/path=\{"([^"]+)"\}/) || [])[1]; + if (!id || !method || !p) continue; + const entry = index.get(`${method.toUpperCase()} ${p}`); + if (entry && entry.specKey === spec.key) { + entry.pageUrl = `${SITE_URL}${spec.docsDir}/${id}`; + } + } + } + for (const [key, entry] of index) { + if (!entry.pageUrl) throw new Error(`No generated API page for ${key}`); + } +} + +module.exports = { + SPECS, + loadRawSpecsSync, + listOperations, + loadDereferencedSpecs, + buildOperationIndex, + setLoadedIndex, + getLoadedIndex, + normaliseEndpointPath, + attachPageUrls, +}; diff --git a/plugins/llms-markdown/api/spec-index.test.js b/plugins/llms-markdown/api/spec-index.test.js new file mode 100644 index 00000000..a85fc347 --- /dev/null +++ b/plugins/llms-markdown/api/spec-index.test.js @@ -0,0 +1,64 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const path = require("path"); +const si = require("./spec-index"); + +const siteDir = path.resolve(__dirname, "../../.."); + +test("listOperations covers both real specs without duplicates", () => { + const ops = si.listOperations(si.loadRawSpecsSync(siteDir)); + const web = ops.filter((o) => o.specKey === "webConsole"); + const collector = ops.filter((o) => o.specKey === "collector"); + assert.ok(web.length > 0); + assert.ok(collector.length > 0); + assert.strictEqual(web.length, 277); + assert.strictEqual(collector.length, 6); + const keys = ops.map((o) => `${o.method} ${o.path}`); + assert.strictEqual(new Set(keys).size, keys.length); + for (const o of ops) assert.match(o.method, /^(GET|PUT|POST|DELETE|PATCH)$/); +}); + +test("buildOperationIndex keys archiveGoal and dereferences", async () => { + const index = si.buildOperationIndex(await si.loadDereferencedSpecs(siteDir)); + const entry = index.get("PUT /goals/{goalId}/archive"); + assert.ok(entry); + assert.strictEqual(entry.operationId, "ArchiveGoal"); + assert.strictEqual(entry.specKey, "webConsole"); + assert.ok(entry.publishedUrl.endsWith("web-console-api.yaml")); + assert.strictEqual(entry.title, undefined); + assert.ok(!JSON.stringify(entry.op.parameters || []).includes('"$ref"')); +}); + +test("duplicate method+path across specs throws", () => { + const op = { operationId: "x", summary: "s" }; + const spec = () => ({ paths: { "/a": { get: op } } }); + const specs = new Map([ + ["collector", spec()], + ["webConsole", spec()], + ]); + assert.throws(() => si.buildOperationIndex(specs), /Duplicate operation/); +}); + +test("normaliseEndpointPath converts colon params", () => { + assert.strictEqual( + si.normaliseEndpointPath("/goals/:goalId/archive"), + "/goals/{goalId}/archive", + ); +}); + +test("getLoadedIndex throws until set", () => { + assert.throws(() => si.getLoadedIndex(), /API spec index not loaded/); + const idx = new Map(); + si.setLoadedIndex(idx); + assert.strictEqual(si.getLoadedIndex(), idx); +}); + +test("attachPageUrls sets page URLs from generated pages", async () => { + const index = si.buildOperationIndex(await si.loadDereferencedSpecs(siteDir)); + si.attachPageUrls(index, siteDir); + assert.strictEqual( + index.get("PUT /goals/{goalId}/archive").pageUrl, + "https://docs.absmartly.com/docs/APIs-and-SDKs/Web-Console-API/archive-goal", + ); + for (const e of index.values()) assert.ok(e.pageUrl, e.operationId); +}); From 4af5a605cfcf27ee2b27ec2c590c5123ab0e8f18 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 11:37:08 +0000 Subject: [PATCH 02/43] feat(api-docs): readable titles for Web Console API pages Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- docusaurus.config.js | 31 +++++++++ plugins/llms-markdown/api/api-titles.js | 64 ++++++++++++++++++ plugins/llms-markdown/api/api-titles.test.js | 69 ++++++++++++++++++++ 3 files changed, 164 insertions(+) create mode 100644 plugins/llms-markdown/api/api-titles.js create mode 100644 plugins/llms-markdown/api/api-titles.test.js diff --git a/docusaurus.config.js b/docusaurus.config.js index 4a9e28d5..95d1b5c1 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -4,6 +4,24 @@ const { themes } = require("prism-react-renderer"); const lightCodeTheme = themes.github; const darkCodeTheme = themes.dracula; +const path = require("path"); +const { createApiPageMD } = require("docusaurus-plugin-openapi-docs/lib/markdown"); +const { loadRawSpecsSync, listOperations, SPECS } = require("./plugins/llms-markdown/api/spec-index"); +const { buildTitleMap, readableApiTitle, titleForMdx } = require("./plugins/llms-markdown/api/api-titles"); + +// Readable API page titles (spec summaries like "Goal [UPDATE]" stay in the sidebar). +const apiOperations = listOperations(loadRawSpecsSync(__dirname)); +const apiTitleMap = buildTitleMap(apiOperations); +const apiOutputDirs = SPECS.map((s) => path.join(__dirname, s.docsDir)); + +function readableCreateApiPageMD(page) { + const method = String(page.api.method).toUpperCase(); + const entry = apiTitleMap.get(`${method} ${page.api.path}`); + return createApiPageMD({ + ...page, + title: entry ? entry.title : readableApiTitle({ ...page.api, summary: page.title }), + }); +} /** @type {import('@docusaurus/types').Config} */ const config = { @@ -18,6 +36,17 @@ const config = { markdown: { mermaid: true, + parseFrontMatter: async ({ filePath, fileContent, defaultParseFrontMatter }) => { + const result = await defaultParseFrontMatter({ filePath, fileContent }); + if (filePath.endsWith(".api.mdx") && apiOutputDirs.some((d) => filePath.startsWith(d + path.sep))) { + const titles = titleForMdx(fileContent, apiTitleMap); + if (titles) { + result.frontMatter.title = titles.title; + result.frontMatter.sidebar_label = titles.sidebarLabel; + } + } + return result; + }, }, // Speeding up the build with swc - was 2m34s on M1 Macbook, now 1m29s @@ -150,6 +179,7 @@ const config = { docsPluginId: "classic", config: { collector: { + markdownGenerators: { createApiPageMD: readableCreateApiPageMD }, specPath: "api-spec.yaml", // Path to designated spec file outputDir: "docs/APIs-and-SDKs/SDK-API", // Output directory for generated .mdx docs sidebarOptions: { @@ -158,6 +188,7 @@ const config = { }, }, nodeapi: { + markdownGenerators: { createApiPageMD: readableCreateApiPageMD }, specPath: "node_modules/@absmartly/api-mocks/openapi/openapi.bundle.yaml", outputDir: "docs/APIs-and-SDKs/Web-Console-API", // Output directory for generated .mdx docs sidebarOptions: { diff --git a/plugins/llms-markdown/api/api-titles.js b/plugins/llms-markdown/api/api-titles.js new file mode 100644 index 00000000..61b55ed4 --- /dev/null +++ b/plugins/llms-markdown/api/api-titles.js @@ -0,0 +1,64 @@ +// Readable titles for API reference pages. Spec summaries such as +// "Goal [UPDATE]" become "Archive goal" (from the operationId); the sidebar +// keeps the original summary. + +const ACRONYMS = { + api: "API", + cors: "CORS", + json: "JSON", + id: "ID", + url: "URL", + sdk: "SDK", + oidc: "OIDC", + sql: "SQL", + csv: "CSV", + mcp: "MCP", +}; + +function formatWords(words) { + const text = words.map((w) => w.toLowerCase()).map((w) => ACRONYMS[w] || w).join(" "); + return text.charAt(0).toUpperCase() + text.slice(1); +} + +function splitCamel(id) { + return id.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+/g) || []; +} + +function readableApiTitle({ operationId, summary }) { + const tag = /^(.*?)\s*\[([^\]]+)\]\s*$/.exec(summary || ""); + if (!tag) return summary; + // e.g. "puteventsUsageAlertsById" has "events" glued onto the verb. + const id = String(operationId || "") + .replace(/^\d+(?:_\d+)?/, "") + .replace(/^(get|put|post|patch|create|update|delete)events(?=[A-Z])/, "$1Events"); + if (/[A-Z]/.test(id)) return formatWords(splitCamel(id)); + const [, noun, verb] = tag; + return formatWords([...verb.trim().split(/\s+/), ...noun.trim().split(/\s+/)]); +} + +function buildTitleMap(ops) { + const entries = ops.map((o) => ({ + key: `${o.method} ${o.path}`, + method: o.method, + path: o.path, + title: readableApiTitle(o), + sidebarLabel: o.summary, + })); + const counts = new Map(); + for (const e of entries) counts.set(e.title, (counts.get(e.title) || 0) + 1); + const map = new Map(); + for (const e of entries) { + const title = counts.get(e.title) > 1 ? `${e.title} (${e.method} ${e.path})` : e.title; + map.set(e.key, { title, sidebarLabel: e.sidebarLabel }); + } + return map; +} + +function titleForMdx(fileContent, titleMap) { + const method = (fileContent.match(/method=\{"([a-z]+)"\}/) || [])[1]; + const p = (fileContent.match(/path=\{"([^"]+)"\}/) || [])[1]; + if (!method || !p) return null; + return titleMap.get(`${method.toUpperCase()} ${p}`) || null; +} + +module.exports = { readableApiTitle, buildTitleMap, titleForMdx }; diff --git a/plugins/llms-markdown/api/api-titles.test.js b/plugins/llms-markdown/api/api-titles.test.js new file mode 100644 index 00000000..3a7a9b23 --- /dev/null +++ b/plugins/llms-markdown/api/api-titles.test.js @@ -0,0 +1,69 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const path = require("path"); +const si = require("./spec-index"); +const t = require("./api-titles"); + +const siteDir = path.resolve(__dirname, "../../.."); + +test("readableApiTitle passes through untagged summaries", () => { + assert.strictEqual( + t.readableApiTitle({ + operationId: "0100_070getExperimentAssetRoleUsers", + summary: "List Asset Role Users for Experiment", + }), + "List Asset Role Users for Experiment", + ); +}); + +test("readableApiTitle humanises operationIds", () => { + const h = (operationId) => t.readableApiTitle({ operationId, summary: "X [LIST]" }); + assert.strictEqual(h("0100_006restartExperiment"), "Restart experiment"); + assert.strictEqual(h("0200_030getApiKey"), "Get API key"); + assert.strictEqual(h("0100_076patchExperiment"), "Patch experiment"); + assert.strictEqual(h("ArchiveGoal"), "Archive goal"); + assert.strictEqual( + h("048updateExperimentCustomSectionsOrder"), + "Update experiment custom sections order", + ); +}); + +test("readableApiTitle falls back to summary when operationId has no word boundaries", () => { + assert.strictEqual( + t.readableApiTitle({ operationId: "createevents", summary: "Events [LIST]" }), + "List events", + ); +}); + +test("buildTitleMap is unique and covers every real operation", () => { + const ops = si.listOperations(si.loadRawSpecsSync(siteDir)); + const map = t.buildTitleMap(ops); + assert.strictEqual(map.size, ops.length); + const titles = [...map.values()].map((v) => v.title); + assert.strictEqual(new Set(titles).size, titles.length); + assert.deepStrictEqual(map.get("PUT /goals/{goalId}/archive"), { + title: "Archive goal", + sidebarLabel: "Goal [UPDATE]", + }); +}); + +test("buildTitleMap disambiguates duplicate titles", () => { + const map = t.buildTitleMap([ + { method: "GET", path: "/a", operationId: "cancelExportHistory", summary: "A [GET]" }, + { method: "DELETE", path: "/b", operationId: "cancelExportHistory", summary: "B [DELETE]" }, + ]); + assert.strictEqual(map.get("GET /a").title, "Cancel export history (GET /a)"); + assert.strictEqual(map.get("DELETE /b").title, "Cancel export history (DELETE /b)"); + assert.strictEqual(map.get("GET /a").sidebarLabel, "A [GET]"); +}); + +test("titleForMdx reads method and path from generated mdx", () => { + const map = t.buildTitleMap(si.listOperations(si.loadRawSpecsSync(siteDir))); + const mdx = `---\nid: archive-goal\n---\n\n\n`; + assert.deepStrictEqual(t.titleForMdx(mdx, map), { + title: "Archive goal", + sidebarLabel: "Goal [UPDATE]", + }); + assert.strictEqual(t.titleForMdx("no endpoint here", map), null); + assert.strictEqual(t.titleForMdx(`method={"get"} path={"/nope"}`, map), null); +}); From 8cffb8280562bd84521479170a017aa90d03f1b2 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 11:40:24 +0000 Subject: [PATCH 03/43] feat(llms): render OpenAPI schemas as Markdown field lists Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- plugins/llms-markdown/api/render-schema.js | 164 ++++++++++++++++++ .../llms-markdown/api/render-schema.test.js | 101 +++++++++++ 2 files changed, 265 insertions(+) create mode 100644 plugins/llms-markdown/api/render-schema.js create mode 100644 plugins/llms-markdown/api/render-schema.test.js diff --git a/plugins/llms-markdown/api/render-schema.js b/plugins/llms-markdown/api/render-schema.js new file mode 100644 index 00000000..f76fcbd5 --- /dev/null +++ b/plugins/llms-markdown/api/render-schema.js @@ -0,0 +1,164 @@ +const OMITTED = "(nested fields omitted; see the OpenAPI spec)"; + +function isObj(v) { + return v && typeof v === "object" && !Array.isArray(v); +} + +// Flatten allOf (recursively) into one view of the schema. Cycle-safe. +function merge(schema, seen = new Set()) { + const m = { + types: [], + properties: new Map(), + required: new Set(), + oneOf: null, + anyOf: null, + nullable: false, + }; + const visit = (s) => { + if (!isObj(s) || seen.has(s)) return; + seen.add(s); + if (Array.isArray(s.allOf)) s.allOf.forEach(visit); + const t = Array.isArray(s.type) ? s.type : s.type ? [s.type] : []; + for (const x of t) { + if (x === "null") m.nullable = true; + else if (!m.types.includes(x)) m.types.push(x); + } + if (s.nullable === true) m.nullable = true; + if (isObj(s.properties)) { + for (const [k, v] of Object.entries(s.properties)) { + const prev = m.properties.get(k); + m.properties.set(k, prev && prev !== v ? { allOf: [prev, v] } : v); + } + } + if (Array.isArray(s.required)) s.required.forEach((r) => m.required.add(r)); + for (const key of ["description", "format", "default", "enum"]) { + if (m[key] === undefined && s[key] !== undefined) m[key] = s[key]; + } + if (m.title === undefined && s.title) m.title = s.title; + if (isObj(s.items)) m.items = m.items && m.items !== s.items ? { allOf: [m.items, s.items] } : s.items; + if (Array.isArray(s.oneOf) && !m.oneOf) m.oneOf = s.oneOf; + if (Array.isArray(s.anyOf) && !m.anyOf) m.anyOf = s.anyOf; + }; + visit(schema); + if (!m.types.length) { + if (m.properties.size) m.types.push("object"); + else if (m.items) m.types.push("array"); + } + return m; +} + +function cleanDescription(text) { + return String(text) + .replace(/:::\w*/g, "") + .replace(/\s*\n\s*/g, " ") + .replace(/\s{2,}/g, " ") + .trim(); +} + +function endSentence(text) { + return /[.!?:]$/.test(text) ? text : `${text}.`; +} + +function code(v) { + return `\`${typeof v === "string" ? v : JSON.stringify(v)}\``; +} + +function typeLabel(m) { + if (m.types.includes("array")) { + if (!m.items) return "array"; + const im = merge(m.items); + const inner = im.types.length ? im.types.join(" or ") : im.oneOf || im.anyOf ? "object" : "any"; + return `array of ${inner}`; + } + return m.types.join(" or "); +} + +function optionLabel(opt) { + const om = merge(opt); + return opt && opt.title ? opt.title : om.title || typeLabel(om) || "any"; +} + +// Lines for the fields of schema `schema` at nesting `depth` (1 = top level). +function renderFields(schema, ctx, depth, indent, path) { + const m = merge(schema); + const lines = []; + const pad = " ".repeat(indent); + for (const [name, prop] of m.properties) { + renderField(name, prop, m.required.has(name), ctx, depth, indent, path, lines); + } + for (const [kw, label] of [["oneOf", "One of:"], ["anyOf", "One of:"]]) { + if (!m[kw]) continue; + lines.push(`${pad}${label}`); + m[kw].forEach((opt, i) => { + lines.push(`${pad}- Option ${i + 1} (${optionLabel(opt)})`); + lines.push(...renderChildren(opt, ctx, depth, indent + 1, path, null)); + }); + } + return lines; +} + +// Children (properties / array items / alternatives) of a schema, or [] if none. +function renderChildren(schema, ctx, depth, indent, path, fieldName) { + const m = merge(schema); + const target = m.types.includes("array") && m.items ? m.items : schema; + const tm = target === schema ? m : merge(target); + if (!tm.properties.size && !tm.oneOf && !tm.anyOf) return []; + const pad = " ".repeat(indent); + if (path.some((p) => p.schema === target)) { + const first = path.find((p) => p.schema === target); + return [`${pad}- (recursive: same shape as ${code(first.name || fieldName || "parent")})`]; + } + if (depth >= ctx.maxDepth) return [`${pad}- ${OMITTED}`]; + return renderFields(target, ctx, depth + 1, indent, [...path, { schema: target, name: fieldName }]); +} + +function renderField(name, prop, required, ctx, depth, indent, path, lines) { + const m = merge(prop); + const meta = []; + const t = typeLabel(m); + if (t) meta.push(t); + if (required) meta.push("required"); + if (m.nullable) meta.push("nullable"); + let head = `${" ".repeat(indent)}- ${code(name)}`; + if (meta.length) head += ` (${meta.join(", ")})`; + + const sentences = []; + if (m.description) { + const d = cleanDescription(m.description); + if (d) sentences.push(endSentence(d)); + } + const enumVals = Array.isArray(m.enum) ? m.enum : m.items ? merge(m.items).enum : null; + if (Array.isArray(enumVals) && enumVals.length) { + sentences.push(`One of: ${enumVals.map(code).join(", ")}.`); + } + if (m.default !== undefined) sentences.push(`Default: ${code(m.default)}.`); + if (m.format) sentences.push(`Format: ${code(m.format)}.`); + + const hasDesc = m.description && cleanDescription(m.description); + if (sentences.length) head += hasDesc ? `: ${sentences.join(" ")}` : `. ${sentences.join(" ")}`; + lines.push(head); + + // Nested structure: the property's own shape, or its array items' shape. + const itemTarget = m.types.includes("array") && m.items ? m.items : prop; + const im = merge(itemTarget); + if (!im.properties.size && !im.oneOf && !im.anyOf) return; + const childIndent = indent + 1; + if (path.some((p) => p.schema === itemTarget) || path.some((p) => p.schema === prop)) { + const hit = path.find((p) => p.schema === itemTarget || p.schema === prop); + lines.push(`${" ".repeat(childIndent)}- (recursive: same shape as ${code(hit.name || name)})`); + return; + } + if (depth >= ctx.maxDepth) { + lines.push(`${" ".repeat(childIndent)}- ${OMITTED}`); + return; + } + lines.push(...renderFields(itemTarget, ctx, depth + 1, childIndent, [...path, { schema: itemTarget, name }])); +} + +function renderSchemaFields(schema, { maxDepth = 6 } = {}) { + if (!isObj(schema)) return ""; + const ctx = { maxDepth }; + return renderFields(schema, ctx, 1, 0, [{ schema, name: null }]).join("\n"); +} + +module.exports = { renderSchemaFields }; diff --git a/plugins/llms-markdown/api/render-schema.test.js b/plugins/llms-markdown/api/render-schema.test.js new file mode 100644 index 00000000..b092e2d7 --- /dev/null +++ b/plugins/llms-markdown/api/render-schema.test.js @@ -0,0 +1,101 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const path = require("path"); +const { renderSchemaFields } = require("./render-schema"); +const si = require("./spec-index"); + +const siteDir = path.resolve(__dirname, "../../.."); + +test("allOf merges properties and required markers", () => { + const out = renderSchemaFields({ + allOf: [ + { type: "object", required: ["a"], properties: { a: { type: "string" } } }, + { type: "object", required: ["b"], properties: { b: { type: "integer" } } }, + ], + }); + assert.match(out, /^- `a` \(string, required\)/m); + assert.match(out, /^- `b` \(integer, required\)/m); +}); + +test("enum, default, format, description, nullable", () => { + const out = renderSchemaFields({ + type: "object", + properties: { + kind: { type: "string", enum: ["a", "b"], default: "a", description: "Kind." }, + at: { type: "string", format: "date-time", nullable: true }, + n: { type: ["integer", "null"] }, + }, + }); + assert.match(out, /`kind` \(string\): Kind\. One of: `a`, `b`\. Default: `a`\./); + assert.match(out, /`at` \(string, nullable\)\. Format: `date-time`\./); + assert.match(out, /`n` \(integer, nullable\)/); +}); + +test("array of objects nests item fields", () => { + const out = renderSchemaFields({ + type: "object", + properties: { + owners: { type: "array", items: { type: "object", properties: { id: { type: "integer" } } } }, + tags: { type: "array", items: { type: "string" } }, + }, + }); + assert.match(out, /^- `owners` \(array of object\)/m); + assert.match(out, /^ {2}- `id` \(integer\)/m); + assert.match(out, /`tags` \(array of string\)/); +}); + +test("oneOf renders labelled options", () => { + const out = renderSchemaFields({ + type: "object", + properties: { + v: { + oneOf: [ + { title: "Num", type: "object", properties: { x: { type: "number" } } }, + { type: "string" }, + ], + }, + }, + }); + assert.match(out, /^ {2}One of:/m); + assert.match(out, /^ {2}- Option 1 \(Num\)/m); + assert.match(out, /^ {4}- `x` \(number\)/m); + assert.match(out, /^ {2}- Option 2 \(string\)/m); +}); + +test("self-referencing schema terminates", () => { + const node = { type: "object", properties: {} }; + node.properties.children = { type: "array", items: node }; + const out = renderSchemaFields(node); + assert.match(out, /recursive: same shape as `children`/); +}); + +test("depth cap emits omission note", () => { + const out = renderSchemaFields( + { + type: "object", + properties: { + a: { type: "object", properties: { b: { type: "object", properties: { c: { type: "string" } } } } }, + }, + }, + { maxDepth: 2 } + ); + assert.match(out, /nested fields omitted; see the OpenAPI spec/); + assert.ok(!out.includes("`c`")); +}); + +test("descriptions are cleaned", () => { + const out = renderSchemaFields({ + type: "object", + properties: { x: { type: "string", description: "x :::\nline two" } }, + }); + assert.ok(!out.includes(":::")); + assert.ok(!out.includes("\nline")); + assert.match(out, /x line two/); +}); + +test("real ExperimentInput includes unit_type_id and owners", async () => { + const specs = await si.loadDereferencedSpecs(siteDir); + const out = renderSchemaFields(specs.get("webConsole").components.schemas.ExperimentInput); + assert.match(out, /`unit_type_id`/); + assert.match(out, /`owners`/); +}); From fcaa4c6a0c643435955bee6c8715cf0f77759c3b Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 11:43:32 +0000 Subject: [PATCH 04/43] fix(llms): schema renderer precedence, null alternatives and dedupe Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- plugins/llms-markdown/api/render-schema.js | 109 ++++++++++-------- .../llms-markdown/api/render-schema.test.js | 103 +++++++++++++++++ 2 files changed, 166 insertions(+), 46 deletions(-) diff --git a/plugins/llms-markdown/api/render-schema.js b/plugins/llms-markdown/api/render-schema.js index f76fcbd5..77249594 100644 --- a/plugins/llms-markdown/api/render-schema.js +++ b/plugins/llms-markdown/api/render-schema.js @@ -4,7 +4,14 @@ function isObj(v) { return v && typeof v === "object" && !Array.isArray(v); } +function isNullSchema(s) { + return isObj(s) && (s.type === "null" || (Array.isArray(s.enum) && s.enum.length === 1 && s.enum[0] === null)); +} + // Flatten allOf (recursively) into one view of the schema. Cycle-safe. +// A schema's own keys take precedence over those of its allOf members. +// `null` alternatives in oneOf/anyOf fold into `nullable`; a single remaining +// alternative is merged in directly. function merge(schema, seen = new Set()) { const m = { types: [], @@ -17,27 +24,33 @@ function merge(schema, seen = new Set()) { const visit = (s) => { if (!isObj(s) || seen.has(s)) return; seen.add(s); - if (Array.isArray(s.allOf)) s.allOf.forEach(visit); + for (const key of ["description", "format", "default", "enum", "title", "items"]) { + if (m[key] === undefined && s[key] !== undefined) m[key] = s[key]; + } const t = Array.isArray(s.type) ? s.type : s.type ? [s.type] : []; for (const x of t) { if (x === "null") m.nullable = true; else if (!m.types.includes(x)) m.types.push(x); } if (s.nullable === true) m.nullable = true; + if (Array.isArray(s.allOf)) s.allOf.forEach(visit); if (isObj(s.properties)) { for (const [k, v] of Object.entries(s.properties)) { const prev = m.properties.get(k); - m.properties.set(k, prev && prev !== v ? { allOf: [prev, v] } : v); + m.properties.set(k, prev && prev !== v ? { allOf: [v, prev] } : v); } } if (Array.isArray(s.required)) s.required.forEach((r) => m.required.add(r)); - for (const key of ["description", "format", "default", "enum"]) { - if (m[key] === undefined && s[key] !== undefined) m[key] = s[key]; + for (const kw of ["oneOf", "anyOf"]) { + if (!Array.isArray(s[kw]) || m[kw]) continue; + const nonNull = s[kw].filter((o) => { + if (!isNullSchema(o)) return true; + m.nullable = true; + return false; + }); + if (nonNull.length === 1) visit(nonNull[0]); + else if (nonNull.length > 1) m[kw] = nonNull; } - if (m.title === undefined && s.title) m.title = s.title; - if (isObj(s.items)) m.items = m.items && m.items !== s.items ? { allOf: [m.items, s.items] } : s.items; - if (Array.isArray(s.oneOf) && !m.oneOf) m.oneOf = s.oneOf; - if (Array.isArray(s.anyOf) && !m.anyOf) m.anyOf = s.anyOf; }; visit(schema); if (!m.types.length) { @@ -47,6 +60,21 @@ function merge(schema, seen = new Set()) { return m; } +// Identity key used for dedupe/recursion: unwrap inline wrappers around a +// single referenced schema (allOf of one, or one non-null alternative). +function canon(schema) { + let s = schema; + for (let i = 0; i < 10 && isObj(s); i++) { + if (s.properties || s.items) break; + const present = ["allOf", "oneOf", "anyOf"] + .map((k) => (Array.isArray(s[k]) ? s[k].filter((o) => !isNullSchema(o)) : null)) + .filter(Boolean); + if (present.length === 1 && present[0].length === 1) s = present[0][0]; + else break; + } + return s; +} + function cleanDescription(text) { return String(text) .replace(/:::\w*/g, "") @@ -75,41 +103,42 @@ function typeLabel(m) { function optionLabel(opt) { const om = merge(opt); - return opt && opt.title ? opt.title : om.title || typeLabel(om) || "any"; + return (opt && opt.title) || om.title || typeLabel(om) || "any"; } -// Lines for the fields of schema `schema` at nesting `depth` (1 = top level). +// Lines for the fields of `schema` at nesting `depth` (1 = top level). +// `path` is the chain of schemas currently being rendered (innermost last). function renderFields(schema, ctx, depth, indent, path) { const m = merge(schema); + const here = path[path.length - 1]; const lines = []; const pad = " ".repeat(indent); for (const [name, prop] of m.properties) { renderField(name, prop, m.required.has(name), ctx, depth, indent, path, lines); } - for (const [kw, label] of [["oneOf", "One of:"], ["anyOf", "One of:"]]) { + for (const kw of ["oneOf", "anyOf"]) { if (!m[kw]) continue; - lines.push(`${pad}${label}`); + lines.push(`${pad}One of:`); m[kw].forEach((opt, i) => { lines.push(`${pad}- Option ${i + 1} (${optionLabel(opt)})`); - lines.push(...renderChildren(opt, ctx, depth, indent + 1, path, null)); + lines.push(...renderNested(opt, here.name, `${here.label} (option ${i + 1})`, ctx, depth, indent + 1, path)); }); } return lines; } -// Children (properties / array items / alternatives) of a schema, or [] if none. -function renderChildren(schema, ctx, depth, indent, path, fieldName) { - const m = merge(schema); - const target = m.types.includes("array") && m.items ? m.items : schema; - const tm = target === schema ? m : merge(target); +// Nested lines for `target` (already unwrapped from arrays), or [] if it has no structure. +function renderNested(target, name, label, ctx, depth, indent, path) { + const tm = merge(target); if (!tm.properties.size && !tm.oneOf && !tm.anyOf) return []; + const key = canon(target); const pad = " ".repeat(indent); - if (path.some((p) => p.schema === target)) { - const first = path.find((p) => p.schema === target); - return [`${pad}- (recursive: same shape as ${code(first.name || fieldName || "parent")})`]; - } + const onPath = path.find((p) => p.key === key); + if (onPath) return [`${pad}- (recursive: same shape as ${code(onPath.name || name || "parent")})`]; + if (ctx.seen.has(key)) return [`${pad}- (same shape as ${code(ctx.seen.get(key))} above)`]; if (depth >= ctx.maxDepth) return [`${pad}- ${OMITTED}`]; - return renderFields(target, ctx, depth + 1, indent, [...path, { schema: target, name: fieldName }]); + ctx.seen.set(key, label); + return renderFields(target, ctx, depth + 1, indent, [...path, { key, name, label }]); } function renderField(name, prop, required, ctx, depth, indent, path, lines) { @@ -123,10 +152,8 @@ function renderField(name, prop, required, ctx, depth, indent, path, lines) { if (meta.length) head += ` (${meta.join(", ")})`; const sentences = []; - if (m.description) { - const d = cleanDescription(m.description); - if (d) sentences.push(endSentence(d)); - } + const desc = m.description ? cleanDescription(m.description) : ""; + if (desc) sentences.push(endSentence(desc)); const enumVals = Array.isArray(m.enum) ? m.enum : m.items ? merge(m.items).enum : null; if (Array.isArray(enumVals) && enumVals.length) { sentences.push(`One of: ${enumVals.map(code).join(", ")}.`); @@ -134,31 +161,21 @@ function renderField(name, prop, required, ctx, depth, indent, path, lines) { if (m.default !== undefined) sentences.push(`Default: ${code(m.default)}.`); if (m.format) sentences.push(`Format: ${code(m.format)}.`); - const hasDesc = m.description && cleanDescription(m.description); - if (sentences.length) head += hasDesc ? `: ${sentences.join(" ")}` : `. ${sentences.join(" ")}`; + if (sentences.length) head += desc ? `: ${sentences.join(" ")}` : `. ${sentences.join(" ")}`; lines.push(head); - // Nested structure: the property's own shape, or its array items' shape. - const itemTarget = m.types.includes("array") && m.items ? m.items : prop; - const im = merge(itemTarget); - if (!im.properties.size && !im.oneOf && !im.anyOf) return; - const childIndent = indent + 1; - if (path.some((p) => p.schema === itemTarget) || path.some((p) => p.schema === prop)) { - const hit = path.find((p) => p.schema === itemTarget || p.schema === prop); - lines.push(`${" ".repeat(childIndent)}- (recursive: same shape as ${code(hit.name || name)})`); - return; - } - if (depth >= ctx.maxDepth) { - lines.push(`${" ".repeat(childIndent)}- ${OMITTED}`); - return; - } - lines.push(...renderFields(itemTarget, ctx, depth + 1, childIndent, [...path, { schema: itemTarget, name }])); + const target = m.types.includes("array") && m.items ? m.items : prop; + const parent = path[path.length - 1].label; + const label = parent ? `${parent}.${name}` : name; + lines.push(...renderNested(target, name, label, ctx, depth, indent + 1, path)); } +// Renders each distinct object schema (by identity) in full only once per call; +// later occurrences become a one-line back-reference. function renderSchemaFields(schema, { maxDepth = 6 } = {}) { if (!isObj(schema)) return ""; - const ctx = { maxDepth }; - return renderFields(schema, ctx, 1, 0, [{ schema, name: null }]).join("\n"); + const ctx = { maxDepth, seen: new Map() }; + return renderFields(schema, ctx, 1, 0, [{ key: canon(schema), name: null, label: "" }]).join("\n"); } module.exports = { renderSchemaFields }; diff --git a/plugins/llms-markdown/api/render-schema.test.js b/plugins/llms-markdown/api/render-schema.test.js index b092e2d7..2ee8dd84 100644 --- a/plugins/llms-markdown/api/render-schema.test.js +++ b/plugins/llms-markdown/api/render-schema.test.js @@ -99,3 +99,106 @@ test("real ExperimentInput includes unit_type_id and owners", async () => { assert.match(out, /`unit_type_id`/); assert.match(out, /`owners`/); }); + +test("schema's own description/default/format/enum beat allOf members", () => { + const out = renderSchemaFields({ + type: "object", + properties: { + f: { + description: "Specific", + default: "own", + format: "own-fmt", + enum: ["own"], + allOf: [{ type: "string", description: "Generic", default: "gen", format: "gen-fmt", enum: ["gen"] }], + }, + }, + }); + assert.match(out, /`f` \(string\): Specific\. One of: `own`\. Default: `own`\. Format: `own-fmt`\./); + assert.ok(!out.includes("Generic") && !out.includes("gen")); +}); + +test("allOf nested inside a property and inside array items", () => { + const out = renderSchemaFields({ + type: "object", + properties: { + p: { allOf: [{ properties: { a: { type: "string" } } }, { properties: { b: { type: "string" } } }] }, + list: { + type: "array", + items: { allOf: [{ properties: { c: { type: "string" } } }, { properties: { d: { type: "string" } } }] }, + }, + }, + }); + assert.match(out, /^ {2}- `a` \(string\)/m); + assert.match(out, /^ {2}- `b` \(string\)/m); + assert.match(out, /^- `list` \(array of object\)/m); + assert.match(out, /^ {2}- `c` \(string\)/m); + assert.match(out, /^ {2}- `d` \(string\)/m); +}); + +test("array whose item is an allOf of scalar + constraints", () => { + const out = renderSchemaFields({ + type: "object", + properties: { ids: { type: "array", items: { allOf: [{ type: "integer" }, { format: "int64" }] } } }, + }); + assert.match(out, /`ids` \(array of integer\)/); +}); + +test("null alternative in anyOf/oneOf folds into nullable", () => { + const out = renderSchemaFields({ + type: "object", + properties: { + one: { anyOf: [{ type: "string" }, { type: "null" }] }, + two: { oneOf: [{ type: "string" }, { type: "integer" }, { type: "null" }] }, + }, + }); + assert.match(out, /^- `one` \(string, nullable\)$/m); + assert.ok(!out.includes("Option 3") && !out.includes("(any)")); + assert.match(out, /^- `two` \(nullable\)/m); + assert.match(out, /Option 1 \(string\)/); + assert.match(out, /Option 2 \(integer\)/); + assert.strictEqual(out.split("One of:").length - 1, 1); +}); + +test("required inside an option is honoured", () => { + const out = renderSchemaFields({ + oneOf: [ + { title: "A", type: "object", required: ["x"], properties: { x: { type: "string" }, y: { type: "string" } } }, + { title: "B", type: "object", properties: { z: { type: "string" } } }, + ], + }); + assert.match(out, /^ {2}- `x` \(string, required\)/m); + assert.match(out, /^ {2}- `y` \(string\)$/m); + assert.match(out, /^- Option 2 \(B\)/m); +}); + +test("same schema object is rendered in full only once", () => { + const user = { type: "object", properties: { id: { type: "integer" }, email: { type: "string" } } }; + const out = renderSchemaFields({ + type: "object", + properties: { + owner: user, + editors: { type: "array", items: user }, + reviewer: { anyOf: [user, { type: "null" }] }, + wrapped: { description: "w", allOf: [user] }, + }, + }); + assert.strictEqual(out.split("`email`").length - 1, 1); + assert.strictEqual(out.split("(same shape as `owner` above)").length - 1, 3); +}); + +test("every schema in both real specs renders without throwing", async () => { + const specs = await si.loadDereferencedSpecs(siteDir); + const sizes = []; + for (const [key, spec] of specs) { + for (const [name, schema] of Object.entries((spec.components && spec.components.schemas) || {})) { + const out = renderSchemaFields(schema); + assert.strictEqual(typeof out, "string"); + sizes.push([`${key}:${name}`, out.length]); + } + } + sizes.sort((a, b) => b[1] - a[1]); + console.log("largest rendered schemas:", JSON.stringify(sizes.slice(0, 5))); + assert.ok(sizes.length > 100); + const input = sizes.find(([n]) => n === "webConsole:ExperimentInput"); + assert.ok(input[1] < 40000, `ExperimentInput is ${input[1]} chars`); +}); From 4a4bb39df1f6a4cd6e137d7e9aeb071d415ab44f Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 11:46:33 +0000 Subject: [PATCH 05/43] feat(llms): render full API operation pages as Markdown Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- plugins/llms-markdown/api/render-operation.js | 178 ++++++++++++++++++ .../api/render-operation.test.js | 85 +++++++++ plugins/llms-markdown/pointer.js | 8 + 3 files changed, 271 insertions(+) create mode 100644 plugins/llms-markdown/api/render-operation.js create mode 100644 plugins/llms-markdown/api/render-operation.test.js create mode 100644 plugins/llms-markdown/pointer.js diff --git a/plugins/llms-markdown/api/render-operation.js b/plugins/llms-markdown/api/render-operation.js new file mode 100644 index 00000000..be53e5be --- /dev/null +++ b/plugins/llms-markdown/api/render-operation.js @@ -0,0 +1,178 @@ +const { renderSchemaFields } = require("./render-schema"); +const { pointerLine } = require("../pointer"); + +const MAX_CHARS = 50000; +const BASE_URL_LINE = + "Base URL: your ABsmartly instance's API endpoint, e.g. `https://.absmartly.io/v1`"; +const AUTH_LINES = { + webConsole: + "**Authentication:** send `Authorization: Api-Key `, with an API key from **Settings → API Keys**, " + + "or a federated OIDC access token. See [Platform API authentication](https://docs.absmartly.com/docs/APIs-and-SDKs/overview#platform-api) " + + "and [Federated Authentication](https://docs.absmartly.com/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens).", + collector: "**Authentication:** send `X-API-Key: `.", +}; +const NO_AUTH_LINE = "**Authentication:** none required."; + +function isObj(v) { + return v && typeof v === "object" && !Array.isArray(v); +} + +function stripAdmonitions(text) { + return String(text || "") + .split("\n") + .filter((l) => !/^\s*:::/.test(l)) + .join("\n") + .replace(/:::\w*/g, "") + .trim(); +} + +function oneLine(text) { + return stripAdmonitions(text).replace(/\s*\n\s*/g, " ").replace(/\|/g, "\\|"); +} + +function paramType(schema) { + if (!isObj(schema)) return ""; + let t = Array.isArray(schema.type) ? schema.type.join(" | ") : schema.type || ""; + if (t === "array" && isObj(schema.items)) t = `array of ${paramType(schema.items) || "any"}`; + if (schema.format) t += ` (${schema.format})`; + return t; +} + +function paramTable(params, where, title) { + const rows = params.filter((p) => p.in === where); + if (!rows.length) return ""; + const lines = [`## ${title}`, "", "| Name | Type | Required | Description |", "| --- | --- | --- | --- |"]; + for (const p of rows) { + let desc = oneLine(p.description || (p.schema && p.schema.description)); + const en = p.schema && Array.isArray(p.schema.enum) ? p.schema.enum : null; + if (en) desc += `${desc ? " " : ""}One of: ${en.map((v) => `\`${v}\``).join(", ")}.`; + lines.push(`| \`${p.name}\` | ${paramType(p.schema)} | ${p.required || where === "path" ? "yes" : "no"} | ${desc} |`); + } + return lines.join("\n"); +} + +function pickContent(content) { + if (!isObj(content)) return null; + const types = Object.keys(content); + if (!types.length) return null; + const type = types.find((t) => /json/.test(t)) || types[0]; + return { type, media: content[type] || {} }; +} + +function operationExample(media, operationId) { + if (media.example !== undefined) return media.example; + if (isObj(media.examples)) { + const keys = Object.keys(media.examples); + if (!keys.length) return undefined; + const key = keys.find((k) => k === operationId) || keys[0]; + const ex = media.examples[key]; + return isObj(ex) && "value" in ex ? ex.value : ex; + } + return undefined; +} + +function sample(fn, schema) { + try { + const v = fn(schema); + return v === undefined || v === null ? undefined : v; + } catch (e) { + return undefined; + } +} + +function jsonBlock(value) { + const text = typeof value === "string" ? value : JSON.stringify(value, null, 2); + return "```json\n" + text.replace(/:::/g, ":: :") + "\n```"; +} + +function exampleFor(media, operationId, sampler, schema) { + const own = operationExample(media, operationId); + if (own !== undefined) return { value: own, generated: false }; + const gen = sample(sampler, schema); + if (gen === undefined || (isObj(gen) && !Object.keys(gen).length)) return null; + return { value: gen, generated: true }; +} + +function fieldList(schema, maxDepth) { + if (!isObj(schema)) return ""; + return stripAdmonitions(renderSchemaFields(schema, { maxDepth })); +} + +function build(entry, pageUrl, { maxDepth, responseExample }) { + const { sampleRequestFromSchema } = require("docusaurus-plugin-openapi-docs/lib/openapi/createRequestExample"); + const { sampleResponseFromSchema } = require("docusaurus-plugin-openapi-docs/lib/openapi/createResponseExample"); + const op = entry.op || {}; + const params = Array.isArray(op.parameters) ? op.parameters : []; + const sections = []; + const push = (s) => s && sections.push(s); + + push(pointerLine(pageUrl)); + push(`# ${entry.title || entry.summary || entry.operationId}`); + push(`\`${entry.method} ${entry.path}\``); + push(BASE_URL_LINE); + push(Array.isArray(op.security) && op.security.length === 0 ? NO_AUTH_LINE : AUTH_LINES[entry.specKey]); + push(stripAdmonitions(op.description || entry.description)); + push(paramTable(params, "path", "Path parameters")); + push(paramTable(params, "query", "Query parameters")); + push(paramTable(params, "header", "Header parameters")); + + const body = op.requestBody && pickContent(op.requestBody.content); + if (body) { + const fields = fieldList(body.media.schema, maxDepth); + const ex = exampleFor(body.media, entry.operationId, sampleRequestFromSchema, body.media.schema); + const note = fields || ex ? fields : "No schema is defined for this body."; + push(`## Request body (\`${body.type}\`)` + (note ? `\n\n${note}` : "")); + if (ex) { + push(`### Example request body${ex.generated ? " (generated from the schema)" : ""}\n\n${jsonBlock(ex.value)}`); + } + } + + const responses = isObj(op.responses) ? op.responses : {}; + const codes = Object.keys(responses); + const ok = codes.filter((c) => /^2/.test(c)); + const errors = codes.filter((c) => !/^2/.test(c)); + if (ok.length) { + push("## Responses"); + for (const code of ok) { + const r = responses[code] || {}; + const parts = [`### ${code} ${oneLine(r.description)}`.trim()]; + const content = pickContent(r.content); + if (content) { + const fields = fieldList(content.media.schema, maxDepth); + if (fields) parts.push(fields); + if (responseExample) { + const ex = exampleFor(content.media, entry.operationId, sampleResponseFromSchema, content.media.schema); + if (ex) parts.push(`${ex.generated ? "Example (generated from the schema):" : "Example:"}\n\n${jsonBlock(ex.value)}`); + } + } + if (parts.length === 1) parts.push("No response body."); + push(parts.join("\n\n")); + } + } + if (errors.length) { + const head = ok.length ? "### Errors" : "## Responses\n\n### Errors"; + push( + `${head}\n\n` + + errors.map((c) => `- \`${c}\` ${oneLine((responses[c] || {}).description)}`.trimEnd()).join("\n"), + ); + } + push(`Source: ${entry.publishedUrl} (operationId \`${entry.operationId}\`)`); + return sections.join("\n\n") + "\n"; +} + +// Size guard: drop the response example first, then reduce schema depth. +function renderOperationMarkdown(entry, { pageUrl }) { + const attempts = [ + { maxDepth: 6, responseExample: true }, + { maxDepth: 6, responseExample: false }, + ]; + for (let d = 5; d >= 1; d--) attempts.push({ maxDepth: d, responseExample: false }); + let out; + for (const a of attempts) { + out = build(entry, pageUrl, a); + if (out.length <= MAX_CHARS) return out; + } + return out; +} + +module.exports = { renderOperationMarkdown, MAX_CHARS, _build: build }; diff --git a/plugins/llms-markdown/api/render-operation.test.js b/plugins/llms-markdown/api/render-operation.test.js new file mode 100644 index 00000000..c343d16c --- /dev/null +++ b/plugins/llms-markdown/api/render-operation.test.js @@ -0,0 +1,85 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const path = require("path"); +const si = require("./spec-index"); +const { buildTitleMap } = require("./api-titles"); +const { renderOperationMarkdown, MAX_CHARS } = require("./render-operation"); +const { pointerLine } = require("../pointer"); + +const siteDir = path.resolve(__dirname, "../../.."); +let cached; +async function load() { + if (!cached) { + const index = si.buildOperationIndex(await si.loadDereferencedSpecs(siteDir)); + const titles = buildTitleMap(si.listOperations(si.loadRawSpecsSync(siteDir))); + for (const [k, e] of index) { + e.title = titles.get(k).title; + e.pageUrl = `https://docs.absmartly.com/docs/test/${e.operationId}`; + } + cached = index; + } + return cached; +} +const render = (e) => renderOperationMarkdown(e, { pageUrl: e.pageUrl }); +// An empty section is a heading directly followed by a heading of the same or higher level. +const noEmptySections = (md) => { + const re = /^(#+) .*\n\n(#+) /gm; + let m; + while ((m = re.exec(md))) assert.ok(m[2].length > m[1].length, `empty section: ${m[0]}`); +}; + +test("pointerLine wording", () => { + assert.strictEqual( + pointerLine("https://docs.absmartly.com/docs/x"), + "> For AI agents: this page is available as Markdown at https://docs.absmartly.com/docs/x.md. The full documentation index is at https://docs.absmartly.com/llms.txt.", + ); +}); + +test("archive goal page", async () => { + const e = (await load()).get("PUT /goals/{goalId}/archive"); + const md = render(e); + assert.ok(md.startsWith(pointerLine(e.pageUrl))); + assert.ok(md.includes("# Archive goal")); + assert.ok(md.includes("`PUT /goals/{goalId}/archive`")); + assert.match(md, /## Path parameters[\s\S]*\| `goalId` \|/); + assert.ok(md.includes("Api-Key")); + assert.ok(md.includes("operationId `ArchiveGoal`")); + assert.ok(md.includes("Base URL: ")); + noEmptySections(md); +}); + +test("create experiment page", async () => { + const md = render((await load()).get("POST /experiments")); + assert.ok(md.includes("## Request body")); + assert.ok(md.includes("unit_type_id")); + const m = md.match(/### Example request body[^\n]*\n\n```json\n([\s\S]*?)\n```/); + assert.ok(m); + JSON.parse(m[1]); +}); + +test("collector context create", async () => { + const md = render((await load()).get("POST /context")); + assert.ok(md.includes("X-API-Key")); + assert.ok(md.includes("(generated from the schema)")); +}); + +test("sparse operations have no empty sections", async () => { + const idx = await load(); + for (const k of ["GET /healthy", "DELETE /events/unit_data"]) { + const e = idx.get(k); + assert.ok(e, k); + const md = render(e); + noEmptySections(md); + assert.doesNotMatch(md, /\n## [^\n]*\n*$/); + } +}); + +test("every operation renders under the cap without :::", async () => { + const idx = await load(); + for (const [k, e] of idx) { + const md = render(e); + assert.ok(md.length <= MAX_CHARS, `${k} is ${md.length}`); + assert.ok(!md.includes(":::"), k); + noEmptySections(md); + } +}); diff --git a/plugins/llms-markdown/pointer.js b/plugins/llms-markdown/pointer.js new file mode 100644 index 00000000..43977292 --- /dev/null +++ b/plugins/llms-markdown/pointer.js @@ -0,0 +1,8 @@ +const LLMS_TXT_URL = "https://docs.absmartly.com/llms.txt"; + +// `pageUrl` is the page's absolute URL without a trailing slash. +function pointerLine(pageUrl) { + return `> For AI agents: this page is available as Markdown at ${pageUrl}.md. The full documentation index is at ${LLMS_TXT_URL}.`; +} + +module.exports = { pointerLine, LLMS_TXT_URL }; From 8834d5232a7244d0c57ddc57ec98e9bf4db6d9f6 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 11:48:55 +0000 Subject: [PATCH 06/43] fix(llms): include path-item parameters in API operation pages Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- plugins/llms-markdown/api/render-operation.js | 18 ++++++-- .../api/render-operation.test.js | 46 +++++++++++++++++++ plugins/llms-markdown/api/spec-index.js | 1 + plugins/llms-markdown/api/spec-index.test.js | 7 +++ 4 files changed, 68 insertions(+), 4 deletions(-) diff --git a/plugins/llms-markdown/api/render-operation.js b/plugins/llms-markdown/api/render-operation.js index be53e5be..bc62cf6f 100644 --- a/plugins/llms-markdown/api/render-operation.js +++ b/plugins/llms-markdown/api/render-operation.js @@ -1,5 +1,7 @@ const { renderSchemaFields } = require("./render-schema"); const { pointerLine } = require("../pointer"); +const { sampleRequestFromSchema } = require("docusaurus-plugin-openapi-docs/lib/openapi/createRequestExample"); +const { sampleResponseFromSchema } = require("docusaurus-plugin-openapi-docs/lib/openapi/createResponseExample"); const MAX_CHARS = 50000; const BASE_URL_LINE = @@ -38,6 +40,15 @@ function paramType(schema) { return t; } +// Path-item parameters apply to every operation; operation-level ones win on name+in. +function mergeParams(pathParams, opParams) { + const own = Array.isArray(opParams) ? opParams : []; + const inherited = (Array.isArray(pathParams) ? pathParams : []).filter( + (p) => !own.some((o) => o.name === p.name && o.in === p.in), + ); + return [...inherited, ...own]; +} + function paramTable(params, where, title) { const rows = params.filter((p) => p.in === where); if (!rows.length) return ""; @@ -45,7 +56,7 @@ function paramTable(params, where, title) { for (const p of rows) { let desc = oneLine(p.description || (p.schema && p.schema.description)); const en = p.schema && Array.isArray(p.schema.enum) ? p.schema.enum : null; - if (en) desc += `${desc ? " " : ""}One of: ${en.map((v) => `\`${v}\``).join(", ")}.`; + if (en) desc += `${desc ? " " : ""}One of: ${en.map((v) => `\`${String(v).replace(/\|/g, "\\|")}\``).join(", ")}.`; lines.push(`| \`${p.name}\` | ${paramType(p.schema)} | ${p.required || where === "path" ? "yes" : "no"} | ${desc} |`); } return lines.join("\n"); @@ -99,10 +110,8 @@ function fieldList(schema, maxDepth) { } function build(entry, pageUrl, { maxDepth, responseExample }) { - const { sampleRequestFromSchema } = require("docusaurus-plugin-openapi-docs/lib/openapi/createRequestExample"); - const { sampleResponseFromSchema } = require("docusaurus-plugin-openapi-docs/lib/openapi/createResponseExample"); const op = entry.op || {}; - const params = Array.isArray(op.parameters) ? op.parameters : []; + const params = mergeParams(entry.pathParameters, op.parameters); const sections = []; const push = (s) => s && sections.push(s); @@ -172,6 +181,7 @@ function renderOperationMarkdown(entry, { pageUrl }) { out = build(entry, pageUrl, a); if (out.length <= MAX_CHARS) return out; } + console.warn(`${entry.method} ${entry.path}: ${out.length} chars, still over ${MAX_CHARS} after the size guard`); return out; } diff --git a/plugins/llms-markdown/api/render-operation.test.js b/plugins/llms-markdown/api/render-operation.test.js index c343d16c..36bc3323 100644 --- a/plugins/llms-markdown/api/render-operation.test.js +++ b/plugins/llms-markdown/api/render-operation.test.js @@ -83,3 +83,49 @@ test("every operation renders under the cap without :::", async () => { noEmptySections(md); } }); + +test("every {placeholder} in every path has a parameter row", async () => { + const idx = await load(); + for (const [k, e] of idx) { + const md = render(e); + for (const [, name] of e.path.matchAll(/\{([^}]+)\}/g)) { + assert.ok(md.includes(`| \`${name}\` |`), `${k} is missing a row for ${name}`); + } + } +}); + +test("operation-level parameters override path-level ones", () => { + const entry = { + specKey: "webConsole", + method: "GET", + path: "/a/{id}", + operationId: "x", + title: "X", + publishedUrl: "u", + pathParameters: [ + { name: "id", in: "path", required: true, schema: { type: "integer" }, description: "path-level" }, + { name: "q", in: "query", schema: { type: "string" }, description: "inherited" }, + ], + op: { + parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" }, description: "op-level" }], + responses: {}, + }, + }; + const md = renderOperationMarkdown(entry, { pageUrl: "https://x/y" }); + assert.ok(md.includes("op-level")); + assert.ok(!md.includes("path-level")); + assert.ok(md.includes("| `q` |")); +}); + +test("enum values escape pipes", () => { + const entry = { + specKey: "collector", + method: "GET", + path: "/a", + operationId: "x", + title: "X", + publishedUrl: "u", + op: { parameters: [{ name: "q", in: "query", schema: { type: "string", enum: ["a|b"] } }], responses: {} }, + }; + assert.ok(renderOperationMarkdown(entry, { pageUrl: "https://x/y" }).includes("`a\\|b`")); +}); diff --git a/plugins/llms-markdown/api/spec-index.js b/plugins/llms-markdown/api/spec-index.js index 9b5c3e30..91f14579 100644 --- a/plugins/llms-markdown/api/spec-index.js +++ b/plugins/llms-markdown/api/spec-index.js @@ -47,6 +47,7 @@ function listOperations(rawSpecs) { summary: op.summary, description: op.description, op, + pathParameters: Array.isArray(item.parameters) ? item.parameters : [], }); } } diff --git a/plugins/llms-markdown/api/spec-index.test.js b/plugins/llms-markdown/api/spec-index.test.js index a85fc347..c280f913 100644 --- a/plugins/llms-markdown/api/spec-index.test.js +++ b/plugins/llms-markdown/api/spec-index.test.js @@ -39,6 +39,13 @@ test("duplicate method+path across specs throws", () => { assert.throws(() => si.buildOperationIndex(specs), /Duplicate operation/); }); +test("entries carry path-item parameters", async () => { + const index = si.buildOperationIndex(await si.loadDereferencedSpecs(siteDir)); + const entry = index.get("GET /experiments/{experimentId}"); + assert.ok(entry.pathParameters.some((p) => p.name === "experimentId" && p.in === "path")); + assert.deepStrictEqual(index.get("GET /healthy").pathParameters, []); +}); + test("normaliseEndpointPath converts colon params", () => { assert.strictEqual( si.normaliseEndpointPath("/goals/:goalId/archive"), From d9c765a0142e935d368b5b4ccc3d48213050b850 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 11:55:18 +0000 Subject: [PATCH 07/43] feat(llms): generate API reference Markdown from the OpenAPI specs API reference pages render their schemas client-side, so their built Markdown was a near-empty stub. A rehype plugin now replaces each API page's content with the reference rendered from the spec, and a wrapper around the llms-txt plugin loads the operation index before conversion. The index now also covers HEAD/OPTIONS/TRACE operations, which have generated pages too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- docusaurus.config.js | 4 +- plugins/llms-markdown/api/spec-index.js | 3 +- plugins/llms-markdown/api/spec-index.test.js | 6 +- plugins/llms-markdown/llms-txt-wrapper.js | 47 ++++++++++ .../llms-markdown/publish-openapi-specs.js | 5 +- plugins/llms-markdown/rehype-api-markdown.js | 63 +++++++++++++ .../llms-markdown/rehype-api-markdown.test.js | 91 +++++++++++++++++++ 7 files changed, 213 insertions(+), 6 deletions(-) create mode 100644 plugins/llms-markdown/llms-txt-wrapper.js create mode 100644 plugins/llms-markdown/rehype-api-markdown.js create mode 100644 plugins/llms-markdown/rehype-api-markdown.test.js diff --git a/docusaurus.config.js b/docusaurus.config.js index 95d1b5c1..2fb93605 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -114,7 +114,8 @@ const config = { "docusaurus-plugin-sass", [ // .md per page + /llms.txt; see netlify/edge-functions/markdown-negotiation.js. - "@signalwire/docusaurus-plugin-llms-txt", + // Wraps @signalwire/docusaurus-plugin-llms-txt to load the OpenAPI index first. + require.resolve("./plugins/llms-markdown/llms-txt-wrapper"), { siteDescription: "ABsmartly product documentation: experimentation platform, SDKs and APIs.\n\n" + @@ -147,6 +148,7 @@ const config = { excludeRoutes: ["/search"], remarkPlugins: [require("./plugins/llms-markdown/remark-fix-md-links")], beforeDefaultRehypePlugins: [ + require("./plugins/llms-markdown/rehype-api-markdown"), require("./plugins/llms-markdown/rehype-docusaurus-cleanup"), ], }, diff --git a/plugins/llms-markdown/api/spec-index.js b/plugins/llms-markdown/api/spec-index.js index 91f14579..aadaf71e 100644 --- a/plugins/llms-markdown/api/spec-index.js +++ b/plugins/llms-markdown/api/spec-index.js @@ -6,7 +6,8 @@ const path = require("path"); const yaml = require("js-yaml"); const SITE_URL = "https://docs.absmartly.com"; -const METHODS = ["get", "put", "post", "delete", "patch"]; +// Every OpenAPI path-item method; docusaurus-plugin-openapi-docs generates a page for each. +const METHODS = ["get", "put", "post", "delete", "patch", "head", "options", "trace"]; const SPECS = [ { diff --git a/plugins/llms-markdown/api/spec-index.test.js b/plugins/llms-markdown/api/spec-index.test.js index c280f913..735d0307 100644 --- a/plugins/llms-markdown/api/spec-index.test.js +++ b/plugins/llms-markdown/api/spec-index.test.js @@ -11,11 +11,13 @@ test("listOperations covers both real specs without duplicates", () => { const collector = ops.filter((o) => o.specKey === "collector"); assert.ok(web.length > 0); assert.ok(collector.length > 0); - assert.strictEqual(web.length, 277); + // One page per operation, including the HEAD /files/... operation. + assert.strictEqual(web.length, 278); + assert.ok(web.some((o) => o.method === "HEAD" && o.path === "/files/{usage}/{id}/{action}/{filename}")); assert.strictEqual(collector.length, 6); const keys = ops.map((o) => `${o.method} ${o.path}`); assert.strictEqual(new Set(keys).size, keys.length); - for (const o of ops) assert.match(o.method, /^(GET|PUT|POST|DELETE|PATCH)$/); + for (const o of ops) assert.match(o.method, /^(GET|PUT|POST|DELETE|PATCH|HEAD|OPTIONS|TRACE)$/); }); test("buildOperationIndex keys archiveGoal and dereferences", async () => { diff --git a/plugins/llms-markdown/llms-txt-wrapper.js b/plugins/llms-markdown/llms-txt-wrapper.js new file mode 100644 index 00000000..e88b301f --- /dev/null +++ b/plugins/llms-markdown/llms-txt-wrapper.js @@ -0,0 +1,47 @@ +// Wraps @signalwire/docusaurus-plugin-llms-txt so the OpenAPI operation index +// is loaded before its postBuild converts pages (rehype-api-markdown reads it). +// Docusaurus runs every plugin's postBuild concurrently, so the index must be +// built inside this postBuild, before awaiting the inner one. + +const { loadFreshModule } = require("@docusaurus/utils"); +const { + loadRawSpecsSync, + listOperations, + loadDereferencedSpecs, + buildOperationIndex, + attachPageUrls, + setLoadedIndex, +} = require("./api/spec-index"); +const { buildTitleMap } = require("./api/api-titles"); + +async function buildApiIndex(siteDir) { + const index = buildOperationIndex(await loadDereferencedSpecs(siteDir)); + attachPageUrls(index, siteDir); + const titles = buildTitleMap(listOperations(loadRawSpecsSync(siteDir))); + for (const [key, entry] of index) entry.title = titles.get(key).title; + return index; +} + +// Post-processing of the generated llms files (Task 6). No-op for now. +async function postProcessLlms(_outDir, _options) {} + +module.exports = async function llmsTxtWrapper(context, options) { + const { postProcess, ...innerOptions } = options; + // The package's ESM build uses extensionless imports that Node's native + // import() rejects; load it the way Docusaurus loads plugins (jiti). + const innerModule = await loadFreshModule( + require.resolve("@signalwire/docusaurus-plugin-llms-txt"), + ); + const innerFactory = innerModule.default ?? innerModule; + const inner = await innerFactory(context, innerOptions); + return { + ...inner, + async postBuild(props) { + setLoadedIndex(await buildApiIndex(props.siteDir || context.siteDir)); + await inner.postBuild(props); + await postProcessLlms(props.outDir, postProcess); + }, + }; +}; + +module.exports._internal = { buildApiIndex, postProcessLlms }; diff --git a/plugins/llms-markdown/publish-openapi-specs.js b/plugins/llms-markdown/publish-openapi-specs.js index c182c4ca..673c59fd 100644 --- a/plugins/llms-markdown/publish-openapi-specs.js +++ b/plugins/llms-markdown/publish-openapi-specs.js @@ -1,5 +1,6 @@ -// Publishes the OpenAPI specs at /openapi/*.yaml: API pages render schemas -// client-side, so their Markdown lacks them. +// Publishes the raw OpenAPI specs at /openapi/*.yaml, the machine-readable +// source of the API reference pages and their generated Markdown +// (see rehype-api-markdown.js). const fs = require("fs/promises"); const path = require("path"); diff --git a/plugins/llms-markdown/rehype-api-markdown.js b/plugins/llms-markdown/rehype-api-markdown.js new file mode 100644 index 00000000..0dc98a61 --- /dev/null +++ b/plugins/llms-markdown/rehype-api-markdown.js @@ -0,0 +1,63 @@ +// API reference pages render their schemas client-side, so the built HTML has +// only the endpoint. This replaces such a page's content with the reference +// generated from the OpenAPI spec (as hast, so the llms-txt pipeline turns it +// back into Markdown). Pages without an endpoint pass through untouched. + +const { getLoadedIndex, normaliseEndpointPath } = require("./api/spec-index"); +const { renderOperationMarkdown } = require("./api/render-operation"); + +const isEl = (node) => node && node.type === "element"; +const hasClass = (node, name) => { + const c = node.properties && node.properties.className; + return (Array.isArray(c) ? c : typeof c === "string" ? c.split(/\s+/) : []).includes(name); +}; + +function find(node, pred) { + if (pred(node)) return node; + for (const child of node.children || []) { + const hit = find(child, pred); + if (hit) return hit; + } + return null; +} + +function toText(node) { + if (node.type === "text") return node.value; + return (node.children || []).map(toText).join(""); +} + +// ESM-only packages; require() of ESM works on Node >= 22.12. +function markdownToHast(markdown) { + const { fromMarkdown } = require("mdast-util-from-markdown"); + const { gfm } = require("micromark-extension-gfm"); + const { gfmFromMarkdown } = require("mdast-util-gfm"); + const { toHast } = require("mdast-util-to-hast"); + const mdast = fromMarkdown(markdown, { + extensions: [gfm()], + mdastExtensions: [gfmFromMarkdown()], + }); + return toHast(mdast); +} + +function endpointOf(tree) { + const pre = find(tree, (n) => isEl(n) && n.tagName === "pre" && hasClass(n, "openapi__method-endpoint")); + if (!pre) return null; + const badge = find(pre, (n) => isEl(n) && hasClass(n, "badge")); + const pathEl = find(pre, (n) => isEl(n) && hasClass(n, "openapi__method-endpoint-path")); + if (!badge || !pathEl) throw new Error("Malformed openapi__method-endpoint element"); + return { + method: toText(badge).trim().toUpperCase(), + path: normaliseEndpointPath(toText(pathEl).trim()), + }; +} + +module.exports = function rehypeApiMarkdown() { + return (tree) => { + const endpoint = endpointOf(tree); + if (!endpoint) return; + const entry = getLoadedIndex().get(`${endpoint.method} ${endpoint.path}`); + if (!entry) throw new Error(`No OpenAPI operation for ${endpoint.method} ${endpoint.path}`); + const hast = markdownToHast(renderOperationMarkdown(entry, { pageUrl: entry.pageUrl })); + tree.children = hast.type === "root" ? hast.children : [hast]; + }; +}; diff --git a/plugins/llms-markdown/rehype-api-markdown.test.js b/plugins/llms-markdown/rehype-api-markdown.test.js new file mode 100644 index 00000000..9f49256e --- /dev/null +++ b/plugins/llms-markdown/rehype-api-markdown.test.js @@ -0,0 +1,91 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const fs = require("fs"); +const path = require("path"); +const si = require("./api/spec-index"); +const rehypeApiMarkdown = require("./rehype-api-markdown"); + +const siteDir = path.resolve(__dirname, "../.."); +const builtArchiveGoal = path.join( + siteDir, + "build/docs/APIs-and-SDKs/Web-Console-API/archive-goal/index.html", +); +const PAGE_URL = "https://docs.absmartly.com/docs/APIs-and-SDKs/Web-Console-API/archive-goal"; + +const endpointHtml = (method, displayPath) => + `

Old title

` + + `
${method} ` +
+  `

${displayPath}

client-side stub

`; + +let stubIndex; +async function loadStubIndex() { + if (!stubIndex) { + const full = si.buildOperationIndex(await si.loadDereferencedSpecs(siteDir)); + const entry = full.get("PUT /goals/{goalId}/archive"); + entry.title = "Archive goal"; + entry.pageUrl = PAGE_URL; + stubIndex = new Map([["PUT /goals/{goalId}/archive", entry]]); + } + si.setLoadedIndex(stubIndex); +} + +// Mirrors what the llms-txt plugin hands to rehype plugins: a root wrapping +// the first `.theme-doc-markdown` element. +async function contentRoot(html) { + const { fromHtml } = await import("hast-util-from-html"); + const { select } = await import("hast-util-select"); + const doc = fromHtml(html); + const el = select(".theme-doc-markdown", doc); + assert.ok(el, "no .theme-doc-markdown element"); + return { type: "root", children: [el] }; +} + +async function run(tree) { + rehypeApiMarkdown()(tree); + const { toHtml } = await import("hast-util-to-html"); + return toHtml(tree); +} + +test("replaces an API page's content with the spec-derived reference", async () => { + await loadStubIndex(); + const html = await run(await contentRoot(endpointHtml("PUT", "/goals/:goalId/archive"))); + assert.match(html, /goalId<\/code><\/td>/); + assert.match(html, /

Archive goal<\/h1>/); + assert.match(html, /
[\s\S]*For AI agents/); + assert.ok(!html.includes("client-side stub")); + assert.ok(!html.includes("Old title")); +}); + +test("real built archive-goal page", async (t) => { + if (!fs.existsSync(builtArchiveGoal)) return t.skip("build/ absent"); + await loadStubIndex(); + const html = await run(await contentRoot(fs.readFileSync(builtArchiveGoal, "utf8"))); + assert.match(html, /goalId<\/code><\/td>/); + assert.match(html, /

Responses<\/h2>/); +}); + +test("JSON code fences keep their language", async () => { + const full = si.buildOperationIndex(await si.loadDereferencedSpecs(siteDir)); + const entry = full.get("POST /experiments"); + entry.title = "Create experiment"; + entry.pageUrl = "https://docs.absmartly.com/docs/x"; + si.setLoadedIndex(new Map([["POST /experiments", entry]])); + const html = await run(await contentRoot(endpointHtml("POST", "/experiments"))); + assert.match(html, //); +}); + +test("unknown endpoint throws naming method and path", async () => { + await loadStubIndex(); + const tree = await contentRoot(endpointHtml("GET", "/nope/:id")); + assert.throws(() => rehypeApiMarkdown()(tree), /No OpenAPI operation for GET \/nope\/\{id\}/); +}); + +test("pages without an endpoint pass through untouched", async () => { + si.setLoadedIndex(new Map()); + const tree = await contentRoot( + `

Web Console API

Intro

`, + ); + const before = JSON.stringify(tree); + rehypeApiMarkdown()(tree); + assert.strictEqual(JSON.stringify(tree), before); +}); From 066be8a966b608b7fab0cfbe6d9db4eee1b4643f Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 12:11:50 +0000 Subject: [PATCH 08/43] feat(llms): restructure llms.txt and trim llms-full.txt - llms.txt gets a "Start here" block; the 278 Web Console API endpoint entries move to docs/APIs-and-SDKs/Web-Console-API/llms.txt (76,359 -> 31,801 chars). API entries are described as "METHOD /path. . Required permissions: ...", other truncated descriptions are replaced with full sentences from the page's Markdown. - llms-full.txt drops Web Console endpoint pages, gets the new index as its header and a note pointing to the API index and specs (3.08 MB -> 1.06 MB). - The wrapper re-exports the inner plugin's validateOptions (postProcess stripped), names a missing API title, and is tested for hook order. - remark-tight-lists stops hast-util-to-mdast spreading lists that have nested lists, so generated field lists are tight. - Declare @docusaurus/utils; add build-output checks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- AGENTS.md | 4 + docusaurus.config.js | 71 +++- package.json | 1 + plugins/build-checks.test.js | 66 ++++ plugins/llms-markdown/llms-txt-wrapper.js | 86 ++-- .../llms-markdown/llms-txt-wrapper.test.js | 72 ++++ plugins/llms-markdown/postprocess-llms.js | 373 +++++++++++++++++ .../llms-markdown/postprocess-llms.test.js | 374 ++++++++++++++++++ plugins/llms-markdown/remark-tight-lists.js | 22 ++ .../llms-markdown/remark-tight-lists.test.js | 27 ++ yarn.lock | 2 +- 11 files changed, 1071 insertions(+), 27 deletions(-) create mode 100644 plugins/build-checks.test.js create mode 100644 plugins/llms-markdown/llms-txt-wrapper.test.js create mode 100644 plugins/llms-markdown/postprocess-llms.js create mode 100644 plugins/llms-markdown/postprocess-llms.test.js create mode 100644 plugins/llms-markdown/remark-tight-lists.js create mode 100644 plugins/llms-markdown/remark-tight-lists.test.js diff --git a/AGENTS.md b/AGENTS.md index 0ec78319..1155b4a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,6 +52,10 @@ yarn gen:api - `@signalwire/docusaurus-plugin-llms-txt` converts every built page to Markdown at `.md` (e.g. `/docs/glossary/` -> `/docs/glossary.md`) and writes `/llms.txt` and `/llms-full.txt`. +- It is wrapped by `plugins/llms-markdown/llms-txt-wrapper.js`, whose `postBuild` then runs + `postprocess-llms.js` (options: `postProcess` in `docusaurus.config.js`): adds the "Start here" + block, moves Web Console API endpoints to `/docs/APIs-and-SDKs/Web-Console-API/llms.txt`, fixes + truncated descriptions, and drops Web Console endpoint pages from `/llms-full.txt`. - `plugins/llms-markdown/rehype-docusaurus-cleanup.js` rewrites tabs, code blocks, admonitions and `
` into plain HTML first so they survive the conversion. - `netlify/edge-functions/markdown-negotiation.js` serves the `.md` at the normal page URL when the diff --git a/docusaurus.config.js b/docusaurus.config.js index 2fb93605..6ead90b9 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -121,8 +121,72 @@ const config = { "ABsmartly product documentation: experimentation platform, SDKs and APIs.\n\n" + "Every page is available as Markdown: append `.md` to the page URL " + "(e.g. https://docs.absmartly.com/docs/glossary.md), or request the normal URL " + - "with `Accept: text/markdown`. /llms-full.txt contains all pages in one file.", + "with `Accept: text/markdown`. /llms-full.txt has the guides and the Collector API " + + "pages in one file; the Web Console API endpoints have their own index at " + + "/docs/APIs-and-SDKs/Web-Console-API/llms.txt.", depth: 2, + // Rewrites llms.txt and llms-full.txt after the inner plugin has written + // them; see plugins/llms-markdown/postprocess-llms.js. + postProcess: { + startHere: [ + { + title: "SDK getting started", + url: "https://docs.absmartly.com/docs/APIs-and-SDKs/SDK-Documentation/getting-started.md", + description: "Install an ABsmartly SDK, create a context and run your first experiment.", + }, + { + title: "SDK guide", + url: "https://docs.absmartly.com/docs/APIs-and-SDKs/SDK-Documentation.md", + description: "How the SDKs assign variants, track exposures and goals, and handle feature flags.", + }, + { + title: "Web Console API endpoint index", + url: "https://docs.absmartly.com/docs/APIs-and-SDKs/Web-Console-API/llms.txt", + description: "Every REST endpoint for managing experiments, metrics, goals, teams and settings.", + }, + { + title: "Web Console API OpenAPI spec", + url: "https://docs.absmartly.com/openapi/web-console-api.yaml", + description: "Full request/response schemas for the Web Console API.", + }, + { + title: "Collector API", + url: "https://docs.absmartly.com/docs/APIs-and-SDKs/SDK-API/absmartly-collector-api.md", + description: "The API the SDKs use to fetch assignments and publish events, for languages without an SDK.", + }, + { + title: "Collector API OpenAPI spec", + url: "https://docs.absmartly.com/openapi/collector-api.yaml", + description: "Full request/response schemas for the Collector API.", + }, + { + title: "MCP server", + url: "https://docs.absmartly.com/docs/APIs-and-SDKs/MCP-Server/overview.md", + description: "Connect AI assistants to ABsmartly through the Model Context Protocol.", + }, + { + title: "CLI", + url: "https://docs.absmartly.com/docs/APIs-and-SDKs/CLI-Documentation.md", + description: "Manage experiments and feature flags from a terminal or script.", + }, + { + title: "Glossary", + url: "https://docs.absmartly.com/docs/glossary.md", + description: "Key experimentation and ABsmartly concepts.", + }, + ], + apiIndexHeader: + "# ABsmartly Web Console API\n\n" + + "> REST API for managing experiments, feature flags, metrics, goals, teams and settings in ABsmartly. " + + "Authenticate with `Authorization: Api-Key ` (API key from Settings → API Keys) or a federated OIDC access token. " + + "Full request/response schemas: https://docs.absmartly.com/openapi/web-console-api.yaml\n\n" + + "Each endpoint page below is Markdown. The main documentation index is at https://docs.absmartly.com/llms.txt.\n", + fullNote: + "This file has the guides and the Collector API pages. Web Console API endpoint pages are not " + + "included: see the endpoint index at https://docs.absmartly.com/docs/APIs-and-SDKs/Web-Console-API/llms.txt " + + "and the OpenAPI specs at https://docs.absmartly.com/openapi/web-console-api.yaml and " + + "https://docs.absmartly.com/openapi/collector-api.yaml.", + }, // A page that fails to convert would still advertise a .md that 404s. onRouteError: "throw", optionalLinks: [ @@ -146,7 +210,10 @@ const config = { includeBlog: false, includePages: false, excludeRoutes: ["/search"], - remarkPlugins: [require("./plugins/llms-markdown/remark-fix-md-links")], + remarkPlugins: [ + require("./plugins/llms-markdown/remark-fix-md-links"), + require("./plugins/llms-markdown/remark-tight-lists"), + ], beforeDefaultRehypePlugins: [ require("./plugins/llms-markdown/rehype-api-markdown"), require("./plugins/llms-markdown/rehype-docusaurus-cleanup"), diff --git a/package.json b/package.json index ba5bf4fc..9934a426 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,7 @@ "@docusaurus/plugin-ideal-image": "^3.10.2", "@docusaurus/preset-classic": "^3.10.2", "@docusaurus/theme-mermaid": "^3.10.2", + "@docusaurus/utils": "^3.10.2", "@mdx-js/react": "^3.1.1", "@signalwire/docusaurus-plugin-llms-txt": "1.2.2", "clsx": "^2.1.0", diff --git a/plugins/build-checks.test.js b/plugins/build-checks.test.js new file mode 100644 index 00000000..b23becf2 --- /dev/null +++ b/plugins/build-checks.test.js @@ -0,0 +1,66 @@ +// Checks on the built site (yarn build). Each check is skipped when build/ is absent. +const test = require("node:test"); +const assert = require("node:assert"); +const fs = require("fs"); +const path = require("path"); + +const buildDir = path.resolve(__dirname, "../build"); +const read = (rel) => fs.readFileSync(path.join(buildDir, rel), "utf8"); +const API_INDEX = "docs/APIs-and-SDKs/Web-Console-API/llms.txt"; +const WC_URL = "https://docs.absmartly.com/docs/APIs-and-SDKs/Web-Console-API/"; + +function buildTest(name, fn) { + test(name, (t) => { + if (!fs.existsSync(path.join(buildDir, "llms.txt"))) return t.skip("build/ absent"); + return fn(t); + }); +} + +buildTest("main llms.txt is under 50,000 characters and has no Web Console endpoints", () => { + const main = read("llms.txt"); + assert.ok(main.length < 50000, `llms.txt is ${main.length} chars`); + assert.match(main, /\n## Start here\n/); + assert.ok(main.includes(`(${WC_URL}llms.txt)`)); + const wcEntries = main.split("\n").filter((l) => l.startsWith("- [") && l.includes(`](${WC_URL}`) && !l.includes("llms.txt)")); + assert.deepStrictEqual(wcEntries, []); +}); + +buildTest("llms.txt descriptions are not truncated or Markdown-formatted", () => { + const { isTruncated } = require("./llms-markdown/postprocess-llms"); + for (const file of ["llms.txt", API_INDEX]) { + for (const line of read(file).split("\n")) { + const m = line.match(/^- \[(.*?)\]\((https:[^)]*)\): (.*)$/); + if (!m || !m[2].startsWith("https://docs.absmartly.com/docs/")) continue; + assert.ok(!m[3].includes("**") && !m[3].includes(":::"), `${file}: ${line}`); + // Descriptions that fell back to the page title are allowed. + if (m[3] !== m[1]) assert.ok(!isTruncated(m[3]), `${file}: truncated: ${line}`); + } + } +}); + +buildTest("the Web Console API index lists every endpoint", () => { + const index = read(API_INDEX); + assert.match(index, /^# ABsmartly Web Console API\n/); + const endpoints = index.split("\n## Endpoints\n")[1].split("\n").filter((l) => l.startsWith("- [")); + assert.ok(endpoints.length >= 270, `${endpoints.length} endpoints`); + for (const line of endpoints) assert.match(line, /\): (GET|PUT|POST|DELETE|PATCH|HEAD|OPTIONS) \//); +}); + +buildTest("llms-full.txt excludes Web Console endpoint pages but keeps Collector ones", () => { + const full = read("llms-full.txt"); + assert.ok(!full.includes(`Markdown at <${WC_URL}`), "Web Console section left in llms-full.txt"); + assert.ok(full.includes("SDK-API/collector-health-check.md")); + assert.ok(full.includes(`${WC_URL}llms.txt`), "note pointing to the API index"); +}); + +buildTest("every generated .md page is under 50,000 characters", () => { + const walk = (dir) => + fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => { + const p = path.join(dir, e.name); + return e.isDirectory() ? walk(p) : e.name.endsWith(".md") ? [p] : []; + }); + for (const file of walk(path.join(buildDir, "docs"))) { + const size = fs.readFileSync(file, "utf8").length; + assert.ok(size < 50000, `${path.relative(buildDir, file)} is ${size} chars`); + } +}); diff --git a/plugins/llms-markdown/llms-txt-wrapper.js b/plugins/llms-markdown/llms-txt-wrapper.js index e88b301f..57ac4bd7 100644 --- a/plugins/llms-markdown/llms-txt-wrapper.js +++ b/plugins/llms-markdown/llms-txt-wrapper.js @@ -1,9 +1,12 @@ // Wraps @signalwire/docusaurus-plugin-llms-txt so the OpenAPI operation index -// is loaded before its postBuild converts pages (rehype-api-markdown reads it). +// is loaded before its postBuild converts pages (rehype-api-markdown reads it), +// and so the generated llms.txt / llms-full.txt are post-processed after it. // Docusaurus runs every plugin's postBuild concurrently, so the index must be // built inside this postBuild, before awaiting the inner one. +// +// Options are the inner plugin's, plus `postProcess` (see postprocess-llms.js). -const { loadFreshModule } = require("@docusaurus/utils"); +const { createRequire } = require("module"); const { loadRawSpecsSync, listOperations, @@ -13,35 +16,70 @@ const { setLoadedIndex, } = require("./api/spec-index"); const { buildTitleMap } = require("./api/api-titles"); +const { postProcessLlms } = require("./postprocess-llms"); + +const INNER = "@signalwire/docusaurus-plugin-llms-txt"; + +// The package's ESM build uses extensionless imports that Node rejects, so it +// is loaded with jiti, as Docusaurus loads plugins (@docusaurus/utils' +// loadFreshModule). That helper is async and Docusaurus calls validateOptions +// synchronously, so this uses the same jiti, resolved from @docusaurus/utils, +// synchronously. +let innerModule; +function loadInnerModule() { + if (!innerModule) { + const jiti = createRequire(require.resolve("@docusaurus/utils"))("jiti"); + innerModule = jiti(__filename, { interopDefault: true })(require.resolve(INNER)); + } + return innerModule; +} async function buildApiIndex(siteDir) { const index = buildOperationIndex(await loadDereferencedSpecs(siteDir)); attachPageUrls(index, siteDir); const titles = buildTitleMap(listOperations(loadRawSpecsSync(siteDir))); - for (const [key, entry] of index) entry.title = titles.get(key).title; + for (const [key, entry] of index) { + const title = titles.get(key); + if (!title) throw new Error(`No title for ${key}`); + entry.title = title.title; + } return index; } -// Post-processing of the generated llms files (Task 6). No-op for now. -async function postProcessLlms(_outDir, _options) {} - -module.exports = async function llmsTxtWrapper(context, options) { - const { postProcess, ...innerOptions } = options; - // The package's ESM build uses extensionless imports that Node's native - // import() rejects; load it the way Docusaurus loads plugins (jiti). - const innerModule = await loadFreshModule( - require.resolve("@signalwire/docusaurus-plugin-llms-txt"), - ); - const innerFactory = innerModule.default ?? innerModule; - const inner = await innerFactory(context, innerOptions); - return { - ...inner, - async postBuild(props) { - setLoadedIndex(await buildApiIndex(props.siteDir || context.siteDir)); - await inner.postBuild(props); - await postProcessLlms(props.outDir, postProcess); - }, +function createLlmsTxtWrapper({ loadInner, buildIndex, postProcess }) { + return async function llmsTxtWrapper(context, options) { + const { postProcess: postProcessOptions, ...innerOptions } = options; + const innerFactory = await loadInner(); + const inner = await innerFactory(context, innerOptions); + return { + ...inner, + async postBuild(props) { + await buildIndex(props.siteDir || context.siteDir); + await inner.postBuild(props); + await postProcess(props.outDir, postProcessOptions); + }, + }; + }; +} + +// Validates the inner plugin's options at config load; `postProcess` is ours. +function createValidateOptions(getInnerValidate) { + return function validateOptions({ options, validate }) { + const { postProcess, ...innerOptions } = options; + const validated = getInnerValidate()({ options: innerOptions, validate }); + return { ...validated, postProcess }; }; -}; +} + +const llmsTxtWrapper = createLlmsTxtWrapper({ + loadInner: async () => { + const inner = loadInnerModule(); + return inner.default ?? inner; + }, + buildIndex: async (siteDir) => setLoadedIndex(await buildApiIndex(siteDir)), + postProcess: postProcessLlms, +}); -module.exports._internal = { buildApiIndex, postProcessLlms }; +module.exports = llmsTxtWrapper; +module.exports.validateOptions = createValidateOptions(() => loadInnerModule().validateOptions); +module.exports._internal = { buildApiIndex, createLlmsTxtWrapper, createValidateOptions }; diff --git a/plugins/llms-markdown/llms-txt-wrapper.test.js b/plugins/llms-markdown/llms-txt-wrapper.test.js new file mode 100644 index 00000000..0b34ee91 --- /dev/null +++ b/plugins/llms-markdown/llms-txt-wrapper.test.js @@ -0,0 +1,72 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const { createLlmsTxtWrapper, createValidateOptions } = require("./llms-txt-wrapper")._internal; + +test("postBuild sets the API index, then awaits the inner postBuild, then post-processes", async () => { + const calls = []; + const tick = () => new Promise((r) => setTimeout(r, 5)); + let innerOptions; + const wrapper = createLlmsTxtWrapper({ + loadInner: async () => (context, options) => { + innerOptions = options; + return { + name: "inner", + loadContent: () => "inner-content", + async postBuild() { + calls.push("inner:start"); + await tick(); + calls.push("inner:end"); + }, + }; + }, + buildIndex: async (siteDir) => { + await tick(); + calls.push(`index:${siteDir}`); + }, + postProcess: async (outDir, options) => { + calls.push(`post:${outDir}:${options.marker}`); + }, + }); + const plugin = await wrapper({ siteDir: "/site" }, { depth: 2, postProcess: { marker: "m" } }); + assert.deepStrictEqual(innerOptions, { depth: 2 }, "postProcess must not reach the inner plugin"); + assert.strictEqual(plugin.name, "inner"); + assert.strictEqual(plugin.loadContent(), "inner-content"); + await plugin.postBuild({ outDir: "/out" }); + assert.deepStrictEqual(calls, ["index:/site", "inner:start", "inner:end", "post:/out:m"]); +}); + +test("validateOptions validates without postProcess and keeps it on the result", () => { + let seen; + const validateOptions = createValidateOptions(() => ({ options, validate }) => { + seen = options; + return { ...validate(options), id: "default" }; + }); + const result = validateOptions({ + options: { depth: 2, postProcess: { a: 1 } }, + validate: (o) => ({ ...o, validated: true }), + }); + assert.deepStrictEqual(seen, { depth: 2 }); + assert.deepStrictEqual(result, { depth: 2, validated: true, id: "default", postProcess: { a: 1 } }); +}); + +test("the exported validateOptions runs the real inner validation", () => { + const { validateOptions } = require("./llms-txt-wrapper"); + const { normalizePluginOptions } = require("@docusaurus/utils-validation"); + const result = validateOptions({ + options: { depth: 2, postProcess: { marker: 1 } }, + validate: normalizePluginOptions, + }); + assert.strictEqual(result.depth, 2); + assert.deepStrictEqual(result.postProcess, { marker: 1 }); + assert.throws( + () => validateOptions({ options: { depth: "deep" }, validate: normalizePluginOptions }), + /"depth" must be a number/, + ); +}); + +test("validateOptions passes inner validation errors through", () => { + const validateOptions = createValidateOptions(() => () => { + throw new Error("bad option"); + }); + assert.throws(() => validateOptions({ options: {}, validate: (o) => o }), /bad option/); +}); diff --git a/plugins/llms-markdown/postprocess-llms.js b/plugins/llms-markdown/postprocess-llms.js new file mode 100644 index 00000000..af837bc6 --- /dev/null +++ b/plugins/llms-markdown/postprocess-llms.js @@ -0,0 +1,373 @@ +// Post-processes the llms-txt plugin's output (spec Part B2/B3): +// - llms.txt: "Start here" block, Web Console API entries moved to their own +// index (docs/APIs-and-SDKs/Web-Console-API/llms.txt), truncated +// descriptions replaced with full sentences from the page's Markdown, API +// entries described from the OpenAPI spec. +// - llms-full.txt: Web Console API endpoint pages dropped, a note added, and +// the index at the top replaced by the new llms.txt. + +const fs = require("fs"); +const path = require("path"); +const { getLoadedIndex } = require("./api/spec-index"); + +const SITE_URL = "https://docs.absmartly.com"; +const WEB_CONSOLE_API_URL = `${SITE_URL}/docs/APIs-and-SDKs/Web-Console-API/`; +const API_INDEX_PATH = "docs/APIs-and-SDKs/Web-Console-API/llms.txt"; +const MAX_DESCRIPTION = 200; +const SECTION_SEPARATOR = "\n\n---\n\n"; +const FULL_CONTENT_HEADING = "# Full Documentation Content\n\n"; + +// --- sentences ------------------------------------------------------------- + +const ABBREVIATION = /\b(?:e\.g|i\.e|vs|cf)\.$/i; + +// Splits prose into sentences. A sentence ends at . ! or ? (plus closing +// quotes/brackets) followed by whitespace and a character that isn't lower case. +function splitSentences(text) { + const sentences = []; + const re = /[.!?]["')\]`]*(?=\s|$)/g; + let start = 0; + let m; + while ((m = re.exec(text))) { + const end = m.index + m[0].length; + if (ABBREVIATION.test(text.slice(0, m.index + 1))) continue; + if (/^\s+[a-z]/.test(text.slice(end))) continue; + sentences.push(text.slice(start, end).trim()); + start = end; + } + return { sentences, rest: text.slice(start).trim() }; +} + +// Markdown inline syntax to plain text (inline code is kept). +function plainInline(text) { + return text + .replace(/!\[[^\]]*\]\([^)]*\)/g, "") + .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/<[^>]+>/g, "") + .replace(/\*\*|__/g, "") + .replace(/:::\S*/g, "") + .replace(/\s+/g, " ") + .trim(); +} + +// A paragraph with no sentence punctuation still counts as one sentence when it +// reads like one: a lead-in ending in a colon ("These options are available on +// every command:") or at least six words (not a label such as "Overview"). +function unterminatedSentence(rest) { + if (/:$/.test(rest)) return rest.replace(/:$/, "."); + if (/^[A-Z`]/.test(rest) && rest.split(/\s+/).length >= 6 && !/[,;]$/.test(rest)) return `${rest}.`; + return null; +} + +// Drops " — … — " asides from a sentence that is too long to use whole. +function shorten(sentence) { + if (sentence.length <= MAX_DESCRIPTION) return sentence; + return sentence.replace(/ — [^—]+? — /g, " "); +} + +// Up to two sentences from the start of `prose`, at most MAX_DESCRIPTION chars. +function leadingSentences(prose) { + const split = splitSentences(prose); + let sentences = split.sentences; + if (!sentences.length) { + const lone = unterminatedSentence(split.rest); + sentences = lone ? [lone] : []; + } + let out = ""; + for (const s of sentences.slice(0, 2).map(shorten)) { + const next = out ? `${out} ${s}` : s; + if (next.length > MAX_DESCRIPTION) break; + out = next; + } + return out || null; +} + +// --- page Markdown ----------------------------------------------------------- + +// Splits Markdown into blocks: { kind, text } where kind is "paragraph" or a +// kind that never yields a description (heading, quote, table, code, list…). +function markdownBlocks(markdown) { + const blocks = []; + let current = null; + let fence = null; + const close = () => { + if (current) blocks.push(current); + current = null; + }; + for (const line of markdown.split("\n")) { + if (fence) { + if (line.trim().startsWith(fence)) fence = null; + continue; + } + const fenceMatch = line.match(/^\s*(`{3,}|~{3,})/); + if (fenceMatch) { + close(); + fence = fenceMatch[1]; + blocks.push({ kind: "code", text: "" }); + continue; + } + if (!line.trim()) { + close(); + continue; + } + if (current) { + current.text += `\n${line}`; + continue; + } + current = { kind: blockKind(line), text: line }; + } + close(); + return blocks; +} + +function blockKind(line) { + if (/^#{1,6}\s/.test(line)) return "heading"; + if (/^\s{0,3}>/.test(line)) return "quote"; + if (/^\s*\|/.test(line)) return "table"; + if (/^\s*([-*+]|\d+[.)])\s/.test(line)) return "list"; + if (/^\s{2,}|^\t/.test(line)) return "indented"; + if (/^:::/.test(line)) return "admonition"; + if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) return "rule"; + if (/^\s*(!\[|<)/.test(line)) return "html-or-image"; + return "paragraph"; +} + +function proseParagraphs(markdown) { + return markdownBlocks(markdown || "") + .filter((b) => b.kind === "paragraph") + .map((b) => plainInline(b.text)) + .filter(Boolean); +} + +// First one or two prose sentences of a page's Markdown (≤ 200 chars), or null. +function extractDescription(markdown) { + for (const paragraph of proseParagraphs(markdown)) { + const sentences = leadingSentences(paragraph); + if (sentences) return sentences; + } + return null; +} + +function pageHeadings(markdown) { + return markdownBlocks(markdown || "") + .filter((b) => b.kind === "heading") + .map((b) => plainInline(b.text.replace(/^#+\s*/, "")).toLowerCase()); +} + +// A description is truncated when it doesn't end like a sentence, carries a +// stray admonition marker, is just one of the page's headings, or (Docusaurus +// takes the first source line of hard-wrapped prose) stops partway through the +// page's first paragraph. +function isTruncated(description, markdown) { + const d = (description || "").trim(); + if (!d || d.includes(":::")) return true; + if (!/[.!?)`]$/.test(d)) return true; + if (!markdown) return false; + if (pageHeadings(markdown).includes(d.toLowerCase())) return true; + const first = proseParagraphs(markdown)[0] || ""; + return !/[.!?]$/.test(d) && first.length > d.length && first.startsWith(d); +} + +// --- API descriptions ------------------------------------------------------- + +const PERMISSIONS = /\*\*Required Permissions\*\*:([^\n]*)/; + +// "METHOD /path. . Required permissions: A or B." +function apiDescriptionFor(operation) { + let text = (operation.description || "").replace(/^:::[^\n]*\n[\s\S]*?^:::[ \t]*$/gm, ""); + const parts = [`${operation.method} ${operation.path}.`]; + + let permissions = null; + const m = text.match(PERMISSIONS); + if (m) { + const { sentences, rest } = splitSentences(m[1].trim()); + permissions = plainInline(sentences[0] || rest).replace(/`/g, "").replace(/\.$/, ""); + text = text.replace(PERMISSIONS, ""); + } + + const firstParagraph = markdownBlocks(text).find((b) => b.kind === "paragraph"); + if (firstParagraph) { + const prose = plainInline(firstParagraph.text); + const { sentences, rest } = splitSentences(prose); + const sentence = sentences[0] || (rest ? `${rest.replace(/[:;,]$/, "")}.` : null); + if (sentence && sentence.length <= MAX_DESCRIPTION) parts.push(sentence); + } + if (permissions) parts.push(`Required permissions: ${permissions}.`); + return parts.join(" "); +} + +// --- llms.txt ----------------------------------------------------------------- + +const ENTRY = /^- \[(.*?)\]\((https?:\/\/[^)]*)\)(?:: (.*))?$/; + +function renderLinks(links) { + return links.map((l) => `- [${l.title}](${l.url})${l.description ? `: ${l.description}` : ""}`).join("\n"); +} + +function describeEntry({ title, url, description }, { readMd, apiDescription }) { + const api = apiDescription(url); + if (api) return { description: api, isOperation: true }; + const markdown = readMd(url); + // Not a docs page with a Markdown file (e.g. the OpenAPI spec links). + if (markdown === null) return { description, isOperation: false }; + if (!isTruncated(description, markdown)) return { description, isOperation: false }; + return { description: extractDescription(markdown) ?? title, isOperation: false }; +} + +function rewriteLlmsTxt(llmsTxt, { readMd, apiDescription, apiIndexUrl, startHere, apiIndexHeader }) { + const main = []; + const apiGuides = []; + const apiEndpoints = []; + let apiLinkAt = -1; + let startHereAt = -1; + + for (const line of llmsTxt.split("\n")) { + const m = line.match(ENTRY); + if (!m) { + if (startHereAt < 0 && line.startsWith("## ")) startHereAt = main.length; + main.push(line); + continue; + } + const entry = { title: m[1], url: m[2], description: m[3] || "" }; + const { description, isOperation } = describeEntry(entry, { readMd, apiDescription }); + const rendered = renderLinks([{ ...entry, description }]); + if (entry.url.startsWith(WEB_CONSOLE_API_URL)) { + (isOperation ? apiEndpoints : apiGuides).push(rendered); + if (apiLinkAt < 0) { + apiLinkAt = main.length; + main.push(null); + } + } else { + main.push(rendered); + } + } + + if (apiLinkAt >= 0) { + main[apiLinkAt] = renderLinks([ + { + title: "Web Console API endpoint index", + url: apiIndexUrl, + description: `Index of the ${apiEndpoints.length} Web Console API endpoint pages, plus the API overview and examples.`, + }, + ]); + } + if (startHereAt >= 0) { + main.splice(startHereAt, 0, `## Start here\n\n${renderLinks(startHere)}\n`); + } + + const apiIndex = [ + apiIndexHeader.trimEnd(), + "", + "## Overview and examples", + "", + ...apiGuides, + "", + "## Endpoints", + "", + ...apiEndpoints, + "", + ].join("\n"); + + return { main: main.join("\n"), apiIndex }; +} + +// --- llms-full.txt ---------------------------------------------------------------- + +const POINTER = /^> For AI agents: this page is available as Markdown at \s]+?)>?\. /; + +function isWebConsoleApiSection(sectionText) { + const m = sectionText.match(POINTER); + return Boolean(m && m[1].startsWith(WEB_CONSOLE_API_URL)); +} + +// Inserts `note` as its own paragraph after the header's H1 description blockquote. +function addNote(header, note) { + const lines = header.trimEnd().split("\n"); + let at = lines.findIndex((l) => l.startsWith("> ")); + if (at < 0) at = 0; + while (at + 1 < lines.length && lines[at + 1].startsWith(">")) at++; + lines.splice(at + 1, 0, "", note); + return `${lines.join("\n")}\n`; +} + +// Page sections are joined by "\n\n---\n\n"; a page may contain a horizontal +// rule of its own, so a chunk that doesn't start a page (pointer line or H1) +// belongs to the previous page. +function rewriteLlmsFull(full, { isApiPage, note, header }) { + const chunks = full.split(SECTION_SEPARATOR); + const out = [addNote(header ?? chunks[0], note)]; + let dropping = false; + for (let i = 1; i < chunks.length; i++) { + let chunk = chunks[i]; + let prefix = ""; + if (chunk.startsWith(FULL_CONTENT_HEADING)) { + prefix = FULL_CONTENT_HEADING; + chunk = chunk.slice(prefix.length); + } + const startsPage = POINTER.test(chunk) || /^# /.test(chunk); + if (startsPage) dropping = isApiPage(chunk); + if (dropping) { + if (prefix) out.push(prefix.trimEnd()); + continue; + } + out.push(prefix + chunk); + } + return out.join(SECTION_SEPARATOR); +} + +// --- build ------------------------------------------------------------------- + +function markdownReader(outDir) { + return (url) => { + if (!url.startsWith(`${SITE_URL}/`) || !url.endsWith(".md")) return null; + const file = path.join(outDir, decodeURI(url.slice(SITE_URL.length + 1))); + return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null; + }; +} + +function apiDescriber() { + const byMarkdownUrl = new Map(); + for (const entry of getLoadedIndex().values()) byMarkdownUrl.set(`${entry.pageUrl}.md`, entry); + return (url) => { + const entry = byMarkdownUrl.get(url); + return entry ? apiDescriptionFor(entry) : null; + }; +} + +async function postProcessLlms(outDir, options) { + if (!options) throw new Error("llms-txt wrapper: missing postProcess options"); + const { startHere, apiIndexHeader, fullNote } = options; + const llmsTxtPath = path.join(outDir, "llms.txt"); + const fullPath = path.join(outDir, "llms-full.txt"); + + const { main, apiIndex } = rewriteLlmsTxt(fs.readFileSync(llmsTxtPath, "utf8"), { + readMd: markdownReader(outDir), + apiDescription: apiDescriber(), + apiIndexUrl: `${SITE_URL}/${API_INDEX_PATH}`, + startHere, + apiIndexHeader, + }); + fs.writeFileSync(llmsTxtPath, main); + fs.mkdirSync(path.dirname(path.join(outDir, API_INDEX_PATH)), { recursive: true }); + fs.writeFileSync(path.join(outDir, API_INDEX_PATH), apiIndex); + + if (fs.existsSync(fullPath)) { + const full = rewriteLlmsFull(fs.readFileSync(fullPath, "utf8"), { + isApiPage: isWebConsoleApiSection, + note: fullNote, + header: main, + }); + fs.writeFileSync(fullPath, full); + } +} + +module.exports = { + extractDescription, + isTruncated, + apiDescriptionFor, + rewriteLlmsTxt, + rewriteLlmsFull, + isWebConsoleApiSection, + postProcessLlms, + API_INDEX_PATH, +}; diff --git a/plugins/llms-markdown/postprocess-llms.test.js b/plugins/llms-markdown/postprocess-llms.test.js new file mode 100644 index 00000000..e8380443 --- /dev/null +++ b/plugins/llms-markdown/postprocess-llms.test.js @@ -0,0 +1,374 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const { + extractDescription, + isTruncated, + rewriteLlmsTxt, + rewriteLlmsFull, + apiDescriptionFor, + isWebConsoleApiSection, +} = require("./postprocess-llms"); + +const SITE = "https://docs.absmartly.com"; +const WC = `${SITE}/docs/APIs-and-SDKs/Web-Console-API`; +const pointer = (url) => + `> For AI agents: this page is available as Markdown at <${url}.md>. The full documentation index is at <${SITE}/llms.txt>.`; + +// --- extractDescription ----------------------------------------------------- + +test("extractDescription returns the first full sentences, skipping the H1 and pointer", () => { + const md = [ + pointer(`${SITE}/docs/a`), + "", + "# Authentication", + "", + "The ABsmartly MCP server supports two authentication methods. Both are configured per client — there are no server-side secrets, so credentials are always provided by your MCP client and isolated per connection.", + ].join("\n"); + assert.strictEqual( + extractDescription(md), + "The ABsmartly MCP server supports two authentication methods.", + ); +}); + +test("extractDescription takes two sentences when they fit in 200 characters", () => { + const md = "# T\n\nFirst sentence here. Second one [with a link](https://x.y/z.md) too! Third is left out."; + assert.strictEqual(extractDescription(md), "First sentence here. Second one with a link too!"); +}); + +test("extractDescription skips an image and an admonition before the prose", () => { + const md = [ + "# Zuko Integration", + "", + "![A screenshot of Zuko](/assets/zuko.png)", + "", + "> **Note**", + ">", + "> This needs a Zuko account.", + "", + "Zuko is a form analytics tool. You can send its events to ABsmartly.", + ].join("\n"); + assert.strictEqual( + extractDescription(md), + "Zuko is a form analytics tool. You can send its events to ABsmartly.", + ); +}); + +test("extractDescription skips headings, tables, code fences, lists and bold-only labels", () => { + const md = [ + "# Global Options", + "", + "## Global options", + "", + "**Overview**", + "", + "| a | b |", + "| - | - |", + "| 1 | 2 |", + "", + "```bash", + "abs doctor. Not a sentence.", + "```", + "", + "- [Link one](https://x.y/one.md)", + "- [Link two](https://x.y/two.md)", + "", + "Every command accepts these options.", + ].join("\n"); + assert.strictEqual(extractDescription(md), "Every command accepts these options."); +}); + +test("extractDescription returns null for a page with only a table and code", () => { + const md = "# Only data\n\n| a | b |\n| - | - |\n| 1 | 2 |\n\n```js\nconst x = 1.\n```\n"; + assert.strictEqual(extractDescription(md), null); +}); + +test("extractDescription does not split on e.g. and ignores sentences over 200 chars", () => { + assert.strictEqual( + extractDescription("# T\n\nUse a key (e.g. Settings → API Keys) for this. Done."), + "Use a key (e.g. Settings → API Keys) for this. Done.", + ); + const long = `${"word ".repeat(50).trim()}.`; + assert.strictEqual(extractDescription(`# T\n\n${long}\n\nShort one.`), "Short one."); +}); + +test("extractDescription joins hard-wrapped lines of a paragraph", () => { + const md = "# T\n\nThe ABsmartly Model Context Protocol (MCP)\nserver connects AI assistants to ABsmartly."; + assert.strictEqual( + extractDescription(md), + "The ABsmartly Model Context Protocol (MCP) server connects AI assistants to ABsmartly.", + ); +}); + +// --- isTruncated -------------------------------------------------------------- + +test("isTruncated flags mid-sentence, :::, empty and heading descriptions", () => { + assert.strictEqual(isTruncated("The ABsmartly MCP server supports two authentication methods. Both are"), true); + assert.strictEqual(isTruncated("Global options"), true); + assert.strictEqual(isTruncated("Read this first. :::"), true); + assert.strictEqual(isTruncated(":::note Something."), true); + assert.strictEqual(isTruncated(""), true); + assert.strictEqual(isTruncated("Installation.", "# Slack\n\n## Installation.\n"), true); + assert.strictEqual(isTruncated("Connect ABsmartly to Snowflake."), false); + assert.strictEqual(isTruncated("Run it (authenticated only)"), false); + assert.strictEqual(isTruncated("Use `abs doctor`"), false); +}); + +test("isTruncated flags a description that stops partway through the first paragraph", () => { + const md = "# MCP\n\nThe ABsmartly [Model Context Protocol](https://m.io/) (MCP) server lets AI assistants operate ABsmartly.\n"; + assert.strictEqual(isTruncated("The ABsmartly Model Context Protocol (MCP)", md), true); + assert.strictEqual(isTruncated("The ABsmartly Model Context Protocol (MCP)"), false); + const full = "# T\n\nCommon issues and how to fix them. More text follows.\n"; + assert.strictEqual(isTruncated("Common issues and how to fix them.", full), false); +}); + +test("extractDescription turns a lead-in paragraph ending in a colon into a sentence", () => { + const md = "# Global Options\n\n## Global options\n\nThese options are available on every command:\n\n| a |\n| - |\n\nThese flags write to stderr.\n"; + assert.strictEqual(extractDescription(md), "These options are available on every command."); +}); + +test("extractDescription drops dash asides from an over-long first sentence", () => { + const md = + "# MCP\n\nThe ABsmartly MCP server lets AI assistants — Claude, Cursor, VS Code, Windsurf, Gemini, ChatGPT and any other MCP-compatible client of your choosing, local or remote — operate the ABsmartly experimentation platform directly. The AI plans experiments.\n\nIt exposes 230+ commands.\n"; + assert.strictEqual( + extractDescription(md), + "The ABsmartly MCP server lets AI assistants operate the ABsmartly experimentation platform directly. The AI plans experiments.", + ); +}); + +test("extractDescription accepts an unpunctuated sentence-length paragraph, not a short label", () => { + assert.strictEqual( + extractDescription("# M\n\nTo create a new metric, open the catalog and click on `Create metric`\n"), + "To create a new metric, open the catalog and click on `Create metric`.", + ); + assert.strictEqual(extractDescription("# M\n\nWhat is an experiment\n"), null); +}); + +// --- apiDescriptionFor ---------------------------------------------------------- + +test("apiDescriptionFor uses the endpoint, a prose sentence and plain-text permissions", () => { + assert.strictEqual( + apiDescriptionFor({ + method: "PUT", + path: "/experiments/{experimentId}/development", + summary: "Start Experiment in Development [UPDATE]", + description: "**Required Permissions**: `Experiment Development` or `Experiment Admin`", + }), + "PUT /experiments/{experimentId}/development. Required permissions: Experiment Development or Experiment Admin.", + ); + assert.strictEqual( + apiDescriptionFor({ + method: "POST", + path: "/datasources/{datasourceId}/json_layouts/recreate", + description: "Drops and recreates the json_layouts table. Destructive.\n**Required Permissions**: `EventDatasourceConfig Edit`", + }), + "POST /datasources/{datasourceId}/json_layouts/recreate. Drops and recreates the json_layouts table. Required permissions: EventDatasourceConfig Edit.", + ); +}); + +test("apiDescriptionFor drops admonitions and permission detail, keeps unterminated prose", () => { + const d = apiDescriptionFor({ + method: "PUT", + path: "/goals/{goalId}", + description: + "**Required Permissions**: `Goal Edit` or `Goal Admin`\n\n:::caution\nOnly fields provided will be updated.\n:::\n", + }); + assert.strictEqual(d, "PUT /goals/{goalId}. Required permissions: Goal Edit or Goal Admin."); + assert.ok(!d.includes(":::") && !d.includes("**")); + assert.strictEqual( + apiDescriptionFor({ + method: "POST", + path: "/experiments/import", + description: + "**Required Permissions**: `Experiment Admin` and (`Experiment Create` or `Experiment CreateFromTemplate`). Importing a feature requires more.\n\nImports an experiment.", + }), + "POST /experiments/import. Imports an experiment. Required permissions: Experiment Admin and (Experiment Create or Experiment CreateFromTemplate).", + ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/notifications/summary", description: "Get user notifications with counts and pagination" }), + "GET /notifications/summary. Get user notifications with counts and pagination.", + ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/events/quota", description: "Get monthly events quota. **Required Permissions**: `List`" }), + "GET /events/quota. Get monthly events quota. Required permissions: List.", + ); + assert.strictEqual(apiDescriptionFor({ method: "GET", path: "/x" }), "GET /x."); + assert.strictEqual( + apiDescriptionFor({ method: "PUT", path: "/goals/{goalId}/archive", description: "**Required Permissions**: `Goal Archive` or `Goal Admin` :::\n" }), + "PUT /goals/{goalId}/archive. Required permissions: Goal Archive or Goal Admin.", + ); + assert.strictEqual( + apiDescriptionFor({ method: "HEAD", path: "/files/{id}", description: "**Required Permissions**: Access to the file based on its usage type." }), + "HEAD /files/{id}. Required permissions: Access to the file based on its usage type.", + ); +}); + +// --- rewriteLlmsTxt --------------------------------------------------------------- + +const LLMS_TXT = `# The ABsmartly Docs + +> ABsmartly product documentation. + +Every page is available as Markdown. + + +## docs + + +### APIs-and-SDKs + +- [Authentication](${SITE}/docs/APIs-and-SDKs/MCP-Server/authentication.md): The ABsmartly MCP server supports two authentication methods. Both are +- [Global Options & Configuration](${SITE}/docs/APIs-and-SDKs/CLI-Documentation/configuration.md): Global options +- [Admonition page](${SITE}/docs/a/admonition.md): :::note +- [Data only](${SITE}/docs/a/data-only.md): Overview +- [Good page](${SITE}/docs/a/good.md): Connect ABsmartly to Snowflake. +- [Set experiment to development](${WC}/003-set-experiment-to-development.md): **Required Permissions**: \`Experiment Development\` or \`Experiment Admin\` +- [ABsmartly Web Console API](${WC}/absmartly-web-console-api.md): An OpenAPI Specification that describes the ABsmartly API for working wit +- [List experiments](${WC}/0100-000-list-experiments.md): **Required Permissions**: \`Experiment List\` or \`Experiment Admin\` +- [Check Service Health](${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check.md): A GET request to check that the service is running as expected. + +### glossary + +- [SAML SSO - Okta](${SITE}/docs/SSO/Okta SAML Setup.md): The ABsmartly Web Console supports SAML SSO with Okta. + +## Optional +- [Web Console API OpenAPI spec](${SITE}/openapi/web-console-api.yaml): Full schemas +- [Missing page](${SITE}/docs/missing.md): Left as it is +`; + +const MDS = { + [`${SITE}/docs/APIs-and-SDKs/MCP-Server/authentication.md`]: + `${pointer(`${SITE}/docs/APIs-and-SDKs/MCP-Server/authentication`)}\n\n# Authentication\n\nThe ABsmartly MCP server supports two authentication methods. Both are configured per client — there are no server-side secrets, so credentials are always provided by your MCP client and isolated per connection.\n`, + [`${SITE}/docs/APIs-and-SDKs/CLI-Documentation/configuration.md`]: + "# Global Options & Configuration\n\n## Global options\n\nEvery command accepts these options.\n", + [`${SITE}/docs/a/admonition.md`]: "# Admonition page\n\n> **Note**\n>\n> Careful.\n\nThis page explains admonitions.\n", + [`${SITE}/docs/a/data-only.md`]: "# Data only\n\n## Overview\n\n| a | b |\n| - | - |\n", + [`${SITE}/docs/a/good.md`]: "# Good\n\nSomething else entirely.\n", + [`${WC}/absmartly-web-console-api.md`]: + "# ABsmartly Web Console API\n\nAn OpenAPI Specification that describes the ABsmartly API for working with experiments. More here.\n", + [`${SITE}/docs/SSO/Okta SAML Setup.md`]: "# Okta\n\nUnused.\n", +}; + +const API = { + [`${WC}/003-set-experiment-to-development.md`]: + "PUT /experiments/{experimentId}/development. Required permissions: Experiment Development or Experiment Admin.", + [`${WC}/0100-000-list-experiments.md`]: + "GET /experiments. Required permissions: Experiment List or Experiment Admin.", + [`${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check.md`]: + "GET /healthy. A GET request to check that the service is running as expected.", +}; + +const API_INDEX_URL = `${WC}/llms.txt`; +const START_HERE = [ + { title: "Web Console API index", url: API_INDEX_URL, description: "Every endpoint." }, + { title: "Glossary", url: `${SITE}/docs/glossary.md`, description: "Key concepts." }, +]; + +function rewrite() { + return rewriteLlmsTxt(LLMS_TXT, { + readMd: (url) => MDS[url] ?? null, + apiDescription: (url) => API[url] ?? null, + apiIndexUrl: API_INDEX_URL, + startHere: START_HERE, + apiIndexHeader: "# ABsmartly Web Console API\n\n> Auth line. Spec link.\n", + }); +} + +const entryLine = (text, title) => text.split("\n").find((l) => l.startsWith(`- [${title}](`)); + +test("rewriteLlmsTxt replaces a truncated description with full sentences from the page", () => { + const { main } = rewrite(); + assert.strictEqual( + entryLine(main, "Authentication"), + `- [Authentication](${SITE}/docs/APIs-and-SDKs/MCP-Server/authentication.md): The ABsmartly MCP server supports two authentication methods.`, + ); +}); + +test("rewriteLlmsTxt replaces heading-only and ::: descriptions, falls back to the title", () => { + const { main } = rewrite(); + assert.match(entryLine(main, "Global Options & Configuration"), /\): Every command accepts these options\.$/); + assert.match(entryLine(main, "Admonition page"), /\): This page explains admonitions\.$/); + assert.match(entryLine(main, "Data only"), /\): Data only$/); + assert.ok(!main.includes(":::")); +}); + +test("rewriteLlmsTxt leaves good descriptions untouched and handles URLs with spaces", () => { + const { main } = rewrite(); + assert.match(entryLine(main, "Good page"), /\): Connect ABsmartly to Snowflake\.$/); + assert.match(entryLine(main, "SAML SSO - Okta"), /Okta SAML Setup\.md\): The ABsmartly Web Console supports SAML SSO with Okta\.$/); +}); + +test("rewriteLlmsTxt leaves entries without a page Markdown file (spec links) untouched", () => { + const { main } = rewrite(); + assert.match(entryLine(main, "Web Console API OpenAPI spec"), /\): Full schemas$/); + assert.match(entryLine(main, "Missing page"), /\): Left as it is$/); +}); + +test("rewriteLlmsTxt moves Web Console entries to the API index and links it once", () => { + const { main, apiIndex } = rewrite(); + assert.ok(!main.includes(`${WC}/0`), "endpoint entries left in main"); + assert.ok(!main.includes("absmartly-web-console-api.md")); + assert.ok(!main.includes("**")); + const link = main.split("\n").filter((l) => l.startsWith("- [") && l.includes(`](${API_INDEX_URL})`)); + assert.strictEqual(link.length, 2, "Start here link + section link"); + assert.match(main, /Index of the 2 Web Console API endpoint pages/); + assert.match( + entryLine(main, "Check Service Health"), + /\): GET \/healthy\. A GET request to check that the service is running as expected\.$/, + ); + + assert.ok(apiIndex.startsWith("# ABsmartly Web Console API\n\n> Auth line. Spec link.\n")); + assert.match(apiIndex, /\n## Endpoints\n\n- \[Set experiment to development\]/); + assert.match( + entryLine(apiIndex, "List experiments"), + /\): GET \/experiments\. Required permissions: Experiment List or Experiment Admin\.$/, + ); + assert.match( + entryLine(apiIndex, "ABsmartly Web Console API"), + /\): An OpenAPI Specification that describes the ABsmartly API for working with experiments\. More here\.$/, + ); + assert.ok(apiIndex.indexOf("## Overview and examples") < apiIndex.indexOf("## Endpoints")); + assert.ok(!apiIndex.includes("**")); +}); + +test("rewriteLlmsTxt inserts the Start here block before the first section", () => { + const { main } = rewrite(); + const startHere = main.indexOf("## Start here"); + assert.ok(startHere > main.indexOf("Every page is available as Markdown.")); + assert.ok(startHere < main.indexOf("## docs")); + assert.match(main, /## Start here\n\n- \[Web Console API index\]\(https:\/\/docs\.absmartly\.com\/docs\/APIs-and-SDKs\/Web-Console-API\/llms\.txt\): Every endpoint\.\n- \[Glossary\]/); +}); + +// --- rewriteLlmsFull ---------------------------------------------------------------- + +const FULL = [ + "# The ABsmartly Docs\n\n> Old description.\n\n## docs\n\n- [x](y): z\n", + `# Full Documentation Content\n\n# ABsmartly CLI\n\nCLI body.`, + `${pointer(`${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check`)}\n\n# Check Service Health\n\nCollector body.`, + `${pointer(`${WC}/archive-goal`)}\n\n# Archive goal\n\nWeb Console body.`, + "Continuation of the Web Console page after a horizontal rule.", + "# Glossary\n\nGlossary body.", + "Glossary continuation.", +].join("\n\n---\n\n"); + +test("rewriteLlmsFull drops Web Console sections and keeps Collector and guide ones", () => { + const out = rewriteLlmsFull(FULL, { + isApiPage: isWebConsoleApiSection, + note: "Web Console API endpoints are not included here.", + header: "# The ABsmartly Docs\n\n> New description.\n\n## Start here\n\n- [a](b): c\n", + }); + assert.ok(out.includes("Collector body.")); + assert.ok(!out.includes("Web Console body.")); + assert.ok(!out.includes("Continuation of the Web Console page")); + assert.ok(out.includes("Glossary body.") && out.includes("Glossary continuation.")); + assert.ok(out.includes("CLI body.")); + assert.ok(out.includes("# Full Documentation Content")); + assert.ok(!out.includes("Old description.")); + assert.ok(out.startsWith("# The ABsmartly Docs\n\n> New description.\n\nWeb Console API endpoints are not included here.\n\n## Start here")); + assert.ok(!out.includes("---\n\n---")); +}); + +test("isWebConsoleApiSection only matches the pointer URL under Web-Console-API", () => { + assert.strictEqual(isWebConsoleApiSection(`${pointer(`${WC}/archive-goal`)}\n\n# Archive goal`), true); + assert.strictEqual(isWebConsoleApiSection(`${pointer(`${SITE}/docs/APIs-and-SDKs/SDK-API/x`)}\n\n# X`), false); + assert.strictEqual(isWebConsoleApiSection("# Custom Slack Integration\n\nSee Web-Console-API pages."), false); +}); diff --git a/plugins/llms-markdown/remark-tight-lists.js b/plugins/llms-markdown/remark-tight-lists.js new file mode 100644 index 00000000..769f70aa --- /dev/null +++ b/plugins/llms-markdown/remark-tight-lists.js @@ -0,0 +1,22 @@ +// Remark plugin: make compact lists tight in the generated Markdown. +// hast-util-to-mdast marks any
  • holding a nested list of two or more items +// as "spread", so every list with nested fields (all the API reference pages) +// came out with a blank line between bullets. A list item is compact when it +// has at most one non-list child (one paragraph plus nested lists); a list +// whose items are all compact is written tight. Items with several paragraphs +// or a code block keep their blank lines. +function isCompact(item) { + return (item.children || []).filter((c) => c.type !== "list").length <= 1; +} + +function walk(node) { + for (const child of node.children || []) walk(child); + if (node.type === "list" && node.children.every(isCompact)) { + node.spread = false; + for (const item of node.children) item.spread = false; + } +} + +module.exports = function remarkTightLists() { + return walk; +}; diff --git a/plugins/llms-markdown/remark-tight-lists.test.js b/plugins/llms-markdown/remark-tight-lists.test.js new file mode 100644 index 00000000..067cc9fa --- /dev/null +++ b/plugins/llms-markdown/remark-tight-lists.test.js @@ -0,0 +1,27 @@ +const test = require("node:test"); +const assert = require("node:assert"); +const remarkTightLists = require("./remark-tight-lists"); + +// Same path as the llms-txt plugin: HTML -> hast -> mdast -> Markdown. +function htmlToMarkdown(html) { + const { fromHtml } = require("hast-util-from-html"); + const { toMdast } = require("hast-util-to-mdast"); + const { toMarkdown } = require("mdast-util-to-markdown"); + const mdast = toMdast(fromHtml(html, { fragment: true })); + remarkTightLists()(mdast); + return toMarkdown(mdast); +} + +test("items with a nested list stay tight (hast-util-to-mdast marks them spread)", () => { + const md = htmlToMarkdown( + "
    • a (string)
    • b (object)\n
      • c
      • d
    ", + ); + assert.strictEqual(md, "* `a` (string)\n* `b` (object)\n * `c`\n * `d`\n"); +}); + +test("items with several paragraphs or a code block stay spread", () => { + const md = htmlToMarkdown("
    • One.

      Two.

    • Three.

    "); + assert.strictEqual(md, "* One.\n\n Two.\n\n* Three.\n"); + const code = htmlToMarkdown("
    1. Run:

      abs doctor\n
    2. Done.
    "); + assert.match(code, /Run:\n\n {3}```\n {3}abs doctor/); +}); diff --git a/yarn.lock b/yarn.lock index 3e8e641a..ececa4f5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2223,7 +2223,7 @@ lodash "^4.17.21" tslib "^2.6.0" -"@docusaurus/utils@3.10.2": +"@docusaurus/utils@3.10.2", "@docusaurus/utils@^3.10.2": version "3.10.2" resolved "https://registry.yarnpkg.com/@docusaurus/utils/-/utils-3.10.2.tgz#d99c1ffc5c7961e912344269a8728ce2aad8b3dc" integrity sha512-xx0W3eav2uW1NRIpuHJWNwLTC15xPNjU4Uxi9NSnd3swYC96BE3vFiT93SD8s24kmAAWNwgZwfZ2fghGZ01Lcw== From eccd010ab662584fd334336bd235173810c73dd7 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 12:20:56 +0000 Subject: [PATCH 09/43] fix(llms): API index under 50k, robust llms-full page splitting - API index entries drop "Required permissions: ..." (ruling R6); they stay on each endpoint page. Index is now 46,229 chars (was 60,620). - llms-full.txt pages are recognised by matching their known .md content instead of guessing from the first line, so pages without a pointer (e.g. the Web Console API overview, which starts with "Version:") are kept; unknown content throws. - An over-long first sentence is cut at a clause boundary (or the title is used) instead of describing the page with a later paragraph. - markdownReader returns null on malformed percent-encoding. - Build checks: API index (and any sub-index) < 50,000 chars; both API overview pages present in llms-full.txt. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- plugins/build-checks.test.js | 15 ++ plugins/llms-markdown/postprocess-llms.js | 158 +++++++++++------- .../llms-markdown/postprocess-llms.test.js | 107 ++++++++---- 3 files changed, 185 insertions(+), 95 deletions(-) diff --git a/plugins/build-checks.test.js b/plugins/build-checks.test.js index b23becf2..b8e5a685 100644 --- a/plugins/build-checks.test.js +++ b/plugins/build-checks.test.js @@ -46,10 +46,25 @@ buildTest("the Web Console API index lists every endpoint", () => { for (const line of endpoints) assert.match(line, /\): (GET|PUT|POST|DELETE|PATCH|HEAD|OPTIONS) \//); }); +buildTest("the Web Console API index and any sub-index are under 50,000 characters", () => { + const dir = path.join(buildDir, path.dirname(API_INDEX)); + const indexes = fs.readdirSync(dir, { recursive: true }).filter((f) => String(f).endsWith("llms.txt")); + assert.ok(indexes.length >= 1); + for (const f of indexes) { + const size = fs.readFileSync(path.join(dir, String(f)), "utf8").length; + assert.ok(size < 50000, `${f} is ${size} chars`); + } +}); + buildTest("llms-full.txt excludes Web Console endpoint pages but keeps Collector ones", () => { const full = read("llms-full.txt"); assert.ok(!full.includes(`Markdown at <${WC_URL}`), "Web Console section left in llms-full.txt"); assert.ok(full.includes("SDK-API/collector-health-check.md")); + // Pages without a pointer line are kept, including the Web Console API overview. + const overview = read("docs/APIs-and-SDKs/Web-Console-API/absmartly-web-console-api.md"); + const collectorOverview = read("docs/APIs-and-SDKs/SDK-API/absmartly-collector-api.md"); + assert.ok(full.includes(`${overview}\n\n---\n\n`), "Web Console API overview page missing"); + assert.ok(full.includes(`${collectorOverview}\n\n---\n\n`), "Collector API overview page missing"); assert.ok(full.includes(`${WC_URL}llms.txt`), "note pointing to the API index"); }); diff --git a/plugins/llms-markdown/postprocess-llms.js b/plugins/llms-markdown/postprocess-llms.js index af837bc6..3713fcb0 100644 --- a/plugins/llms-markdown/postprocess-llms.js +++ b/plugins/llms-markdown/postprocess-llms.js @@ -59,27 +59,39 @@ function unterminatedSentence(rest) { return null; } -// Drops " — … — " asides from a sentence that is too long to use whole. +const MIN_CLAUSE = 40; + +// Fits a sentence into MAX_DESCRIPTION: drops " — … — " asides, then cuts at +// the last clause boundary (", ", "; " or " — ") that fits, ending with ".". +// Returns { text, cut } (cut: ended at a clause), or null when there is no +// usable boundary. function shorten(sentence) { - if (sentence.length <= MAX_DESCRIPTION) return sentence; - return sentence.replace(/ — [^—]+? — /g, " "); + if (sentence.length <= MAX_DESCRIPTION) return { text: sentence, cut: false }; + const withoutAsides = sentence.replace(/ — [^—]+? — /g, " "); + if (withoutAsides.length <= MAX_DESCRIPTION) return { text: withoutAsides, cut: false }; + const head = withoutAsides.slice(0, MAX_DESCRIPTION); + let at = -1; + for (const m of head.matchAll(/(?:[,;]| —) /g)) at = m.index; + return at >= MIN_CLAUSE ? { text: `${withoutAsides.slice(0, at)}.`, cut: true } : null; } // Up to two sentences from the start of `prose`, at most MAX_DESCRIPTION chars. +// Returns undefined when the paragraph has no sentence (the caller tries the +// next one) and null when its first sentence cannot be shortened (the caller +// falls back to the title rather than describing the page with a later, +// possibly unrelated, paragraph). function leadingSentences(prose) { const split = splitSentences(prose); let sentences = split.sentences; if (!sentences.length) { const lone = unterminatedSentence(split.rest); - sentences = lone ? [lone] : []; - } - let out = ""; - for (const s of sentences.slice(0, 2).map(shorten)) { - const next = out ? `${out} ${s}` : s; - if (next.length > MAX_DESCRIPTION) break; - out = next; + if (!lone) return undefined; + sentences = [lone]; } - return out || null; + const first = shorten(sentences[0]); + if (!first) return null; + const two = `${first.text} ${sentences[1]}`; + return sentences[1] && !first.cut && two.length <= MAX_DESCRIPTION ? two : first.text; } // --- page Markdown ----------------------------------------------------------- @@ -143,7 +155,7 @@ function proseParagraphs(markdown) { function extractDescription(markdown) { for (const paragraph of proseParagraphs(markdown)) { const sentences = leadingSentences(paragraph); - if (sentences) return sentences; + if (sentences !== undefined) return sentences; } return null; } @@ -172,19 +184,14 @@ function isTruncated(description, markdown) { const PERMISSIONS = /\*\*Required Permissions\*\*:([^\n]*)/; -// "METHOD /path. . Required permissions: A or B." +// "METHOD /path. ." Permissions are left to the endpoint +// page (ruling R6: they pushed the API index over 50,000 characters). function apiDescriptionFor(operation) { - let text = (operation.description || "").replace(/^:::[^\n]*\n[\s\S]*?^:::[ \t]*$/gm, ""); + const text = (operation.description || "") + .replace(/^:::[^\n]*\n[\s\S]*?^:::[ \t]*$/gm, "") + .replace(PERMISSIONS, ""); const parts = [`${operation.method} ${operation.path}.`]; - let permissions = null; - const m = text.match(PERMISSIONS); - if (m) { - const { sentences, rest } = splitSentences(m[1].trim()); - permissions = plainInline(sentences[0] || rest).replace(/`/g, "").replace(/\.$/, ""); - text = text.replace(PERMISSIONS, ""); - } - const firstParagraph = markdownBlocks(text).find((b) => b.kind === "paragraph"); if (firstParagraph) { const prose = plainInline(firstParagraph.text); @@ -192,7 +199,6 @@ function apiDescriptionFor(operation) { const sentence = sentences[0] || (rest ? `${rest.replace(/[:;,]$/, "")}.` : null); if (sentence && sentence.length <= MAX_DESCRIPTION) parts.push(sentence); } - if (permissions) parts.push(`Required permissions: ${permissions}.`); return parts.join(" "); } @@ -273,13 +279,6 @@ function rewriteLlmsTxt(llmsTxt, { readMd, apiDescription, apiIndexUrl, startHer // --- llms-full.txt ---------------------------------------------------------------- -const POINTER = /^> For AI agents: this page is available as Markdown at \s]+?)>?\. /; - -function isWebConsoleApiSection(sectionText) { - const m = sectionText.match(POINTER); - return Boolean(m && m[1].startsWith(WEB_CONSOLE_API_URL)); -} - // Inserts `note` as its own paragraph after the header's H1 description blockquote. function addNote(header, note) { const lines = header.trimEnd().split("\n"); @@ -290,29 +289,45 @@ function addNote(header, note) { return `${lines.join("\n")}\n`; } -// Page sections are joined by "\n\n---\n\n"; a page may contain a horizontal -// rule of its own, so a chunk that doesn't start a page (pointer line or H1) -// belongs to the previous page. -function rewriteLlmsFull(full, { isApiPage, note, header }) { - const chunks = full.split(SECTION_SEPARATOR); - const out = [addNote(header ?? chunks[0], note)]; - let dropping = false; - for (let i = 1; i < chunks.length; i++) { - let chunk = chunks[i]; - let prefix = ""; - if (chunk.startsWith(FULL_CONTENT_HEADING)) { - prefix = FULL_CONTENT_HEADING; - chunk = chunk.slice(prefix.length); - } - const startsPage = POINTER.test(chunk) || /^# /.test(chunk); - if (startsPage) dropping = isApiPage(chunk); - if (dropping) { - if (prefix) out.push(prefix.trimEnd()); - continue; +// The inner plugin writes llms-full.txt as: the llms.txt content, then +// "\n\n---\n\n# Full Documentation Content\n\n", then each page's .md file +// verbatim followed by "\n\n---\n\n". Pages are recognised by matching their +// known .md content at each position (`pages`: Map<.md URL, Markdown>), not by +// guessing from their first line; pages may contain "---" rules of their own. +// Pages for which isApiPage(url) is true are dropped; every other page is kept. +// Content that matches no known page throws rather than being guessed at. +function rewriteLlmsFull(full, { pages, isApiPage, note, header }) { + const marker = `${SECTION_SEPARATOR}${FULL_CONTENT_HEADING}`; + const at = full.indexOf(marker); + if (at < 0) throw new Error("llms-full.txt: no Full Documentation Content section"); + const body = full.slice(at + marker.length); + + // Candidates by their first characters, longest content first. + const PREFIX = 32; + const byPrefix = new Map(); + for (const [url, markdown] of pages) { + if (!markdown) continue; + const key = markdown.slice(0, PREFIX); + if (!byPrefix.has(key)) byPrefix.set(key, []); + byPrefix.get(key).push({ url, section: `${markdown}${SECTION_SEPARATOR}` }); + } + for (const list of byPrefix.values()) list.sort((a, b) => b.section.length - a.section.length); + + const kept = []; + let pos = 0; + while (pos < body.length) { + const candidates = [...byPrefix.entries()] + .filter(([key]) => body.startsWith(key, pos)) + .flatMap(([, list]) => list); + const page = candidates.find((c) => body.startsWith(c.section, pos)); + if (!page) { + throw new Error(`llms-full.txt: no known page at offset ${pos}: ${JSON.stringify(body.slice(pos, pos + 80))}`); } - out.push(prefix + chunk); + if (!isApiPage(page.url)) kept.push(page.section); + pos += page.section.length; } - return out.join(SECTION_SEPARATOR); + + return `${addNote(header ?? full.slice(0, at), note)}${marker}${kept.join("")}`; } // --- build ------------------------------------------------------------------- @@ -320,18 +335,33 @@ function rewriteLlmsFull(full, { isApiPage, note, header }) { function markdownReader(outDir) { return (url) => { if (!url.startsWith(`${SITE_URL}/`) || !url.endsWith(".md")) return null; - const file = path.join(outDir, decodeURI(url.slice(SITE_URL.length + 1))); + let relative; + try { + relative = decodeURI(url.slice(SITE_URL.length + 1)); + } catch (err) { + if (err instanceof URIError) return null; + throw err; + } + const file = path.join(outDir, relative); return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null; }; } -function apiDescriber() { +function operationsByMarkdownUrl() { const byMarkdownUrl = new Map(); for (const entry of getLoadedIndex().values()) byMarkdownUrl.set(`${entry.pageUrl}.md`, entry); - return (url) => { - const entry = byMarkdownUrl.get(url); - return entry ? apiDescriptionFor(entry) : null; - }; + return byMarkdownUrl; +} + +// .md URL -> Markdown for every page entry of the (original) llms.txt. +function pagesOf(llmsTxt, readMd) { + const pages = new Map(); + for (const line of llmsTxt.split("\n")) { + const m = line.match(ENTRY); + const markdown = m && readMd(m[2]); + if (markdown) pages.set(m[2], markdown); + } + return pages; } async function postProcessLlms(outDir, options) { @@ -340,9 +370,12 @@ async function postProcessLlms(outDir, options) { const llmsTxtPath = path.join(outDir, "llms.txt"); const fullPath = path.join(outDir, "llms-full.txt"); - const { main, apiIndex } = rewriteLlmsTxt(fs.readFileSync(llmsTxtPath, "utf8"), { - readMd: markdownReader(outDir), - apiDescription: apiDescriber(), + const readMd = markdownReader(outDir); + const operations = operationsByMarkdownUrl(); + const llmsTxt = fs.readFileSync(llmsTxtPath, "utf8"); + const { main, apiIndex } = rewriteLlmsTxt(llmsTxt, { + readMd, + apiDescription: (url) => (operations.has(url) ? apiDescriptionFor(operations.get(url)) : null), apiIndexUrl: `${SITE_URL}/${API_INDEX_PATH}`, startHere, apiIndexHeader, @@ -353,7 +386,8 @@ async function postProcessLlms(outDir, options) { if (fs.existsSync(fullPath)) { const full = rewriteLlmsFull(fs.readFileSync(fullPath, "utf8"), { - isApiPage: isWebConsoleApiSection, + pages: pagesOf(llmsTxt, readMd), + isApiPage: (url) => operations.get(url)?.specKey === "webConsole", note: fullNote, header: main, }); @@ -367,7 +401,7 @@ module.exports = { apiDescriptionFor, rewriteLlmsTxt, rewriteLlmsFull, - isWebConsoleApiSection, + markdownReader, postProcessLlms, API_INDEX_PATH, }; diff --git a/plugins/llms-markdown/postprocess-llms.test.js b/plugins/llms-markdown/postprocess-llms.test.js index e8380443..f25ebcbc 100644 --- a/plugins/llms-markdown/postprocess-llms.test.js +++ b/plugins/llms-markdown/postprocess-llms.test.js @@ -6,7 +6,7 @@ const { rewriteLlmsTxt, rewriteLlmsFull, apiDescriptionFor, - isWebConsoleApiSection, + markdownReader, } = require("./postprocess-llms"); const SITE = "https://docs.absmartly.com"; @@ -82,13 +82,21 @@ test("extractDescription returns null for a page with only a table and code", () assert.strictEqual(extractDescription(md), null); }); -test("extractDescription does not split on e.g. and ignores sentences over 200 chars", () => { +test("extractDescription does not split on e.g.", () => { assert.strictEqual( extractDescription("# T\n\nUse a key (e.g. Settings → API Keys) for this. Done."), "Use a key (e.g. Settings → API Keys) for this. Done.", ); - const long = `${"word ".repeat(50).trim()}.`; - assert.strictEqual(extractDescription(`# T\n\n${long}\n\nShort one.`), "Short one."); +}); + +test("an over-long first sentence is cut at a clause boundary, never replaced by a later paragraph", () => { + const clause = "This release marks the start of the data retention rollout for every workspace on the platform"; + const long = `${clause}, ${"and it also changes many other things across reports ".repeat(3).trim()}.`; + assert.ok(long.length > 200); + assert.strictEqual(extractDescription(`# T\n\n${long}\n\nShort one.`), `${clause}.`); + // No clause boundary to cut at: the caller falls back to the title. + const unbroken = `${"word ".repeat(50).trim()}.`; + assert.strictEqual(extractDescription(`# T\n\n${unbroken}\n\nShort one.`), null); }); test("extractDescription joins hard-wrapped lines of a paragraph", () => { @@ -145,7 +153,7 @@ test("extractDescription accepts an unpunctuated sentence-length paragraph, not // --- apiDescriptionFor ---------------------------------------------------------- -test("apiDescriptionFor uses the endpoint, a prose sentence and plain-text permissions", () => { +test("apiDescriptionFor is the endpoint and a prose sentence, without permissions (ruling R6)", () => { assert.strictEqual( apiDescriptionFor({ method: "PUT", @@ -153,7 +161,7 @@ test("apiDescriptionFor uses the endpoint, a prose sentence and plain-text permi summary: "Start Experiment in Development [UPDATE]", description: "**Required Permissions**: `Experiment Development` or `Experiment Admin`", }), - "PUT /experiments/{experimentId}/development. Required permissions: Experiment Development or Experiment Admin.", + "PUT /experiments/{experimentId}/development.", ); assert.strictEqual( apiDescriptionFor({ @@ -161,18 +169,18 @@ test("apiDescriptionFor uses the endpoint, a prose sentence and plain-text permi path: "/datasources/{datasourceId}/json_layouts/recreate", description: "Drops and recreates the json_layouts table. Destructive.\n**Required Permissions**: `EventDatasourceConfig Edit`", }), - "POST /datasources/{datasourceId}/json_layouts/recreate. Drops and recreates the json_layouts table. Required permissions: EventDatasourceConfig Edit.", + "POST /datasources/{datasourceId}/json_layouts/recreate. Drops and recreates the json_layouts table.", ); }); -test("apiDescriptionFor drops admonitions and permission detail, keeps unterminated prose", () => { +test("apiDescriptionFor drops admonitions and permission text, keeps unterminated prose", () => { const d = apiDescriptionFor({ method: "PUT", path: "/goals/{goalId}", description: "**Required Permissions**: `Goal Edit` or `Goal Admin`\n\n:::caution\nOnly fields provided will be updated.\n:::\n", }); - assert.strictEqual(d, "PUT /goals/{goalId}. Required permissions: Goal Edit or Goal Admin."); + assert.strictEqual(d, "PUT /goals/{goalId}."); assert.ok(!d.includes(":::") && !d.includes("**")); assert.strictEqual( apiDescriptionFor({ @@ -181,7 +189,7 @@ test("apiDescriptionFor drops admonitions and permission detail, keeps untermina description: "**Required Permissions**: `Experiment Admin` and (`Experiment Create` or `Experiment CreateFromTemplate`). Importing a feature requires more.\n\nImports an experiment.", }), - "POST /experiments/import. Imports an experiment. Required permissions: Experiment Admin and (Experiment Create or Experiment CreateFromTemplate).", + "POST /experiments/import. Imports an experiment.", ); assert.strictEqual( apiDescriptionFor({ method: "GET", path: "/notifications/summary", description: "Get user notifications with counts and pagination" }), @@ -189,16 +197,16 @@ test("apiDescriptionFor drops admonitions and permission detail, keeps untermina ); assert.strictEqual( apiDescriptionFor({ method: "GET", path: "/events/quota", description: "Get monthly events quota. **Required Permissions**: `List`" }), - "GET /events/quota. Get monthly events quota. Required permissions: List.", + "GET /events/quota. Get monthly events quota.", ); assert.strictEqual(apiDescriptionFor({ method: "GET", path: "/x" }), "GET /x."); assert.strictEqual( apiDescriptionFor({ method: "PUT", path: "/goals/{goalId}/archive", description: "**Required Permissions**: `Goal Archive` or `Goal Admin` :::\n" }), - "PUT /goals/{goalId}/archive. Required permissions: Goal Archive or Goal Admin.", + "PUT /goals/{goalId}/archive.", ); assert.strictEqual( apiDescriptionFor({ method: "HEAD", path: "/files/{id}", description: "**Required Permissions**: Access to the file based on its usage type." }), - "HEAD /files/{id}. Required permissions: Access to the file based on its usage type.", + "HEAD /files/{id}.", ); }); @@ -250,9 +258,9 @@ const MDS = { const API = { [`${WC}/003-set-experiment-to-development.md`]: - "PUT /experiments/{experimentId}/development. Required permissions: Experiment Development or Experiment Admin.", + "PUT /experiments/{experimentId}/development.", [`${WC}/0100-000-list-experiments.md`]: - "GET /experiments. Required permissions: Experiment List or Experiment Admin.", + "GET /experiments.", [`${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check.md`]: "GET /healthy. A GET request to check that the service is running as expected.", }; @@ -320,7 +328,7 @@ test("rewriteLlmsTxt moves Web Console entries to the API index and links it onc assert.match(apiIndex, /\n## Endpoints\n\n- \[Set experiment to development\]/); assert.match( entryLine(apiIndex, "List experiments"), - /\): GET \/experiments\. Required permissions: Experiment List or Experiment Admin\.$/, + /\): GET \/experiments\.$/, ); assert.match( entryLine(apiIndex, "ABsmartly Web Console API"), @@ -340,25 +348,43 @@ test("rewriteLlmsTxt inserts the Start here block before the first section", () // --- rewriteLlmsFull ---------------------------------------------------------------- -const FULL = [ - "# The ABsmartly Docs\n\n> Old description.\n\n## docs\n\n- [x](y): z\n", - `# Full Documentation Content\n\n# ABsmartly CLI\n\nCLI body.`, - `${pointer(`${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check`)}\n\n# Check Service Health\n\nCollector body.`, - `${pointer(`${WC}/archive-goal`)}\n\n# Archive goal\n\nWeb Console body.`, - "Continuation of the Web Console page after a horizontal rule.", - "# Glossary\n\nGlossary body.", - "Glossary continuation.", -].join("\n\n---\n\n"); - -test("rewriteLlmsFull drops Web Console sections and keeps Collector and guide ones", () => { - const out = rewriteLlmsFull(FULL, { - isApiPage: isWebConsoleApiSection, +// The inner plugin writes: llms.txt, then "\n\n---\n\n# Full Documentation Content\n\n", +// then each page's .md content followed by "\n\n---\n\n". +const PAGES = new Map([ + [`${SITE}/docs/cli.md`, "# ABsmartly CLI\n\nCLI body."], + [ + `${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check.md`, + `${pointer(`${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check`)}\n\n# Check Service Health\n\nCollector body.`, + ], + [ + `${WC}/archive-goal.md`, + `${pointer(`${WC}/archive-goal`)}\n\n# Archive goal\n\nWeb Console body.\n\n---\n\nContinuation of the Web Console page after a horizontal rule.`, + ], + [`${WC}/absmartly-web-console-api.md`, "Version: 1.0.0\n\n# ABsmartly Web Console API\n\nAPI overview body."], + [`${WC}/list-goals.md`, `${pointer(`${WC}/list-goals`)}\n\n# List goals\n\nAnother endpoint body.`], + [`${SITE}/docs/glossary.md`, "# Glossary\n\nGlossary body.\n\n---\n\nGlossary continuation."], +]); +const FULL = + "# The ABsmartly Docs\n\n> Old description.\n\n## docs\n\n- [x](y): z\n" + + "\n\n---\n\n# Full Documentation Content\n\n" + + [...PAGES.values()].map((md) => `${md}\n\n---\n\n`).join(""); +const OPERATION_URLS = new Set([`${WC}/archive-goal.md`, `${WC}/list-goals.md`]); + +function rewriteFull(full = FULL) { + return rewriteLlmsFull(full, { + pages: PAGES, + isApiPage: (url) => OPERATION_URLS.has(url), note: "Web Console API endpoints are not included here.", header: "# The ABsmartly Docs\n\n> New description.\n\n## Start here\n\n- [a](b): c\n", }); +} + +test("rewriteLlmsFull drops Web Console endpoint pages and keeps every other page", () => { + const out = rewriteFull(); assert.ok(out.includes("Collector body.")); assert.ok(!out.includes("Web Console body.")); assert.ok(!out.includes("Continuation of the Web Console page")); + assert.ok(!out.includes("Another endpoint body.")); assert.ok(out.includes("Glossary body.") && out.includes("Glossary continuation.")); assert.ok(out.includes("CLI body.")); assert.ok(out.includes("# Full Documentation Content")); @@ -367,8 +393,23 @@ test("rewriteLlmsFull drops Web Console sections and keeps Collector and guide o assert.ok(!out.includes("---\n\n---")); }); -test("isWebConsoleApiSection only matches the pointer URL under Web-Console-API", () => { - assert.strictEqual(isWebConsoleApiSection(`${pointer(`${WC}/archive-goal`)}\n\n# Archive goal`), true); - assert.strictEqual(isWebConsoleApiSection(`${pointer(`${SITE}/docs/APIs-and-SDKs/SDK-API/x`)}\n\n# X`), false); - assert.strictEqual(isWebConsoleApiSection("# Custom Slack Integration\n\nSee Web-Console-API pages."), false); +test("rewriteLlmsFull keeps a page starting with `Version:` that follows an endpoint page", () => { + const out = rewriteFull(); + assert.ok(out.includes("Version: 1.0.0\n\n# ABsmartly Web Console API\n\nAPI overview body.")); + assert.match(out, /Collector body\.\n\n---\n\nVersion: 1\.0\.0/); +}); + +test("rewriteLlmsFull throws on content that matches no known page", () => { + assert.throws( + () => rewriteFull(FULL.replace("Glossary body.", "Changed body.")), + /llms-full\.txt: no known page at .*# Glossary/, + ); +}); + +// --- markdownReader ----------------------------------------------------------------- + +test("markdownReader returns null for a malformed percent-encoded URL", () => { + const read = markdownReader(__dirname); + assert.strictEqual(read(`${SITE}/docs/bad%E0%A4%A.md`), null); + assert.strictEqual(read(`${SITE}/openapi/web-console-api.yaml`), null); }); From e16d47720af314aec0765fc719bc82062e5904e4 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 12:25:48 +0000 Subject: [PATCH 10/43] feat(theme): add agent pointer to llms.txt and page Markdown Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- .../markdown-negotiation.test.js | 4 +- plugins/build-checks.test.js | 40 +++++++++++++++- plugins/llms-markdown/pointer.js | 22 +++++++-- .../rehype-docusaurus-cleanup.js | 5 ++ src/components/AgentPointer/index.js | 23 +++++++++ src/components/AgentPointer/styles.module.css | 13 +++++ src/theme/DocItem/Content/index.js | 47 +++++++++++++++++++ src/theme/DocItem/Metadata/index.js | 3 +- src/utils/markdownUrl.js | 11 +++++ 9 files changed, 160 insertions(+), 8 deletions(-) create mode 100644 src/components/AgentPointer/index.js create mode 100644 src/components/AgentPointer/styles.module.css create mode 100644 src/theme/DocItem/Content/index.js create mode 100644 src/utils/markdownUrl.js diff --git a/netlify/edge-functions-tests/markdown-negotiation.test.js b/netlify/edge-functions-tests/markdown-negotiation.test.js index 4f48758d..7f55e8d8 100644 --- a/netlify/edge-functions-tests/markdown-negotiation.test.js +++ b/netlify/edge-functions-tests/markdown-negotiation.test.js @@ -85,7 +85,7 @@ const PAGE = "/docs/APIs-and-SDKs/SDK-Documentation/getting-started/"; Deno.test("negotiation: agent gets Markdown, browser gets HTML", async () => { let r = await call(PAGE, "text/markdown"); eq(r.headers.get("content-type").startsWith("text/markdown"), true); - eq((await r.text()).startsWith("# Getting Started"), true); + eq((await r.text()).includes("\n# Getting Started"), true); eq(r.headers.get("vary"), "Accept"); r = await call(PAGE, "text/html,*/*;q=0.8"); @@ -129,7 +129,7 @@ Deno.test("negotiated Markdown drops upstream encoding/length headers", async () const r = await call(PAGE, "text/markdown"); eq(r.headers.get("content-encoding"), null); eq(r.headers.get("content-length"), null); - eq((await r.text()).startsWith("# Getting Started"), true); + eq((await r.text()).includes("\n# Getting Started"), true); } finally { globalThis.fetch = (u) => serve(new URL(u).pathname); } diff --git a/plugins/build-checks.test.js b/plugins/build-checks.test.js index b8e5a685..10d2568d 100644 --- a/plugins/build-checks.test.js +++ b/plugins/build-checks.test.js @@ -58,7 +58,10 @@ buildTest("the Web Console API index and any sub-index are under 50,000 characte buildTest("llms-full.txt excludes Web Console endpoint pages but keeps Collector ones", () => { const full = read("llms-full.txt"); - assert.ok(!full.includes(`Markdown at <${WC_URL}`), "Web Console section left in llms-full.txt"); + // Pages that keep a pointer line: the overview and the hand-written examples, never endpoint pages. + const wcPages = [...full.matchAll(/Markdown at <(https:[^>]*Web-Console-API\/[^>]*)\.md>/g)].map((m) => m[1]); + const endpointPages = wcPages.filter((u) => !u.endsWith("/absmartly-web-console-api") && !u.includes("/examples/")); + assert.deepStrictEqual(endpointPages, [], "Web Console endpoint pages left in llms-full.txt"); assert.ok(full.includes("SDK-API/collector-health-check.md")); // Pages without a pointer line are kept, including the Web Console API overview. const overview = read("docs/APIs-and-SDKs/Web-Console-API/absmartly-web-console-api.md"); @@ -79,3 +82,38 @@ buildTest("every generated .md page is under 50,000 characters", () => { assert.ok(size < 50000, `${path.relative(buildDir, file)} is ${size} chars`); } }); + +const { pointerLine } = require("./llms-markdown/pointer"); +const SITE = "https://docs.absmartly.com"; + +buildTest("page Markdown starts with the agent pointer line (before the H1) and the HTML carries it", () => { + const md = read("docs/glossary.md"); + const lines = md.split("\n"); + assert.match(lines[2], /^# /); + // Markdown conversion renders bare URLs as autolinks. + const autolinked = pointerLine(`${SITE}/docs/glossary`).replace(/https:[^ ]*?(\.md|\.txt)/g, "<$&>"); + assert.strictEqual(lines[0], autolinked); + assert.strictEqual(md.split("For AI agents:").length - 1, 1); + const html = read("docs/glossary/index.html"); + assert.ok(html.includes("For AI agents: this page is available as Markdown at")); + assert.ok(html.includes(`${SITE}/docs/glossary.md`) && html.includes(`${SITE}/llms.txt`)); + assert.ok(!/]*>For AI agents/.test(html), "pointer must not be a

    (Algolia)"); +}); + +buildTest("the SSO page pointer URL equals the URL llms.txt lists for it", () => { + const rel = "docs/Third-party-integrations/SSO/Okta SAML Setup.md"; + const listed = read("llms.txt").match(/\[SAML SSO - Okta\]\((https:[^)]*)\)/); + assert.ok(listed, "Okta page listed in llms.txt"); + assert.ok(read(rel).split("\n")[0].includes(listed[1])); +}); + +buildTest("an API endpoint .md has exactly one pointer line", () => { + const md = read("docs/APIs-and-SDKs/SDK-API/collector-health-check.md"); + assert.strictEqual(md.split("For AI agents:").length - 1, 1); +}); + +buildTest("llms.txt descriptions never start with the pointer", () => { + for (const file of ["llms.txt", API_INDEX]) { + assert.ok(!/: For AI agents/.test(read(file)), file); + } +}); diff --git a/plugins/llms-markdown/pointer.js b/plugins/llms-markdown/pointer.js index 43977292..fcd03ab1 100644 --- a/plugins/llms-markdown/pointer.js +++ b/plugins/llms-markdown/pointer.js @@ -1,8 +1,22 @@ -const LLMS_TXT_URL = "https://docs.absmartly.com/llms.txt"; +const SITE_URL = "https://docs.absmartly.com"; +const LLMS_TXT_URL = `${SITE_URL}/llms.txt`; + +// The pointer sentence as segments, shared by the Markdown line below and the +// React component (which renders the two URLs as links), so the wording lives +// in one place. `pageUrl` is the page's absolute URL without a trailing slash. +function pointerParts(pageUrl) { + return { + before: "For AI agents: this page is available as Markdown at ", + markdownUrl: `${pageUrl}.md`, + between: ". The full documentation index is at ", + llmsUrl: LLMS_TXT_URL, + after: ".", + }; +} -// `pageUrl` is the page's absolute URL without a trailing slash. function pointerLine(pageUrl) { - return `> For AI agents: this page is available as Markdown at ${pageUrl}.md. The full documentation index is at ${LLMS_TXT_URL}.`; + const p = pointerParts(pageUrl); + return `> ${p.before}${p.markdownUrl}${p.between}${p.llmsUrl}${p.after}`; } -module.exports = { pointerLine, LLMS_TXT_URL }; +module.exports = { pointerLine, pointerParts, LLMS_TXT_URL, SITE_URL }; diff --git a/plugins/llms-markdown/rehype-docusaurus-cleanup.js b/plugins/llms-markdown/rehype-docusaurus-cleanup.js index 923ba5aa..0ccab69d 100644 --- a/plugins/llms-markdown/rehype-docusaurus-cleanup.js +++ b/plugins/llms-markdown/rehype-docusaurus-cleanup.js @@ -115,6 +115,11 @@ function transform(node) { if (hasClass(child, "hash-link") || child.tagName === "svg") continue; let replacement = null; + // Visually hidden agent pointer (a div, so Algolia skips it) -> blockquote line. + if (hasClass(child, "agent-pointer")) { + next.push(el("blockquote", {}, [el("p", {}, child.children)])); + continue; + } if (hasClass(child, "theme-code-block")) replacement = convertCodeBlock(child); else if (hasClass(child, "tabs-container")) replacement = convertTabs(child); else if (hasClass(child, "theme-admonition")) replacement = convertAdmonition(child); diff --git a/src/components/AgentPointer/index.js b/src/components/AgentPointer/index.js new file mode 100644 index 00000000..2582900c --- /dev/null +++ b/src/components/AgentPointer/index.js @@ -0,0 +1,23 @@ +import React from "react"; +import { useDoc } from "@docusaurus/plugin-content-docs/client"; +import { pointerParts } from "../../../plugins/llms-markdown/pointer"; +import { pageUrlFor } from "../../utils/markdownUrl"; +import styles from "./styles.module.css"; + +// Visually hidden line that points HTML-reading agents at the page's Markdown +// version and the llms.txt index. A div (not a p) so Algolia does not index it. +// The `agent-pointer` class is the hook rehype-docusaurus-cleanup uses to turn +// it into the Markdown pointer blockquote. +export default function AgentPointer() { + const { metadata } = useDoc(); + const p = pointerParts(pageUrlFor(metadata.permalink)); + return ( +

    + {p.before} + {p.markdownUrl} + {p.between} + {p.llmsUrl} + {p.after} +
    + ); +} diff --git a/src/components/AgentPointer/styles.module.css b/src/components/AgentPointer/styles.module.css new file mode 100644 index 00000000..70389182 --- /dev/null +++ b/src/components/AgentPointer/styles.module.css @@ -0,0 +1,13 @@ +/* Standard visually-hidden pattern: stays in the DOM and accessibility tree, + takes no space and cannot cause layout shift. */ +.srOnly { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} diff --git a/src/theme/DocItem/Content/index.js b/src/theme/DocItem/Content/index.js new file mode 100644 index 00000000..64ad8ea7 --- /dev/null +++ b/src/theme/DocItem/Content/index.js @@ -0,0 +1,47 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import React from 'react'; +import clsx from 'clsx'; +import {ThemeClassNames} from '@docusaurus/theme-common'; +import {useDoc} from '@docusaurus/plugin-content-docs/client'; +import Heading from '@theme/Heading'; +import MDXContent from '@theme/MDXContent'; +// Ejected from @docusaurus/theme-classic: the only change is . +import AgentPointer from '@site/src/components/AgentPointer'; +/** + Title can be declared inside md content or declared through + front matter and added manually. To make both cases consistent, + the added title is added under the same div.markdown block + See https://github.com/facebook/docusaurus/pull/4882#issuecomment-853021120 + + We render a "synthetic title" if: + - user doesn't ask to hide it with front matter + - the markdown content does not already contain a top-level h1 heading +*/ +function useSyntheticTitle() { + const {metadata, frontMatter, contentTitle} = useDoc(); + const shouldRender = + !frontMatter.hide_title && typeof contentTitle === 'undefined'; + if (!shouldRender) { + return null; + } + return metadata.title; +} +export default function DocItemContent({children}) { + const syntheticTitle = useSyntheticTitle(); + return ( +
    + + {syntheticTitle && ( +
    + {syntheticTitle} +
    + )} + {children} +
    + ); +} diff --git a/src/theme/DocItem/Metadata/index.js b/src/theme/DocItem/Metadata/index.js index 423712b9..de823fb9 100644 --- a/src/theme/DocItem/Metadata/index.js +++ b/src/theme/DocItem/Metadata/index.js @@ -5,10 +5,11 @@ import React from "react"; import Head from "@docusaurus/Head"; import Metadata from "@theme-original/DocItem/Metadata"; import { useDoc } from "@docusaurus/plugin-content-docs/client"; +import { markdownUrlFor } from "../../../utils/markdownUrl"; export default function MetadataWrapper(props) { const { metadata } = useDoc(); - const mdHref = `${metadata.permalink.replace(/\/+$/, "")}.md`; + const mdHref = markdownUrlFor(metadata.permalink); return ( <> diff --git a/src/utils/markdownUrl.js b/src/utils/markdownUrl.js new file mode 100644 index 00000000..56bf3cc2 --- /dev/null +++ b/src/utils/markdownUrl.js @@ -0,0 +1,11 @@ +import { SITE_URL } from "../../plugins/llms-markdown/pointer"; + +// Absolute URL of a docs page's Markdown version (generated at build time by +// the llms-txt plugin). The permalink's percent-encoding is kept as given. +export function pageUrlFor(permalink) { + return `${SITE_URL}${permalink.replace(/\/+$/, "")}`; +} + +export function markdownUrlFor(permalink) { + return `${pageUrlFor(permalink)}.md`; +} From d77e976abcadc81b9b322a6003a512114a61dc1b Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 12:29:14 +0000 Subject: [PATCH 11/43] feat(theme): add copy page and open-in-assistant menu Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- plugins/build-checks.test.js | 14 +++ .../rehype-docusaurus-cleanup.js | 3 + src/components/AgentPointer/index.js | 4 +- src/components/PageAiActions/index.js | 112 ++++++++++++++++++ .../PageAiActions/styles.module.css | 50 ++++++++ src/theme/DocItem/Content/index.js | 4 +- 6 files changed, 184 insertions(+), 3 deletions(-) create mode 100644 src/components/PageAiActions/index.js create mode 100644 src/components/PageAiActions/styles.module.css diff --git a/plugins/build-checks.test.js b/plugins/build-checks.test.js index 10d2568d..70eacd52 100644 --- a/plugins/build-checks.test.js +++ b/plugins/build-checks.test.js @@ -117,3 +117,17 @@ buildTest("llms.txt descriptions never start with the pointer", () => { assert.ok(!/: For AI agents/.test(read(file)), file); } }); + +buildTest("doc and API pages render the Copy page menu; it stays out of the Markdown", () => { + for (const rel of ["docs/glossary/index.html", "docs/APIs-and-SDKs/SDK-API/collector-health-check/index.html"]) { + const html = read(rel); + assert.ok(html.includes("page-ai-actions"), `${rel}: menu wrapper`); + assert.ok(/]*aria-haspopup="menu"[^>]*aria-expanded="false"/.test(html), `${rel}: trigger`); + assert.ok(html.includes("Copy page"), `${rel}: label`); + assert.ok(!/]*>[^<]*Copy page/.test(html), `${rel}: must not be an li (Algolia)`); + } + for (const rel of ["docs/glossary.md", "docs/APIs-and-SDKs/SDK-API/collector-health-check.md"]) { + const md = read(rel); + assert.ok(!md.includes("Copy page") && !md.includes("Open in Claude"), `${rel}: menu leaked into Markdown`); + } +}); diff --git a/plugins/llms-markdown/rehype-docusaurus-cleanup.js b/plugins/llms-markdown/rehype-docusaurus-cleanup.js index 0ccab69d..fa665403 100644 --- a/plugins/llms-markdown/rehype-docusaurus-cleanup.js +++ b/plugins/llms-markdown/rehype-docusaurus-cleanup.js @@ -114,6 +114,9 @@ function transform(node) { // Drop heading permalink anchors ("Direct link to ...") and icons. if (hasClass(child, "hash-link") || child.tagName === "svg") continue; + // "Copy page" menu is UI only. + if (hasClass(child, "page-ai-actions")) continue; + let replacement = null; // Visually hidden agent pointer (a div, so Algolia skips it) -> blockquote line. if (hasClass(child, "agent-pointer")) { diff --git a/src/components/AgentPointer/index.js b/src/components/AgentPointer/index.js index 2582900c..d842d97f 100644 --- a/src/components/AgentPointer/index.js +++ b/src/components/AgentPointer/index.js @@ -14,9 +14,9 @@ export default function AgentPointer() { return (
    {p.before} - {p.markdownUrl} + {p.markdownUrl} {p.between} - {p.llmsUrl} + {p.llmsUrl} {p.after}
    ); diff --git a/src/components/PageAiActions/index.js b/src/components/PageAiActions/index.js new file mode 100644 index 00000000..cafd2e03 --- /dev/null +++ b/src/components/PageAiActions/index.js @@ -0,0 +1,112 @@ +import React, { useCallback, useEffect, useRef, useState } from "react"; +import clsx from "clsx"; +import { useDoc } from "@docusaurus/plugin-content-docs/client"; +import { markdownUrlFor } from "../../utils/markdownUrl"; +import styles from "./styles.module.css"; + +// "Copy page" dropdown: copies the page's Markdown or opens it in an assistant. +// Built from divs/buttons/anchors (no ul/li) so Algolia's `li` selector skips it; +// the `page-ai-actions` class is the hook rehype-docusaurus-cleanup uses to drop +// it from the Markdown conversion. window/navigator are only used in handlers. +export default function PageAiActions() { + const { metadata } = useDoc(); + const mdUrl = markdownUrlFor(metadata.permalink); + const prompt = encodeURIComponent(`Read ${mdUrl} and help me with questions about it.`); + const [open, setOpen] = useState(false); + const [status, setStatus] = useState("idle"); // idle | copied | failed + const rootRef = useRef(null); + const timer = useRef(null); + + useEffect(() => { + if (!open) return undefined; + const onPointer = (e) => { + if (rootRef.current && !rootRef.current.contains(e.target)) setOpen(false); + }; + const onKey = (e) => { + if (e.key === "Escape") { + setOpen(false); + rootRef.current?.querySelector("button")?.focus(); + } + }; + document.addEventListener("mousedown", onPointer); + document.addEventListener("touchstart", onPointer); + document.addEventListener("keydown", onKey); + return () => { + document.removeEventListener("mousedown", onPointer); + document.removeEventListener("touchstart", onPointer); + document.removeEventListener("keydown", onKey); + }; + }, [open]); + + useEffect(() => () => clearTimeout(timer.current), []); + + const copy = useCallback(async () => { + let next = "copied"; + try { + const res = await fetch(mdUrl); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + await navigator.clipboard.writeText(await res.text()); + } catch (e) { + next = "failed"; + } + setStatus(next); + clearTimeout(timer.current); + if (next === "copied") { + timer.current = setTimeout(() => { + setStatus("idle"); + setOpen(false); + }, 2000); + } + }, [mdUrl]); + + const onMenuKeyDown = (e) => { + if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return; + e.preventDefault(); + const items = [...rootRef.current.querySelectorAll('[role="menuitem"]')]; + const i = items.indexOf(document.activeElement); + const d = e.key === "ArrowDown" ? 1 : -1; + items[(i + d + items.length) % items.length]?.focus(); + }; + + const itemClass = clsx("dropdown__link", styles.item); + const ext = { target: "_blank", rel: "noopener noreferrer", role: "menuitem", className: itemClass }; + + return ( +
    + +
    + + {status === "failed" && ( +
    + Copy the link instead: {mdUrl} +
    + )} + + View as Markdown + + + Open in Claude + + + Open in ChatGPT + +
    +
    + ); +} diff --git a/src/components/PageAiActions/styles.module.css b/src/components/PageAiActions/styles.module.css new file mode 100644 index 00000000..452b8eb5 --- /dev/null +++ b/src/components/PageAiActions/styles.module.css @@ -0,0 +1,50 @@ +/* Top-right of the content, beside the title on desktop; own line on mobile. */ +.root { + float: right; + margin: 0 0 0.5rem 1rem; +} + +.trigger { + display: inline-flex; + align-items: center; + gap: 0.4rem; +} + +.caret { + flex: none; +} + +.menu { + right: 0; + left: auto; + min-width: 14rem; +} + +.item { + display: block; + width: 100%; + margin: 0; + background: none; + border: 0; + font: inherit; + text-align: left; + cursor: pointer; +} + +.note { + padding: 0.25rem 0.75rem; + font-size: 0.8rem; + overflow-wrap: anywhere; +} + +@media (max-width: 996px) { + .root { + float: none; + margin: 0 0 1rem; + } + + .menu { + left: 0; + right: auto; + } +} diff --git a/src/theme/DocItem/Content/index.js b/src/theme/DocItem/Content/index.js index 64ad8ea7..29650752 100644 --- a/src/theme/DocItem/Content/index.js +++ b/src/theme/DocItem/Content/index.js @@ -10,8 +10,9 @@ import {ThemeClassNames} from '@docusaurus/theme-common'; import {useDoc} from '@docusaurus/plugin-content-docs/client'; import Heading from '@theme/Heading'; import MDXContent from '@theme/MDXContent'; -// Ejected from @docusaurus/theme-classic: the only change is . +// Ejected from @docusaurus/theme-classic: the only changes are and . import AgentPointer from '@site/src/components/AgentPointer'; +import PageAiActions from '@site/src/components/PageAiActions'; /** Title can be declared inside md content or declared through front matter and added manually. To make both cases consistent, @@ -36,6 +37,7 @@ export default function DocItemContent({children}) { return (
    + {syntheticTitle && (
    {syntheticTitle} From 12af826655e68e208a3934955223b95280a40b72 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 12:31:49 +0000 Subject: [PATCH 12/43] fix(theme): place copy menu on API pages, same-origin copy, themed trigger, click-only Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- src/components/PageAiActions/index.js | 18 +++++++---- .../PageAiActions/styles.module.css | 31 +++++++++++++++++++ 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/src/components/PageAiActions/index.js b/src/components/PageAiActions/index.js index cafd2e03..86f95588 100644 --- a/src/components/PageAiActions/index.js +++ b/src/components/PageAiActions/index.js @@ -9,7 +9,10 @@ import styles from "./styles.module.css"; // the `page-ai-actions` class is the hook rehype-docusaurus-cleanup uses to drop // it from the Markdown conversion. window/navigator are only used in handlers. export default function PageAiActions() { - const { metadata } = useDoc(); + const { metadata, frontMatter } = useDoc(); + // API endpoint pages span the content column and the API explorer, so a right + // float would land beyond the explorer: keep the menu above the title instead. + const inline = Boolean(frontMatter.api); const mdUrl = markdownUrlFor(metadata.permalink); const prompt = encodeURIComponent(`Read ${mdUrl} and help me with questions about it.`); const [open, setOpen] = useState(false); @@ -43,7 +46,7 @@ export default function PageAiActions() { const copy = useCallback(async () => { let next = "copied"; try { - const res = await fetch(mdUrl); + const res = await fetch(`${metadata.permalink.replace(/\/+$/, "")}.md`); // same-origin copy if (!res.ok) throw new Error(`HTTP ${res.status}`); await navigator.clipboard.writeText(await res.text()); } catch (e) { @@ -57,7 +60,7 @@ export default function PageAiActions() { setOpen(false); }, 2000); } - }, [mdUrl]); + }, [mdUrl, metadata.permalink]); const onMenuKeyDown = (e) => { if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return; @@ -74,14 +77,17 @@ export default function PageAiActions() { return (
    + , + ); + const trigger = screen.getByRole("button", { name: /Copy page$/ }); + const items = () => screen.getAllByRole("menuitem"); + return { user, trigger, items }; +} + +describe("PageAiActions", () => { + let closeTimer; + after(() => dom.window.close()); + beforeEach(() => stubCopy({ succeeds: true })); + afterEach(() => { + cleanup(); + closeTimer?.restore(); + closeTimer = undefined; + }); + + test("clicking the trigger opens the menu and clicking again closes it", async () => { + const { user, trigger } = renderMenu(); + assert.equal(trigger.getAttribute("aria-expanded"), "false"); + + await user.click(trigger); + assert.equal(trigger.getAttribute("aria-expanded"), "true"); + + await user.click(trigger); + assert.equal(trigger.getAttribute("aria-expanded"), "false"); + }); + + test("Escape closes the menu and returns focus to the trigger", async () => { + const { user, trigger, items } = renderMenu(); + await user.click(trigger); + items()[0].focus(); + + await user.keyboard("{Escape}"); + + assert.equal(trigger.getAttribute("aria-expanded"), "false"); + assert.equal(document.activeElement, trigger); + }); + + for (const key of ["{ArrowDown}", "{Enter}"]) { + test(`${key} on the trigger opens the menu and focuses the first item`, async () => { + const { user, trigger, items } = renderMenu(); + trigger.focus(); + + await user.keyboard(key); + + assert.equal(trigger.getAttribute("aria-expanded"), "true"); + assert.equal(document.activeElement, items()[0]); + }); + } + + test("tabbing out of the menu closes it", async () => { + const { user, trigger, items } = renderMenu(); + trigger.focus(); + await user.keyboard("{ArrowDown}"); + items().at(-1).focus(); + + await user.tab(); + + assert.equal(document.activeElement, screen.getByRole("button", { name: "Outside" })); + assert.equal(trigger.getAttribute("aria-expanded"), "false"); + }); + + test("a successful copy shows Copied", async () => { + const { user, trigger } = renderMenu(); + await user.click(trigger); + + await user.click(screen.getByRole("menuitem", { name: "Copy page as Markdown" })); + + assert.ok(screen.getByRole("menuitem", { name: "Copied" })); + }); + + test("a failed copy offers the link in a live region outside the menu", async () => { + stubCopy({ succeeds: false }); + const { user, trigger } = renderMenu(); + await user.click(trigger); + + await user.click(screen.getByRole("menuitem", { name: "Copy page as Markdown" })); + + assert.ok(screen.getByRole("menuitem", { name: "Couldn't copy" })); + const note = screen.getByRole("status"); + assert.equal(note.closest('[role="menu"]'), null); + assert.equal(note.querySelector("a").getAttribute("href"), "https://docs.example.com/docs/page.md"); + }); + + test("reopening within 2 s of a copy keeps the menu open", async () => { + closeTimer = controlCloseTimer(); + const { user, trigger } = renderMenu(); + await user.click(trigger); + await user.click(screen.getByRole("menuitem", { name: "Copy page as Markdown" })); + + await user.click(trigger); + await user.click(trigger); + closeTimer.fire(); + + assert.equal(trigger.getAttribute("aria-expanded"), "true"); + }); + + test("after a keyboard copy the timer closes the menu with focus back on the trigger", async () => { + closeTimer = controlCloseTimer(); + const { user, trigger, items } = renderMenu(); + trigger.focus(); + await user.keyboard("{ArrowDown}"); + assert.equal(document.activeElement, items()[0]); + + await user.keyboard("{Enter}"); + closeTimer.fire(); + + assert.equal(trigger.getAttribute("aria-expanded"), "false"); + assert.equal(document.activeElement, trigger); + }); +}); diff --git a/src/components/PageAiActions/index.js b/src/components/PageAiActions/index.js index ee179f0a..95e31558 100644 --- a/src/components/PageAiActions/index.js +++ b/src/components/PageAiActions/index.js @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useRef, useState } from "react"; +import React, { useEffect, useRef, useState } from "react"; import clsx from "clsx"; import useDocusaurusContext from "@docusaurus/useDocusaurusContext"; import { useDoc } from "@docusaurus/plugin-content-docs/client"; @@ -6,6 +6,12 @@ import { markdownUrlFor } from "../../utils/markdownUrl"; import { copyMarkdown } from "../../utils/copyMarkdown"; import styles from "./styles.module.css"; +const copyLabels = { + idle: "Copy page as Markdown", + copied: "Copied", + failed: "Couldn't copy", +}; + // "Copy page" dropdown: copies the page's Markdown or opens it in an assistant. // Built from divs/buttons/anchors (no ul/li) so Algolia's `li` selector skips it; // the `page-ai-actions` class is the hook rehype-docusaurus-cleanup uses to drop @@ -15,79 +21,80 @@ export default function PageAiActions() { const { siteConfig } = useDocusaurusContext(); // API endpoint pages span the content column and the API explorer, so a right // float would land beyond the explorer: keep the menu above the title instead. - const inline = Boolean(frontMatter.api); + const isInline = Boolean(frontMatter.api); const mdUrl = markdownUrlFor(metadata.permalink, siteConfig.url); const prompt = encodeURIComponent(`Read ${mdUrl} and help me with questions about it.`); - const [open, setOpen] = useState(false); + const [isOpen, setIsOpen] = useState(false); const [status, setStatus] = useState("idle"); // idle | copied | failed const rootRef = useRef(null); - const timer = useRef(null); - - useEffect(() => { - if (!open) return undefined; - const onPointer = (e) => { - if (rootRef.current && !rootRef.current.contains(e.target)) setOpen(false); - }; - const onKey = (e) => { - if (e.key === "Escape") { - setOpen(false); - rootRef.current?.querySelector("button")?.focus(); - } - }; - document.addEventListener("mousedown", onPointer); - document.addEventListener("touchstart", onPointer); - document.addEventListener("keydown", onKey); - return () => { - document.removeEventListener("mousedown", onPointer); - document.removeEventListener("touchstart", onPointer); - document.removeEventListener("keydown", onKey); - }; - }, [open]); + const triggerRef = useRef(null); + const closeTimer = useRef(null); + const shouldFocusFirstItem = useRef(false); - useEffect(() => () => clearTimeout(timer.current), []); + useEffect( + function closeOnOutsidePointerOrEscape() { + if (!isOpen) return undefined; + const closeOnOutsidePointer = (event) => { + if (rootRef.current && !rootRef.current.contains(event.target)) setIsOpen(false); + }; + const closeOnEscape = (event) => { + if (event.key === "Escape") { + setIsOpen(false); + triggerRef.current?.focus(); + } + }; + document.addEventListener("mousedown", closeOnOutsidePointer); + document.addEventListener("touchstart", closeOnOutsidePointer); + document.addEventListener("keydown", closeOnEscape); + return () => { + document.removeEventListener("mousedown", closeOnOutsidePointer); + document.removeEventListener("touchstart", closeOnOutsidePointer); + document.removeEventListener("keydown", closeOnEscape); + }; + }, + [isOpen], + ); - const copy = useCallback(async () => { - let next = "copied"; - try { - await copyMarkdown(`${metadata.permalink.replace(/\/+$/, "")}.md`); // same-origin copy - } catch (e) { - next = "failed"; - } - setStatus(next); - clearTimeout(timer.current); - if (next === "copied") { - timer.current = setTimeout(() => { - setStatus("idle"); - setOpen(false); - }, 2000); + useEffect(function focusFirstItemAfterKeyboardOpen() { + if (isOpen && shouldFocusFirstItem.current) { + rootRef.current.querySelector('[role="menuitem"]')?.focus(); } - }, [metadata.permalink]); + shouldFocusFirstItem.current = false; + }); - const onMenuKeyDown = (e) => { - if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return; - e.preventDefault(); - const items = [...rootRef.current.querySelectorAll('[role="menuitem"]')]; - const i = items.indexOf(document.activeElement); - const d = e.key === "ArrowDown" ? 1 : -1; - items[(i + d + items.length) % items.length]?.focus(); - }; + useEffect(() => () => clearTimeout(closeTimer.current), []); const itemClass = clsx("dropdown__link", styles.item); - const ext = { target: "_blank", rel: "noopener noreferrer", role: "menuitem", className: itemClass }; + const externalLink = { target: "_blank", rel: "noopener noreferrer", role: "menuitem", className: itemClass }; return (
    { + // A null relatedTarget (Safari doesn't focus clicked buttons) must not close the menu mid-click. + if (event.relatedTarget && !rootRef.current.contains(event.relatedTarget)) setIsOpen(false); + }} > -
    - - {status === "failed" && ( -
    - Copy the link instead: {mdUrl} -
    - )} - + View as Markdown - + Open in Claude - + Open in ChatGPT
    + {status === "failed" && ( +
    + Copy the link instead: {mdUrl} +
    + )}
    ); } diff --git a/src/components/PageAiActions/styles.module.css b/src/components/PageAiActions/styles.module.css index e3ad8023..4a239c6b 100644 --- a/src/components/PageAiActions/styles.module.css +++ b/src/components/PageAiActions/styles.module.css @@ -24,13 +24,6 @@ background: var(--ifm-color-emphasis-200); } -/* Click-only: Infima also opens .dropdown on hover. */ -.root.closed:hover > .menu { - visibility: hidden; - opacity: 0; - pointer-events: none; -} - .inline { float: none; margin: 0 0 1rem; diff --git a/test-support/docusaurus-context-stub.mjs b/test-support/docusaurus-context-stub.mjs new file mode 100644 index 00000000..54ccf90f --- /dev/null +++ b/test-support/docusaurus-context-stub.mjs @@ -0,0 +1,3 @@ +export default function useDocusaurusContext() { + return globalThis.docusaurusMock.context; +} diff --git a/test-support/docusaurus-docs-stub.mjs b/test-support/docusaurus-docs-stub.mjs new file mode 100644 index 00000000..9247e112 --- /dev/null +++ b/test-support/docusaurus-docs-stub.mjs @@ -0,0 +1,3 @@ +export function useDoc() { + return globalThis.docusaurusMock.doc; +} diff --git a/test-support/jsx-loader.mjs b/test-support/jsx-loader.mjs new file mode 100644 index 00000000..8fa95955 --- /dev/null +++ b/test-support/jsx-loader.mjs @@ -0,0 +1,42 @@ +import { readFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import swc from "@swc/core"; + +const stubs = { + "@docusaurus/useDocusaurusContext": new URL("./docusaurus-context-stub.mjs", import.meta.url).href, + "@docusaurus/plugin-content-docs/client": new URL("./docusaurus-docs-stub.mjs", import.meta.url).href, +}; +const srcDir = new URL("../src/", import.meta.url).href; + +export async function resolve(specifier, context, nextResolve) { + if (stubs[specifier]) return { url: stubs[specifier], shortCircuit: true }; + const isExtensionless = specifier.startsWith(".") && !/\.\w+$/.test(specifier); + if (isExtensionless && context.parentURL?.startsWith(srcDir)) { + return nextResolve(`${specifier}.js`, context); + } + return nextResolve(specifier, context); +} + +export async function load(url, context, nextLoad) { + if (url.endsWith(".css")) { + return { + format: "module", + source: "export default new Proxy({}, { get: (_, name) => String(name) });", + shortCircuit: true, + }; + } + if (url.startsWith(srcDir) && url.endsWith(".js")) { + const filename = fileURLToPath(url); + const { code } = await swc.transform(await readFile(filename, "utf8"), { + filename, + jsc: { + parser: { syntax: "ecmascript", jsx: true }, + transform: { react: { runtime: "automatic" } }, + target: "es2022", + }, + module: { type: "es6" }, + }); + return { format: "module", source: code, shortCircuit: true }; + } + return nextLoad(url, context); +} diff --git a/test-support/register.mjs b/test-support/register.mjs new file mode 100644 index 00000000..94e5cd6a --- /dev/null +++ b/test-support/register.mjs @@ -0,0 +1,3 @@ +import { register } from "node:module"; + +register("./jsx-loader.mjs", import.meta.url); diff --git a/yarn.lock b/yarn.lock index ececa4f5..a12a3d81 100644 --- a/yarn.lock +++ b/yarn.lock @@ -227,7 +227,7 @@ js-tokens "^4.0.0" picocolors "^1.1.1" -"@babel/code-frame@^7.29.7": +"@babel/code-frame@^7.10.4", "@babel/code-frame@^7.29.7": version "7.29.7" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.29.7.tgz#f2fbbfea87c44a21590ec515b778b2c26d8866e7" integrity sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw== @@ -2250,6 +2250,11 @@ utility-types "^3.10.0" webpack "^5.88.1" +"@exodus/bytes@^1.15.1", "@exodus/bytes@^1.16.0": + version "1.16.0" + resolved "https://registry.yarnpkg.com/@exodus/bytes/-/bytes-1.16.0.tgz#954c9d9dd7eec15b966b2e8f2d883c04295b720c" + integrity sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA== + "@exodus/schemasafe@^1.0.0-rc.2": version "1.3.0" resolved "https://registry.yarnpkg.com/@exodus/schemasafe/-/schemasafe-1.3.0.tgz#731656abe21e8e769a7f70a4d833e6312fe59b7f" @@ -3160,11 +3165,42 @@ dependencies: defer-to-connect "^2.0.1" +"@testing-library/dom@^10.4.2": + version "10.4.2" + resolved "https://registry.yarnpkg.com/@testing-library/dom/-/dom-10.4.2.tgz#e996827c4e5e1f13589527293b4b3958de2f709f" + integrity sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q== + dependencies: + "@babel/code-frame" "^7.10.4" + "@babel/runtime" "^7.12.5" + "@types/aria-query" "^5.0.1" + aria-query "5.3.0" + dom-accessibility-api "^0.5.9" + lz-string "^1.5.0" + picocolors "1.1.1" + pretty-format "^27.0.2" + +"@testing-library/react@^16.3.3": + version "16.3.3" + resolved "https://registry.yarnpkg.com/@testing-library/react/-/react-16.3.3.tgz#426907e7716f37038dab8aa69d8f0459f9ec24b2" + integrity sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg== + dependencies: + "@babel/runtime" "^7.12.5" + +"@testing-library/user-event@^14.6.13": + version "14.6.13" + resolved "https://registry.yarnpkg.com/@testing-library/user-event/-/user-event-14.6.13.tgz#00a33d2a57730090336f0d7cbd11aa72968c2a5a" + integrity sha512-2LVZGptuB5un1Cu/u31o9adkCwbsUTMp4B4p04xupI7uobvTIpgKidSdShqZiReo/mQmvR9xjgdgTgge4oAbYA== + "@tsconfig/docusaurus@^2.0.3": version "2.0.9" resolved "https://registry.yarnpkg.com/@tsconfig/docusaurus/-/docusaurus-2.0.9.tgz#e530ae78bca4f88917af48fe25a944d6d6bdcdf5" integrity sha512-0jVxZCgy2v7TnJrW9kVNikNwJHeiWb68Zhiiw2vHw4tzBFSP5vS2zn3O5EY2oPEVz5dXZRkK7MnWG3Ay5q0mIg== +"@types/aria-query@^5.0.1": + version "5.0.4" + resolved "https://registry.yarnpkg.com/@types/aria-query/-/aria-query-5.0.4.tgz#1a31c3d378850d2778dabb6374d036dcba4ba708" + integrity sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw== + "@types/body-parser@*": version "1.19.6" resolved "https://registry.yarnpkg.com/@types/body-parser/-/body-parser-1.19.6.tgz#1859bebb8fd7dac9918a45d54c1971ab8b5af474" @@ -4026,6 +4062,11 @@ ansi-styles@^4.0.0, ansi-styles@^4.1.0: dependencies: color-convert "^2.0.1" +ansi-styles@^5.0.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-5.2.0.tgz#07449690ad45777d1924ac2abb2fc8895dba836b" + integrity sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA== + ansi-styles@^6.1.0: version "6.2.3" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-6.2.3.tgz#c044d5dcc521a076413472597a1acb1f103c4041" @@ -4059,6 +4100,13 @@ argparse@^2.0.1: resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== +aria-query@5.3.0: + version "5.3.0" + resolved "https://registry.yarnpkg.com/aria-query/-/aria-query-5.3.0.tgz#650c569e41ad90b51b3d7df5e5eed1c7549c103e" + integrity sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A== + dependencies: + dequal "^2.0.3" + array-flatten@1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/array-flatten/-/array-flatten-1.1.1.tgz#9a5f699051b1e7073328f2a008968b64ea2955d2" @@ -4218,11 +4266,20 @@ batch@0.6.1: resolved "https://registry.yarnpkg.com/batch/-/batch-0.6.1.tgz#dc34314f4e679318093fc760272525f94bf25c16" integrity sha512-x+VAiMRL6UPkx+kudNvxTl6hB2XNNCG2r+7wixVfIYwu/2HKRXimwQyaumLjMveWvT2Hkd/cAJw+QBMfJ/EKVw== -bcp-47-match@^2.0.0: +bcp-47-match@^2.0.0, bcp-47-match@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/bcp-47-match/-/bcp-47-match-2.0.3.tgz#603226f6e5d3914a581408be33b28a53144b09d0" integrity sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ== +bcp-47@^2.1.2: + version "2.1.2" + resolved "https://registry.yarnpkg.com/bcp-47/-/bcp-47-2.1.2.tgz#daf552d46cf73300da467eee035a90141de97b9c" + integrity sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg== + dependencies: + is-alphabetical "^2.0.0" + is-alphanumerical "^2.0.0" + is-decimal "^2.0.0" + big.js@^5.2.2: version "5.2.2" resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328" @@ -5398,6 +5455,14 @@ dagre-d3-es@7.0.14: d3 "^7.9.0" lodash-es "^4.17.21" +data-urls@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/data-urls/-/data-urls-8.0.0.tgz#d4e925beae8249dbe99a1defed36cebb9cc7a84c" + integrity sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ== + dependencies: + whatwg-mimetype "^5.0.0" + whatwg-url "^17.1.2" + dayjs@^1.11.20: version "1.11.21" resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.21.tgz#57f87562e62de76f3c704bd2b8d522fc33068eb2" @@ -5422,6 +5487,11 @@ debug@^4.0.0, debug@^4.1.0, debug@^4.3.1, debug@^4.4.3: dependencies: ms "^2.1.3" +decimal.js@^10.6.0: + version "10.6.0" + resolved "https://registry.yarnpkg.com/decimal.js/-/decimal.js-10.6.0.tgz#e649a43e3ab953a72192ff5983865e509f37ed9a" + integrity sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg== + decode-named-character-reference@^1.0.0: version "1.3.0" resolved "https://registry.yarnpkg.com/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz#3e40603760874c2e5867691b599d73a7da25b53f" @@ -5509,7 +5579,7 @@ depd@~1.1.2: resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9" integrity sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ== -dequal@^2.0.0: +dequal@^2.0.0, dequal@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/dequal/-/dequal-2.0.3.tgz#2644214f1997d39ed0ee0ece72335490a7ac67be" integrity sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA== @@ -5631,6 +5701,11 @@ docusaurus-theme-openapi-docs@^5.1.3: url "^0.11.4" xml-formatter "^3.6.6" +dom-accessibility-api@^0.5.9: + version "0.5.16" + resolved "https://registry.yarnpkg.com/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz#5a7429e6066eb3664d911e33fb0e45de8eb08453" + integrity sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg== + dom-converter@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/dom-converter/-/dom-converter-0.2.0.tgz#6721a9daee2e293682955b6afe416771627bb768" @@ -5809,6 +5884,11 @@ entities@^6.0.0: resolved "https://registry.yarnpkg.com/entities/-/entities-6.0.1.tgz#c28c34a43379ca7f61d074130b2f5f7020a30694" integrity sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g== +entities@^9.0.0: + version "9.0.0" + resolved "https://registry.yarnpkg.com/entities/-/entities-9.0.0.tgz#c45df3cdbc5ce805474759f4ec4ea7907d9d5477" + integrity sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg== + error-ex@^1.3.1: version "1.3.4" resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.4.tgz#b3a8d8bb6f92eecc1629e3e27d3c8607a8a32414" @@ -6782,6 +6862,13 @@ hpack.js@^2.1.6: readable-stream "^2.0.1" wbuf "^1.1.0" +html-encoding-sniffer@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz#cf995009e50fa6f90d74906ab5137f8ee9b7c9d8" + integrity sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w== + dependencies: + "@exodus/bytes" "^1.15.1" + html-escaper@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-2.0.2.tgz#dfd60027da36a36dfcbe236262c00a5822681453" @@ -7229,6 +7316,11 @@ is-plain-object@^2.0.4: dependencies: isobject "^3.0.1" +is-potential-custom-element-name@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz#171ed6f19e3ac554394edf78caa05784a45bebb5" + integrity sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ== + is-regexp@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-regexp/-/is-regexp-1.0.0.tgz#fd2d883545c46bac5a633e7b9a09e87fa2cb5069" @@ -7368,6 +7460,30 @@ js-yaml@^5.2.2: dependencies: argparse "^2.0.1" +jsdom@^31.0.1: + version "31.0.1" + resolved "https://registry.yarnpkg.com/jsdom/-/jsdom-31.0.1.tgz#2f543cea1a4fb30bc5e00ed2a3e37153f82eff33" + integrity sha512-CbhJL8ZQg3eKswxSZth4QO9tW0jPIhmR0vtSXQSbKSfWbwIT6hoRc17wdHIVTQ43KI0mdV5iTJr3281IDgVZ5g== + dependencies: + "@exodus/bytes" "^1.16.0" + bcp-47 "^2.1.2" + bcp-47-match "^2.0.3" + data-urls "^8.0.0" + decimal.js "^10.6.0" + html-encoding-sniffer "^7.0.0" + is-potential-custom-element-name "^1.0.1" + lru-cache "^11.5.3" + parse5 "^8.1.0" + parse5-parser-stream "^8.1.0" + saxes "^6.0.0" + tough-cookie "^6.0.2" + undici "^8.12.3" + w3c-xmlserializer "^6.0.0" + webidl-conversions "^8.0.1" + whatwg-mimetype "^5.0.0" + whatwg-url "^17.3.0" + xml-name-validator "^5.0.0" + jsesc@^3.0.2, jsesc@~3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-3.1.0.tgz#74d335a234f67ed19907fdadfac7ccf9d409825d" @@ -7583,6 +7699,11 @@ lowercase-keys@^3.0.0: resolved "https://registry.yarnpkg.com/lowercase-keys/-/lowercase-keys-3.0.0.tgz#c5e7d442e37ead247ae9db117a9d0a467c89d4f2" integrity sha512-ozCC6gdQ+glXOQsveKD0YsDy8DSQFjDTz4zyzEHNV5+JP5D62LmfDZ6o1cycFx9ouG940M5dE8C8CTewdj2YWQ== +lru-cache@^11.5.3: + version "11.5.4" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-11.5.4.tgz#6073dda1feb2a438e568f791fd13fffa223be76f" + integrity sha512-B8nJCTi8JuSaDBg0tBdnImV6j5O2CXaqKfdj24ZTCFbyivN8KZ2Z+RL3aHjwJAfLutD9cNnObG4SIgW4gMufiw== + lru-cache@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-5.1.1.tgz#1da27e6710271947695daf6848e847f01d84b920" @@ -7590,6 +7711,11 @@ lru-cache@^5.1.1: dependencies: yallist "^3.0.2" +lz-string@^1.5.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/lz-string/-/lz-string-1.5.0.tgz#c1ab50f77887b712621201ba9fd4e3a6ed099941" + integrity sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ== + markdown-extensions@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/markdown-extensions/-/markdown-extensions-2.0.0.tgz#34bebc83e9938cae16e0e017e4a9814a8330d3c4" @@ -8922,6 +9048,13 @@ parse5-htmlparser2-tree-adapter@^7.0.0: domhandler "^5.0.3" parse5 "^7.0.0" +parse5-parser-stream@^8.1.0: + version "8.1.1" + resolved "https://registry.yarnpkg.com/parse5-parser-stream/-/parse5-parser-stream-8.1.1.tgz#27e0507c62b705bf327741cd24b96765173b0ca2" + integrity sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw== + dependencies: + parse5 "^8.1.1" + parse5@^7.0.0: version "7.3.0" resolved "https://registry.yarnpkg.com/parse5/-/parse5-7.3.0.tgz#d7e224fa72399c7a175099f45fc2ad024b05ec05" @@ -8929,6 +9062,13 @@ parse5@^7.0.0: dependencies: entities "^6.0.0" +parse5@^8.1.0, parse5@^8.1.1: + version "8.1.1" + resolved "https://registry.yarnpkg.com/parse5/-/parse5-8.1.1.tgz#d73eb52282024c921e9c5a19b870f53492e631b2" + integrity sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w== + dependencies: + entities "^9.0.0" + parseurl@~1.3.3: version "1.3.3" resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" @@ -8999,7 +9139,7 @@ path-type@^4.0.0: resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw== -picocolors@^1.0.0, picocolors@^1.1.1: +picocolors@1.1.1, picocolors@^1.0.0, picocolors@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.1.1.tgz#3d321af3eab939b083c8f929a1d12cda81c26b6b" integrity sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA== @@ -9690,6 +9830,15 @@ pretty-error@^4.0.0: lodash "^4.17.20" renderkid "^3.0.0" +pretty-format@^27.0.2: + version "27.5.1" + resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-27.5.1.tgz#2181879fdea51a7a5851fb39d920faa63f01d88e" + integrity sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ== + dependencies: + ansi-regex "^5.0.1" + ansi-styles "^5.0.0" + react-is "^17.0.1" + pretty-time@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/pretty-time/-/pretty-time-1.1.0.tgz#ffb7429afabb8535c346a34e41873adf3d74dd0e" @@ -9886,6 +10035,11 @@ react-is@^16.13.1, react-is@^16.6.0, react-is@^16.7.0: resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4" integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ== +react-is@^17.0.1: + version "17.0.2" + resolved "https://registry.yarnpkg.com/react-is/-/react-is-17.0.2.tgz#e691d4a8e9c789365655539ab372762b0efb54f0" + integrity sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w== + react-json-view-lite@^2.3.0: version "2.5.0" resolved "https://registry.yarnpkg.com/react-json-view-lite/-/react-json-view-lite-2.5.0.tgz#c7ff011c7cc80e9900abc7aa4916c6a5c6d6c1c6" @@ -10463,6 +10617,13 @@ sax@^1.2.4, sax@^1.5.0: resolved "https://registry.yarnpkg.com/sax/-/sax-1.6.0.tgz#da59637629307b97e7c4cb28e080a7bc38560d5b" integrity sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA== +saxes@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/saxes/-/saxes-6.0.0.tgz#fe5b4a4768df4f14a201b1ba6a65c1f3d9988cc5" + integrity sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA== + dependencies: + xmlchars "^2.2.0" + scheduler@^0.23.2: version "0.23.2" resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.23.2.tgz#414ba64a3b282892e944cf2108ecc078d115cdc3" @@ -11253,6 +11414,18 @@ tinypool@^1.0.2: resolved "https://registry.yarnpkg.com/tinypool/-/tinypool-1.1.1.tgz#059f2d042bd37567fbc017d3d426bdd2a2612591" integrity sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg== +tldts-core@^7.6.4: + version "7.6.4" + resolved "https://registry.yarnpkg.com/tldts-core/-/tldts-core-7.6.4.tgz#ea3d475cf0f09564d54fb5dcd73289d1a74828c5" + integrity sha512-QywQ9lgQyZMuc3NVlqmuxHOhlwirSdvgD/vDLvX8dZYcYgy1cdri5rY/TXDHcF4J3VBSdJLcJNIJI6zGJ7jE+w== + +tldts@^7.0.5: + version "7.6.4" + resolved "https://registry.yarnpkg.com/tldts/-/tldts-7.6.4.tgz#4cf4a818a4309916a634b6de46fa6130375f96e3" + integrity sha512-wp+ZdvQyov404xynNcjbXoJyeGM28W/aCwMmry/rJ+Y0SsObukJYkWwuxWGbNpIjeqMaEbNUtXPNtPPfI5cTFA== + dependencies: + tldts-core "^7.6.4" + to-regex-range@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" @@ -11270,6 +11443,20 @@ totalist@^3.0.0: resolved "https://registry.yarnpkg.com/totalist/-/totalist-3.0.1.tgz#ba3a3d600c915b1a97872348f79c127475f6acf8" integrity sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ== +tough-cookie@^6.0.2: + version "6.1.0" + resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-6.1.0.tgz#eafa6e331d2b948cdd73d75ee1190cb5a8f0df0d" + integrity sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w== + dependencies: + tldts "^7.0.5" + +tr46@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/tr46/-/tr46-7.0.0.tgz#af39140d4a8860868de4e16477a4a946bda03a62" + integrity sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg== + dependencies: + punycode "^2.3.1" + tr46@~0.0.3: version "0.0.3" resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a" @@ -11374,6 +11561,11 @@ undici@^6.28.0: resolved "https://registry.yarnpkg.com/undici/-/undici-6.28.0.tgz#9f0e385744fef5021d6596c5bccd783f61193c1c" integrity sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA== +undici@^8.12.3: + version "8.14.0" + resolved "https://registry.yarnpkg.com/undici/-/undici-8.14.0.tgz#25f8b8172b69c5f67f1b671522052030451748e6" + integrity sha512-MqM6wqORYo0jb1WFUwFKZTFWFz6VeBMPj9op5Hq+RvlrQjISQCyLEfx5+/iqOLWC/LL1HliJ5t0NP1BgYpXeVQ== + unicode-canonical-property-names-ecmascript@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.1.tgz#cb3173fe47ca743e228216e4a3ddc4c84d628cc2" @@ -11658,6 +11850,13 @@ vfile@^6.0.0, vfile@^6.0.1: "@types/unist" "^3.0.0" vfile-message "^4.0.0" +w3c-xmlserializer@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz#27c0747e0091ada8cdb513c3645362e71fc50d82" + integrity sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q== + dependencies: + xml-name-validator "^5.0.0" + warning@^4.0.3: version "4.0.3" resolved "https://registry.yarnpkg.com/warning/-/warning-4.0.3.tgz#16e9e077eb8a86d6af7d64aa1e05fd85b4678ca3" @@ -11689,6 +11888,11 @@ webidl-conversions@^3.0.0: resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871" integrity sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ== +webidl-conversions@^8.0.1: + version "8.0.1" + resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-8.0.1.tgz#0657e571fe6f06fcb15ca50ed1fdbcb495cd1686" + integrity sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ== + webpack-bundle-analyzer@^4.10.2: version "4.10.2" resolved "https://registry.yarnpkg.com/webpack-bundle-analyzer/-/webpack-bundle-analyzer-4.10.2.tgz#633af2862c213730be3dbdf40456db171b60d5bd" @@ -11826,6 +12030,20 @@ websocket-extensions@>=0.1.1: resolved "https://registry.yarnpkg.com/websocket-extensions/-/websocket-extensions-0.1.4.tgz#7f8473bc839dfd87608adb95d7eb075211578a42" integrity sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg== +whatwg-mimetype@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz#d8232895dbd527ceaee74efd4162008fb8a8cf48" + integrity sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw== + +whatwg-url@^17.1.2, whatwg-url@^17.3.0: + version "17.3.0" + resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-17.3.0.tgz#261af70e10e3a6788a842751c5c81ad63f04e87f" + integrity sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg== + dependencies: + "@exodus/bytes" "^1.16.0" + tr46 "^7.0.0" + webidl-conversions "^8.0.1" + whatwg-url@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d" @@ -11922,11 +12140,21 @@ xml-js@^1.6.11: dependencies: sax "^1.2.4" +xml-name-validator@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-5.0.0.tgz#82be9b957f7afdacf961e5980f1bf227c0bf7673" + integrity sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg== + xml-parser-xo@^4.1.5: version "4.1.6" resolved "https://registry.yarnpkg.com/xml-parser-xo/-/xml-parser-xo-4.1.6.tgz#22bb2d0e1f651f92de04c7b79433a9df6f1490f2" integrity sha512-mXbSNSM+rIwndoxSwmFa83bOdeP8G/cOGr7XvxA67X7ebCzoAuVez9JYDCDub3zRDNBZxIbfjuXLSsamr7NfwQ== +xmlchars@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/xmlchars/-/xmlchars-2.2.0.tgz#060fe1bcb7f9c76fe2a17db86a9bc3ab894210cb" + integrity sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw== + y18n@^5.0.5: version "5.0.8" resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55" From ce0359d70b684b60d37adccf2cf71ce9b8bd5521 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 18:25:52 +0000 Subject: [PATCH 28/43] docs: turn the absolute links this branch added into file links Each of the 260 links is master's original relative link plus `.mdx` (or `/index.mdx` for the SDK Guide overview link), so Docusaurus resolves it from the source file regardless of trailing slashes. Built hrefs are unchanged on every page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- .../CLI-Documentation/configuration.mdx | 4 +-- .../experiments-and-feature-flags.mdx | 8 +++--- .../CLI-Documentation/other-entities.mdx | 10 +++---- .../federated-oidc-tokens.mdx | 10 +++---- .../microsoft-entra-id.mdx | 22 +++++++-------- .../MCP-Server/authentication.mdx | 10 +++---- .../MCP-Server/oauth-clients.mdx | 14 +++++----- docs/APIs-and-SDKs/MCP-Server/overview.mdx | 20 ++++++------- docs/APIs-and-SDKs/MCP-Server/quick-start.mdx | 12 ++++---- docs/APIs-and-SDKs/MCP-Server/setup.mdx | 20 ++++++------- .../MCP-Server/troubleshooting.mdx | 8 +++--- .../MCP-Server/usage-examples.mdx | 4 +-- .../_create-context-basic.mdx | 2 +- .../SDK-Documentation/_initialize-basic.mdx | 4 +-- .../SDK-Documentation/config-api.mdx | 2 +- .../SDK-Documentation/getting-started.mdx | 4 +-- .../pre-fetching-context-data.mdx | 4 +-- .../running-your-first-experiment.mdx | 8 +++--- .../SDK-Documentation/using-custom-fields.mdx | 6 ++-- .../using-variables-as-code.mdx | 4 +-- .../SSO/Azure SAML Setup.mdx | 2 +- .../SSO/Google SAML Setup.mdx | 2 +- .../SSO/Okta SAML Setup.mdx | 2 +- .../SSO/SAML Role Mapping.mdx | 6 ++-- docs/platform-release-notes/2026/06.mdx | 4 +-- docs/platform-release-notes/2026/09.mdx | 2 +- docs/web-console-docs/configuration/units.mdx | 2 +- .../events/downloading-events.mdx | 6 ++-- .../events/exposure-events.mdx | 8 +++--- docs/web-console-docs/events/goal-events.mdx | 4 +-- .../events/the-events-page.mdx | 8 +++--- .../events/visitors-identity.mdx | 2 +- .../experiments/aborting-experiments.mdx | 2 +- .../experiments/creating-an-experiment.mdx | 12 ++++---- .../experiments/experiment-health-checks.mdx | 2 +- .../experiments/experiment-reports.mdx | 10 +++---- ...rpreting-metrics-in-experiment-results.mdx | 2 +- .../web-console-docs/experiments/overview.mdx | 18 ++++++------ .../setting-up-a-fixed-horizon-experiment.mdx | 2 +- .../setting-up-a-gst-experiment.mdx | 2 +- .../experiments/unit-assignment.mdx | 4 +-- .../goals/composite-goals.mdx | 10 +++---- .../goals-and-metrics/goals/create.mdx | 2 +- .../goals-and-metrics/goals/overview.mdx | 6 ++-- .../goals-and-metrics/metrics/create.mdx | 24 ++++++++-------- .../metric-types/activity-per-period.mdx | 10 +++---- .../metrics/metric-types/goal-count.mdx | 12 ++++---- .../metric-types/goal-unique-count.mdx | 12 ++++---- .../metrics/metric-types/property.mdx | 14 +++++----- .../metrics/metric-types/ratio.mdx | 10 +++---- .../metrics/metric-types/retention.mdx | 12 ++++---- .../metric-types/time-to-achievement.mdx | 12 ++++---- .../metric-types/unique-property-count.mdx | 8 +++--- .../goals-and-metrics/metrics/overview.mdx | 6 ++-- .../getting-started.mdx | 2 +- .../ownership-and-permissions.mdx | 2 +- .../users-teams-permissions/roles.mdx | 6 ++-- .../warehouse-native/connect/bigquery.mdx | 8 +++--- .../warehouse-native/connect/clickhouse.mdx | 2 +- .../warehouse-native/connect/databricks.mdx | 2 +- .../warehouse-native/connect/redshift.mdx | 2 +- .../warehouse-native/connect/snowflake.mdx | 2 +- .../warehouse-native/get-started.mdx | 28 +++++++++---------- .../warehouse-native/modes.mdx | 8 +++--- .../warehouse-native/overview.mdx | 4 +-- 65 files changed, 241 insertions(+), 241 deletions(-) diff --git a/docs/APIs-and-SDKs/CLI-Documentation/configuration.mdx b/docs/APIs-and-SDKs/CLI-Documentation/configuration.mdx index 8d349c6a..167ee071 100644 --- a/docs/APIs-and-SDKs/CLI-Documentation/configuration.mdx +++ b/docs/APIs-and-SDKs/CLI-Documentation/configuration.mdx @@ -45,7 +45,7 @@ abs experiments update 123 --field "Hypothesis=Updated hypothesis" --show-reques `--curl` output redacts the `Authorization` header and known sensitive body fields by default. That makes it safer to share, but other headers, query parameters, paths or body fields can still contain credentials or user data, so check the output before sharing it. Redacted output won't authenticate if you paste it into a shell. Add `--show-secrets` to get a replayable, authenticated command; this prints your API key in plain text, so don't paste that output into tickets, chat or logs. `--headers-only` strips request bodies, so combining it with `--curl` won't give a complete, replayable command for requests that send a body (`POST`, `PUT`, `PATCH`). -`--show-request` is the fastest way to see the exact payload shape the CLI sends for a given command — useful when integrating directly against the REST API and you want to confirm a field's wire format, such as [custom field values](/docs/APIs-and-SDKs/CLI-Documentation/experiments-and-feature-flags#custom-field-options). +`--show-request` is the fastest way to see the exact payload shape the CLI sends for a given command — useful when integrating directly against the REST API and you want to confirm a field's wire format, such as [custom field values](./experiments-and-feature-flags.mdx#custom-field-options). ## Configuration file @@ -95,7 +95,7 @@ profiles: | `ABSMARTLY_API_KEY` | API key (overrides keychain and credentials file) | | `ABSMARTLY_API_ENDPOINT` | API endpoint URL (overrides profile config) | -See [Authentication](/docs/APIs-and-SDKs/CLI-Documentation/authentication) for the full credential resolution order and OAuth/API key login flows. +See [Authentication](./authentication.mdx) for the full credential resolution order and OAuth/API key login flows. ## Date formats diff --git a/docs/APIs-and-SDKs/CLI-Documentation/experiments-and-feature-flags.mdx b/docs/APIs-and-SDKs/CLI-Documentation/experiments-and-feature-flags.mdx index b7c16e3d..5795fcdf 100644 --- a/docs/APIs-and-SDKs/CLI-Documentation/experiments-and-feature-flags.mdx +++ b/docs/APIs-and-SDKs/CLI-Documentation/experiments-and-feature-flags.mdx @@ -71,7 +71,7 @@ abs experiments search "onboarding" | `--show ` | Add extra columns | | `--exclude ` | Hide columns | -All `--from`, `--to`, `--created-after`, and other date options accept the shared [date formats](/docs/APIs-and-SDKs/CLI-Documentation/configuration#date-formats). +All `--from`, `--to`, `--created-after`, and other date options accept the shared [date formats](./configuration.mdx#date-formats). ## Getting details @@ -128,7 +128,7 @@ abs experiments restart 123 --hypothesis "New iteration" abs experiments create --name test --field "Hypothesis=We believe X" ``` -Custom field values are sent to the API as an object keyed by each field's numeric id (not an array) — the CLI builds this automatically. If you're integrating directly against the REST API and want to see the exact request the CLI sends for a given custom field update, use the global [`--show-request`](/docs/APIs-and-SDKs/CLI-Documentation/configuration#debugging-api-traffic) flag: +Custom field values are sent to the API as an object keyed by each field's numeric id (not an array) — the CLI builds this automatically. If you're integrating directly against the REST API and want to see the exact request the CLI sends for a given custom field update, use the global [`--show-request`](./configuration.mdx#debugging-api-traffic) flag: ```bash abs experiments update 123 --field "Hypothesis=Updated hypothesis" --show-request @@ -207,7 +207,7 @@ abs experiments archive 123 --unarchive ## Metric results -`--from`/`--to` accept all [date formats](/docs/APIs-and-SDKs/CLI-Documentation/configuration#date-formats). +`--from`/`--to` accept all [date formats](./configuration.mdx#date-formats). ```bash abs experiments metrics list 123 # list assigned metrics @@ -410,4 +410,4 @@ abs experiments estimate-participants --unit-type user_id --from 90d abs experiments estimate-participants --unit-type user_id -o json ``` -See [Experiment Templates](/docs/APIs-and-SDKs/CLI-Documentation/experiment-templates) for the markdown+YAML round-trip format used by `--from-file` and `-o template`. +See [Experiment Templates](./experiment-templates.mdx) for the markdown+YAML round-trip format used by `--from-file` and `-o template`. diff --git a/docs/APIs-and-SDKs/CLI-Documentation/other-entities.mdx b/docs/APIs-and-SDKs/CLI-Documentation/other-entities.mdx index 0ca74aa1..bf10616d 100644 --- a/docs/APIs-and-SDKs/CLI-Documentation/other-entities.mdx +++ b/docs/APIs-and-SDKs/CLI-Documentation/other-entities.mdx @@ -8,7 +8,7 @@ Command reference for every CLI entity outside of experiments and feature flags ## Activity feed -Global activity feed across all experiments. Scans recent experiments and aggregates their activity notes. `--since` accepts all [date formats](/docs/APIs-and-SDKs/CLI-Documentation/configuration#date-formats). +Global activity feed across all experiments. Scans recent experiments and aggregates their activity notes. `--since` accepts all [date formats](./configuration.mdx#date-formats). Aliases: `activity-feed` @@ -35,7 +35,7 @@ abs experiments activity list checkout_redesign --notes --show-images abs experiments activity create checkout_redesign --note "Deployed to staging" ``` -See [Experiments & Feature Flags](/docs/APIs-and-SDKs/CLI-Documentation/experiments-and-feature-flags#activity-log) for the full per-experiment activity command reference (edit, reply, etc.). +See [Experiments & Feature Flags](./experiments-and-feature-flags.mdx#activity-log) for the full per-experiment activity command reference (edit, reply, etc.). ## Goals @@ -335,7 +335,7 @@ abs custom-sections reorder --sections "1:0,2:1,3:2" ## Events -View and manage event tracking data. `--from`/`--to` accept all [date formats](/docs/APIs-and-SDKs/CLI-Documentation/configuration#date-formats). +View and manage event tracking data. `--from`/`--to` accept all [date formats](./configuration.mdx#date-formats). Aliases: `events`, `event` @@ -356,7 +356,7 @@ abs events json-layouts --source unit_attribute --phase after_enrichment ## Insights -View experiment velocity and decision analytics. `--from`/`--to` accept ISO dates (see [date formats](/docs/APIs-and-SDKs/CLI-Documentation/configuration#date-formats)). +View experiment velocity and decision analytics. `--from`/`--to` accept ISO dates (see [date formats](./configuration.mdx#date-formats)). Aliases: `insights`, `insight` @@ -407,7 +407,7 @@ abs action-dialog-fields update 1 --config '{"required": true}' ## Platform configuration -Manage server-side platform settings (not local CLI config — see [Configuration](/docs/APIs-and-SDKs/CLI-Documentation/configuration) for local config). +Manage server-side platform settings (not local CLI config — see [Configuration](./configuration.mdx) for local config). Aliases: `platform-config`, `platformconfig`, `platform-configs` diff --git a/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens.mdx b/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens.mdx index 58eaafef..a1cdfbc8 100644 --- a/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens.mdx +++ b/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens.mdx @@ -27,7 +27,7 @@ Federated tokens can be enabled for two endpoints: This page describes what works with any identity provider. For the step-by-step setup of a specific provider, see its guide: -- [Microsoft Entra ID](/docs/APIs-and-SDKs/Federated-Authentication/microsoft-entra-id) +- [Microsoft Entra ID](./microsoft-entra-id.mdx) :::info Enabled on request Federated tokens are off by default. ABsmartly support turns them on for your @@ -137,7 +137,7 @@ providers often issue different identifiers to different applications, and some put a changeable login or email in `sub`. Configure a SAML assertion attribute that contains exactly the value your access tokens carry in the subject claim, and tell ABsmartly support its name. For Entra ID, see -[the SAML attribute setup](/docs/APIs-and-SDKs/Federated-Authentication/microsoft-entra-id#link-users-through-saml-sso). +[the SAML attribute setup](./microsoft-entra-id.mdx#link-users-through-saml-sso). When a user signs in through that SAML provider, ABsmartly records the link, and the tenant from the assertion if it carries one. Every user must sign in @@ -229,7 +229,7 @@ opaque access tokens, so use a custom authorization server. How your backend gets the token depends on your identity provider: - **Microsoft Entra ID** uses the On-Behalf-Of flow. See - [Request a token with the On-Behalf-Of flow](/docs/APIs-and-SDKs/Federated-Authentication/microsoft-entra-id#request-a-token-with-the-on-behalf-of-flow). + [Request a token with the On-Behalf-Of flow](./microsoft-entra-id.mdx#request-a-token-with-the-on-behalf-of-flow). - **Providers that support OAuth 2.0 Token Exchange** ([RFC 8693](https://www.rfc-editor.org/rfc/rfc8693)) exchange the user's token at the token endpoint with @@ -498,11 +498,11 @@ with the [token requirements](#token-requirements). | An MCP tool call that runs for more than five minutes fails partway with `401` | The internal credential the MCP server uses for each request is valid for five minutes | Split the work into shorter tool calls | For provider-specific problems, see the provider guide, for example -[Microsoft Entra ID troubleshooting](/docs/APIs-and-SDKs/Federated-Authentication/microsoft-entra-id#troubleshooting). +[Microsoft Entra ID troubleshooting](./microsoft-entra-id.mdx#troubleshooting). ## Related -- [Microsoft Entra ID](/docs/APIs-and-SDKs/Federated-Authentication/microsoft-entra-id) — step-by-step setup for Entra ID +- [Microsoft Entra ID](./microsoft-entra-id.mdx) — step-by-step setup for Entra ID - [Platform API](/docs/APIs-and-SDKs/Web-Console-API/absmartly-web-console-api) — the REST API reference - [MCP Server authentication](/docs/APIs-and-SDKs/MCP-Server/authentication) diff --git a/docs/APIs-and-SDKs/Federated-Authentication/microsoft-entra-id.mdx b/docs/APIs-and-SDKs/Federated-Authentication/microsoft-entra-id.mdx index 0b882c70..1d48c586 100644 --- a/docs/APIs-and-SDKs/Federated-Authentication/microsoft-entra-id.mdx +++ b/docs/APIs-and-SDKs/Federated-Authentication/microsoft-entra-id.mdx @@ -6,7 +6,7 @@ description: Set up Microsoft Entra ID so your backend can call the ABsmartly RE # Microsoft Entra ID -This guide sets up [federated OIDC access tokens](/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens) +This guide sets up [federated OIDC access tokens](./federated-oidc-tokens.mdx) with Microsoft Entra ID. Your backend uses the Entra [On-Behalf-Of (OBO) flow](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-on-behalf-of-flow) to exchange a signed-in user's token for an access token issued for ABsmartly, @@ -14,7 +14,7 @@ and calls the ABsmartly REST API (`/v1`) or your instance's `/mcp` endpoint with it. Each call acts as the matching ABsmartly user, with exactly that user's permissions. -Read [Federated OIDC access tokens](/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens) first for how the +Read [Federated OIDC access tokens](./federated-oidc-tokens.mdx) first for how the feature works, how to call `/v1` and `/mcp`, the errors and the security model. This page covers only the Entra ID setup. @@ -75,7 +75,7 @@ is separate from the enterprise application you created for SAML SSO. Click **Add scope**. `mcp.access` grants access to `/mcp` and `api.access` grants access to `/v1`. -See [REST API and MCP access](/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens#rest-api-and-mcp-access). +See [REST API and MCP access](./federated-oidc-tokens.mdx#rest-api-and-mcp-access). These are the scope names we use by convention. ABsmartly configures the scopes for your instance, so if you need different names, agree them with ABsmartly support and use them everywhere this page says `mcp.access` or @@ -141,9 +141,9 @@ even if they already have an account or browser session. There is no bulk import. The first sign-in decides the link, so check that every user's email in Entra ID maps to the right ABsmartly user before you enable it. Links are never reassigned automatically; see -[Link users through SAML SSO](/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens#link-users-through-saml-sso) +[Link users through SAML SSO](./federated-oidc-tokens.mdx#link-users-through-saml-sso) for details and for how to -[fix a wrong link](/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens#fix-a-wrong-or-stuck-link). +[fix a wrong link](./federated-oidc-tokens.mdx#fix-a-wrong-or-stuck-link). ## Step 2: Give your backend app permission to call ABsmartly @@ -270,15 +270,15 @@ Send the `access_token` from the OBO response as `Authorization: Bearer ` on every request to `https://your-instance.absmartly.com/v1/...` or `https://your-instance.absmartly.com/mcp`. See -[Call the REST API with the token](/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens#call-the-rest-api-with-the-token) +[Call the REST API with the token](./federated-oidc-tokens.mdx#call-the-rest-api-with-the-token) and -[Call the MCP server with the token](/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens#call-the-mcp-server-with-the-token) +[Call the MCP server with the token](./federated-oidc-tokens.mdx#call-the-mcp-server-with-the-token) for full examples. ## What ABsmartly checks in Entra ID tokens ABsmartly applies all the -[token requirements](/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens#token-requirements). For Entra ID +[token requirements](./federated-oidc-tokens.mdx#token-requirements). For Entra ID they mean: | Check | Token claim | Must be | @@ -303,7 +303,7 @@ archived. ## Troubleshooting Rejected tokens come back with an `error_description` that says why. See -[Error reasons](/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens#error-reasons) for the full list. These +[Error reasons](./federated-oidc-tokens.mdx#error-reasons) for the full list. These problems are specific to Entra ID: | Symptom | Likely cause | Fix | @@ -316,14 +316,14 @@ problems are specific to Entra ID: | `required scope missing` (`403`) | `scp` doesn't contain the scope named in the `WWW-Authenticate` header (`mcp.access` on `/mcp`, `api.access` on `/v1`): the scope wasn't requested, or consent wasn't granted | Request `api:///` and [grant admin consent](#step-2-give-your-backend-app-permission-to-call-absmartly) | | `federated tokens are not accepted on this endpoint` on `/v1` | REST API access isn't enabled for your instance | Ask ABsmartly support to enable it with your API scope, or call `/mcp` | | `token subject claim missing` | The token has no `oid` | Send a delegated access token issued for the ABsmartly app | -| `no active ABsmartly user for this identity` | The user hasn't signed in with SAML since federated tokens were enabled, the SAML assertion lacks the [object ID attribute](#link-users-through-saml-sso), the linked user is archived, or the token is from a different tenant than the one recorded at SAML sign-in (or has no `tid`) | Have the user sign in with SAML SSO once, and request the token from the same tenant the user signs in to ABsmartly with. If the link is wrong, [fix it](/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens#fix-a-wrong-or-stuck-link). | +| `no active ABsmartly user for this identity` | The user hasn't signed in with SAML since federated tokens were enabled, the SAML assertion lacks the [object ID attribute](#link-users-through-saml-sso), the linked user is archived, or the token is from a different tenant than the one recorded at SAML sign-in (or has no `tid`) | Have the user sign in with SAML SSO once, and request the token from the same tenant the user signs in to ABsmartly with. If the link is wrong, [fix it](./federated-oidc-tokens.mdx#fix-a-wrong-or-stuck-link). | | `app-only tokens are not accepted` | The token comes from the client credentials flow, not OBO | Use the [OBO flow](#request-a-token-with-the-on-behalf-of-flow) with a signed-in user's token | | The OBO request fails with `AADSTS65001` | Admin consent wasn't granted to your backend app | Grant admin consent in **API permissions** | | The OBO request fails with `AADSTS50013` or `AADSTS50027` | The `assertion` isn't a valid access token for your backend app | Pass the user's access token for your backend app, not an ID token | ## Related -- [Federated OIDC access tokens](/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens) — how the feature +- [Federated OIDC access tokens](./federated-oidc-tokens.mdx) — how the feature works, calling `/v1` and `/mcp`, errors and security - [SAML SSO - Azure](/docs/Third-party-integrations/SSO/Azure%20SAML%20Setup) — set up Entra ID sign-in to the Web Console diff --git a/docs/APIs-and-SDKs/MCP-Server/authentication.mdx b/docs/APIs-and-SDKs/MCP-Server/authentication.mdx index c905b456..e3d4658f 100644 --- a/docs/APIs-and-SDKs/MCP-Server/authentication.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/authentication.mdx @@ -33,7 +33,7 @@ Depending on the client, the API key is supplied as either: - A query string parameter on the connection URL (`?api_key=YOUR_API_KEY&absmartly-endpoint=https://your-instance.absmartly.com`). -See the [Setup](/docs/APIs-and-SDKs/MCP-Server/setup) guide for the exact configuration per client. +See the [Setup](./setup.mdx) guide for the exact configuration per client. ### Authorization header formats @@ -82,7 +82,7 @@ There are two OAuth-enabled MCP URLs: Every OAuth connection uses the authorization code flow with PKCE (`S256`). For the full sequence, the endpoints involved and the ways an MCP client can be -registered, see [OAuth & Client Registration](/docs/APIs-and-SDKs/MCP-Server/oauth-clients). +registered, see [OAuth & Client Registration](./oauth-clients.mdx). ### Specifying the instance URL @@ -101,7 +101,7 @@ instance is implied by the URL. Most MCP clients are accepted automatically, either through a trusted client metadata document or through dynamic client registration with an allowlisted redirect URI. If your client is rejected, use an API key instead, or see -[Your client isn't on the list?](/docs/APIs-and-SDKs/MCP-Server/oauth-clients#your-client-isnt-on-the-list). +[Your client isn't on the list?](./oauth-clients.mdx#your-client-isnt-on-the-list). ## Federated OIDC tokens (e.g. Microsoft Entra ID) @@ -136,12 +136,12 @@ profile with `--profile=` (for example, `--profile=production`). authentication-method confusion. - **Restricted OAuth clients** — only trusted clients and allowlisted redirect URIs can receive OAuth access, and every new client is shown on a consent - page first (see [OAuth & Client Registration](/docs/APIs-and-SDKs/MCP-Server/oauth-clients)). + page first (see [OAuth & Client Registration](./oauth-clients.mdx)). - **PKCE required** — OAuth requests must use PKCE with `S256`. - **Destructive action confirmation** — destructive operations such as `start`, `stop`, `archive` and `delete` ask you to confirm before they run, on every transport (see the - [Tools Reference](/docs/APIs-and-SDKs/MCP-Server/tools-reference#execute_command)). + [Tools Reference](./tools-reference.mdx#execute_command)). - **API error surfacing** — validation errors from the API are returned with full detail so the assistant can correct them. diff --git a/docs/APIs-and-SDKs/MCP-Server/oauth-clients.mdx b/docs/APIs-and-SDKs/MCP-Server/oauth-clients.mdx index e70afeed..5fdac55c 100644 --- a/docs/APIs-and-SDKs/MCP-Server/oauth-clients.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/oauth-clients.mdx @@ -10,7 +10,7 @@ This page explains what happens when an MCP client signs in to ABsmartly with OAuth: which endpoints it calls, how it gets registered, and why some clients are accepted while others are rejected. You don't need any of this to connect a supported client, because the client does it all for you. It is useful when you -connect a client that isn't listed in [Setup](/docs/APIs-and-SDKs/MCP-Server/setup), or when you need to +connect a client that isn't listed in [Setup](./setup.mdx), or when you need to debug a failed connection. ## Two ways to connect with OAuth @@ -217,7 +217,7 @@ with that URL, then update the connection with the new `client_id` and ### API key If your client can't use OAuth at all, or isn't on the allowlist, connect with -an [API key](/docs/APIs-and-SDKs/MCP-Server/authentication#api-key) instead. API key connections skip OAuth +an [API key](./authentication.mdx#api-key) instead. API key connections skip OAuth entirely, so no registration is needed. This works with any client that can send an HTTP header or connect to a URL with a query string. @@ -257,7 +257,7 @@ receive the access. The consent page shows a warning for these hosts. Only approve when you have just started the connection yourself. These platforms connect from their own cloud. Connect them to the hosted -server URL, as shown in [Setup](/docs/APIs-and-SDKs/MCP-Server/setup#cloud-agent-platforms). +server URL, as shown in [Setup](./setup.mdx#cloud-agent-platforms). ::: ### Your client isn't on the list? @@ -265,7 +265,7 @@ server URL, as shown in [Setup](/docs/APIs-and-SDKs/MCP-Server/setup#cloud-agent If your MCP client is rejected and isn't covered above: 1. **Use an API key.** It works with any client and needs no registration. See - [Authentication](/docs/APIs-and-SDKs/MCP-Server/authentication#api-key). + [Authentication](./authentication.mdx#api-key). 2. **Ask for the client to be added.** Contact ABsmartly support with the client's name and its redirect URI or metadata-document URL. You can also open an issue on @@ -297,8 +297,8 @@ MCP client. ## Related -- [Authentication](/docs/APIs-and-SDKs/MCP-Server/authentication) — API keys, header formats and the +- [Authentication](./authentication.mdx) — API keys, header formats and the security model -- [Setup](/docs/APIs-and-SDKs/MCP-Server/setup) — per-client configuration -- [Troubleshooting](/docs/APIs-and-SDKs/MCP-Server/troubleshooting#oauth-errors) — what each OAuth error +- [Setup](./setup.mdx) — per-client configuration +- [Troubleshooting](./troubleshooting.mdx#oauth-errors) — what each OAuth error means diff --git a/docs/APIs-and-SDKs/MCP-Server/overview.mdx b/docs/APIs-and-SDKs/MCP-Server/overview.mdx index 9f799179..b7a744d6 100644 --- a/docs/APIs-and-SDKs/MCP-Server/overview.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/overview.mdx @@ -74,7 +74,7 @@ always ask you to confirm before they run — through an in-client prompt on the hosted server and local stdio server where the client supports it, or in the chat. Experiment creation from templates returns a preview first. -See the [Tools Reference](/docs/APIs-and-SDKs/MCP-Server/tools-reference) for the full surface. +See the [Tools Reference](./tools-reference.mdx) for the full surface. ## Authentication at a glance @@ -84,8 +84,8 @@ See the [Tools Reference](/docs/APIs-and-SDKs/MCP-Server/tools-reference) for th | **API Key** | Programmatic access, CI/CD, headless, or clients that can't use OAuth | Pass the key in HTTP headers or via the URL | | **Federated OIDC token** | Your own backend agent acting for users signed in to your identity provider (e.g. Microsoft Entra ID) | Send an access token from your identity provider to your instance's `/mcp` (enabled on request) | -All methods are documented in detail in [Authentication](/docs/APIs-and-SDKs/MCP-Server/authentication). -[OAuth & Client Registration](/docs/APIs-and-SDKs/MCP-Server/oauth-clients) explains the OAuth flow, the +All methods are documented in detail in [Authentication](./authentication.mdx). +[OAuth & Client Registration](./oauth-clients.mdx) explains the OAuth flow, the endpoints involved and which clients are accepted. [Federated OIDC access tokens](/docs/APIs-and-SDKs/Federated-Authentication/federated-oidc-tokens) explains federated tokens, which also work on the REST API, with a step-by-step guide for @@ -102,18 +102,18 @@ tokens, which also work on the REST API, with a step-by-step guide for ## What's next -- **[Quick Start](/docs/APIs-and-SDKs/MCP-Server/quick-start)** — connect Claude Desktop with OAuth and run +- **[Quick Start](./quick-start.mdx)** — connect Claude Desktop with OAuth and run your first command in under five minutes -- **[Setup](/docs/APIs-and-SDKs/MCP-Server/setup)** — per-client setup for every supported MCP client -- **[Authentication](/docs/APIs-and-SDKs/MCP-Server/authentication)** — API key formats, OAuth, +- **[Setup](./setup.mdx)** — per-client setup for every supported MCP client +- **[Authentication](./authentication.mdx)** — API key formats, OAuth, security model -- **[OAuth & Client Registration](/docs/APIs-and-SDKs/MCP-Server/oauth-clients)** — the OAuth flow with +- **[OAuth & Client Registration](./oauth-clients.mdx)** — the OAuth flow with diagrams, endpoints, and how MCP clients are registered and accepted -- **[Usage Examples](/docs/APIs-and-SDKs/MCP-Server/usage-examples)** — natural-language prompts that work +- **[Usage Examples](./usage-examples.mdx)** — natural-language prompts that work today -- **[Tools Reference](/docs/APIs-and-SDKs/MCP-Server/tools-reference)** — full list of tools, command groups, +- **[Tools Reference](./tools-reference.mdx)** — full list of tools, command groups, resources and prompts -- **[Troubleshooting](/docs/APIs-and-SDKs/MCP-Server/troubleshooting)** — common errors and how to fix them +- **[Troubleshooting](./troubleshooting.mdx)** — common errors and how to fix them ## Source code diff --git a/docs/APIs-and-SDKs/MCP-Server/quick-start.mdx b/docs/APIs-and-SDKs/MCP-Server/quick-start.mdx index faedef86..2d0e50c3 100644 --- a/docs/APIs-and-SDKs/MCP-Server/quick-start.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/quick-start.mdx @@ -9,7 +9,7 @@ This guide gets you from zero to running your first ABsmartly command via the MCP server in under five minutes. We'll use **Claude Desktop** with **OAuth** — the fastest path with no API keys to manage. -For other clients or API key setups, jump straight to [Setup](/docs/APIs-and-SDKs/MCP-Server/setup). +For other clients or API key setups, jump straight to [Setup](./setup.mdx). ## Prerequisites @@ -48,7 +48,7 @@ shows that Claude is asking for access to your ABsmartly account, and click your org uses it). When the browser confirms success, the connector is live. Your approval is remembered in that browser, so reconnecting later skips the -consent page. See [OAuth & Client Registration](/docs/APIs-and-SDKs/MCP-Server/oauth-clients) for what +consent page. See [OAuth & Client Registration](./oauth-clients.mdx) for what happens behind the scenes. :::tip @@ -106,11 +106,11 @@ and show a preview / confirmation step — destructive actions like `start`, ## Where to go next -- **[Usage Examples](/docs/APIs-and-SDKs/MCP-Server/usage-examples)** — more natural-language prompts that +- **[Usage Examples](./usage-examples.mdx)** — more natural-language prompts that work today -- **[Tools Reference](/docs/APIs-and-SDKs/MCP-Server/tools-reference)** — the full set of commands, including +- **[Tools Reference](./tools-reference.mdx)** — the full set of commands, including experiment creation from markdown templates -- **[Authentication](/docs/APIs-and-SDKs/MCP-Server/authentication)** — switch to API key auth (for CI or +- **[Authentication](./authentication.mdx)** — switch to API key auth (for CI or headless use), or learn about the security model -- **[Troubleshooting](/docs/APIs-and-SDKs/MCP-Server/troubleshooting)** — if the connection isn't working, +- **[Troubleshooting](./troubleshooting.mdx)** — if the connection isn't working, start here diff --git a/docs/APIs-and-SDKs/MCP-Server/setup.mdx b/docs/APIs-and-SDKs/MCP-Server/setup.mdx index db90acd0..7c9629bd 100644 --- a/docs/APIs-and-SDKs/MCP-Server/setup.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/setup.mdx @@ -34,8 +34,8 @@ covers Claude Desktop, Claude Code, Cursor, Windsurf, VS Code (Copilot), Gemini agent platforms and the DXT extension. For details on API keys and supported `Authorization` header formats, see -[Authentication](/docs/APIs-and-SDKs/MCP-Server/authentication). For how OAuth clients are registered and -which ones are accepted, see [OAuth & Client Registration](/docs/APIs-and-SDKs/MCP-Server/oauth-clients). +[Authentication](./authentication.mdx). For how OAuth clients are registered and +which ones are accepted, see [OAuth & Client Registration](./oauth-clients.mdx). ## Transports @@ -62,7 +62,7 @@ login, or an API key sent as `Authorization: Api-Key YOUR_API_KEY`. Because the URL already identifies your instance, no `absmartly-endpoint` parameter or `x-absmartly-endpoint` header is needed. Use this URL in place of `https://mcp.absmartly.com/mcp` in any of the Streamable HTTP examples below. -See [OAuth & Client Registration](/docs/APIs-and-SDKs/MCP-Server/oauth-clients#two-ways-to-connect-with-oauth) +See [OAuth & Client Registration](./oauth-clients.mdx#two-ways-to-connect-with-oauth) for how the two differ. :::info Availability @@ -574,11 +574,11 @@ Streamable HTTP transport — use the `/mcp` endpoint: 3. **Server URL:** `https://mcp.absmartly.com/mcp?absmartly-endpoint=https://your-instance.absmartly.com` 4. **Authentication:** OAuth. The connector form asks for an existing OAuth - client. First [register a client manually](/docs/APIs-and-SDKs/MCP-Server/oauth-clients#manual-registration) + client. First [register a client manually](./oauth-clients.mdx#manual-registration) with the redirect URI `https://vertexaisearch.cloud.google.com/oauth-redirect`, then enter its `client_id` and `client_secret`, the authorization and token URLs from the - [endpoint table](/docs/APIs-and-SDKs/MCP-Server/oauth-clients#endpoints), and the `mcp:access` scope. + [endpoint table](./oauth-clients.mdx#endpoints), and the `mcp:access` scope. Select **Enable PKCE Support**: ABsmartly requires PKCE with `S256`. Keep **Use HTTP Basic Authentication** selected, to match the `client_secret_basic` method in the registration example. @@ -680,12 +680,12 @@ https://mcp.absmartly.com/mcp?absmartly-endpoint=https://your-instance.absmartly [Gemini Enterprise](#gemini-enterprise-google-cloud-console) is covered above. Other platforms whose callbacks are on the -[allowlist](/docs/APIs-and-SDKs/MCP-Server/oauth-clients#allowed-redirect-uris) may work, but we haven't +[allowlist](./oauth-clients.mdx#allowed-redirect-uris) may work, but we haven't tested them yet, so they have no setup guide here. ABsmartly requires the authorization-code flow with PKCE (`S256`). If a platform asks you for a client ID and secret instead of registering itself, see -[Manual registration](/docs/APIs-and-SDKs/MCP-Server/oauth-clients#manual-registration). If it can't connect, -use an [API key](/docs/APIs-and-SDKs/MCP-Server/authentication#api-key). +[Manual registration](./oauth-clients.mdx#manual-registration). If it can't connect, +use an [API key](./authentication.mdx#api-key). These platforms use callback URLs shared by all their customers, so the consent page shows an extra warning. @@ -696,12 +696,12 @@ page shows an extra warning. Any MCP client that supports OAuth with dynamic client registration or a trusted client metadata document, and uses an -[allowed redirect URI](/docs/APIs-and-SDKs/MCP-Server/oauth-clients#allowed-redirect-uris), works with the +[allowed redirect URI](./oauth-clients.mdx#allowed-redirect-uris), works with the same URL as above. Local clients that sign in through a `localhost` callback, such as Zed, Kiro, OpenCode or MCP Inspector, are accepted automatically. If your client is rejected, connect with an API key instead, or see -[Your client isn't on the list?](/docs/APIs-and-SDKs/MCP-Server/oauth-clients#your-client-isnt-on-the-list). +[Your client isn't on the list?](./oauth-clients.mdx#your-client-isnt-on-the-list). --- diff --git a/docs/APIs-and-SDKs/MCP-Server/troubleshooting.mdx b/docs/APIs-and-SDKs/MCP-Server/troubleshooting.mdx index 8fd0824e..ab149c9f 100644 --- a/docs/APIs-and-SDKs/MCP-Server/troubleshooting.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/troubleshooting.mdx @@ -49,16 +49,16 @@ instance's own `/mcp` endpoint. Where they differ, both are listed. | Error | Cause | Fix | | --- | --- | --- | -| `invalid_client` — *"This MCP client is not supported by this server"* (hosted server) or *"Unknown client"* (your instance) | The client identifies itself with a metadata-document URL that isn't on the trusted list. | Use an API key, or [ask for the client to be added](/docs/APIs-and-SDKs/MCP-Server/oauth-clients#your-client-isnt-on-the-list). | -| `invalid_redirect_uri` — *"One or more redirect_uris are not allowed"* | The client tried to register with a redirect URI that isn't on the [allowlist](/docs/APIs-and-SDKs/MCP-Server/oauth-clients#allowed-redirect-uris). | Use an API key, or ask for the client to be added. | -| `invalid_client` for a client that used to work | The client's registration expired. On the hosted server, registrations expire 90 days after they are created. On your instance, they expire after 90 days without use. | Remove the connector and add it again so it registers again. If you registered the client manually, [register it again](/docs/APIs-and-SDKs/MCP-Server/oauth-clients#manual-registration) and enter the new `client_id` and `client_secret` in the connector. | +| `invalid_client` — *"This MCP client is not supported by this server"* (hosted server) or *"Unknown client"* (your instance) | The client identifies itself with a metadata-document URL that isn't on the trusted list. | Use an API key, or [ask for the client to be added](./oauth-clients.mdx#your-client-isnt-on-the-list). | +| `invalid_redirect_uri` — *"One or more redirect_uris are not allowed"* | The client tried to register with a redirect URI that isn't on the [allowlist](./oauth-clients.mdx#allowed-redirect-uris). | Use an API key, or ask for the client to be added. | +| `invalid_client` for a client that used to work | The client's registration expired. On the hosted server, registrations expire 90 days after they are created. On your instance, they expire after 90 days without use. | Remove the connector and add it again so it registers again. If you registered the client manually, [register it again](./oauth-clients.mdx#manual-registration) and enter the new `client_id` and `client_secret` in the connector. | | *"PKCE with code_challenge_method=S256 is required"* (hosted server) or `invalid_request` — *"PKCE is required. Supported code_challenge_method: S256"* (your instance) | The client sent no PKCE challenge, or used `plain`. | Update the client. If it can't use `S256`, use an API key. | | *"Authorization request expired or invalid, please restart the connection from your MCP client"* | The consent page was left open for more than 10 minutes, or was approved in a different browser from the one that started it. On the hosted server, it also appears if the page was submitted twice. | Start the connection again from the MCP client, and complete it in one browser. | | *"This login was started in a different browser…"* (hosted server only) | The sign-in to your instance finished in a different browser from the one that approved the consent page. | Copy the authorization link into the browser where you're signed in to ABsmartly, or restart the connection. | | `invalid_grant` — *"The ABsmartly session has ended, please sign in again"* (hosted server) or *"The session that approved this request has ended"* (your instance) | You signed out of ABsmartly, or your session expired. | Reconnect the client and sign in again. | | `access_denied` | You clicked **Deny** on the consent page. | Reconnect and click **Approve**. | -See [OAuth & Client Registration](/docs/APIs-and-SDKs/MCP-Server/oauth-clients) for how clients are +See [OAuth & Client Registration](./oauth-clients.mdx) for how clients are accepted. ### Errors with a federated OIDC token (e.g. Microsoft Entra ID) diff --git a/docs/APIs-and-SDKs/MCP-Server/usage-examples.mdx b/docs/APIs-and-SDKs/MCP-Server/usage-examples.mdx index 878d6489..cf64d822 100644 --- a/docs/APIs-and-SDKs/MCP-Server/usage-examples.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/usage-examples.mdx @@ -5,9 +5,9 @@ sidebar_position: 6 # Usage Examples -Once the MCP server is connected in your AI assistant (see [Setup](/docs/APIs-and-SDKs/MCP-Server/setup)), +Once the MCP server is connected in your AI assistant (see [Setup](./setup.mdx)), you can drive ABsmartly with plain language. Here are prompts that map cleanly -to the underlying [tools](/docs/APIs-and-SDKs/MCP-Server/tools-reference). +to the underlying [tools](./tools-reference.mdx). ## Discover what's available diff --git a/docs/APIs-and-SDKs/SDK-Documentation/_create-context-basic.mdx b/docs/APIs-and-SDKs/SDK-Documentation/_create-context-basic.mdx index 6397e091..b19514e8 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/_create-context-basic.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/_create-context-basic.mdx @@ -205,5 +205,5 @@ The `user_id` above is just an example. You can use any unit type that you've co in your Web Console under Settings > Units (e.g. `session_id`, `device_id`, `email`). Pass all the units you have available for the current user. If you're not sure which ones to use, check Settings > Units in the Web Console. You'll see how these connect -to experiments on the [next page](/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment). +to experiments on the [next page](./running-your-first-experiment.mdx). ::: diff --git a/docs/APIs-and-SDKs/SDK-Documentation/_initialize-basic.mdx b/docs/APIs-and-SDKs/SDK-Documentation/_initialize-basic.mdx index bef66473..5d735c1f 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/_initialize-basic.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/_initialize-basic.mdx @@ -151,7 +151,7 @@ Vue.use(absmartly.ABSmartlyVue, { Using pre-fetched context data If you have already fetched context data on the server (see -[Pre-Fetching Context Data](/docs/APIs-and-SDKs/SDK-Documentation/pre-fetching-context-data)), you can pass it directly +[Pre-Fetching Context Data](./pre-fetching-context-data.mdx)), you can pass it directly to avoid an extra network request: ```js @@ -236,7 +236,7 @@ app.use(absmartly.ABSmartlyVue, { Using pre-fetched context data If you have already fetched context data on the server (see -[Pre-Fetching Context Data](/docs/APIs-and-SDKs/SDK-Documentation/pre-fetching-context-data)), you can pass it directly +[Pre-Fetching Context Data](./pre-fetching-context-data.mdx)), you can pass it directly to avoid an extra network request: ```js diff --git a/docs/APIs-and-SDKs/SDK-Documentation/config-api.mdx b/docs/APIs-and-SDKs/SDK-Documentation/config-api.mdx index 853656b1..d7d15953 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/config-api.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/config-api.mdx @@ -72,5 +72,5 @@ exposures are tracked without you having to think about it. You've reached the end of the SDK Guide. For per-SDK API details beyond what's covered here, check the README in each SDK's GitHub repository (linked on the -[SDK Guide overview](/docs/APIs-and-SDKs/SDK-Documentation/)). If you have questions, reach out to our team through +[SDK Guide overview](./index.mdx)). If you have questions, reach out to our team through the Web Console. diff --git a/docs/APIs-and-SDKs/SDK-Documentation/getting-started.mdx b/docs/APIs-and-SDKs/SDK-Documentation/getting-started.mdx index 1426b940..074bea22 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/getting-started.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/getting-started.mdx @@ -12,7 +12,7 @@ import CustomEventLogger from "./_shared/custom-event-logger/_custom-event-logge This page walks you through connecting your application to ABsmartly. By the end, you'll have the SDK installed, initialised, and a context ready to use for experiments. -Once you've finished here, the [next page](/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment) walks through +Once you've finished here, the [next page](./running-your-first-experiment.mdx) walks through a complete experiment: assigning variants, reading variables, and tracking goals. Together, these two pages give you everything you need to run your first test. @@ -56,5 +56,5 @@ before you can check treatments or track goals. ## Next steps Your SDK is installed, initialised, and you have a context ready to go. Head over to -[Running Your First Experiment](/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment) to learn how to +[Running Your First Experiment](./running-your-first-experiment.mdx) to learn how to assign variants, use variables, and track goals. diff --git a/docs/APIs-and-SDKs/SDK-Documentation/pre-fetching-context-data.mdx b/docs/APIs-and-SDKs/SDK-Documentation/pre-fetching-context-data.mdx index 8a9cc6ff..4a645cd6 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/pre-fetching-context-data.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/pre-fetching-context-data.mdx @@ -345,7 +345,7 @@ user sees the correct variant on the very first paint. ## Related topics -- [Targeting Users and Controlling Assignments](/docs/APIs-and-SDKs/SDK-Documentation/targeting-and-audiences) shows how +- [Targeting Users and Controlling Assignments](./targeting-and-audiences.mdx) shows how to pass user attributes, use custom assignments, and override variants during QA. -- [Using Custom Fields](/docs/APIs-and-SDKs/SDK-Documentation/using-custom-fields) covers adding per-experiment metadata +- [Using Custom Fields](./using-custom-fields.mdx) covers adding per-experiment metadata for advanced use cases. diff --git a/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment.mdx b/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment.mdx index 27db38c5..8ea46dec 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment.mdx @@ -119,11 +119,11 @@ creation, treatment checking, variable usage, goal tracking, and cleanup. You now have everything you need to run a basic experiment. When you're ready to go deeper: -- [Managing the Context Lifecycle](/docs/APIs-and-SDKs/SDK-Documentation/managing-the-context-lifecycle) covers when to +- [Managing the Context Lifecycle](./managing-the-context-lifecycle.mdx) covers when to close contexts, refresh experiment data, and flush events. -- [Pre-Fetching Context Data](/docs/APIs-and-SDKs/SDK-Documentation/pre-fetching-context-data) shows how to fetch +- [Pre-Fetching Context Data](./pre-fetching-context-data.mdx) shows how to fetch experiment data on the server and pass it to the client to avoid flickering. -- [Targeting Users and Controlling Assignments](/docs/APIs-and-SDKs/SDK-Documentation/targeting-and-audiences) shows how +- [Targeting Users and Controlling Assignments](./targeting-and-audiences.mdx) shows how to pass user attributes, use custom assignments, and override variants during QA. -- [Checking Variants Without Triggering Exposures](/docs/APIs-and-SDKs/SDK-Documentation/checking-variants-without-exposures) +- [Checking Variants Without Triggering Exposures](./checking-variants-without-exposures.mdx) explains peeking, which is useful for pre-loading assets or debugging. diff --git a/docs/APIs-and-SDKs/SDK-Documentation/using-custom-fields.mdx b/docs/APIs-and-SDKs/SDK-Documentation/using-custom-fields.mdx index 89bed456..32964d22 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/using-custom-fields.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/using-custom-fields.mdx @@ -180,12 +180,12 @@ edited on the Web Console to change the variant that developers see. :::caution Overriding an experiment allocation will not count the user towards the experiment data. -To learn more about overrides, have a look at the [overrides documentation](/docs/APIs-and-SDKs/SDK-Documentation/targeting-and-audiences#overriding-variants-for-development-and-qa). +To learn more about overrides, have a look at the [overrides documentation](./targeting-and-audiences.mdx#overriding-variants-for-development-and-qa). ::: ## Next steps -- [Targeting Users and Controlling Assignments](/docs/APIs-and-SDKs/SDK-Documentation/targeting-and-audiences) covers +- [Targeting Users and Controlling Assignments](./targeting-and-audiences.mdx) covers overrides and custom assignments in more detail. -- [Config API](/docs/APIs-and-SDKs/SDK-Documentation/config-api) shows another way to use experiment data without +- [Config API](./config-api.mdx) shows another way to use experiment data without branching logic in your code. diff --git a/docs/APIs-and-SDKs/SDK-Documentation/using-variables-as-code.mdx b/docs/APIs-and-SDKs/SDK-Documentation/using-variables-as-code.mdx index 5f922001..35f8ca16 100644 --- a/docs/APIs-and-SDKs/SDK-Documentation/using-variables-as-code.mdx +++ b/docs/APIs-and-SDKs/SDK-Documentation/using-variables-as-code.mdx @@ -6,7 +6,7 @@ import Image from "@theme/IdealImage"; # Using Variables as Code -[Treatment variables](/docs/APIs-and-SDKs/SDK-Documentation/running-your-first-experiment#step-2-use-variables-for-flexible-experiments) +[Treatment variables](./running-your-first-experiment.mdx#step-2-use-variables-for-flexible-experiments) are great for setting values like colours, copy, or feature flags. But sometimes you want the Web Console to control actual behaviour: injecting HTML elements, running functions, or applying CSS styles. @@ -18,7 +18,7 @@ a function directly from the Web Console. ## Starting Point For these examples, we're using a basic Vite app with the SDK already initialised and a -context ready (see [Getting Started](/docs/APIs-and-SDKs/SDK-Documentation/getting-started) if you need to set that up). +context ready (see [Getting Started](./getting-started.mdx) if you need to set that up). The page starts with a simple heading:
    diff --git a/docs/Third-party-integrations/SSO/Azure SAML Setup.mdx b/docs/Third-party-integrations/SSO/Azure SAML Setup.mdx index dfff7c06..bf783248 100644 --- a/docs/Third-party-integrations/SSO/Azure SAML Setup.mdx +++ b/docs/Third-party-integrations/SSO/Azure SAML Setup.mdx @@ -93,7 +93,7 @@ Feel free to add [the ABsmartly logo](/img/logo.png) to the application in **Pro | `lastName` | `Attribute` | `user.surname` | | `department` | `Attribute` | `user.department` | -To assign ABsmartly roles from Azure, also add a `roles` claim, see [Assigning Roles](/docs/Third-party-integrations/SSO/SAML%20Role%20Mapping). +To assign ABsmartly roles from Azure, also add a `roles` claim, see [Assigning Roles](./SAML%20Role%20Mapping.mdx). firstName - Last Name -> lastName - To assign ABsmartly roles from Google Workspace, also map a `roles` attribute, see [Assigning Roles](/docs/Third-party-integrations/SSO/SAML%20Role%20Mapping). + To assign ABsmartly roles from Google Workspace, also map a `roles` attribute, see [Assigning Roles](./SAML%20Role%20Mapping.mdx). -Check the [Exposure events](/docs/web-console-docs/events/exposure-events) and [Goal events](/docs/web-console-docs/events/goal-events) pages for more details on those events +Check the [Exposure events](exposure-events.mdx) and [Goal events](goal-events.mdx) pages for more details on those events ## Events Filters @@ -94,4 +94,4 @@ this box and only your own events will appear in the list. ## Downloading Events -See the [downloading events page](/docs/web-console-docs/events/downloading-events) for a complete guide to downloading raw events. \ No newline at end of file +See the [downloading events page](downloading-events.mdx) for a complete guide to downloading raw events. \ No newline at end of file diff --git a/docs/web-console-docs/events/visitors-identity.mdx b/docs/web-console-docs/events/visitors-identity.mdx index ba5c64fc..a5a22d78 100644 --- a/docs/web-console-docs/events/visitors-identity.mdx +++ b/docs/web-console-docs/events/visitors-identity.mdx @@ -18,7 +18,7 @@ Those identifiers are used to uniquely identify visitors in experiments through to link them to the goals events they are triggering as they use your products. What identifiers exist depends on where the experiment is running and what you know about the visitor at that moment. -Those tracking identifiers (also know as Units) need to be pre-registered on the ABsmartly platform, see [Units](/docs/web-console-docs/configuration/units) for more details. +Those tracking identifiers (also know as Units) need to be pre-registered on the ABsmartly platform, see [Units](../configuration/units.mdx) for more details. Below is an example on how the ABsmartly context can be initialised with 3 different unit types. diff --git a/docs/web-console-docs/experiments/aborting-experiments.mdx b/docs/web-console-docs/experiments/aborting-experiments.mdx index 6e7f3ee0..a45f8892 100644 --- a/docs/web-console-docs/experiments/aborting-experiments.mdx +++ b/docs/web-console-docs/experiments/aborting-experiments.mdx @@ -47,7 +47,7 @@ If the treatment introduces a **bug** or **technical failure** that disrupts cor A bug in the checkout flow prevents users from completing transactions, making it imperative to abort the experiment immediately. ### Experiment Health Checks alert -[Health Checks](/docs/web-console-docs/experiments/experiment-health-checks) are quality checks run in the background to ensure the experiment and data are reliable. Most health checks alerts would require to abort the experiment and investigate the reason for the alert. +[Health Checks](experiment-health-checks.mdx) are quality checks run in the background to ensure the experiment and data are reliable. Most health checks alerts would require to abort the experiment and investigate the reason for the alert. **Example**: The health checks show an assignment conflicts was detected meaning that some visitors have been exposed to more than one variant. This might require the experiment to be stopped and the issue investigated. diff --git a/docs/web-console-docs/experiments/creating-an-experiment.mdx b/docs/web-console-docs/experiments/creating-an-experiment.mdx index 056ae90e..5dbb4a3c 100644 --- a/docs/web-console-docs/experiments/creating-an-experiment.mdx +++ b/docs/web-console-docs/experiments/creating-an-experiment.mdx @@ -13,7 +13,7 @@ To get started with creating a new experiment, you can click **Experiments** on :::info Instead of creating an experiment from scratch you can also decide to use a pre-existing template. -To find out more about creating and using templates check our [template documentation](/docs/web-console-docs/experiments/templates). +To find out more about creating and using templates check our [template documentation](templates.mdx). ::: ## Basics @@ -80,7 +80,7 @@ Screenshots are useful to quickly understand what an experiment is changing. The audiences’ step is where you will control where the experiment will run and who will be exposed to it. :::info Redesigned experiment form -In the redesigned experiment form, this step is split into the **Tracking** and **Unit assignments** sections, the targeting audience is called **eligibility rules**, and exclusion rules are called **override rules**. See [Unit Assignment](/docs/web-console-docs/experiments/unit-assignment) for details. +In the redesigned experiment form, this step is split into the **Tracking** and **Unit assignments** sections, the targeting audience is called **eligibility rules**, and exclusion rules are called **override rules**. See [Unit Assignment](./unit-assignment.mdx) for details. ::: Defining the audience @@ -240,7 +240,7 @@ It is good practice to have a set of guardrail metrics agreed upon and shared by To improve their usefulness, it is possible to define on the metric’s page, a threshold at which an alert would be triggered so you don’t miss it. Depending on the severity of the issues they signal, **Guardrail Metrics** can be used both for early stopping of experiments and to assess their impact at decision time. -For more information on early stopping of experiments using ABsmartly you can read our [**early stopping guide**](/docs/web-console-docs/experiments/aborting-experiments). +For more information on early stopping of experiments using ABsmartly you can read our [**early stopping guide**](aborting-experiments.mdx). ### The Exploratory Metrics @@ -272,12 +272,12 @@ Cannot find your metric in the list? Make sure it is `active` as `draft` metrics ## Analysis In this step, you can choose and set up the analysis type you want to use. -To choose between a Group Sequential or Fixed Horizon analysis check our [analysis type article](/docs/web-console-docs/experiments/overview#analysis-methods). +To choose between a Group Sequential or Fixed Horizon analysis check our [analysis type article](overview.mdx#analysis-methods). To continue to properly set up your experiment refer to the relevant setup guide -- [**Group Sequential setup guide**](/docs/web-console-docs/experiments/setting-up-a-gst-experiment) -- [**Fixed Horizon setup guide**](/docs/web-console-docs/experiments/setting-up-a-fixed-horizon-experiment) +- [**Group Sequential setup guide**](setting-up-a-gst-experiment.mdx) +- [**Fixed Horizon setup guide**](setting-up-a-fixed-horizon-experiment.mdx) ## Metadata diff --git a/docs/web-console-docs/experiments/experiment-health-checks.mdx b/docs/web-console-docs/experiments/experiment-health-checks.mdx index 2e1abf7a..e74539cd 100644 --- a/docs/web-console-docs/experiments/experiment-health-checks.mdx +++ b/docs/web-console-docs/experiments/experiment-health-checks.mdx @@ -90,7 +90,7 @@ Assess the risk of the interaction and abort one or both of the experiments to e ### Variables Conflicting **What is it?** -Checks for conflicting variables used across 2 or more experiments. This check is performed when [Experiment Variables](/docs/web-console-docs/experiments/creating-an-experiment#variant-variables) are used in the experiment setup. +Checks for conflicting variables used across 2 or more experiments. This check is performed when [Experiment Variables](creating-an-experiment.mdx#variant-variables) are used in the experiment setup. :::caution Variable keys that are prefixed with a double underscore (`__`) are ignored during this health check. diff --git a/docs/web-console-docs/experiments/experiment-reports.mdx b/docs/web-console-docs/experiments/experiment-reports.mdx index 649e3c82..77003e3b 100644 --- a/docs/web-console-docs/experiments/experiment-reports.mdx +++ b/docs/web-console-docs/experiments/experiment-reports.mdx @@ -89,8 +89,8 @@ Even if an experiment was running only for a few seconds it would appear on the Experiments completed report This report highlights the number of experiment which were successfully completed in the reporting period. -In the case of a [Fixed Horizon Experiment](/docs/web-console-docs/experiments/overview#analysis-methods), it is deemed completed once it reaches its expected sample size or planned duration. -For a [Group Sequential Test](/docs/web-console-docs/experiments/overview#analysis-methods), an experiment is completed once it crosses one of the test boundaries (efficiency or futility). +In the case of a [Fixed Horizon Experiment](overview.mdx#analysis-methods), it is deemed completed once it reaches its expected sample size or planned duration. +For a [Group Sequential Test](overview.mdx#analysis-methods), an experiment is completed once it crosses one of the test boundaries (efficiency or futility). The report also visualises the outcome of the statistical test on the primary metric at the moment the experiment was completed. The experiment will be shown in `green` if its **primary metric was significant in the expected direction** at the time the experiment was completed. @@ -112,7 +112,7 @@ Knowing that something does not have the expected impact on customer behaviour c In the case of **early stopped experiments** (also known as aborted experiments), the decisions to abort can happen because of bugs in the implementation, early worrying negative signals, strategic reasons or for any other reason. Depending on the reason for early stopping, aborted experiments are typically restarted once the underlying issue is fixed. -Read our [When to abort an experiment?](/docs/web-console-docs/experiments/aborting-experiments) guide to understand more about aborting experiments. +Read our [When to abort an experiment?](aborting-experiments.mdx) guide to understand more about aborting experiments. While aborting experiments is common and part of the process, **early Full on**, should be rare as they indicate that changes were pushed without supporting evidence. This can sometimes happen for strategic or legal reasons but because the experiment did not complete, it does not provide the reliable evidence needed to support or discard the underlying hypothesis. @@ -156,7 +156,7 @@ It is nonetheless possible for `Full on` decisions to not be fully supported by Currently a `Full on` decision is shown as supported by evidence **if and only if the experiment was completed and the primary metric is significant in the expected direction**. :::caution -The supported by evidence validation does not currently include checks on the secondary and guardrail metrics nor on the experiment [health checks](/docs/web-console-docs/experiments/experiment-health-checks). +The supported by evidence validation does not currently include checks on the secondary and guardrail metrics nor on the experiment [health checks](experiment-health-checks.mdx). ::: @@ -176,7 +176,7 @@ This typically happens when the evidence does not support the hypothesis. This widget provides a view on how many `Abort` decisions were made in the reporting period. Aborting means stopping an experiment before it is completed. Aborting can happen when a bug is found or when early negative signals indicate a possible degradation in certain key metrics but it could also be a strategic choice to stop early. -Read our [When to abort an experiment?](/docs/web-console-docs/experiments/aborting-experiments) guide to understand more about aborting experiments. +Read our [When to abort an experiment?](aborting-experiments.mdx) guide to understand more about aborting experiments. Like with `Keep current` decisions, `Abort` decisons means that the current experience remains but unlike `Keep current` decisions it does not say anything about the hypothesis being tested or not. ### Decisions history diff --git a/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results.mdx b/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results.mdx index a7ef7a52..d40aa40d 100644 --- a/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results.mdx +++ b/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results.mdx @@ -22,7 +22,7 @@ The metrics table provides the following key data points for each variant: - **Participants**: The number of individuals assigned to each variant, expressed as a count and percentage of the total participants. - **Value**: The total count or sum associated with the metric (e.g., number of "buyers") for each variant. -- **Mean**: The average performance of the metric for each variant, calculated as: `Mean = Value / Participants`. If the metric uses [CUPED](/docs/web-console-docs/goals-and-metrics/metrics/variance-reduction-cuped), Value and Mean are CUPED-adjusted. For [Ratio](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio) metrics, Value and Mean both show the ratio. +- **Mean**: The average performance of the metric for each variant, calculated as: `Mean = Value / Participants`. If the metric uses [CUPED](../goals-and-metrics/metrics/variance-reduction-cuped.mdx), Value and Mean are CUPED-adjusted. For [Ratio](../goals-and-metrics/metrics/metric-types/ratio.mdx) metrics, Value and Mean both show the ratio. - **Confidence**: The statistical confidence that the observed difference between variants is real, not due to random chance. diff --git a/docs/web-console-docs/experiments/overview.mdx b/docs/web-console-docs/experiments/overview.mdx index 1e4a135e..6e1386d4 100644 --- a/docs/web-console-docs/experiments/overview.mdx +++ b/docs/web-console-docs/experiments/overview.mdx @@ -41,7 +41,7 @@ When a user reaches an experiment, ABsmartly assigns them to a variant using a d - consistent behaviour during the entire experiment - predictable control of traffic allocation -[Exposure events](/docs/web-console-docs/events/exposure-events) are sent automatically by the SDK, and these events define when users become part of the analysis dataset. +[Exposure events](../events/exposure-events.mdx) are sent automatically by the SDK, and these events define when users become part of the analysis dataset. ### Variants @@ -57,7 +57,7 @@ Variants determine what users see, while the metrics determine how those differe ### Goals and metrics -Experiments are measured using [goals](/docs/web-console-docs/goals-and-metrics/goals/overview) and the [metrics](/docs/web-console-docs/goals-and-metrics/metrics/overview) derived from them. +Experiments are measured using [goals](../goals-and-metrics/goals/overview.mdx) and the [metrics](../goals-and-metrics/metrics/overview.mdx) derived from them. Examples of goals: @@ -67,7 +67,7 @@ context.track("add_to_cart", { product_id: "ABC123" }); context.track("view_item", { item_id: "XYZ987" }); ``` -Metrics take your [goal events](/docs/web-console-docs/events/goal-events) and turn them into meaningful measurements of user behaviour. +Metrics take your [goal events](../events/goal-events.mdx) and turn them into meaningful measurements of user behaviour. They let you answer questions like: - how many times something happened @@ -79,16 +79,16 @@ ABsmartly handles all the computation and presents the results in a clear, compa ### Guardrails and monitoring -Before experiment results can be trusted, ABsmartly performs several [health checks](/docs/web-console-docs/experiments/experiment-health-checks) automatically: +Before experiment results can be trusted, ABsmartly performs several [health checks](experiment-health-checks.mdx) automatically: - Sample Ratio Mismatch at the experiment level - assignment and exposure conflicts - guardrail metric thresholds - unexpected behaviour in exposure or goal events - data quality anomalies -Guardrails help detect harmful side effects and make it possible to [abort experiments](/docs/web-console-docs/experiments/aborting-experiments) if needed. +Guardrails help detect harmful side effects and make it possible to [abort experiments](aborting-experiments.mdx) if needed. -You can also configure guardrail metrics with [thresholds](/docs/web-console-docs/goals-and-metrics/metrics/create#metric-threshold-alert) that alert you when impact crosses meaningful limits, +You can also configure guardrail metrics with [thresholds](../goals-and-metrics/metrics/create.mdx#metric-threshold-alert) that alert you when impact crosses meaningful limits, for example when a performance metric becomes slower or when a business KPI shows a potential drop. ### Analysing results @@ -102,7 +102,7 @@ For each metric you will see: - confidence interval - impact per day -You can use our guide on [interpreting metrics results](/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results) to help with the analysis step. +You can use our guide on [interpreting metrics results](interpreting-metrics-in-experiment-results.mdx) to help with the analysis step. ### Decisions @@ -223,7 +223,7 @@ The frontend calls `context.track`. The SDK returns the assigned variant, and th - Very fast iteration - No backend deployment needed - Ideal for design and UX teams -- Non-engineers can create visually in the [Visual Editor](/docs/web-console-docs/launchpad-browser-extension/getting-started) +- Non-engineers can create visually in the [Visual Editor](../launchpad-browser-extension/getting-started.mdx) **Things to consider** - Must be implemented correctly to avoid flicker @@ -362,7 +362,7 @@ The following permissions exist when managing and working with `experiments`. #### Global access -Permission to create and manage `experiments` can be granted to the relevant users through their [role](/docs/web-console-docs/configuration/settings#roles) at the platform level. +Permission to create and manage `experiments` can be granted to the relevant users through their [role](../configuration/settings.mdx#roles) at the platform level. :::info It is not recommended to provide access to `metrics` to non platform admin users at the platform level. diff --git a/docs/web-console-docs/experiments/setting-up-a-fixed-horizon-experiment.mdx b/docs/web-console-docs/experiments/setting-up-a-fixed-horizon-experiment.mdx index ede339df..8976e9bb 100644 --- a/docs/web-console-docs/experiments/setting-up-a-fixed-horizon-experiment.mdx +++ b/docs/web-console-docs/experiments/setting-up-a-fixed-horizon-experiment.mdx @@ -11,7 +11,7 @@ A step by step guide to set up and configure a Fixed Horizon experiment. ## Type of Analysis A Fixed Horizon test can be configured on the Analysis step (Step 5) of the experimentation setup. -To understand the differences between Group Sequential and Fixed Horizon experiment check our [analysis type article](/docs/web-console-docs/experiments/overview#analysis-methods). +To understand the differences between Group Sequential and Fixed Horizon experiment check our [analysis type article](overview.mdx#analysis-methods). Choosing an analysis type diff --git a/docs/web-console-docs/experiments/setting-up-a-gst-experiment.mdx b/docs/web-console-docs/experiments/setting-up-a-gst-experiment.mdx index 0f119212..fc734ab1 100644 --- a/docs/web-console-docs/experiments/setting-up-a-gst-experiment.mdx +++ b/docs/web-console-docs/experiments/setting-up-a-gst-experiment.mdx @@ -11,7 +11,7 @@ A step by step guide to set up and configure a Group Sequential experiment. ## Type of Analysis A Group Sequential test can be configured on the Analysis step (Step 5) of the experimentation setup. -To understand the differences between Group Sequential and Fixed Horizon experiment check our [analysis type article](/docs/web-console-docs/experiments/overview#analysis-methods). +To understand the differences between Group Sequential and Fixed Horizon experiment check our [analysis type article](overview.mdx#analysis-methods). Choosing an analysis type diff --git a/docs/web-console-docs/experiments/unit-assignment.mdx b/docs/web-console-docs/experiments/unit-assignment.mdx index 039f95e8..0e56bffa 100644 --- a/docs/web-console-docs/experiments/unit-assignment.mdx +++ b/docs/web-console-docs/experiments/unit-assignment.mdx @@ -15,7 +15,7 @@ In the redesigned experiment form, the **Unit assignments** section decides whic - [Override rules](#override-rules): units forced into a variant, or into their own traffic split, and excluded from the analysis - [Assignment summary](#assignment-summary): a live view of how every unit will be assigned -The tracking unit and the applications are set in the **Tracking** section, just above. See [Create an experiment](/docs/web-console-docs/experiments/creating-an-experiment#tracking-unit) for more details on choosing them. +The tracking unit and the applications are set in the **Tracking** section, just above. See [Create an experiment](./creating-an-experiment.mdx#tracking-unit) for more details on choosing them. ## Eligibility rules @@ -28,7 +28,7 @@ The rules are shown in the **Experiment rules** card, under **Eligibility**. Eac The **Audience enforced** switch decides what happens to units which don't match the eligibility rules: - **Audience enforced**: only units matching the eligibility rules take part in the experiment. Other units are shown the control variant, but their data is not tracked. -- **Audience not enforced**: every unit takes part, and it is up to you to make sure only eligible units are shown the experiment in your code. ABsmartly shows an [audience mismatch](/docs/web-console-docs/experiments/experiment-health-checks#audience-mismatch) warning when units not matching the rules are exposed. +- **Audience not enforced**: every unit takes part, and it is up to you to make sure only eligible units are shown the experiment in your code. ABsmartly shows an [audience mismatch](./experiment-health-checks.mdx#audience-mismatch) warning when units not matching the rules are exposed. ## Traffic allocation and variant split diff --git a/docs/web-console-docs/goals-and-metrics/goals/composite-goals.mdx b/docs/web-console-docs/goals-and-metrics/goals/composite-goals.mdx index 492fb923..b8d7c5f7 100644 --- a/docs/web-console-docs/goals-and-metrics/goals/composite-goals.mdx +++ b/docs/web-console-docs/goals-and-metrics/goals/composite-goals.mdx @@ -14,11 +14,11 @@ Composite goals are useful when the same outcome is tracked under different goal - A sign-up event was renamed from `signup` to `registration` and older code still sends the old name - Several micro-conversions such as `add_to_wishlist`, `share_product` and `save_for_later` together describe engagement -Instead of building a separate metric for each goal, you create one composite goal and build your [metrics](/docs/web-console-docs/goals-and-metrics/metrics/overview) on top of it, exactly as you would with any other goal. +Instead of building a separate metric for each goal, you create one composite goal and build your [metrics](../metrics/overview.mdx) on top of it, exactly as you would with any other goal. ## Creating a composite goal -Composite goals are created from `Settings` > `Goals`, in the same way as any other [goal](/docs/web-console-docs/goals-and-metrics/goals/create). +Composite goals are created from `Settings` > `Goals`, in the same way as any other [goal](./create.mdx). 1. Enter a **Goal name** and a **Description** 2. Set **Goal type** to `Composite Goal` @@ -61,7 +61,7 @@ Component goals don't always use the same names for the same data. For example, | `revenue` | `total` | `amount` | | `currency` | `currency` | `currency_code` | -The mapped properties can then be used in metrics built on the composite goal, both as the metric's [property](/docs/web-console-docs/goals-and-metrics/metrics/create#property) and in [property filters](/docs/web-console-docs/goals-and-metrics/metrics/create#property-filters). +The mapped properties can then be used in metrics built on the composite goal, both as the metric's [property](../metrics/create.mdx#property) and in [property filters](../metrics/create.mdx#property-filters). ## Using composite goals in metrics @@ -73,9 +73,9 @@ For example, with a composite goal `purchase` combining `payment_web` and `payme - A **goal property** metric on `revenue` sums `total` from `payment_web` and `amount` from `payment_app` :::info -Composite goals cannot currently be used as the foreign goal of a [goal relation](/docs/web-console-docs/goals-and-metrics/metrics/create#goal-relations), such as a cancellation or a refund. +Composite goals cannot currently be used as the foreign goal of a [goal relation](../metrics/create.mdx#goal-relations), such as a cancellation or a refund. ::: ## Tracking composite goals -Nothing changes in your code. Composite goals are built from the goals you already track with the SDK's `track` method, so you don't send events for the composite goal itself. See [Goal Events](/docs/web-console-docs/events/goal-events) for more details on tracking goals. +Nothing changes in your code. Composite goals are built from the goals you already track with the SDK's `track` method, so you don't send events for the composite goal itself. See [Goal Events](../../events/goal-events.mdx) for more details on tracking goals. diff --git a/docs/web-console-docs/goals-and-metrics/goals/create.mdx b/docs/web-console-docs/goals-and-metrics/goals/create.mdx index 25d2389a..da9fb1b3 100644 --- a/docs/web-console-docs/goals-and-metrics/goals/create.mdx +++ b/docs/web-console-docs/goals-and-metrics/goals/create.mdx @@ -20,7 +20,7 @@ Goals can be created in the ABsmartly's console by navigating to `Settings` and | Field | Description | |-------|--------------| | **Goal Name** | The unique goal name. This is the name which needs to be used in when calling `track` | -| **Goal type** | `Simple Goal` for a goal tracked with the SDK, or `Composite Goal` to combine several existing goals. See [Composite Goals](/docs/web-console-docs/goals-and-metrics/goals/composite-goals). | +| **Goal type** | `Simple Goal` for a goal tracked with the SDK, or `Composite Goal` to combine several existing goals. See [Composite Goals](./composite-goals.mdx). | | **Description**| Describes what this goal tracks. | | **Owners**| The list of goal owners. Owners can be Teams or individuals. | | **Tags**| Tags used to better describe the goal and improve discoverability. | diff --git a/docs/web-console-docs/goals-and-metrics/goals/overview.mdx b/docs/web-console-docs/goals-and-metrics/goals/overview.mdx index 21be015a..14b8b673 100644 --- a/docs/web-console-docs/goals-and-metrics/goals/overview.mdx +++ b/docs/web-console-docs/goals-and-metrics/goals/overview.mdx @@ -12,7 +12,7 @@ sidebar_position: 1 They represent actions that are meaningful to the product or business — such as viewing a page, clicking a button, adding an item to a cart, or completing a purchase. Each goal is defined by a name and any associated contextual data (for example, `product ID`, `price`, or `category`). Goals are the building blocks of measurement: they define what to observe in the experiment. -Goals are the raw data used to compute [Metrics](/docs/web-console-docs/goals-and-metrics/metrics/overview). +Goals are the raw data used to compute [Metrics](../metrics/overview.mdx). ## Goal Events @@ -30,7 +30,7 @@ context.track("purchase", { ``` In the example above, a `goal` with the name **purchase** was triggered. This goal has additional property information which can be used to compute the metric. -To learn more about `events` you can read the dedicated [Goal Events page](/docs/web-console-docs/events/goal-events) in the knowledge base. +To learn more about `events` you can read the dedicated [Goal Events page](../../events/goal-events.mdx) in the knowledge base. ## Ownership & permissions @@ -71,7 +71,7 @@ The following permissions exist when managing and working with `goals`. #### Global access -Permission to create and manage `goals` can be granted to the relevant users through their [role](/docs/web-console-docs/configuration/settings#roles) at the platform level. +Permission to create and manage `goals` can be granted to the relevant users through their [role](../../configuration/settings.mdx#roles) at the platform level. :::info It is not recommended to provide access to `goals` to non platform admin at the platform level. diff --git a/docs/web-console-docs/goals-and-metrics/metrics/create.mdx b/docs/web-console-docs/goals-and-metrics/metrics/create.mdx index 76c88ca1..b5c03442 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/create.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/create.mdx @@ -30,15 +30,15 @@ This information is version-specific and, as such, can differ between different |-------|--------------| | **Description** | Providing a good description is important as it helps experiments choose the right metric.| | **Impact**| Directionality of the metric. `positive` means that increasing this metric is good. `negative` means that decreasing the metric is good. Use `unknown` if the metric has no preferred direction.| -| **Metric type**| Describes how the metric is implemented. Choose between [`Goal Unique Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-unique-count), [`Goal Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count), [`Goal Time To Achievement`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/time-to-achievement), [`Goal Property`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/property), [`Goal Property Unique Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/unique-property-count), [`Goal Retention`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/retention), [`Goal Activity Period Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/activity-per-period) and [`Ratio`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio). `Custom SQL` is also available when [warehouse-native](/docs/web-console-docs/warehouse-native/overview) is enabled. | +| **Metric type**| Describes how the metric is implemented. Choose between [`Goal Unique Count`](metric-types/goal-unique-count.mdx), [`Goal Count`](metric-types/goal-count.mdx), [`Goal Time To Achievement`](metric-types/time-to-achievement.mdx), [`Goal Property`](metric-types/property.mdx), [`Goal Property Unique Count`](metric-types/unique-property-count.mdx), [`Goal Retention`](metric-types/retention.mdx), [`Goal Activity Period Count`](metric-types/activity-per-period.mdx) and [`Ratio`](metric-types/ratio.mdx). `Custom SQL` is also available when [warehouse-native](../../warehouse-native/overview.mdx) is enabled. | | **Tags** (optional)| Makes the metric more discoverable by providing relevant [tags](/docs/web-console-docs/configuration/settings#tags).| -| **Category** (optional)| The [category](/docs/web-console-docs/goals-and-metrics/metrics/categories) the metric belongs to (`conversion`, `performance`, etc). While optional, selecting a category makes it easier for experimenters to find relevant metrics. | -| **Applications** (optional)| Select the [applications](/docs/web-console-docs/configuration/applications) where this metric makes sense. Only experiments running on these applications should track this metric. While optional, setting the correct `Application(s)` helps experimenters find relevant metrics for their experiments. | -| **Units** (optional)| Select the [tracking units](/docs/web-console-docs/configuration/units) for which this metric is computed. The tracking unit of the metric should match the tracking unit of the experiments where it is tracked. While optional, setting the correct `Tracking Unit(s)` will help experimenters track relevant metrics in their experiments. | +| **Category** (optional)| The [category](categories.mdx) the metric belongs to (`conversion`, `performance`, etc). While optional, selecting a category makes it easier for experimenters to find relevant metrics. | +| **Applications** (optional)| Select the [applications](../../configuration/applications.mdx) where this metric makes sense. Only experiments running on these applications should track this metric. While optional, setting the correct `Application(s)` helps experimenters find relevant metrics for their experiments. | +| **Units** (optional)| Select the [tracking units](../../configuration/units.mdx) for which this metric is computed. The tracking unit of the metric should match the tracking unit of the experiments where it is tracked. While optional, setting the correct `Tracking Unit(s)` will help experimenters track relevant metrics in their experiments. | ## Goal -In this section, you can select and configure the [goal](/docs/web-console-docs/goals-and-metrics/goals/overview) which provides the raw data for this metric. +In this section, you can select and configure the [goal](../goals/overview.mdx) which provides the raw data for this metric. :::info This part of a metric’s setup is version-controlled. @@ -58,7 +58,7 @@ context.track("purchase", { ### Goal -Select the [goal](/docs/web-console-docs/goals-and-metrics/goals/overview) to use as a source for this metric. +Select the [goal](../goals/overview.mdx) to use as a source for this metric. In the example above, the name of the goal is `purchase`. If you don't see a goal in the list, make sure it exists and make sure you have the correct permissions to view and use it. @@ -69,7 +69,7 @@ Auto-created goals do not have an owner when created. For governance reasons, ma ### Property -In the case of [`Goal Property`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/property) or [`Goal Property Unique Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/unique-property-count) metrics, +In the case of [`Goal Property`](metric-types/property.mdx) or [`Goal Property Unique Count`](metric-types/unique-property-count.mdx) metrics, you also need to choose which property of the metric to use. For example, a `revenue` metric built using the goal event above, would use the event property **price**. @@ -91,7 +91,7 @@ A time filter lets you include only the goal events that happen within a defined This ensures your metric measures behavior in a controlled, meaningful period (for example, `purchases within the first hour` or `engagement in the first 7 days`). :::caution -If your metric uses [CUPED](/docs/web-console-docs/goals-and-metrics/metrics/variance-reduction-cuped) and has an `At least` or `Between` time filter, the lookback period must be longer than the start of the time filter. +If your metric uses [CUPED](variance-reduction-cuped.mdx) and has an `At least` or `Between` time filter, the lookback period must be longer than the start of the time filter. For example, if your metric measures `conversions achieved at least 2 weeks after exposure`, the CUPED lookback period must be 3 or 4 weeks. ::: @@ -219,7 +219,7 @@ Goal relations define how one goal (the current one) is linked to another goal ( This identifier is provided through a property in both events (for example **order_number**, **purchase_id**, or **transaction_id**). Each relation type has its own behaviour and additional fields. -Refund and replacement relations are only available for [`Goal Property`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/property#refunds-and-replacements) metrics, including a Goal Property numerator or denominator in a Ratio. +Refund and replacement relations are only available for [`Goal Property`](metric-types/property.mdx#refunds-and-replacements) metrics, including a Goal Property numerator or denominator in a Ratio. #### Cancellation @@ -348,8 +348,8 @@ Replacement relations allow the metric to reflect up-to-date values when items a ## Variance reduction -If applicable, you can enable [CUPED](/docs/web-console-docs/goals-and-metrics/metrics/variance-reduction-cuped) for this metric to help reduce variance. -Enable [CUPED](/docs/web-console-docs/goals-and-metrics/metrics/variance-reduction-cuped) for this metric by checking the checkbox and choose a lookback period which matches the user behaviour. +If applicable, you can enable [CUPED](variance-reduction-cuped.mdx) for this metric to help reduce variance. +Enable [CUPED](variance-reduction-cuped.mdx) for this metric by checking the checkbox and choose a lookback period which matches the user behaviour. ## Format, scale and precisions @@ -378,7 +378,7 @@ These settings allow you to present the metric in a readable and meaningful way ### Value The Value column in the results table displays the total summed value of your metric for each variant. -For [ratio metrics](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio), Value and Mean both show the ratio, so set both formats to suit the ratio. +For [ratio metrics](metric-types/ratio.mdx), Value and Mean both show the ratio, so set both formats to suit the ratio. You can control how this number appears using: #### Format diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/activity-per-period.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/activity-per-period.mdx index 04220733..83b46e98 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/activity-per-period.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/activity-per-period.mdx @@ -30,11 +30,11 @@ Three users are exposed to the experiment: In the experiment results, this group would show a **Value** of 3 (2 + 1 + 0 active days in total) and a **Mean** of 3 / 3 = **1.0** active day per participant. -Compare that with a [`Goal Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count) on the same goal, which counts every event: Ana 3, Ben 12 and Cara 0, so a **Value** of 15 and a **Mean** of 5. Ben's burst of activity dominates the count, while the activity period count shows that Ana came back on more days. +Compare that with a [`Goal Count`](./goal-count.mdx) on the same goal, which counts every event: Ana 3, Ben 12 and Cara 0, so a **Value** of 15 and a **Mean** of 5. Ben's burst of activity dominates the count, while the activity period count shows that Ana came back on more days. ## Creating the metric -When [creating a metric](/docs/web-console-docs/goals-and-metrics/metrics/create), choose `Goal Activity Period Count` as the metric type, then: +When [creating a metric](../create.mdx), choose `Goal Activity Period Count` as the metric type, then: 1. Select the goal you want to measure, for example `app_open`. 2. Set the **Activity interval**: a number and a unit (`Hours`, `Days` or `Weeks`). @@ -50,7 +50,7 @@ Because the slots don't start at the user's exposure, a user's first period can ## Reading the results -In the [metric results table](/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results), **Value** is the total number of active periods across all participants in the variant, and **Mean** is that total divided by the number of participants. The impact is calculated on the Mean, as with other continuous metrics such as `Goal Count`. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the total number of active periods across all participants in the variant, and **Mean** is that total divided by the number of participants. The impact is calculated on the Mean, as with other continuous metrics such as `Goal Count`. If CUPED is active for the metric, both Value and Mean are CUPED-adjusted, so they won't match the raw count of active periods and can be fractional. Configuring CUPED isn't always enough: if the pre-exposure covariate doesn't correlate well enough with the metric, or the adjustment wouldn't reduce variance, ABsmartly falls back to the unadjusted values. @@ -61,7 +61,7 @@ Because the value counts periods rather than dividing by them, it grows the long - `Active days`: goal `app_open`, interval `1 day`. How many different days users opened the app. - `Active weeks with a purchase`: goal `purchase`, interval `1 week`. How many different weeks users bought something. - `Active hours watching`: goal `video_play`, interval `1 hour`. How many different hours users started a video. -- `Purchases per active day`: a [Ratio](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio) metric with a `Goal Count` of `purchase` as the numerator and a `Goal Activity Period Count` of `app_open` (1 day) as the denominator. +- `Purchases per active day`: a [Ratio](./ratio.mdx) metric with a `Goal Count` of `purchase` as the numerator and a `Goal Activity Period Count` of `app_open` (1 day) as the denominator. ## Good to know @@ -69,5 +69,5 @@ Because the value counts periods rather than dividing by them, it grows the long - Less sensitive to bursts than `Goal Count`, because repeat events in the same period add nothing. - Filters on the goal apply before periods are counted, so `Active days with a purchase in category ZYZ123` only counts days with a matching purchase. - If you cancel goal events, a period stops counting only when every event in it has been cancelled. -- If you use [CUPED](/docs/web-console-docs/goals-and-metrics/metrics/variance-reduction-cuped), the pre-exposure covariate is the same count of active periods, measured over the lookback window before exposure. +- If you use [CUPED](../variance-reduction-cuped.mdx), the pre-exposure covariate is the same count of active periods, measured over the lookback window before exposure. - Changing the activity interval changes what the metric means and requires a new metric version. diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count.mdx index 870ca0ba..803ac7dc 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count.mdx @@ -28,23 +28,23 @@ Three users in the same variant are exposed to the experiment: In the experiment results, this variant would show a **Value** of 11 (2 + 9 + 0 purchases in total) and a **Mean** of 11 / 3 = **3.6667** purchases per participant. -Compare that with a [`Goal Unique Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-unique-count) on the same goal, which only asks whether each user purchased: Ana 1, Ben 1 and Cara 0, so a **Value** of 2 and a **Mean** of **66.67%**. The unique count says two out of three users bought something. The goal count says how much buying happened, and most of it came from Ben. +Compare that with a [`Goal Unique Count`](./goal-unique-count.mdx) on the same goal, which only asks whether each user purchased: Ana 1, Ben 1 and Cara 0, so a **Value** of 2 and a **Mean** of **66.67%**. The unique count says two out of three users bought something. The goal count says how much buying happened, and most of it came from Ben. ## Creating the metric -When [creating a metric](/docs/web-console-docs/goals-and-metrics/metrics/create), choose `Goal Count` as the **Metric type**, then: +When [creating a metric](../create.mdx), choose `Goal Count` as the **Metric type**, then: 1. Select the **Goal** you want to count, for example `purchase`. 2. Optionally set an **Outliers limit method** to cap heavy users (see below). 3. Optionally add **Metric property filters** to count only matching events, for example purchases where `category_id` is `ZYZ123`. 4. Optionally use **Add time filters** to count only events within a time range relative to exposure. -5. Optionally use **Add cancellation** under **Goal relations** so that cancelled events stop counting. The goal and the cancellation event need a shared key property, such as an order number. See [Cancellation](/docs/web-console-docs/goals-and-metrics/metrics/create#cancellation). +5. Optionally use **Add cancellation** under **Goal relations** so that cancelled events stop counting. The goal and the cancellation event need a shared key property, such as an order number. See [Cancellation](../create.mdx#cancellation). The goal is the only required field. `Add refund` and `Add replacement` are not available for this metric type. ## Capping heavy users -A few very active users can dominate a count and make the results noisy. [Outlier limits](/docs/web-console-docs/goals-and-metrics/metrics/create#outliers) cap each user's total count, not individual events. +A few very active users can dominate a count and make the results noisy. [Outlier limits](../create.mdx#outliers) cap each user's total count, not individual events. In the example above, with the `Fixed` method, a **Lower limit value** of 0 and an **Upper limit value** of 5: @@ -60,7 +60,7 @@ Users with no events are never raised to the lower limit. They stay at 0. ## Reading the results -In the [metric results table](/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results), **Value** is the total number of events across all participants in the variant, and **Mean** is that total divided by the number of participants. The impact is calculated on the Mean, as a continuous metric. If the metric uses CUPED, both Value and Mean are CUPED-adjusted. Value is still shown rounded to a whole number. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the total number of events across all participants in the variant, and **Mean** is that total divided by the number of participants. The impact is calculated on the Mean, as a continuous metric. If the metric uses CUPED, both Value and Mean are CUPED-adjusted. Value is still shown rounded to a whole number. A change in the Mean can come from more users doing the action, or from the same users doing it more often. To tell those apart, look at a `Goal Unique Count` on the same goal next to it. @@ -69,7 +69,7 @@ A change in the Mean can come from more users doing the action, or from the same - `Total purchases`: goal `purchase`. How many orders users placed. - `Purchases in category ZYZ123`: goal `purchase` with a property filter on `category_id`. How many orders in one category. - `Searches`: goal `search`. How often users searched. -- `Purchases per visit`: a [Ratio](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio) metric with a `Goal Count` of `purchase` as the numerator and a `Goal Count` of `session_start` as the denominator. +- `Purchases per visit`: a [Ratio](./ratio.mdx) metric with a `Goal Count` of `purchase` as the numerator and a `Goal Count` of `session_start` as the denominator. ## Good to know diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-unique-count.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-unique-count.mdx index 90eed05d..6ee64c92 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-unique-count.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-unique-count.mdx @@ -29,11 +29,11 @@ Four users are exposed to the experiment: In the experiment results, this group would show a **Value** of 2 (two users purchased) and a **Mean** of 2 / 4 = **50.00%**, the conversion rate. -Compare that with a [`Goal Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count) on the same goal, which counts every event: Ana 3, Ben 1, Cara 0 and Dan 0, so a **Value** of 4 and a **Mean** of 1.0000 purchases per participant. The goal count tells you how much people bought. The unique count tells you how many people bought at all. +Compare that with a [`Goal Count`](./goal-count.mdx) on the same goal, which counts every event: Ana 3, Ben 1, Cara 0 and Dan 0, so a **Value** of 4 and a **Mean** of 1.0000 purchases per participant. The goal count tells you how much people bought. The unique count tells you how many people bought at all. ## Creating the metric -When [creating a metric](/docs/web-console-docs/goals-and-metrics/metrics/create), choose `Goal Unique Count` as the **Metric type**, then: +When [creating a metric](../create.mdx), choose `Goal Unique Count` as the **Metric type**, then: 1. Select the **Goal** you want to measure, for example `purchase`. 2. Optionally add **Metric property filters**, for example on `category_id`. A user then converts only if at least one of their events matches. @@ -42,7 +42,7 @@ The **Outliers limit method** can't be changed for this metric type, since each ## Reading the results -In the [metric results table](/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results), **Value** is the number of participants in the variant who triggered the goal at least once, and **Mean** is that number divided by the number of participants: the conversion rate. When CUPED is applied in an analysis, both columns show CUPED-adjusted values, so **Value** is no longer an exact count of converters. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the number of participants in the variant who triggered the goal at least once, and **Mean** is that number divided by the number of participants: the conversion rate. When CUPED is applied in an analysis, both columns show CUPED-adjusted values, so **Value** is no longer an exact count of converters. By default the Mean is shown as a percentage with two decimals, for example `50.00%`. You can change this with the **Format**, **Scale** and **Precision** fields under **Mean**. @@ -51,11 +51,11 @@ By default the Mean is shown as a percentage with two decimals, for example `50. - `Purchasers`: goal `purchase`. The share of users who bought something. - `Sign-up conversion`: goal `sign_up`. The share of users who created an account. - `Purchasers in category ZYZ123`: goal `purchase`, with a property filter on `category_id`. The share of users who bought from that category. -- `Purchases per purchaser`: a [Ratio](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio) metric with `Goal Count` of `purchase` as the **Numerator type** and `Goal Unique Count` of `purchase` as the **Denominator type**. +- `Purchases per purchaser`: a [Ratio](./ratio.mdx) metric with `Goal Count` of `purchase` as the **Numerator type** and `Goal Unique Count` of `purchase` as the **Denominator type**. ## Good to know - A few very active users can't skew the result, because each user counts at most once. That's also why outlier limits don't apply. -- It doesn't show how often users do something. Use a [`Goal Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count) for volume, or a [`Goal Activity Period Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/activity-per-period) for how regularly they come back. +- It doesn't show how often users do something. Use a [`Goal Count`](./goal-count.mdx) for volume, or a [`Goal Activity Period Count`](./activity-per-period.mdx) for how regularly they come back. - If you add a cancellation under **Goal relations**, a user stops counting as converted only when every event that counted for them has been cancelled. Cancelling one of Ana's three purchases leaves her at 1. -- If you use [CUPED](/docs/web-console-docs/goals-and-metrics/metrics/variance-reduction-cuped), the pre-exposure covariate is whether the user triggered the same goal before they were exposed. When CUPED is applied in an analysis, the adjusted values are no longer just 0 or 1, so the metric is analysed as a continuous metric instead of a binomial one. +- If you use [CUPED](../variance-reduction-cuped.mdx), the pre-exposure covariate is whether the user triggered the same goal before they were exposed. When CUPED is applied in an analysis, the adjusted values are no longer just 0 or 1, so the metric is analysed as a continuous metric instead of a binomial one. diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/property.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/property.mdx index 44f74108..1b3bbe32 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/property.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/property.mdx @@ -10,7 +10,7 @@ A `Goal Property` metric answers the question: **how much of this did each user You pick a goal and one of its numeric properties, such as `price`, `quantity` or `duration`. For each user, ABsmartly adds up that property across all of their goal events. Two orders of 40 and 25 give that user a value of 65. -This is the metric type behind revenue, items sold, time watched and any other amount carried in the event. It's also the only type that supports [refunds and replacements](#refunds-and-replacements), including when it's used as the numerator or denominator of a [Ratio](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio). That lets you measure net revenue rather than gross. +This is the metric type behind revenue, items sold, time watched and any other amount carried in the event. It's also the only type that supports [refunds and replacements](#refunds-and-replacements), including when it's used as the numerator or denominator of a [Ratio](./ratio.mdx). That lets you measure net revenue rather than gross. ## How it's calculated @@ -33,13 +33,13 @@ Three users are exposed to the experiment: In the experiment results, this group would show a **Value** of 180 (65 + 115 + 0) and a **Mean** of 180 / 3 = **60** per participant. -Compare that with a [`Goal Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count) on the same goal, which counts orders instead of adding up their price: Ana 2, Ben 1 and Cara 0, so a **Value** of 3 and a **Mean** of 1. Ana places more orders, but Ben spends more. A change that gets people to buy more often and a change that gets them to spend more per order can look very different on these two metrics. +Compare that with a [`Goal Count`](./goal-count.mdx) on the same goal, which counts orders instead of adding up their price: Ana 2, Ben 1 and Cara 0, so a **Value** of 3 and a **Mean** of 1. Ana places more orders, but Ben spends more. A change that gets people to buy more often and a change that gets them to spend more per order can look very different on these two metrics. If the property is missing on an event, or isn't a number, that event adds 0. Numbers sent as strings, such as `"12.50"`, are converted and counted. ## Creating the metric -When [creating a metric](/docs/web-console-docs/goals-and-metrics/metrics/create), choose `Goal Property` as the metric type, then: +When [creating a metric](../create.mdx), choose `Goal Property` as the metric type, then: 1. Select the goal you want to measure, for example `purchase`. 2. In **Property**, enter the name of the numeric property, for example `price`. The field suggests properties as you type. For a nested property, separate the levels with `/`, for example `cart/total`. @@ -48,7 +48,7 @@ When [creating a metric](/docs/web-console-docs/goals-and-metrics/metrics/create The property is required and can be up to 256 characters long. -To show amounts as money, set the **Format** fields in the [Format, Scale & Precision](/docs/web-console-docs/goals-and-metrics/metrics/create#format-scale-and-precisions) section, for example `€{}` or `${}`. The Value and the Mean each have their own Format. +To show amounts as money, set the **Format** fields in the [Format, Scale & Precision](../create.mdx#format-scale-and-precisions) section, for example `€{}` or `${}`. The Value and the Mean each have their own Format. ## Refunds and replacements @@ -101,9 +101,9 @@ You can combine a refund or replacement with a cancellation. If an order is canc ## Reading the results -In the [metric results table](/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results), **Value** is the total of the property across all participants in the variant, after any refunds, replacements and cancellations. **Mean** is that total divided by the number of participants. The impact is calculated on the Mean. If CUPED is applied to the metric, the Value and Mean shown are CUPED-adjusted. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the total of the property across all participants in the variant, after any refunds, replacements and cancellations. **Mean** is that total divided by the number of participants. The impact is calculated on the Mean. If CUPED is applied to the metric, the Value and Mean shown are CUPED-adjusted. -Because every participant counts in the Mean, including those who never bought anything, a revenue metric's Mean is revenue per participant, not revenue per order. To measure average order value, use a [Ratio](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio) metric instead. +Because every participant counts in the Mean, including those who never bought anything, a revenue metric's Mean is revenue per participant, not revenue per order. To measure average order value, use a [Ratio](./ratio.mdx) metric instead. ## More examples @@ -112,7 +112,7 @@ Because every participant counts in the Mean, including those who never bought a - `Items sold`: goal `purchase`, property `quantity`. - `Shipping revenue`: goal `purchase`, property `cart/shipping`. - `Time watched`: goal `video_progress`, property `seconds_watched`. -- `Average order value`: a [Ratio](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio) metric with a `Goal Property` of `price` as the numerator and a `Goal Count` of `purchase` as the denominator. +- `Average order value`: a [Ratio](./ratio.mdx) metric with a `Goal Property` of `price` as the numerator and a `Goal Count` of `purchase` as the denominator. ## Good to know diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio.mdx index 859e7b29..df0f30d1 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio.mdx @@ -34,11 +34,11 @@ The totals are 4 clicks and 10 page views, so the ratio is 4 / 10 = **0.4** clic This is a ratio of totals, not an average of each user's own ratio. Averaging Ana (0.5), Ben (1) and Cara (0) would give 0.5, and Dan would have no ratio at all. With a ratio of totals, users with more page views carry more weight, and every participant can be included. -Compare that with a [`Goal Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count) of `click` on the same data: a **Value** of 4 clicks and a **Mean** of 4 / 4 = 1 click per participant. The `Goal Count` tells you how much users clicked. The ratio tells you how often a page view led to a click. +Compare that with a [`Goal Count`](./goal-count.mdx) of `click` on the same data: a **Value** of 4 clicks and a **Mean** of 4 / 4 = 1 click per participant. The `Goal Count` tells you how much users clicked. The ratio tells you how often a page view led to a click. ## Creating the metric -When [creating a metric](/docs/web-console-docs/goals-and-metrics/metrics/create), choose `Ratio` as the metric type, then: +When [creating a metric](../create.mdx), choose `Ratio` as the metric type, then: 1. In **Numerator Configuration**, pick a **Numerator type** and set it up as you would that metric type: the **Goal**, plus the **Property**, **Activity interval** or **Retention period** if the type needs one, **Metric property filters** and, where the type allows it, **Outliers limit method**. 2. In **Denominator Configuration**, do the same with a **Denominator type**. The denominator goal must share a datasource with the numerator goal. @@ -59,7 +59,7 @@ With `Require denominator` set, a participant's numerator only counts if their d ## Reading the results -In the [metric results table](/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results), **Value** and **Mean** both show the ratio for the variant, and the **Metric total** row shows the total numerator divided by the total denominator across all variants. Unless the **GST** switch is on, you can hover over a variant's Value to see its numerator and denominator totals, and over its Mean to see their averages per participant. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** and **Mean** both show the ratio for the variant, and the **Metric total** row shows the total numerator divided by the total denominator across all variants. Unless the **GST** switch is on, you can hover over a variant's Value to see its numerator and denominator totals, and over its Mean to see their averages per participant. The **Relative impact** compares the ratio between variants, as a continuous metric. The **Impact per day** column shows `--` for ratio metrics. @@ -72,11 +72,11 @@ A ratio can move because either side moved. If the ratio changes, check the Valu - `Click-through rate`: `Goal Count` of `click` divided by `Goal Count` of `page_view`. - `Average order value`: `Goal Property` of `purchase` (`revenue`) divided by `Goal Count` of `purchase`. - `Items per order`: `Goal Property` of `purchase` (`items`) divided by `Goal Count` of `purchase`. -- `Purchases per active day`: `Goal Count` of `purchase` divided by [`Goal Activity Period Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/activity-per-period) of `app_open` (1 day). +- `Purchases per active day`: `Goal Count` of `purchase` divided by [`Goal Activity Period Count`](./activity-per-period.mdx) of `app_open` (1 day). - `Payments per checkout`: `Goal Unique Count` of `payment` divided by `Goal Unique Count` of `checkout`, with `Require denominator`. ## Good to know - **Metric property filters**, **Outliers limit method**, **Time filter** and **Goal relations** are set separately for the numerator and the denominator, and each side uses its own settings. -- If you use [CUPED](/docs/web-console-docs/goals-and-metrics/metrics/variance-reduction-cuped), the numerator and denominator are each adjusted using their own pre-exposure value over the same lookback period. The Numerator and Denominator shown in the tooltips are the adjusted values. +- If you use [CUPED](../variance-reduction-cuped.mdx), the numerator and denominator are each adjusted using their own pre-exposure value over the same lookback period. The Numerator and Denominator shown in the tooltips are the adjusted values. - If the denominator total for a variant is 0, the ratio shows 0. diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/retention.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/retention.mdx index d08014c1..514adfd8 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/retention.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/retention.mdx @@ -32,11 +32,11 @@ With **First exposure**, this group would show a **Value** of 2 (Ana and Cara) a With **First achievement**, the **Value** is 1 (Ana only) and the **Mean** is 1 / 3, about **33%**. Here the question becomes "did they buy again at least 7 days after their first purchase?". -Compare that with a [`Goal Unique Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-unique-count) on the same goal, which counts anyone who purchased at all: a **Value** of 3 and a **Mean** of **100%**. Retention leaves out Ben, who bought twice but only in the first week. +Compare that with a [`Goal Unique Count`](./goal-unique-count.mdx) on the same goal, which counts anyone who purchased at all: a **Value** of 3 and a **Mean** of **100%**. Retention leaves out Ben, who bought twice but only in the first week. ## Creating the metric -When [creating a metric](/docs/web-console-docs/goals-and-metrics/metrics/create), choose `Goal Retention` as the metric type, then: +When [creating a metric](../create.mdx), choose `Goal Retention` as the metric type, then: 1. Select the goal you want to measure, for example `purchase`. 2. Set the **Retention period**: a number from 1 to 30 and a unit (`Seconds`, `Minutes`, `Hours`, `Days`, `Weeks` or `Months`). A month is 30 days. The default is 1 day. @@ -54,7 +54,7 @@ If you add property filters, only matching events count, both for the first achi ## Reading the results -In the [metric results table](/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results), **Value** is the number of retained participants in the variant, and **Mean** is that number divided by the number of participants, shown as a percentage. It's analysed as a binomial metric, like `Goal Unique Count`. If the metric uses CUPED, Value and Mean are CUPED-adjusted, so Value is no longer a whole number of users. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the number of retained participants in the variant, and **Mean** is that number divided by the number of participants, shown as a percentage. It's analysed as a binomial metric, like `Goal Unique Count`. If the metric uses CUPED, Value and Mean are CUPED-adjusted, so Value is no longer a whole number of users. Users exposed less than one retention period ago haven't had the chance to be retained yet, but they still count as participants with a value of 0. So the Mean starts low and tends to rise as the experiment runs, and it reads lower than the true retention rate while recent users are still in their retention period. Random assignment gives both variants a similar mix of exposure times, so the comparison stays fair, but read the raw percentage with that in mind. The longer the retention period, the stronger the effect. @@ -63,9 +63,9 @@ Users exposed less than one retention period ago haven't had the chance to be re - `Purchase retention (7 days)`: goal `purchase`, `7 Days` after `First exposure`. The share of users who bought something a week or more after seeing the experiment. - `Repeat purchase (30 days)`: goal `purchase`, `30 Days` after `First achievement`. The share of users who bought again at least 30 days after their first purchase. - `App return (1 day)`: goal `app_open`, `1` `Days` after `First exposure`. The share of users who opened the app at any point from 24 hours after exposure, whether that's day 2 or day 30. -- `Returned in week 2`: goal `app_open`, `7 Days` after `First exposure`, with a [time filter](/docs/web-console-docs/goals-and-metrics/metrics/create#time-filters) of `At most` 14 days. Adding the time filter caps the window, so only returns between day 7 and day 14 count. +- `Returned in week 2`: goal `app_open`, `7 Days` after `First exposure`, with a [time filter](../create.mdx#time-filters) of `At most` 14 days. Adding the time filter caps the window, so only returns between day 7 and day 14 count. ## Good to know -- With `First exposure`, you can count only returns within a window by adding an `At most` [time filter](/docs/web-console-docs/goals-and-metrics/metrics/create#time-filters), as in `Returned in week 2` above. -- If you use [CUPED](/docs/web-console-docs/goals-and-metrics/metrics/variance-reduction-cuped), the lookback window must be longer than the retention period, not equal to it. A 7-day retention period needs a lookback of at least 2 weeks, and since the longest lookback is 4 weeks, retention periods of 4 weeks or more can't use CUPED. +- With `First exposure`, you can count only returns within a window by adding an `At most` [time filter](../create.mdx#time-filters), as in `Returned in week 2` above. +- If you use [CUPED](../variance-reduction-cuped.mdx), the lookback window must be longer than the retention period, not equal to it. A 7-day retention period needs a lookback of at least 2 weeks, and since the longest lookback is 4 weeks, retention periods of 4 weeks or more can't use CUPED. diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/time-to-achievement.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/time-to-achievement.mdx index d1ec650f..482f7c5e 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/time-to-achievement.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/time-to-achievement.mdx @@ -32,11 +32,11 @@ In the experiment results, this group would show a **Value** of `3 days, 2 hrs` Ana's second purchase on Wednesday adds nothing, and Cara pulls the Mean down even though she never bought anything. -Compare that with a [`Goal Unique Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-unique-count) on the same goal, which counts whether each user purchased at all: Ana 1, Ben 1 and Cara 0, so a **Value** of 2 and a **Mean** of 66.67%. The unique count tells you how many users got there. The time to achievement adds how long they took, mixed with how many got there. +Compare that with a [`Goal Unique Count`](./goal-unique-count.mdx) on the same goal, which counts whether each user purchased at all: Ana 1, Ben 1 and Cara 0, so a **Value** of 2 and a **Mean** of 66.67%. The unique count tells you how many users got there. The time to achievement adds how long they took, mixed with how many got there. ## Creating the metric -When [creating a metric](/docs/web-console-docs/goals-and-metrics/metrics/create), choose `Goal Time To Achievement` as the metric type, then: +When [creating a metric](../create.mdx), choose `Goal Time To Achievement` as the metric type, then: 1. Choose the **Impact**. It defaults to `Positive`. See [Choosing the impact](#choosing-the-impact) below. 2. Select the **Goal** you want to measure, for example `purchase`. @@ -48,7 +48,7 @@ Values and means are shown as durations, such as `1 day, 40 mins`, using the two ## Reading the results -In the [metric results table](/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results), **Value** is the total time to first achievement across all participants in the variant, and **Mean** is that total divided by the number of participants, including those who never reached the goal. The impact is calculated on the Mean, as with other continuous metrics. If the metric uses CUPED, both Value and Mean are CUPED-adjusted. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the total time to first achievement across all participants in the variant, and **Mean** is that total divided by the number of participants, including those who never reached the goal. The impact is calculated on the Mean, as with other continuous metrics. If the metric uses CUPED, both Value and Mean are CUPED-adjusted. Because users who never reach the goal count as 0, the Mean goes **up** when more users reach the goal, even if nobody got there any faster. In the example above, if Cara had also bought on Friday at 09:00 (4 days after exposure), the Value would rise to `1 wk, 2 hrs` and the Mean to `2 days, 8 hrs`. The variant converted more users, but its Mean looks slower. @@ -61,7 +61,7 @@ Always read it next to a `Goal Unique Count` on the same goal. If the unique cou ### Average time for users who reached the goal -To measure the average wait only for users who reached the goal, create a [Ratio](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio) metric with: +To measure the average wait only for users who reached the goal, create a [Ratio](./ratio.mdx) metric with: - a `Goal Time To Achievement` numerator on your goal, and - a `Goal Unique Count` denominator on the same goal, with the same property filters, time filters and cancellation. @@ -81,7 +81,7 @@ Ratio metrics don't format their values as durations, so the result is a number - `Time to first purchase`: goal `purchase`. How long users take to buy after entering the experiment. - `Time to first search`: goal `search`. How quickly users find and use search. - `Time to activation`: goal `onboarding_completed`. How long users take to finish onboarding. -- `Average time to first purchase for buyers`: a [Ratio](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio) with a `Goal Time To Achievement` numerator and a `Goal Unique Count` denominator, both on `purchase`. +- `Average time to first purchase for buyers`: a [Ratio](./ratio.mdx) with a `Goal Time To Achievement` numerator and a `Goal Unique Count` denominator, both on `purchase`. ## Good to know @@ -89,4 +89,4 @@ Ratio metrics don't format their values as durations, so the result is a number - Property filters and time filters decide which events can count as the first one, but the time is still measured from exposure. With a time filter of `Goal is achieved At least 4 days after first exposure`, a user who buys on day 3 and on day 6 has a value of 6 days. - If you add a cancellation (**Add cancellation** under **Goal relations**), a cancelled event no longer counts. The value becomes the time to the earliest event that hasn't been cancelled, so it can increase. If all of a user's events are cancelled, they go back to 0. Refunds and replacements aren't available for this metric type. - The values can have a very long tail, with a few users who took weeks. To limit their influence, set the **Outliers limit method**, for example to `Fixed` with a **Lower limit value** of `0` and an **Upper limit value** of `604800` (7 days, in seconds). Outlier limits only apply to users who reached the goal, so users who never did stay at 0. -- If you use [CUPED](/docs/web-console-docs/goals-and-metrics/metrics/variance-reduction-cuped), the pre-exposure covariate is the time from the start of the lookback window (the experiment start minus the lookback period) to the user's first goal event before exposure, or 0 if there was none. +- If you use [CUPED](../variance-reduction-cuped.mdx), the pre-exposure covariate is the time from the start of the lookback window (the experiment start minus the lookback period) to the user's first goal event before exposure, or 0 if there was none. diff --git a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/unique-property-count.mdx b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/unique-property-count.mdx index 212b7d68..0704f8d7 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/metric-types/unique-property-count.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/metric-types/unique-property-count.mdx @@ -32,11 +32,11 @@ In the experiment results, this group would show a **Value** of 4 (3 + 1 + 0) an Values are distinct per user, not across the whole experiment. Ana and Ben both viewed P1, so it counts once for each of them. The group viewed only three different products, but the Value is 4. -Compare that with a [`Goal Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-count) on the same goal, which counts every event: Ana 4, Ben 5 and Cara 0, so a **Value** of 9 and a **Mean** of 3.0000. Ben's repeat views make him look like the more active user, while the unique count shows that Ana looked at more products. +Compare that with a [`Goal Count`](./goal-count.mdx) on the same goal, which counts every event: Ana 4, Ben 5 and Cara 0, so a **Value** of 9 and a **Mean** of 3.0000. Ben's repeat views make him look like the more active user, while the unique count shows that Ana looked at more products. ## Creating the metric -When [creating a metric](/docs/web-console-docs/goals-and-metrics/metrics/create), choose `Goal Property Unique Count` as the metric type, then: +When [creating a metric](../create.mdx), choose `Goal Property Unique Count` as the metric type, then: 1. Select the **Goal** you want to measure, for example `product_view`. 2. In **Property**, type the event property whose distinct values you want to count, for example `product_id`. This field is required. @@ -52,7 +52,7 @@ Under **Goal relations**, you can **Add cancellation**. Unlike `Goal Property`, ## Reading the results -In the [metric results table](/docs/web-console-docs/experiments/interpreting-metrics-in-experiment-results), **Value** is the sum of every participant's distinct count in the variant, and **Mean** is that total divided by the number of participants. The impact is calculated on the Mean, as with other continuous metrics such as `Goal Count`. +In the [metric results table](../../../experiments/interpreting-metrics-in-experiment-results.mdx), **Value** is the sum of every participant's distinct count in the variant, and **Mean** is that total divided by the number of participants. The impact is calculated on the Mean, as with other continuous metrics such as `Goal Count`. Because each user's values are counted separately, Value is not the number of different values seen in the variant. If every user viewed the same single product, the Value would equal the number of users who viewed it. @@ -61,7 +61,7 @@ Because each user's values are counted separately, Value is not the number of di - `Products viewed`: goal `product_view`, property `product_id`. How many different products users looked at. - `Categories purchased from`: goal `purchase`, property `category_id`. How many different categories users bought from. - `Articles read`: goal `article_read`, property `article_id`. How many different articles users opened. -- `Products per purchaser`: a [Ratio](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/ratio) metric with a `Goal Property Unique Count` of `purchase` on `product_id` as the numerator and a [`Goal Unique Count`](/docs/web-console-docs/goals-and-metrics/metrics/metric-types/goal-unique-count) of `purchase` as the denominator. How many different products buyers bought, on average. +- `Products per purchaser`: a [Ratio](./ratio.mdx) metric with a `Goal Property Unique Count` of `purchase` on `product_id` as the numerator and a [`Goal Unique Count`](./goal-unique-count.mdx) of `purchase` as the denominator. How many different products buyers bought, on average. ## Good to know diff --git a/docs/web-console-docs/goals-and-metrics/metrics/overview.mdx b/docs/web-console-docs/goals-and-metrics/metrics/overview.mdx index 92a94f95..05c652f4 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/overview.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/overview.mdx @@ -8,13 +8,13 @@ sidebar_position: 1 ## Experimentation Metrics -Metrics are aggregations or computations derived from [goals](/docs/web-console-docs/goals-and-metrics/goals/overview). +Metrics are aggregations or computations derived from [goals](../goals/overview.mdx). They transform raw event data into interpretable measures that quantify the effect of an experiment. Metrics summarize performance over a group of experiment visitors — for example, `conversion rate`, `Average revenue per visitor`, or `click-through rate`. Metrics can represent direct business outcomes, engagement signals, or technical performance indicators, -and are often grouped into [categories](/docs/web-console-docs/goals-and-metrics/metrics/categories) such as `conversion`, `engagement`, `retention`, or `revenue`. +and are often grouped into [categories](categories.mdx) such as `conversion`, `engagement`, `retention`, or `revenue`. ## Understanding Experimentation Metrics @@ -265,7 +265,7 @@ The following permissions exist when managing and working with `metrics`. #### Global access -Permission to create and manage `metrics` can be granted to the relevant users through their [role](/docs/web-console-docs/configuration/settings#roles) at the platform level. +Permission to create and manage `metrics` can be granted to the relevant users through their [role](../../configuration/settings.mdx#roles) at the platform level. :::info It is not recommended to provide access to `metrics` to non platform admin users at the platform level. diff --git a/docs/web-console-docs/launchpad-browser-extension/getting-started.mdx b/docs/web-console-docs/launchpad-browser-extension/getting-started.mdx index 93b745ed..36af6410 100644 --- a/docs/web-console-docs/launchpad-browser-extension/getting-started.mdx +++ b/docs/web-console-docs/launchpad-browser-extension/getting-started.mdx @@ -36,7 +36,7 @@ First you need to download and install the LaunchPad as a Chrome extension. This 4. Select **JWT from Browser Cookie** to use the ABsmartly cookie. 5. Click **Authenticate in ABsmartly** to connect to your ABsmartly's instance. 6. You are now ready to use the ABsmartly's LaunchPad to create new experiments. -7. Check our [how-to guide](/docs/web-console-docs/launchpad-browser-extension/creating-an-experiment-with-the-launchpad) to create your first experiment. +7. Check our [how-to guide](creating-an-experiment-with-the-launchpad.mdx) to create your first experiment. ### How It Works diff --git a/docs/web-console-docs/users-teams-permissions/ownership-and-permissions.mdx b/docs/web-console-docs/users-teams-permissions/ownership-and-permissions.mdx index 82cb163a..2053c6eb 100644 --- a/docs/web-console-docs/users-teams-permissions/ownership-and-permissions.mdx +++ b/docs/web-console-docs/users-teams-permissions/ownership-and-permissions.mdx @@ -11,7 +11,7 @@ In this document we will discuss those changes and how you can start making use Experiment Assets in scope: **Experiments**, **Features**, **Templates**, **Metrics** & **Goals**. -All other configuration settings are managed using global roles. For more details see our [Roles](/docs/web-console-docs/users-teams-permissions/roles) page. +All other configuration settings are managed using global roles. For more details see our [Roles](./roles.mdx) page. --- diff --git a/docs/web-console-docs/users-teams-permissions/roles.mdx b/docs/web-console-docs/users-teams-permissions/roles.mdx index 56140956..ffec34f4 100644 --- a/docs/web-console-docs/users-teams-permissions/roles.mdx +++ b/docs/web-console-docs/users-teams-permissions/roles.mdx @@ -57,8 +57,8 @@ This role should only be granted to the person(s) managing the platform. While the 2 roles mentioned above cover most usecases, your organisation might have specific needs. In this case custom roles can be created and assigned to certain users as needed. -For example, custom roles could be created for allowing some users to create and manage [Units](/docs/web-console-docs/configuration/units), -[Applications](/docs/web-console-docs/configuration/applications), API Keys, etc which otherwise can only be managed by the `FullAdmin`. +For example, custom roles could be created for allowing some users to create and manage [Units](../configuration/units.mdx), +[Applications](../configuration/applications.mdx), API Keys, etc which otherwise can only be managed by the `FullAdmin`. ### Assigning Global Roles @@ -119,6 +119,6 @@ Global `FullAdmin` or users with `Team Admin` on that team, can invite users to ## Ownership and Permissions model for Experiment Assets -Read our [The Ownership Model](/docs/web-console-docs/users-teams-permissions/ownership-and-permissions) for a more detailed explanation on how to manage ownership and permissions for Experiment Assets. +Read our [The Ownership Model](./ownership-and-permissions.mdx) for a more detailed explanation on how to manage ownership and permissions for Experiment Assets. diff --git a/docs/web-console-docs/warehouse-native/connect/bigquery.mdx b/docs/web-console-docs/warehouse-native/connect/bigquery.mdx index dd677d03..37e5cf49 100644 --- a/docs/web-console-docs/warehouse-native/connect/bigquery.mdx +++ b/docs/web-console-docs/warehouse-native/connect/bigquery.mdx @@ -148,8 +148,8 @@ The staging dataset holds only objects ABsmartly owns: the `json_layouts` table The staging dataset requirements depend on the feature: -- **JSON layouts** (auto-complete for JSON properties in the metric editor) require a staging dataset under **Trust relationship**. They stay turned off until you set a **Staging dataset**. With **Service account key (JSON)**, a staging dataset is optional for JSON layouts: without one, they use the ABsmartly dataset. See [JSON layouts table](/docs/web-console-docs/warehouse-native/get-started#json-layouts-table). -- **Exposures import** _(Hybrid only)_ requires a staging dataset with either **Service account key (JSON)** or **Trust relationship** authentication. The import creates a temporary external table, so it needs a staging dataset to create it in. ABsmartly won't save a data source with an exposures import, or run **Test exposures import**, until you set a **Staging dataset**. A data source saved earlier without a staging dataset keeps failing Hybrid metric queries until you add one, and its next save requires it. See [Exposures import](/docs/web-console-docs/warehouse-native/get-started#step-4-configure-exposures-import-hybrid-only). +- **JSON layouts** (auto-complete for JSON properties in the metric editor) require a staging dataset under **Trust relationship**. They stay turned off until you set a **Staging dataset**. With **Service account key (JSON)**, a staging dataset is optional for JSON layouts: without one, they use the ABsmartly dataset. See [JSON layouts table](../get-started.mdx#json-layouts-table). +- **Exposures import** _(Hybrid only)_ requires a staging dataset with either **Service account key (JSON)** or **Trust relationship** authentication. The import creates a temporary external table, so it needs a staging dataset to create it in. ABsmartly won't save a data source with an exposures import, or run **Test exposures import**, until you set a **Staging dataset**. A data source saved earlier without a staging dataset keeps failing Hybrid metric queries until you add one, and its next save requires it. See [Exposures import](../get-started.mdx#step-4-configure-exposures-import-hybrid-only). We recommend a staging dataset for every BigQuery data source, including Warehouse Native deployments without exposures import. It is where ABsmartly creates and maintains the tables it owns, so it keeps them out of your ABsmartly dataset and lets JSON layouts work under either authentication method. @@ -172,7 +172,7 @@ bq update --source ds.json : ### 5. Grant access to the exposures staging bucket _(Hybrid only)_ -Skip this step unless you use [Exposures import](/docs/web-console-docs/warehouse-native/get-started#step-4-configure-exposures-import-hybrid-only). With a **Trust relationship** data source, BigQuery reads the staged files as ABsmartly's service account, so grant this role even if the **Exposures staging** section uses **Access key (HMAC)**. If **Exposures staging** also uses **Trust relationship**, the same role lets ABsmartly write the files. +Skip this step unless you use [Exposures import](../get-started.mdx#step-4-configure-exposures-import-hybrid-only). With a **Trust relationship** data source, BigQuery reads the staged files as ABsmartly's service account, so grant this role even if the **Exposures staging** section uses **Access key (HMAC)**. If **Exposures staging** also uses **Trust relationship**, the same role lets ABsmartly write the files. Put the bucket in the same location as your staging and source datasets. If those datasets are in the `US` or `EU` multi-region, the bucket can also be in a single region inside it (for example `europe-west1` for `EU`). BigQuery reads the staged files through an external table, which can't read a bucket outside the dataset's location. @@ -225,4 +225,4 @@ If the test fails, double-check your credentials and make sure ABsmartly's IP ad With **Trust relationship**, a failed test shows the missing role and resource (for example "Missing BigQuery Job User on ``") with a **See permissions** link. **Test connection** doesn't exercise inserts, so a missing **Service Usage Consumer** grant on a separate job project shows up later as failed writes, not as a failed test. ::: -Once connected, save the data source and proceed to [map your tables](/docs/web-console-docs/warehouse-native/get-started#step-2-map-your-tables). +Once connected, save the data source and proceed to [map your tables](../get-started.mdx#step-2-map-your-tables). diff --git a/docs/web-console-docs/warehouse-native/connect/clickhouse.mdx b/docs/web-console-docs/warehouse-native/connect/clickhouse.mdx index 65c7bb40..a0ca1e6f 100644 --- a/docs/web-console-docs/warehouse-native/connect/clickhouse.mdx +++ b/docs/web-console-docs/warehouse-native/connect/clickhouse.mdx @@ -30,4 +30,4 @@ Click **Test connection** at the bottom of the form. If everything is configured If the test fails, double-check your credentials and make sure ABsmartly's IP addresses are allowed through your ClickHouse firewall or network policies. ::: -Once connected, save the data source and proceed to [map your tables](/docs/web-console-docs/warehouse-native/get-started#step-2-map-your-tables). +Once connected, save the data source and proceed to [map your tables](../get-started.mdx#step-2-map-your-tables). diff --git a/docs/web-console-docs/warehouse-native/connect/databricks.mdx b/docs/web-console-docs/warehouse-native/connect/databricks.mdx index 0e292dc7..e8e89144 100644 --- a/docs/web-console-docs/warehouse-native/connect/databricks.mdx +++ b/docs/web-console-docs/warehouse-native/connect/databricks.mdx @@ -31,4 +31,4 @@ Click **Test connection** at the bottom of the form. If everything is configured If the test fails, double-check your credentials and make sure ABsmartly's IP addresses are allowed through your Databricks workspace network settings. ::: -Once connected, save the data source and proceed to [map your tables](/docs/web-console-docs/warehouse-native/get-started#step-2-map-your-tables). +Once connected, save the data source and proceed to [map your tables](../get-started.mdx#step-2-map-your-tables). diff --git a/docs/web-console-docs/warehouse-native/connect/redshift.mdx b/docs/web-console-docs/warehouse-native/connect/redshift.mdx index a38e4256..022c57c1 100644 --- a/docs/web-console-docs/warehouse-native/connect/redshift.mdx +++ b/docs/web-console-docs/warehouse-native/connect/redshift.mdx @@ -31,4 +31,4 @@ Click **Test connection** at the bottom of the form. If everything is configured If the test fails, double-check your credentials and make sure ABsmartly's IP addresses are allowed through your Redshift cluster's security groups and VPC settings. ::: -Once connected, save the data source and proceed to [map your tables](/docs/web-console-docs/warehouse-native/get-started#step-2-map-your-tables). +Once connected, save the data source and proceed to [map your tables](../get-started.mdx#step-2-map-your-tables). diff --git a/docs/web-console-docs/warehouse-native/connect/snowflake.mdx b/docs/web-console-docs/warehouse-native/connect/snowflake.mdx index 5d8b40ab..eeef9337 100644 --- a/docs/web-console-docs/warehouse-native/connect/snowflake.mdx +++ b/docs/web-console-docs/warehouse-native/connect/snowflake.mdx @@ -31,4 +31,4 @@ Click **Test connection** at the bottom of the form. If everything is configured If the test fails, double-check your credentials and make sure ABsmartly's IP addresses are allowed through your Snowflake network policies. ::: -Once connected, save the data source and proceed to [map your tables](/docs/web-console-docs/warehouse-native/get-started#step-2-map-your-tables). +Once connected, save the data source and proceed to [map your tables](../get-started.mdx#step-2-map-your-tables). diff --git a/docs/web-console-docs/warehouse-native/get-started.mdx b/docs/web-console-docs/warehouse-native/get-started.mdx index 88fd94bb..e355dd7e 100644 --- a/docs/web-console-docs/warehouse-native/get-started.mdx +++ b/docs/web-console-docs/warehouse-native/get-started.mdx @@ -11,7 +11,7 @@ import Image from "../../../src/components/Image"; Warehouse Native lets you run experiments directly on data that lives in your own data warehouse. Instead of sending events to ABsmartly's collectors, you point ABsmartly at your existing tables — exposures, goals, and attributes — and it takes care of the rest. :::tip New to Warehouse Native? -This guide covers connecting and configuring a data source. If you're deciding between **Hybrid** and **Fully** Warehouse Native first, read [Warehouse Native Modes](/docs/web-console-docs/warehouse-native/modes). +This guide covers connecting and configuring a data source. If you're deciding between **Hybrid** and **Fully** Warehouse Native first, read [Warehouse Native Modes](./modes.mdx). ::: Getting started takes three steps: @@ -27,7 +27,7 @@ Getting started takes three steps: To begin, navigate to **Settings → Data Sources** and click **Add data source**. :::note The default data source -Every installation ships with a built-in **default** data source, managed by ABsmartly. In [Hybrid mode](/docs/web-console-docs/warehouse-native/modes#hybrid-warehouse-native) you keep this default and add external data sources for your goals. In [Fully mode](/docs/web-console-docs/warehouse-native/modes#fully-warehouse-native) your own warehouse becomes the default. Exposure events always come from the default data source, so which one is the default determines your mode. +Every installation ships with a built-in **default** data source, managed by ABsmartly. In [Hybrid mode](./modes.mdx#hybrid-warehouse-native) you keep this default and add external data sources for your goals. In [Fully mode](./modes.mdx#fully-warehouse-native) your own warehouse becomes the default. Exposure events always come from the default data source, so which one is the default determines your mode. ::: You'll see a form with two sections: general information about the data source, and the connection credentials specific to your warehouse type. @@ -40,11 +40,11 @@ Start by giving your data source a **name** and an optional **description**. The Select your warehouse from the **Database type** dropdown. ABsmartly supports five warehouse types — follow the guide for yours: -- **[BigQuery](/docs/web-console-docs/warehouse-native/connect/bigquery)** -- **[Snowflake](/docs/web-console-docs/warehouse-native/connect/snowflake)** -- **[ClickHouse](/docs/web-console-docs/warehouse-native/connect/clickhouse)** -- **[Redshift](/docs/web-console-docs/warehouse-native/connect/redshift)** -- **[Databricks](/docs/web-console-docs/warehouse-native/connect/databricks)** +- **[BigQuery](./connect/bigquery.mdx)** +- **[Snowflake](./connect/snowflake.mdx)** +- **[ClickHouse](./connect/clickhouse.mdx)** +- **[Redshift](./connect/redshift.mdx)** +- **[Databricks](./connect/databricks.mdx)** Each guide walks you through the specific credentials needed and how to test the connection. @@ -59,7 +59,7 @@ With your warehouse connected, the next step is to tell ABsmartly where your exp For each table, you can either use the **Column mapping** tab to select columns from a dropdown, or switch to the **SQL query** tab to write a custom query. :::note Which tables apply to your data source -Exposures always come from the **[default data source](/docs/web-console-docs/warehouse-native/modes#the-default-data-source)**, so the exposure mapping below matters most on whichever data source is your default. On an **external** (non-default) data source used in [Hybrid mode](/docs/web-console-docs/warehouse-native/modes#hybrid-warehouse-native), you'll typically map only the **goals** table — exposures are brought in automatically through the [Exposures import](#step-4-configure-exposures-import-hybrid-only) setup rather than mapped here. +Exposures always come from the **[default data source](./modes.mdx#the-default-data-source)**, so the exposure mapping below matters most on whichever data source is your default. On an **external** (non-default) data source used in [Hybrid mode](./modes.mdx#hybrid-warehouse-native), you'll typically map only the **goals** table — exposures are brought in automatically through the [Exposures import](#step-4-configure-exposures-import-hybrid-only) setup rather than mapped here. ::: ### Exposure table @@ -151,7 +151,7 @@ Without this table, experiments will still work — but JSON-property auto-compl ::: :::note -On BigQuery with a **Staging dataset** set, the `json_layouts` table lives in the staging dataset instead. With **Trust relationship** authentication, JSON layouts are turned off until you set one. With **Service account key (JSON)** and no staging dataset, JSON layouts use the ABsmartly dataset. See [Create the staging dataset](/docs/web-console-docs/warehouse-native/connect/bigquery#4-create-the-staging-dataset). +On BigQuery with a **Staging dataset** set, the `json_layouts` table lives in the staging dataset instead. With **Trust relationship** authentication, JSON layouts are turned off until you set one. With **Service account key (JSON)** and no staging dataset, JSON layouts use the ABsmartly dataset. See [Create the staging dataset](./connect/bigquery.mdx#4-create-the-staging-dataset). ::: --- @@ -181,13 +181,13 @@ ABsmartly will show a preview of the computed schedule in both UTC and your loca Match the frequency to your actual ETL schedule. If your data lands once a day at 8 AM UTC, use **Daily at specific time** with a 480-minute offset. Querying more often than data arrives just adds unnecessary load to your warehouse. ::: -Save the data source. If you're setting up [Fully Warehouse Native](/docs/web-console-docs/warehouse-native/modes#fully-warehouse-native) and this warehouse is your **default** data source, you're done - ABsmartly will start querying your warehouse on the configured schedule and your experiment data will flow through automatically. The built-in ABsmartly-managed default data source needs no such configuration, since it isn't a warehouse of yours. If you're connecting an **external** data source for [Hybrid mode](/docs/web-console-docs/warehouse-native/modes#hybrid-warehouse-native), continue to Step 4. +Save the data source. If you're setting up [Fully Warehouse Native](./modes.mdx#fully-warehouse-native) and this warehouse is your **default** data source, you're done - ABsmartly will start querying your warehouse on the configured schedule and your experiment data will flow through automatically. The built-in ABsmartly-managed default data source needs no such configuration, since it isn't a warehouse of yours. If you're connecting an **external** data source for [Hybrid mode](./modes.mdx#hybrid-warehouse-native), continue to Step 4. --- ## Step 4: Configure exposures import _(Hybrid only)_ -This step only applies to **external** (non-default) data sources — the setup used in [Hybrid Warehouse Native](/docs/web-console-docs/warehouse-native/modes#hybrid-warehouse-native). If your warehouse is the default data source, you can skip it. +This step only applies to **external** (non-default) data sources — the setup used in [Hybrid Warehouse Native](./modes.mdx#hybrid-warehouse-native). If your warehouse is the default data source, you can skip it. In Hybrid mode, a goal can live in an external warehouse, but exposures come from the default data source (managed by ABsmartly). To compute metrics for such a goal, ABsmartly needs to make those exposures available to your external warehouse. It does this through an object store that you provide - you point ABsmartly at a storage location it can use, and your warehouse reads the exposures from there. @@ -198,11 +198,11 @@ The **Exposures staging** section configures that storage location: | **Object store URL** | The bucket/prefix ABsmartly uses to stage exposures for your warehouse. The accepted scheme depends on your warehouse (for example, `gs://` for BigQuery, `s3://` for Redshift, and `s3://`, `gs://`, or `azure://` for Snowflake). | | **Credentials** | The access needed to read and write that location — an access key/secret for ClickHouse, a stage name for Snowflake, an IAM role ARN for Redshift. Databricks needs no extra credentials. For BigQuery, pick the method in the section's own **Authentication** dropdown: **Access key (HMAC)** (the default, an access key/secret) or **Trust relationship**. | -With **Trust relationship** on BigQuery, the access key and secret fields are replaced by ABsmartly's service account email: grant that service account **Storage Object User** (`roles/storage.objectUser`) on the staging bucket. The dropdown is independent of the data source's own **Authentication** setting, but BigQuery always reads the staged files with the data source's credentials. That service account needs access to the bucket too: **Storage Object User** for ABsmartly's service account under Trust relationship (see [Grant access to the exposures staging bucket](/docs/web-console-docs/warehouse-native/connect/bigquery#5-grant-access-to-the-exposures-staging-bucket-hybrid-only)), or **Storage Object Viewer** (`roles/storage.objectViewer`) for your own service account under Service account key (JSON). +With **Trust relationship** on BigQuery, the access key and secret fields are replaced by ABsmartly's service account email: grant that service account **Storage Object User** (`roles/storage.objectUser`) on the staging bucket. The dropdown is independent of the data source's own **Authentication** setting, but BigQuery always reads the staged files with the data source's credentials. That service account needs access to the bucket too: **Storage Object User** for ABsmartly's service account under Trust relationship (see [Grant access to the exposures staging bucket](./connect/bigquery.mdx#5-grant-access-to-the-exposures-staging-bucket-hybrid-only)), or **Storage Object Viewer** (`roles/storage.objectViewer`) for your own service account under Service account key (JSON). With **Access key (HMAC)**, the `storage.restrictAuthTypes` organization policy on the bucket's project must allow HMAC authentication. -On BigQuery, Hybrid exposures import requires a [staging dataset](/docs/web-console-docs/warehouse-native/connect/bigquery#4-create-the-staging-dataset) with either **Service account key (JSON)** or **Trust relationship** as the data source's authentication, regardless of the exposures staging **Authentication** choice. The import creates its temporary external table there. ABsmartly won't save a data source with an exposures import, or run **Test exposures import**, until you set a **Staging dataset**. A data source saved earlier without a staging dataset keeps failing Hybrid metric queries until you add one, and its next save requires it. Put the bucket in the same location as the staging and source datasets, or, for a `US` or `EU` multi-region dataset, in a single region inside that multi-region (for example `europe-west1` for `EU`). +On BigQuery, Hybrid exposures import requires a [staging dataset](./connect/bigquery.mdx#4-create-the-staging-dataset) with either **Service account key (JSON)** or **Trust relationship** as the data source's authentication, regardless of the exposures staging **Authentication** choice. The import creates its temporary external table there. ABsmartly won't save a data source with an exposures import, or run **Test exposures import**, until you set a **Staging dataset**. A data source saved earlier without a staging dataset keeps failing Hybrid metric queries until you add one, and its next save requires it. Put the bucket in the same location as the staging and source datasets, or, for a `US` or `EU` multi-region dataset, in a single region inside that multi-region (for example `europe-west1` for `EU`). :::note Staged files are cached and reused for a short window, then cleaned up automatically — no manual cleanup is required. For defense in depth, you can also add a bucket lifecycle rule (e.g. "delete objects older than 1 day") as a backstop. @@ -210,4 +210,4 @@ Staged files are cached and reused for a short window, then cleaned up automatic Save the data source once the exposures import is configured. ABsmartly will then query your warehouse on the configured schedule, evaluating your externally-sourced goals against the exposures automatically. -In [Fully Warehouse Native](/docs/web-console-docs/warehouse-native/modes#fully-warehouse-native), your warehouse is the default and already holds the exposures, so this step doesn't apply. +In [Fully Warehouse Native](./modes.mdx#fully-warehouse-native), your warehouse is the default and already holds the exposures, so this step doesn't apply. diff --git a/docs/web-console-docs/warehouse-native/modes.mdx b/docs/web-console-docs/warehouse-native/modes.mdx index 74af98f0..fe794d95 100644 --- a/docs/web-console-docs/warehouse-native/modes.mdx +++ b/docs/web-console-docs/warehouse-native/modes.mdx @@ -11,7 +11,7 @@ ABsmartly supports two ways of running Warehouse Native, depending on how much o - **Hybrid Warehouse Native** - ABsmartly handles assignment and exposures, while your **goals and metrics** can be computed against your own warehouse. This is set per goal, so you can mix goals that stay with ABsmartly with goals sourced from your warehouse. - **Fully Warehouse Native** - your warehouse holds **everything** - exposures, goals, and attributes - and nothing user-level ever leaves your infrastructure. -Both modes are built on the same foundation: **[data sources](/docs/web-console-docs/warehouse-native/get-started)**. The mode you're in is determined by which data source is your **default**. +Both modes are built on the same foundation: **[data sources](./get-started.mdx)**. The mode you're in is determined by which data source is your **default**. ## The default data source @@ -30,7 +30,7 @@ In Hybrid mode, you keep the ABsmartly-managed data source as your default and a - **Assignment and exposures** are handled by ABsmartly. - **Goals and metrics** are assigned a data source per goal. A goal can be sourced from an external warehouse - where your business data already lives, so results line up with what your BI and finance teams report - or it can stay managed by ABsmartly. You can mix both. -- When a goal is sourced from an external warehouse, ABsmartly makes the default source's exposures available to that warehouse so the two can be evaluated together. You enable this by pointing ABsmartly at an object store through the **[Exposures import](/docs/web-console-docs/warehouse-native/get-started#step-4-configure-exposures-import-hybrid-only)** section on each external data source. +- When a goal is sourced from an external warehouse, ABsmartly makes the default source's exposures available to that warehouse so the two can be evaluated together. You enable this by pointing ABsmartly at an object store through the **[Exposures import](./get-started.mdx#step-4-configure-exposures-import-hybrid-only)** section on each external data source. - Because that import lands the exposures inside your warehouse, **goals sourced from your warehouse can filter and enrich those exposures** the same way Fully mode does - strip out bots and internal traffic, or join in your own attributes table. **Goals that stay managed by ABsmartly don't get this**, since their exposures never leave ABsmartly's default data source. ![Hybrid Warehouse Native architecture: the ABsmartly SDK sends exposures into ABsmartly's default source, which handles unfiltered managed goals directly and also imports exposures into the customer's external warehouse, where imported exposures, goals, and attributes are filtered and enriched before ABsmartly Cloud runs a scheduled query and returns only aggregate results. ABsmartly Cloud retains user-level data for exposures and any goals kept on the managed default source.](/img/warehouse-native/hybrid-architecture.svg) @@ -72,5 +72,5 @@ Exposure-side filtering (bots, scrapers, internal traffic) and attribute enrichm Whichever mode you're targeting, the setup starts the same way — by connecting a data source: -- **[Get Started with Warehouse Native](/docs/web-console-docs/warehouse-native/get-started)** — connect your warehouse, map your tables, and configure data freshness. -- **[Connect your warehouse](/docs/web-console-docs/warehouse-native/get-started#step-1-connect-to-your-data-warehouse)** — step-by-step guides for BigQuery, Snowflake, ClickHouse, Redshift, and Databricks. +- **[Get Started with Warehouse Native](./get-started.mdx)** — connect your warehouse, map your tables, and configure data freshness. +- **[Connect your warehouse](./get-started.mdx#step-1-connect-to-your-data-warehouse)** — step-by-step guides for BigQuery, Snowflake, ClickHouse, Redshift, and Databricks. diff --git a/docs/web-console-docs/warehouse-native/overview.mdx b/docs/web-console-docs/warehouse-native/overview.mdx index 68256b99..f63585f2 100644 --- a/docs/web-console-docs/warehouse-native/overview.mdx +++ b/docs/web-console-docs/warehouse-native/overview.mdx @@ -31,7 +31,7 @@ Warehouse Native comes in two flavors, depending on how much of your data you wa - **Hybrid Warehouse Native** - ABsmartly manages assignment and exposures, while your **goals and metrics** can be computed against your own warehouse. It's set per goal, so you can mix goals managed by ABsmartly with goals sourced from your warehouse. Goals sourced from your warehouse can also be filtered and enriched with your own attributes. - **Fully Warehouse Native** - **everything** lives in your warehouse: exposures, goals, and attributes. No user-level data ever leaves your infrastructure, and you can filter or enrich exposures for every goal. -Which mode you're in is determined by which data source is your **default**. See **[Warehouse Native Modes](/docs/web-console-docs/warehouse-native/modes)** for a full comparison and guidance on choosing. +Which mode you're in is determined by which data source is your **default**. See **[Warehouse Native Modes](./modes.mdx)** for a full comparison and guidance on choosing. ### Supported warehouses @@ -56,4 +56,4 @@ Which mode you're in is determined by which data source is your **default**. See ## Next steps -New to Warehouse Native? Start by understanding the [two modes](/docs/web-console-docs/warehouse-native/modes) — Hybrid and Fully — and which one fits your needs. When you're ready to set it up, head to the [Get Started guide](/docs/web-console-docs/warehouse-native/get-started) to connect your warehouse, map your tables, and configure data freshness. +New to Warehouse Native? Start by understanding the [two modes](./modes.mdx) — Hybrid and Fully — and which one fits your needs. When you're ready to set it up, head to the [Get Started guide](./get-started.mdx) to connect your warehouse, map your tables, and configure data freshness. From 98df8008dd16c661fa649571daf564b3d97c0f1d Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 18:28:07 +0000 Subject: [PATCH 29/43] docs: match H1s to the new titles, throw on broken file links, one link rule - The nine retitled pages now have an H1 matching their title; a build check rejects a bare "# Overview", "# Authentication" or "# Experiment Templates" on hand-written pages. - Replace the deprecated siteConfig.onBrokenMarkdownLinks with markdown.hooks.onBrokenMarkdownLinks: "throw". - AGENTS.md and the write-feature-docs conventions both ask for file links (./page.mdx); AGENTS.md also notes the src/ component tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- .../references/docusaurus-conventions.md | 4 ++-- AGENTS.md | 12 +++++++++--- .../CLI-Documentation/authentication.mdx | 2 +- .../CLI-Documentation/experiment-templates.mdx | 2 +- docs/APIs-and-SDKs/MCP-Server/authentication.mdx | 2 +- docs/APIs-and-SDKs/overview.mdx | 2 +- docs/web-console-docs/experiments/overview.mdx | 2 +- docs/web-console-docs/experiments/templates.mdx | 2 +- .../goals-and-metrics/goals/overview.mdx | 2 +- .../goals-and-metrics/metrics/overview.mdx | 2 +- docs/web-console-docs/overview.mdx | 2 +- docusaurus.config.js | 2 +- plugins/build-checks.test.js | 9 +++++++++ 13 files changed, 30 insertions(+), 15 deletions(-) diff --git a/.claude/skills/write-feature-docs/references/docusaurus-conventions.md b/.claude/skills/write-feature-docs/references/docusaurus-conventions.md index 375f8983..6a065182 100644 --- a/.claude/skills/write-feature-docs/references/docusaurus-conventions.md +++ b/.claude/skills/write-feature-docs/references/docusaurus-conventions.md @@ -72,8 +72,8 @@ Match the neighbors' usage — `:::tip` for guidance, `:::note` for caveats, `:: ## Internal links and anchors -- **Cross-page:** relative path without extension — `[Get Started](./get-started)` or `[Modes](./modes)`. -- **Anchor on another page:** `./get-started#step-4-configure-exposures-import-hybrid-only`. +- **Cross-page:** a file link — the target's source file, with its extension, relative to the file the link is in: `[Get Started](./get-started.mdx)`, `[Create](../create.mdx)`, or `./index.mdx` for a category's index page. Percent-encode spaces (`./SAML%20Role%20Mapping.mdx`). Docusaurus turns it into the page URL, and the build fails (`markdown.hooks.onBrokenMarkdownLinks: "throw"`) when it doesn't resolve. Don't write URL links (`./get-started`, `/docs/...`): the build doesn't resolve them against files, and `./get-started` silently changes target under `trailingSlash: true`. +- **Anchor on another page:** `./get-started.mdx#step-4-configure-exposures-import-hybrid-only`. - **Same-page anchor:** `#the-default-data-source`. - The anchor **slug is the kebab-cased heading text** (lowercased, spaces→hyphens, punctuation dropped, `_italics_` markers dropped). So `## Step 4: Configure exposures import _(Hybrid only)_` → `step-4-configure-exposures-import-hybrid-only`. - **If you rename a heading, update every link that targets its old slug.** Validation (Phase 5) catches broken anchors, but grep for the old slug proactively: diff --git a/AGENTS.md b/AGENTS.md index 2c93fd07..726bc045 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -107,8 +107,12 @@ yarn gen:api ## SEO -- `trailingSlash: true`. Write internal links as absolute `/docs/.../` paths; page-relative links - (`./foo`) break or silently change target under trailing slashes. +- `trailingSlash: true`. Write internal links as file links: the target's source file, with its + extension, relative to the file the link is in (`./get-started.mdx`, `../create.mdx#anchor`, + `./index.mdx` for a category's index page, `%20` for spaces). Docusaurus turns them into the page + URL, and `markdown.hooks.onBrokenMarkdownLinks: "throw"` fails the build when one doesn't + resolve. Don't write URL links (`./foo`, `/docs/...`): the build doesn't resolve them against + files, and `./foo` silently changes target under trailing slashes. - `static/robots.txt` allows all crawlers (AI training crawlers included) everywhere except `/search`, and points to the sitemap and `/llms.txt`. The sitemap ignores `/search` and `/blog`. @@ -118,7 +122,9 @@ yarn gen:api ## Tests -- `yarn test` runs `node --test` over `plugins/**/*.test.js`. Run `yarn gen:api` first (tests +- `yarn test` runs `node --test` over `plugins/**/*.test.js` and the React component tests in + `src/**/*.test.js` (JSX loaded through `test-support/register.mjs`, which compiles it with swc + and stubs the Docusaurus modules). Run `yarn gen:api` first (tests that need the generated `.api.mdx` pages skip without them) and `yarn build` for `plugins/build-checks.test.js`, which inspects `build/` and is skipped when it is absent. - Edge function: `yarn build && deno test --no-check --allow-read netlify/edge-functions-tests/`. diff --git a/docs/APIs-and-SDKs/CLI-Documentation/authentication.mdx b/docs/APIs-and-SDKs/CLI-Documentation/authentication.mdx index ba9c0a4f..08d0959b 100644 --- a/docs/APIs-and-SDKs/CLI-Documentation/authentication.mdx +++ b/docs/APIs-and-SDKs/CLI-Documentation/authentication.mdx @@ -4,7 +4,7 @@ sidebar_label: "Authentication" sidebar_position: 2 --- -# Authentication +# CLI Authentication The CLI stores credentials in your OS keychain (via keytar) and configuration in `~/.config/absmartly/config.yaml`. On headless systems without a keychain service, credentials fall back to a local `~/.config/absmartly/credentials.json` file. diff --git a/docs/APIs-and-SDKs/CLI-Documentation/experiment-templates.mdx b/docs/APIs-and-SDKs/CLI-Documentation/experiment-templates.mdx index d44013b4..b14c9fb2 100644 --- a/docs/APIs-and-SDKs/CLI-Documentation/experiment-templates.mdx +++ b/docs/APIs-and-SDKs/CLI-Documentation/experiment-templates.mdx @@ -4,7 +4,7 @@ sidebar_label: "Experiment Templates" sidebar_position: 6 --- -# Experiment Templates +# CLI Experiment Templates The CLI uses Markdown templates with YAML frontmatter for experiment round-trips. All names (metrics, owners, teams, tags, applications) are resolved by name — no IDs needed. diff --git a/docs/APIs-and-SDKs/MCP-Server/authentication.mdx b/docs/APIs-and-SDKs/MCP-Server/authentication.mdx index e3d4658f..6c36a9a2 100644 --- a/docs/APIs-and-SDKs/MCP-Server/authentication.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/authentication.mdx @@ -4,7 +4,7 @@ sidebar_label: "Authentication" sidebar_position: 4 --- -# Authentication +# MCP Server Authentication The ABsmartly MCP server supports two authentication methods. Both are configured per client — there are no server-side secrets, so credentials are diff --git a/docs/APIs-and-SDKs/overview.mdx b/docs/APIs-and-SDKs/overview.mdx index 32cc281d..6723188c 100644 --- a/docs/APIs-and-SDKs/overview.mdx +++ b/docs/APIs-and-SDKs/overview.mdx @@ -4,7 +4,7 @@ sidebar_label: "Overview" sidebar_position: 0 --- -# Overview +# Developer Tools Overview The **Developer Tools** section is the technical home of ABsmartly. It covers every way you can integrate, automate, extend or operate the platform from diff --git a/docs/web-console-docs/experiments/overview.mdx b/docs/web-console-docs/experiments/overview.mdx index 6e1386d4..a491d9e3 100644 --- a/docs/web-console-docs/experiments/overview.mdx +++ b/docs/web-console-docs/experiments/overview.mdx @@ -6,7 +6,7 @@ sidebar_position: 1 import Image from "../../../src/components/Image"; -# Overview +# Experiments Overview ## What is an experiment diff --git a/docs/web-console-docs/experiments/templates.mdx b/docs/web-console-docs/experiments/templates.mdx index 6acd78f8..23b5a568 100644 --- a/docs/web-console-docs/experiments/templates.mdx +++ b/docs/web-console-docs/experiments/templates.mdx @@ -6,7 +6,7 @@ sidebar_position: 8 import Image from "../../../src/components/Image"; -# Experiment Templates +# Experiment Templates in the Web Console ## Overview **Templates** are designed to streamline the process of creating experiments and feature flags. By using templates, you can quickly set up experiments with pre-configured settings, avoiding the need to start from scratch each time. This not only speeds up the process but also ensures consistency and quality across all experiments and feature flags. diff --git a/docs/web-console-docs/goals-and-metrics/goals/overview.mdx b/docs/web-console-docs/goals-and-metrics/goals/overview.mdx index 14b8b673..a7a1c3cf 100644 --- a/docs/web-console-docs/goals-and-metrics/goals/overview.mdx +++ b/docs/web-console-docs/goals-and-metrics/goals/overview.mdx @@ -4,7 +4,7 @@ sidebar_label: "Overview" sidebar_position: 1 --- -# Overview +# Goals Overview ## Goals diff --git a/docs/web-console-docs/goals-and-metrics/metrics/overview.mdx b/docs/web-console-docs/goals-and-metrics/metrics/overview.mdx index 05c652f4..48353b17 100644 --- a/docs/web-console-docs/goals-and-metrics/metrics/overview.mdx +++ b/docs/web-console-docs/goals-and-metrics/metrics/overview.mdx @@ -4,7 +4,7 @@ sidebar_label: "Overview" sidebar_position: 1 --- -# Overview +# Metrics Overview ## Experimentation Metrics diff --git a/docs/web-console-docs/overview.mdx b/docs/web-console-docs/overview.mdx index 9caa0ae2..91a09539 100644 --- a/docs/web-console-docs/overview.mdx +++ b/docs/web-console-docs/overview.mdx @@ -4,7 +4,7 @@ sidebar_label: "Overview" sidebar_position: 0 --- -# Overview +# Product Documentation Overview The Product Documentation section explains how to use the ABsmartly Web Console. If you run experiments, manage feature flags or work with goals and metrics, this is where you will find everything you need. diff --git a/docusaurus.config.js b/docusaurus.config.js index 484aca49..b4ace53d 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -78,11 +78,11 @@ const config = { trailingSlash: true, future: { experimental_vcs: vcs }, onBrokenLinks: "throw", - onBrokenMarkdownLinks: "warn", favicon: "img/favicon.ico", markdown: { mermaid: true, + hooks: { onBrokenMarkdownLinks: "throw" }, parseFrontMatter: async ({ filePath, fileContent, defaultParseFrontMatter }) => { const result = await defaultParseFrontMatter({ filePath, fileContent }); if (filePath.endsWith(".api.mdx") && apiOutputDirs.some((d) => filePath.startsWith(d + path.sep))) { diff --git a/plugins/build-checks.test.js b/plugins/build-checks.test.js index e91c0446..33aa24e2 100644 --- a/plugins/build-checks.test.js +++ b/plugins/build-checks.test.js @@ -242,3 +242,12 @@ buildTest("hand-written page titles are unique", () => { } assert.deepStrictEqual([...seen].filter(([, v]) => v.length > 1), []); }); + +buildTest("no hand-written page's H1 is a bare generic heading", () => { + const generic = new Set(["# Overview", "# Authentication", "# Experiment Templates"]); + const apiDir = /^APIs-and-SDKs\/(Web-Console-API|SDK-API)\//; + const bare = fs.readdirSync(path.join(buildDir, "docs"), { recursive: true }).map(String) + .filter((f) => f.endsWith(".md") && !apiDir.test(f)) + .filter((f) => generic.has(read(path.join("docs", f)).split("\n").find((l) => l.startsWith("# ")))); + assert.deepStrictEqual(bare, []); +}); From 259e22b05ae32188c8fee0a65a4d9cb82cdbcc4f Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 18:31:02 +0000 Subject: [PATCH 30/43] fix(docs): pin jsdom for Node 24.13 and keep the copy-failure note in a persistent live region jsdom 31 requires Node >= 24.15 while .nvmrc pins 24.13.0; use jsdom 29 and raise engines.node to >=22.13. The status note is now always mounted inside the dropdown popover (empty until a copy fails, cleared on close). Close the menu on window blur and give the first-item focus effect its deps. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- package.json | 4 +- .../PageAiActions/PageAiActions.test.js | 21 +- src/components/PageAiActions/index.js | 107 +++++---- .../PageAiActions/styles.module.css | 4 + yarn.lock | 212 ++++++++++++------ 5 files changed, 231 insertions(+), 117 deletions(-) diff --git a/package.json b/package.json index 95d5d20d..3a24fe23 100644 --- a/package.json +++ b/package.json @@ -49,7 +49,7 @@ "@testing-library/react": "^16.3.3", "@testing-library/user-event": "^14.6.13", "@tsconfig/docusaurus": "^2.0.3", - "jsdom": "^31.0.1", + "jsdom": "^29.1.1", "swc-loader": "^0.2.6", "typescript": "^5.4.3" }, @@ -66,6 +66,6 @@ ] }, "engines": { - "node": ">=22.12" + "node": ">=22.13" } } diff --git a/src/components/PageAiActions/PageAiActions.test.js b/src/components/PageAiActions/PageAiActions.test.js index ecc49782..efe4eab7 100644 --- a/src/components/PageAiActions/PageAiActions.test.js +++ b/src/components/PageAiActions/PageAiActions.test.js @@ -131,14 +131,31 @@ describe("PageAiActions", () => { test("a failed copy offers the link in a live region outside the menu", async () => { stubCopy({ succeeds: false }); const { user, trigger } = renderMenu(); + const note = screen.getByRole("status"); + assert.equal(note.textContent, ""); + assert.equal(note.closest('[role="menu"]'), null); await user.click(trigger); await user.click(screen.getByRole("menuitem", { name: "Copy page as Markdown" })); assert.ok(screen.getByRole("menuitem", { name: "Couldn't copy" })); - const note = screen.getByRole("status"); - assert.equal(note.closest('[role="menu"]'), null); + assert.equal(screen.getByRole("status"), note); + assert.match(note.textContent, /Copy the link instead/); assert.equal(note.querySelector("a").getAttribute("href"), "https://docs.example.com/docs/page.md"); + + await user.click(trigger); + assert.equal(note.textContent, ""); + }); + + test("the page losing focus closes the menu", async () => { + const { user, trigger } = renderMenu(); + await user.click(trigger); + + act(() => { + window.dispatchEvent(new window.Event("blur")); + }); + + assert.equal(trigger.getAttribute("aria-expanded"), "false"); }); test("reopening within 2 s of a copy keeps the menu open", async () => { diff --git a/src/components/PageAiActions/index.js b/src/components/PageAiActions/index.js index 95e31558..02cdc554 100644 --- a/src/components/PageAiActions/index.js +++ b/src/components/PageAiActions/index.js @@ -43,10 +43,13 @@ export default function PageAiActions() { triggerRef.current?.focus(); } }; + const closeOnPageBlur = () => setIsOpen(false); document.addEventListener("mousedown", closeOnOutsidePointer); document.addEventListener("touchstart", closeOnOutsidePointer); document.addEventListener("keydown", closeOnEscape); + window.addEventListener("blur", closeOnPageBlur); return () => { + window.removeEventListener("blur", closeOnPageBlur); document.removeEventListener("mousedown", closeOnOutsidePointer); document.removeEventListener("touchstart", closeOnOutsidePointer); document.removeEventListener("keydown", closeOnEscape); @@ -60,7 +63,11 @@ export default function PageAiActions() { rootRef.current.querySelector('[role="menuitem"]')?.focus(); } shouldFocusFirstItem.current = false; - }); + }, [isOpen]); + + useEffect(function clearStatusOnClose() { + if (!isOpen) setStatus("idle"); + }, [isOpen]); useEffect(() => () => clearTimeout(closeTimer.current), []); @@ -72,7 +79,6 @@ export default function PageAiActions() { ref={rootRef} className={clsx("page-ai-actions", "dropdown", styles.root, isInline && styles.inline, isOpen && "dropdown--show")} onBlur={(event) => { - // A null relatedTarget (Safari doesn't focus clicked buttons) must not close the menu mid-click. if (event.relatedTarget && !rootRef.current.contains(event.relatedTarget)) setIsOpen(false); }} > @@ -102,57 +108,60 @@ export default function PageAiActions() { -
    { - if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return; - event.preventDefault(); - const items = [...rootRef.current.querySelectorAll('[role="menuitem"]')]; - const step = event.key === "ArrowDown" ? 1 : -1; - const current = items.indexOf(document.activeElement); - items[(current + step + items.length) % items.length]?.focus(); - }} - > - - - View as Markdown - - - Open in Claude - - - Open in ChatGPT - -
    - {status === "failed" && ( + + + View as Markdown + + + Open in Claude + + + Open in ChatGPT + +
    - Copy the link instead: {mdUrl} + {status === "failed" && ( + <> + Copy the link instead: {mdUrl} + + )}
    - )} +
    ); } diff --git a/src/components/PageAiActions/styles.module.css b/src/components/PageAiActions/styles.module.css index 4a239c6b..c4cb2d6f 100644 --- a/src/components/PageAiActions/styles.module.css +++ b/src/components/PageAiActions/styles.module.css @@ -61,6 +61,10 @@ overflow-wrap: anywhere; } +.note:empty { + padding: 0; +} + @media (max-width: 996px) { .root { float: none; diff --git a/yarn.lock b/yarn.lock index a12a3d81..4fc23b10 100644 --- a/yarn.lock +++ b/yarn.lock @@ -218,6 +218,38 @@ js-yaml "^5.2.2" undici "^6.28.0" +"@asamuzakjp/css-color@^5.1.11": + version "5.1.11" + resolved "https://registry.yarnpkg.com/@asamuzakjp/css-color/-/css-color-5.1.11.tgz#28a0aac8220a4cc19045ac3bd9a813d4060bd375" + integrity sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg== + dependencies: + "@asamuzakjp/generational-cache" "^1.0.1" + "@csstools/css-calc" "^3.2.0" + "@csstools/css-color-parser" "^4.1.0" + "@csstools/css-parser-algorithms" "^4.0.0" + "@csstools/css-tokenizer" "^4.0.0" + +"@asamuzakjp/dom-selector@^7.1.1": + version "7.1.1" + resolved "https://registry.yarnpkg.com/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz#01880086bb2490098f167beb58555da1a6c9adbd" + integrity sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ== + dependencies: + "@asamuzakjp/generational-cache" "^1.0.1" + "@asamuzakjp/nwsapi" "^2.3.9" + bidi-js "^1.0.3" + css-tree "^3.2.1" + is-potential-custom-element-name "^1.0.1" + +"@asamuzakjp/generational-cache@^1.0.1": + version "1.0.1" + resolved "https://registry.yarnpkg.com/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz#3d0bf6be4fc059851390a7070720c6007af793ec" + integrity sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg== + +"@asamuzakjp/nwsapi@^2.3.9": + version "2.3.9" + resolved "https://registry.yarnpkg.com/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz#ad5549322dfe9d153d4b4dd6f7ff2ae234b06e24" + integrity sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q== + "@babel/code-frame@^7.0.0", "@babel/code-frame@^7.28.6", "@babel/code-frame@^7.29.0": version "7.29.0" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.29.0.tgz#7cd7a59f15b3cc0dcd803038f7792712a7d0b15c" @@ -1305,6 +1337,13 @@ resolved "https://registry.yarnpkg.com/@braintree/sanitize-url/-/sanitize-url-7.1.2.tgz#ca2035b0fefe956a8676ff0c69af73e605fcd81f" integrity sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA== +"@bramus/specificity@^2.4.2": + version "2.4.5" + resolved "https://registry.yarnpkg.com/@bramus/specificity/-/specificity-2.4.5.tgz#214c09c99d6fbca5d60c56338f1f90bfc083a17e" + integrity sha512-TWjoxMCb5z1j19ZAVlGIkRkoq22F9F1+s+sTcJcw3GN+sEj/ZhWD+PPyol0feaRGZyajOA22FTCv95Ow26i6iA== + dependencies: + css-tree "^3.2.1" + "@chevrotain/types@~11.1.2": version "11.1.2" resolved "https://registry.yarnpkg.com/@chevrotain/types/-/types-11.1.2.tgz#e83a1a2704f0c5e49e7592b214031a0f4a34d7e5" @@ -1325,11 +1364,21 @@ resolved "https://registry.yarnpkg.com/@csstools/color-helpers/-/color-helpers-5.1.0.tgz#106c54c808cabfd1ab4c602d8505ee584c2996ef" integrity sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA== +"@csstools/color-helpers@^6.1.3": + version "6.1.3" + resolved "https://registry.yarnpkg.com/@csstools/color-helpers/-/color-helpers-6.1.3.tgz#fb5643a6ee828cc10c4a1aa6a6606940f459d780" + integrity sha512-c6CpX5G1pvuOKTXiRFJ54Lzc8zQrZ3qUjp44QC5DJNt1OmA1vmfUxOMCcKdDqsvffVDG0/MHnY63J+Mn0nmdUg== + "@csstools/css-calc@^2.1.4": version "2.1.4" resolved "https://registry.yarnpkg.com/@csstools/css-calc/-/css-calc-2.1.4.tgz#8473f63e2fcd6e459838dd412401d5948f224c65" integrity sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ== +"@csstools/css-calc@^3.2.0", "@csstools/css-calc@^3.4.4": + version "3.4.4" + resolved "https://registry.yarnpkg.com/@csstools/css-calc/-/css-calc-3.4.4.tgz#05416934945345f6ff69a354a7822faa9e742dea" + integrity sha512-Jwo1Z8DUsZ8xVOLBdLMfhjJFvWD6pqaUTlBNQZ+qIB2i9g7yG8kd/UBJj2c9J9Twr+u87cjy9BjkmfvMbyOk3Q== + "@csstools/css-color-parser@^3.1.0": version "3.1.0" resolved "https://registry.yarnpkg.com/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz#4e386af3a99dd36c46fef013cfe4c1c341eed6f0" @@ -1338,16 +1387,39 @@ "@csstools/color-helpers" "^5.1.0" "@csstools/css-calc" "^2.1.4" +"@csstools/css-color-parser@^4.1.0": + version "4.2.8" + resolved "https://registry.yarnpkg.com/@csstools/css-color-parser/-/css-color-parser-4.2.8.tgz#d3e30fcb87de2d74847c9474c21942d4529aa7e2" + integrity sha512-JLsKBee9dmnA3L+H+vYK4lQ6n5CoY3yEnh33zdlMutRfrTxtqt+hFeoZ1maHRt5vLw67huDLpOkDb3rl9A51MQ== + dependencies: + "@csstools/color-helpers" "^6.1.3" + "@csstools/css-calc" "^3.4.4" + "@csstools/css-parser-algorithms@^3.0.5": version "3.0.5" resolved "https://registry.yarnpkg.com/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz#5755370a9a29abaec5515b43c8b3f2cf9c2e3076" integrity sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ== +"@csstools/css-parser-algorithms@^4.0.0": + version "4.0.3" + resolved "https://registry.yarnpkg.com/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.3.tgz#d3f9a5502b828fca49511a66aa274b279e15157d" + integrity sha512-EpCfUDaJtwohPHC7egoXxPGT/R1/WyyAhw87MKB/7BPPZvZU+IcEqo4er5FpLnby2Gvwt9Lpxy+WNEDyFjoXtA== + +"@csstools/css-syntax-patches-for-csstree@^1.1.3": + version "1.1.17" + resolved "https://registry.yarnpkg.com/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.17.tgz#42b82855d0f0711f134619d9ac4a538617f0e3f3" + integrity sha512-IPx9W33+t0Yt5TVb+Y7oICrThOIry0TY6GuXfSHOatxA0uiHqbzi98Gai905lpBAX1m/LH7iI96e9jcI7Dkvxw== + "@csstools/css-tokenizer@^3.0.4": version "3.0.4" resolved "https://registry.yarnpkg.com/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz#333fedabc3fd1a8e5d0100013731cf19e6a8c5d3" integrity sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw== +"@csstools/css-tokenizer@^4.0.0": + version "4.0.3" + resolved "https://registry.yarnpkg.com/@csstools/css-tokenizer/-/css-tokenizer-4.0.3.tgz#eeab5057075343851c12b5181bd6efb463b0dd11" + integrity sha512-gdkFe/Z4KU1q8Y5S3GYScXGcOnO56dgWwIs5+97Ij1VIKISItOIUlCXUq4VLbdnRclF+SSQ49sLsn3KeV111AA== + "@csstools/media-query-list-parser@^4.0.3": version "4.0.3" resolved "https://registry.yarnpkg.com/@csstools/media-query-list-parser/-/media-query-list-parser-4.0.3.tgz#7aec77bcb89c2da80ef207e73f474ef9e1b3cdf1" @@ -2250,7 +2322,7 @@ utility-types "^3.10.0" webpack "^5.88.1" -"@exodus/bytes@^1.15.1", "@exodus/bytes@^1.16.0": +"@exodus/bytes@^1.11.0", "@exodus/bytes@^1.15.0", "@exodus/bytes@^1.6.0": version "1.16.0" resolved "https://registry.yarnpkg.com/@exodus/bytes/-/bytes-1.16.0.tgz#954c9d9dd7eec15b966b2e8f2d883c04295b720c" integrity sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA== @@ -4266,19 +4338,17 @@ batch@0.6.1: resolved "https://registry.yarnpkg.com/batch/-/batch-0.6.1.tgz#dc34314f4e679318093fc760272525f94bf25c16" integrity sha512-x+VAiMRL6UPkx+kudNvxTl6hB2XNNCG2r+7wixVfIYwu/2HKRXimwQyaumLjMveWvT2Hkd/cAJw+QBMfJ/EKVw== -bcp-47-match@^2.0.0, bcp-47-match@^2.0.3: +bcp-47-match@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/bcp-47-match/-/bcp-47-match-2.0.3.tgz#603226f6e5d3914a581408be33b28a53144b09d0" integrity sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ== -bcp-47@^2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/bcp-47/-/bcp-47-2.1.2.tgz#daf552d46cf73300da467eee035a90141de97b9c" - integrity sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg== +bidi-js@^1.0.3: + version "1.1.0" + resolved "https://registry.yarnpkg.com/bidi-js/-/bidi-js-1.1.0.tgz#c92efafe3fce3b9fdd30ba67bdddf0dd4d424af7" + integrity sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg== dependencies: - is-alphabetical "^2.0.0" - is-alphanumerical "^2.0.0" - is-decimal "^2.0.0" + require-from-string "^2.0.2" big.js@^5.2.2: version "5.2.2" @@ -5060,6 +5130,14 @@ css-tree@^2.3.1: mdn-data "2.0.30" source-map-js "^1.0.1" +css-tree@^3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/css-tree/-/css-tree-3.2.1.tgz#86cac7011561272b30e6b1e042ba6ce047aa7518" + integrity sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA== + dependencies: + mdn-data "2.27.1" + source-map-js "^1.2.1" + css-tree@~2.2.0: version "2.2.1" resolved "https://registry.yarnpkg.com/css-tree/-/css-tree-2.2.1.tgz#36115d382d60afd271e377f9c5f67d02bd48c032" @@ -5455,13 +5533,13 @@ dagre-d3-es@7.0.14: d3 "^7.9.0" lodash-es "^4.17.21" -data-urls@^8.0.0: - version "8.0.0" - resolved "https://registry.yarnpkg.com/data-urls/-/data-urls-8.0.0.tgz#d4e925beae8249dbe99a1defed36cebb9cc7a84c" - integrity sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ== +data-urls@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/data-urls/-/data-urls-7.0.0.tgz#6dce8b63226a1ecfdd907ce18a8ccfb1eee506d3" + integrity sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA== dependencies: whatwg-mimetype "^5.0.0" - whatwg-url "^17.1.2" + whatwg-url "^16.0.0" dayjs@^1.11.20: version "1.11.21" @@ -6862,12 +6940,12 @@ hpack.js@^2.1.6: readable-stream "^2.0.1" wbuf "^1.1.0" -html-encoding-sniffer@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz#cf995009e50fa6f90d74906ab5137f8ee9b7c9d8" - integrity sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w== +html-encoding-sniffer@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz#f8d9390b3b348b50d4f61c16dd2ef5c05980a882" + integrity sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg== dependencies: - "@exodus/bytes" "^1.15.1" + "@exodus/bytes" "^1.6.0" html-escaper@^2.0.2: version "2.0.2" @@ -7460,28 +7538,31 @@ js-yaml@^5.2.2: dependencies: argparse "^2.0.1" -jsdom@^31.0.1: - version "31.0.1" - resolved "https://registry.yarnpkg.com/jsdom/-/jsdom-31.0.1.tgz#2f543cea1a4fb30bc5e00ed2a3e37153f82eff33" - integrity sha512-CbhJL8ZQg3eKswxSZth4QO9tW0jPIhmR0vtSXQSbKSfWbwIT6hoRc17wdHIVTQ43KI0mdV5iTJr3281IDgVZ5g== - dependencies: - "@exodus/bytes" "^1.16.0" - bcp-47 "^2.1.2" - bcp-47-match "^2.0.3" - data-urls "^8.0.0" +jsdom@^29.1.1: + version "29.1.1" + resolved "https://registry.yarnpkg.com/jsdom/-/jsdom-29.1.1.tgz#5b9704906f3cd510c34aa941ae2f8f7f8179df01" + integrity sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q== + dependencies: + "@asamuzakjp/css-color" "^5.1.11" + "@asamuzakjp/dom-selector" "^7.1.1" + "@bramus/specificity" "^2.4.2" + "@csstools/css-syntax-patches-for-csstree" "^1.1.3" + "@exodus/bytes" "^1.15.0" + css-tree "^3.2.1" + data-urls "^7.0.0" decimal.js "^10.6.0" - html-encoding-sniffer "^7.0.0" + html-encoding-sniffer "^6.0.0" is-potential-custom-element-name "^1.0.1" - lru-cache "^11.5.3" - parse5 "^8.1.0" - parse5-parser-stream "^8.1.0" + lru-cache "^11.3.5" + parse5 "^8.0.1" saxes "^6.0.0" - tough-cookie "^6.0.2" - undici "^8.12.3" - w3c-xmlserializer "^6.0.0" + symbol-tree "^3.2.4" + tough-cookie "^6.0.1" + undici "^7.25.0" + w3c-xmlserializer "^5.0.0" webidl-conversions "^8.0.1" whatwg-mimetype "^5.0.0" - whatwg-url "^17.3.0" + whatwg-url "^16.0.1" xml-name-validator "^5.0.0" jsesc@^3.0.2, jsesc@~3.1.0: @@ -7699,7 +7780,7 @@ lowercase-keys@^3.0.0: resolved "https://registry.yarnpkg.com/lowercase-keys/-/lowercase-keys-3.0.0.tgz#c5e7d442e37ead247ae9db117a9d0a467c89d4f2" integrity sha512-ozCC6gdQ+glXOQsveKD0YsDy8DSQFjDTz4zyzEHNV5+JP5D62LmfDZ6o1cycFx9ouG940M5dE8C8CTewdj2YWQ== -lru-cache@^11.5.3: +lru-cache@^11.3.5: version "11.5.4" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-11.5.4.tgz#6073dda1feb2a438e568f791fd13fffa223be76f" integrity sha512-B8nJCTi8JuSaDBg0tBdnImV6j5O2CXaqKfdj24ZTCFbyivN8KZ2Z+RL3aHjwJAfLutD9cNnObG4SIgW4gMufiw== @@ -7964,6 +8045,11 @@ mdn-data@2.0.30: resolved "https://registry.yarnpkg.com/mdn-data/-/mdn-data-2.0.30.tgz#ce4df6f80af6cfbe218ecd5c552ba13c4dfa08cc" integrity sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA== +mdn-data@2.27.1: + version "2.27.1" + resolved "https://registry.yarnpkg.com/mdn-data/-/mdn-data-2.27.1.tgz#e37b9c50880b75366c4d40ac63d9bbcacdb61f0e" + integrity sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ== + media-typer@0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748" @@ -9048,13 +9134,6 @@ parse5-htmlparser2-tree-adapter@^7.0.0: domhandler "^5.0.3" parse5 "^7.0.0" -parse5-parser-stream@^8.1.0: - version "8.1.1" - resolved "https://registry.yarnpkg.com/parse5-parser-stream/-/parse5-parser-stream-8.1.1.tgz#27e0507c62b705bf327741cd24b96765173b0ca2" - integrity sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw== - dependencies: - parse5 "^8.1.1" - parse5@^7.0.0: version "7.3.0" resolved "https://registry.yarnpkg.com/parse5/-/parse5-7.3.0.tgz#d7e224fa72399c7a175099f45fc2ad024b05ec05" @@ -9062,7 +9141,7 @@ parse5@^7.0.0: dependencies: entities "^6.0.0" -parse5@^8.1.0, parse5@^8.1.1: +parse5@^8.0.1: version "8.1.1" resolved "https://registry.yarnpkg.com/parse5/-/parse5-8.1.1.tgz#d73eb52282024c921e9c5a19b870f53492e631b2" integrity sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w== @@ -11271,6 +11350,11 @@ swc-loader@^0.2.6: dependencies: "@swc/counter" "^0.1.3" +symbol-tree@^3.2.4: + version "3.2.4" + resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2" + integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw== + tapable@^2.0.0, tapable@^2.2.1, tapable@^2.3.0, tapable@^2.3.3: version "2.3.3" resolved "https://registry.yarnpkg.com/tapable/-/tapable-2.3.3.tgz#5da7c9992c46038221267985ab28421a8879f160" @@ -11443,17 +11527,17 @@ totalist@^3.0.0: resolved "https://registry.yarnpkg.com/totalist/-/totalist-3.0.1.tgz#ba3a3d600c915b1a97872348f79c127475f6acf8" integrity sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ== -tough-cookie@^6.0.2: +tough-cookie@^6.0.1: version "6.1.0" resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-6.1.0.tgz#eafa6e331d2b948cdd73d75ee1190cb5a8f0df0d" integrity sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w== dependencies: tldts "^7.0.5" -tr46@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/tr46/-/tr46-7.0.0.tgz#af39140d4a8860868de4e16477a4a946bda03a62" - integrity sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg== +tr46@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/tr46/-/tr46-6.0.0.tgz#f5a1ae546a0adb32a277a2278d0d17fa2f9093e6" + integrity sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw== dependencies: punycode "^2.3.1" @@ -11561,10 +11645,10 @@ undici@^6.28.0: resolved "https://registry.yarnpkg.com/undici/-/undici-6.28.0.tgz#9f0e385744fef5021d6596c5bccd783f61193c1c" integrity sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA== -undici@^8.12.3: - version "8.14.0" - resolved "https://registry.yarnpkg.com/undici/-/undici-8.14.0.tgz#25f8b8172b69c5f67f1b671522052030451748e6" - integrity sha512-MqM6wqORYo0jb1WFUwFKZTFWFz6VeBMPj9op5Hq+RvlrQjISQCyLEfx5+/iqOLWC/LL1HliJ5t0NP1BgYpXeVQ== +undici@^7.25.0: + version "7.30.2" + resolved "https://registry.yarnpkg.com/undici/-/undici-7.30.2.tgz#26c6acb0ffe838f823511f8cb79a8d530652135e" + integrity sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA== unicode-canonical-property-names-ecmascript@^2.0.0: version "2.0.1" @@ -11850,10 +11934,10 @@ vfile@^6.0.0, vfile@^6.0.1: "@types/unist" "^3.0.0" vfile-message "^4.0.0" -w3c-xmlserializer@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz#27c0747e0091ada8cdb513c3645362e71fc50d82" - integrity sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q== +w3c-xmlserializer@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz#f925ba26855158594d907313cedd1476c5967f6c" + integrity sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA== dependencies: xml-name-validator "^5.0.0" @@ -12035,13 +12119,13 @@ whatwg-mimetype@^5.0.0: resolved "https://registry.yarnpkg.com/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz#d8232895dbd527ceaee74efd4162008fb8a8cf48" integrity sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw== -whatwg-url@^17.1.2, whatwg-url@^17.3.0: - version "17.3.0" - resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-17.3.0.tgz#261af70e10e3a6788a842751c5c81ad63f04e87f" - integrity sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg== +whatwg-url@^16.0.0, whatwg-url@^16.0.1: + version "16.0.1" + resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-16.0.1.tgz#047f7f4bd36ef76b7198c172d1b1cebc66f764dd" + integrity sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw== dependencies: - "@exodus/bytes" "^1.16.0" - tr46 "^7.0.0" + "@exodus/bytes" "^1.11.0" + tr46 "^6.0.0" webidl-conversions "^8.0.1" whatwg-url@^5.0.0: From 08f1a6199b8857a3900c75344f5ef26905153b1d Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 18:34:36 +0000 Subject: [PATCH 31/43] fix(llms): skip abbreviations and lead images in API index descriptions, match the pointer line literally Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- plugins/llms-markdown/postprocess-llms.js | 21 +++++++++++---- .../llms-markdown/postprocess-llms.test.js | 26 +++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/plugins/llms-markdown/postprocess-llms.js b/plugins/llms-markdown/postprocess-llms.js index e8e98302..5b1f1782 100644 --- a/plugins/llms-markdown/postprocess-llms.js +++ b/plugins/llms-markdown/postprocess-llms.js @@ -31,12 +31,23 @@ function apiDescriptionFor(operation) { .replace(PERMISSIONS, "") .split(/\n\s*\n/) .map((p) => p.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\*\*/g, "").replace(/\s+/g, " ").trim()) - .find((p) => p && !/^(#|[-*+] |\d+[.)] |\||>|```|:::)/.test(p)); + .find((p) => p && !/^(#|[-*+] |\d+[.)] |\||>|```|:::|!|<)/.test(p)); if (!prose) return endpoint; - const sentence = prose.match(/^.*?[.!?](?=\s|$)/)?.[0] ?? `${prose.replace(/[:;,]$/, "")}.`; + const sentence = firstSentence(prose) ?? `${prose.replace(/[:;,]$/, "")}.`; return sentence.length <= MAX_DESCRIPTION ? `${endpoint} ${sentence}` : endpoint; } +const ABBREVIATION = /(?:^|\s)(?:e\.g|i\.e|etc|vs|cf)\.$/i; + +function firstSentence(text) { + for (const m of text.matchAll(/[.!?](?=\s|$)/g)) { + const sentence = text.slice(0, m.index + 1); + const next = text.slice(m.index + 1).trimStart(); + if (!ABBREVIATION.test(sentence) && !/^[a-z]/.test(next)) return sentence; + } + return null; +} + // --- llms.txt ----------------------------------------------------------------- const ENTRY = /^- \[(.*?)\]\((https?:\/\/[^)]*)\)(?:: (.*))?$/; @@ -118,10 +129,10 @@ function addNote(header, note) { return `${lines.join("\n")}\n`; } -const POINTER = new RegExp(`^> ${POINTER_LEAD}.*\n\n`); - function withoutPointer(section) { - return section.replace(POINTER, ""); + const lineEnd = section.indexOf("\n"); + const isPointer = section.startsWith(`> ${POINTER_LEAD}`) && section.startsWith("\n\n", lineEnd); + return isPointer ? section.slice(lineEnd + 2) : section; } // The inner plugin writes llms-full.txt as: the llms.txt content, then diff --git a/plugins/llms-markdown/postprocess-llms.test.js b/plugins/llms-markdown/postprocess-llms.test.js index 520c993a..ad2b15d0 100644 --- a/plugins/llms-markdown/postprocess-llms.test.js +++ b/plugins/llms-markdown/postprocess-llms.test.js @@ -71,6 +71,32 @@ test("apiDescriptionFor drops admonitions and permission text, keeps unterminate ); }); +test("apiDescriptionFor does not end the sentence at an abbreviation", () => { + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/goals", description: "Use e.g. this endpoint to list goals. Paginated." }), + "GET /goals. Use e.g. this endpoint to list goals.", + ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/teams", description: "Lists teams, i.e. groups of users. Sorted by name." }), + "GET /teams. Lists teams, i.e. groups of users.", + ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/units", description: "Returns approx. three units per page. Cached." }), + "GET /units. Returns approx. three units per page.", + ); +}); + +test("apiDescriptionFor skips lead images and HTML", () => { + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/a", description: "![Diagram](/img/a.png)\n\nLists things. More." }), + "GET /a. Lists things.", + ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/b", description: "\n\nGets a thing." }), + "GET /b. Gets a thing.", + ); +}); + // --- rewriteLlmsTxt --------------------------------------------------------------- const LLMS_TXT = `# The ABsmartly Docs From 1fc9cba00d042766c31737549c9faf940511d34b Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 18:34:55 +0000 Subject: [PATCH 32/43] fix(edge): serve HTML when negotiated Markdown was redirected off-origin Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- .../markdown-negotiation.test.js | 18 ++++++++++++++++++ netlify/edge-functions/markdown-negotiation.js | 7 ++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/netlify/edge-functions-tests/markdown-negotiation.test.js b/netlify/edge-functions-tests/markdown-negotiation.test.js index 89807c99..7d994b20 100644 --- a/netlify/edge-functions-tests/markdown-negotiation.test.js +++ b/netlify/edge-functions-tests/markdown-negotiation.test.js @@ -250,6 +250,24 @@ Deno.test("negotiation after a redirect: canonical and Content-Location name the } }); +Deno.test("negotiation serves HTML when the Markdown fetch was redirected to another origin", async () => { + globalThis.fetch = async () => { + const r = await serve(PAGE.replace(/\/$/, ".md")); + Object.defineProperties(r, { + redirected: { value: true }, + url: { value: "https://elsewhere.example/docs/other.md" }, + }); + return r; + }; + try { + const r = await call(PAGE, "text/markdown"); + eq(r.status, 200); + eq((await r.text()).startsWith(""), true); + } finally { + globalThis.fetch = (u) => serve(new URL(u).pathname); + } +}); + Deno.test("negotiated Markdown has one canonical Link when the .md fetch already carries one", async () => { globalThis.fetch = (u) => handler(new Request(u), { next: () => serve(new URL(u).pathname) }); try { diff --git a/netlify/edge-functions/markdown-negotiation.js b/netlify/edge-functions/markdown-negotiation.js index ed55d80a..f7b95924 100644 --- a/netlify/edge-functions/markdown-negotiation.js +++ b/netlify/edge-functions/markdown-negotiation.js @@ -144,9 +144,10 @@ async function handleMarkdownUrl(request, context, url) { async function fetchMarkdown(mdPath, origin) { try { const res = await fetch(new URL(mdPath, origin), { headers: { accept: "text/markdown" } }); - const path = res.redirected ? new URL(res.url).pathname : mdPath; - if (res.ok && path.endsWith(".md")) return { response: res, path }; - console.warn(`markdown-negotiation: ${mdPath} returned ${res.status} from ${path}; serving HTML`); + const finalUrl = res.redirected ? new URL(res.url) : new URL(mdPath, origin); + const path = finalUrl.pathname; + if (res.ok && finalUrl.origin === origin && path.endsWith(".md")) return { response: res, path }; + console.warn(`markdown-negotiation: ${mdPath} returned ${res.status} from ${finalUrl}; serving HTML`); } catch (err) { console.warn(`markdown-negotiation: fetching ${mdPath} failed: ${err}; serving HTML`); } From c62ad0fdb0adb50ad5bd02da2a1ca7e5b787bca3 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 18:35:27 +0000 Subject: [PATCH 33/43] test(llms): catch raw spaces in bracketed link URLs of the agent link lists Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- plugins/build-checks.test.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/plugins/build-checks.test.js b/plugins/build-checks.test.js index 33aa24e2..ef733753 100644 --- a/plugins/build-checks.test.js +++ b/plugins/build-checks.test.js @@ -31,8 +31,13 @@ buildTest("API endpoint descriptions in the index are not Markdown-formatted", ( }); buildTest("link URLs in the agent indexes contain no raw spaces", () => { - for (const file of ["llms.txt", API_INDEX, "llms-full.txt"]) { - const raw = read(file).split("\n").filter((l) => /\]\(https?:[^)]* [^)]*\.md\)/.test(l)); + const linkLists = { + "llms.txt": read("llms.txt"), + [API_INDEX]: read(API_INDEX), + "llms-full.txt": read("llms-full.txt").split("\n# Full Documentation Content\n")[0], + }; + for (const [file, text] of Object.entries(linkLists)) { + const raw = text.split("\n").filter((l) => /\]\(]* [^>]*>\)|\]\(https?:[^)]* [^)]*\.md\)/.test(l)); assert.deepStrictEqual(raw, [], `${file}: raw spaces in link URLs`); } }); From 6d8985794574e8f86436168ab70effc91f8b613f Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 18:35:42 +0000 Subject: [PATCH 34/43] docs: match the MCP overview H1 to its title, note that bare file links resolve from the same folder Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- .../write-feature-docs/references/docusaurus-conventions.md | 2 +- AGENTS.md | 2 +- docs/APIs-and-SDKs/MCP-Server/overview.mdx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.claude/skills/write-feature-docs/references/docusaurus-conventions.md b/.claude/skills/write-feature-docs/references/docusaurus-conventions.md index 6a065182..c773f0eb 100644 --- a/.claude/skills/write-feature-docs/references/docusaurus-conventions.md +++ b/.claude/skills/write-feature-docs/references/docusaurus-conventions.md @@ -72,7 +72,7 @@ Match the neighbors' usage — `:::tip` for guidance, `:::note` for caveats, `:: ## Internal links and anchors -- **Cross-page:** a file link — the target's source file, with its extension, relative to the file the link is in: `[Get Started](./get-started.mdx)`, `[Create](../create.mdx)`, or `./index.mdx` for a category's index page. Percent-encode spaces (`./SAML%20Role%20Mapping.mdx`). Docusaurus turns it into the page URL, and the build fails (`markdown.hooks.onBrokenMarkdownLinks: "throw"`) when it doesn't resolve. Don't write URL links (`./get-started`, `/docs/...`): the build doesn't resolve them against files, and `./get-started` silently changes target under `trailingSlash: true`. +- **Cross-page:** a file link — the target's source file, with its extension, relative to the file the link is in: `[Get Started](./get-started.mdx)`, `[Create](../create.mdx)`, or `./index.mdx` for a category's index page. Percent-encode spaces (`./SAML%20Role%20Mapping.mdx`). Docusaurus turns it into the page URL, and the build fails (`markdown.hooks.onBrokenMarkdownLinks: "throw"`) when it doesn't resolve. A file link without `./` (`get-started.mdx`) also resolves from the same folder. Don't write URL links (`./get-started`, `/docs/...`): the build doesn't resolve them against files, and `./get-started` silently changes target under `trailingSlash: true`. - **Anchor on another page:** `./get-started.mdx#step-4-configure-exposures-import-hybrid-only`. - **Same-page anchor:** `#the-default-data-source`. - The anchor **slug is the kebab-cased heading text** (lowercased, spaces→hyphens, punctuation dropped, `_italics_` markers dropped). So `## Step 4: Configure exposures import _(Hybrid only)_` → `step-4-configure-exposures-import-hybrid-only`. diff --git a/AGENTS.md b/AGENTS.md index 726bc045..fc2632d4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -111,7 +111,7 @@ yarn gen:api extension, relative to the file the link is in (`./get-started.mdx`, `../create.mdx#anchor`, `./index.mdx` for a category's index page, `%20` for spaces). Docusaurus turns them into the page URL, and `markdown.hooks.onBrokenMarkdownLinks: "throw"` fails the build when one doesn't - resolve. Don't write URL links (`./foo`, `/docs/...`): the build doesn't resolve them against + resolve. A file link without `./` (`get-started.mdx`) also resolves from the same folder. Don't write URL links (`./foo`, `/docs/...`): the build doesn't resolve them against files, and `./foo` silently changes target under trailing slashes. - `static/robots.txt` allows all crawlers (AI training crawlers included) everywhere except `/search`, and points to the sitemap and `/llms.txt`. diff --git a/docs/APIs-and-SDKs/MCP-Server/overview.mdx b/docs/APIs-and-SDKs/MCP-Server/overview.mdx index b7a744d6..6d09935b 100644 --- a/docs/APIs-and-SDKs/MCP-Server/overview.mdx +++ b/docs/APIs-and-SDKs/MCP-Server/overview.mdx @@ -4,7 +4,7 @@ sidebar_label: "Overview" sidebar_position: 1 --- -# ABsmartly MCP Server +# MCP Server Overview The ABsmartly [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) server lets AI assistants — Claude, Cursor, VS Code, Windsurf, Gemini, ChatGPT From 80f41a62ac400e927af49135b314de5f5bb9e954 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 18:39:31 +0000 Subject: [PATCH 35/43] refactor(llms): build complete API index entries in one pure function and pass the index explicitly buildOperationIndex(specs, pages, titles, siteUrl) now returns finished entries (page URL and title included) instead of half-built ones completed by mutation. The wrapper hands the index to rehype-api-markdown (which it now registers) and to postprocess-llms, replacing the spec-index module singletons, and reuses the title map built once in docusaurus.config.js. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- AGENTS.md | 13 ++- docusaurus.config.js | 10 +- .../api/render-operation.test.js | 9 +- plugins/llms-markdown/api/spec-index.js | 94 +++++++------------ plugins/llms-markdown/api/spec-index.test.js | 94 +++++++++---------- plugins/llms-markdown/llms-txt-wrapper.js | 82 +++++++--------- .../llms-markdown/llms-txt-wrapper.test.js | 92 ++++++++++-------- plugins/llms-markdown/postprocess-llms.js | 11 +-- plugins/llms-markdown/rehype-api-markdown.js | 10 +- .../llms-markdown/rehype-api-markdown.test.js | 50 +++++----- 10 files changed, 216 insertions(+), 249 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fc2632d4..0e1456e7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,15 +71,18 @@ yarn gen:api its `` (`src/theme/DocItem/Metadata/index.js`, a swizzle wrapper), and the `/llms.txt` header explains the `.md` suffix and `Accept: text/markdown` options. - API reference Markdown is generated from the OpenAPI specs, not from the client-rendered pages. - `llms-txt-wrapper.js` builds the operation index (`api/spec-index.js`: dereferenced specs, page - URLs) in its own `postBuild` before awaiting the inner plugin's `postBuild` (Docusaurus runs - postBuilds concurrently). `rehype-api-markdown.js` then replaces an endpoint page's content with + In its `postBuild` (Docusaurus runs postBuilds concurrently), `llms-txt-wrapper.js` builds the + operation index with `buildOperationIndex` (`api/spec-index.js`: dereferenced specs, generated + page URLs, readable titles), then runs the inner plugin with `rehype-api-markdown.js` added + first to `beforeDefaultRehypePlugins` and given that index, and passes the same index to + `postprocess-llms.js`. `rehype-api-markdown.js` replaces an endpoint page's content with Markdown from `api/render-operation.js` and `api/render-schema.js`. Auth lines are hand-written there (from `APIs-and-SDKs/overview.mdx`), never derived from `securitySchemes`. The raw specs are also published at `/openapi/*.yaml` (`publish-openapi-specs.js`) and linked from `/llms.txt`. - Readable API titles (`api/api-titles.js`) are applied at parse time by `markdown.parseFrontMatter` - plus a `createApiPageMD` wrapper in `docusaurus.config.js`. Sidebar labels keep the spec - summaries, and the generated `.api.mdx` files still contain the original `title:`. + plus a `createApiPageMD` wrapper in `docusaurus.config.js`, which builds the title map once and + also hands it to the wrapper (`apiTitles` option). Sidebar labels keep the spec summaries, and the + generated `.api.mdx` files still contain the original `title:`. - `pointer.js` holds the pointer line at the top of every `.md` (and of every rendered page): "For AI agents: this page is available as Markdown at `.md`. The full documentation index is at https://docs.absmartly.com/llms.txt." Its `encodeUrlPath` percent-encodes page URLs (some SSO diff --git a/docusaurus.config.js b/docusaurus.config.js index b4ace53d..b3b97427 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -16,9 +16,7 @@ const { siteUrl } = require("./plugins/site-url"); // branch deploys, so agent-facing links on a preview stay on the preview. const SITE_URL = siteUrl(); -// Readable API page titles (spec summaries like "Goal [UPDATE]" stay in the sidebar). -const apiOperations = listOperations(loadRawSpecsSync(__dirname)); -const apiTitleMap = buildTitleMap(apiOperations); +const apiTitleMap = buildTitleMap(listOperations(loadRawSpecsSync(__dirname))); const apiOutputDirs = SPECS.map((s) => path.join(__dirname, s.docsDir)); function readableCreateApiPageMD(page) { @@ -176,6 +174,7 @@ const config = { "pages in one file; the Web Console API endpoints have their own index at " + "/docs/APIs-and-SDKs/Web-Console-API/llms.txt.", depth: 2, + apiTitles: apiTitleMap, // Rewrites llms.txt and llms-full.txt after the inner plugin has written // them; see plugins/llms-markdown/postprocess-llms.js. postProcess: { @@ -267,10 +266,7 @@ const config = { require("./plugins/llms-markdown/remark-fix-md-links"), require("./plugins/llms-markdown/remark-tight-lists"), ], - beforeDefaultRehypePlugins: [ - [require("./plugins/llms-markdown/rehype-api-markdown"), { siteUrl: SITE_URL }], - require("./plugins/llms-markdown/rehype-docusaurus-cleanup"), - ], + beforeDefaultRehypePlugins: [require("./plugins/llms-markdown/rehype-docusaurus-cleanup")], }, }, ], diff --git a/plugins/llms-markdown/api/render-operation.test.js b/plugins/llms-markdown/api/render-operation.test.js index 07c045e3..c2b5693d 100644 --- a/plugins/llms-markdown/api/render-operation.test.js +++ b/plugins/llms-markdown/api/render-operation.test.js @@ -10,13 +10,10 @@ const siteDir = path.resolve(__dirname, "../../.."); let cached; async function load() { if (!cached) { - const index = si.buildOperationIndex(await si.loadDereferencedSpecs(siteDir)); + const specs = await si.loadDereferencedSpecs(siteDir); + const pages = new Map(si.listOperations(specs).map((o) => [`${o.method} ${o.path}`, `/docs/test/${o.operationId}`])); const titles = buildTitleMap(si.listOperations(si.loadRawSpecsSync(siteDir))); - for (const [k, e] of index) { - e.title = titles.get(k).title; - e.pageUrl = `https://docs.absmartly.com/docs/test/${e.operationId}`; - } - cached = index; + cached = si.buildOperationIndex(specs, pages, titles); } return cached; } diff --git a/plugins/llms-markdown/api/spec-index.js b/plugins/llms-markdown/api/spec-index.js index ae24a85c..d7e5bfb2 100644 --- a/plugins/llms-markdown/api/spec-index.js +++ b/plugins/llms-markdown/api/spec-index.js @@ -70,58 +70,12 @@ async function loadDereferencedSpecs(siteDir) { return specs; } -function buildOperationIndex(derefSpecs, siteUrl = defaultSiteUrl()) { - const index = new Map(); - for (const o of listOperations(derefSpecs)) { - const key = `${o.method} ${o.path}`; - if (index.has(key)) throw new Error(`Duplicate operation ${key}`); - const spec = SPECS.find((s) => s.key === o.specKey); - index.set(key, { - ...o, - publishedUrl: `${siteUrl}${spec.publishedPath}`, - pageUrl: undefined, - title: undefined, - }); - } - return index; -} - -let loadedIndex = null; -// Operation keys whose page content rehype-api-markdown replaced since the index was set. -let replacedEndpoints = new Set(); - -function setLoadedIndex(index) { - loadedIndex = index; - replacedEndpoints = new Set(); -} - -function getLoadedIndex() { - if (!loadedIndex) throw new Error("API spec index not loaded"); - return loadedIndex; -} - -function recordReplacedEndpoint(key) { - replacedEndpoints.add(key); -} - -// Every operation has a page, so every one must have been replaced. Fewer means -// the theme's endpoint markup changed and pages shipped as sparse Markdown. -function assertAllEndpointsReplaced() { - const index = getLoadedIndex(); - if (replacedEndpoints.size >= index.size) return; - const missing = [...index.keys()].filter((k) => !replacedEndpoints.has(k)); - throw new Error( - `Only ${replacedEndpoints.size} of ${index.size} API endpoint pages got the spec-derived Markdown ` + - `(is the openapi__method-endpoint markup unchanged?). Missing: ${missing.slice(0, 5).join(", ")}` + - (missing.length > 5 ? ", …" : ""), - ); -} - function normaliseEndpointPath(displayPath) { return displayPath.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, "{$1}"); } -function attachPageUrls(index, siteDir, siteUrl = defaultSiteUrl()) { +function readApiPages(siteDir) { + const pages = new Map(); for (const spec of SPECS) { const dir = path.join(siteDir, spec.docsDir); for (const file of fs.readdirSync(dir)) { @@ -131,15 +85,40 @@ function attachPageUrls(index, siteDir, siteUrl = defaultSiteUrl()) { const method = (text.match(/method=\{"([a-z]+)"\}/) || [])[1]; const p = (text.match(/path=\{"([^"]+)"\}/) || [])[1]; if (!id || !method || !p) continue; - const entry = index.get(`${method.toUpperCase()} ${p}`); - if (entry && entry.specKey === spec.key) { - entry.pageUrl = `${siteUrl}${spec.docsDir}/${id}`; - } + pages.set(`${method.toUpperCase()} ${p}`, `${spec.docsDir}/${id}`); } } - for (const [key, entry] of index) { - if (!entry.pageUrl) throw new Error(`No generated API page for ${key}`); + return pages; +} + +function buildOperationIndex(specs, pages, titles, siteUrl = defaultSiteUrl()) { + const index = new Map(); + for (const o of listOperations(specs)) { + const key = `${o.method} ${o.path}`; + if (index.has(key)) throw new Error(`Duplicate operation ${key}`); + const route = pages.get(key); + if (!route) throw new Error(`No generated API page for ${key}`); + const title = titles.get(key); + if (!title) throw new Error(`No title for ${key}`); + const spec = SPECS.find((s) => s.key === o.specKey); + index.set(key, { + ...o, + publishedUrl: `${siteUrl}${spec.publishedPath}`, + pageUrl: `${siteUrl}${route}`, + title: title.title, + }); } + return index; +} + +function assertAllEndpointsReplaced(index, replacedKeys) { + if (replacedKeys.size >= index.size) return; + const missing = [...index.keys()].filter((k) => !replacedKeys.has(k)); + throw new Error( + `Only ${replacedKeys.size} of ${index.size} API endpoint pages got the spec-derived Markdown ` + + `(is the openapi__method-endpoint markup unchanged?). Missing: ${missing.slice(0, 5).join(", ")}` + + (missing.length > 5 ? ", …" : ""), + ); } module.exports = { @@ -147,11 +126,8 @@ module.exports = { loadRawSpecsSync, listOperations, loadDereferencedSpecs, + normaliseEndpointPath, + readApiPages, buildOperationIndex, - setLoadedIndex, - getLoadedIndex, - recordReplacedEndpoint, assertAllEndpointsReplaced, - normaliseEndpointPath, - attachPageUrls, }; diff --git a/plugins/llms-markdown/api/spec-index.test.js b/plugins/llms-markdown/api/spec-index.test.js index 7ee538f4..6e150689 100644 --- a/plugins/llms-markdown/api/spec-index.test.js +++ b/plugins/llms-markdown/api/spec-index.test.js @@ -19,29 +19,50 @@ test("listOperations covers both real specs without duplicates", () => { for (const o of ops) assert.match(o.method, /^(GET|PUT|POST|DELETE|PATCH|HEAD|OPTIONS|TRACE)$/); }); -test("buildOperationIndex keys archiveGoal and dereferences", async () => { - const index = si.buildOperationIndex(await si.loadDereferencedSpecs(siteDir)); +const keyOf = (o) => `${o.method} ${o.path}`; +const pagesFor = (specs) => + new Map(si.listOperations(specs).map((o) => [keyOf(o), `/docs/test/${o.operationId}`])); +const titlesFor = (specs) => new Map(si.listOperations(specs).map((o) => [keyOf(o), { title: `Title ${o.operationId}` }])); +const indexFor = (specs, siteUrl) => si.buildOperationIndex(specs, pagesFor(specs), titlesFor(specs), siteUrl); + +test("buildOperationIndex builds complete, dereferenced entries", async () => { + const index = indexFor(await si.loadDereferencedSpecs(siteDir)); const entry = index.get("PUT /goals/{goalId}/archive"); - assert.ok(entry); assert.strictEqual(entry.operationId, "ArchiveGoal"); assert.strictEqual(entry.specKey, "webConsole"); - assert.ok(entry.publishedUrl.endsWith("web-console-api.yaml")); - assert.strictEqual(entry.title, undefined); + assert.strictEqual(entry.publishedUrl, "https://docs.absmartly.com/openapi/web-console-api.yaml"); + assert.strictEqual(entry.pageUrl, "https://docs.absmartly.com/docs/test/ArchiveGoal"); + assert.strictEqual(entry.title, "Title ArchiveGoal"); assert.ok(!JSON.stringify(entry.op.parameters || []).includes('"$ref"')); }); -test("duplicate method+path across specs throws", () => { - const op = { operationId: "x", summary: "s" }; - const spec = () => ({ paths: { "/a": { get: op } } }); - const specs = new Map([ - ["collector", spec()], - ["webConsole", spec()], +test("buildOperationIndex uses the given site URL", async () => { + const entry = indexFor(await si.loadDereferencedSpecs(siteDir), "https://preview.example").get("PUT /goals/{goalId}/archive"); + assert.strictEqual(entry.publishedUrl, "https://preview.example/openapi/web-console-api.yaml"); + assert.strictEqual(entry.pageUrl, "https://preview.example/docs/test/ArchiveGoal"); +}); + +const tinySpecs = (collectorPaths, webConsolePaths) => + new Map([ + ["collector", { paths: collectorPaths }], + ["webConsole", { paths: webConsolePaths }], ]); - assert.throws(() => si.buildOperationIndex(specs), /Duplicate operation/); +const op = { operationId: "x", summary: "s" }; + +test("duplicate method+path across specs throws", () => { + const specs = tinySpecs({ "/a": { get: op } }, { "/a": { get: op } }); + assert.throws(() => indexFor(specs), /Duplicate operation/); +}); + +test("buildOperationIndex throws for an operation without a page or a title", () => { + const specs = tinySpecs({}, { "/a": { get: op } }); + const titles = titlesFor(specs); + assert.throws(() => si.buildOperationIndex(specs, new Map(), titles), /No generated API page for GET \/a/); + assert.throws(() => si.buildOperationIndex(specs, pagesFor(specs), new Map()), /No title for GET \/a/); }); test("entries carry path-item parameters", async () => { - const index = si.buildOperationIndex(await si.loadDereferencedSpecs(siteDir)); + const index = indexFor(await si.loadDereferencedSpecs(siteDir)); const entry = index.get("GET /experiments/{experimentId}"); assert.ok(entry.pathParameters.some((p) => p.name === "experimentId" && p.in === "path")); assert.deepStrictEqual(index.get("GET /healthy").pathParameters, []); @@ -54,23 +75,11 @@ test("normaliseEndpointPath converts colon params", () => { ); }); -test("getLoadedIndex throws until set", () => { - assert.throws(() => si.getLoadedIndex(), /API spec index not loaded/); - const idx = new Map(); - si.setLoadedIndex(idx); - assert.strictEqual(si.getLoadedIndex(), idx); -}); - -test("assertAllEndpointsReplaced counts distinct replaced operations and resets with the index", () => { - si.setLoadedIndex(new Map([["GET /a", {}], ["GET /b", {}]])); - assert.throws(() => si.assertAllEndpointsReplaced(), /0 of 2/); - si.recordReplacedEndpoint("GET /a"); - si.recordReplacedEndpoint("GET /a"); - assert.throws(() => si.assertAllEndpointsReplaced(), /1 of 2[\s\S]*GET \/b/); - si.recordReplacedEndpoint("GET /b"); - si.assertAllEndpointsReplaced(); - si.setLoadedIndex(new Map([["GET /a", {}]])); - assert.throws(() => si.assertAllEndpointsReplaced(), /0 of 1/); +test("assertAllEndpointsReplaced names the operations whose pages were not replaced", () => { + const index = new Map([["GET /a", {}], ["GET /b", {}]]); + assert.throws(() => si.assertAllEndpointsReplaced(index, new Set()), /0 of 2/); + assert.throws(() => si.assertAllEndpointsReplaced(index, new Set(["GET /a"])), /1 of 2[\s\S]*GET \/b/); + si.assertAllEndpointsReplaced(index, new Set(["GET /a", "GET /b"])); }); // Generated API pages (docs/…/*.api.mdx) are gitignored; `yarn gen:api` creates them. @@ -81,23 +90,12 @@ function generatedPagesPresent() { }); } -test("attachPageUrls sets page URLs from generated pages", async (t) => { - if (!generatedPagesPresent()) return t.skip("generated API pages absent: run yarn gen:api"); - const index = si.buildOperationIndex(await si.loadDereferencedSpecs(siteDir)); - si.attachPageUrls(index, siteDir); - assert.strictEqual( - index.get("PUT /goals/{goalId}/archive").pageUrl, - "https://docs.absmartly.com/docs/APIs-and-SDKs/Web-Console-API/archive-goal", - ); - for (const e of index.values()) assert.ok(e.pageUrl, e.operationId); -}); - -test("buildOperationIndex and attachPageUrls use the given site URL", async (t) => { +test("readApiPages finds a generated page for every operation", async (t) => { if (!generatedPagesPresent()) return t.skip("generated API pages absent: run yarn gen:api"); - const site = "https://preview.example"; - const index = si.buildOperationIndex(await si.loadDereferencedSpecs(siteDir), site); - si.attachPageUrls(index, siteDir, site); - const entry = index.get("PUT /goals/{goalId}/archive"); - assert.strictEqual(entry.publishedUrl, `${site}/openapi/web-console-api.yaml`); - assert.strictEqual(entry.pageUrl, `${site}/docs/APIs-and-SDKs/Web-Console-API/archive-goal`); + const pages = si.readApiPages(siteDir); + assert.strictEqual(pages.get("PUT /goals/{goalId}/archive"), "/docs/APIs-and-SDKs/Web-Console-API/archive-goal"); + for (const o of si.listOperations(si.loadRawSpecsSync(siteDir))) { + const docsDir = si.SPECS.find((s) => s.key === o.specKey).docsDir; + assert.ok(pages.get(keyOf(o))?.startsWith(`${docsDir}/`), keyOf(o)); + } }); diff --git a/plugins/llms-markdown/llms-txt-wrapper.js b/plugins/llms-markdown/llms-txt-wrapper.js index 03144ca7..59dc1d15 100644 --- a/plugins/llms-markdown/llms-txt-wrapper.js +++ b/plugins/llms-markdown/llms-txt-wrapper.js @@ -1,31 +1,16 @@ -// Wraps @signalwire/docusaurus-plugin-llms-txt so the OpenAPI operation index -// is loaded before its postBuild converts pages (rehype-api-markdown reads it), -// and so the generated llms.txt / llms-full.txt are post-processed after it. -// Docusaurus runs every plugin's postBuild concurrently, so the index must be -// built inside this postBuild, before awaiting the inner one. -// -// Options are the inner plugin's, plus `postProcess` (see postprocess-llms.js). - const { createRequire } = require("module"); const { - loadRawSpecsSync, - listOperations, loadDereferencedSpecs, + readApiPages, buildOperationIndex, - attachPageUrls, - setLoadedIndex, assertAllEndpointsReplaced, } = require("./api/spec-index"); -const { buildTitleMap } = require("./api/api-titles"); +const rehypeApiMarkdown = require("./rehype-api-markdown"); const { postProcessLlms } = require("./postprocess-llms"); const INNER = "@signalwire/docusaurus-plugin-llms-txt"; -// The package's ESM build uses extensionless imports that Node rejects, so it -// is loaded with jiti, as Docusaurus loads plugins (@docusaurus/utils' -// loadFreshModule). That helper is async and Docusaurus calls validateOptions -// synchronously, so this uses the same jiti, resolved from @docusaurus/utils, -// synchronously. +// Loaded with jiti, as Docusaurus does: the package's ESM build has extensionless imports Node rejects. let innerModule; function loadInnerModule() { if (!innerModule) { @@ -35,59 +20,64 @@ function loadInnerModule() { return innerModule; } -async function buildApiIndex(siteDir, siteUrl) { - const index = buildOperationIndex(await loadDereferencedSpecs(siteDir), siteUrl); - attachPageUrls(index, siteDir, siteUrl); - const titles = buildTitleMap(listOperations(loadRawSpecsSync(siteDir))); - for (const [key, entry] of index) { - const title = titles.get(key); - if (!title) throw new Error(`No title for ${key}`); - entry.title = title.title; - } - return index; +async function loadApiIndex(siteDir, titles, siteUrl) { + return buildOperationIndex(await loadDereferencedSpecs(siteDir), readApiPages(siteDir), titles, siteUrl); +} + +function withApiMarkdown(innerOptions, apiMarkdownOptions) { + const content = innerOptions.content ?? {}; + return { + ...innerOptions, + content: { + ...content, + beforeDefaultRehypePlugins: [ + [rehypeApiMarkdown, apiMarkdownOptions], + ...(content.beforeDefaultRehypePlugins ?? []), + ], + }, + }; } -// verifyApiPages runs after the inner postBuild and throws unless every API -// endpoint page was replaced by rehype-api-markdown. -function createLlmsTxtWrapper({ loadInner, buildIndex, verifyApiPages, postProcess }) { +function createLlmsTxtWrapper({ loadInner, loadApiIndex, postProcess }) { return async function llmsTxtWrapper(context, options) { - const { postProcess: postProcessOptions, ...innerOptions } = options; + const { postProcess: postProcessOptions, apiTitles, ...innerOptions } = options; const innerFactory = await loadInner(); const inner = await innerFactory(context, innerOptions); - // Undefined (no siteConfig) falls back to plugins/site-url.js downstream. const siteUrl = context.siteConfig?.url; return { ...inner, async postBuild(props) { - await buildIndex(props.siteDir || context.siteDir, siteUrl); - await inner.postBuild(props); - verifyApiPages(); - await postProcess(props.outDir, postProcessOptions, siteUrl); + const index = await loadApiIndex(props.siteDir || context.siteDir, apiTitles, siteUrl); + const replaced = new Set(); + const converter = await innerFactory( + context, + withApiMarkdown(innerOptions, { index, siteUrl, onReplaced: (key) => replaced.add(key) }), + ); + await converter.postBuild(props); + assertAllEndpointsReplaced(index, replaced); + await postProcess(props.outDir, postProcessOptions, index, siteUrl); }, }; }; } -// Validates the inner plugin's options at config load; `postProcess` is ours. function createValidateOptions(getInnerValidate) { return function validateOptions({ options, validate }) { - const { postProcess, ...innerOptions } = options; + const { postProcess, apiTitles, ...innerOptions } = options; const validated = getInnerValidate()({ options: innerOptions, validate }); - return { ...validated, postProcess }; + return { ...validated, postProcess, apiTitles }; }; } -const defaultDeps = { +const llmsTxtWrapper = createLlmsTxtWrapper({ loadInner: async () => { const inner = loadInnerModule(); return inner.default ?? inner; }, - buildIndex: async (siteDir, siteUrl) => setLoadedIndex(await buildApiIndex(siteDir, siteUrl)), - verifyApiPages: assertAllEndpointsReplaced, + loadApiIndex, postProcess: postProcessLlms, -}; -const llmsTxtWrapper = createLlmsTxtWrapper(defaultDeps); +}); module.exports = llmsTxtWrapper; module.exports.validateOptions = createValidateOptions(() => loadInnerModule().validateOptions); -module.exports._internal = { buildApiIndex, createLlmsTxtWrapper, createValidateOptions, defaultDeps }; +module.exports._internal = { createLlmsTxtWrapper, createValidateOptions }; diff --git a/plugins/llms-markdown/llms-txt-wrapper.test.js b/plugins/llms-markdown/llms-txt-wrapper.test.js index 1b48f62e..c63afd2f 100644 --- a/plugins/llms-markdown/llms-txt-wrapper.test.js +++ b/plugins/llms-markdown/llms-txt-wrapper.test.js @@ -2,75 +2,91 @@ const test = require("node:test"); const assert = require("node:assert"); const { createLlmsTxtWrapper, createValidateOptions } = require("./llms-txt-wrapper")._internal; -test("postBuild sets the API index, then awaits the inner postBuild, then post-processes", async () => { +const rehypeApiMarkdown = require("./rehype-api-markdown"); +const tick = () => new Promise((r) => setTimeout(r, 5)); +const cleanup = () => {}; + +function fakeInner(calls, created, replaceKeys = []) { + return async () => (context, options) => { + created.push(options); + return { + name: "inner", + loadContent: () => "inner-content", + async postBuild() { + calls.push("inner:start"); + const [plugin, apiOptions] = options.content.beforeDefaultRehypePlugins[0]; + assert.strictEqual(plugin, rehypeApiMarkdown); + for (const key of replaceKeys) apiOptions.onReplaced(key); + await tick(); + calls.push("inner:end"); + }, + }; + }; +} + +const INDEX = new Map([["GET /a", { pageUrl: "https://x/a" }]]); + +test("postBuild loads the API index, converts pages with it, then post-processes with it", async () => { const calls = []; - const tick = () => new Promise((r) => setTimeout(r, 5)); - let innerOptions; + const created = []; const wrapper = createLlmsTxtWrapper({ - loadInner: async () => (context, options) => { - innerOptions = options; - return { - name: "inner", - loadContent: () => "inner-content", - async postBuild() { - calls.push("inner:start"); - await tick(); - calls.push("inner:end"); - }, - }; - }, - buildIndex: async (siteDir) => { + loadInner: fakeInner(calls, created, ["GET /a"]), + loadApiIndex: async (siteDir, titles, siteUrl) => { await tick(); - calls.push(`index:${siteDir}`); + calls.push(`index:${siteDir}:${titles.get("GET /a")}:${siteUrl}`); + return INDEX; }, - verifyApiPages: () => calls.push("verify"), - postProcess: async (outDir, options) => { - calls.push(`post:${outDir}:${options.marker}`); + postProcess: async (outDir, options, index, siteUrl) => { + assert.strictEqual(index, INDEX); + calls.push(`post:${outDir}:${options.marker}:${siteUrl}`); }, }); - const plugin = await wrapper({ siteDir: "/site" }, { depth: 2, postProcess: { marker: "m" } }); - assert.deepStrictEqual(innerOptions, { depth: 2 }, "postProcess must not reach the inner plugin"); + const options = { + depth: 2, + postProcess: { marker: "m" }, + apiTitles: new Map([["GET /a", "A"]]), + content: { beforeDefaultRehypePlugins: [cleanup] }, + }; + const plugin = await wrapper({ siteDir: "/site", siteConfig: { url: "https://site" } }, options); + assert.deepStrictEqual(created[0], { depth: 2, content: { beforeDefaultRehypePlugins: [cleanup] } }); assert.strictEqual(plugin.name, "inner"); assert.strictEqual(plugin.loadContent(), "inner-content"); await plugin.postBuild({ outDir: "/out" }); - assert.deepStrictEqual(calls, ["index:/site", "inner:start", "inner:end", "verify", "post:/out:m"]); + assert.deepStrictEqual(calls, ["index:/site:A:https://site", "inner:start", "inner:end", "post:/out:m:https://site"]); + const [[plugin0, apiOptions], next] = created[1].content.beforeDefaultRehypePlugins; + assert.strictEqual(plugin0, rehypeApiMarkdown); + assert.strictEqual(apiOptions.index, INDEX); + assert.strictEqual(apiOptions.siteUrl, "https://site"); + assert.strictEqual(next, cleanup); }); test("postBuild fails when API pages were not all replaced", async () => { let postProcessed = false; const wrapper = createLlmsTxtWrapper({ - loadInner: async () => () => ({ async postBuild() {} }), - buildIndex: async () => {}, - verifyApiPages: () => { - throw new Error("Only 0 of 2 API endpoint pages"); - }, + loadInner: fakeInner([], []), + loadApiIndex: async () => INDEX, postProcess: async () => { postProcessed = true; }, }); const plugin = await wrapper({ siteDir: "/site" }, {}); - await assert.rejects(plugin.postBuild({ outDir: "/out" }), /Only 0 of 2/); + await assert.rejects(plugin.postBuild({ outDir: "/out" }), /Only 0 of 1[\s\S]*GET \/a/); assert.strictEqual(postProcessed, false); }); -test("the default wrapper verifies with the spec index's completeness check", () => { - const { defaultDeps } = require("./llms-txt-wrapper")._internal; - const si = require("./api/spec-index"); - assert.strictEqual(defaultDeps.verifyApiPages, si.assertAllEndpointsReplaced); -}); - -test("validateOptions validates without postProcess and keeps it on the result", () => { +test("validateOptions validates without postProcess and apiTitles and keeps them on the result", () => { let seen; + const titles = new Map(); const validateOptions = createValidateOptions(() => ({ options, validate }) => { seen = options; return { ...validate(options), id: "default" }; }); const result = validateOptions({ - options: { depth: 2, postProcess: { a: 1 } }, + options: { depth: 2, postProcess: { a: 1 }, apiTitles: titles }, validate: (o) => ({ ...o, validated: true }), }); assert.deepStrictEqual(seen, { depth: 2 }); - assert.deepStrictEqual(result, { depth: 2, validated: true, id: "default", postProcess: { a: 1 } }); + assert.deepStrictEqual(result, { depth: 2, validated: true, id: "default", postProcess: { a: 1 }, apiTitles: titles }); }); test("the exported validateOptions runs the real inner validation", () => { diff --git a/plugins/llms-markdown/postprocess-llms.js b/plugins/llms-markdown/postprocess-llms.js index 5b1f1782..4a2cc7fc 100644 --- a/plugins/llms-markdown/postprocess-llms.js +++ b/plugins/llms-markdown/postprocess-llms.js @@ -8,7 +8,6 @@ const fs = require("fs"); const path = require("path"); -const { getLoadedIndex } = require("./api/spec-index"); const { encodeUrlPath, POINTER_LEAD } = require("./pointer"); const { siteUrl: defaultSiteUrl } = require("../site-url"); @@ -194,10 +193,8 @@ function markdownReader(outDir, siteUrl = defaultSiteUrl()) { }; } -function operationsByMarkdownUrl() { - const byMarkdownUrl = new Map(); - for (const entry of getLoadedIndex().values()) byMarkdownUrl.set(`${entry.pageUrl}.md`, entry); - return byMarkdownUrl; +function operationsByMarkdownUrl(index) { + return new Map([...index.values()].map((entry) => [`${entry.pageUrl}.md`, entry])); } // .md URL -> Markdown for every page entry of the (original) llms.txt. @@ -211,14 +208,14 @@ function pagesOf(llmsTxt, readMd) { return pages; } -async function postProcessLlms(outDir, options, siteUrl = defaultSiteUrl()) { +async function postProcessLlms(outDir, options, index, siteUrl = defaultSiteUrl()) { if (!options) throw new Error("llms-txt wrapper: missing postProcess options"); const { startHere, apiIndexHeader, fullNote } = options; const llmsTxtPath = path.join(outDir, "llms.txt"); const fullPath = path.join(outDir, "llms-full.txt"); const readMd = markdownReader(outDir, siteUrl); - const operations = operationsByMarkdownUrl(); + const operations = operationsByMarkdownUrl(index); const llmsTxt = fs.readFileSync(llmsTxtPath, "utf8"); const { main, apiIndex } = rewriteLlmsTxt(llmsTxt, { apiDescription: (url) => (operations.has(url) ? apiDescriptionFor(operations.get(url)) : null), diff --git a/plugins/llms-markdown/rehype-api-markdown.js b/plugins/llms-markdown/rehype-api-markdown.js index 449308b2..04f8825e 100644 --- a/plugins/llms-markdown/rehype-api-markdown.js +++ b/plugins/llms-markdown/rehype-api-markdown.js @@ -3,7 +3,7 @@ // generated from the OpenAPI spec (as hast, so the llms-txt pipeline turns it // back into Markdown). Pages without an endpoint pass through untouched. -const { getLoadedIndex, normaliseEndpointPath, recordReplacedEndpoint } = require("./api/spec-index"); +const { normaliseEndpointPath } = require("./api/spec-index"); const { renderOperationMarkdown } = require("./api/render-operation"); const { siteUrl: defaultSiteUrl } = require("../site-url"); @@ -52,17 +52,15 @@ function endpointOf(tree) { }; } -// Options: `siteUrl` (the config's `url`; defaults to plugins/site-url.js). -module.exports = function rehypeApiMarkdown(options = {}) { - const siteUrl = options.siteUrl || defaultSiteUrl(); +module.exports = function rehypeApiMarkdown({ index, onReplaced, siteUrl = defaultSiteUrl() }) { return (tree) => { const endpoint = endpointOf(tree); if (!endpoint) return; const key = `${endpoint.method} ${endpoint.path}`; - const entry = getLoadedIndex().get(key); + const entry = index.get(key); if (!entry) throw new Error(`No OpenAPI operation for ${endpoint.method} ${endpoint.path}`); const hast = markdownToHast(renderOperationMarkdown(entry, { pageUrl: entry.pageUrl, siteUrl })); tree.children = hast.type === "root" ? hast.children : [hast]; - recordReplacedEndpoint(key); + onReplaced(key); }; }; diff --git a/plugins/llms-markdown/rehype-api-markdown.test.js b/plugins/llms-markdown/rehype-api-markdown.test.js index fff8da1f..dbb8036b 100644 --- a/plugins/llms-markdown/rehype-api-markdown.test.js +++ b/plugins/llms-markdown/rehype-api-markdown.test.js @@ -17,16 +17,19 @@ const endpointHtml = (method, displayPath) => `
    ${method} ` +
       `

    ${displayPath}

    client-side stub

    `; -let stubIndex; -async function loadStubIndex() { - if (!stubIndex) { - const full = si.buildOperationIndex(await si.loadDereferencedSpecs(siteDir)); - const entry = full.get("PUT /goals/{goalId}/archive"); - entry.title = "Archive goal"; - entry.pageUrl = PAGE_URL; - stubIndex = new Map([["PUT /goals/{goalId}/archive", entry]]); +const keyOf = (o) => `${o.method} ${o.path}`; +let fullIndex; +async function loadIndex() { + if (!fullIndex) { + const specs = await si.loadDereferencedSpecs(siteDir); + const ops = si.listOperations(specs); + const pages = new Map(ops.map((o) => [keyOf(o), `/docs/test/${o.operationId}`])); + pages.set("PUT /goals/{goalId}/archive", "/docs/APIs-and-SDKs/Web-Console-API/archive-goal"); + const titles = new Map(ops.map((o) => [keyOf(o), { title: `Title ${o.operationId}` }])); + titles.set("PUT /goals/{goalId}/archive", { title: "Archive goal" }); + fullIndex = si.buildOperationIndex(specs, pages, titles); } - si.setLoadedIndex(stubIndex); + return fullIndex; } // Mirrors what the llms-txt plugin hands to rehype plugins: a root wrapping @@ -40,59 +43,52 @@ async function contentRoot(html) { return { type: "root", children: [el] }; } -async function run(tree) { - rehypeApiMarkdown()(tree); +async function run(tree, onReplaced = () => {}) { + rehypeApiMarkdown({ index: await loadIndex(), onReplaced })(tree); const { toHtml } = await import("hast-util-to-html"); return toHtml(tree); } test("replaces an API page's content with the spec-derived reference", async () => { - await loadStubIndex(); const html = await run(await contentRoot(endpointHtml("PUT", "/goals/:goalId/archive"))); assert.match(html, /goalId<\/code><\/td>/); assert.match(html, /

    Archive goal<\/h1>/); assert.match(html, /
    [\s\S]*For AI agents/); + assert.ok(html.includes(`${PAGE_URL}.md`)); assert.ok(!html.includes("client-side stub")); assert.ok(!html.includes("Old title")); }); test("real built archive-goal page", async (t) => { if (!fs.existsSync(builtArchiveGoal)) return t.skip("build/ absent"); - await loadStubIndex(); const html = await run(await contentRoot(fs.readFileSync(builtArchiveGoal, "utf8"))); assert.match(html, /goalId<\/code><\/td>/); assert.match(html, /

    Responses<\/h2>/); }); test("JSON code fences keep their language", async () => { - const full = si.buildOperationIndex(await si.loadDereferencedSpecs(siteDir)); - const entry = full.get("POST /experiments"); - entry.title = "Create experiment"; - entry.pageUrl = "https://docs.absmartly.com/docs/x"; - si.setLoadedIndex(new Map([["POST /experiments", entry]])); const html = await run(await contentRoot(endpointHtml("POST", "/experiments"))); assert.match(html, //); }); test("unknown endpoint throws naming method and path", async () => { - await loadStubIndex(); const tree = await contentRoot(endpointHtml("GET", "/nope/:id")); - assert.throws(() => rehypeApiMarkdown()(tree), /No OpenAPI operation for GET \/nope\/\{id\}/); + await assert.rejects(run(tree), /No OpenAPI operation for GET \/nope\/\{id\}/); }); -test("records each replaced endpoint for the completeness check", async () => { - await loadStubIndex(); - assert.throws(() => si.assertAllEndpointsReplaced(), /0 of 1/); - rehypeApiMarkdown()(await contentRoot(endpointHtml("PUT", "/goals/:goalId/archive"))); - si.assertAllEndpointsReplaced(); +test("reports each replaced endpoint", async () => { + const replaced = []; + await run(await contentRoot(endpointHtml("PUT", "/goals/:goalId/archive")), (key) => replaced.push(key)); + assert.deepStrictEqual(replaced, ["PUT /goals/{goalId}/archive"]); }); test("pages without an endpoint pass through untouched", async () => { - si.setLoadedIndex(new Map()); const tree = await contentRoot( `

    Web Console API

    Intro

    `, ); const before = JSON.stringify(tree); - rehypeApiMarkdown()(tree); + const replaced = []; + await run(tree, (key) => replaced.push(key)); assert.strictEqual(JSON.stringify(tree), before); + assert.deepStrictEqual(replaced, []); }); From 206a79645b3269e72b6d13e8ed9c6d1fbbb2ec0a Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 18:42:57 +0000 Subject: [PATCH 36/43] chore: cut comments to the abs comment rules Drop multi-line and why-it-is-right comments, section dividers and the references to the design doc and rulings; keep one-line comments only where a library or platform workaround needs one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- docusaurus.config.js | 20 +------------ .../edge-functions/markdown-negotiation.js | 25 +--------------- plugins/llms-markdown/api/render-schema.js | 12 ++------ plugins/llms-markdown/api/spec-index.js | 4 --- plugins/llms-markdown/pointer.js | 11 ------- plugins/llms-markdown/postprocess-llms.js | 30 +------------------ .../llms-markdown/postprocess-llms.test.js | 2 +- plugins/llms-markdown/rehype-api-markdown.js | 5 ---- .../rehype-docusaurus-cleanup.js | 2 +- plugins/llms-markdown/remark-tight-lists.js | 7 ----- plugins/site-url.js | 5 ---- src/components/AgentPointer/index.js | 4 --- src/components/PageAiActions/index.js | 8 +---- src/utils/copyMarkdown.js | 12 ++------ src/utils/markdownUrl.js | 3 -- 15 files changed, 11 insertions(+), 139 deletions(-) diff --git a/docusaurus.config.js b/docusaurus.config.js index b3b97427..af10a795 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -12,8 +12,6 @@ const { loadRawSpecsSync, listOperations, SPECS } = require("./plugins/llms-mark const { buildTitleMap, readableApiTitle, titleForMdx } = require("./plugins/llms-markdown/api/api-titles"); const { siteUrl } = require("./plugins/site-url"); -// Production URL, or the deploy's own origin on Netlify deploy previews and -// branch deploys, so agent-facing links on a preview stay on the preview. const SITE_URL = siteUrl(); const apiTitleMap = buildTitleMap(listOperations(loadRawSpecsSync(__dirname))); @@ -28,9 +26,6 @@ function readableCreateApiPageMD(page) { }); } -// "Last updated" dates and sitemap lastmod come from git history. A shallow -// checkout (CI default, possibly Netlify) would stamp every page with the -// checkout date, so they are only enabled when full history is available. function hasFullGitHistory() { try { const out = execFileSync("git", ["rev-parse", "--is-shallow-repository"], { @@ -39,7 +34,7 @@ function hasFullGitHistory() { }); return out.toString().trim() === "false"; } catch { - return false; // no git, or unknown: be safe + return false; } } const gitDates = hasFullGitHistory(); @@ -50,10 +45,6 @@ if (!gitDates) { ); } -// Generated API pages (*.api.mdx, *.info.mdx) are gitignored. Some were tracked -// before and still have history, so git would report a misleading date for -// them; others are untracked and make Docusaurus warn. Report "no date" for -// all of them: no "Last updated" line, no sitemap lastmod, no warning. const defaultVcs = getVcsPreset("default-v1"); const isGeneratedApiPage = (filePath) => /\.(api|info)\.mdx$/.test(filePath) && apiOutputDirs.some((d) => filePath.startsWith(d + path.sep)); @@ -71,8 +62,6 @@ const config = { "Booking.com experimentation culture without the big investment.", url: SITE_URL, baseUrl: "/", - // Matches Netlify, which redirects /docs/foo to /docs/foo/, so canonical - // tags and sitemap URLs point at the served page rather than a redirect. trailingSlash: true, future: { experimental_vcs: vcs }, onBrokenLinks: "throw", @@ -151,7 +140,6 @@ const config = { changefreq: "weekly", priority: 0.5, filename: "sitemap.xml", - // /search is the Algolia search page; /blog redirects off-site. ignorePatterns: ["/search/**", "/search", "/blog/**", "/blog"], lastmod: gitDates ? "date" : null, }, @@ -162,8 +150,6 @@ const config = { plugins: [ "docusaurus-plugin-sass", [ - // .md per page + /llms.txt; see netlify/edge-functions/markdown-negotiation.js. - // Wraps @signalwire/docusaurus-plugin-llms-txt to load the OpenAPI index first. require.resolve("./plugins/llms-markdown/llms-txt-wrapper"), { siteDescription: @@ -175,8 +161,6 @@ const config = { "/docs/APIs-and-SDKs/Web-Console-API/llms.txt.", depth: 2, apiTitles: apiTitleMap, - // Rewrites llms.txt and llms-full.txt after the inner plugin has written - // them; see plugins/llms-markdown/postprocess-llms.js. postProcess: { startHere: [ { @@ -238,7 +222,6 @@ const config = { `and the OpenAPI specs at ${SITE_URL}/openapi/web-console-api.yaml and ` + `${SITE_URL}/openapi/collector-api.yaml.`, }, - // A page that fails to convert would still advertise a .md that 404s. onRouteError: "throw", optionalLinks: [ { @@ -260,7 +243,6 @@ const config = { relativePaths: false, includeBlog: false, includePages: false, - // Routes carry a trailing slash (trailingSlash: true); match both forms. excludeRoutes: ["/search", "/search/", "/search/**"], remarkPlugins: [ require("./plugins/llms-markdown/remark-fix-md-links"), diff --git a/netlify/edge-functions/markdown-negotiation.js b/netlify/edge-functions/markdown-negotiation.js index f7b95924..5e56b7ee 100644 --- a/netlify/edge-functions/markdown-negotiation.js +++ b/netlify/edge-functions/markdown-negotiation.js @@ -1,16 +1,10 @@ // Serves the build-time `.md` at the page URL when the Accept header // prefers text/markdown (browsers never send it), and handles `.md` URLs. -// Every Markdown response carries a canonical Link header to its HTML page. const PRODUCTION_URL = "https://docs.absmartly.com"; const PREVIEW_CONTEXTS = ["deploy-preview", "branch-deploy"]; -// Origin for canonical links: the deploy's own origin on deploy previews and -// branch deploys (matching the build's siteConfig.url, see plugins/site-url.js), -// production otherwise. The build-time CONTEXT/DEPLOY_PRIME_URL variables are -// not always visible to edge functions at runtime, so the edge context's deploy -// context (with the request's origin) is the fallback. The Netlify global is -// absent outside Netlify (tests). +// Netlify does not always expose CONTEXT/DEPLOY_PRIME_URL to edge functions, hence the deploy-context fallback. export function siteOrigin(context, requestOrigin) { if (typeof Netlify !== "undefined") { const prime = Netlify.env.get("DEPLOY_PRIME_URL"); @@ -36,8 +30,6 @@ export function parseAccept(header) { .filter((entry) => entry.type); } -// True when text/markdown is explicitly accepted and preferred at least as much -// as text/html. Wildcards alone never select Markdown. export function prefersMarkdown(acceptHeader) { const entries = parseAccept(acceptHeader); const qFor = (type) => { @@ -68,9 +60,6 @@ export function appendVary(headers) { } } -// Canonical Markdown path for a URL that already asks for Markdown by -// extension: "/docs/foo/index.md", "/docs/foo/.md", "/docs/foo.md/" all map -// to "/docs/foo.md". Returns null when the path is not a .md request. export function canonicalMarkdownPath(pathname) { const m = pathname.match(/^(.*?)(?:\/index)?\/?\.md\/?$/); if (!m) return null; @@ -78,12 +67,10 @@ export function canonicalMarkdownPath(pathname) { return base ? `${base}.md` : null; } -// "/docs/foo.md" -> "/docs/foo/" (the site uses trailing-slash page URLs). export function htmlPathForMarkdown(mdPath) { return mdPath.replace(/\.md$/, "/"); } -// Points search engines at the HTML page instead of its Markdown copy. function setCanonicalLink(headers, mdPath, origin) { headers.append("Link", `<${origin}${htmlPathForMarkdown(mdPath)}>; rel="canonical"`); } @@ -98,9 +85,6 @@ function withHeaders(response, edit) { }); } -// Handles explicit `.md` URLs. The static file is served directly when it -// exists; otherwise normalise odd spellings and follow page redirects (e.g. -// renamed sections in _redirects) to the Markdown of the target page. async function handleMarkdownUrl(request, context, url) { const canonical = canonicalMarkdownPath(url.pathname); if (!canonical) { @@ -116,8 +100,6 @@ async function handleMarkdownUrl(request, context, url) { return withHeaders(response, (h) => setCanonicalLink(h, canonical, siteOrigin(context, url.origin))); } - // A splat in _redirects can match the .md URL before a page-specific rule, - // so follow the redirect of the HTML page URL instead. const pagePath = canonical.replace(/\.md$/, ""); for (const candidate of [pagePath, `${pagePath}/`]) { let probe; @@ -139,8 +121,6 @@ async function handleMarkdownUrl(request, context, url) { return response; } -// Returns { response, path } with the path of the Markdown actually served -// (after redirects), or null on any failure so the caller falls back to HTML. async function fetchMarkdown(mdPath, origin) { try { const res = await fetch(new URL(mdPath, origin), { headers: { accept: "text/markdown" } }); @@ -165,13 +145,10 @@ export default async function handler(request, context) { const markdown = await fetchMarkdown(mdPath, url.origin); if (markdown) { const headers = new Headers(markdown.response.headers); - // fetch() hands back a decoded body; the upstream encoding/length no - // longer describe it. headers.delete("Content-Encoding"); headers.delete("Content-Length"); headers.set("Content-Type", "text/markdown; charset=utf-8"); headers.set("Content-Location", markdown.path); - // The .md response passed through this function and already has its canonical. headers.delete("Link"); setCanonicalLink(headers, markdown.path, siteOrigin(context, url.origin)); appendVary(headers); diff --git a/plugins/llms-markdown/api/render-schema.js b/plugins/llms-markdown/api/render-schema.js index 0a8ee21c..ad6c51dd 100644 --- a/plugins/llms-markdown/api/render-schema.js +++ b/plugins/llms-markdown/api/render-schema.js @@ -14,10 +14,7 @@ function isNullSchema(s) { return isObj(s) && (s.type === "null" || (Array.isArray(s.enum) && s.enum.length === 1 && s.enum[0] === null)); } -// Flatten allOf (recursively) into one view of the schema. Cycle-safe. -// A schema's own keys take precedence over those of its allOf members. -// `null` alternatives in oneOf/anyOf fold into `nullable`; a single remaining -// alternative is merged in directly. +// Flattens allOf (own keys win) and folds `null` oneOf/anyOf alternatives into `nullable`. function merge(schema, seen = new Set()) { const m = { types: [], @@ -73,8 +70,7 @@ function merge(schema, seen = new Set()) { return m; } -// Identity key used for dedupe/recursion: unwrap inline wrappers around a -// single referenced schema (allOf of one, or one non-null alternative). +// Unwraps an allOf of one, or a single non-null alternative, around a referenced schema. function canon(schema) { let s = schema; for (let i = 0; i < 10 && isObj(s); i++) { @@ -186,8 +182,6 @@ function descriptionSentences(m) { return sentences; } -// Lines for the fields of `schema` at nesting `depth` (1 = top level). -// `path` is the chain of schemas currently being rendered (innermost last). function renderFields(schema, ctx, depth, indent, path) { const m = merge(schema); const here = path[path.length - 1]; @@ -270,8 +264,6 @@ function rootBody(schema, m, ctx) { return m.types.length ? `Type: ${typeLabel(m)}.` : ""; } -// Renders each distinct object schema (by identity) in full only once per call; -// later occurrences become a one-line back-reference. function renderSchemaFields(schema, { maxDepth = 6 } = {}) { if (!isObj(schema)) return ""; const m = merge(schema); diff --git a/plugins/llms-markdown/api/spec-index.js b/plugins/llms-markdown/api/spec-index.js index d7e5bfb2..2f5f28ca 100644 --- a/plugins/llms-markdown/api/spec-index.js +++ b/plugins/llms-markdown/api/spec-index.js @@ -1,13 +1,9 @@ -// Shared OpenAPI loader: indexes every operation of both API specs so the -// agent Markdown generators can look operations up by "METHOD /path". - const fs = require("fs"); const path = require("path"); const yaml = require("js-yaml"); const { siteUrl: defaultSiteUrl } = require("../../site-url"); -// Every OpenAPI path-item method; docusaurus-plugin-openapi-docs generates a page for each. const METHODS = ["get", "put", "post", "delete", "patch", "head", "options", "trace"]; const SPECS = [ diff --git a/plugins/llms-markdown/pointer.js b/plugins/llms-markdown/pointer.js index af6d8077..ea881b57 100644 --- a/plugins/llms-markdown/pointer.js +++ b/plugins/llms-markdown/pointer.js @@ -1,10 +1,3 @@ -// Shared with the client bundle, so it takes the site URL as an argument -// (siteConfig.url there; plugins/site-url.js at build time). - -// Percent-encodes characters that may not appear raw in a URL (spaces in -// permalinks such as ".../SSO/Okta SAML Setup", quotes, non-ASCII), so the URL -// survives being pasted into prose or a prompt. Existing %XX escapes and URL -// syntax characters are kept, so encoding twice changes nothing. function encodeUrlPath(url) { return url.replace(/%(?![0-9A-Fa-f]{2})|[^A-Za-z0-9\-._~!$&'()*+,;=:@/?#%]/gu, (c) => encodeURIComponent(c), @@ -13,10 +6,6 @@ function encodeUrlPath(url) { const POINTER_LEAD = "For AI agents: this page is available as Markdown at "; -// The pointer sentence as segments, shared by the Markdown line below and the -// React component (which renders the two URLs as links), so the wording lives -// in one place. `pageUrl` is the page's absolute URL without a trailing slash; -// `siteUrl` is the site's origin without a trailing slash. function pointerParts(pageUrl, siteUrl) { if (!siteUrl) throw new Error("pointerParts: siteUrl is required"); return { diff --git a/plugins/llms-markdown/postprocess-llms.js b/plugins/llms-markdown/postprocess-llms.js index 4a2cc7fc..bad51772 100644 --- a/plugins/llms-markdown/postprocess-llms.js +++ b/plugins/llms-markdown/postprocess-llms.js @@ -1,11 +1,3 @@ -// Post-processes the llms-txt plugin's output (spec Part B2/B3): -// - llms.txt: "Start here" block, Web Console API entries moved to their own -// index (docs/APIs-and-SDKs/Web-Console-API/llms.txt), API entries described -// from the OpenAPI spec, link URLs percent-encoded. -// - llms-full.txt: Web Console API endpoint pages and the per-page agent -// pointer lines dropped, a note added, and the index at the top replaced by -// the new llms.txt. - const fs = require("fs"); const path = require("path"); const { encodeUrlPath, POINTER_LEAD } = require("./pointer"); @@ -17,12 +9,8 @@ const MAX_DESCRIPTION = 200; const SECTION_SEPARATOR = "\n\n---\n\n"; const FULL_CONTENT_HEADING = "# Full Documentation Content\n\n"; -// --- API descriptions ------------------------------------------------------- - const PERMISSIONS = /\*\*Required Permissions\*\*:([^\n]*)/; -// "METHOD /path. ." Permissions are left to the endpoint -// page (ruling R6: they pushed the API index over 50,000 characters). function apiDescriptionFor(operation) { const endpoint = `${operation.method} ${operation.path}.`; const prose = (operation.description || "") @@ -47,8 +35,6 @@ function firstSentence(text) { return null; } -// --- llms.txt ----------------------------------------------------------------- - const ENTRY = /^- \[(.*?)\]\((https?:\/\/[^)]*)\)(?:: (.*))?$/; function renderLinks(links) { @@ -116,9 +102,6 @@ function rewriteLlmsTxt(llmsTxt, { apiDescription, apiIndexUrl, startHere, apiIn return { main: main.join("\n"), apiIndex }; } -// --- llms-full.txt ---------------------------------------------------------------- - -// Inserts `note` as its own paragraph after the header's H1 description blockquote. function addNote(header, note) { const lines = header.trimEnd().split("\n"); let at = lines.findIndex((l) => l.startsWith("> ")); @@ -134,21 +117,13 @@ function withoutPointer(section) { return isPointer ? section.slice(lineEnd + 2) : section; } -// The inner plugin writes llms-full.txt as: the llms.txt content, then -// "\n\n---\n\n# Full Documentation Content\n\n", then each page's .md file -// verbatim followed by "\n\n---\n\n". Pages are recognised by matching their -// known .md content at each position (`pages`: Map<.md URL, Markdown>), not by -// guessing from their first line; pages may contain "---" rules of their own. -// Pages for which isApiPage(url) is true are dropped; every other page is kept -// without its agent pointer line. -// Content that matches no known page throws rather than being guessed at. +// The inner plugin writes each page's .md verbatim plus SECTION_SEPARATOR, and pages may contain "---" themselves. function rewriteLlmsFull(full, { pages, isApiPage, note, header }) { const marker = `${SECTION_SEPARATOR}${FULL_CONTENT_HEADING}`; const at = full.indexOf(marker); if (at < 0) throw new Error("llms-full.txt: no Full Documentation Content section"); const body = full.slice(at + marker.length); - // Candidates by their first characters, longest content first. const PREFIX = 32; const byPrefix = new Map(); for (const [url, markdown] of pages) { @@ -176,8 +151,6 @@ function rewriteLlmsFull(full, { pages, isApiPage, note, header }) { return `${addNote(header ?? full.slice(0, at), note)}${marker}${kept.join("")}`; } -// --- build ------------------------------------------------------------------- - function markdownReader(outDir, siteUrl = defaultSiteUrl()) { return (url) => { if (!url.startsWith(`${siteUrl}/`) || !url.endsWith(".md")) return null; @@ -197,7 +170,6 @@ function operationsByMarkdownUrl(index) { return new Map([...index.values()].map((entry) => [`${entry.pageUrl}.md`, entry])); } -// .md URL -> Markdown for every page entry of the (original) llms.txt. function pagesOf(llmsTxt, readMd) { const pages = new Map(); for (const line of llmsTxt.split("\n")) { diff --git a/plugins/llms-markdown/postprocess-llms.test.js b/plugins/llms-markdown/postprocess-llms.test.js index ad2b15d0..4082de2d 100644 --- a/plugins/llms-markdown/postprocess-llms.test.js +++ b/plugins/llms-markdown/postprocess-llms.test.js @@ -14,7 +14,7 @@ const pointer = (url) => // --- apiDescriptionFor ---------------------------------------------------------- -test("apiDescriptionFor is the endpoint and a prose sentence, without permissions (ruling R6)", () => { +test("apiDescriptionFor is the endpoint and a prose sentence, without permissions", () => { assert.strictEqual( apiDescriptionFor({ method: "PUT", diff --git a/plugins/llms-markdown/rehype-api-markdown.js b/plugins/llms-markdown/rehype-api-markdown.js index 04f8825e..b0dc02a8 100644 --- a/plugins/llms-markdown/rehype-api-markdown.js +++ b/plugins/llms-markdown/rehype-api-markdown.js @@ -1,8 +1,3 @@ -// API reference pages render their schemas client-side, so the built HTML has -// only the endpoint. This replaces such a page's content with the reference -// generated from the OpenAPI spec (as hast, so the llms-txt pipeline turns it -// back into Markdown). Pages without an endpoint pass through untouched. - const { normaliseEndpointPath } = require("./api/spec-index"); const { renderOperationMarkdown } = require("./api/render-operation"); const { siteUrl: defaultSiteUrl } = require("../site-url"); diff --git a/plugins/llms-markdown/rehype-docusaurus-cleanup.js b/plugins/llms-markdown/rehype-docusaurus-cleanup.js index fa665403..bccab1ef 100644 --- a/plugins/llms-markdown/rehype-docusaurus-cleanup.js +++ b/plugins/llms-markdown/rehype-docusaurus-cleanup.js @@ -118,7 +118,7 @@ function transform(node) { if (hasClass(child, "page-ai-actions")) continue; let replacement = null; - // Visually hidden agent pointer (a div, so Algolia skips it) -> blockquote line. + // Agent pointer -> blockquote line. if (hasClass(child, "agent-pointer")) { next.push(el("blockquote", {}, [el("p", {}, child.children)])); continue; diff --git a/plugins/llms-markdown/remark-tight-lists.js b/plugins/llms-markdown/remark-tight-lists.js index 769f70aa..6d86faf5 100644 --- a/plugins/llms-markdown/remark-tight-lists.js +++ b/plugins/llms-markdown/remark-tight-lists.js @@ -1,10 +1,3 @@ -// Remark plugin: make compact lists tight in the generated Markdown. -// hast-util-to-mdast marks any
  • holding a nested list of two or more items -// as "spread", so every list with nested fields (all the API reference pages) -// came out with a blank line between bullets. A list item is compact when it -// has at most one non-list child (one paragraph plus nested lists); a list -// whose items are all compact is written tight. Items with several paragraphs -// or a code block keep their blank lines. function isCompact(item) { return (item.children || []).filter((c) => c.type !== "list").length <= 1; } diff --git a/plugins/site-url.js b/plugins/site-url.js index 5258f26a..43227196 100644 --- a/plugins/site-url.js +++ b/plugins/site-url.js @@ -1,8 +1,3 @@ -// The one place the site's absolute URL comes from. Netlify deploy previews and -// branch deploys build with their own origin (DEPLOY_PRIME_URL), so the -// agent-facing output of a preview (llms.txt, pointer lines, API Markdown, copy -// menu) links to the preview, not to production. Every other build, including -// local ones, uses the production URL. // Server-side only: client code takes the URL from siteConfig.url. const PRODUCTION_URL = "https://docs.absmartly.com"; diff --git a/src/components/AgentPointer/index.js b/src/components/AgentPointer/index.js index 31a773e0..d328ac9a 100644 --- a/src/components/AgentPointer/index.js +++ b/src/components/AgentPointer/index.js @@ -5,10 +5,6 @@ import { pointerParts } from "../../../plugins/llms-markdown/pointer"; import { pageUrlFor } from "../../utils/markdownUrl"; import styles from "./styles.module.css"; -// Line hidden from sighted and screen-reader users that points HTML-reading agents at the page's Markdown -// version and the llms.txt index. A div (not a p) so Algolia does not index it. -// The `agent-pointer` class is the hook rehype-docusaurus-cleanup uses to turn -// it into the Markdown pointer blockquote. export default function AgentPointer() { const { metadata } = useDoc(); const { siteConfig } = useDocusaurusContext(); diff --git a/src/components/PageAiActions/index.js b/src/components/PageAiActions/index.js index 02cdc554..2a591c94 100644 --- a/src/components/PageAiActions/index.js +++ b/src/components/PageAiActions/index.js @@ -12,20 +12,14 @@ const copyLabels = { failed: "Couldn't copy", }; -// "Copy page" dropdown: copies the page's Markdown or opens it in an assistant. -// Built from divs/buttons/anchors (no ul/li) so Algolia's `li` selector skips it; -// the `page-ai-actions` class is the hook rehype-docusaurus-cleanup uses to drop -// it from the Markdown conversion. window/navigator are only used in handlers. export default function PageAiActions() { const { metadata, frontMatter } = useDoc(); const { siteConfig } = useDocusaurusContext(); - // API endpoint pages span the content column and the API explorer, so a right - // float would land beyond the explorer: keep the menu above the title instead. const isInline = Boolean(frontMatter.api); const mdUrl = markdownUrlFor(metadata.permalink, siteConfig.url); const prompt = encodeURIComponent(`Read ${mdUrl} and help me with questions about it.`); const [isOpen, setIsOpen] = useState(false); - const [status, setStatus] = useState("idle"); // idle | copied | failed + const [status, setStatus] = useState("idle"); const rootRef = useRef(null); const triggerRef = useRef(null); const closeTimer = useRef(null); diff --git a/src/utils/copyMarkdown.js b/src/utils/copyMarkdown.js index 3fe3c0c8..764411a8 100644 --- a/src/utils/copyMarkdown.js +++ b/src/utils/copyMarkdown.js @@ -1,8 +1,4 @@ -// Copies the Markdown at `url` to the clipboard. Safari drops the click's user -// activation once a fetch has been awaited, so where ClipboardItem exists the -// clipboard write starts synchronously with a promise for the text; otherwise -// (or if that write is refused) the text is fetched, then written. Rejects when -// the fetch or the copy fails. `deps` are for tests. +// Safari drops the click's user activation after an awaited fetch, so the ClipboardItem write starts first. export async function copyMarkdown(url, deps = {}) { const fetchImpl = deps.fetch ?? ((...args) => window.fetch(...args)); const clipboard = deps.clipboard ?? navigator.clipboard; @@ -14,7 +10,7 @@ export async function copyMarkdown(url, deps = {}) { if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.text(); }); - // Handled below on every path; avoid an unhandled-rejection report meanwhile. + // Awaited below on every path; this only prevents an early unhandled-rejection report. text.catch(() => {}); if (Item && typeof clipboard.write === "function") { @@ -23,9 +19,7 @@ export async function copyMarkdown(url, deps = {}) { blob.catch(() => {}); await clipboard.write([new Item({ "text/plain": blob })]); return; - } catch (e) { - // Fall through to writeText (rethrows if the fetch itself failed). - } + } catch {} } await clipboard.writeText(await text); } diff --git a/src/utils/markdownUrl.js b/src/utils/markdownUrl.js index 2b5344e2..5908d464 100644 --- a/src/utils/markdownUrl.js +++ b/src/utils/markdownUrl.js @@ -1,8 +1,5 @@ import { encodeUrlPath } from "../../plugins/llms-markdown/pointer"; -// Absolute URL of a docs page (and of its Markdown version, generated at build -// time by the llms-txt plugin), percent-encoded: some permalinks contain spaces. -// `siteUrl` is siteConfig.url (the deploy's own origin on Netlify previews). export function pageUrlFor(permalink, siteUrl) { return encodeUrlPath(`${siteUrl}${permalink.replace(/\/+$/, "")}`); } From 37937684b634c186d8ae98fa36ff819bdea8c7d7 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 18:52:03 +0000 Subject: [PATCH 37/43] build(deps): adopt @absmartly/api-mocks 1.0.12 and drop the docs-side spec workarounds 1.0.12 has readable "{Resource} {action}" summaries, labelled examples, the real server and auth header, and no stray `:::`. So: - Delete the title-rewriting layer (api-titles.js, the createApiPageMD and parseFrontMatter overrides, the apiTitles option). Page titles, sidebar labels, breadcrumbs and llms.txt entries now come from the spec summaries; buildOperationIndex takes the title from the summary and needs an explicit site URL. - Delete the stray-`:::` workarounds in the API renderer; real `:::caution` blocks still become labelled quotes and the build check stays. - Don't repeat the generic "Example request" label on request examples. - 301 the renamed metric query page (0100_014addExperimentMetric -> 0100_014queryExperimentMetricData), page URL and .md. - Build checks: Web Console page titles have no `[` and are unique; API rename redirects go from a missing page to a built one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- AGENTS.md | 12 ++-- docusaurus.config.js | 28 +------- package.json | 2 +- plugins/build-checks.test.js | 22 ++++++ plugins/llms-markdown/api/api-titles.js | 64 ----------------- plugins/llms-markdown/api/api-titles.test.js | 69 ------------------- plugins/llms-markdown/api/render-operation.js | 7 +- .../api/render-operation.test.js | 13 ++-- plugins/llms-markdown/api/render-schema.js | 4 +- .../llms-markdown/api/render-schema.test.js | 3 +- plugins/llms-markdown/api/spec-index.js | 9 +-- plugins/llms-markdown/api/spec-index.test.js | 12 ++-- plugins/llms-markdown/llms-txt-wrapper.js | 12 ++-- .../llms-markdown/llms-txt-wrapper.test.js | 14 ++-- .../llms-markdown/postprocess-llms.test.js | 4 -- .../llms-markdown/rehype-api-markdown.test.js | 8 +-- static/_redirects | 6 ++ yarn.lock | 8 +-- 18 files changed, 76 insertions(+), 221 deletions(-) delete mode 100644 plugins/llms-markdown/api/api-titles.js delete mode 100644 plugins/llms-markdown/api/api-titles.test.js diff --git a/AGENTS.md b/AGENTS.md index 0e1456e7..c58f0290 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,16 +73,16 @@ yarn gen:api - API reference Markdown is generated from the OpenAPI specs, not from the client-rendered pages. In its `postBuild` (Docusaurus runs postBuilds concurrently), `llms-txt-wrapper.js` builds the operation index with `buildOperationIndex` (`api/spec-index.js`: dereferenced specs, generated - page URLs, readable titles), then runs the inner plugin with `rehype-api-markdown.js` added + page URLs, titles from the spec summaries), then runs the inner plugin with `rehype-api-markdown.js` added first to `beforeDefaultRehypePlugins` and given that index, and passes the same index to `postprocess-llms.js`. `rehype-api-markdown.js` replaces an endpoint page's content with Markdown from `api/render-operation.js` and `api/render-schema.js`. Auth lines are hand-written there (from `APIs-and-SDKs/overview.mdx`), never derived from `securitySchemes`. The raw specs are also published at `/openapi/*.yaml` (`publish-openapi-specs.js`) and linked from `/llms.txt`. -- Readable API titles (`api/api-titles.js`) are applied at parse time by `markdown.parseFrontMatter` - plus a `createApiPageMD` wrapper in `docusaurus.config.js`, which builds the title map once and - also hands it to the wrapper (`apiTitles` option). Sidebar labels keep the spec summaries, and the - generated `.api.mdx` files still contain the original `title:`. +- API page titles, sidebar labels, breadcrumbs and llms.txt entry titles are the operation + `summary` values from the specs (api-mocks uses readable, unique "{Resource} {action}" summaries, + e.g. "Goal archive"); the docs don't rewrite them. When an operationId changes, the generated page + slug changes too: add a 301 for the old page URL and its `.md` to `static/_redirects`. - `pointer.js` holds the pointer line at the top of every `.md` (and of every rendered page): "For AI agents: this page is available as Markdown at `.md`. The full documentation index is at https://docs.absmartly.com/llms.txt." Its `encodeUrlPath` percent-encodes page URLs (some SSO @@ -142,5 +142,5 @@ yarn gen:api ## Notes - The site URL comes from `plugins/site-url.js` (client code: `siteConfig.url`): Netlify deploy previews and branch deploys use their own `DEPLOY_PRIME_URL`, so their llms.txt, `.md` pages, pointer lines, copy menu and canonical headers link to the preview; every other build uses `https://docs.absmartly.com`. Don't hard-code the production URL elsewhere (a test checks `plugins/` and `src/`); `static/robots.txt` is the exception. -- The Web Console API spec uses placeholder metadata (`sandbox.example.com/v1`, `api@example.com`) from the api-mocks package; this is intentional. +- The Web Console API spec's server (`https://{subdomain}.absmartly.com/v1`) and auth header (`Authorization: Api-Key `) are real; only `info.contact` (`api@example.com`) and `license.url` are still placeholders from the api-mocks package. - `yarn build` may emit a pre-existing broken-anchor warning on `SDK-Documentation/getting-started` (`#using-a-custom-event-logger`) — unrelated to the API docs work. diff --git a/docusaurus.config.js b/docusaurus.config.js index af10a795..b1956763 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -7,25 +7,13 @@ const darkCodeTheme = themes.dracula; const path = require("path"); const { execFileSync } = require("child_process"); const { getVcsPreset } = require("@docusaurus/utils"); -const { createApiPageMD } = require("docusaurus-plugin-openapi-docs/lib/markdown"); -const { loadRawSpecsSync, listOperations, SPECS } = require("./plugins/llms-markdown/api/spec-index"); -const { buildTitleMap, readableApiTitle, titleForMdx } = require("./plugins/llms-markdown/api/api-titles"); +const { SPECS } = require("./plugins/llms-markdown/api/spec-index"); const { siteUrl } = require("./plugins/site-url"); const SITE_URL = siteUrl(); -const apiTitleMap = buildTitleMap(listOperations(loadRawSpecsSync(__dirname))); const apiOutputDirs = SPECS.map((s) => path.join(__dirname, s.docsDir)); -function readableCreateApiPageMD(page) { - const method = String(page.api.method).toUpperCase(); - const entry = apiTitleMap.get(`${method} ${page.api.path}`); - return createApiPageMD({ - ...page, - title: entry ? entry.title : readableApiTitle({ ...page.api, summary: page.title }), - }); -} - function hasFullGitHistory() { try { const out = execFileSync("git", ["rev-parse", "--is-shallow-repository"], { @@ -70,17 +58,6 @@ const config = { markdown: { mermaid: true, hooks: { onBrokenMarkdownLinks: "throw" }, - parseFrontMatter: async ({ filePath, fileContent, defaultParseFrontMatter }) => { - const result = await defaultParseFrontMatter({ filePath, fileContent }); - if (filePath.endsWith(".api.mdx") && apiOutputDirs.some((d) => filePath.startsWith(d + path.sep))) { - const titles = titleForMdx(fileContent, apiTitleMap); - if (titles) { - result.frontMatter.title = titles.title; - result.frontMatter.sidebar_label = titles.sidebarLabel; - } - } - return result; - }, }, // Speeding up the build with swc - was 2m34s on M1 Macbook, now 1m29s @@ -160,7 +137,6 @@ const config = { "pages in one file; the Web Console API endpoints have their own index at " + "/docs/APIs-and-SDKs/Web-Console-API/llms.txt.", depth: 2, - apiTitles: apiTitleMap, postProcess: { startHere: [ { @@ -279,7 +255,6 @@ const config = { docsPluginId: "classic", config: { collector: { - markdownGenerators: { createApiPageMD: readableCreateApiPageMD }, specPath: "api-spec.yaml", // Path to designated spec file outputDir: "docs/APIs-and-SDKs/SDK-API", // Output directory for generated .mdx docs sidebarOptions: { @@ -288,7 +263,6 @@ const config = { }, }, nodeapi: { - markdownGenerators: { createApiPageMD: readableCreateApiPageMD }, specPath: "node_modules/@absmartly/api-mocks/openapi/openapi.bundle.yaml", outputDir: "docs/APIs-and-SDKs/Web-Console-API", // Output directory for generated .mdx docs sidebarOptions: { diff --git a/package.json b/package.json index 3a24fe23..b634a7af 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,7 @@ "sass": "^1.75.0" }, "devDependencies": { - "@absmartly/api-mocks": "1.0.11", + "@absmartly/api-mocks": "1.0.12", "@docusaurus/module-type-aliases": "^3.10.2", "@swc/core": "^1.4.13", "@testing-library/dom": "^10.4.2", diff --git a/plugins/build-checks.test.js b/plugins/build-checks.test.js index ef733753..fe1b1398 100644 --- a/plugins/build-checks.test.js +++ b/plugins/build-checks.test.js @@ -248,6 +248,28 @@ buildTest("hand-written page titles are unique", () => { assert.deepStrictEqual([...seen].filter(([, v]) => v.length > 1), []); }); +buildTest("Web Console API page titles are the readable spec summaries, unique", () => { + const dir = path.join(buildDir, "docs/APIs-and-SDKs/Web-Console-API"); + const titles = fs.readdirSync(dir, { withFileTypes: true }) + .filter((d) => d.isDirectory() && fs.existsSync(path.join(dir, d.name, "index.html"))) + .map((d) => fs.readFileSync(path.join(dir, d.name, "index.html"), "utf8").match(/]*>([^<]*)/)[1]); + assert.ok(titles.length >= 270, `${titles.length} pages`); + assert.deepStrictEqual(titles.filter((t) => t.includes("[")), []); + assert.deepStrictEqual(titles.filter((t, i) => titles.indexOf(t) !== i), []); +}); + +buildTest("redirects of renamed API pages point from a missing page to a built one", () => { + const rules = read("_redirects").split("\n") + .map((l) => l.trim().split(/\s+/)) + .filter(([from]) => from && from.startsWith("/docs/APIs-and-SDKs/Web-Console-API/0")); + assert.ok(rules.length >= 2, "no API rename redirects"); + const built = (p) => fs.existsSync(path.join(buildDir, p.endsWith("/") ? `${p}index.html` : p)); + for (const [from, to] of rules) { + assert.ok(!built(from) && !built(`${from}/`), `${from} still exists`); + assert.ok(built(to), `${to} missing`); + } +}); + buildTest("no hand-written page's H1 is a bare generic heading", () => { const generic = new Set(["# Overview", "# Authentication", "# Experiment Templates"]); const apiDir = /^APIs-and-SDKs\/(Web-Console-API|SDK-API)\//; diff --git a/plugins/llms-markdown/api/api-titles.js b/plugins/llms-markdown/api/api-titles.js deleted file mode 100644 index 61b55ed4..00000000 --- a/plugins/llms-markdown/api/api-titles.js +++ /dev/null @@ -1,64 +0,0 @@ -// Readable titles for API reference pages. Spec summaries such as -// "Goal [UPDATE]" become "Archive goal" (from the operationId); the sidebar -// keeps the original summary. - -const ACRONYMS = { - api: "API", - cors: "CORS", - json: "JSON", - id: "ID", - url: "URL", - sdk: "SDK", - oidc: "OIDC", - sql: "SQL", - csv: "CSV", - mcp: "MCP", -}; - -function formatWords(words) { - const text = words.map((w) => w.toLowerCase()).map((w) => ACRONYMS[w] || w).join(" "); - return text.charAt(0).toUpperCase() + text.slice(1); -} - -function splitCamel(id) { - return id.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+/g) || []; -} - -function readableApiTitle({ operationId, summary }) { - const tag = /^(.*?)\s*\[([^\]]+)\]\s*$/.exec(summary || ""); - if (!tag) return summary; - // e.g. "puteventsUsageAlertsById" has "events" glued onto the verb. - const id = String(operationId || "") - .replace(/^\d+(?:_\d+)?/, "") - .replace(/^(get|put|post|patch|create|update|delete)events(?=[A-Z])/, "$1Events"); - if (/[A-Z]/.test(id)) return formatWords(splitCamel(id)); - const [, noun, verb] = tag; - return formatWords([...verb.trim().split(/\s+/), ...noun.trim().split(/\s+/)]); -} - -function buildTitleMap(ops) { - const entries = ops.map((o) => ({ - key: `${o.method} ${o.path}`, - method: o.method, - path: o.path, - title: readableApiTitle(o), - sidebarLabel: o.summary, - })); - const counts = new Map(); - for (const e of entries) counts.set(e.title, (counts.get(e.title) || 0) + 1); - const map = new Map(); - for (const e of entries) { - const title = counts.get(e.title) > 1 ? `${e.title} (${e.method} ${e.path})` : e.title; - map.set(e.key, { title, sidebarLabel: e.sidebarLabel }); - } - return map; -} - -function titleForMdx(fileContent, titleMap) { - const method = (fileContent.match(/method=\{"([a-z]+)"\}/) || [])[1]; - const p = (fileContent.match(/path=\{"([^"]+)"\}/) || [])[1]; - if (!method || !p) return null; - return titleMap.get(`${method.toUpperCase()} ${p}`) || null; -} - -module.exports = { readableApiTitle, buildTitleMap, titleForMdx }; diff --git a/plugins/llms-markdown/api/api-titles.test.js b/plugins/llms-markdown/api/api-titles.test.js deleted file mode 100644 index 3a7a9b23..00000000 --- a/plugins/llms-markdown/api/api-titles.test.js +++ /dev/null @@ -1,69 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert"); -const path = require("path"); -const si = require("./spec-index"); -const t = require("./api-titles"); - -const siteDir = path.resolve(__dirname, "../../.."); - -test("readableApiTitle passes through untagged summaries", () => { - assert.strictEqual( - t.readableApiTitle({ - operationId: "0100_070getExperimentAssetRoleUsers", - summary: "List Asset Role Users for Experiment", - }), - "List Asset Role Users for Experiment", - ); -}); - -test("readableApiTitle humanises operationIds", () => { - const h = (operationId) => t.readableApiTitle({ operationId, summary: "X [LIST]" }); - assert.strictEqual(h("0100_006restartExperiment"), "Restart experiment"); - assert.strictEqual(h("0200_030getApiKey"), "Get API key"); - assert.strictEqual(h("0100_076patchExperiment"), "Patch experiment"); - assert.strictEqual(h("ArchiveGoal"), "Archive goal"); - assert.strictEqual( - h("048updateExperimentCustomSectionsOrder"), - "Update experiment custom sections order", - ); -}); - -test("readableApiTitle falls back to summary when operationId has no word boundaries", () => { - assert.strictEqual( - t.readableApiTitle({ operationId: "createevents", summary: "Events [LIST]" }), - "List events", - ); -}); - -test("buildTitleMap is unique and covers every real operation", () => { - const ops = si.listOperations(si.loadRawSpecsSync(siteDir)); - const map = t.buildTitleMap(ops); - assert.strictEqual(map.size, ops.length); - const titles = [...map.values()].map((v) => v.title); - assert.strictEqual(new Set(titles).size, titles.length); - assert.deepStrictEqual(map.get("PUT /goals/{goalId}/archive"), { - title: "Archive goal", - sidebarLabel: "Goal [UPDATE]", - }); -}); - -test("buildTitleMap disambiguates duplicate titles", () => { - const map = t.buildTitleMap([ - { method: "GET", path: "/a", operationId: "cancelExportHistory", summary: "A [GET]" }, - { method: "DELETE", path: "/b", operationId: "cancelExportHistory", summary: "B [DELETE]" }, - ]); - assert.strictEqual(map.get("GET /a").title, "Cancel export history (GET /a)"); - assert.strictEqual(map.get("DELETE /b").title, "Cancel export history (DELETE /b)"); - assert.strictEqual(map.get("GET /a").sidebarLabel, "A [GET]"); -}); - -test("titleForMdx reads method and path from generated mdx", () => { - const map = t.buildTitleMap(si.listOperations(si.loadRawSpecsSync(siteDir))); - const mdx = `---\nid: archive-goal\n---\n\n\n`; - assert.deepStrictEqual(t.titleForMdx(mdx, map), { - title: "Archive goal", - sidebarLabel: "Goal [UPDATE]", - }); - assert.strictEqual(t.titleForMdx("no endpoint here", map), null); - assert.strictEqual(t.titleForMdx(`method={"get"} path={"/nope"}`, map), null); -}); diff --git a/plugins/llms-markdown/api/render-operation.js b/plugins/llms-markdown/api/render-operation.js index c1bb2c03..031eb21a 100644 --- a/plugins/llms-markdown/api/render-operation.js +++ b/plugins/llms-markdown/api/render-operation.js @@ -34,7 +34,6 @@ function stripAdmonitions(text) { .split("\n") .filter((l) => !/^\s*:::/.test(l)) .join("\n") - .replace(/:::\w*/g, "") .trim(); } @@ -59,7 +58,6 @@ function quoteAdmonitions(text) { if (open) out.push(admonitionQuote(open.type, open.lines)); return out .join("\n") - .replace(/:::\w*/g, "") .replace(/[ \t]+$/gm, "") .trim(); } @@ -132,7 +130,7 @@ function sample(fn, schema) { function jsonBlock(value) { const text = typeof value === "string" ? value : JSON.stringify(value, null, 2); - return "```json\n" + text.replace(/:::/g, ":: :") + "\n```"; + return "```json\n" + text + "\n```"; } function isNotOk(value) { @@ -183,7 +181,8 @@ function build(entry, pageUrl, { requestDepth, responseDepth, examples, siteUrl const note = fields || exs.length ? fields : "No schema is defined for this body."; push(`## Request body (\`${body.type}\`)` + (note ? `\n\n${note}` : "")); for (const ex of exs) { - const suffix = ex.generated ? " (generated from the schema)" : ex.label ? `: ${ex.label}` : ""; + const label = ex.label === "Example request" ? null : ex.label; + const suffix = ex.generated ? " (generated from the schema)" : label ? `: ${label}` : ""; push(`### Example request body${suffix}\n\n${jsonBlock(ex.value)}`); } } diff --git a/plugins/llms-markdown/api/render-operation.test.js b/plugins/llms-markdown/api/render-operation.test.js index c2b5693d..f1ea9496 100644 --- a/plugins/llms-markdown/api/render-operation.test.js +++ b/plugins/llms-markdown/api/render-operation.test.js @@ -2,7 +2,6 @@ const test = require("node:test"); const assert = require("node:assert"); const path = require("path"); const si = require("./spec-index"); -const { buildTitleMap } = require("./api-titles"); const { renderOperationMarkdown, MAX_CHARS, SIZE_BUDGET } = require("./render-operation"); const { pointerLine } = require("../pointer"); @@ -12,8 +11,7 @@ async function load() { if (!cached) { const specs = await si.loadDereferencedSpecs(siteDir); const pages = new Map(si.listOperations(specs).map((o) => [`${o.method} ${o.path}`, `/docs/test/${o.operationId}`])); - const titles = buildTitleMap(si.listOperations(si.loadRawSpecsSync(siteDir))); - cached = si.buildOperationIndex(specs, pages, titles); + cached = si.buildOperationIndex(specs, pages, "https://docs.absmartly.com"); } return cached; } @@ -38,7 +36,7 @@ test("archive goal page", async () => { const e = (await load()).get("PUT /goals/{goalId}/archive"); const md = render(e); assert.ok(md.startsWith(pointerLine(e.pageUrl, SITE))); - assert.ok(md.includes("# Archive goal")); + assert.ok(md.includes("# Goal archive")); assert.ok(md.includes("`PUT /goals/{goalId}/archive`")); assert.match(md, /## Path parameters[\s\S]*\| `goalId` \|/); assert.ok(md.includes("Api-Key")); @@ -317,7 +315,10 @@ test("type arrays read 'a or b' in parameter tables", () => { test("the full-on page shows the success example and the ok discriminator", async () => { const md = render((await load()).get("PUT /experiments/{experimentId}/full_on")); assert.ok(md.includes("`https://.absmartly.com/v1`")); - assert.ok(md.includes("Example: `put_experiments_id_full_on_200`"), md); + assert.ok(md.includes("### Example request body\n"), md); + const labels = md.split("\n").filter((l) => l.startsWith("Example: ")); + assert.strictEqual(labels[0], "Example: Success"); + assert.ok(labels.slice(1).length >= 1 && labels.slice(1).every((l) => l.startsWith("Example: Error: ")), labels.join("\n")); assert.match(md, /"ok": true/); assert.match(md, /"ok": false/); assert.ok(md.includes("Option 1 (`ok: true`)")); @@ -327,7 +328,7 @@ test("the full-on page shows the success example and the ok discriminator", asyn test("admonitions in the description become labelled blockquotes", () => { const md = renderOperationMarkdown( fixture("webConsole", { - description: "**Required**: x :::\n\n:::caution\nFirst line.\n\nSecond line.\n:::\n\n:::note Heads up\nA note.\n:::", + description: "**Required**: x\n\n:::caution\nFirst line.\n\nSecond line.\n:::\n\n:::note Heads up\nA note.\n:::", }), { pageUrl: "https://x/y" }, ); diff --git a/plugins/llms-markdown/api/render-schema.js b/plugins/llms-markdown/api/render-schema.js index ad6c51dd..3fafbf05 100644 --- a/plugins/llms-markdown/api/render-schema.js +++ b/plugins/llms-markdown/api/render-schema.js @@ -90,8 +90,8 @@ function admonitionLabel(type) { function cleanDescription(text) { return String(text) - .replace(/:::(\w+)/g, (_, type) => admonitionLabel(type)) - .replace(/:::/g, "") + .replace(/^\s*:::(\w+)/gm, (_, type) => admonitionLabel(type)) + .replace(/^\s*:::\s*$/gm, "") .replace(/\s*\n\s*/g, " ") .replace(/\s{2,}/g, " ") .trim(); diff --git a/plugins/llms-markdown/api/render-schema.test.js b/plugins/llms-markdown/api/render-schema.test.js index 94ba17c7..46786462 100644 --- a/plugins/llms-markdown/api/render-schema.test.js +++ b/plugins/llms-markdown/api/render-schema.test.js @@ -86,9 +86,8 @@ test("depth cap emits omission note", () => { test("descriptions are cleaned", () => { const out = renderSchemaFields({ type: "object", - properties: { x: { type: "string", description: "x :::\nline two" } }, + properties: { x: { type: "string", description: "x\n line two" } }, }); - assert.ok(!out.includes(":::")); assert.ok(!out.includes("\nline")); assert.match(out, /x line two/); }); diff --git a/plugins/llms-markdown/api/spec-index.js b/plugins/llms-markdown/api/spec-index.js index 2f5f28ca..983debd8 100644 --- a/plugins/llms-markdown/api/spec-index.js +++ b/plugins/llms-markdown/api/spec-index.js @@ -2,8 +2,6 @@ const fs = require("fs"); const path = require("path"); const yaml = require("js-yaml"); -const { siteUrl: defaultSiteUrl } = require("../../site-url"); - const METHODS = ["get", "put", "post", "delete", "patch", "head", "options", "trace"]; const SPECS = [ @@ -87,21 +85,20 @@ function readApiPages(siteDir) { return pages; } -function buildOperationIndex(specs, pages, titles, siteUrl = defaultSiteUrl()) { +function buildOperationIndex(specs, pages, siteUrl) { const index = new Map(); for (const o of listOperations(specs)) { const key = `${o.method} ${o.path}`; if (index.has(key)) throw new Error(`Duplicate operation ${key}`); const route = pages.get(key); if (!route) throw new Error(`No generated API page for ${key}`); - const title = titles.get(key); - if (!title) throw new Error(`No title for ${key}`); + if (!o.summary) throw new Error(`No summary for ${key}`); const spec = SPECS.find((s) => s.key === o.specKey); index.set(key, { ...o, publishedUrl: `${siteUrl}${spec.publishedPath}`, pageUrl: `${siteUrl}${route}`, - title: title.title, + title: o.summary, }); } return index; diff --git a/plugins/llms-markdown/api/spec-index.test.js b/plugins/llms-markdown/api/spec-index.test.js index 6e150689..d15d714e 100644 --- a/plugins/llms-markdown/api/spec-index.test.js +++ b/plugins/llms-markdown/api/spec-index.test.js @@ -22,8 +22,7 @@ test("listOperations covers both real specs without duplicates", () => { const keyOf = (o) => `${o.method} ${o.path}`; const pagesFor = (specs) => new Map(si.listOperations(specs).map((o) => [keyOf(o), `/docs/test/${o.operationId}`])); -const titlesFor = (specs) => new Map(si.listOperations(specs).map((o) => [keyOf(o), { title: `Title ${o.operationId}` }])); -const indexFor = (specs, siteUrl) => si.buildOperationIndex(specs, pagesFor(specs), titlesFor(specs), siteUrl); +const indexFor = (specs, siteUrl = "https://docs.absmartly.com") => si.buildOperationIndex(specs, pagesFor(specs), siteUrl); test("buildOperationIndex builds complete, dereferenced entries", async () => { const index = indexFor(await si.loadDereferencedSpecs(siteDir)); @@ -32,7 +31,7 @@ test("buildOperationIndex builds complete, dereferenced entries", async () => { assert.strictEqual(entry.specKey, "webConsole"); assert.strictEqual(entry.publishedUrl, "https://docs.absmartly.com/openapi/web-console-api.yaml"); assert.strictEqual(entry.pageUrl, "https://docs.absmartly.com/docs/test/ArchiveGoal"); - assert.strictEqual(entry.title, "Title ArchiveGoal"); + assert.strictEqual(entry.title, "Goal archive"); assert.ok(!JSON.stringify(entry.op.parameters || []).includes('"$ref"')); }); @@ -54,11 +53,10 @@ test("duplicate method+path across specs throws", () => { assert.throws(() => indexFor(specs), /Duplicate operation/); }); -test("buildOperationIndex throws for an operation without a page or a title", () => { +test("buildOperationIndex throws for an operation without a page or a summary", () => { const specs = tinySpecs({}, { "/a": { get: op } }); - const titles = titlesFor(specs); - assert.throws(() => si.buildOperationIndex(specs, new Map(), titles), /No generated API page for GET \/a/); - assert.throws(() => si.buildOperationIndex(specs, pagesFor(specs), new Map()), /No title for GET \/a/); + assert.throws(() => si.buildOperationIndex(specs, new Map(), "https://x"), /No generated API page for GET \/a/); + assert.throws(() => indexFor(tinySpecs({}, { "/a": { get: { operationId: "x" } } })), /No summary for GET \/a/); }); test("entries carry path-item parameters", async () => { diff --git a/plugins/llms-markdown/llms-txt-wrapper.js b/plugins/llms-markdown/llms-txt-wrapper.js index 59dc1d15..0d0af7f9 100644 --- a/plugins/llms-markdown/llms-txt-wrapper.js +++ b/plugins/llms-markdown/llms-txt-wrapper.js @@ -20,8 +20,8 @@ function loadInnerModule() { return innerModule; } -async function loadApiIndex(siteDir, titles, siteUrl) { - return buildOperationIndex(await loadDereferencedSpecs(siteDir), readApiPages(siteDir), titles, siteUrl); +async function loadApiIndex(siteDir, siteUrl) { + return buildOperationIndex(await loadDereferencedSpecs(siteDir), readApiPages(siteDir), siteUrl); } function withApiMarkdown(innerOptions, apiMarkdownOptions) { @@ -40,14 +40,14 @@ function withApiMarkdown(innerOptions, apiMarkdownOptions) { function createLlmsTxtWrapper({ loadInner, loadApiIndex, postProcess }) { return async function llmsTxtWrapper(context, options) { - const { postProcess: postProcessOptions, apiTitles, ...innerOptions } = options; + const { postProcess: postProcessOptions, ...innerOptions } = options; const innerFactory = await loadInner(); const inner = await innerFactory(context, innerOptions); const siteUrl = context.siteConfig?.url; return { ...inner, async postBuild(props) { - const index = await loadApiIndex(props.siteDir || context.siteDir, apiTitles, siteUrl); + const index = await loadApiIndex(props.siteDir || context.siteDir, siteUrl); const replaced = new Set(); const converter = await innerFactory( context, @@ -63,9 +63,9 @@ function createLlmsTxtWrapper({ loadInner, loadApiIndex, postProcess }) { function createValidateOptions(getInnerValidate) { return function validateOptions({ options, validate }) { - const { postProcess, apiTitles, ...innerOptions } = options; + const { postProcess, ...innerOptions } = options; const validated = getInnerValidate()({ options: innerOptions, validate }); - return { ...validated, postProcess, apiTitles }; + return { ...validated, postProcess }; }; } diff --git a/plugins/llms-markdown/llms-txt-wrapper.test.js b/plugins/llms-markdown/llms-txt-wrapper.test.js index c63afd2f..d1a13196 100644 --- a/plugins/llms-markdown/llms-txt-wrapper.test.js +++ b/plugins/llms-markdown/llms-txt-wrapper.test.js @@ -31,9 +31,9 @@ test("postBuild loads the API index, converts pages with it, then post-processes const created = []; const wrapper = createLlmsTxtWrapper({ loadInner: fakeInner(calls, created, ["GET /a"]), - loadApiIndex: async (siteDir, titles, siteUrl) => { + loadApiIndex: async (siteDir, siteUrl) => { await tick(); - calls.push(`index:${siteDir}:${titles.get("GET /a")}:${siteUrl}`); + calls.push(`index:${siteDir}:${siteUrl}`); return INDEX; }, postProcess: async (outDir, options, index, siteUrl) => { @@ -44,7 +44,6 @@ test("postBuild loads the API index, converts pages with it, then post-processes const options = { depth: 2, postProcess: { marker: "m" }, - apiTitles: new Map([["GET /a", "A"]]), content: { beforeDefaultRehypePlugins: [cleanup] }, }; const plugin = await wrapper({ siteDir: "/site", siteConfig: { url: "https://site" } }, options); @@ -52,7 +51,7 @@ test("postBuild loads the API index, converts pages with it, then post-processes assert.strictEqual(plugin.name, "inner"); assert.strictEqual(plugin.loadContent(), "inner-content"); await plugin.postBuild({ outDir: "/out" }); - assert.deepStrictEqual(calls, ["index:/site:A:https://site", "inner:start", "inner:end", "post:/out:m:https://site"]); + assert.deepStrictEqual(calls, ["index:/site:https://site", "inner:start", "inner:end", "post:/out:m:https://site"]); const [[plugin0, apiOptions], next] = created[1].content.beforeDefaultRehypePlugins; assert.strictEqual(plugin0, rehypeApiMarkdown); assert.strictEqual(apiOptions.index, INDEX); @@ -74,19 +73,18 @@ test("postBuild fails when API pages were not all replaced", async () => { assert.strictEqual(postProcessed, false); }); -test("validateOptions validates without postProcess and apiTitles and keeps them on the result", () => { +test("validateOptions validates without postProcess and keeps it on the result", () => { let seen; - const titles = new Map(); const validateOptions = createValidateOptions(() => ({ options, validate }) => { seen = options; return { ...validate(options), id: "default" }; }); const result = validateOptions({ - options: { depth: 2, postProcess: { a: 1 }, apiTitles: titles }, + options: { depth: 2, postProcess: { a: 1 } }, validate: (o) => ({ ...o, validated: true }), }); assert.deepStrictEqual(seen, { depth: 2 }); - assert.deepStrictEqual(result, { depth: 2, validated: true, id: "default", postProcess: { a: 1 }, apiTitles: titles }); + assert.deepStrictEqual(result, { depth: 2, validated: true, id: "default", postProcess: { a: 1 } }); }); test("the exported validateOptions runs the real inner validation", () => { diff --git a/plugins/llms-markdown/postprocess-llms.test.js b/plugins/llms-markdown/postprocess-llms.test.js index 4082de2d..460acea9 100644 --- a/plugins/llms-markdown/postprocess-llms.test.js +++ b/plugins/llms-markdown/postprocess-llms.test.js @@ -61,10 +61,6 @@ test("apiDescriptionFor drops admonitions and permission text, keeps unterminate "GET /events/quota. Get monthly events quota.", ); assert.strictEqual(apiDescriptionFor({ method: "GET", path: "/x" }), "GET /x."); - assert.strictEqual( - apiDescriptionFor({ method: "PUT", path: "/goals/{goalId}/archive", description: "**Required Permissions**: `Goal Archive` or `Goal Admin` :::\n" }), - "PUT /goals/{goalId}/archive.", - ); assert.strictEqual( apiDescriptionFor({ method: "HEAD", path: "/files/{id}", description: "**Required Permissions**: Access to the file based on its usage type." }), "HEAD /files/{id}.", diff --git a/plugins/llms-markdown/rehype-api-markdown.test.js b/plugins/llms-markdown/rehype-api-markdown.test.js index dbb8036b..438f0bbd 100644 --- a/plugins/llms-markdown/rehype-api-markdown.test.js +++ b/plugins/llms-markdown/rehype-api-markdown.test.js @@ -25,9 +25,7 @@ async function loadIndex() { const ops = si.listOperations(specs); const pages = new Map(ops.map((o) => [keyOf(o), `/docs/test/${o.operationId}`])); pages.set("PUT /goals/{goalId}/archive", "/docs/APIs-and-SDKs/Web-Console-API/archive-goal"); - const titles = new Map(ops.map((o) => [keyOf(o), { title: `Title ${o.operationId}` }])); - titles.set("PUT /goals/{goalId}/archive", { title: "Archive goal" }); - fullIndex = si.buildOperationIndex(specs, pages, titles); + fullIndex = si.buildOperationIndex(specs, pages, "https://docs.absmartly.com"); } return fullIndex; } @@ -44,7 +42,7 @@ async function contentRoot(html) { } async function run(tree, onReplaced = () => {}) { - rehypeApiMarkdown({ index: await loadIndex(), onReplaced })(tree); + rehypeApiMarkdown({ index: await loadIndex(), onReplaced, siteUrl: "https://docs.absmartly.com" })(tree); const { toHtml } = await import("hast-util-to-html"); return toHtml(tree); } @@ -52,7 +50,7 @@ async function run(tree, onReplaced = () => {}) { test("replaces an API page's content with the spec-derived reference", async () => { const html = await run(await contentRoot(endpointHtml("PUT", "/goals/:goalId/archive"))); assert.match(html, /goalId<\/code><\/td>/); - assert.match(html, /

    Archive goal<\/h1>/); + assert.match(html, /

    Goal archive<\/h1>/); assert.match(html, /
    [\s\S]*For AI agents/); assert.ok(html.includes(`${PAGE_URL}.md`)); assert.ok(!html.includes("client-side stub")); diff --git a/static/_redirects b/static/_redirects index b9e6b07d..da6565ec 100644 --- a/static/_redirects +++ b/static/_redirects @@ -186,3 +186,9 @@ # APIs-and-SDKs overview rename # ============================================================================= /docs/APIs-and-SDKs/apis-and-sdks /docs/APIs-and-SDKs/overview/ 302 + +# ============================================================================= +# Web Console API operationId rename (api-mocks 1.0.12: 0100_014addExperimentMetric → 0100_014queryExperimentMetricData) +# ============================================================================= +/docs/APIs-and-SDKs/Web-Console-API/0100-014-add-experiment-metric.md /docs/APIs-and-SDKs/Web-Console-API/0100-014-query-experiment-metric-data.md 301 +/docs/APIs-and-SDKs/Web-Console-API/0100-014-add-experiment-metric /docs/APIs-and-SDKs/Web-Console-API/0100-014-query-experiment-metric-data/ 301 diff --git a/yarn.lock b/yarn.lock index 4fc23b10..f3d6f8df 100644 --- a/yarn.lock +++ b/yarn.lock @@ -12,10 +12,10 @@ section-matter "^1.0.0" strip-bom-string "^1.0.0" -"@absmartly/api-mocks@1.0.11": - version "1.0.11" - resolved "https://registry.yarnpkg.com/@absmartly/api-mocks/-/api-mocks-1.0.11.tgz#a9c4ff0f3c61ca54ddd93eabbab10f5125a00217" - integrity sha512-TadRn2wnTBspGlOFvzZF6uHxPlxO9PM3ffaUKYFPWfPw5k8WlRcJIzac6eVlUS7Sb6k/giZZEucbYIMZy+T2kQ== +"@absmartly/api-mocks@1.0.12": + version "1.0.12" + resolved "https://registry.yarnpkg.com/@absmartly/api-mocks/-/api-mocks-1.0.12.tgz#633e1ae741067a001ba820cfc20554cc6af67616" + integrity sha512-+ocYwO+3QKk0xqtzjrjFpHyLSf1v3VA7pv6BjgpeLlca0fgYMiS1iAgN9aOx0c7NdFuM5y3V5Ei4mD42pJQzqQ== dependencies: "@apidevtools/json-schema-ref-parser" "^15.2.2" "@faker-js/faker" "^10.2.0" From 21dc8c43d3597200f47739b1957e646fe7790d51 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 18:52:11 +0000 Subject: [PATCH 38/43] refactor(llms): drop the inner plugin's CLI command and the rehype siteUrl default `docusaurus llms-txt` can't load the API index, so it would write sparse API pages; the wrapper no longer exposes the inner extendCli. rehypeApiMarkdown takes siteUrl from its caller like the rest of the pipeline. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- AGENTS.md | 4 ++-- plugins/llms-markdown/llms-txt-wrapper.js | 3 ++- plugins/llms-markdown/llms-txt-wrapper.test.js | 2 ++ plugins/llms-markdown/rehype-api-markdown.js | 3 +-- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c58f0290..e24c6fda 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -103,8 +103,8 @@ yarn gen:api - The edge function also sets a canonical `Link` header on `.md` responses (for negotiated Markdown, from the final URL when the `.md` fetch was redirected), and `netlify.toml` sets `X-Robots-Tag: noindex` on `/llms-full.txt`. -- Known limits: the inner plugin's `docusaurus llms-txt` CLI command is unsupported (the API index - is not loaded there; use `yarn build`). `yarn clean:api` also deletes the tracked +- Known limits: the inner plugin's `docusaurus llms-txt` CLI command is not registered (the wrapper + drops its `extendCli`, as the API index is not loaded there; use `yarn build`). `yarn clean:api` also deletes the tracked `_category_.json` files in both API dirs; restore them with `git checkout` and never commit the deletion. diff --git a/plugins/llms-markdown/llms-txt-wrapper.js b/plugins/llms-markdown/llms-txt-wrapper.js index 0d0af7f9..0d059daf 100644 --- a/plugins/llms-markdown/llms-txt-wrapper.js +++ b/plugins/llms-markdown/llms-txt-wrapper.js @@ -42,7 +42,8 @@ function createLlmsTxtWrapper({ loadInner, loadApiIndex, postProcess }) { return async function llmsTxtWrapper(context, options) { const { postProcess: postProcessOptions, ...innerOptions } = options; const innerFactory = await loadInner(); - const inner = await innerFactory(context, innerOptions); + // The inner `docusaurus llms-txt` CLI command can't load the API index, so it would write sparse API pages. + const { extendCli, ...inner } = await innerFactory(context, innerOptions); const siteUrl = context.siteConfig?.url; return { ...inner, diff --git a/plugins/llms-markdown/llms-txt-wrapper.test.js b/plugins/llms-markdown/llms-txt-wrapper.test.js index d1a13196..8668fd0a 100644 --- a/plugins/llms-markdown/llms-txt-wrapper.test.js +++ b/plugins/llms-markdown/llms-txt-wrapper.test.js @@ -12,6 +12,7 @@ function fakeInner(calls, created, replaceKeys = []) { return { name: "inner", loadContent: () => "inner-content", + extendCli: () => {}, async postBuild() { calls.push("inner:start"); const [plugin, apiOptions] = options.content.beforeDefaultRehypePlugins[0]; @@ -50,6 +51,7 @@ test("postBuild loads the API index, converts pages with it, then post-processes assert.deepStrictEqual(created[0], { depth: 2, content: { beforeDefaultRehypePlugins: [cleanup] } }); assert.strictEqual(plugin.name, "inner"); assert.strictEqual(plugin.loadContent(), "inner-content"); + assert.strictEqual(plugin.extendCli, undefined); await plugin.postBuild({ outDir: "/out" }); assert.deepStrictEqual(calls, ["index:/site:https://site", "inner:start", "inner:end", "post:/out:m:https://site"]); const [[plugin0, apiOptions], next] = created[1].content.beforeDefaultRehypePlugins; diff --git a/plugins/llms-markdown/rehype-api-markdown.js b/plugins/llms-markdown/rehype-api-markdown.js index b0dc02a8..cc76315d 100644 --- a/plugins/llms-markdown/rehype-api-markdown.js +++ b/plugins/llms-markdown/rehype-api-markdown.js @@ -1,6 +1,5 @@ const { normaliseEndpointPath } = require("./api/spec-index"); const { renderOperationMarkdown } = require("./api/render-operation"); -const { siteUrl: defaultSiteUrl } = require("../site-url"); const isEl = (node) => node && node.type === "element"; const hasClass = (node, name) => { @@ -47,7 +46,7 @@ function endpointOf(tree) { }; } -module.exports = function rehypeApiMarkdown({ index, onReplaced, siteUrl = defaultSiteUrl() }) { +module.exports = function rehypeApiMarkdown({ index, onReplaced, siteUrl }) { return (tree) => { const endpoint = endpointOf(tree); if (!endpoint) return; From a9bb27ea4723d2f89071a743e2cb916c96877b13 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 18:52:11 +0000 Subject: [PATCH 39/43] fix(llms): end an API index description at "etc." before a capitalised word Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- plugins/llms-markdown/postprocess-llms.js | 3 ++- plugins/llms-markdown/postprocess-llms.test.js | 10 +++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/plugins/llms-markdown/postprocess-llms.js b/plugins/llms-markdown/postprocess-llms.js index bad51772..bf3e3cd2 100644 --- a/plugins/llms-markdown/postprocess-llms.js +++ b/plugins/llms-markdown/postprocess-llms.js @@ -24,7 +24,8 @@ function apiDescriptionFor(operation) { return sentence.length <= MAX_DESCRIPTION ? `${endpoint} ${sentence}` : endpoint; } -const ABBREVIATION = /(?:^|\s)(?:e\.g|i\.e|etc|vs|cf)\.$/i; +// "etc." is left out: before a capitalised word it ends the sentence. +const ABBREVIATION = /(?:^|\s)(?:e\.g|i\.e|vs|cf)\.$/i; function firstSentence(text) { for (const m of text.matchAll(/[.!?](?=\s|$)/g)) { diff --git a/plugins/llms-markdown/postprocess-llms.test.js b/plugins/llms-markdown/postprocess-llms.test.js index 460acea9..5011e977 100644 --- a/plugins/llms-markdown/postprocess-llms.test.js +++ b/plugins/llms-markdown/postprocess-llms.test.js @@ -67,7 +67,7 @@ test("apiDescriptionFor drops admonitions and permission text, keeps unterminate ); }); -test("apiDescriptionFor does not end the sentence at an abbreviation", () => { +test("apiDescriptionFor ends the sentence at \"etc.\" before a capital, not at other abbreviations", () => { assert.strictEqual( apiDescriptionFor({ method: "GET", path: "/goals", description: "Use e.g. this endpoint to list goals. Paginated." }), "GET /goals. Use e.g. this endpoint to list goals.", @@ -80,6 +80,14 @@ test("apiDescriptionFor does not end the sentence at an abbreviation", () => { apiDescriptionFor({ method: "GET", path: "/units", description: "Returns approx. three units per page. Cached." }), "GET /units. Returns approx. three units per page.", ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/tags", description: "Lists goals, metrics, etc. and their tags. Sorted." }), + "GET /tags. Lists goals, metrics, etc. and their tags.", + ); + assert.strictEqual( + apiDescriptionFor({ method: "GET", path: "/labels", description: "Lists goals, metrics, etc. Paginated." }), + "GET /labels. Lists goals, metrics, etc.", + ); }); test("apiDescriptionFor skips lead images and HTML", () => { From bcc508ab10170ff525a787d7329198f719144f83 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 18:52:11 +0000 Subject: [PATCH 40/43] chore: one-line header comments in the edge function and the cleanup plugin Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- netlify/edge-functions/markdown-negotiation.js | 3 +-- plugins/llms-markdown/rehype-docusaurus-cleanup.js | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/netlify/edge-functions/markdown-negotiation.js b/netlify/edge-functions/markdown-negotiation.js index 5e56b7ee..5302c940 100644 --- a/netlify/edge-functions/markdown-negotiation.js +++ b/netlify/edge-functions/markdown-negotiation.js @@ -1,5 +1,4 @@ -// Serves the build-time `.md` at the page URL when the Accept header -// prefers text/markdown (browsers never send it), and handles `.md` URLs. +// Serves `.md` at the page URL when the Accept header prefers text/markdown, and handles `.md` URLs. const PRODUCTION_URL = "https://docs.absmartly.com"; const PREVIEW_CONTEXTS = ["deploy-preview", "branch-deploy"]; diff --git a/plugins/llms-markdown/rehype-docusaurus-cleanup.js b/plugins/llms-markdown/rehype-docusaurus-cleanup.js index bccab1ef..5395b670 100644 --- a/plugins/llms-markdown/rehype-docusaurus-cleanup.js +++ b/plugins/llms-markdown/rehype-docusaurus-cleanup.js @@ -1,5 +1,4 @@ -// Rewrites Docusaurus theme markup (tabs, code blocks, admonitions, details) -// into plain HTML so the llms-txt HTML -> Markdown conversion keeps its meaning. +// Rewrites Docusaurus theme markup into plain HTML so the HTML -> Markdown conversion keeps its meaning. const el = (tagName, properties, children) => ({ type: "element", From 72e7e812c53f40b54c867a334bec8208fba0a062 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 19:02:52 +0000 Subject: [PATCH 41/43] fix(llms): nest unions beside fields and require the site URL - An object with both fields and oneOf/anyOf renders the union as its own "One of these shapes:" list item with nested options, so the options no longer run on from the last field. Options that only list required fields read "requires `a`, `b`" instead of "any". A build check rejects a "One of:" line followed by an option at its indent. - renderOperationMarkdown and postProcessLlms require siteUrl, the wrapper reads siteConfig.url without a fallback, and the siteUrl() defaults are gone; tests pass the site URL explicitly. - Drop the unused catch binding in PageAiActions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- plugins/build-checks.test.js | 2 + plugins/llms-markdown/api/render-operation.js | 4 +- .../api/render-operation.test.js | 38 ++++++++++--------- plugins/llms-markdown/api/render-schema.js | 10 +++-- .../llms-markdown/api/render-schema.test.js | 33 ++++++++++++++++ plugins/llms-markdown/llms-txt-wrapper.js | 2 +- .../llms-markdown/llms-txt-wrapper.test.js | 2 +- plugins/llms-markdown/postprocess-llms.js | 8 ++-- .../llms-markdown/postprocess-llms.test.js | 8 +++- src/components/PageAiActions/index.js | 2 +- 10 files changed, 79 insertions(+), 30 deletions(-) diff --git a/plugins/build-checks.test.js b/plugins/build-checks.test.js index fe1b1398..99c6e9b0 100644 --- a/plugins/build-checks.test.js +++ b/plugins/build-checks.test.js @@ -61,6 +61,8 @@ buildTest("every API endpoint .md has the spec-derived reference and no admoniti if (dir === "Web-Console-API") assert.ok(!md.includes("absmartly.io/v1"), `${dir}/${f}: Collector base URL`); if (f.endsWith("-api.md") || f.startsWith("examples")) continue; assert.match(md, /^Source: \(operationId `/m, `${dir}/${f}: not rendered from the spec`); + const glued = md.match(/^( *)[*-] [^\n]*One of:\n\1[*-] Option /m); + assert.ok(!glued, `${dir}/${f}: options run on from a field: ${glued && glued[0]}`); endpoints++; } } diff --git a/plugins/llms-markdown/api/render-operation.js b/plugins/llms-markdown/api/render-operation.js index 031eb21a..2ad667ef 100644 --- a/plugins/llms-markdown/api/render-operation.js +++ b/plugins/llms-markdown/api/render-operation.js @@ -1,6 +1,5 @@ const { renderSchemaFields, canReturnNotOk, admonitionLabel } = require("./render-schema"); const { pointerLine } = require("../pointer"); -const { siteUrl: defaultSiteUrl } = require("../../site-url"); const { sampleRequestFromSchema } = require("docusaurus-plugin-openapi-docs/lib/openapi/createRequestExample"); const { sampleResponseFromSchema } = require("docusaurus-plugin-openapi-docs/lib/openapi/createResponseExample"); @@ -223,7 +222,8 @@ function build(entry, pageUrl, { requestDepth, responseDepth, examples, siteUrl } // Size guard: drop extra examples, then response examples, then reduce response depth, then request depth. -function renderOperationMarkdown(entry, { pageUrl, siteUrl = defaultSiteUrl() }) { +function renderOperationMarkdown(entry, { pageUrl, siteUrl }) { + if (!siteUrl) throw new Error("renderOperationMarkdown: siteUrl is required"); const attempts = [ { requestDepth: MAX_DEPTH, responseDepth: MAX_DEPTH, examples: ALL_EXAMPLES }, { requestDepth: MAX_DEPTH, responseDepth: MAX_DEPTH, examples: ONE_EXAMPLE_EACH }, diff --git a/plugins/llms-markdown/api/render-operation.test.js b/plugins/llms-markdown/api/render-operation.test.js index f1ea9496..e64bcd17 100644 --- a/plugins/llms-markdown/api/render-operation.test.js +++ b/plugins/llms-markdown/api/render-operation.test.js @@ -15,7 +15,7 @@ async function load() { } return cached; } -const render = (e) => renderOperationMarkdown(e, { pageUrl: e.pageUrl }); +const render = (e) => renderOperationMarkdown(e, { pageUrl: e.pageUrl, siteUrl: SITE }); // An empty section is a heading directly followed by a heading of the same or higher level. const noEmptySections = (md) => { const re = /^(#+) .*\n\n(#+) /gm; @@ -126,7 +126,7 @@ test("operation-level parameters override path-level ones", () => { responses: {}, }, }; - const md = renderOperationMarkdown(entry, { pageUrl: "https://x/y" }); + const md = renderOperationMarkdown(entry, { pageUrl: "https://x/y", siteUrl: SITE }); assert.ok(md.includes("op-level")); assert.ok(!md.includes("path-level")); assert.ok(md.includes("| `q` |")); @@ -142,7 +142,7 @@ test("enum values escape pipes", () => { publishedUrl: "u", op: { parameters: [{ name: "q", in: "query", schema: { type: "string", enum: ["a|b"] } }], responses: {} }, }; - assert.ok(renderOperationMarkdown(entry, { pageUrl: "https://x/y" }).includes("`a\\|b`")); + assert.ok(renderOperationMarkdown(entry, { pageUrl: "https://x/y", siteUrl: SITE }).includes("`a\\|b`")); }); test("param descriptions and enum lists are separate sentences", () => { @@ -162,7 +162,7 @@ test("param descriptions and enum lists are separate sentences", () => { responses: {}, }, }; - const md = renderOperationMarkdown(entry, { pageUrl: "https://x/y" }); + const md = renderOperationMarkdown(entry, { pageUrl: "https://x/y", siteUrl: SITE }); assert.ok(md.includes("| Filter by sample ratio mismatch. One of: `0`, `1`. |"), md); assert.ok(md.includes("| Ends in a stop. One of: `a`. |")); assert.ok(md.includes("| One of: `b`. |")); @@ -179,8 +179,8 @@ const fixture = (specKey, op) => ({ }); test("the base URL depends on the spec", () => { - const wc = renderOperationMarkdown(fixture("webConsole", {}), { pageUrl: "https://x/y" }); - const collector = renderOperationMarkdown(fixture("collector", {}), { pageUrl: "https://x/y" }); + const wc = renderOperationMarkdown(fixture("webConsole", {}), { pageUrl: "https://x/y", siteUrl: SITE }); + const collector = renderOperationMarkdown(fixture("collector", {}), { pageUrl: "https://x/y", siteUrl: SITE }); assert.ok(wc.includes("`https://.absmartly.com/v1`"), wc); assert.ok(!wc.includes("absmartly.io")); assert.ok(collector.includes("`https://.absmartly.io/v1`"), collector); @@ -205,7 +205,7 @@ test("every named response example is rendered with its summary or key", () => { succeeded: { summary: "Success", value: { ok: true, id: 7 } }, }), ), - { pageUrl: "https://x/y" }, + { pageUrl: "https://x/y", siteUrl: SITE }, ); assert.ok(md.includes("Example: `failed`"), md); assert.ok(md.includes("Example: Success"), md); @@ -216,7 +216,7 @@ test("every named response example is rendered with its summary or key", () => { const NOT_OK = "This endpoint can return HTTP 200 with `ok: false` on failure; always check `ok`."; test("endpoints whose 200 can carry ok: false say so", () => { - const md = renderOperationMarkdown(fixture("webConsole", okResponses(undefined)), { pageUrl: "https://x/y" }); + const md = renderOperationMarkdown(fixture("webConsole", okResponses(undefined)), { pageUrl: "https://x/y", siteUrl: SITE }); assert.ok(md.includes("This endpoint can return HTTP 200 with `ok: false` on failure; always check `ok`."), md); const plain = renderOperationMarkdown( fixture("webConsole", { @@ -224,7 +224,7 @@ test("endpoints whose 200 can carry ok: false say so", () => { 200: { description: "OK", content: { "application/json": { schema: { type: "object", properties: { id: { type: "integer" } } } } } }, }, }), - { pageUrl: "https://x/y" }, + { pageUrl: "https://x/y", siteUrl: SITE }, ); assert.ok(!plain.includes("ok: false")); }); @@ -233,7 +233,7 @@ test("the size guard drops extra examples before the first one", () => { const big = { ok: false, errors: ["x".repeat(MAX_CHARS)] }; const md = renderOperationMarkdown( fixture("webConsole", okResponses({ first: { value: { ok: true, id: 1 } }, second: { value: big } })), - { pageUrl: "https://x/y" }, + { pageUrl: "https://x/y", siteUrl: SITE }, ); assert.ok(md.includes('"id": 1'), md.slice(0, 2000)); assert.ok(!md.includes("xxxxxxxxxx")); @@ -252,7 +252,7 @@ const plainResponses = (examples) => ({ test("an ok: false 200 example triggers the note even when the schema does not model it", () => { const md = renderOperationMarkdown( fixture("webConsole", plainResponses({ failed: { value: { ok: false, errors: ["nope"] } } })), - { pageUrl: "https://x/y" }, + { pageUrl: "https://x/y", siteUrl: SITE }, ); assert.ok(md.includes(NOT_OK), md); }); @@ -261,7 +261,7 @@ test("the example-driven note survives the size guard dropping every response ex const huge = "x".repeat(MAX_CHARS); const md = renderOperationMarkdown( fixture("webConsole", plainResponses({ failed: { value: { ok: false, errors: [huge] } } })), - { pageUrl: "https://x/y" }, + { pageUrl: "https://x/y", siteUrl: SITE }, ); assert.ok(!md.includes("xxxxxxxxxx")); assert.ok(md.includes(NOT_OK), md.slice(0, 2000)); @@ -277,7 +277,7 @@ test("with only one example per response the size guard keeps a success example" huge: { value: { ok: false, errors: ["x".repeat(MAX_CHARS)] } }, }), ), - { pageUrl: "https://x/y" }, + { pageUrl: "https://x/y", siteUrl: SITE }, ); assert.ok(md.includes('"id": 1'), md.slice(0, 2000)); assert.ok(!md.includes("first error")); @@ -287,7 +287,7 @@ test("with only one example per response the size guard keeps a success example" test("example captions keep pipes unescaped", () => { const md = renderOperationMarkdown( fixture("webConsole", okResponses({ a: { summary: "on | off", value: { ok: true, id: 1 } } })), - { pageUrl: "https://x/y" }, + { pageUrl: "https://x/y", siteUrl: SITE }, ); assert.ok(md.includes("Example: on | off"), md); }); @@ -307,7 +307,7 @@ test("real endpoints that return ok: false in a 200 carry the note", async () => test("type arrays read 'a or b' in parameter tables", () => { const md = renderOperationMarkdown( fixture("collector", { parameters: [{ name: "q", in: "query", schema: { type: ["integer", "string"] } }] }), - { pageUrl: "https://x/y" }, + { pageUrl: "https://x/y", siteUrl: SITE }, ); assert.ok(md.includes("| `q` | integer or string | no |"), md); }); @@ -330,7 +330,7 @@ test("admonitions in the description become labelled blockquotes", () => { fixture("webConsole", { description: "**Required**: x\n\n:::caution\nFirst line.\n\nSecond line.\n:::\n\n:::note Heads up\nA note.\n:::", }), - { pageUrl: "https://x/y" }, + { pageUrl: "https://x/y", siteUrl: SITE }, ); assert.ok(md.includes("**Required**: x\n\n> **Caution:** First line.\n>\n> Second line.\n\n> **Note:** A note."), md); assert.ok(!md.includes(":::")); @@ -351,7 +351,7 @@ test("the size guard shrinks the response before the request", () => { requestBody: { content: { "application/json": { schema: deep(4), example: { level4: {} } } } }, responses: { 200: { description: "OK", content: { "application/json": { schema: wide } } } }, }), - { pageUrl: "https://x/y" }, + { pageUrl: "https://x/y", siteUrl: SITE }, ); assert.ok(md.length < SIZE_BUDGET, `${md.length}`); assert.ok(md.includes("deepleaf"), md.slice(0, 1500)); @@ -379,3 +379,7 @@ test("real pages: root shapes, maps, cautions, request depth and back-references assert.ok(!fullOn.includes("(option"), "option numbers in back-references"); assert.match(fullOn, /`seed` \(integer or string\)/); }); + +test("renderOperationMarkdown requires a site URL", () => { + assert.throws(() => renderOperationMarkdown(fixture("collector", {}), { pageUrl: "https://x/y" }), /siteUrl/); +}); diff --git a/plugins/llms-markdown/api/render-schema.js b/plugins/llms-markdown/api/render-schema.js index 3fafbf05..a1a3e8f1 100644 --- a/plugins/llms-markdown/api/render-schema.js +++ b/plugins/llms-markdown/api/render-schema.js @@ -152,6 +152,7 @@ function optionLabels(options) { if (consts.length) return consts.map(code).join(", "); if (opt.title || om.title) return opt.title || om.title; const names = [...om.properties.keys()]; + if (!names.length && !om.types.length && om.required.size) return `requires ${[...om.required].map(code).join(", ")}`; if (!names.length) return typeLabel(om) || "any"; const own = names.filter((n) => !merged.some((other, j) => j !== i && other.properties.has(n))); return `object with ${(own.length ? own : names).slice(0, MAX_LABEL_FIELDS).map(code).join(", ")}`; @@ -195,16 +196,19 @@ function renderFields(schema, ctx, depth, indent, path) { const keyPattern = isObj(m.propertyNames) ? m.propertyNames.pattern : undefined; lines.push(...renderField("", value, { keyPattern }, ctx, depth, indent, path)); } + const hasFields = lines.length > 0; for (const kw of ["oneOf", "anyOf"]) { if (!m[kw]) continue; - lines.push(`${pad}One of:`); + lines.push(hasFields ? `${pad}- One of these shapes:` : `${pad}One of:`); + const optionIndent = hasFields ? indent + 1 : indent; + const optionPad = " ".repeat(optionIndent); const labels = optionLabels(m[kw]); const disambiguate = sharesFieldNames(m[kw]); m[kw].forEach((opt, i) => { const om = merge(opt); - lines.push(`${pad}- Option ${i + 1} (${labels[i]})${describe(descriptionSentences(om), Boolean(om.description))}`); + lines.push(`${optionPad}- Option ${i + 1} (${labels[i]})${describe(descriptionSentences(om), Boolean(om.description))}`); const option = disambiguate ? labels[i].replace(/`/g, "") : here.option; - lines.push(...renderNested(opt, here.name, here.label, ctx, depth, indent + 1, path, option)); + lines.push(...renderNested(opt, here.name, here.label, ctx, depth, optionIndent + 1, path, option)); }); } return lines; diff --git a/plugins/llms-markdown/api/render-schema.test.js b/plugins/llms-markdown/api/render-schema.test.js index 46786462..c2f5328c 100644 --- a/plugins/llms-markdown/api/render-schema.test.js +++ b/plugins/llms-markdown/api/render-schema.test.js @@ -327,3 +327,36 @@ test("empty-object and scalar roots", () => { assert.strictEqual(renderSchemaFields({ type: "object", additionalProperties: false }), "Empty JSON object."); assert.strictEqual(renderSchemaFields({ type: "string", format: "binary" }), "Type: string."); }); + +test("a union next to fields is its own list item with nested options", () => { + const out = renderSchemaFields({ + type: "object", + properties: { a: { type: "string" } }, + oneOf: [ + { type: "object", properties: { b: { type: "string" } } }, + { type: "object", properties: { c: { type: "integer" } } }, + ], + }); + assert.strictEqual( + out, + [ + "- `a` (string)", + "- One of these shapes:", + " - Option 1 (object with `b`)", + " - `b` (string)", + " - Option 2 (object with `c`)", + " - `c` (integer)", + ].join("\n"), + ); +}); + +test("options that only list required fields say which fields they require", () => { + const out = renderSchemaFields({ + type: "object", + properties: { items: { type: "array", items: { type: "string" } }, page: { type: "integer" }, id: { type: "integer" } }, + anyOf: [{ required: ["items", "page"] }, { required: ["id"] }], + }); + assert.match(out, /^ {2}- Option 1 \(requires `items`, `page`\)$/m); + assert.match(out, /^ {2}- Option 2 \(requires `id`\)$/m); + assert.ok(!out.includes("(any)"), out); +}); diff --git a/plugins/llms-markdown/llms-txt-wrapper.js b/plugins/llms-markdown/llms-txt-wrapper.js index 0d059daf..8266017b 100644 --- a/plugins/llms-markdown/llms-txt-wrapper.js +++ b/plugins/llms-markdown/llms-txt-wrapper.js @@ -44,7 +44,7 @@ function createLlmsTxtWrapper({ loadInner, loadApiIndex, postProcess }) { const innerFactory = await loadInner(); // The inner `docusaurus llms-txt` CLI command can't load the API index, so it would write sparse API pages. const { extendCli, ...inner } = await innerFactory(context, innerOptions); - const siteUrl = context.siteConfig?.url; + const siteUrl = context.siteConfig.url; return { ...inner, async postBuild(props) { diff --git a/plugins/llms-markdown/llms-txt-wrapper.test.js b/plugins/llms-markdown/llms-txt-wrapper.test.js index 8668fd0a..483d07ba 100644 --- a/plugins/llms-markdown/llms-txt-wrapper.test.js +++ b/plugins/llms-markdown/llms-txt-wrapper.test.js @@ -70,7 +70,7 @@ test("postBuild fails when API pages were not all replaced", async () => { postProcessed = true; }, }); - const plugin = await wrapper({ siteDir: "/site" }, {}); + const plugin = await wrapper({ siteDir: "/site", siteConfig: { url: "https://site" } }, {}); await assert.rejects(plugin.postBuild({ outDir: "/out" }), /Only 0 of 1[\s\S]*GET \/a/); assert.strictEqual(postProcessed, false); }); diff --git a/plugins/llms-markdown/postprocess-llms.js b/plugins/llms-markdown/postprocess-llms.js index bf3e3cd2..6d670ee4 100644 --- a/plugins/llms-markdown/postprocess-llms.js +++ b/plugins/llms-markdown/postprocess-llms.js @@ -2,7 +2,6 @@ const fs = require("fs"); const path = require("path"); const { encodeUrlPath, POINTER_LEAD } = require("./pointer"); -const { siteUrl: defaultSiteUrl } = require("../site-url"); const WEB_CONSOLE_API_DIR = "/docs/APIs-and-SDKs/Web-Console-API/"; const API_INDEX_PATH = "docs/APIs-and-SDKs/Web-Console-API/llms.txt"; const MAX_DESCRIPTION = 200; @@ -44,7 +43,7 @@ function renderLinks(links) { .join("\n"); } -function rewriteLlmsTxt(llmsTxt, { apiDescription, apiIndexUrl, startHere, apiIndexHeader, siteUrl = defaultSiteUrl() }) { +function rewriteLlmsTxt(llmsTxt, { apiDescription, apiIndexUrl, startHere, apiIndexHeader, siteUrl }) { const webConsoleApiUrl = `${siteUrl}${WEB_CONSOLE_API_DIR}`; const main = []; const apiGuides = []; @@ -152,7 +151,7 @@ function rewriteLlmsFull(full, { pages, isApiPage, note, header }) { return `${addNote(header ?? full.slice(0, at), note)}${marker}${kept.join("")}`; } -function markdownReader(outDir, siteUrl = defaultSiteUrl()) { +function markdownReader(outDir, siteUrl) { return (url) => { if (!url.startsWith(`${siteUrl}/`) || !url.endsWith(".md")) return null; let relative; @@ -181,7 +180,8 @@ function pagesOf(llmsTxt, readMd) { return pages; } -async function postProcessLlms(outDir, options, index, siteUrl = defaultSiteUrl()) { +async function postProcessLlms(outDir, options, index, siteUrl) { + if (!siteUrl) throw new Error("llms-txt wrapper: postProcessLlms: siteUrl is required"); if (!options) throw new Error("llms-txt wrapper: missing postProcess options"); const { startHere, apiIndexHeader, fullNote } = options; const llmsTxtPath = path.join(outDir, "llms.txt"); diff --git a/plugins/llms-markdown/postprocess-llms.test.js b/plugins/llms-markdown/postprocess-llms.test.js index 5011e977..2bdd3ea8 100644 --- a/plugins/llms-markdown/postprocess-llms.test.js +++ b/plugins/llms-markdown/postprocess-llms.test.js @@ -5,6 +5,7 @@ const { rewriteLlmsFull, apiDescriptionFor, markdownReader, + postProcessLlms, } = require("./postprocess-llms"); const SITE = "https://docs.absmartly.com"; @@ -154,6 +155,7 @@ function rewrite() { apiIndexUrl: API_INDEX_URL, startHere: START_HERE, apiIndexHeader: "# ABsmartly Web Console API\n\n> Auth line. Spec link.\n", + siteUrl: SITE, }); } @@ -286,7 +288,7 @@ test("rewriteLlmsFull throws on content that matches no known page", () => { // --- markdownReader ----------------------------------------------------------------- test("markdownReader returns null for a malformed percent-encoded URL", () => { - const read = markdownReader(__dirname); + const read = markdownReader(__dirname, SITE); assert.strictEqual(read(`${SITE}/docs/bad%E0%A4%A.md`), null); assert.strictEqual(read(`${SITE}/openapi/web-console-api.yaml`), null); }); @@ -301,3 +303,7 @@ test("markdownReader reads URLs under the given site URL", () => { assert.strictEqual(read(`${SITE}/page.md`), null); fs.rmSync(tmp, { recursive: true }); }); + +test("postProcessLlms requires a site URL", async () => { + await assert.rejects(postProcessLlms(__dirname, {}, new Map()), /siteUrl/); +}); diff --git a/src/components/PageAiActions/index.js b/src/components/PageAiActions/index.js index 2a591c94..921413b7 100644 --- a/src/components/PageAiActions/index.js +++ b/src/components/PageAiActions/index.js @@ -122,7 +122,7 @@ export default function PageAiActions() { let result = "copied"; try { await copyMarkdown(`${metadata.permalink.replace(/\/+$/, "")}.md`); // same-origin copy - } catch (error) { + } catch { result = "failed"; } setStatus(result); From 1dd1fb6cb139817bfd4f48b148a9a8ef19594b55 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 19:46:02 +0000 Subject: [PATCH 42/43] feat(llms): split the Web Console API index into per-resource endpoint lists The API index (/docs/APIs-and-SDKs/Web-Console-API/llms.txt) now lists one entry per resource; each resource's endpoints live in /docs/APIs-and-SDKs/Web-Console-API/llms/.txt, sorted by title. Build checks keep every agent index under 50,000 characters even on the longest deploy-preview origin and check that the resource lists cover every Web Console endpoint page exactly once. netlify.toml serves the new files as UTF-8 plain text with open CORS. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- AGENTS.md | 18 ++-- docusaurus.config.js | 2 +- netlify.toml | 7 ++ plugins/build-checks.test.js | 72 +++++++++++---- plugins/llms-markdown/postprocess-llms.js | 88 +++++++++++++++---- .../llms-markdown/postprocess-llms.test.js | 78 +++++++++++++--- plugins/netlify-headers.test.js | 2 +- 7 files changed, 210 insertions(+), 57 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e24c6fda..5b222abb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,7 +54,8 @@ yarn gen:api (e.g. `/docs/glossary/` -> `/docs/glossary.md`) and writes `/llms.txt` and `/llms-full.txt`. - It is wrapped by `plugins/llms-markdown/llms-txt-wrapper.js`, whose `postBuild` then runs `postprocess-llms.js` (options: `postProcess` in `docusaurus.config.js`): adds the "Start here" - block, moves Web Console API endpoints to `/docs/APIs-and-SDKs/Web-Console-API/llms.txt`, + block, moves Web Console API endpoints to per-resource lists behind + `/docs/APIs-and-SDKs/Web-Console-API/llms.txt`, describes API entries from the OpenAPI spec, percent-encodes link URLs, and drops Web Console endpoint pages and the per-page pointer lines from `/llms-full.txt`. Other entries keep the inner plugin's description (front-matter `description`, else the first source line of the first @@ -92,10 +93,17 @@ yarn gen:api `rehype-api-markdown.js` than there are operations (e.g. after a theme markup change), so API pages never ship as sparse Markdown. `/search` is excluded via `excludeRoutes` (both `/search` and `/search/`, as routes carry trailing slashes). -- llms.txt structure: a "Start here" block, Web Console endpoints split out to - `/docs/APIs-and-SDKs/Web-Console-API/llms.txt`, API descriptions written by `postprocess-llms.js`; - `/llms-full.txt` excludes Web Console endpoint pages and pointer lines. Every `.md` and `/llms.txt` must stay under - 50,000 characters (enforced by `plugins/build-checks.test.js`). +- llms.txt structure: a "Start here" block, with the Web Console endpoints split out in two levels. + `/docs/APIs-and-SDKs/Web-Console-API/llms.txt` is the API index: the auth and `ok: false` notes, + the overview and examples pages, and one entry per resource. Each resource (the endpoint path's + first segment, e.g. `/goals/...` -> `goals`) has its own list of endpoints at + `/docs/APIs-and-SDKs/Web-Console-API/llms/.txt`, sorted by title, with descriptions + written by `postprocess-llms.js`. `netlify.toml` serves those lists as UTF-8 plain text with open + CORS. `/llms-full.txt` excludes Web Console endpoint pages and pointer lines. Every `.md` must + stay under 50,000 characters. `/llms.txt`, the API index and each resource list must also stay + under 50,000 characters when every URL uses the longest deploy-preview origin. The resource lists + together must contain every Web Console endpoint page exactly once. All of these limits are + enforced by `plugins/build-checks.test.js`. - Pointer line and copy menu on rendered pages: `src/theme/DocItem/Content/index.js` is an ejected copy of the upstream component, so re-diff it against `@docusaurus/theme-classic` when upgrading Docusaurus. It uses `src/components/AgentPointer`, `src/components/PageAiActions` (copy-page diff --git a/docusaurus.config.js b/docusaurus.config.js index b1956763..ed0252cc 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -191,7 +191,7 @@ const config = { "Authenticate with `Authorization: Api-Key ` (API key from Settings → API Keys) or a federated OIDC access token. " + `Full request/response schemas: ${SITE_URL}/openapi/web-console-api.yaml\n\n` + "Some endpoints return HTTP 200 with `ok: false` on failure; always check `ok`.\n\n" + - `Each endpoint page below is Markdown. The main documentation index is at ${SITE_URL}/llms.txt.\n`, + `Each resource below links to a list of its endpoints; every endpoint page is Markdown. The main documentation index is at ${SITE_URL}/llms.txt.\n`, fullNote: "This file has the guides and the Collector API pages. Web Console API endpoint pages are not " + `included: see the endpoint index at ${SITE_URL}/docs/APIs-and-SDKs/Web-Console-API/llms.txt ` + diff --git a/netlify.toml b/netlify.toml index a9db6e88..1c628580 100644 --- a/netlify.toml +++ b/netlify.toml @@ -20,6 +20,13 @@ Content-Type = "text/plain; charset=utf-8" Access-Control-Allow-Origin = "*" +# The per-resource Web Console API endpoint lists (linked from the endpoint index). +[[headers]] + for = "/docs/APIs-and-SDKs/Web-Console-API/llms/*" + [headers.values] + Content-Type = "text/plain; charset=utf-8" + Access-Control-Allow-Origin = "*" + # The full dump duplicates every page; keep it out of search results. [[headers]] for = "/llms-full.txt" diff --git a/plugins/build-checks.test.js b/plugins/build-checks.test.js index 99c6e9b0..597d61c9 100644 --- a/plugins/build-checks.test.js +++ b/plugins/build-checks.test.js @@ -7,7 +7,19 @@ const path = require("path"); const buildDir = path.resolve(__dirname, "../build"); const read = (rel) => fs.readFileSync(path.join(buildDir, rel), "utf8"); const API_INDEX = "docs/APIs-and-SDKs/Web-Console-API/llms.txt"; +const RESOURCE_DIR = "docs/APIs-and-SDKs/Web-Console-API/llms/"; const WC_URL = "https://docs.absmartly.com/docs/APIs-and-SDKs/Web-Console-API/"; +const PRODUCTION_URL = "https://docs.absmartly.com"; +const LONGEST_PREVIEW_URL = "https://deploy-preview-99999--absmartly-docs.netlify.app"; + +const resourceFiles = () => + fs.readdirSync(path.join(buildDir, RESOURCE_DIR)).map((f) => `${RESOURCE_DIR}${f}`); + +// Agent link lists: build-relative path -> text. +const agentIndexes = () => + Object.fromEntries(["llms.txt", API_INDEX, ...resourceFiles()].map((rel) => [rel, read(rel)])); + +const linkLines = (text) => text.split("\n").filter((l) => l.startsWith("- [")); function buildTest(name, fn) { test(name, (t) => { @@ -25,15 +37,15 @@ buildTest("main llms.txt is under 50,000 characters and has no Web Console endpo assert.deepStrictEqual(wcEntries, []); }); -buildTest("API endpoint descriptions in the index are not Markdown-formatted", () => { - const endpoints = read(API_INDEX).split("\n## Endpoints\n")[1].split("\n").filter((l) => l.startsWith("- [")); - for (const line of endpoints) assert.ok(!line.includes("**") && !line.includes(":::"), line); +buildTest("API endpoint descriptions in the resource files are not Markdown-formatted", () => { + for (const rel of resourceFiles()) { + for (const line of linkLines(read(rel))) assert.ok(!line.includes("**") && !line.includes(":::"), `${rel}: ${line}`); + } }); buildTest("link URLs in the agent indexes contain no raw spaces", () => { const linkLists = { - "llms.txt": read("llms.txt"), - [API_INDEX]: read(API_INDEX), + ...agentIndexes(), "llms-full.txt": read("llms-full.txt").split("\n# Full Documentation Content\n")[0], }; for (const [file, text] of Object.entries(linkLists)) { @@ -69,22 +81,46 @@ buildTest("every API endpoint .md has the spec-derived reference and no admoniti assert.ok(endpoints >= 255, `only ${endpoints} endpoint pages`); }); -buildTest("the Web Console API index lists every endpoint", () => { +buildTest("the Web Console API index links each resource file once", () => { const index = read(API_INDEX); assert.match(index, /^# ABsmartly Web Console API\n/); assert.ok(index.includes("Some endpoints return HTTP 200 with `ok: false` on failure; always check `ok`.")); - const endpoints = index.split("\n## Endpoints\n")[1].split("\n").filter((l) => l.startsWith("- [")); - assert.ok(endpoints.length >= 270, `${endpoints.length} endpoints`); - for (const line of endpoints) assert.match(line, /\): (GET|PUT|POST|DELETE|PATCH|HEAD|OPTIONS) \//); + const linked = linkLines(index.split("\n## Resources\n")[1]).map((l) => l.match(/\]\(([^)]*)\)/)[1]); + assert.deepStrictEqual(linked, [...new Set(linked)]); + assert.deepStrictEqual(linked.sort(), resourceFiles().map((rel) => `${PRODUCTION_URL}/${rel}`).sort()); + for (const line of linkLines(index.split("\n## Resources\n")[1])) assert.match(line, /\): \d+ endpoints? — /); }); -buildTest("the Web Console API index and any sub-index are under 50,000 characters", () => { - const dir = path.join(buildDir, path.dirname(API_INDEX)); - const indexes = fs.readdirSync(dir, { recursive: true }).filter((f) => String(f).endsWith("llms.txt")); - assert.ok(indexes.length >= 1); - for (const f of indexes) { - const size = fs.readFileSync(path.join(dir, String(f)), "utf8").length; - assert.ok(size < 50000, `${f} is ${size} chars`); +buildTest("the resource files list every Web Console endpoint page exactly once", () => { + const dir = path.join(buildDir, "docs/APIs-and-SDKs/Web-Console-API"); + const pages = fs + .readdirSync(dir) + .filter((f) => f.endsWith(".md") && /^Source: <[^>]*web-console-api\.yaml>/m.test(fs.readFileSync(path.join(dir, f), "utf8"))) + .map((f) => `${WC_URL}${f}`); + const listed = resourceFiles().flatMap((rel) => { + const text = read(rel); + assert.match(text, /^# ABsmartly Web Console API: .+\n\n> .*\n\n## Endpoints\n\n/, rel); + return linkLines(text).map((l) => { + assert.match(l, /\): (GET|PUT|POST|DELETE|PATCH|HEAD|OPTIONS) \//, `${rel}: ${l}`); + return l.match(/\]\(([^)]*)\)/)[1]; + }); + }); + assert.ok(pages.length >= 270, `${pages.length} endpoint pages`); + assert.strictEqual(listed.length, new Set(listed).size, "an endpoint is listed twice"); + assert.deepStrictEqual(listed.sort(), pages.sort()); +}); + +buildTest("the resource files cannot collide with a page route", () => { + for (const f of ["index.html", "../llms.md", "../llms/index.html"]) { + assert.ok(!fs.existsSync(path.join(buildDir, RESOURCE_DIR, f)), `${RESOURCE_DIR}${f} exists`); + } +}); + +buildTest("every agent index stays under 50,000 characters on the longest preview origin", () => { + for (const [rel, text] of Object.entries(agentIndexes())) { + const urls = text.split(PRODUCTION_URL).length - 1; + const size = text.length + urls * (LONGEST_PREVIEW_URL.length - PRODUCTION_URL.length); + assert.ok(size < 50000, `${rel} would be ${size} chars (${text.length} in production)`); } }); @@ -159,9 +195,7 @@ buildTest("an API endpoint .md has exactly one pointer line", () => { }); buildTest("llms.txt descriptions never start with the pointer", () => { - for (const file of ["llms.txt", API_INDEX]) { - assert.ok(!/: For AI agents/.test(read(file)), file); - } + for (const [rel, text] of Object.entries(agentIndexes())) assert.ok(!/: For AI agents/.test(text), rel); }); buildTest("doc and API pages render the Copy page menu; it stays out of the Markdown", () => { diff --git a/plugins/llms-markdown/postprocess-llms.js b/plugins/llms-markdown/postprocess-llms.js index 6d670ee4..ffffd285 100644 --- a/plugins/llms-markdown/postprocess-llms.js +++ b/plugins/llms-markdown/postprocess-llms.js @@ -4,6 +4,9 @@ const { encodeUrlPath, POINTER_LEAD } = require("./pointer"); const WEB_CONSOLE_API_DIR = "/docs/APIs-and-SDKs/Web-Console-API/"; const API_INDEX_PATH = "docs/APIs-and-SDKs/Web-Console-API/llms.txt"; +const RESOURCE_DIR = "docs/APIs-and-SDKs/Web-Console-API/llms/"; +const ACRONYMS = new Set(["api", "cors"]); +const RESOURCE_SUMMARY_TITLES = 3; const MAX_DESCRIPTION = 200; const SECTION_SEPARATOR = "\n\n---\n\n"; const FULL_CONTENT_HEADING = "# Full Documentation Content\n\n"; @@ -43,11 +46,45 @@ function renderLinks(links) { .join("\n"); } -function rewriteLlmsTxt(llmsTxt, { apiDescription, apiIndexUrl, startHere, apiIndexHeader, siteUrl }) { +function resourceOf(apiPath) { + const slug = apiPath.split("/")[1] || ""; + if (!/^[a-z0-9][a-z0-9_-]*$/i.test(slug)) throw new Error(`No resource in API path ${apiPath}`); + const words = slug.split(/[_-]/).map((w) => (ACRONYMS.has(w.toLowerCase()) ? w.toUpperCase() : w)); + const name = words.join(" "); + return { slug, name: name.charAt(0).toUpperCase() + name.slice(1) }; +} + +const byTitle = (a, b) => a.title.localeCompare(b.title); +const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`; + +function resourceFile(resource, apiIndexUrl) { + const endpoints = [...resource.endpoints].sort(byTitle); + return [ + `# ABsmartly Web Console API: ${resource.name}`, + "", + `> ${plural(endpoints.length, "endpoint")}. Authentication, the \`ok: false\` note and the other resources: ` + + `${apiIndexUrl}. Full schemas: ${resource.specUrl}.`, + "", + "## Endpoints", + "", + renderLinks(endpoints), + "", + ].join("\n"); +} + +function resourceEntry(resource, url) { + const titles = [...resource.endpoints].sort(byTitle).map((e) => e.title); + const shown = titles.slice(0, RESOURCE_SUMMARY_TITLES).join(", "); + const more = titles.length > RESOURCE_SUMMARY_TITLES ? ", …" : ""; + return { title: resource.name, url, description: `${plural(titles.length, "endpoint")} — ${shown}${more}` }; +} + +function rewriteLlmsTxt(llmsTxt, { apiOperation, apiIndexUrl, startHere, apiIndexHeader, siteUrl }) { const webConsoleApiUrl = `${siteUrl}${WEB_CONSOLE_API_DIR}`; const main = []; const apiGuides = []; - const apiEndpoints = []; + const resourcesBySlug = new Map(); + let endpointCount = 0; let apiLinkAt = -1; let startHereAt = -1; @@ -59,17 +96,25 @@ function rewriteLlmsTxt(llmsTxt, { apiDescription, apiIndexUrl, startHere, apiIn continue; } const entry = { title: m[1], url: m[2], description: m[3] || "" }; - const api = apiDescription(entry.url); - const isOperation = api !== null; - const rendered = renderLinks([{ ...entry, description: api ?? entry.description }]); - if (entry.url.startsWith(webConsoleApiUrl)) { - (isOperation ? apiEndpoints : apiGuides).push(rendered); - if (apiLinkAt < 0) { - apiLinkAt = main.length; - main.push(null); + const operation = apiOperation(entry.url); + const described = operation ? { ...entry, description: apiDescriptionFor(operation) } : entry; + if (!entry.url.startsWith(webConsoleApiUrl)) { + main.push(renderLinks([described])); + continue; + } + if (operation) { + const { slug, name } = resourceOf(operation.path); + if (!resourcesBySlug.has(slug)) { + resourcesBySlug.set(slug, { name, specUrl: operation.publishedUrl, endpoints: [] }); } + resourcesBySlug.get(slug).endpoints.push(described); + endpointCount++; } else { - main.push(rendered); + apiGuides.push(renderLinks([described])); + } + if (apiLinkAt < 0) { + apiLinkAt = main.length; + main.push(null); } } @@ -78,7 +123,7 @@ function rewriteLlmsTxt(llmsTxt, { apiDescription, apiIndexUrl, startHere, apiIn { title: "Web Console API endpoint index", url: apiIndexUrl, - description: `Index of the ${apiEndpoints.length} Web Console API endpoint pages, plus the API overview and examples.`, + description: `Index of the ${endpointCount} Web Console API endpoints, grouped by resource, plus the API overview and examples.`, }, ]); } @@ -86,6 +131,10 @@ function rewriteLlmsTxt(llmsTxt, { apiDescription, apiIndexUrl, startHere, apiIn main.splice(startHereAt, 0, `## Start here\n\n${renderLinks(startHere)}\n`); } + const sorted = [...resourcesBySlug].sort(([, a], [, b]) => a.name.localeCompare(b.name)); + const resources = new Map(sorted.map(([slug, r]) => [slug, resourceFile(r, apiIndexUrl)])); + const resourceEntries = sorted.map(([slug, r]) => resourceEntry(r, `${siteUrl}/${RESOURCE_DIR}${slug}.txt`)); + const apiIndex = [ apiIndexHeader.trimEnd(), "", @@ -93,13 +142,13 @@ function rewriteLlmsTxt(llmsTxt, { apiDescription, apiIndexUrl, startHere, apiIn "", ...apiGuides, "", - "## Endpoints", + "## Resources", "", - ...apiEndpoints, + renderLinks(resourceEntries), "", ].join("\n"); - return { main: main.join("\n"), apiIndex }; + return { main: main.join("\n"), apiIndex, resources }; } function addNote(header, note) { @@ -190,8 +239,8 @@ async function postProcessLlms(outDir, options, index, siteUrl) { const readMd = markdownReader(outDir, siteUrl); const operations = operationsByMarkdownUrl(index); const llmsTxt = fs.readFileSync(llmsTxtPath, "utf8"); - const { main, apiIndex } = rewriteLlmsTxt(llmsTxt, { - apiDescription: (url) => (operations.has(url) ? apiDescriptionFor(operations.get(url)) : null), + const { main, apiIndex, resources } = rewriteLlmsTxt(llmsTxt, { + apiOperation: (url) => operations.get(url) ?? null, apiIndexUrl: `${siteUrl}/${API_INDEX_PATH}`, siteUrl, startHere, @@ -200,6 +249,9 @@ async function postProcessLlms(outDir, options, index, siteUrl) { fs.writeFileSync(llmsTxtPath, main); fs.mkdirSync(path.dirname(path.join(outDir, API_INDEX_PATH)), { recursive: true }); fs.writeFileSync(path.join(outDir, API_INDEX_PATH), apiIndex); + fs.rmSync(path.join(outDir, RESOURCE_DIR), { recursive: true, force: true }); + fs.mkdirSync(path.join(outDir, RESOURCE_DIR), { recursive: true }); + for (const [slug, text] of resources) fs.writeFileSync(path.join(outDir, RESOURCE_DIR, `${slug}.txt`), text); if (fs.existsSync(fullPath)) { const full = rewriteLlmsFull(fs.readFileSync(fullPath, "utf8"), { @@ -215,8 +267,10 @@ async function postProcessLlms(outDir, options, index, siteUrl) { module.exports = { apiDescriptionFor, rewriteLlmsTxt, + resourceOf, rewriteLlmsFull, markdownReader, postProcessLlms, API_INDEX_PATH, + RESOURCE_DIR, }; diff --git a/plugins/llms-markdown/postprocess-llms.test.js b/plugins/llms-markdown/postprocess-llms.test.js index 2bdd3ea8..52bdf415 100644 --- a/plugins/llms-markdown/postprocess-llms.test.js +++ b/plugins/llms-markdown/postprocess-llms.test.js @@ -2,6 +2,7 @@ const test = require("node:test"); const assert = require("node:assert"); const { rewriteLlmsTxt, + resourceOf, rewriteLlmsFull, apiDescriptionFor, markdownReader, @@ -122,6 +123,7 @@ Every page is available as Markdown. - [Set experiment to development](${WC}/003-set-experiment-to-development.md): **Required Permissions**: \`Experiment Development\` or \`Experiment Admin\` - [ABsmartly Web Console API](${WC}/absmartly-web-console-api.md): An OpenAPI Specification that describes the ABsmartly API for working wit - [List experiments](${WC}/0100-000-list-experiments.md): **Required Permissions**: \`Experiment List\` or \`Experiment Admin\` +- [Goal list](${WC}/0200-000-list-goals.md): **Required Permissions**: \`Goal List\` - [Check Service Health](${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check.md): A GET request to check that the service is running as expected. ### glossary @@ -134,13 +136,22 @@ Every page is available as Markdown. - [Missing page](${SITE}/docs/missing.md): Left as it is `; +const WC_SPEC = `${SITE}/openapi/web-console-api.yaml`; const API = { - [`${WC}/003-set-experiment-to-development.md`]: - "PUT /experiments/{experimentId}/development.", - [`${WC}/0100-000-list-experiments.md`]: - "GET /experiments.", - [`${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check.md`]: - "GET /healthy. A GET request to check that the service is running as expected.", + [`${WC}/003-set-experiment-to-development.md`]: { + method: "PUT", + path: "/experiments/{experimentId}/development", + description: "**Required Permissions**: `Experiment Development`", + publishedUrl: WC_SPEC, + }, + [`${WC}/0100-000-list-experiments.md`]: { method: "GET", path: "/experiments", publishedUrl: WC_SPEC }, + [`${WC}/0200-000-list-goals.md`]: { method: "GET", path: "/goals", description: "Lists goals.", publishedUrl: WC_SPEC }, + [`${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check.md`]: { + method: "GET", + path: "/healthy", + description: "A GET request to check that the service is running as expected.", + publishedUrl: `${SITE}/openapi/collector-api.yaml`, + }, }; const API_INDEX_URL = `${WC}/llms.txt`; @@ -151,7 +162,7 @@ const START_HERE = [ function rewrite() { return rewriteLlmsTxt(LLMS_TXT, { - apiDescription: (url) => API[url] ?? null, + apiOperation: (url) => API[url] ?? null, apiIndexUrl: API_INDEX_URL, startHere: START_HERE, apiIndexHeader: "# ABsmartly Web Console API\n\n> Auth line. Spec link.\n", @@ -191,26 +202,65 @@ test("rewriteLlmsTxt moves Web Console entries to the API index and links it onc assert.ok(!main.includes("**")); const link = main.split("\n").filter((l) => l.startsWith("- [") && l.includes(`](${API_INDEX_URL})`)); assert.strictEqual(link.length, 2, "Start here link + section link"); - assert.match(main, /Index of the 2 Web Console API endpoint pages/); + assert.match(main, /Index of the 3 Web Console API endpoints, grouped by resource/); assert.match( entryLine(main, "Check Service Health"), /\): GET \/healthy\. A GET request to check that the service is running as expected\.$/, ); assert.ok(apiIndex.startsWith("# ABsmartly Web Console API\n\n> Auth line. Spec link.\n")); - assert.match(apiIndex, /\n## Endpoints\n\n- \[Set experiment to development\]/); - assert.match( - entryLine(apiIndex, "List experiments"), - /\): GET \/experiments\.$/, - ); assert.match( entryLine(apiIndex, "ABsmartly Web Console API"), /\): An OpenAPI Specification that describes the ABsmartly API for working wit$/, ); - assert.ok(apiIndex.indexOf("## Overview and examples") < apiIndex.indexOf("## Endpoints")); + assert.ok(apiIndex.indexOf("## Overview and examples") < apiIndex.indexOf("## Resources")); assert.ok(!apiIndex.includes("**")); }); +test("the API index lists one entry per resource and no endpoint pages", () => { + const { apiIndex } = rewrite(); + assert.ok(!apiIndex.includes("## Endpoints")); + assert.ok(!/\/0\d{2}[^)]*\.md\)/.test(apiIndex), "endpoint page linked from the API index"); + const resources = apiIndex.split("\n## Resources\n\n")[1].trimEnd().split("\n"); + assert.deepStrictEqual(resources, [ + `- [Experiments](${WC}/llms/experiments.txt): 2 endpoints — List experiments, Set experiment to development`, + `- [Goals](${WC}/llms/goals.txt): 1 endpoint — Goal list`, + ]); +}); + +test("each resource file lists its endpoints sorted by title and points back to the index and spec", () => { + const { resources } = rewrite(); + assert.deepStrictEqual([...resources.keys()], ["experiments", "goals"]); + assert.strictEqual( + resources.get("experiments"), + [ + "# ABsmartly Web Console API: Experiments", + "", + `> 2 endpoints. Authentication, the \`ok: false\` note and the other resources: ${API_INDEX_URL}. Full schemas: ${WC_SPEC}.`, + "", + "## Endpoints", + "", + `- [List experiments](${WC}/0100-000-list-experiments.md): GET /experiments.`, + `- [Set experiment to development](${WC}/003-set-experiment-to-development.md): PUT /experiments/{experimentId}/development.`, + "", + ].join("\n"), + ); + assert.match(resources.get("goals"), /\n- \[Goal list\]\([^)]*\): GET \/goals\. Lists goals\.\n$/); +}); + +test("resourceOf groups by the path's first segment", () => { + assert.deepStrictEqual(resourceOf("/experiments/{experimentId}/start"), { slug: "experiments", name: "Experiments" }); + assert.deepStrictEqual(resourceOf("/experiment_custom_sections/order"), { + slug: "experiment_custom_sections", + name: "Experiment custom sections", + }); + assert.deepStrictEqual(resourceOf("/stop-reasons"), { slug: "stop-reasons", name: "Stop reasons" }); + assert.deepStrictEqual(resourceOf("/api_keys/{id}"), { slug: "api_keys", name: "API keys" }); + assert.deepStrictEqual(resourceOf("/cors"), { slug: "cors", name: "CORS" }); + assert.throws(() => resourceOf("/{id}"), /resource/); + assert.throws(() => resourceOf("/"), /resource/); +}); + test("rewriteLlmsTxt inserts the Start here block before the first section", () => { const { main } = rewrite(); const startHere = main.indexOf("## Start here"); diff --git a/plugins/netlify-headers.test.js b/plugins/netlify-headers.test.js index 53820525..b6b978c0 100644 --- a/plugins/netlify-headers.test.js +++ b/plugins/netlify-headers.test.js @@ -22,7 +22,7 @@ function headerRules() { test("every llms.txt index is served as UTF-8 plain text with open CORS", () => { const rules = headerRules(); - for (const file of ["/llms*.txt", "/docs/APIs-and-SDKs/Web-Console-API/llms.txt"]) { + for (const file of ["/llms*.txt", "/docs/APIs-and-SDKs/Web-Console-API/llms.txt", "/docs/APIs-and-SDKs/Web-Console-API/llms/*"]) { const rule = rules.get(file); assert.ok(rule, `no [[headers]] rule for ${file}`); assert.strictEqual(rule["Content-Type"], "text/plain; charset=utf-8", file); From 6ecb7e8686fcd4d10dff089d00cd339067e60363 Mon Sep 17 00:00:00 2001 From: Cal Courtney Date: Tue, 1 Dec 2026 19:53:13 +0000 Subject: [PATCH 43/43] feat(llms): describe each API resource by its actions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resource entries in the Web Console API index now list the endpoint actions with the shared title prefix stripped (list, get, create, update, delete, archive first, then the rest alphabetically), cut with "…" only past 300 characters. The index intro notes that sub-resources have their own lists, and the Start-here entry describes the index as a list of resources. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JHXkV5dJwVX16SFdNf7YB4 --- docusaurus.config.js | 6 ++- plugins/build-checks.test.js | 5 +- plugins/llms-markdown/postprocess-llms.js | 34 +++++++++++-- .../llms-markdown/postprocess-llms.test.js | 50 ++++++++++++++++--- 4 files changed, 81 insertions(+), 14 deletions(-) diff --git a/docusaurus.config.js b/docusaurus.config.js index ed0252cc..e02b18c3 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -152,7 +152,7 @@ const config = { { title: "Web Console API endpoint index", url: `${SITE_URL}/docs/APIs-and-SDKs/Web-Console-API/llms.txt`, - description: "Every REST endpoint for managing experiments, metrics, goals, teams and settings.", + description: "Web Console API resources (experiments, metrics, goals, teams, settings…), each linking to its REST endpoints.", }, { title: "Web Console API OpenAPI spec", @@ -191,7 +191,9 @@ const config = { "Authenticate with `Authorization: Api-Key ` (API key from Settings → API Keys) or a federated OIDC access token. " + `Full request/response schemas: ${SITE_URL}/openapi/web-console-api.yaml\n\n` + "Some endpoints return HTTP 200 with `ok: false` on failure; always check `ok`.\n\n" + - `Each resource below links to a list of its endpoints; every endpoint page is Markdown. The main documentation index is at ${SITE_URL}/llms.txt.\n`, + `Each resource below links to a list of its endpoints; every endpoint page is Markdown. ` + + "Sub-resources such as experiment custom sections and action dialog fields have their own lists. " + + `The main documentation index is at ${SITE_URL}/llms.txt.\n`, fullNote: "This file has the guides and the Collector API pages. Web Console API endpoint pages are not " + `included: see the endpoint index at ${SITE_URL}/docs/APIs-and-SDKs/Web-Console-API/llms.txt ` + diff --git a/plugins/build-checks.test.js b/plugins/build-checks.test.js index 597d61c9..9208dd49 100644 --- a/plugins/build-checks.test.js +++ b/plugins/build-checks.test.js @@ -88,7 +88,10 @@ buildTest("the Web Console API index links each resource file once", () => { const linked = linkLines(index.split("\n## Resources\n")[1]).map((l) => l.match(/\]\(([^)]*)\)/)[1]); assert.deepStrictEqual(linked, [...new Set(linked)]); assert.deepStrictEqual(linked.sort(), resourceFiles().map((rel) => `${PRODUCTION_URL}/${rel}`).sort()); - for (const line of linkLines(index.split("\n## Resources\n")[1])) assert.match(line, /\): \d+ endpoints? — /); + for (const line of linkLines(index.split("\n## Resources\n")[1])) { + assert.match(line, /\): \d+ endpoints?: \S/); + assert.ok(line.length <= 300, `${line.length} chars: ${line}`); + } }); buildTest("the resource files list every Web Console endpoint page exactly once", () => { diff --git a/plugins/llms-markdown/postprocess-llms.js b/plugins/llms-markdown/postprocess-llms.js index ffffd285..df45cb4f 100644 --- a/plugins/llms-markdown/postprocess-llms.js +++ b/plugins/llms-markdown/postprocess-llms.js @@ -6,7 +6,8 @@ const WEB_CONSOLE_API_DIR = "/docs/APIs-and-SDKs/Web-Console-API/"; const API_INDEX_PATH = "docs/APIs-and-SDKs/Web-Console-API/llms.txt"; const RESOURCE_DIR = "docs/APIs-and-SDKs/Web-Console-API/llms/"; const ACRONYMS = new Set(["api", "cors"]); -const RESOURCE_SUMMARY_TITLES = 3; +const ACTION_ORDER = ["list", "get", "create", "update", "delete", "archive"]; +const MAX_RESOURCE_LINE = 300; const MAX_DESCRIPTION = 200; const SECTION_SEPARATOR = "\n\n---\n\n"; const FULL_CONTENT_HEADING = "# Full Documentation Content\n\n"; @@ -72,11 +73,33 @@ function resourceFile(resource, apiIndexUrl) { ].join("\n"); } +// Titles outside the most common first word (e.g. "Team role list" among roles) are kept whole. +function resourceActions(titles) { + const words = titles.map((t) => t.split(" ")); + const firstWordCount = (w) => words.filter((v) => v[0] === w[0]).length; + const lead = words.reduce((best, w) => (firstWordCount(w) > firstWordCount(best) ? w : best))[0]; + const group = words.filter((w) => w[0] === lead); + const shortest = Math.min(...group.map((w) => w.length)); + let common = 0; + while (common < shortest - 1 && group.every((w) => w[common] === group[0][common])) common++; + const actions = [...new Set(words.map((w) => (w[0] === lead ? w.slice(common) : w).join(" ")))]; + const rank = (action) => { + const at = ACTION_ORDER.indexOf(action); + return at < 0 ? ACTION_ORDER.length : at; + }; + return actions.sort((x, y) => rank(x) - rank(y) || x.localeCompare(y)); +} + function resourceEntry(resource, url) { - const titles = [...resource.endpoints].sort(byTitle).map((e) => e.title); - const shown = titles.slice(0, RESOURCE_SUMMARY_TITLES).join(", "); - const more = titles.length > RESOURCE_SUMMARY_TITLES ? ", …" : ""; - return { title: resource.name, url, description: `${plural(titles.length, "endpoint")} — ${shown}${more}` }; + const actions = resourceActions(resource.endpoints.map((e) => e.title)); + const entry = (shown) => { + const more = shown < actions.length ? ", …" : ""; + const list = `${actions.slice(0, shown).join(", ")}${more}`; + return { title: resource.name, url, description: `${plural(resource.endpoints.length, "endpoint")}: ${list}` }; + }; + let shown = actions.length; + while (shown > 1 && renderLinks([entry(shown)]).length > MAX_RESOURCE_LINE) shown--; + return entry(shown); } function rewriteLlmsTxt(llmsTxt, { apiOperation, apiIndexUrl, startHere, apiIndexHeader, siteUrl }) { @@ -268,6 +291,7 @@ module.exports = { apiDescriptionFor, rewriteLlmsTxt, resourceOf, + resourceActions, rewriteLlmsFull, markdownReader, postProcessLlms, diff --git a/plugins/llms-markdown/postprocess-llms.test.js b/plugins/llms-markdown/postprocess-llms.test.js index 52bdf415..0e3bbc75 100644 --- a/plugins/llms-markdown/postprocess-llms.test.js +++ b/plugins/llms-markdown/postprocess-llms.test.js @@ -3,6 +3,7 @@ const assert = require("node:assert"); const { rewriteLlmsTxt, resourceOf, + resourceActions, rewriteLlmsFull, apiDescriptionFor, markdownReader, @@ -120,9 +121,9 @@ Every page is available as Markdown. - [Authentication](${SITE}/docs/APIs-and-SDKs/MCP-Server/authentication.md): The ABsmartly MCP server supports two authentication methods. Both are - [Global Options & Configuration](${SITE}/docs/APIs-and-SDKs/CLI-Documentation/configuration.md): Global options - [Good page](${SITE}/docs/a/good.md): Connect ABsmartly to Snowflake. -- [Set experiment to development](${WC}/003-set-experiment-to-development.md): **Required Permissions**: \`Experiment Development\` or \`Experiment Admin\` +- [Experiment development start](${WC}/003-set-experiment-to-development.md): **Required Permissions**: \`Experiment Development\` or \`Experiment Admin\` - [ABsmartly Web Console API](${WC}/absmartly-web-console-api.md): An OpenAPI Specification that describes the ABsmartly API for working wit -- [List experiments](${WC}/0100-000-list-experiments.md): **Required Permissions**: \`Experiment List\` or \`Experiment Admin\` +- [Experiment list](${WC}/0100-000-list-experiments.md): **Required Permissions**: \`Experiment List\` or \`Experiment Admin\` - [Goal list](${WC}/0200-000-list-goals.md): **Required Permissions**: \`Goal List\` - [Check Service Health](${SITE}/docs/APIs-and-SDKs/SDK-API/collector-health-check.md): A GET request to check that the service is running as expected. @@ -223,8 +224,8 @@ test("the API index lists one entry per resource and no endpoint pages", () => { assert.ok(!/\/0\d{2}[^)]*\.md\)/.test(apiIndex), "endpoint page linked from the API index"); const resources = apiIndex.split("\n## Resources\n\n")[1].trimEnd().split("\n"); assert.deepStrictEqual(resources, [ - `- [Experiments](${WC}/llms/experiments.txt): 2 endpoints — List experiments, Set experiment to development`, - `- [Goals](${WC}/llms/goals.txt): 1 endpoint — Goal list`, + `- [Experiments](${WC}/llms/experiments.txt): 2 endpoints: list, development start`, + `- [Goals](${WC}/llms/goals.txt): 1 endpoint: list`, ]); }); @@ -240,14 +241,51 @@ test("each resource file lists its endpoints sorted by title and points back to "", "## Endpoints", "", - `- [List experiments](${WC}/0100-000-list-experiments.md): GET /experiments.`, - `- [Set experiment to development](${WC}/003-set-experiment-to-development.md): PUT /experiments/{experimentId}/development.`, + `- [Experiment development start](${WC}/003-set-experiment-to-development.md): PUT /experiments/{experimentId}/development.`, + `- [Experiment list](${WC}/0100-000-list-experiments.md): GET /experiments.`, "", ].join("\n"), ); assert.match(resources.get("goals"), /\n- \[Goal list\]\([^)]*\): GET \/goals\. Lists goals\.\n$/); }); +test("resourceActions strips the common prefix and orders list, get, create, update, delete, archive first", () => { + assert.deepStrictEqual( + resourceActions(["API key update", "API key delete", "API key list", "API key create", "API key get"]), + ["list", "get", "create", "update", "delete"], + ); + assert.deepStrictEqual( + resourceActions(["Datasource connection test", "Datasource archive", "Datasource list", "Datasource introspect"]), + ["list", "archive", "connection test", "introspect"], + ); + assert.deepStrictEqual(resourceActions(["Permission list"]), ["list"]); + assert.deepStrictEqual(resourceActions(["Config update", "Config bulk update", "Config update"]), ["update", "bulk update"]); + assert.deepStrictEqual( + resourceActions(["Role create", "Role list", "Team role list", "Role get"]), + ["list", "get", "create", "Team role list"], + ); +}); + +test("a resource entry ends in … only when the full action list would pass 300 characters", () => { + const actions = Array.from({ length: 40 }, (_, i) => `step${String(i).padStart(2, "0")} run`); + const lines = actions.map((a, i) => `- [Widget ${a}](${WC}/w-${i}.md): x`).join("\n"); + const ops = Object.fromEntries( + actions.map((a, i) => [`${WC}/w-${i}.md`, { method: "GET", path: `/widgets/${i}`, publishedUrl: WC_SPEC }]), + ); + const { apiIndex } = rewriteLlmsTxt(`# T\n\n## docs\n\n${lines}\n`, { + apiOperation: (url) => ops[url] ?? null, + apiIndexUrl: API_INDEX_URL, + startHere: [], + apiIndexHeader: "# H\n", + siteUrl: SITE, + }); + const line = entryLine(apiIndex, "Widgets"); + assert.ok(line.length <= 300, `${line.length} chars`); + assert.match(line, /\): 40 endpoints: step00 run, step01 run, .*, …$/); + const short = entryLine(rewrite().apiIndex, "Experiments"); + assert.ok(!short.includes("…")); +}); + test("resourceOf groups by the path's first segment", () => { assert.deepStrictEqual(resourceOf("/experiments/{experimentId}/start"), { slug: "experiments", name: "Experiments" }); assert.deepStrictEqual(resourceOf("/experiment_custom_sections/order"), {