It shipped 1.77 MB of vendored assets to every site - swagger-ui-bundle.min.js
alone is larger than Redoc - in order to provide an Execute button that only the
development config ever enabled. Production config had it off, testing had it
off hard, and when off the routes were never bound at all. The staticdocs
directory drops from 2.9 MB to 1.1 MB, and there is one fewer vendored
dependency to track for licences and advisories.
What replaces it: an agent has the MCP server's shopdb_call, and a human has
Redoc for reading plus the 324 harvested examples in the spec for a curl that is
mostly copy-paste. The read-only page was always the one that mattered.
The tests this leaves behind are the interesting part. That file was named for
try-it but half of it proved things about the page that stays, above all that
nothing it loads comes from the internet, which is what a CDN reference costs on
an air-gapped box. Those are kept and the file is renamed for what it covers.
Pointing the air-gap test at redoc.standalone.js immediately failed: the bundle
still carried a trailing sourceMappingURL for a .map that was never vendored,
so every devtools open was a guaranteed 404 with no internet to fall back on.
That was visible in a browser console and nobody had chased it, because the test
had only ever been parametrised over the two Swagger files. The pragma is gone
and the assertion now checks the TRAILING pragma specifically: Redoc's own code
contains that string three more times, in a data: URI it assembles and in a
worker blob, and a blunt "not in body" assertion fails on correct code.
A first attempt to strip it with a line-anchored pattern removed 507 KB, because
the bundle is minified onto long lines. Hence the anchored, byte-exact removal
and the assertion that can tell a directive from source.
(cherry picked from commit 581baafee0)
364 lines
18 KiB
Python
364 lines
18 KiB
Python
"""Interactive API docs: self-hosted Redoc over the generated OpenAPI spec.
|
|
|
|
Served at /api/docs (relative to the mount). The Redoc bundle is vendored in
|
|
staticdocs/ so this works fully offline on the air-gapped prod box - no CDN.
|
|
The spec is docs/openapi.json in the repo (regenerate with
|
|
scripts/gen_openapi.py after API changes).
|
|
|
|
Two renderers over ONE spec. Redoc is read-only by design and is the default,
|
|
because what is published is a contract.
|
|
whole value and the whole reason it is off unless a site turns it on - see
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
|
|
from markupsafe import escape
|
|
|
|
from flask import Blueprint, Response, current_app, request, send_file, url_for
|
|
|
|
docs_bp = Blueprint('docs', __name__)
|
|
|
|
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
# shopdb/core/api -> repo root
|
|
_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(_HERE)))
|
|
_SPEC = os.path.join(_REPO_ROOT, 'docs', 'openapi.json')
|
|
_LLMS = os.path.join(_REPO_ROOT, 'docs', 'llms.txt')
|
|
_REDOC = os.path.join(_HERE, 'staticdocs', 'redoc.standalone.js')
|
|
|
|
|
|
|
|
@docs_bp.route('/', strict_slashes=False)
|
|
def docs_index():
|
|
"""Redoc page. url_for keeps the asset URLs correct under any mount."""
|
|
spec_url = url_for('docs.openapi_spec')
|
|
redoc_url = url_for('docs.redoc_js')
|
|
# DARK MODE. Redoc does not read prefers-color-scheme on its own, and
|
|
# the <redoc spec-url> element takes no theme - so the page goes through
|
|
# Redoc.init instead, which does. The app has a dark theme and this was
|
|
# the one page that stayed white when the rest of the site went dark.
|
|
#
|
|
# The page RE-INITIALISES when the OS scheme flips rather than restyling:
|
|
# Redoc bakes its colours into styled-components at init, so a CSS
|
|
# override reaches the chrome and misses the content.
|
|
page = (
|
|
'<!doctype html><html><head>'
|
|
'<title>ShopDB API</title>'
|
|
'<meta charset="utf-8">'
|
|
'<meta name="viewport" content="width=device-width, initial-scale=1">'
|
|
'<style>'
|
|
# color-scheme follows the SAME attribute Redoc is themed from, so the
|
|
# OS never paints dark scrollbars under a page the user set to light.
|
|
':root{color-scheme:light}'
|
|
':root[data-theme="dark"]{color-scheme:dark}'
|
|
'body{margin:0;padding:0;background:#fff}'
|
|
'.docs-note{font:14px/1.6 system-ui,-apple-system,Segoe UI,sans-serif;'
|
|
'margin:0;padding:10px 16px;background:#f5f5f5;color:#1a1a2e;'
|
|
'border-bottom:1px solid #dee2e6}'
|
|
'.docs-note a{color:#2d6ce0}'
|
|
# The ONLY Redoc elements with no theme key. Each is a colour hard-coded
|
|
# in the vendored bundle, so it cannot be reached from the theme object:
|
|
# h5 section headings ("query Parameters"),
|
|
# rgba(38,50,56,.5) - fails AA on light too
|
|
# td[colspan] > div nested schema tables at depth 2 are
|
|
# painted #ffffff whatever nestedBackground
|
|
# says, and the response envelopes nest 3
|
|
# deep, so it shows on every operation
|
|
# .react-tabs__tab--selected right-panel tab paints text.primary on
|
|
# rightPanel.textColor; both are light in
|
|
# dark mode, so the selected tab label
|
|
# vanished into its own background
|
|
# Selectors use Redoc's own DOM - tag, colspan attribute, react-tabs
|
|
# class - never generated class hashes, which change on every build.
|
|
'#redoc h5{color:#5c636a;border-bottom-color:#dee2e6}'
|
|
':root[data-theme="dark"] body{background:#0a0a1a}'
|
|
':root[data-theme="dark"] .docs-note{background:#0d0d2b;color:#e6e6e8;'
|
|
'border-bottom-color:rgba(65,129,255,0.2)}'
|
|
':root[data-theme="dark"] .docs-note a{color:#4181ff}'
|
|
':root[data-theme="dark"] #redoc h5{color:#9d9da3;'
|
|
'border-bottom-color:rgba(255,255,255,0.2)}'
|
|
':root[data-theme="dark"] #redoc td[colspan="2"]>div td[colspan="2"]>div'
|
|
'{background:#0a0a1a}'
|
|
':root[data-theme="dark"] #redoc td[colspan="2"]>div td[colspan="2"]>div '
|
|
'td[colspan="2"]>div{background:#0d0d2b}'
|
|
':root[data-theme="dark"] #redoc .react-tabs__tab--selected{color:#0a0a1a}'
|
|
# The content-type control is a native <select>. Redoc never styles it,
|
|
# so it keeps the OS default (black text, transparent background) and
|
|
# reads 1.07:1 on the dark right panel. Name both halves; the border
|
|
# keeps it looking like a control rather than stray text.
|
|
# The content-type label ("application/json") is a span INSIDE that
|
|
# same h5, carrying its own hard-coded black, so theming the h5 alone
|
|
# left it at 1.07:1 on the dark panel. Inherit rather than restate, so
|
|
# it tracks whatever the heading colour is.
|
|
'#redoc h5 span{color:inherit}'
|
|
# Redoc's footer badge links to redocly.com and its logo was replaced
|
|
# with a blank GIF so an air-gapped box stops reaching for a CDN, so
|
|
# what remains is a dead external link on a shop-floor kiosk. The MIT
|
|
# licence requires the notice be retained in the DISTRIBUTION, which
|
|
# staticdocs/redoc.standalone.js.LICENSE.txt covers; it does not
|
|
# require rendering a badge.
|
|
'#redoc a[href*="redocly.com"]{display:none}'
|
|
'</style></head><body>'
|
|
'<div id="redoc"></div>'
|
|
'<script src="%s"></script>'
|
|
'<script>'
|
|
'var SPEC = %s;'
|
|
# Product type: the app's body stack and its mono stack. Inter is
|
|
# bundled into the SPA under a hashed filename this standalone page
|
|
# cannot reference, so system-ui is the honest choice (Segoe UI on the
|
|
# Windows kiosks).
|
|
'var FONT="system-ui,-apple-system,Segoe UI,sans-serif";'
|
|
'var MONO="SF Mono,Monaco,Consolas,monospace";'
|
|
# The product chrome is the same navy with white text in BOTH themes,
|
|
# so one object serves both. Redoc deep-merges the theme into a fresh
|
|
# copy of its defaults and snapshots it, so sharing is safe.
|
|
'var SIDEBAR={backgroundColor:"#00003d",'
|
|
'textColor:"rgba(255,255,255,0.85)",activeTextColor:"#ffffff",'
|
|
'groupItems:{activeBackgroundColor:"rgba(255,255,255,0.1)"},'
|
|
'level1Items:{activeBackgroundColor:"rgba(255,255,255,0.1)"},'
|
|
'arrow:{color:"rgba(255,255,255,0.85)"}};'
|
|
# Light. The middle column is the product CARD white. primary is
|
|
# --primary-dark rather than --primary, because --primary is 3.6:1 on
|
|
# white and fails AA; success and error are a shade darker than the
|
|
# product tokens for the same reason - those tokens are designed as
|
|
# fills, not as text on the nested panels where type names and required
|
|
# labels live. tabTextColor is pinned because the response tabs sit on
|
|
# the DARK code block in both themes, and Redoc would otherwise derive
|
|
# them from the light middle-panel colours.
|
|
'var LIGHT={colors:{primary:{main:"#2d6ce0",light:"#2d6ce0"},'
|
|
'success:{main:"#0b7a3b"},'
|
|
'warning:{main:"#ff9500",contrastText:"#1a1a2e"},'
|
|
'error:{main:"#c1273a"},'
|
|
'text:{primary:"#1a1a2e",secondary:"#5c636a"},'
|
|
'border:{dark:"#dee2e6"},'
|
|
'gray:{50:"#f5f5f5",100:"#f5f5f5"},'
|
|
# tabTextColor is deliberately NOT pinned here. It was, on the
|
|
# assumption that these tabs sit on the dark code block in both
|
|
# themes; measuring the rendered page showed the light-theme tab list
|
|
# on the white panel, where the bright green read 1.95:1. Unset, Redoc
|
|
# derives it from success.main, which is chosen to pass on white.
|
|
'responses:{}},'
|
|
'schema:{nestedBackground:"#f5f5f5"},'
|
|
'typography:{fontSize:"15px",lineHeight:"1.6em",fontFamily:FONT,'
|
|
'fontWeightBold:"600",headings:{fontFamily:FONT,fontWeight:"600"},'
|
|
'code:{fontFamily:MONO,color:"#1a1a2e",'
|
|
'backgroundColor:"rgba(26,26,46,0.06)"},'
|
|
'links:{hover:"#4181ff"}},'
|
|
'sidebar:SIDEBAR,'
|
|
'rightPanel:{backgroundColor:"#00003d",textColor:"#ffffff",'
|
|
'servers:{overlay:{backgroundColor:"#f5f5f5",textColor:"#1a1a2e"},'
|
|
'url:{backgroundColor:"#ffffff"}}},'
|
|
'codeBlock:{backgroundColor:"#0a0a1a"}};'
|
|
# Dark. Product tokens verbatim, with the two alpha text tokens
|
|
# flattened onto the page background so Redoc's own lighten and
|
|
# transparentize derivations stay predictable. The response accordion
|
|
# tints are named because Redoc derives a 7% tint that is invisible on
|
|
# a near-black page.
|
|
'var DARK={colors:{primary:{main:"#4181ff"},'
|
|
'success:{main:"#0ad64f"},'
|
|
'warning:{main:"#ff9500",contrastText:"#1a1a2e"},'
|
|
'error:{main:"#f5365c"},'
|
|
'text:{primary:"#e6e6e8",secondary:"#9d9da3"},'
|
|
'border:{dark:"rgba(65,129,255,0.2)"},'
|
|
'gray:{50:"#0d0d2b",100:"#0d0d2b"},'
|
|
'responses:{success:{backgroundColor:"rgba(10,214,79,0.12)"},'
|
|
'error:{backgroundColor:"rgba(245,54,92,0.12)"}}},'
|
|
'schema:{nestedBackground:"#0d0d2b"},'
|
|
'typography:{fontSize:"15px",lineHeight:"1.6em",fontFamily:FONT,'
|
|
'fontWeightBold:"600",headings:{fontFamily:FONT,fontWeight:"600"},'
|
|
'code:{fontFamily:MONO,color:"#e6e6e8",'
|
|
'backgroundColor:"rgba(255,255,255,0.08)"},'
|
|
'links:{hover:"#7aa8ff"}},'
|
|
'sidebar:SIDEBAR,'
|
|
'rightPanel:{backgroundColor:"#00003d",textColor:"#ffffff",'
|
|
'servers:{overlay:{backgroundColor:"#0d0d2b",textColor:"#e6e6e8"},'
|
|
'url:{backgroundColor:"#0a0a1a"}}},'
|
|
'codeBlock:{backgroundColor:"#0a0a1a"}};'
|
|
# THEME SOURCE. The app stores an explicit choice under this key and
|
|
# stamps <html data-theme>. This page is served from the same origin,
|
|
# so it reads the same key rather than guessing from the OS - picking
|
|
# light in the app on a dark-OS kiosk used to give a dark docs page.
|
|
# The OS scheme is only the fallback, exactly as in the app's store.
|
|
# localStorage can throw outright on a locked-down kiosk browser.
|
|
'var KEY="shopdb-theme";'
|
|
'var q=window.matchMedia("(prefers-color-scheme: dark)");'
|
|
'var el=document.getElementById("redoc");'
|
|
'function pick(){var t=null;'
|
|
'try{t=window.localStorage.getItem(KEY);}catch(e){}'
|
|
'if(t!=="dark"&&t!=="light"){t=q.matches?"dark":"light";}'
|
|
'return t;}'
|
|
# Re-initialise rather than restyle: Redoc bakes colours into
|
|
# styled-components at init. data-theme is stamped first so the CSS
|
|
# above and the Redoc theme can never disagree about which one is live.
|
|
'function draw(){var t=pick();'
|
|
'document.documentElement.setAttribute("data-theme",t);'
|
|
'el.innerHTML="";'
|
|
'Redoc.init(SPEC,{theme:t==="dark"?DARK:LIGHT},el);}'
|
|
'draw();'
|
|
# addEventListener is missing from MediaQueryList in older WebViews,
|
|
# and a shop-floor kiosk browser is exactly where this gets read.
|
|
'if(q.addEventListener){q.addEventListener("change",draw);}'
|
|
'else if(q.addListener){q.addListener(draw);}'
|
|
# Fires in THIS tab when the app in another tab toggles the theme.
|
|
'window.addEventListener("storage",function(e){'
|
|
'if(e.key===KEY){draw();}});'
|
|
'</script>'
|
|
'</body></html>' % (redoc_url, json.dumps(spec_url))
|
|
)
|
|
return Response(page, mimetype='text/html')
|
|
|
|
|
|
_SPEC_CACHE = {}
|
|
|
|
|
|
def _spec_with_server():
|
|
"""The generated spec, with `servers` set to where this instance is mounted.
|
|
|
|
THE MOUNT IS A DEPLOYMENT FACT, NOT A BUILD FACT. gen_openapi.py writes
|
|
servers: [{"url": "/"}] because it cannot know where the app will be hung,
|
|
and wsgi.py moves MOUNT_PATH from PATH_INFO into SCRIPT_NAME at runtime. So
|
|
an instance under /shopdb served a spec whose paths start at /api, and both
|
|
renderers dutifully built https://host/api/apitokens - a URL that 404s.
|
|
Anyone who copied it out of the docs page got a broken call, and Swagger's
|
|
try-it fired at the wrong place.
|
|
|
|
request.script_root is the runtime answer: '' for a root install, '/shopdb'
|
|
under the subpath method, and correct behind a proxy that sets the prefix.
|
|
|
|
The file is ~1 MB, so it is parsed once and cached by mtime; each request
|
|
gets a shallow copy with only `servers` replaced, which keeps two requests
|
|
on different mounts from racing on one dict.
|
|
"""
|
|
stamp = os.path.getmtime(_SPEC)
|
|
if _SPEC_CACHE.get('stamp') != stamp:
|
|
with open(_SPEC, 'r', encoding='utf-8') as handle:
|
|
_SPEC_CACHE['spec'] = json.load(handle)
|
|
_SPEC_CACHE['stamp'] = stamp
|
|
|
|
root = request.script_root or ''
|
|
spec = dict(_SPEC_CACHE['spec'])
|
|
spec['servers'] = [{
|
|
'url': root or '/',
|
|
'description': 'this instance',
|
|
}]
|
|
return spec
|
|
|
|
|
|
@docs_bp.route('/openapi.json')
|
|
def openapi_spec():
|
|
"""The generated OpenAPI 3.1 spec (machine + LLM readable).
|
|
|
|
?tag=core-assets narrows it to one tag group. The whole spec is ~700 KB
|
|
across 483 operations, which is more than a caller generating a client for
|
|
one area needs and more than most model context windows should spend. The
|
|
filtered copy keeps components intact, because a pruned schema graph is
|
|
worse than a large one: a $ref that resolves to nothing turns a working
|
|
generator into a confusing failure.
|
|
"""
|
|
if not os.path.isfile(_SPEC):
|
|
return Response('{"error":"openapi.json not generated"}',
|
|
status=404, mimetype='application/json')
|
|
spec = _spec_with_server()
|
|
wanted = (request.args.get('tag') or '').strip()
|
|
if wanted:
|
|
paths = {}
|
|
for path, methods in (spec.get('paths') or {}).items():
|
|
kept = {m: op for m, op in methods.items()
|
|
if not isinstance(op, dict) or wanted in (op.get('tags') or [])}
|
|
# A path whose only survivors are shared keys (parameters, summary)
|
|
# carries no operation and would read as an endpoint that exists
|
|
# and does nothing.
|
|
if any(isinstance(op, dict) and op.get('tags') for op in kept.values()):
|
|
paths[path] = kept
|
|
if not paths:
|
|
return Response(
|
|
json.dumps({'error': f'no operations tagged {wanted!r}',
|
|
'tags': sorted(_operation_tags(spec))}),
|
|
status=404, mimetype='application/json')
|
|
spec = dict(spec, paths=paths)
|
|
return Response(json.dumps(spec), mimetype='application/json')
|
|
|
|
|
|
def _operation_tags(spec):
|
|
"""Every tag that actually carries an operation."""
|
|
tags = set()
|
|
for methods in (spec.get('paths') or {}).values():
|
|
for op in methods.values():
|
|
if isinstance(op, dict):
|
|
tags.update(op.get('tags') or [])
|
|
return tags
|
|
|
|
|
|
@docs_bp.route('/operations.txt')
|
|
def operations_index():
|
|
"""Every operation, one line each: method, path, tag, auth, summary.
|
|
|
|
WHY THIS EXISTS. The spec is the reference and it is ~700 KB; this is the
|
|
index, and it is ~40 KB. A caller - a person or an agent writing a script -
|
|
can hold every one of the 483 operations at once here, find the four it
|
|
needs, and only then fetch their schemas from openapi.json?tag=... Handing
|
|
over the whole spec instead means either truncating it or spending a context
|
|
window on 479 operations nobody asked about.
|
|
|
|
Plain text on purpose: it is meant to be read and grepped, not parsed.
|
|
"""
|
|
if not os.path.isfile(_SPEC):
|
|
return Response('openapi.json not generated', status=404,
|
|
mimetype='text/plain')
|
|
spec = _spec_with_server()
|
|
servers = spec.get('servers') or [{'url': '/'}]
|
|
rows = []
|
|
for path, methods in sorted((spec.get('paths') or {}).items()):
|
|
for method, op in sorted(methods.items()):
|
|
if not isinstance(op, dict) or method.upper() not in _HTTP_METHODS:
|
|
continue
|
|
tag = (op.get('tags') or ['-'])[0]
|
|
# security == [] means public. A list containing an EMPTY dict
|
|
# means the scheme is optional - the route works signed out and
|
|
# returns more when authenticated - and 14 routes here are that
|
|
# shape. Collapsing them to the scheme name told a caller reading
|
|
# only the index that it needed a token for a route that does not
|
|
# require one.
|
|
security = op.get('security')
|
|
if security == []:
|
|
auth = 'public'
|
|
else:
|
|
entries = security or []
|
|
schemes = sorted({k for entry in entries for k in entry})
|
|
optional = any(not entry for entry in entries)
|
|
auth = ','.join(schemes) or 'bearer'
|
|
if optional:
|
|
auth += ',optional'
|
|
summary = ' '.join((op.get('summary') or '').split())
|
|
rows.append(f'{method.upper():<6} {path:<52} [{tag}] ({auth}) {summary}')
|
|
header = (
|
|
'# ShopDB API - operation index\n'
|
|
f'# {len(rows)} operations. Base URL: {servers[0].get("url", "/")}\n'
|
|
'#\n'
|
|
'# This is the INDEX. Schemas, parameters and examples are in the spec:\n'
|
|
'# /api/docs/openapi.json full (large)\n'
|
|
'# /api/docs/openapi.json?tag=<tag> one group\n'
|
|
'# Orientation for an agent, including the response envelope and auth:\n'
|
|
'# /api/docs/llms.txt\n'
|
|
'#\n'
|
|
'# METHOD path [tag] (auth) summary\n'
|
|
)
|
|
return Response(header + '\n'.join(rows) + '\n', mimetype='text/plain')
|
|
|
|
|
|
_HTTP_METHODS = {'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'}
|
|
|
|
|
|
@docs_bp.route('/redoc.standalone.js')
|
|
def redoc_js():
|
|
"""Vendored Redoc bundle (offline)."""
|
|
return send_file(_REDOC, mimetype='application/javascript')
|
|
|
|
|
|
@docs_bp.route('/llms.txt')
|
|
def llms_txt():
|
|
"""Concise LLM-oriented API guide."""
|
|
if not os.path.isfile(_LLMS):
|
|
return Response('llms.txt not found', status=404, mimetype='text/plain')
|
|
return send_file(_LLMS, mimetype='text/plain')
|