SPB Git

Repository Public

docs.js 34.2 KB 667 lines javascript

1// Documentation shell: client-side routing, navigation, table of contents, search, live tables.2import { $, $$, h, esc, initChrome, fetchJSON, getStatus, fmtInt, fmtNum, fmtDate, announce } from "/assets/site/core.js";3import { codeTabs, snippet } from "/assets/site/codeblock.js";4import { SAMPLES, SDK } from "/assets/site/samples.js";5import { SECTIONS, LINKS, SNIPPETS, PARAM_DOCS, ERROR_DOCS, LIMIT_DOCS, ENDPOINT_DOCS } from "/assets/site/docs-content.js";67initChrome();89const article = $("[data-article]");10const BY_SLUG = new Map(SECTIONS.map((s) => [s.slug, s]));11const pathFor = (s) => s.path || (s.slug === "overview" ? "/docs" : `/docs/${s.slug}`);12const htmlOf = (s) => (s._html ??= s.html()); // evaluated once: code() registers snippets as a side effect13const EXTERNAL = '<svg viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.500" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4.500 2.500h5v5M9.500 2.500 3 9"/></svg>';1415// ------------------------------------------------------------------ live data (fetched once)16let openapiPromise;17function openapi() {18  return (openapiPromise ??= fetchJSON("/openapi.json").then((r) => {19    if (!r.ok || !r.body) throw new Error(`HTTP ${r.status}`);20    return r.body;21  }));22}2324function stateBox(title, text) {25  return h("div", { class: "dyn-state", role: "status" }, h("strong", null, title), text);26}27const loadFailed = (what) => stateBox(`${what} could not be loaded`,28  "This part of the page is generated from the live backend, which did not answer. Reload the page to try again; nothing is shown rather than a copy that might be out of date.");2930function table(headers, rows) {31  return h("div", { class: "table-wrap", tabindex: "0", role: "region", "aria-label": headers.map((x) => x.label || x).join(", ") },32    h("table", { class: "data stack" },33      h("thead", null, h("tr", null, headers.map((x) => h("th", { class: x.num ? "num" : null, scope: "col" }, x.label || x)))),34      h("tbody", null, rows.map((tr) => {35        Array.from(tr.children).forEach((td, i) => { if (headers[i]) td.dataset.label = headers[i].label || headers[i]; });36        return tr;37      }))));38}3940// ---- JSON Schema → readable type / constraints41function refName(ref) { return ref.split("/").pop(); }42function variants(schema) {43  const list = schema.anyOf || schema.oneOf;44  return list ? list.filter((v) => v.type !== "null") : [schema];45}46function typeNode(schema) {47  const parts = variants(schema).map((v) => {48    if (v.$ref) { const n = refName(v.$ref); return h("a", { href: `#schema-${n}` }, n); }49    if (v.enum) return v.enum.map((e) => JSON.stringify(e)).join(" | ");50    if (v.const !== undefined) return JSON.stringify(v.const);51    if (v.type === "array") {52      const inner = v.items ? typeNode(v.items) : "any";53      return h("span", null, inner, "[]");54    }55    return Array.isArray(v.type) ? v.type.filter((t) => t !== "null").join(" | ") : (v.type || "any");56  });57  const out = h("span", { class: "param-type" });58  parts.forEach((p, i) => { if (i) out.append(" | "); out.append(p); });59  return out;60}61function constraints(schema) {62  const out = [];63  for (const v of variants(schema)) {64    const lo = v.minimum ?? null, hi = v.maximum ?? null;65    const xlo = v.exclusiveMinimum ?? null, xhi = v.exclusiveMaximum ?? null;66    if (lo !== null && hi !== null) out.push(lo === hi ? `= ${lo}` : `${lo} to ${hi}`);67    else if (xlo !== null && hi !== null) out.push(`> ${xlo}, ≤ ${hi}`);68    else {69      if (lo !== null) out.push(`≥ ${lo}`);70      if (xlo !== null) out.push(`> ${xlo}`);71      if (hi !== null) out.push(`≤ ${hi}`);72      if (xhi !== null) out.push(`< ${xhi}`);73    }74    if (v.minLength != null && v.maxLength != null) out.push(`${v.minLength} to ${v.maxLength} chars`);75    else if (v.minLength != null) out.push(`≥ ${v.minLength} chars`);76    else if (v.maxLength != null) out.push(`≤ ${v.maxLength} chars`);77    if (v.minItems != null) out.push(`≥ ${v.minItems} item${v.minItems > 1 ? "s" : ""}`);78    if (v.maxItems != null) out.push(`≤ ${v.maxItems} items`);79    if (v.pattern) out.push(`pattern ${v.pattern}`);80  }81  return out;82}8384async function renderParams(el) {85  const name = el.dataset.schema;86  try {87    const api = await openapi();88    const schema = api.components?.schemas?.[name];89    if (!schema || !schema.properties) throw new Error("schema missing");90    const required = new Set(schema.required || []);91    const docs = PARAM_DOCS[name] || {};92    const prefix = name === "ChatRequest" ? "param-" : `param-${name}-`;93    const names = Object.keys(schema.properties).sort((a, b) => (required.has(b) - required.has(a)));94    const rows = names.map((key) => {95      const p = schema.properties[key];96      const cons = constraints(p);97      const hasDefault = Object.prototype.hasOwnProperty.call(p, "default") && p.default !== null;98      const desc = h("td");99      if (docs[key]) desc.innerHTML = docs[key]; // authored text from docs-content.js100      else if (p.description) desc.textContent = p.description;101      return h("tr", { id: `${prefix}${key}` },102        h("td", null, h("span", { class: "param-name" }, key), required.has(key) ? h("span", { class: "param-req" }, "required") : null),103        h("td", null, typeNode(p)),104        h("td", { class: cons.length ? "tabular" : "muted" }, cons.length ? cons.join("; ") : "—"),105        h("td", { class: hasDefault ? null : "muted" }, hasDefault ? h("code", null, JSON.stringify(p.default)) : "—"),106        desc);107    });108    el.replaceChildren(table(["Parameter", "Type", "Constraints", "Default", "Description"], rows));109    indexDynamic(name, names.map((key) => ({ anchor: `${prefix}${key}`, heading: key, text: stripTags(docs[key] || "") })));110  } catch {111    el.replaceChildren(loadFailed("The parameter table"));112  }113}114115async function renderErrors(el) {116  try {117    const api = await openapi();118    const codes = api["x-error-codes"];119    if (!codes || typeof codes !== "object") throw new Error("missing");120    const rows = Object.entries(codes).map(([code, info]) => {121      const doc = ERROR_DOCS[code];122      const desc = h("td"), retry = h("td");123      if (doc) { desc.innerHTML = doc[0]; retry.innerHTML = doc[1]; } else { desc.textContent = info.description || ""; retry.textContent = "—"; }124      const cls = info.status >= 500 ? "danger" : info.status === 429 ? "warn" : "info";125      return h("tr", { id: `error-${code}` }, h("td", { class: "num" }, h("span", { class: `badge ${cls}` }, String(info.status))),126        h("td", null, h("code", null, code)), desc, retry);127    });128    el.replaceChildren(table([{ label: "Status", num: true }, "Code", "Meaning", "Retry?"], rows));129    indexDynamic("errors", Object.keys(codes).map((code) => ({ anchor: `error-${code}`, heading: code, text: stripTags(ERROR_DOCS[code]?.[0] || "") })));130  } catch {131    el.replaceChildren(loadFailed("The error code table"));132  }133}134135function fmtLimit(key, value) {136  const unit = LIMIT_DOCS[key]?.[1];137  if (typeof value !== "number") return String(value);138  if (unit === "bytes") {139    const mib = value / 1048576;140    return `${fmtInt(value)} bytes (${Number.isInteger(mib) ? mib : mib.toFixed(1)} MiB)`;141  }142  if (unit === "seconds") return `${fmtInt(value)} s`;143  return unit ? `${fmtInt(value)} ${unit}` : fmtInt(value);144}145async function renderLimits(el) {146  try {147    const limits = (await openapi())["x-limits"];148    if (!limits || typeof limits !== "object") throw new Error("missing");149    const rows = Object.entries(limits).map(([key, value]) => {150      const doc = LIMIT_DOCS[key];151      const noteCell = h("td");152      if (doc) noteCell.innerHTML = doc[2];153      return h("tr", null, h("td", null, doc ? h("strong", null, doc[0]) : h("code", null, key)),154        h("td", { class: "num" }, fmtLimit(key, value)), noteCell);155    });156    el.replaceChildren(table(["Limit", { label: "Value", num: true }, "Effect"], rows));157  } catch {158    el.replaceChildren(loadFailed("The server limits"));159  }160}161async function fillInlineLimits(root) {162  const spans = $$("[data-limit]", root);163  if (!spans.length) return;164  try {165    const limits = (await openapi())["x-limits"] || {};166    for (const s of spans) if (limits[s.dataset.limit] !== undefined) s.textContent = fmtLimit(s.dataset.limit, limits[s.dataset.limit]);167  } catch { /* keep the generic wording */ }168}169170async function renderEndpoints(el) {171  try {172    const api = await openapi();173    const rows = [];174    for (const [path, ops] of Object.entries(api.paths || {})) {175      for (const [method, op] of Object.entries(ops)) {176        const M = method.toUpperCase();177        const full = path;178        rows.push(h("tr", null,179          h("td", null, h("span", { class: `method ${method === "post" ? "post" : ""}` }, M)),180          h("td", null, h("code", null, full)),181          h("td", null, ENDPOINT_DOCS[`${M} ${path}`] || op.summary || ""),182          h("td", null, op.security ? "API key" : "None")));183      }184    }185    if (!rows.length) throw new Error("no paths");186    el.replaceChildren(table(["Method", "Path", "Purpose", "Auth"], rows));187  } catch {188    el.replaceChildren(loadFailed("The endpoint list"));189  }190}191192async function renderModels(el) {193  const { state, data } = await getStatus();194  if (!data) { el.replaceChildren(loadFailed("The model list")); return; }195  const models = Array.isArray(data.models) ? data.models : [];196  if (!models.length) { el.replaceChildren(stateBox("No public model is reported", "The status endpoint answered without any model.")); return; }197  const rows = models.map((m) => h("tr", null,198    h("td", null, h("strong", null, m.display_name || "—")),199    h("td", null, h("code", null, m.id)),200    h("td", null, m.quantization || "—"),201    h("td", { class: "num" }, typeof m.context_window === "number" ? `${fmtInt(m.context_window)} tokens` : "—"),202    h("td", null, h("span", { class: `badge ${m.available ? "ok" : "danger"}` }, m.available ? "Available" : "Unavailable"))));203  el.replaceChildren(table(["Model", "id", "Quantization", { label: "Context window", num: true }, "Status"], rows),204    h("p", { class: "source-note" }, `Engine: ${data.engine || "—"} · API version ${data.api_version || "—"} · service ${state}`));205}206207async function renderChangelog(el) {208  try {209    const r = await fetchJSON("/changelog.json", { cache: "no-cache" });210    if (!r.ok || !Array.isArray(r.body)) throw new Error("bad");211    if (!r.body.length) { el.replaceChildren(stateBox("No release has been published yet", "The changelog is empty.")); return; }212    el.replaceChildren(...r.body.map((rel) => h("section", { class: "release", id: `v${String(rel.version || "").replace(/[^\w.-]/g, "")}` },213      h("div", { class: "release-head" },214        h("span", { class: "badge accent tabular" }, `v${rel.version ?? "?"}`),215        h("h2", null, rel.title || "Release"),216        h("time", { datetime: rel.date || null }, fmtDate(rel.date))),217      h("ul", null, (Array.isArray(rel.changes) ? rel.changes : []).map((c) => h("li", null, String(c)))))));218  } catch {219    el.replaceChildren(loadFailed("The changelog"));220  }221}222223// ------------------------------------------------------------------ benchmarks224const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);225const ms = (v) => (num(v) === null ? "—" : `${fmtNum(v, v >= 100 ? 0 : 1)} ms`);226const tps = (v) => (num(v) === null ? "—" : fmtNum(v, 1));227const pct = (v) => (num(v) === null ? "—" : `${fmtNum(v * 100, v === 0 ? 0 : 2)} %`);228const txt = (v) => (v === null || v === undefined || v === "" ? "—" : String(v));229230function tile(label, value, unit) {231  return h("div", { class: "bench-tile" }, h("dt", null, label), h("dd", null, value, value !== "—" && unit ? h("small", null, unit) : null));232}233234function svgEl(tag, attrs, ...children) {235  const el = document.createElementNS("http://www.w3.org/2000/svg", tag);236  for (const [k, v] of Object.entries(attrs || {})) if (v !== null && v !== undefined) el.setAttribute(k, v);237  el.append(...children);238  return el;239}240function niceMax(v) {241  const p = 10 ** Math.floor(Math.log10(v));242  for (const m of [1, 2, 2.5, 5, 10]) if (v <= m * p) return m * p;243  return 10 * p;244}245246function concurrencyChart(rows) {247  const pts = rows.filter((r) => num(r.clients) !== null).sort((a, b) => a.clients - b.clients);248  const series = [249    { key: "aggregate_tps", label: "Aggregate throughput", color: "var(--s1)" },250    { key: "per_request_tps", label: "Per-request speed", color: "var(--s2)" },251  ].filter((s) => pts.filter((p) => num(p[s.key]) !== null).length >= 2);252  if (!series.length) return null;253254  const W = 720, H = 300, m = { l: 48, r: 132, t: 14, b: 40 };255  const maxY = niceMax(Math.max(...series.flatMap((s) => pts.map((p) => num(p[s.key]) ?? 0))) || 1);256  const xs = pts.map((p) => p.clients);257  const x0 = Math.min(...xs), x1 = Math.max(...xs);258  const X = (v) => m.l + (x1 === x0 ? 0.5 : (v - x0) / (x1 - x0)) * (W - m.l - m.r);259  const Y = (v) => H - m.b - (v / maxY) * (H - m.t - m.b);260261  const svg = svgEl("svg", { viewBox: `0 0 ${W} ${H}`, role: "img",262    "aria-label": `Line chart of tokens per second against concurrent clients, from ${x0} to ${x1} clients. The same values are in the table below.` });263  for (let i = 0; i <= 4; i++) {264    const v = (maxY / 4) * i;265    svg.append(svgEl("line", { class: "grid", x1: m.l, x2: W - m.r, y1: Y(v), y2: Y(v) }),266      svgEl("text", { class: "axis-text", x: m.l - 8, y: Y(v) + 4, "text-anchor": "end" }, fmtNum(v, Number.isInteger(maxY / 4) ? 0 : maxY / 4 < 1 ? 2 : 1)));267  }268  for (const p of pts) svg.append(svgEl("text", { class: "axis-text", x: X(p.clients), y: H - m.b + 18, "text-anchor": "middle" }, String(p.clients)));269  svg.append(svgEl("text", { class: "axis-title", x: (m.l + W - m.r) / 2, y: H - 4, "text-anchor": "middle" }, "Concurrent clients"));270  const cross = svgEl("line", { class: "cross", y1: m.t, y2: H - m.b, visibility: "hidden" });271  svg.append(cross);272273  const labelYs = [];274  for (const s of series) {275    const sp = pts.filter((p) => num(p[s.key]) !== null);276    svg.append(svgEl("path", { class: "line", stroke: s.color, d: sp.map((p, i) => `${i ? "L" : "M"}${X(p.clients).toFixed(1)} ${Y(p[s.key]).toFixed(1)}` ).join("") }));277    for (const p of sp) svg.append(svgEl("circle", { class: "pt", fill: s.color, cx: X(p.clients), cy: Y(p[s.key]), r: 4.500 }));278    const end = sp[sp.length - 1];279    let ly = Y(end[s.key]) + 4;280    for (const other of labelYs) if (Math.abs(other - ly) < 14) ly = other + (ly >= other ? 14 : -14);281    labelYs.push(ly);282    svg.append(svgEl("text", { class: "series-label", x: X(end.clients) + 12, y: ly }, s.label));283  }284285  const tip = h("div", { class: "chart-tip", hidden: true });286  const box = h("div", { class: "chart" },287    h("h4", null, "Throughput against concurrency (tokens per second)"),288    h("div", { class: "chart-legend" }, series.map((s) => h("span", null, h("i", { style: `background:${s.color}` }), s.label))),289    svg, tip);290291  function show(p) {292    cross.setAttribute("x1", X(p.clients)); cross.setAttribute("x2", X(p.clients)); cross.setAttribute("visibility", "visible");293    tip.replaceChildren(h("strong", null, `${p.clients} client${p.clients === 1 ? "" : "s"}`),294      ...series.map((s) => h("span", null, h("i", { style: `background:${s.color}` }), `${s.label}: ${tps(p[s.key])} tok/s`)));295    tip.hidden = false;296    const rect = svg.getBoundingClientRect(), host = box.getBoundingClientRect();297    const px = rect.left - host.left + (X(p.clients) / W) * rect.width;298    const left = Math.min(Math.max(8, px + 12), host.width - tip.offsetWidth - 8);299    tip.style.left = `${left}px`;300    tip.style.top = `${rect.top - host.top + 8}px`;301  }302  function hide() { tip.hidden = true; cross.setAttribute("visibility", "hidden"); }303  svg.addEventListener("pointermove", (e) => {304    const rect = svg.getBoundingClientRect();305    const vx = ((e.clientX - rect.left) / rect.width) * W;306    let best = pts[0];307    for (const p of pts) if (Math.abs(X(p.clients) - vx) < Math.abs(X(best.clients) - vx)) best = p;308    show(best);309  });310  svg.addEventListener("pointerleave", hide);311  return box;312}313314async function renderBenchmarks(el) {315  let res;316  try { res = await fetchJSON("/assets/data/benchmarks.json", { cache: "no-cache" }); }317  catch { el.replaceChildren(loadFailed("The benchmark file")); return; }318  if (res.status === 404) {319    el.replaceChildren(stateBox("Benchmarks have not been published yet",320      "No measurement file is available for this deployment. Figures will appear here once a benchmark run has been published; until then this page shows no numbers at all rather than estimates."));321    return;322  }323  const b = res.body;324  if (!res.ok || !b || typeof b !== "object" || Array.isArray(b)) { el.replaceChildren(loadFailed("The benchmark file")); return; }325326  const out = [];327  const meta = b.meta || {};328  const META = [["date", "Date"], ["host", "Host"], ["chip", "Chip"], ["memory_gb", "Memory"], ["macos", "macOS"], ["mlx", "MLX"], ["mlx_lm", "mlx-lm"], ["model", "Model"], ["revision", "Revision"]];329  out.push(h("h3", { id: "bench-setup" }, "Test setup"),330    table(["Item", "Value"], META.map(([k, label]) => h("tr", null, h("td", null, label),331      h("td", { class: "tabular" }, k === "memory_gb" && num(meta[k]) !== null ? `${meta[k]} GB` : k === "date" && meta[k] ? fmtDate(String(meta[k])) : txt(meta[k]))))));332333  const single = b.single || {};334  const cache = b.prefix_cache || {};335  out.push(h("h3", { id: "bench-single" }, "Single request"),336    h("dl", { class: "bench-tiles" },337      tile("Time to first token", num(single.ttft_ms) === null ? "—" : fmtNum(single.ttft_ms, 0), "ms"),338      tile("Generation speed", tps(single.tokens_per_second), "tok/s"),339      tile("Prompt processing", tps(single.prompt_tokens_per_second), "tok/s"),340      tile("Peak memory", num(b.peak_memory_bytes) === null ? "—" : fmtNum(b.peak_memory_bytes / 1073741824, 1), "GiB"),341      tile("TTFT, cold prefix", num(cache.cold_ttft_ms) === null ? "—" : fmtNum(cache.cold_ttft_ms, 0), "ms"),342      tile("TTFT, warm prefix", num(cache.warm_ttft_ms) === null ? "—" : fmtNum(cache.warm_ttft_ms, 0), "ms"),343      tile("Recommended concurrency", num(b.recommended?.max_active) === null ? "—" : fmtInt(b.recommended.max_active), "active")));344345  const conc = Array.isArray(b.concurrency) ? b.concurrency : [];346  out.push(h("h3", { id: "bench-concurrency" }, "Concurrency"));347  if (conc.length) {348    const chart = concurrencyChart(conc);349    if (chart) out.push(chart);350    out.push(table([{ label: "Clients", num: true }, { label: "Aggregate tok/s", num: true }, { label: "Per-request tok/s", num: true },351      { label: "TTFT p50", num: true }, { label: "TTFT p95", num: true }, { label: "Latency p95", num: true }, { label: "Errors", num: true }],352      conc.map((c) => h("tr", null, ...[txt(c.clients), tps(c.aggregate_tps), tps(c.per_request_tps), ms(c.ttft_p50_ms), ms(c.ttft_p95_ms), ms(c.latency_p95_ms), pct(c.error_rate)]353        .map((v) => h("td", { class: "num" }, v))))));354  } else out.push(h("p", { class: "muted" }, "— No concurrency measurements in the published file."));355356  const sc = Array.isArray(b.scenarios) ? b.scenarios : [];357  out.push(h("h3", { id: "bench-scenarios" }, "Scenarios"));358  if (sc.length) {359    out.push(table(["Scenario", { label: "Requests", num: true }, { label: "TTFT p50", num: true }, { label: "TTFT p95", num: true },360      { label: "tok/s p50", num: true }, { label: "Latency p50", num: true }, { label: "Latency p95", num: true }, { label: "Errors", num: true }],361      sc.map((s) => h("tr", null, h("td", null, h("strong", null, txt(s.name)), s.description ? h("div", { class: "muted" }, String(s.description)) : null),362        ...[num(s.requests) === null ? "—" : fmtInt(s.requests), ms(s.ttft_ms_p50), ms(s.ttft_ms_p95), tps(s.tokens_per_second_p50), ms(s.latency_ms_p50), ms(s.latency_ms_p95), pct(s.error_rate)]363          .map((v) => h("td", { class: "num" }, v))))));364  } else out.push(h("p", { class: "muted" }, "— No scenario measurements in the published file."));365366  if (Array.isArray(b.notes) && b.notes.length) out.push(h("h3", { id: "bench-notes" }, "Notes"), h("ul", null, b.notes.map((n) => h("li", null, String(n)))));367  out.push(h("p", { class: "source-note" }, "Source: /assets/data/benchmarks.json, as published by the operator. Missing values are shown as “—”."));368  el.replaceChildren(...out);369}370371const DYN = { params: renderParams, errors: renderErrors, limits: renderLimits, endpoints: renderEndpoints, models: renderModels,372  changelog: renderChangelog, benchmarks: renderBenchmarks };373374// ------------------------------------------------------------------ navigation375function buildNav() {376  const entries = [...SECTIONS.map((s) => ({ title: s.title, href: pathFor(s), group: s.group, slug: s.slug })), ...LINKS.map((l) => ({ ...l, external: true }))];377  for (const nav of $$("[data-docs-nav]")) {378    let group = null, ul = null;379    nav.replaceChildren();380    for (const e of entries) {381      if (e.group !== group) { group = e.group; nav.append(h("h2", null, group)); ul = h("ul"); nav.append(ul); }382      const a = h("a", { href: e.href, dataset: { slug: e.slug } }, h("span", null, e.title));383      if (e.external) a.insertAdjacentHTML("beforeend", EXTERNAL);384      ul.append(h("li", null, a));385    }386  }387}388389function slugFromLocation() {390  const path = location.pathname.replace(/\/+$/, "");391  if (path === "/changelog") return "changelog";392  if (path === "/docs" || path === "") return "overview";393  return decodeURIComponent(path.replace(/^\/docs\//, ""));394}395396let renderToken = 0;397async function render({ focus = false, scroll = true } = {}) {398  const slug = slugFromLocation();399  const link = LINKS.find((l) => l.slug === slug);400  if (link) { location.replace(link.href); return; }401  const section = BY_SLUG.get(slug);402  const token = ++renderToken;403404  for (const a of $$("[data-docs-nav] a")) {405    if (a.dataset.slug === slug) a.setAttribute("aria-current", "page"); else a.removeAttribute("aria-current");406  }407  const topNav = $('.site-nav [data-nav="changelog"]'), docsNav = $('.site-nav [data-nav="docs"]');408  if (topNav && docsNav) {409    (slug === "changelog" ? topNav : docsNav).setAttribute("aria-current", "page");410    (slug === "changelog" ? docsNav : topNav).removeAttribute("aria-current");411  }412413  if (!section) {414    document.title = "Section not found — MacLustr AI";415    $("[data-current-title]").textContent = "Not found";416    article.replaceChildren(h("span", { class: "eyebrow kicker" }, "Documentation"), h("h1", { tabindex: "-1" }, "This section does not exist."),417      h("p", { class: "lede" }, "The documentation has no page at this address. Pick a section from the menu, or search."),418      h("p", null, h("a", { class: "btn", href: "/docs" }, "Go to the overview")));419    $("[data-toc]").replaceChildren(); $("[data-pager]").replaceChildren();420    return;421  }422423  document.title = `${section.title} — MacLustr AI docs`;424  $("[data-current-title]").textContent = section.title;425  const body = h("div", { html: htmlOf(section) });426  article.replaceChildren(h("span", { class: "eyebrow kicker" }, section.group), h("h1", { tabindex: "-1", id: "top" }, section.title),427    h("p", { class: "lede" }, section.lede), ...body.childNodes);428  // restart the entrance animation429  article.style.animation = "none"; void article.offsetWidth; article.style.animation = "";430431  for (const el of $$("[data-sample]", article)) {432    const s = SAMPLES[el.dataset.sample];433    if (s) el.replaceWith(codeTabs(s, { label: el.dataset.label || "Code sample" }));434  }435  for (const el of $$("[data-snip]", article)) {436    const s = SNIPPETS[Number(el.dataset.snip)];437    el.replaceWith(snippet(s.text, s.lang, s.title));438  }439  for (const el of $$("[data-sdk]", article)) el.replaceWith(snippet(SDK[el.dataset.sdk], el.dataset.lang, el.dataset.title));440  for (const hd of $$("h2[id], h3[id]", article)) {441    hd.append(h("a", { class: "anchor", href: `#${hd.id}`, "aria-label": `Link to “${hd.textContent}”` }, "#"));442  }443  buildToc();444  buildPager(section);445446  const dyn = $$("[data-dyn]", article).map((el) => {447    el.replaceChildren(h("div", { class: "dyn-state", "aria-busy": "true" }, h("span", { class: "skeleton", style: "width:60%" })));448    return DYN[el.dataset.dyn]?.(el);449  });450  fillInlineLimits(article);451452  const toHash = () => {453    if (token !== renderToken) return;454    const id = decodeURIComponent(location.hash.slice(1));455    const target = id ? document.getElementById(id) : null;456    if (target) target.scrollIntoView({ block: "start" });457    else if (scroll) window.scrollTo(0, 0);458    return target;459  };460  toHash();461  if (focus) $("h1", article).focus({ preventScroll: true });462  if (dyn.length) Promise.allSettled(dyn).then(() => { if (token === renderToken) { buildToc(); if (location.hash) toHash(); } });463  if (focus) announce(`${section.title} loaded`);464}465466function buildToc() {467  const items = $$("h2[id], h3[id]", article).filter((hd) => !hd.closest(".release"));468  $("[data-toc]").replaceChildren(...items.map((hd) => h("li", null,469    h("a", { href: `#${hd.id}`, class: hd.tagName === "H3" ? "sub" : null, dataset: { target: hd.id } }, hd.firstChild?.textContent || hd.textContent))));470  $(".docs-toc").hidden = items.length === 0;471  spy();472}473let spyQueued = false;474function spy() {475  spyQueued = false;476  const links = $$("[data-toc] a");477  if (!links.length) return;478  let active = links[0];479  for (const a of links) {480    const el = document.getElementById(a.dataset.target);481    if (el && el.getBoundingClientRect().top <= 140) active = a;482  }483  for (const a of links) a.classList.toggle("active", a === active);484}485window.addEventListener("scroll", () => { if (!spyQueued) { spyQueued = true; requestAnimationFrame(spy); } }, { passive: true });486487function buildPager(section) {488  const i = SECTIONS.indexOf(section);489  const prev = SECTIONS[i - 1], next = SECTIONS[i + 1];490  $("[data-pager]").replaceChildren(491    prev ? h("a", { class: "prev", href: pathFor(prev), rel: "prev" }, h("small", null, "← Previous"), h("span", null, prev.title)) : "",492    next ? h("a", { class: "next", href: pathFor(next), rel: "next" }, h("small", null, "Next →"), h("span", null, next.title)) : "");493}494495function isDocsPath(path) { return path === "/docs" || path.startsWith("/docs/") || path === "/changelog"; }496function go(url, { focus = true } = {}) {497  const u = new URL(url, location.href);498  const samePage = u.pathname === location.pathname;499  history.pushState(null, "", u.pathname + u.hash);500  if (samePage) {501    const target = u.hash ? document.getElementById(decodeURIComponent(u.hash.slice(1))) : null;502    if (target) target.scrollIntoView({ block: "start" }); else window.scrollTo(0, 0);503  } else render({ focus });504}505document.addEventListener("click", (e) => {506  if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;507  const a = e.target.closest("a[href]");508  if (!a || a.target || a.origin !== location.origin || !isDocsPath(a.pathname)) return;509  if (a.pathname === location.pathname && a.hash) return; // in-page anchor: native behaviour510  e.preventDefault();511  closeDrawer();512  go(a.href);513});514window.addEventListener("popstate", () => render({ scroll: false }));515516// ------------------------------------------------------------------ mobile drawer517const drawer = $("#docs-drawer");518const drawerBtn = $("[data-drawer-open]");519function closeDrawer() { if (drawer.open) drawer.close(); }520drawerBtn.addEventListener("click", () => { drawer.showModal(); drawerBtn.setAttribute("aria-expanded", "true"); ($('a[aria-current="page"]', drawer) || $("a", drawer))?.focus(); });521drawer.addEventListener("close", () => drawerBtn.setAttribute("aria-expanded", "false"));522drawer.addEventListener("click", (e) => { if (e.target === drawer) drawer.close(); });523$("[data-drawer-close]").addEventListener("click", closeDrawer);524525// ------------------------------------------------------------------ search526const searchDlg = $("#docs-search");527const input = $("#search-input");528const results = $("#search-results");529const hint = $("[data-search-hint]");530let index = null;531const dynamicIndex = new Map();532let hits = [], cursor = -1;533534function stripTags(html) { const d = document.createElement("div"); d.innerHTML = html; return d.textContent || ""; }535function indexDynamic(group, entries) {536  const sec = BY_SLUG.get(group === "errors" ? "error-handling" : "chat-completions");537  dynamicIndex.set(group, entries.map((e) => ({ slug: sec.slug, title: sec.title, anchor: e.anchor, heading: e.heading, text: e.text, weight: 8 })));538}539540function buildIndex() {541  const out = [];542  for (const s of SECTIONS) {543    const root = h("div", { html: htmlOf(s) });544    let cur = { slug: s.slug, title: s.title, anchor: "", heading: s.title, text: `${s.lede} `, weight: 12 };545    out.push(cur);546    const walk = (node) => {547      for (const child of node.childNodes) {548        if (child.nodeType === 3) { cur.text += child.textContent; continue; }549        if (child.nodeType !== 1) continue;550        if (/^H[23]$/.test(child.tagName) && child.id) {551          cur = { slug: s.slug, title: s.title, anchor: child.id, heading: child.textContent, text: "", weight: 10 };552          out.push(cur);553        } else if (child.dataset.snip !== undefined) cur.text += ` ${SNIPPETS[Number(child.dataset.snip)].text} `;554        else if (child.dataset.sdk !== undefined || child.dataset.sample !== undefined || child.tagName === "svg") continue;555        else { walk(child); if (/^(P|LI|TR|TD|TH|DIV|OL|UL)$/.test(child.tagName)) cur.text += " "; }556      }557    };558    walk(root);559  }560  for (const e of out) e.text = e.text.replace(/\s+/g, " ").trim();561  return out;562}563564function search(q) {565  index ??= buildIndex();566  const terms = q.toLowerCase().split(/\s+/).filter(Boolean);567  if (!terms.length) return [];568  const all = [...index, ...[...dynamicIndex.values()].flat()];569  const scored = [];570  for (const e of all) {571    const hd = e.heading.toLowerCase(), tx = e.text.toLowerCase(), ti = e.title.toLowerCase();572    let score = 0, ok = true, pos = -1;573    for (const t of terms) {574      const inH = hd.includes(t), inT = tx.indexOf(t), inTi = ti.includes(t);575      if (!inH && inT < 0 && !inTi) { ok = false; break; }576      const freq = inT >= 0 ? Math.min(6, tx.split(t).length - 1) : 0;577      score += (inH ? e.weight + (hd === t ? 8 : hd.startsWith(t) ? 4 : 0) : 0) + (inTi ? 3 : 0) + freq * 1.5 + (inT >= 0 ? Math.max(0, 1 - inT / 400) : 0);578      if (pos < 0 && inT >= 0) pos = inT;579    }580    if (ok) scored.push({ e, score, pos });581  }582  return scored.sort((a, b) => b.score - a.score).slice(0, 12);583}584585function marked(text, terms) {586  const frag = document.createDocumentFragment();587  const re = new RegExp(`(${terms.map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})`, "ig");588  let last = 0, m;589  while ((m = re.exec(text)) !== null) {590    if (m[0] === "") { re.lastIndex++; continue; }591    frag.append(text.slice(last, m.index), h("mark", null, m[0]));592    last = m.index + m[0].length;593  }594  frag.append(text.slice(last));595  return frag;596}597598function renderResults() {599  const q = input.value.trim();600  const terms = q.toLowerCase().split(/\s+/).filter(Boolean);601  hits = search(q);602  cursor = hits.length ? 0 : -1;603  results.replaceChildren(...hits.map(({ e, pos }, i) => {604    const start = Math.max(0, pos - 50);605    const excerpt = (start > 0 ? "…" : "") + e.text.slice(start, start + 170) + (e.text.length > start + 170 ? "…" : "");606    return h("li", { role: "option", id: `sr-${i}`, "aria-selected": i === 0 ? "true" : "false", dataset: { i } },607      h("div", { class: "r-title" }, h("span", null, marked(e.heading, terms)), e.heading !== e.title ? h("small", null, e.title) : null),608      excerpt ? h("div", { class: "r-text" }, marked(excerpt, terms)) : null);609  }));610  input.setAttribute("aria-expanded", hits.length ? "true" : "false");611  if (hits.length) input.setAttribute("aria-activedescendant", "sr-0"); else input.removeAttribute("aria-activedescendant");612  hint.textContent = !q ? "Type to search every section. Use ↑ ↓ to move and Enter to open."613    : hits.length ? `${hits.length} result${hits.length === 1 ? "" : "s"}` : `No result for “${q}”.`;614}615function moveCursor(d) {616  if (!hits.length) return;617  cursor = (cursor + d + hits.length) % hits.length;618  $$("li", results).forEach((li, i) => li.setAttribute("aria-selected", i === cursor ? "true" : "false"));619  input.setAttribute("aria-activedescendant", `sr-${cursor}`);620  $(`#sr-${cursor}`)?.scrollIntoView({ block: "nearest" });621}622function openHit(i) {623  const hit = hits[i];624  if (!hit) return;625  searchDlg.close();626  const s = BY_SLUG.get(hit.e.slug);627  go(pathFor(s) + (hit.e.anchor ? `#${hit.e.anchor}` : ""));628}629function openSearch() {630  if (searchDlg.open) return;631  closeDrawer();632  searchDlg.showModal();633  input.select();634  renderResults();635  // Warm the dynamic part of the index (parameter and error tables) so it is searchable from any section.636  openapi().then((api) => {637    if (!dynamicIndex.has("ChatRequest")) {638      const props = Object.keys(api.components?.schemas?.ChatRequest?.properties || {});639      indexDynamic("ChatRequest", props.map((k) => ({ anchor: `param-${k}`, heading: k, text: stripTags(PARAM_DOCS.ChatRequest[k] || "") })));640    }641    if (!dynamicIndex.has("errors")) {642      indexDynamic("errors", Object.keys(api["x-error-codes"] || {}).map((c) => ({ anchor: `error-${c}`, heading: c, text: stripTags(ERROR_DOCS[c]?.[0] || "") })));643    }644    if (searchDlg.open && input.value.trim()) renderResults();645  }).catch(() => {});646}647for (const b of $$("[data-search-open]")) b.addEventListener("click", openSearch);648$("[data-search-close]").addEventListener("click", () => searchDlg.close());649searchDlg.addEventListener("click", (e) => { if (e.target === searchDlg) searchDlg.close(); });650input.addEventListener("input", renderResults);651input.addEventListener("keydown", (e) => {652  if (e.key === "ArrowDown") { e.preventDefault(); moveCursor(1); }653  else if (e.key === "ArrowUp") { e.preventDefault(); moveCursor(-1); }654  else if (e.key === "Enter") { e.preventDefault(); openHit(cursor); }655  else if (e.key === "Escape") { e.preventDefault(); searchDlg.close(); }656});657results.addEventListener("click", (e) => { const li = e.target.closest("li"); if (li) openHit(Number(li.dataset.i)); });658document.addEventListener("keydown", (e) => {659  const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName || "") || document.activeElement?.isContentEditable;660  if ((e.key === "k" || e.key === "K") && (e.metaKey || e.ctrlKey)) { e.preventDefault(); openSearch(); }661  else if (e.key === "/" && !typing && !e.metaKey && !e.ctrlKey && !e.altKey) { e.preventDefault(); openSearch(); }662});663664// ------------------------------------------------------------------ boot665buildNav();666render();667
Files main
Menu

Theme