@scalar/server-side-rendering 0.1.1 → 0.1.2
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/CHANGELOG.md +6 -0
- package/README.md +14 -33
- package/dist/ssr.js +25 -17
- package/dist/ssr.js.map +1 -1
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
package/README.md
CHANGED
|
@@ -1,45 +1,26 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
This file is auto-generated by the Scalar README generator.
|
|
3
|
+
Command: pnpm --filter @scalar-internal/build-scripts start generate-readme
|
|
4
|
+
|
|
5
|
+
Do not edit this file manually. Changes will be lost when the file is regenerated.
|
|
6
|
+
-->
|
|
7
|
+
|
|
1
8
|
# Scalar Server-Side Rendering
|
|
2
9
|
|
|
3
|
-
[](https://www.npmjs.com/package/@scalar/server-side-rendering)
|
|
11
|
+
[](https://www.npmjs.com/package/@scalar/server-side-rendering)
|
|
12
|
+
[](https://www.npmjs.com/package/@scalar/server-side-rendering)
|
|
6
13
|
[](https://discord.gg/scalar)
|
|
7
14
|
|
|
8
15
|
Server-side render the Scalar API Reference with client-side hydration. Pre-renders HTML on the server for instant content, then hydrates with the standalone bundle for full interactivity.
|
|
9
16
|
|
|
10
|
-
##
|
|
11
|
-
|
|
12
|
-
```bash
|
|
13
|
-
npm install @scalar/server-side-rendering
|
|
14
|
-
```
|
|
15
|
-
|
|
16
|
-
## Usage
|
|
17
|
-
|
|
18
|
-
Render the HTML and JS once at startup, then serve from memory.
|
|
19
|
-
|
|
20
|
-
```ts
|
|
21
|
-
import { renderApiReference, getJsAsset } from '@scalar/server-side-rendering'
|
|
22
|
-
|
|
23
|
-
// Render once at startup
|
|
24
|
-
const html = await renderApiReference({
|
|
25
|
-
config: {
|
|
26
|
-
url: 'https://registry.scalar.com/@scalar/apis/galaxy?format=json',
|
|
27
|
-
},
|
|
28
|
-
pageTitle: 'My API Reference',
|
|
29
|
-
})
|
|
17
|
+
## Documentation
|
|
30
18
|
|
|
31
|
-
|
|
19
|
+
[Read the documentation here](https://scalar.com/products/api-references/server-side-rendering)
|
|
32
20
|
|
|
33
|
-
|
|
34
|
-
app.get('/scalar/scalar.js', (c) => {
|
|
35
|
-
return c.body(js, {
|
|
36
|
-
headers: { 'content-type': 'application/javascript' },
|
|
37
|
-
})
|
|
38
|
-
})
|
|
21
|
+
## Changelog
|
|
39
22
|
|
|
40
|
-
|
|
41
|
-
app.get('/scalar', (c) => c.html(html))
|
|
42
|
-
```
|
|
23
|
+
See [CHANGELOG.md](https://github.com/scalar/scalar/blob/main/packages/server-side-rendering/CHANGELOG.md) for a list of changes.
|
|
43
24
|
|
|
44
25
|
## Community
|
|
45
26
|
|
package/dist/ssr.js
CHANGED
|
@@ -12,6 +12,14 @@ var require = (0, import___vite_browser_external.createRequire)(import.meta.url)
|
|
|
12
12
|
function unwrapConfig(configuration) {
|
|
13
13
|
return (Array.isArray(configuration) ? configuration[0] : configuration) ?? {};
|
|
14
14
|
}
|
|
15
|
+
function parseForceDarkModeState(config) {
|
|
16
|
+
const forced = config.forceDarkModeState;
|
|
17
|
+
if (forced === "dark" || forced === "light") return forced;
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
function parseDarkMode(config) {
|
|
21
|
+
return typeof config.darkMode === "boolean" ? config.darkMode : null;
|
|
22
|
+
}
|
|
15
23
|
/**
|
|
16
24
|
* Generate an inline script that detects the user's color mode preference
|
|
17
25
|
* and applies the correct class to <body> before content paints.
|
|
@@ -28,8 +36,8 @@ function unwrapConfig(configuration) {
|
|
|
28
36
|
*/
|
|
29
37
|
function generateBodyScript(configuration) {
|
|
30
38
|
const config = unwrapConfig(configuration);
|
|
31
|
-
const forced = config
|
|
32
|
-
const darkMode = config
|
|
39
|
+
const forced = parseForceDarkModeState(config);
|
|
40
|
+
const darkMode = parseDarkMode(config);
|
|
33
41
|
/** When forceDarkModeState is set, we do not need runtime detection at all. */
|
|
34
42
|
if (forced) return `<script>(function(){var cl=document.body.classList;cl.remove('dark-mode','light-mode');cl.add('${forced === "dark" ? "dark-mode" : "light-mode"}')})()<\/script>`;
|
|
35
43
|
return `<script>(function(){var cl=document.body.classList;function set(d){cl.remove('dark-mode','light-mode');cl.add(d?'dark-mode':'light-mode')}try{var s=localStorage.getItem('colorMode');if(s==='dark'||s==='light'){set(s==='dark');return}}catch(e){}${darkMode === null ? `set(window.matchMedia('(prefers-color-scheme:dark)').matches)` : `set(${darkMode})`}})()<\/script>`;
|
|
@@ -44,8 +52,8 @@ function generateBodyScript(configuration) {
|
|
|
44
52
|
*/
|
|
45
53
|
function getInitialBodyClass(configuration) {
|
|
46
54
|
const config = unwrapConfig(configuration);
|
|
47
|
-
const forced = config
|
|
48
|
-
const darkMode = config
|
|
55
|
+
const forced = parseForceDarkModeState(config);
|
|
56
|
+
const darkMode = parseDarkMode(config);
|
|
49
57
|
if (forced) return forced === "dark" ? "dark-mode" : "light-mode";
|
|
50
58
|
if (darkMode !== null) return darkMode ? "dark-mode" : "light-mode";
|
|
51
59
|
return "dark-mode";
|
|
@@ -90,23 +98,23 @@ function escapeHtml(str) {
|
|
|
90
98
|
function escapeHtmlAttribute(str) {
|
|
91
99
|
return escapeHtml(str).replace(/"/g, """).replace(/'/g, "'");
|
|
92
100
|
}
|
|
93
|
-
/**
|
|
94
|
-
|
|
95
|
-
|
|
101
|
+
/**
|
|
102
|
+
* Escape a JSON string so it is safe to embed inside an inline script tag.
|
|
103
|
+
* This prevents user content from closing the script tag.
|
|
104
|
+
*/
|
|
105
|
+
function escapeJsonForInlineScript(json) {
|
|
106
|
+
return json.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
96
107
|
}
|
|
97
108
|
/**
|
|
98
|
-
* Serialize a configuration object to
|
|
99
|
-
*
|
|
109
|
+
* Serialize a configuration object to JSON for hydration.
|
|
110
|
+
* Function values are intentionally stripped because they cannot be safely
|
|
111
|
+
* represented in an inline script.
|
|
100
112
|
*/
|
|
101
113
|
function serializeConfigToJs(config) {
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
else jsonProps[key] = value;
|
|
107
|
-
const jsonString = JSON.stringify(jsonProps);
|
|
108
|
-
if (functionProps.length === 0) return jsonString;
|
|
109
|
-
return `{${[jsonString === "{}" ? "" : jsonString.slice(1, -1), functionProps.join(", ")].filter(Boolean).join(", ")}}`;
|
|
114
|
+
return escapeJsonForInlineScript(JSON.stringify(config, (_, value) => {
|
|
115
|
+
if (typeof value === "function") return;
|
|
116
|
+
return value;
|
|
117
|
+
}));
|
|
110
118
|
}
|
|
111
119
|
/**
|
|
112
120
|
* Render the Scalar API Reference as a complete HTML document with client-side
|
package/dist/ssr.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssr.js","names":[],"sources":["../src/ssr.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\n\nimport { ApiReference } from '@scalar/api-reference'\nimport type { AnyApiReferenceConfiguration } from '@scalar/types/api-reference'\nimport { createSSRApp, h } from 'vue'\nimport { renderToString } from 'vue/server-renderer'\n\nconst require = createRequire(import.meta.url)\n\n/**\n * Unwrap the configuration from an array if needed, since AnyApiReferenceConfiguration\n * can be a single config or an array of configs.\n */\nfunction unwrapConfig(configuration: AnyApiReferenceConfiguration): Record<string, unknown> {\n const config = Array.isArray(configuration) ? configuration[0] : configuration\n return (config ?? {}) as Record<string, unknown>\n}\n\n/**\n * Generate an inline script that detects the user's color mode preference\n * and applies the correct class to <body> before content paints.\n *\n * Place this script before the app container in your HTML so it runs before\n * the first paint without interfering with Vue hydration.\n *\n * Priority:\n * 1. forceDarkModeState → always wins (no runtime detection)\n * 2. localStorage 'colorMode' → user's saved preference\n * 3. matchMedia system preference\n * 4. darkMode config → explicit default\n * 5. Fallback → light-mode\n */\nexport function generateBodyScript(configuration: AnyApiReferenceConfiguration): string {\n const config = unwrapConfig(configuration)\n const forced = (config.forceDarkModeState as string | undefined) ?? null\n const darkMode = (config.darkMode as boolean | undefined) ?? null\n\n /** When forceDarkModeState is set, we do not need runtime detection at all. */\n if (forced) {\n return `<script>(function(){var cl=document.body.classList;cl.remove('dark-mode','light-mode');cl.add('${forced === 'dark' ? 'dark-mode' : 'light-mode'}')})()</script>`\n }\n\n /**\n * Runtime detection script: checks localStorage first, then system preference,\n * then falls back to the darkMode config value.\n */\n const fallback =\n darkMode === null ? `set(window.matchMedia('(prefers-color-scheme:dark)').matches)` : `set(${darkMode})`\n\n return `<script>(function(){var cl=document.body.classList;function set(d){cl.remove('dark-mode','light-mode');cl.add(d?'dark-mode':'light-mode')}try{var s=localStorage.getItem('colorMode');if(s==='dark'||s==='light'){set(s==='dark');return}}catch(e){}${fallback}})()</script>`\n}\n\n/**\n * Derive the initial SSR class for <body> from config.\n *\n * Priority:\n * 1. forceDarkModeState\n * 2. darkMode\n * 3. fallback to dark-mode (then runtime script can refine from localStorage/matchMedia)\n */\nfunction getInitialBodyClass(configuration: AnyApiReferenceConfiguration): 'dark-mode' | 'light-mode' {\n const config = unwrapConfig(configuration)\n const forced = (config.forceDarkModeState as string | undefined) ?? null\n const darkMode = (config.darkMode as boolean | undefined) ?? null\n\n if (forced) {\n return forced === 'dark' ? 'dark-mode' : 'light-mode'\n }\n\n if (darkMode !== null) {\n return darkMode ? 'dark-mode' : 'light-mode'\n }\n\n return 'dark-mode'\n}\n\n/**\n * Render the Scalar API Reference to an HTML string for server-side rendering.\n * Use createApiReference on the client to hydrate the server-rendered output.\n *\n * Returns only the Vue-rendered HTML. Use generateBodyScript separately to get\n * the dark/light mode script — place it outside the app container so it does not\n * interfere with Vue hydration.\n */\nexport async function renderApiReferenceToString(configuration: AnyApiReferenceConfiguration): Promise<string> {\n const normalizedConfiguration = unwrapConfig(configuration)\n const app = createSSRApp(() => h(ApiReference, { configuration: normalizedConfiguration }))\n app.config.idPrefix = 'scalar-refs'\n\n return await renderToString(app)\n}\n\nlet _cachedCss: string | undefined\nlet _cachedJs: string | undefined\n\n/** Read the built style.css from the @scalar/api-reference package. */\nfunction getDefaultCss(): string {\n if (_cachedCss === undefined) {\n const cssPath = require.resolve('@scalar/api-reference/style.css')\n _cachedCss = readFileSync(cssPath, 'utf-8')\n }\n return _cachedCss\n}\n\n/**\n * Get the standalone JavaScript bundle as a string.\n *\n * Serve this at a route (e.g. `/scalar/scalar.js`) and pass the same path\n * as the `cdn` option to `renderApiReference`. The bundle handles client-side\n * hydration of the server-rendered HTML.\n */\nexport function getJsAsset(): string {\n if (_cachedJs === undefined) {\n const jsPath = require.resolve('@scalar/api-reference/browser/standalone.js')\n _cachedJs = readFileSync(jsPath, 'utf-8')\n }\n return _cachedJs\n}\n\n/** Escape HTML special characters in user-provided strings. */\nfunction escapeHtml(str: string): string {\n return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')\n}\n\n/** Escape user-provided strings before inserting into HTML attributes. */\nfunction escapeHtmlAttribute(str: string): string {\n return escapeHtml(str).replace(/\"/g, '"').replace(/'/g, ''')\n}\n\n/** Serialize an array that may contain functions. */\nfunction serializeArrayWithFunctions(arr: unknown[]): string {\n return `[${arr.map((item) => (typeof item === 'function' ? item.toString() : JSON.stringify(item))).join(', ')}]`\n}\n\n/**\n * Serialize a configuration object to a JavaScript expression string,\n * preserving function values (which JSON.stringify would silently drop).\n */\nfunction serializeConfigToJs(config: Record<string, unknown>): string {\n const jsonProps: Record<string, unknown> = {}\n const functionProps: string[] = []\n\n for (const [key, value] of Object.entries(config)) {\n if (typeof value === 'function') {\n functionProps.push(`\"${key}\": ${value.toString()}`)\n } else if (Array.isArray(value) && value.some((item) => typeof item === 'function')) {\n functionProps.push(`\"${key}\": ${serializeArrayWithFunctions(value)}`)\n } else {\n jsonProps[key] = value\n }\n }\n\n const jsonString = JSON.stringify(jsonProps)\n\n if (functionProps.length === 0) {\n return jsonString\n }\n\n const jsonEntries = jsonString === '{}' ? '' : jsonString.slice(1, -1)\n const functionEntries = functionProps.join(', ')\n\n return `{${[jsonEntries, functionEntries].filter(Boolean).join(', ')}}`\n}\n\n/**\n * Render the Scalar API Reference as a complete HTML document with client-side\n * hydration.\n *\n * Returns a full `<!doctype html>` page with:\n * - Inline CSS in `<head>` (prevents flash of unstyled content)\n * - Color-mode detection script (runs before first paint)\n * - Pre-rendered Vue HTML (immediate content, no blank page)\n * - Script tags to load the standalone bundle and hydrate\n *\n * Serve the standalone JS bundle via `getJsAsset()` at the route matching\n * the `cdn` option (defaults to `/scalar/scalar.js`).\n */\nexport async function renderApiReference(options: {\n /** The API reference configuration. */\n config: AnyApiReferenceConfiguration\n /** Page title. Defaults to \"Scalar API Reference\". */\n pageTitle?: string\n /** Override the built-in CSS. */\n css?: string\n /** URL path to the standalone JS bundle. Defaults to \"/scalar/scalar.js\". */\n cdn?: string\n}): Promise<string> {\n const title = escapeHtml(options.pageTitle ?? 'Scalar API Reference')\n const css = options.css ?? getDefaultCss()\n const cdn = escapeHtmlAttribute(options.cdn ?? '/scalar/scalar.js')\n const html = await renderApiReferenceToString(options.config)\n const bodyScript = generateBodyScript(options.config)\n const initialBodyClass = getInitialBodyClass(options.config)\n const configJs = serializeConfigToJs(unwrapConfig(options.config))\n\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${title}</title>\n <style>${css}</style>\n </head>\n <body class=\"${initialBodyClass}\">\n ${bodyScript}\n <div id=\"app\">${html}</div>\n <script src=\"${cdn}\"></script>\n <script>Scalar.createApiReference('#app', ${configJs})</script>\n </body>\n</html>`\n}\n"],"mappings":";;;;;;AAQA,IAAM,WAAA,GAAA,+BAAA,eAAwB,OAAO,KAAK,IAAI;;;;;AAM9C,SAAS,aAAa,eAAsE;AAE1F,SADe,MAAM,QAAQ,cAAc,GAAG,cAAc,KAAK,kBAC/C,EAAE;;;;;;;;;;;;;;;;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'node:module'\n\nimport { ApiReference } from '@scalar/api-reference'\nimport type { AnyApiReferenceConfiguration } from '@scalar/types/api-reference'\nimport { createSSRApp, h } from 'vue'\nimport { renderToString } from 'vue/server-renderer'\n\nconst require = createRequire(import.meta.url)\n\n/**\n * Unwrap the configuration from an array if needed, since AnyApiReferenceConfiguration\n * can be a single config or an array of configs.\n */\nfunction unwrapConfig(configuration: AnyApiReferenceConfiguration): Record<string, unknown> {\n const config = Array.isArray(configuration) ? configuration[0] : configuration\n return (config ?? {}) as Record<string, unknown>\n}\n\nfunction parseForceDarkModeState(config: Record<string, unknown>): 'dark' | 'light' | null {\n const forced = config.forceDarkModeState\n\n if (forced === 'dark' || forced === 'light') {\n return forced\n }\n\n return null\n}\n\nfunction parseDarkMode(config: Record<string, unknown>): boolean | null {\n return typeof config.darkMode === 'boolean' ? config.darkMode : null\n}\n\n/**\n * Generate an inline script that detects the user's color mode preference\n * and applies the correct class to <body> before content paints.\n *\n * Place this script before the app container in your HTML so it runs before\n * the first paint without interfering with Vue hydration.\n *\n * Priority:\n * 1. forceDarkModeState → always wins (no runtime detection)\n * 2. localStorage 'colorMode' → user's saved preference\n * 3. matchMedia system preference\n * 4. darkMode config → explicit default\n * 5. Fallback → light-mode\n */\nexport function generateBodyScript(configuration: AnyApiReferenceConfiguration): string {\n const config = unwrapConfig(configuration)\n const forced = parseForceDarkModeState(config)\n const darkMode = parseDarkMode(config)\n\n /** When forceDarkModeState is set, we do not need runtime detection at all. */\n if (forced) {\n return `<script>(function(){var cl=document.body.classList;cl.remove('dark-mode','light-mode');cl.add('${forced === 'dark' ? 'dark-mode' : 'light-mode'}')})()</script>`\n }\n\n /**\n * Runtime detection script: checks localStorage first, then system preference,\n * then falls back to the darkMode config value.\n */\n const fallback =\n darkMode === null ? `set(window.matchMedia('(prefers-color-scheme:dark)').matches)` : `set(${darkMode})`\n\n return `<script>(function(){var cl=document.body.classList;function set(d){cl.remove('dark-mode','light-mode');cl.add(d?'dark-mode':'light-mode')}try{var s=localStorage.getItem('colorMode');if(s==='dark'||s==='light'){set(s==='dark');return}}catch(e){}${fallback}})()</script>`\n}\n\n/**\n * Derive the initial SSR class for <body> from config.\n *\n * Priority:\n * 1. forceDarkModeState\n * 2. darkMode\n * 3. fallback to dark-mode (then runtime script can refine from localStorage/matchMedia)\n */\nfunction getInitialBodyClass(configuration: AnyApiReferenceConfiguration): 'dark-mode' | 'light-mode' {\n const config = unwrapConfig(configuration)\n const forced = parseForceDarkModeState(config)\n const darkMode = parseDarkMode(config)\n\n if (forced) {\n return forced === 'dark' ? 'dark-mode' : 'light-mode'\n }\n\n if (darkMode !== null) {\n return darkMode ? 'dark-mode' : 'light-mode'\n }\n\n return 'dark-mode'\n}\n\n/**\n * Render the Scalar API Reference to an HTML string for server-side rendering.\n * Use createApiReference on the client to hydrate the server-rendered output.\n *\n * Returns only the Vue-rendered HTML. Use generateBodyScript separately to get\n * the dark/light mode script — place it outside the app container so it does not\n * interfere with Vue hydration.\n */\nexport async function renderApiReferenceToString(configuration: AnyApiReferenceConfiguration): Promise<string> {\n const normalizedConfiguration = unwrapConfig(configuration)\n const app = createSSRApp(() => h(ApiReference, { configuration: normalizedConfiguration }))\n app.config.idPrefix = 'scalar-refs'\n\n return await renderToString(app)\n}\n\nlet _cachedCss: string | undefined\nlet _cachedJs: string | undefined\n\n/** Read the built style.css from the @scalar/api-reference package. */\nfunction getDefaultCss(): string {\n if (_cachedCss === undefined) {\n const cssPath = require.resolve('@scalar/api-reference/style.css')\n _cachedCss = readFileSync(cssPath, 'utf-8')\n }\n return _cachedCss\n}\n\n/**\n * Get the standalone JavaScript bundle as a string.\n *\n * Serve this at a route (e.g. `/scalar/scalar.js`) and pass the same path\n * as the `cdn` option to `renderApiReference`. The bundle handles client-side\n * hydration of the server-rendered HTML.\n */\nexport function getJsAsset(): string {\n if (_cachedJs === undefined) {\n const jsPath = require.resolve('@scalar/api-reference/browser/standalone.js')\n _cachedJs = readFileSync(jsPath, 'utf-8')\n }\n return _cachedJs\n}\n\n/** Escape HTML special characters in user-provided strings. */\nfunction escapeHtml(str: string): string {\n return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')\n}\n\n/** Escape user-provided strings before inserting into HTML attributes. */\nfunction escapeHtmlAttribute(str: string): string {\n return escapeHtml(str).replace(/\"/g, '"').replace(/'/g, ''')\n}\n\n/**\n * Escape a JSON string so it is safe to embed inside an inline script tag.\n * This prevents user content from closing the script tag.\n */\nfunction escapeJsonForInlineScript(json: string): string {\n return json\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/&/g, '\\\\u0026')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029')\n}\n\n/**\n * Serialize a configuration object to JSON for hydration.\n * Function values are intentionally stripped because they cannot be safely\n * represented in an inline script.\n */\nfunction serializeConfigToJs(config: Record<string, unknown>): string {\n const jsonString = JSON.stringify(config, (_, value) => {\n if (typeof value === 'function') {\n return undefined\n }\n\n return value\n })\n\n return escapeJsonForInlineScript(jsonString)\n}\n\n/**\n * Render the Scalar API Reference as a complete HTML document with client-side\n * hydration.\n *\n * Returns a full `<!doctype html>` page with:\n * - Inline CSS in `<head>` (prevents flash of unstyled content)\n * - Color-mode detection script (runs before first paint)\n * - Pre-rendered Vue HTML (immediate content, no blank page)\n * - Script tags to load the standalone bundle and hydrate\n *\n * Serve the standalone JS bundle via `getJsAsset()` at the route matching\n * the `cdn` option (defaults to `/scalar/scalar.js`).\n */\nexport async function renderApiReference(options: {\n /** The API reference configuration. */\n config: AnyApiReferenceConfiguration\n /** Page title. Defaults to \"Scalar API Reference\". */\n pageTitle?: string\n /** Override the built-in CSS. */\n css?: string\n /** URL path to the standalone JS bundle. Defaults to \"/scalar/scalar.js\". */\n cdn?: string\n}): Promise<string> {\n const title = escapeHtml(options.pageTitle ?? 'Scalar API Reference')\n const css = options.css ?? getDefaultCss()\n const cdn = escapeHtmlAttribute(options.cdn ?? '/scalar/scalar.js')\n const html = await renderApiReferenceToString(options.config)\n const bodyScript = generateBodyScript(options.config)\n const initialBodyClass = getInitialBodyClass(options.config)\n const configJs = serializeConfigToJs(unwrapConfig(options.config))\n\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${title}</title>\n <style>${css}</style>\n </head>\n <body class=\"${initialBodyClass}\">\n ${bodyScript}\n <div id=\"app\">${html}</div>\n <script src=\"${cdn}\"></script>\n <script>Scalar.createApiReference('#app', ${configJs})</script>\n </body>\n</html>`\n}\n"],"mappings":";;;;;;AAQA,IAAM,WAAA,GAAA,+BAAA,eAAwB,OAAO,KAAK,IAAI;;;;;AAM9C,SAAS,aAAa,eAAsE;AAE1F,SADe,MAAM,QAAQ,cAAc,GAAG,cAAc,KAAK,kBAC/C,EAAE;;AAGtB,SAAS,wBAAwB,QAA0D;CACzF,MAAM,SAAS,OAAO;AAEtB,KAAI,WAAW,UAAU,WAAW,QAClC,QAAO;AAGT,QAAO;;AAGT,SAAS,cAAc,QAAiD;AACtE,QAAO,OAAO,OAAO,aAAa,YAAY,OAAO,WAAW;;;;;;;;;;;;;;;;AAiBlE,SAAgB,mBAAmB,eAAqD;CACtF,MAAM,SAAS,aAAa,cAAc;CAC1C,MAAM,SAAS,wBAAwB,OAAO;CAC9C,MAAM,WAAW,cAAc,OAAO;;AAGtC,KAAI,OACF,QAAO,kGAAkG,WAAW,SAAS,cAAc,aAAa;AAU1J,QAAO,uPAFL,aAAa,OAAO,kEAAkE,OAAO,SAAS,GAE+J;;;;;;;;;;AAWzQ,SAAS,oBAAoB,eAAyE;CACpG,MAAM,SAAS,aAAa,cAAc;CAC1C,MAAM,SAAS,wBAAwB,OAAO;CAC9C,MAAM,WAAW,cAAc,OAAO;AAEtC,KAAI,OACF,QAAO,WAAW,SAAS,cAAc;AAG3C,KAAI,aAAa,KACf,QAAO,WAAW,cAAc;AAGlC,QAAO;;;;;;;;;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2B,QAAQ,OAAO;CAC7D,MAAM,aAAa,mBAAmB,QAAQ,OAAO;AAIrD,QAAO;;;;;aAKI,MAAM;aACN,IAAI;;iBATU,oBAAoB,QAAQ,OAAO,CAW5B;MAC5B,WAAW;oBACG,KAAK;mBACN,IAAI;gDAbJ,oBAAoB,aAAa,QAAQ,OAAO,CAAC,CAcX"}
|
package/package.json
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"directory": "packages/server-side-rendering"
|
|
12
12
|
},
|
|
13
13
|
"keywords": [],
|
|
14
|
-
"version": "0.1.
|
|
14
|
+
"version": "0.1.2",
|
|
15
15
|
"engines": {
|
|
16
16
|
"node": ">=22"
|
|
17
17
|
},
|
|
@@ -29,8 +29,8 @@
|
|
|
29
29
|
],
|
|
30
30
|
"dependencies": {
|
|
31
31
|
"vue": "^3.5.30",
|
|
32
|
-
"@scalar/api-reference": "1.52.
|
|
33
|
-
"@scalar/types": "0.
|
|
32
|
+
"@scalar/api-reference": "1.52.2",
|
|
33
|
+
"@scalar/types": "0.9.0"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@hono/node-server": "^1.19.10",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"scripts": {
|
|
43
43
|
"build": "vite build",
|
|
44
44
|
"dev": "tsx playground/server.ts",
|
|
45
|
-
"test": "vitest",
|
|
45
|
+
"test": "vitest --run",
|
|
46
46
|
"types:check": "tsc --noEmit"
|
|
47
47
|
}
|
|
48
48
|
}
|