Initial commit of Descrybe v2 without local scratch artifacts.

Drop one-shot tmp/axe scripts and agent i18n scratch so the Gitea tree is deployable.
This commit is contained in:
greeneclipse committed 2026-08-09 22:47:43 +02:00
commit 8580c996c3
1285 files changed
+325780

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
import type { DocsGuideEndpoint, DocsGuideHttpMethod } from "./types";
/** Public API-key surface prefix (matches `mountV1` + OpenAPI servers). */
export const API_V1_PREFIX = "/api/v1";
/**
* Characters RapiDoc replaces with `-` when building operation/tag elementIds
* (`pt` in rapidoc-min.js). Keep Ask deep links in lockstep with the viewer.
*/
export const RAPIDOC_ID_UNSAFE = /[\s#:?&={}]/g;
/** Normalize an OpenAPI path to the RapiDoc operation id path segment. */
export function rapidocPathId(openApiPath: string): string {
const path = openApiPath.startsWith("/") ? openApiPath : `/${openApiPath}`;
return path.replace(RAPIDOC_ID_UNSAFE, "-");
}
/**
* RapiDoc operation hash for the /docs viewer.
* OpenAPI paths are relative to the `/api/v1` server (e.g. `/products`).
* Matches RapiDoc `use-path-in-nav-bar`: `${method}-${path}` with `{}/spaces/…` → `-`.
* Example: POST `/feeds/{id}/sync` → `/docs#post-/feeds/-id-/sync`.
*/
export function docsOperationHref(method: DocsGuideHttpMethod | string, openApiPath: string): string {
const m = method.toLowerCase();
return `/docs#${m}-${rapidocPathId(openApiPath)}`;
}
/** RapiDoc tag hash (tag names from OpenAPI `tags[].name`). */
export function docsTagHref(tagName: string): string {
return `/docs#tag--${tagName.replace(RAPIDOC_ID_UNSAFE, "-")}`;
}
/** RapiDoc Authentication / Authorize panel (Try-it credentials). */
export function docsAuthHref(): string {
return "/docs#auth";
}
/**
* RapiDoc Overview section. Optional slug matches markdown H2 under `info.description`
* (e.g. `authenticate`, `quick-curl`, `processing-contracts-dual-mode`).
*/
export function docsOverviewHref(sectionSlug?: string): string {
if (!sectionSlug) return "/docs#overview";
const slug = sectionSlug.replace(RAPIDOC_ID_UNSAFE, "-").replace(/^-+|-+$/g, "");
return `/docs#overview--${slug}`;
}
export function apiV1Path(openApiPath: string): string {
const path = openApiPath.startsWith("/") ? openApiPath : `/${openApiPath}`;
return `${API_V1_PREFIX}${path}`;
}
export function endpoint(
method: DocsGuideHttpMethod,
openApiPath: string,
summary?: string
): DocsGuideEndpoint {
return {
method,
path: apiV1Path(openApiPath),
summary,
href: docsOperationHref(method, openApiPath)
};
}
/** Extract a RapiDoc fragment from a bare hash or `/docs#…` href. */
export function docsHashFromHref(hashOrHref: string): string {
const raw = hashOrHref.trim();
if (!raw) return "";
const docsIdx = raw.indexOf("/docs#");
if (docsIdx >= 0) return raw.slice(docsIdx + 6).replace(/^#/, "").trim();
return raw.replace(/^#/, "").trim();
}
/** Normalize and apply a RapiDoc hash; prefers element.scrollTo when available. */
export function jumpToRapiDocSection(
hashOrHref: string,
rapiEl?: HTMLElement | null
): void {
const clean = docsHashFromHref(hashOrHref);
if (!clean || typeof window === "undefined") return;
window.location.hash = clean;
const el = rapiEl as
| (HTMLElement & {
scrollTo?: (path: string) => void;
gotoPath?: (path: string) => void;
})
| null
| undefined;
try {
if (typeof el?.scrollTo === "function") {
el.scrollTo(clean);
return;
}
if (typeof el?.gotoPath === "function") {
el.gotoPath(clean);
}
} catch {
/* hash navigation is enough when scrollTo rejects unknown paths */
}
}
+50
View File
@@ -0,0 +1,50 @@
/**
* No-LLM docs Ask decision-tree content + helpers.
*
* UI agent contract:
* - Import `DOCS_GUIDE_TREE`, `getGuideNode`, `isQuestionNode`, `isAnswerNode`.
* - Deep-link with `endpoint.href` / `docsOperationHref` → `/docs#method-/path`
* (RapiDoc replaces `{param}` with `-param-`; use helpers, never raw braces).
* - Authorize / Try-it: `docsAuthHref()` → `/docs#auth`; overview via `docsOverviewHref`.
* - Shareable steps: `node.pathKey` → `?ask=path=<pathKey>` via `nodeIdForPathKey`.
* - Footer: `tree.escapeLinks` (support → `/support/new`).
* - Deep-open: `?ask=open` or `?ask=path=<pathKey>`.
* - Do not wire Ask to any LLM / AI config slot — routing is this tree only.
*/
export type {
DocsGuideAnswerNode,
DocsGuideChoice,
DocsGuideEndpoint,
DocsGuideHttpMethod,
DocsGuideLink,
DocsGuideLinkKind,
DocsGuideNode,
DocsGuideQuestionNode,
DocsGuideTree
} from "./types";
export {
API_V1_PREFIX,
apiV1Path,
docsAuthHref,
docsHashFromHref,
docsOperationHref,
docsOverviewHref,
docsTagHref,
endpoint,
jumpToRapiDocSection,
RAPIDOC_ID_UNSAFE,
rapidocPathId
} from "./hrefs";
export {
getGuideNode,
isAnswerNode,
isQuestionNode,
matchGuideSynonym,
nodeIdForPathKey,
validateDocsGuideTree
} from "./resolve";
export { assertDocsGuideTree, DOCS_GUIDE_TREE } from "./tree";
+136
View File
@@ -0,0 +1,136 @@
import type { DocsGuideAnswerNode, DocsGuideNode, DocsGuideQuestionNode, DocsGuideTree } from "./types";
export function getGuideNode(tree: DocsGuideTree, id: string | null | undefined): DocsGuideNode | undefined {
if (!id) return undefined;
return tree.nodes[id];
}
export function isQuestionNode(node: DocsGuideNode | undefined): node is DocsGuideQuestionNode {
return node?.kind === "question";
}
export function isAnswerNode(node: DocsGuideNode | undefined): node is DocsGuideAnswerNode {
return node?.kind === "answer";
}
/** Resolve a shareable `?ask=path=` key to a node id. */
export function nodeIdForPathKey(tree: DocsGuideTree, pathKey: string | null | undefined): string | undefined {
if (!pathKey) return undefined;
const key = pathKey.trim().toLowerCase();
for (const node of Object.values(tree.nodes)) {
if (node.pathKey?.toLowerCase() === key) return node.id;
}
return undefined;
}
/**
* Lightweight synonym match for optional chip preselection (still no LLM).
* Returns the best answer/question id or undefined.
*/
export function matchGuideSynonym(tree: DocsGuideTree, query: string | null | undefined): string | undefined {
const q = query?.trim().toLowerCase();
if (!q || q.length < 2) return undefined;
let bestId: string | undefined;
let bestScore = 0;
for (const node of Object.values(tree.nodes)) {
for (const syn of node.synonyms ?? []) {
const s = syn.toLowerCase();
if (q === s) return node.id;
if (q.includes(s) || s.includes(q)) {
const score = Math.min(q.length, s.length);
if (score > bestScore) {
bestScore = score;
bestId = node.id;
}
}
}
}
return bestId;
}
/** Structural integrity checks for tests / CI. Returns human-readable errors. */
export function validateDocsGuideTree(tree: DocsGuideTree): string[] {
const errors: string[] = [];
if (!tree.rootId || !tree.nodes[tree.rootId]) {
errors.push(`missing root node "${tree.rootId}"`);
}
for (const [id, node] of Object.entries(tree.nodes)) {
if (node.id !== id) {
errors.push(`node key "${id}" does not match node.id "${node.id}"`);
}
if (node.kind === "question") {
const n = node.choices.length;
if (n < 2 || n > 3) {
errors.push(`question "${id}" should have 2–3 choices (has ${n})`);
}
const choiceIds = new Set<string>();
for (const c of node.choices) {
if (!c.id || !c.label || !c.nextId) {
errors.push(`question "${id}" has incomplete choice`);
}
if (choiceIds.has(c.id)) {
errors.push(`question "${id}" duplicate choice id "${c.id}"`);
}
choiceIds.add(c.id);
if (!tree.nodes[c.nextId]) {
errors.push(`question "${id}" choice "${c.id}" points to missing "${c.nextId}"`);
}
}
} else {
if (!node.title || !node.outcome) {
errors.push(`answer "${id}" missing title or outcome`);
}
for (const rel of node.relatedIds ?? []) {
if (!tree.nodes[rel]) {
errors.push(`answer "${id}" relatedIds missing "${rel}"`);
}
}
for (const ep of node.endpoints ?? []) {
if (!ep.href.startsWith("/docs#")) {
errors.push(`answer "${id}" endpoint href should be a /docs# hash`);
}
if (/[{}\s]/.test(ep.href)) {
errors.push(
`answer "${id}" endpoint href must use RapiDoc ids (no braces/spaces): ${ep.href}`
);
}
if (!ep.path.startsWith("/api/v1/")) {
errors.push(`answer "${id}" endpoint path should start with /api/v1/`);
}
}
for (const link of node.links ?? []) {
if (link.kind === "docs" && link.href) {
if (!link.href.startsWith("/docs#") && link.href !== "/docs") {
errors.push(`answer "${id}" docs link should be /docs or /docs#…`);
}
if (/[{}]/.test(link.href)) {
errors.push(
`answer "${id}" docs link must use RapiDoc ids (no braces): ${link.href}`
);
}
}
if (link.kind === "support" && link.href && link.href !== "/support/new") {
errors.push(`answer "${id}" support link should be /support/new (got ${link.href})`);
}
}
}
}
const pathKeys = new Map<string, string>();
for (const node of Object.values(tree.nodes)) {
if (!node.pathKey) continue;
const prev = pathKeys.get(node.pathKey);
if (prev) {
errors.push(`duplicate pathKey "${node.pathKey}" on "${prev}" and "${node.id}"`);
}
pathKeys.set(node.pathKey, node.id);
}
for (const link of tree.escapeLinks) {
if (link.kind === "support" && link.href && link.href !== "/support/new") {
errors.push(`escapeLinks support should be /support/new (got ${link.href})`);
}
if (link.kind === "docs" && link.href && /[{}]/.test(link.href)) {
errors.push(`escapeLinks docs href must use RapiDoc ids (no braces): ${link.href}`);
}
}
return errors;
}
+802
View File
@@ -0,0 +1,802 @@
import { docsAuthHref, docsOperationHref, docsOverviewHref, docsTagHref, endpoint } from "./hrefs";
import type { DocsGuideTree } from "./types";
import { validateDocsGuideTree } from "./resolve";
/**
* Decision-tree CONTENT for the no-LLM docs Ask guide.
* Source of truth for routes: `mountV1` in apps/api/internal/httpapi/v1.go
* and OpenAPI in apps/api/internal/httpapi/v1_openapi.go.
*
* UI agent: import DOCS_GUIDE_TREE / helpers from `$lib/docs-guide`.
* Deep links must match RapiDoc ids (`{id}` → `-id-`); use href helpers.
*/
const AUTH_NOTE =
"Company API key (prefix dk_…). Prefer Authorization: Bearer; X-API-Key also works. Create keys in Settings → API keys. On /docs when logged in, use Use my API key for RapiDoc Try-it. Do not use dashboard session cookies on /api/v1.";
const TRY_IT_TIP =
"In RapiDoc: open Authorize (/docs#auth), paste Bearer dk_… (or X-API-Key), then expand an operation and use TRY. Prefer the server that matches your environment.";
export const DOCS_GUIDE_TREE: DocsGuideTree = {
version: 2,
disclaimer:
"This is a guided router for the public API docs — not a chat bot and not an AI. Pick options to land on the right endpoints.",
rootId: "root",
escapeLinks: [
{ label: "Browse API reference", href: "/docs#overview", kind: "docs" },
{ label: "OpenAPI YAML", href: "/api/v1/openapi.yaml", kind: "openapi" },
{ label: "Contact support", href: "/support/new", kind: "support" }
],
nodes: {
root: {
kind: "question",
id: "root",
pathKey: "start",
title: "What are you trying to do?",
body: "I’ll route you to the right Descrybe public API docs (/api/v1). Pick one option — no free-text needed.",
choices: [
{
id: "first",
label: "First API call / Try-it",
description: "API key, Authorize, health, Try",
nextId: "answer.first-win"
},
{
id: "specific",
label: "Something specific",
description: "Feeds, process, export, catalog…",
nextId: "q.intent"
},
{
id: "stuck",
label: "Error / stuck",
description: "401, 429, empty catalog, wrong process API",
nextId: "q.troubleshoot"
}
]
},
"q.intent": {
kind: "question",
id: "q.intent",
pathKey: "intent",
title: "Which job?",
body: "Think in pipeline steps, not resource names.",
choices: [
{
id: "pipeline",
label: "Feeds → process → export",
description: "Ingest, enrich, or outbound feeds",
nextId: "q.pipeline"
},
{
id: "catalog",
label: "Catalog & taxonomy",
description: "Categories, attributes, products",
nextId: "q.catalog"
},
{
id: "other",
label: "Marketing or billing",
description: "Calendar / campaigns, plan limits",
nextId: "q.other"
}
]
},
"q.pipeline": {
kind: "question",
id: "q.pipeline",
pathKey: "pipeline",
title: "Where in the pipeline?",
choices: [
{
id: "feeds",
label: "Connect or sync a feed",
description: "Create, map, sync, sample",
nextId: "q.feeds"
},
{
id: "process",
label: "Process / enrich products",
description: "Two contracts — choose carefully",
nextId: "q.process"
},
{
id: "export",
label: "Export a channel feed",
description: "Templates, generate, selected SKUs",
nextId: "q.export"
}
]
},
"q.feeds": {
kind: "question",
id: "q.feeds",
pathKey: "feeds",
synonyms: ["supplier feed", "import csv", "sync feed"],
title: "Feeds — what do you need?",
choices: [
{
id: "create",
label: "Create or manage a feed",
nextId: "answer.feeds.crud"
},
{
id: "map",
label: "Map fields / extract schema",
nextId: "answer.feeds.mapping"
},
{
id: "sync",
label: "Sync or sample-process",
nextId: "answer.feeds.sync"
}
]
},
"q.process": {
kind: "question",
id: "q.process",
pathKey: "process",
synonyms: ["enrich", "generate descriptions", "ai process"],
title: "Which processing contract?",
body: "Do not mix bodies or response envelopes between these two surfaces.",
choices: [
{
id: "legacy",
label: "Legacy EAN batch",
description: "POST /products/process · { data: { process_id } }",
nextId: "answer.process.legacy"
},
{
id: "jobs",
label: "Dashboard-style jobs",
description: "POST /process · flat JSON · 202 Accepted",
nextId: "answer.process.jobs"
},
{
id: "chooser",
label: "Not sure — compare both",
nextId: "answer.process.chooser"
}
]
},
"q.export": {
kind: "question",
id: "q.export",
pathKey: "export",
synonyms: ["channel feed", "google shopping", "export csv"],
title: "Export feeds — what do you need?",
choices: [
{
id: "setup",
label: "Create / template",
nextId: "answer.export.setup"
},
{
id: "generate",
label: "Generate full export",
nextId: "answer.export.generate"
},
{
id: "selected",
label: "Export selected products",
nextId: "answer.export.selected"
}
]
},
"q.catalog": {
kind: "question",
id: "q.catalog",
pathKey: "catalog",
title: "Catalog work",
choices: [
{
id: "taxonomy",
label: "Categories & attributes",
nextId: "answer.taxonomy"
},
{
id: "products",
label: "Read or update products",
nextId: "answer.products"
},
{
id: "quality",
label: "Quality scores / reset",
nextId: "answer.products.quality"
}
]
},
"q.other": {
kind: "question",
id: "q.other",
pathKey: "other",
title: "Marketing, account, or Try-it",
choices: [
{
id: "marketing",
label: "Marketing calendar / campaigns",
nextId: "answer.marketing"
},
{
id: "billing",
label: "Billing / plan limits",
nextId: "answer.billing"
},
{
id: "tryit",
label: "Authorize & Try-it in docs",
nextId: "answer.tryit"
}
]
},
"q.troubleshoot": {
kind: "question",
id: "q.troubleshoot",
pathKey: "troubleshoot",
synonyms: ["error", "unauthorized", "failed", "empty"],
title: "What’s going wrong?",
choices: [
{
id: "auth",
label: "401 Unauthorized",
nextId: "answer.error.401"
},
{
id: "rate",
label: "429 rate limit",
nextId: "answer.error.429"
},
{
id: "data",
label: "Jobs stuck or empty products",
nextId: "q.troubleshoot.data"
}
]
},
"q.troubleshoot.data": {
kind: "question",
id: "q.troubleshoot.data",
pathKey: "troubleshoot.data",
title: "Data / job symptoms",
choices: [
{
id: "job",
label: "Process job pending or failed",
nextId: "answer.error.job"
},
{
id: "empty",
label: "Empty catalog after sync",
nextId: "answer.error.empty"
},
{
id: "wrong",
label: "Wrong process endpoint?",
nextId: "answer.process.chooser"
}
]
},
/* ——— Answers ——— */
"answer.first-win": {
kind: "answer",
id: "answer.first-win",
pathKey: "auth.first",
synonyms: ["api key", "authenticate", "health", "openapi", "bearer", "dk_", "try it", "try-it", "authorize"],
title: "First successful API call",
outcome: "Create a dk_ key, Authorize in RapiDoc, Try GET /health or /products.",
body: "Public surface is API-key only under /api/v1. Health and OpenAPI are unauthenticated; everything else needs a key. Dashboard JSON under /api/* (cookies + CSRF) is a separate surface. In the docs viewer: 1) Create a key in Settings → API keys. 2) Open Authorize and paste Bearer dk_… (or X-API-Key). 3) Expand an operation and click TRY.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("GET", "/health", "Liveness (also /healthz and /readyz on the API host)"),
endpoint("GET", "/openapi.yaml", "This OpenAPI document"),
endpoint("GET", "/products", "List products (legacy { data, meta } envelope)")
],
links: [
{ label: "Settings → API keys", href: "/settings?tab=api-keys", kind: "app" },
{ label: "Authorize (Try-it)", href: docsAuthHref(), kind: "docs" },
{ label: "Auth overview", href: docsOverviewHref("authenticate"), kind: "docs" },
{ label: "Try GET /products", href: docsOperationHref("GET", "/products"), kind: "docs" },
{ label: "OpenAPI YAML", href: "/api/v1/openapi.yaml", kind: "openapi" }
],
tip: TRY_IT_TIP,
relatedIds: ["answer.tryit", "answer.feeds.crud", "answer.process.chooser"]
},
"answer.tryit": {
kind: "answer",
id: "answer.tryit",
pathKey: "auth.tryit",
synonyms: ["try it", "try-it", "authorize", "rapidoc auth", "test in browser"],
title: "Authorize and Try-it in the docs",
outcome: "Unlock RapiDoc TRY for authenticated /api/v1 operations.",
body: "1) Create or copy a company API key (dk_…). 2) Jump to Authorize and enter Authorization: Bearer dk_… (preferred) or X-API-Key. 3) Confirm the server URL matches your environment. 4) Open any operation below, fill params/body from the examples, and click TRY. Unauthenticated smoke: GET /health. Authenticated smoke: GET /products.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("GET", "/health", "No key required — confirm the viewer reaches the API"),
endpoint("GET", "/products", "Authenticated smoke list (page=1&limit=1)"),
endpoint("POST", "/products/process", "Legacy process — after Authorize"),
endpoint("POST", "/process", "Jobs process — after Authorize")
],
links: [
{ label: "Authorize panel", href: docsAuthHref(), kind: "docs" },
{ label: "Overview → Authenticate", href: docsOverviewHref("authenticate"), kind: "docs" },
{ label: "Overview → Quick curl", href: docsOverviewHref("quick-curl"), kind: "docs" },
{ label: "Settings → API keys", href: "/settings?tab=api-keys", kind: "app" },
{ label: "Contact support", href: "/support/new", kind: "support" }
],
tip: TRY_IT_TIP,
relatedIds: ["answer.first-win", "answer.error.401", "answer.process.chooser"]
},
"answer.feeds.crud": {
kind: "answer",
id: "answer.feeds.crud",
pathKey: "feeds.crud",
synonyms: ["create feed", "list feeds", "delete feed"],
title: "Create and manage input feeds",
outcome: "Register a supplier CSV/XML/URL feed for your company.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("GET", "/feeds", "List input feeds"),
endpoint("POST", "/feeds", "Create feed"),
endpoint("GET", "/feeds/{id}", "Get feed"),
endpoint("PATCH", "/feeds/{id}", "Update feed"),
endpoint("DELETE", "/feeds/{id}", "Delete feed")
],
links: [
{ label: "Feeds UI", href: "/feeds", kind: "app" },
{ label: "Feeds in docs", href: docsTagHref("Feeds"), kind: "docs" },
{ label: "Try GET /feeds", href: docsOperationHref("GET", "/feeds"), kind: "docs" },
{ label: "Authorize", href: docsAuthHref(), kind: "docs" },
{ label: "Stores hub", href: "/stores", kind: "app" }
],
warning: "Avoid deleting live feeds unless you intend to remove sync history for that source.",
relatedIds: ["answer.feeds.mapping", "answer.feeds.sync"]
},
"answer.feeds.mapping": {
kind: "answer",
id: "answer.feeds.mapping",
pathKey: "feeds.mapping",
synonyms: ["field mapping", "extract schema", "map columns"],
title: "Map feed fields and extract schema",
outcome: "Discover sample paths, then PUT mappings before a meaningful sync.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("POST", "/feeds/{id}/extract-schema", "Extract schema sample paths and preview"),
endpoint("GET", "/feeds/{id}/mappings", "Get feed mappings"),
endpoint("PUT", "/feeds/{id}/mappings", "Put feed mappings")
],
links: [
{ label: "Feeds UI", href: "/feeds", kind: "app" },
{ label: "Standard fields", href: "/standard-fields", kind: "app" },
{
label: "Extract schema in docs",
href: docsOperationHref("POST", "/feeds/{id}/extract-schema"),
kind: "docs"
},
{ label: "Authorize", href: docsAuthHref(), kind: "docs" }
],
tip: "Enable recommended standard fields in the UI before fine-tuning mappings.",
relatedIds: ["answer.feeds.sync", "answer.taxonomy"]
},
"answer.feeds.sync": {
kind: "answer",
id: "answer.feeds.sync",
pathKey: "feeds.sync",
synonyms: ["pull feed", "refresh import", "sync-process-sample"],
title: "Sync a feed (and optional sample process)",
outcome: "Pull supplier rows into the company catalog; optionally process a sample.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("POST", "/feeds/{id}/sync", "Trigger feed sync"),
endpoint("POST", "/feeds/{id}/sync-process-sample", "Sync then process a sample of raw products"),
endpoint("GET", "/products", "List products after sync")
],
links: [
{ label: "Sync in docs", href: docsOperationHref("POST", "/feeds/{id}/sync"), kind: "docs" },
{ label: "Authorize", href: docsAuthHref(), kind: "docs" },
{ label: "Feeds UI", href: "/feeds", kind: "app" }
],
tip: "Heavy mutations are rate-limited per company (HTTP 429: rate limit exceeded).",
relatedIds: ["answer.process.legacy", "answer.process.jobs", "answer.error.empty"]
},
"answer.process.legacy": {
kind: "answer",
id: "answer.process.legacy",
pathKey: "process.legacy",
synonyms: ["ean", "items[].ean", "products/process"],
title: "Legacy public process (EAN batch)",
outcome: "Start and poll enrichment using the legacy Descrybe contract.",
body: "POST body uses items[].ean (preferred). Handler also accepts raw_product_ids as an alternate on this same path. Responses use HTTP 200 with { data: { process_id, … } } and completed items[] when done.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("POST", "/products/process", "Start processing by EAN (legacy public contract)"),
endpoint("GET", "/products/process/{id}", "Processing job status by process_id")
],
links: [
{ label: "Legacy start in docs", href: docsOperationHref("POST", "/products/process"), kind: "docs" },
{
label: "Legacy status in docs",
href: docsOperationHref("GET", "/products/process/{id}"),
kind: "docs"
},
{ label: "Authorize & Try", href: docsAuthHref(), kind: "docs" },
{ label: "Processing UI", href: "/processing", kind: "app" }
],
warning: "Not an alias of POST/GET /process — different body and envelope.",
relatedIds: ["answer.process.jobs", "answer.process.chooser", "answer.products"]
},
"answer.process.jobs": {
kind: "answer",
id: "answer.process.jobs",
pathKey: "process.jobs",
synonyms: ["raw_product_ids", "cancel job", "retry job"],
title: "Dashboard-style processing jobs",
outcome: "Start flat JSON jobs by raw_product_ids; poll, cancel, or retry.",
body: "Same body shape as dashboard POST /api/processing/jobs. Start/retry return 202 Accepted with flat JSON (no data wrapper). Prefer /products/process for legacy integrations.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("POST", "/process", "Start processing job by raw_product_ids"),
endpoint("GET", "/process", "List processing jobs"),
endpoint("GET", "/process/{id}", "Processing job status"),
endpoint("POST", "/process/{id}/cancel", "Cancel processing job"),
endpoint("POST", "/process/{id}/terminate", "Terminate (alias of cancel)"),
endpoint("POST", "/process/{id}/retry", "Retry a failed or cancelled job")
],
links: [
{ label: "Start job in docs", href: docsOperationHref("POST", "/process"), kind: "docs" },
{ label: "Processing tag", href: docsTagHref("Processing"), kind: "docs" },
{ label: "Authorize & Try", href: docsAuthHref(), kind: "docs" },
{ label: "Processing UI", href: "/processing", kind: "app" }
],
relatedIds: ["answer.process.legacy", "answer.error.job"]
},
"answer.process.chooser": {
kind: "answer",
id: "answer.process.chooser",
pathKey: "process.which",
synonyms: ["which process", "dual contract"],
title: "Which process API should I use?",
outcome: "Pick legacy EAN for integrations; pick /process for dashboard-style jobs.",
body: "1) Legacy public: POST/GET /products/process — items[].ean, HTTP 200 { data: { process_id } }. 2) Jobs: POST/GET /process — raw_product_ids, flat JSON, 202 on start. Mixing envelopes is the most common integration bug.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("POST", "/products/process", "Legacy EAN batch"),
endpoint("POST", "/process", "Dashboard-style jobs")
],
links: [
{ label: "Legacy process", href: docsOperationHref("POST", "/products/process"), kind: "docs" },
{ label: "Jobs process", href: docsOperationHref("POST", "/process"), kind: "docs" },
{
label: "Dual-mode overview",
href: docsOverviewHref("processing-contracts-dual-mode"),
kind: "docs"
},
{ label: "Authorize", href: docsAuthHref(), kind: "docs" }
],
relatedIds: ["answer.process.legacy", "answer.process.jobs"]
},
"answer.export.setup": {
kind: "answer",
id: "answer.export.setup",
pathKey: "export.setup",
synonyms: ["export template", "create export feed"],
title: "Create an export feed and template",
outcome: "Define an outbound channel feed and its template before generating files.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("GET", "/export-feeds", "List export feeds"),
endpoint("POST", "/export-feeds", "Create export feed"),
endpoint("GET", "/export-feeds/{id}", "Get export feed"),
endpoint("PATCH", "/export-feeds/{id}", "Update export feed"),
endpoint("PUT", "/export-feeds/{id}/template", "Update export feed template"),
endpoint("DELETE", "/export-feeds/{id}", "Delete export feed")
],
links: [
{ label: "Export feeds UI", href: "/export-feeds", kind: "app" },
{ label: "Export feeds tag", href: docsTagHref("Export feeds"), kind: "docs" },
{ label: "Try GET /export-feeds", href: docsOperationHref("GET", "/export-feeds"), kind: "docs" },
{ label: "Authorize", href: docsAuthHref(), kind: "docs" }
],
tip: "Input /feeds (ingest) ≠ /export-feeds (outbound).",
relatedIds: ["answer.export.generate", "answer.export.selected"]
},
"answer.export.generate": {
kind: "answer",
id: "answer.export.generate",
pathKey: "export.generate",
synonyms: ["generate export", "build channel file"],
title: "Generate a full export feed file",
outcome: "Render the configured template into a downloadable/exportable feed file.",
authNote: AUTH_NOTE,
endpoints: [endpoint("POST", "/export-feeds/{id}/generate", "Generate export feed file")],
links: [
{
label: "Generate in docs",
href: docsOperationHref("POST", "/export-feeds/{id}/generate"),
kind: "docs"
},
{ label: "Authorize & Try", href: docsAuthHref(), kind: "docs" },
{ label: "Export feeds UI", href: "/export-feeds", kind: "app" }
],
tip: "Generate is rate-limited with other heavy /api/v1 mutations.",
relatedIds: ["answer.export.setup", "answer.export.selected"]
},
"answer.export.selected": {
kind: "answer",
id: "answer.export.selected",
pathKey: "export.selected",
synonyms: ["export selected", "export products"],
title: "Export selected processed products",
outcome: "Push a chosen product set through an export feed without a full regenerate.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("POST", "/export-feeds/{id}/export-products", "Export selected processed products")
],
links: [
{
label: "Export selected in docs",
href: docsOperationHref("POST", "/export-feeds/{id}/export-products"),
kind: "docs"
},
{ label: "Authorize & Try", href: docsAuthHref(), kind: "docs" },
{ label: "Products UI", href: "/products", kind: "app" }
],
relatedIds: ["answer.export.generate", "answer.products"]
},
"answer.taxonomy": {
kind: "answer",
id: "answer.taxonomy",
pathKey: "taxonomy",
synonyms: ["categories", "attributes", "taxonomy"],
title: "Categories and attributes",
outcome: "Organize the catalog and define structured attributes used in descriptions.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("GET", "/categories", "List categories"),
endpoint("POST", "/categories", "Create category"),
endpoint("POST", "/categories/create", "Create category (legacy alias)"),
endpoint("GET", "/categories/{id}", "Get category by UUID"),
endpoint("PATCH", "/categories/{id}", "Update category"),
endpoint("DELETE", "/categories/{id}", "Delete category by unique_id"),
endpoint("GET", "/attributes", "List attributes"),
endpoint("POST", "/attributes", "Create attribute"),
endpoint("POST", "/attributes/create", "Create attribute (legacy alias)"),
endpoint("PATCH", "/attributes/{id}", "Update attribute"),
endpoint("DELETE", "/attributes/{id}", "Delete attribute")
],
links: [
{ label: "Categories UI", href: "/categories", kind: "app" },
{ label: "Attributes UI", href: "/attributes", kind: "app" },
{ label: "Categories tag", href: docsTagHref("Categories"), kind: "docs" },
{ label: "Attributes tag", href: docsTagHref("Attributes"), kind: "docs" },
{ label: "Authorize", href: docsAuthHref(), kind: "docs" }
],
tip: "Prefer canonical POST /categories and POST /attributes; /create aliases exist for legacy clients.",
relatedIds: ["answer.feeds.mapping", "answer.products"]
},
"answer.products": {
kind: "answer",
id: "answer.products",
pathKey: "products",
synonyms: ["list products", "get product", "patch product"],
title: "Read or update products",
outcome: "List the processed catalog, fetch one product, or patch fields.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("GET", "/products", "List products"),
endpoint("GET", "/products/{id}", "Get processed product"),
endpoint("PATCH", "/products/{id}", "Update processed product")
],
links: [
{ label: "Products UI", href: "/products", kind: "app" },
{ label: "Products tag", href: docsTagHref("Products"), kind: "docs" },
{ label: "Try GET /products", href: docsOperationHref("GET", "/products"), kind: "docs" },
{ label: "Authorize", href: docsAuthHref(), kind: "docs" }
],
tip: "List uses legacy query params: page, limit, status, search, sortBy, sortOrder, feedId.",
relatedIds: ["answer.products.quality", "answer.process.legacy"]
},
"answer.products.quality": {
kind: "answer",
id: "answer.products.quality",
pathKey: "products.quality",
synonyms: ["quality score", "reset products"],
title: "Product quality and reset",
outcome: "Inspect quality scores or reset products back to unprocessed.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("GET", "/products/quality", "List product quality scores"),
endpoint("POST", "/products/reset", "Reset products to unprocessed")
],
links: [
{ label: "Quality in docs", href: docsOperationHref("GET", "/products/quality"), kind: "docs" },
{ label: "Reset in docs", href: docsOperationHref("POST", "/products/reset"), kind: "docs" },
{ label: "Authorize", href: docsAuthHref(), kind: "docs" },
{ label: "Products UI", href: "/products", kind: "app" }
],
warning: "Reset is destructive to processed state — confirm before calling in production.",
relatedIds: ["answer.products", "answer.process.jobs"]
},
"answer.marketing": {
kind: "answer",
id: "answer.marketing",
pathKey: "marketing",
synonyms: ["campaigns", "calendar", "seasonal"],
title: "Marketing calendar (API)",
outcome: "List seasonal presets and prepare a calendar export via the public API.",
body: "Public /api/v1/marketing/calendar* (and legacy /campaigns aliases) are API-key routes for the content calendar. They are separate from session email campaigns under /api/campaigns in the dashboard UI.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("GET", "/marketing/calendar", "List seasonal campaign presets"),
endpoint("POST", "/marketing/calendar/prepare", "Prepare seasonal campaign export"),
endpoint("GET", "/campaigns", "List presets (legacy alias)"),
endpoint("POST", "/campaigns/prepare", "Prepare export (legacy alias)")
],
links: [
{
label: "Calendar in docs",
href: docsOperationHref("GET", "/marketing/calendar"),
kind: "docs"
},
{ label: "Campaigns tag", href: docsTagHref("Campaigns"), kind: "docs" },
{ label: "Authorize", href: docsAuthHref(), kind: "docs" },
{ label: "Campaigns UI", href: "/campaigns", kind: "app" },
{ label: "Marketing UI", href: "/marketing", kind: "app" }
],
relatedIds: ["answer.export.generate"]
},
"answer.billing": {
kind: "answer",
id: "answer.billing",
pathKey: "billing",
synonyms: ["credits", "plan", "upgrade", "limits"],
title: "Billing and plan limits",
outcome: "Plan and credit limits are enforced server-side on processing — manage them in the app, not via /api/v1.",
body: "The public API-key surface does not expose checkout. Use Plans / Billing in the web app. Insufficient credits or free-tier gates typically surface as processing failures rather than OpenAPI operations.",
links: [
{ label: "Plans", href: "/plans", kind: "app" },
{ label: "Billing", href: "/billing", kind: "app" },
{ label: "Settings", href: "/settings", kind: "app" },
{ label: "Contact support", href: "/support/new", kind: "support" }
],
tip: "After upgrading, retry the same process endpoint you already chose (legacy vs jobs).",
relatedIds: ["answer.error.job", "answer.process.chooser"]
},
"answer.error.401": {
kind: "answer",
id: "answer.error.401",
pathKey: "error.401",
synonyms: ["unauthorized", "invalid key", "missing key"],
title: "Fix 401 Unauthorized",
outcome: "Send a valid company API key on every authenticated /api/v1 call.",
body: 'Missing or invalid keys return HTTP 401 with { "error": { "code": "unauthorized", "message": "Unauthorized" } }. Session cookies and CSRF tokens are for /api dashboard routes only.',
authNote: AUTH_NOTE,
endpoints: [
endpoint("GET", "/health", "Unauthenticated liveness check"),
endpoint("GET", "/products", "Authenticated smoke list")
],
links: [
{ label: "Create API key", href: "/settings?tab=api-keys", kind: "app" },
{ label: "Authorize panel", href: docsAuthHref(), kind: "docs" },
{ label: "Auth overview", href: docsOverviewHref("authenticate"), kind: "docs" },
{ label: "Contact support", href: "/support/new", kind: "support" }
],
tip: "Bearer is preferred when both Authorization and X-API-Key are set.",
relatedIds: ["answer.first-win", "answer.error.429"]
},
"answer.error.429": {
kind: "answer",
id: "answer.error.429",
pathKey: "error.429",
synonyms: ["rate limit", "too many requests"],
title: "Fix 429 rate limit exceeded",
outcome: "Back off and retry; heavy process / feed sync / export mutations are throttled per company.",
body: "RateLimitV1Process guards authenticated /api/v1 mutations (in-process per API replica). Message: rate limit exceeded. Space out sync, process, generate, and export-products calls; prefer listing/GETs while waiting.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("POST", "/feeds/{id}/sync", "Sync (rate-limited)"),
endpoint("POST", "/products/process", "Legacy process (rate-limited)"),
endpoint("POST", "/process", "Jobs process (rate-limited)"),
endpoint("POST", "/export-feeds/{id}/generate", "Generate export (rate-limited)")
],
links: [
{ label: "Browse Health tag", href: docsTagHref("Health"), kind: "docs" },
{ label: "Authorize", href: docsAuthHref(), kind: "docs" },
{ label: "Contact support", href: "/support/new", kind: "support" }
],
relatedIds: ["answer.error.job", "answer.billing"]
},
"answer.error.job": {
kind: "answer",
id: "answer.error.job",
pathKey: "error.job",
synonyms: ["job failed", "pending", "cancel", "retry"],
title: "Process job pending or failed",
outcome: "Poll the matching status endpoint; cancel/retry only on the /process job surface.",
body: "Legacy: GET /products/process/{id} (data envelope). Jobs: GET /process/{id} plus POST …/cancel|terminate|retry. Confirm you started the job on the same contract you are polling.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("GET", "/products/process/{id}", "Legacy poll"),
endpoint("GET", "/process/{id}", "Jobs poll"),
endpoint("POST", "/process/{id}/retry", "Retry failed/cancelled job")
],
links: [
{ label: "Processing UI", href: "/processing", kind: "app" },
{
label: "Compare process APIs",
href: docsOverviewHref("processing-contracts-dual-mode"),
kind: "docs"
},
{ label: "Authorize", href: docsAuthHref(), kind: "docs" },
{ label: "Contact support", href: "/support/new", kind: "support" }
],
relatedIds: ["answer.process.chooser", "answer.billing", "answer.error.429"]
},
"answer.error.empty": {
kind: "answer",
id: "answer.error.empty",
pathKey: "error.empty",
synonyms: ["no products", "empty after sync", "zero products"],
title: "Empty catalog after sync",
outcome: "Verify mappings and sync status, then list products again.",
body: "Typical causes: feed not mapped, sync not finished, wrong company API key, or products still raw/unprocessed. Extract schema → PUT mappings → POST sync → GET /products. For enrichment, call the correct process contract next.",
authNote: AUTH_NOTE,
endpoints: [
endpoint("GET", "/feeds/{id}", "Get feed status"),
endpoint("GET", "/feeds/{id}/mappings", "Confirm mappings exist"),
endpoint("POST", "/feeds/{id}/sync", "Re-trigger sync"),
endpoint("GET", "/products", "List products")
],
links: [
{ label: "Feeds UI", href: "/feeds", kind: "app" },
{
label: "Mapping docs",
href: docsOperationHref("PUT", "/feeds/{id}/mappings"),
kind: "docs"
},
{ label: "Authorize", href: docsAuthHref(), kind: "docs" },
{ label: "Contact support", href: "/support/new", kind: "support" }
],
relatedIds: ["answer.feeds.mapping", "answer.feeds.sync", "answer.process.chooser"]
}
}
};
/** Throws if the tree is structurally invalid (import-time safety for UI/tests). */
export function assertDocsGuideTree(tree: DocsGuideTree = DOCS_GUIDE_TREE): void {
const errors = validateDocsGuideTree(tree);
if (errors.length > 0) {
throw new Error(`docs-guide tree invalid:\n- ${errors.join("\n- ")}`);
}
}
assertDocsGuideTree(DOCS_GUIDE_TREE);
+87
View File
@@ -0,0 +1,87 @@
/**
* No-LLM docs Ask decision tree — content contract for the /docs UI.
* UI renders questions as chip choices and answers as resolution cards.
* Never call an LLM from this module or its consumers for Ask routing.
*
* Future: admin AI roles `docs_api` / `support` are config slots only; keep
* Ask rule-based. Do not wire ticket LLM auto-reply through this tree.
*/
export type DocsGuideHttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
/** Deep-link kinds the Ask panel can render. */
export type DocsGuideLinkKind = "docs" | "app" | "openapi" | "support";
export type DocsGuideLink = {
label: string;
/**
* App route (`/settings?tab=api-keys`), docs hash (`/docs#get-/products`),
* or OpenAPI URL (`/api/v1/openapi.yaml`). When kind is `support`,
* omit to default to `/support/new`.
*/
href?: string;
kind: DocsGuideLinkKind;
};
export type DocsGuideEndpoint = {
method: DocsGuideHttpMethod;
/** Full public path including `/api/v1` prefix for display/copy. */
path: string;
summary?: string;
/** RapiDoc hash on `/docs`, e.g. `/docs#post-/feeds/-id-/sync` (braces → `-`). */
href: string;
};
export type DocsGuideChoice = {
id: string;
label: string;
description?: string;
/** Next node id (question or answer). */
nextId: string;
};
type DocsGuideNodeBase = {
id: string;
/**
* Stable slug for shareable URLs (`?ask=path=feeds.sync`).
* Prefer dotted job ids over resource names.
*/
pathKey?: string;
/** Optional keyword synonyms for non-LLM chip preselection (UI may ignore). */
synonyms?: string[];
};
export type DocsGuideQuestionNode = DocsGuideNodeBase & {
kind: "question";
title: string;
body?: string;
/** Keep 2–3 choices for completion rate. */
choices: DocsGuideChoice[];
};
export type DocsGuideAnswerNode = DocsGuideNodeBase & {
kind: "answer";
title: string;
/** One-line success outcome (what the user can do next). */
outcome: string;
body?: string;
authNote?: string;
endpoints?: DocsGuideEndpoint[];
links?: DocsGuideLink[];
tip?: string;
warning?: string;
/** Related answer node ids for “Try related”. */
relatedIds?: string[];
};
export type DocsGuideNode = DocsGuideQuestionNode | DocsGuideAnswerNode;
export type DocsGuideTree = {
version: number;
/** Disclose that Ask is a guide, not a person/LLM. */
disclaimer: string;
rootId: string;
nodes: Record<string, DocsGuideNode>;
/** Persistent footer actions shown on every step. */
escapeLinks: DocsGuideLink[];
};