@rapidoc/starlight 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Mrinmoy Majumdar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # @rapidoc/starlight
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Adds API reference pages to a [Starlight](https://starlight.astro.build) site. Each OpenAPI document becomes a page drawn by [RapiDoc](https://rapidocui.com), inside Starlight's own layout, with the API's tags and operations in Starlight's sidebar.
4
+
5
+ ```bash
6
+ npm install @rapidoc/starlight
7
+ ```
8
+
9
+ ```js
10
+ // astro.config.mjs
11
+ import { defineConfig } from "astro/config";
12
+ import starlight from "@astrojs/starlight";
13
+ import starlightRapidoc from "@rapidoc/starlight";
14
+
15
+ export default defineConfig({
16
+ integrations: [
17
+ starlight({
18
+ title: "My docs",
19
+ plugins: [starlightRapidoc({ path: "/api", spec: "./openapi.yaml" })],
20
+ }),
21
+ ],
22
+ });
23
+ ```
24
+
25
+ The reference is at `/api`. The sidebar gets a group named after the API, with an overview link and a link for every operation, grouped by tag.
26
+
27
+ ## What you get
28
+
29
+ - **Starlight's layout**: its header, sidebar, search and theme switch stay; RapiDoc's own header and sidebar are off.
30
+ - **The site's colours**: the reference follows Starlight's light and dark themes and sits on its background.
31
+ - **One page per API**: an operation link is a section of that page (`/api/#list-pets`), so moving between operations does not reload it.
32
+ - **No request for the spec**: the document is read at build time and written into the page.
33
+ - **Try it and OAuth**: the console works as in RapiDoc; the OAuth return page is built at `{path}/oauth-receiver/`.
34
+
35
+ ## Options
36
+
37
+ | Option | Default | |
38
+ | :-------- | :-------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- |
39
+ | `path` | required | Where the reference page is served, for example `/api` |
40
+ | `spec` | required | The OpenAPI document: a JSON or YAML file (relative to the project root), a URL, or the object. It is read when the site is built |
41
+ | `title` | the document's `info.title` | Page title |
42
+ | `label` | the title | Sidebar group label |
43
+ | `options` | | [Attributes of `<rapi-doc>`](https://rapidocui.com/api/), in kebab-case or camelCase: `{ allowTry: false, theme: "jade" }`. They win over the plugin's own |
44
+ | `sidebar` | | `false` adds nothing to the sidebar (link to the page yourself); `{ collapsed: true }` starts the tag groups collapsed |
45
+
46
+ For several APIs, pass `{ apis: [{ path, spec }, { path, spec }] }`.
47
+
48
+ The sidebar group is added after your own `sidebar` entries. If your config has no `sidebar`, Starlight generates one from your files; adding the API group replaces that generated sidebar, so list your pages in `sidebar` too, for example with `{ label: "Guides", autogenerate: { directory: "guides" } }`.
49
+
50
+ ## Notes
51
+
52
+ - The plugin sets `render-style="focused"`, `show-header="false"`, `show-side-nav="false"`, `auto-height="true"` and `color-scheme="auto"`. Change any of them through `options`.
53
+ - API pages are not in the site search (Pagefind): their content is drawn in the browser.
54
+ - Starlight 0.32 or later; Astro 5 or later. MIT.
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@rapidoc/starlight",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "description": "RapiDoc for Starlight: OpenAPI reference pages inside your Starlight docs, with the operations in the sidebar",
5
+ "keywords": [
6
+ "api documentation",
7
+ "astro",
8
+ "openapi",
9
+ "rapidoc",
10
+ "rapidoc-integration",
11
+ "starlight",
12
+ "starlight-plugin"
13
+ ],
14
+ "homepage": "https://rapidocui.com",
15
+ "bugs": {
16
+ "url": "https://github.com/rapi-doc/RapiDoc/issues"
17
+ },
18
+ "license": "MIT",
19
+ "author": "Mrinmoy Majumdar <mrin9@yahoo.com>",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/rapi-doc/RapiDoc.git",
23
+ "directory": "packages/rapidoc-starlight"
24
+ },
25
+ "files": [
26
+ "src"
27
+ ],
28
+ "type": "module",
29
+ "main": "./src/index.js",
30
+ "types": "./src/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./src/index.d.ts",
34
+ "default": "./src/index.js"
35
+ }
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "scripts": {
41
+ "test": "node --test tests/**/*.test.js"
42
+ },
43
+ "dependencies": {
44
+ "@rapidoc/embed": "^0.0.0",
45
+ "@rapidoc/prerender": "^0.1.5",
46
+ "rapidoc": "^12.1.2",
47
+ "yaml": "^2.9.1"
48
+ },
49
+ "peerDependencies": {
50
+ "@astrojs/starlight": ">=0.32.0",
51
+ "astro": ">=5.0.0"
52
+ },
53
+ "engines": {
54
+ "node": ">=22.12.0"
55
+ }
56
+ }
@@ -0,0 +1,87 @@
1
+ ---
2
+ // One API's reference: <rapi-doc> in Starlight's page layout. The spec is written into the page, so the
3
+ // reference renders without a second request.
4
+ import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
5
+ import { apis } from 'virtual:rapidoc-starlight';
6
+
7
+ const base = import.meta.env.BASE_URL.replace(/\/+$/, '');
8
+ const pathname = Astro.url.pathname.slice(base.length).replace(/\/+$/, '');
9
+ const api = apis.find((candidate) => candidate.path === pathname);
10
+ if (!api) throw new Error(`@rapidoc/starlight: no API is configured at ${Astro.url.pathname}`);
11
+ ---
12
+
13
+ <StarlightPage
14
+ frontmatter={{
15
+ title: api.title,
16
+ tableOfContents: false,
17
+ // the sidebar's operation links are sections of this page, not pages to step through
18
+ prev: false,
19
+ next: false,
20
+ pagefind: false,
21
+ }}
22
+ >
23
+ <rapi-doc class="rapidoc-starlight not-content" {...api.attributes}>
24
+ <script is:inline type="application/json" slot="rapidoc-spec" set:html={api.specJson} />
25
+ </rapi-doc>
26
+ </StarlightPage>
27
+
28
+ <script>
29
+ import 'rapidoc';
30
+
31
+ // The sidebar's operation links all point into this page, so Starlight marks none or all of them as
32
+ // current. <rapi-doc> says which section is showing; mark that one.
33
+ const element = document.querySelector('rapi-doc.rapidoc-starlight');
34
+ const links = () => document.querySelectorAll<HTMLAnchorElement>('a[data-rapidoc-op]');
35
+
36
+ function markCurrent(id: string) {
37
+ let found = false;
38
+ for (const link of links()) {
39
+ const isCurrent = link.dataset.rapidocOp === id;
40
+ if (isCurrent) {
41
+ link.setAttribute('aria-current', 'page');
42
+ found = true;
43
+ } else {
44
+ link.removeAttribute('aria-current');
45
+ }
46
+ }
47
+ return found;
48
+ }
49
+
50
+ const fromHash = () => decodeURIComponent(window.location.hash.slice(1)) || 'overview';
51
+ markCurrent(fromHash());
52
+ window.addEventListener('hashchange', () => markCurrent(fromHash()));
53
+ element?.addEventListener('nav-active-change', (event) => {
54
+ const { elementId, id } = (event as CustomEvent).detail ?? {};
55
+ if (!markCurrent(elementId ?? id)) markCurrent('overview');
56
+ });
57
+ </script>
58
+
59
+ <style is:global>
60
+ /* The reference needs more room than prose; only pages with <rapi-doc> load this rule. */
61
+ :root:has(rapi-doc.rapidoc-starlight) {
62
+ --sl-content-width: 72rem;
63
+ }
64
+
65
+ rapi-doc.rapidoc-starlight {
66
+ display: block;
67
+ width: 100%;
68
+ min-height: 60vh;
69
+ /* sit on the site's own background, in both of its themes */
70
+ --background: var(--sl-color-bg);
71
+ }
72
+
73
+ /* The reference opens with the API's title, so Starlight's page title is kept for assistive technology only */
74
+ :root:has(rapi-doc.rapidoc-starlight) .content-panel:has(h1#_top) {
75
+ position: absolute;
76
+ width: 1px;
77
+ height: 1px;
78
+ padding: 0;
79
+ overflow: hidden;
80
+ clip-path: inset(50%);
81
+ border: 0;
82
+ }
83
+
84
+ :root:has(rapi-doc.rapidoc-starlight) .content-panel + .content-panel {
85
+ border-top: 0;
86
+ }
87
+ </style>
@@ -0,0 +1,19 @@
1
+ ---
2
+ // The page an OAuth provider sends the sign-in popup back to: <oauth-receiver> hands the reply to the
3
+ // reference that opened it. No layout: it is only ever seen for a moment, in a popup.
4
+ ---
5
+
6
+ <!doctype html>
7
+ <html lang="en">
8
+ <head>
9
+ <meta charset="utf-8" />
10
+ <meta name="robots" content="noindex" />
11
+ <title>OAuth sign-in</title>
12
+ </head>
13
+ <body>
14
+ <oauth-receiver></oauth-receiver>
15
+ <script>
16
+ import 'rapidoc';
17
+ </script>
18
+ </body>
19
+ </html>
package/src/apis.js ADDED
@@ -0,0 +1,148 @@
1
+ // What the plugin works out at build time, with no Astro or Starlight import: the options as given become,
2
+ // per API, the spec (loaded from a file, a URL or an object), the attributes of <rapi-doc> and the sidebar
3
+ // entries for its tags and operations.
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { parse } from "yaml";
7
+ import { normalizePath, toAttributes, inlineJson } from "@rapidoc/embed/core";
8
+ import { getSpecNavigation } from "@rapidoc/prerender";
9
+
10
+ /**
11
+ * How <rapi-doc> sits in a Starlight page: Starlight's sidebar and header replace its own, the page
12
+ * scrolls instead of the element, and its colours follow the site's light and dark themes.
13
+ */
14
+ export const PAGE_ATTRIBUTES = {
15
+ "render-style": "focused",
16
+ "show-header": "false",
17
+ "show-side-nav": "false",
18
+ "auto-height": "true",
19
+ "color-scheme": "auto",
20
+ "allow-spec-url-load": "false",
21
+ "allow-spec-file-load": "false",
22
+ };
23
+
24
+ const isUrl = (value) => /^https?:\/\//i.test(value);
25
+
26
+ /** The OpenAPI document as an object: from a file (JSON or YAML, relative to `root`), a URL or as given. */
27
+ export async function loadSpec(spec, root) {
28
+ if (spec && typeof spec === "object") return spec;
29
+ if (typeof spec !== "string" || spec === "") {
30
+ throw new TypeError(
31
+ "@rapidoc/starlight: each API needs `spec`: a file path, a URL or an object",
32
+ );
33
+ }
34
+ let text;
35
+ if (isUrl(spec)) {
36
+ const response = await fetch(spec);
37
+ if (!response.ok) {
38
+ throw new Error(`@rapidoc/starlight: ${spec} answered ${response.status}`);
39
+ }
40
+ text = await response.text();
41
+ } else {
42
+ const file = path.resolve(root, spec);
43
+ if (!fs.existsSync(file)) throw new Error(`@rapidoc/starlight: spec file not found: ${file}`);
44
+ text = fs.readFileSync(file, "utf8");
45
+ }
46
+ const document = parse(text);
47
+ if (!document || typeof document !== "object") {
48
+ throw new Error(`@rapidoc/starlight: ${spec} is not an OpenAPI document`);
49
+ }
50
+ return document;
51
+ }
52
+
53
+ /** `/docs/api/` → `/docs/api`; a path is required, and the site root is not allowed (Starlight owns it). */
54
+ function apiPath(value) {
55
+ const normalized = normalizePath(value ?? "");
56
+ if (normalized === "") {
57
+ throw new TypeError('@rapidoc/starlight: each API needs `path`, for example "/api"');
58
+ }
59
+ return normalized;
60
+ }
61
+
62
+ /** A page URL under the site's `base`, with the trailing slash the site uses. */
63
+ export function pageUrl(base, pagePath, trailingSlash = "ignore") {
64
+ const prefix = normalizePath(base ?? "/");
65
+ return `${prefix}${pagePath}${trailingSlash === "never" ? "" : "/"}`;
66
+ }
67
+
68
+ const operationLabel = (operation) => operation.summary || `${operation.method} ${operation.path}`;
69
+
70
+ function tagItems(tag, href) {
71
+ return tag.paths.map((operation) => ({
72
+ label: operationLabel(operation),
73
+ link: `${href}#${operation.elementId}`,
74
+ ...(operation.deprecated ? { badge: { text: "deprecated", variant: "caution" } } : {}),
75
+ attrs: { "data-rapidoc-op": operation.elementId, "data-method": operation.method },
76
+ }));
77
+ }
78
+
79
+ /**
80
+ * The Starlight sidebar group of one API: an overview link, then a group per tag with its operations.
81
+ * Links point into the API's page (`#<operation id>`); <rapi-doc> shows the operation the hash names.
82
+ */
83
+ export function sidebarGroup(api, navigation, href) {
84
+ const tags = navigation.tagGroups.length
85
+ ? [...navigation.tagGroups.flatMap((group) => group.tags), ...navigation.remainingTags]
86
+ : navigation.tags;
87
+ const items = [{ label: "Overview", link: href, attrs: { "data-rapidoc-op": "overview" } }];
88
+ for (const tag of tags) {
89
+ if (tag.paths.length === 0) continue;
90
+ items.push({
91
+ label: tag.displayName || tag.name,
92
+ collapsed: api.sidebar?.collapsed ?? false,
93
+ items: tagItems(tag, href),
94
+ });
95
+ }
96
+ return { label: api.label ?? api.title, collapsed: false, items };
97
+ }
98
+
99
+ /**
100
+ * Resolves the plugin's options against the site.
101
+ * @returns {Promise<{ apis: object[], sidebar: object[] }>} `apis` is what the pages render (JSON-safe);
102
+ * `sidebar` is the groups to append to Starlight's sidebar.
103
+ */
104
+ export async function resolveApis(userOptions, site) {
105
+ const list = Array.isArray(userOptions?.apis)
106
+ ? userOptions.apis
107
+ : userOptions
108
+ ? [userOptions]
109
+ : [];
110
+ if (list.length === 0) {
111
+ throw new TypeError("@rapidoc/starlight: give at least one API: { path, spec }");
112
+ }
113
+ const apis = [];
114
+ const sidebar = [];
115
+ const seen = new Set();
116
+ for (const given of list) {
117
+ const pagePath = apiPath(given.path);
118
+ if (seen.has(pagePath))
119
+ throw new TypeError(`@rapidoc/starlight: two APIs use the path ${pagePath}`);
120
+ seen.add(pagePath);
121
+
122
+ const spec = await loadSpec(given.spec, site.root);
123
+ const navigation = await getSpecNavigation(structuredClone(spec));
124
+ const title = given.title ?? navigation.title ?? "API Reference";
125
+ const href = pageUrl(site.base, pagePath, site.trailingSlash);
126
+ const receiver = pageUrl(site.base, `${pagePath}/oauth-receiver`, site.trailingSlash);
127
+
128
+ // The contract's attribute rules (names, booleans, sorting); the page defaults first, the user's last
129
+ const attributes = Object.fromEntries(
130
+ toAttributes({
131
+ path: pagePath,
132
+ options: {
133
+ ...PAGE_ATTRIBUTES,
134
+ "oauth-receiver": receiver,
135
+ ...(isUrl(given.spec) ? { "spec-url": given.spec } : {}),
136
+ ...given.options,
137
+ },
138
+ }),
139
+ );
140
+
141
+ const api = { path: pagePath, title, attributes, specJson: inlineJson(spec) };
142
+ apis.push(api);
143
+ if (given.sidebar !== false) {
144
+ sidebar.push(sidebarGroup({ ...given, title }, navigation, href));
145
+ }
146
+ }
147
+ return { apis, sidebar };
148
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { StarlightPlugin } from "@astrojs/starlight/types";
2
+ import type { RapiDocOptions } from "@rapidoc/embed";
3
+
4
+ export interface StarlightRapidocApi {
5
+ /** Where the reference page is served, for example `/api`. */
6
+ path: string;
7
+ /** The OpenAPI document: a file (JSON or YAML, relative to the project root), a URL, or the object. Read at build time. */
8
+ spec: string | object;
9
+ /** Page title. Default: the document's `info.title`. */
10
+ title?: string;
11
+ /** Sidebar group label. Default: the title. */
12
+ label?: string;
13
+ /** Attributes of `<rapi-doc>`, in kebab-case or camelCase. They win over the plugin's own. */
14
+ options?: RapiDocOptions;
15
+ /** `false` adds nothing to the sidebar; `{ collapsed: true }` starts the tag groups collapsed. */
16
+ sidebar?: false | { collapsed?: boolean };
17
+ }
18
+
19
+ export type StarlightRapidocOptions = StarlightRapidocApi | { apis: StarlightRapidocApi[] };
20
+
21
+ /** Starlight plugin: an API reference page per OpenAPI document, with its operations in the sidebar. */
22
+ export default function starlightRapidoc(options: StarlightRapidocOptions): StarlightPlugin;
package/src/index.js ADDED
@@ -0,0 +1,63 @@
1
+ // @rapidoc/starlight: a Starlight plugin that adds an API reference page per OpenAPI document, drawn by
2
+ // <rapi-doc> inside Starlight's layout, with the API's tags and operations in Starlight's sidebar.
3
+ import { fileURLToPath } from "node:url";
4
+ import { resolveApis } from "./apis.js";
5
+
6
+ const VIRTUAL_ID = "virtual:rapidoc-starlight";
7
+ const entry = (file) => fileURLToPath(new URL(file, import.meta.url));
8
+
9
+ /** The Astro integration the plugin adds: one route per API, its OAuth return page, and the pages' data. */
10
+ function rapidocIntegration(apis) {
11
+ return {
12
+ name: "@rapidoc/starlight",
13
+ hooks: {
14
+ "astro:config:setup"({ injectRoute, updateConfig }) {
15
+ for (const api of apis) {
16
+ injectRoute({ pattern: api.path, entrypoint: entry("./ApiPage.astro"), prerender: true });
17
+ injectRoute({
18
+ pattern: `${api.path}/oauth-receiver`,
19
+ entrypoint: entry("./OAuthReceiver.astro"),
20
+ prerender: true,
21
+ });
22
+ }
23
+ updateConfig({
24
+ vite: {
25
+ plugins: [
26
+ {
27
+ name: "rapidoc-starlight-data",
28
+ resolveId: (id) => (id === VIRTUAL_ID ? `\0${VIRTUAL_ID}` : undefined),
29
+ load: (id) =>
30
+ id === `\0${VIRTUAL_ID}`
31
+ ? `export const apis = ${JSON.stringify(apis)};`
32
+ : undefined,
33
+ },
34
+ ],
35
+ },
36
+ });
37
+ },
38
+ },
39
+ };
40
+ }
41
+
42
+ /**
43
+ * `starlight({ plugins: [starlightRapidoc({ path: "/api", spec: "./openapi.yaml" })] })`, or
44
+ * `starlightRapidoc({ apis: [...] })` for several APIs.
45
+ */
46
+ export default function starlightRapidoc(userOptions) {
47
+ return {
48
+ name: "@rapidoc/starlight",
49
+ hooks: {
50
+ async "config:setup"({ config, astroConfig, updateConfig, addIntegration }) {
51
+ const { apis, sidebar } = await resolveApis(userOptions, {
52
+ root: fileURLToPath(astroConfig.root),
53
+ base: astroConfig.base,
54
+ trailingSlash: astroConfig.trailingSlash,
55
+ });
56
+ if (sidebar.length > 0) {
57
+ updateConfig({ sidebar: [...(config.sidebar ?? []), ...sidebar] });
58
+ }
59
+ addIntegration(rapidocIntegration(apis));
60
+ },
61
+ },
62
+ };
63
+ }