sdocs 0.0.25 → 0.0.26

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 CHANGED
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.0.26] - 2026-07-03
11
+
12
+ ### Fixed
13
+
14
+ - **Embedded production builds now include working previews.** The Vite
15
+ plugin emits each preview as a static page (plus your `css` stylesheets)
16
+ into the host app's client build under `previews/`, and `virtual:sdocs`
17
+ references those pages — preview iframes no longer 404 in deployed apps.
18
+ - The standalone CLI (`sdocs dev`/`sdocs build`) failed from an installed
19
+ package: the client app was staged from a wrong path, and its `ui/` styles
20
+ and fonts were not staged at all.
21
+ - The docs UI stops calling the dev-only highlight endpoint after the first
22
+ failure in production and falls back to plain code.
23
+
10
24
  ## [0.0.25] - 2026-07-02
11
25
 
12
26
  ### Added
@@ -169,13 +169,20 @@
169
169
  return generateFallbackCode(componentName, propValues, cssValues);
170
170
  });
171
171
 
172
- // Highlighted usage code via server-side Shiki
172
+ // Highlighted usage code via server-side Shiki. The endpoint is dev-server
173
+ // middleware; in a production build it doesn't exist, so after the first
174
+ // failure stop asking and fall back to plain code.
173
175
  let highlightedUsageHtml = $state('');
174
176
  let highlightTimer: ReturnType<typeof setTimeout> | undefined;
177
+ let highlightAvailable = true;
175
178
 
176
179
  $effect(() => {
177
180
  const code = usageCode;
178
181
  clearTimeout(highlightTimer);
182
+ if (!highlightAvailable) {
183
+ highlightedUsageHtml = '';
184
+ return;
185
+ }
179
186
  highlightTimer = setTimeout(async () => {
180
187
  try {
181
188
  const res = await fetch('/__sdocs/highlight', {
@@ -186,9 +193,13 @@
186
193
  if (res.ok) {
187
194
  const { html } = await res.json();
188
195
  highlightedUsageHtml = html;
196
+ } else {
197
+ highlightAvailable = false;
198
+ highlightedUsageHtml = '';
189
199
  }
190
200
  } catch {
191
- // Fallback: leave previous value
201
+ highlightAvailable = false;
202
+ highlightedUsageHtml = '';
192
203
  }
193
204
  }, 150);
194
205
  });
@@ -5,9 +5,14 @@ import { discoverDocFiles, getSdocKind } from './discovery.js';
5
5
  import { extractSnippets, hasDefaultSnippet } from './snippet-extractor.js';
6
6
  import { base64urlEncode } from './snippet-compiler.js';
7
7
  const __dirname = dirname(fileURLToPath(import.meta.url));
8
- /** Source client directory in the installed package */
8
+ /** Source client directory in the installed package (dist/client, next to dist/server) */
9
9
  function getClientSourceDir() {
10
- return resolve(__dirname, 'client');
10
+ return resolve(__dirname, '../client');
11
+ }
12
+ /** Copy the client app plus the ui/ tree it imports (styles, fonts, components) */
13
+ async function copyClientApp(sdocsDir) {
14
+ await copyDir(getClientSourceDir(), resolve(sdocsDir, 'client'));
15
+ await copyDir(resolve(__dirname, '../ui'), resolve(sdocsDir, 'ui'));
11
16
  }
12
17
  /** Copy a directory recursively */
13
18
  async function copyDir(src, dest) {
@@ -129,7 +134,7 @@ export async function generateDevFiles(config, cwd) {
129
134
  const sdocsDir = resolve(cwd, '.sdocs');
130
135
  await mkdir(sdocsDir, { recursive: true });
131
136
  // Copy client components into .sdocs/client/ so they're compiled outside node_modules
132
- await copyDir(getClientSourceDir(), resolve(sdocsDir, 'client'));
137
+ await copyClientApp(sdocsDir);
133
138
  await writeFile(resolve(sdocsDir, 'index.html'), generateIndexHtml(config.logo));
134
139
  await writeFile(resolve(sdocsDir, 'entry.js'), generateEntryJs(config));
135
140
  return sdocsDir;
@@ -139,7 +144,7 @@ export async function generateBuildFiles(config, cwd) {
139
144
  const sdocsDir = resolve(cwd, '.sdocs');
140
145
  await mkdir(sdocsDir, { recursive: true });
141
146
  // Copy client components into .sdocs/client/
142
- await copyDir(getClientSourceDir(), resolve(sdocsDir, 'client'));
147
+ await copyClientApp(sdocsDir);
143
148
  await writeFile(resolve(sdocsDir, 'index.html'), generateIndexHtml(config.logo));
144
149
  await writeFile(resolve(sdocsDir, 'entry.js'), generateEntryJs(config));
145
150
  const inputs = {
@@ -7,14 +7,30 @@ export declare function resolveImportsToAbsolute(imports: string[], docFilePath:
7
7
  /** Generate a virtual Svelte iframe wrapper component for a snippet.
8
8
  * Includes $state for reactive prop updates via postMessage. */
9
9
  export declare function generateIframeComponent(absoluteImports: string[], snippetBody: string): string;
10
- /** Generate the HTML page served inside the iframe */
10
+ /** The JS that boots a preview page: mount the wrapper + parent-frame messaging. */
11
+ export declare function generateMountScript(iframeComponentId: string): string;
12
+ /** Generate the HTML page served inside the iframe (dev / CLI-build inputs) */
11
13
  export declare function generatePreviewHtml(iframeComponentId: string, css: string | Record<string, string> | null): string;
14
+ export interface StaticCssLink {
15
+ href: string;
16
+ name?: string;
17
+ disabled?: boolean;
18
+ }
19
+ /** Generate the HTML page for a preview emitted into a host app's build. */
20
+ export declare function generateStaticPreviewHtml(scriptSrc: string, cssLinks: StaticCssLink[]): string;
12
21
  /** Build the virtual module ID for an iframe wrapper component */
13
22
  export declare function iframeVirtualId(docFilePath: string, snippetName: string): string;
14
23
  /** Build the preview URL for an iframe HTML page (dev mode) */
15
24
  export declare function previewUrl(docFilePath: string, snippetName: string): string;
16
25
  /** Build the preview URL for static build output */
17
26
  export declare function buildPreviewUrl(docFilePath: string, snippetName: string): string;
27
+ /** Virtual module ID for a preview's mount script (embedded production builds) */
28
+ export declare function mountVirtualId(docFilePath: string, snippetName: string): string;
29
+ /** Parse a mount virtual ID back into its parts */
30
+ export declare function parseMountId(id: string): {
31
+ docFilePath: string;
32
+ snippetName: string;
33
+ } | null;
18
34
  /** Parse an iframe virtual ID back into its parts */
19
35
  export declare function parseIframeId(id: string): {
20
36
  docFilePath: string;
@@ -97,9 +97,27 @@ function generateCssLinks(css) {
97
97
  .map((name, i) => `<link rel="stylesheet" href="${normalizeCssHref(css[name])}" data-sdocs-stylesheet="${name}"${i > 0 ? ' disabled' : ''}>`)
98
98
  .join('\n\t');
99
99
  }
100
- /** Generate the HTML page served inside the iframe */
101
- export function generatePreviewHtml(iframeComponentId, css) {
102
- const cssLinks = generateCssLinks(css);
100
+ /** The JS that boots a preview page: mount the wrapper + parent-frame messaging. */
101
+ export function generateMountScript(iframeComponentId) {
102
+ return `import { mount } from 'svelte';
103
+ import App from '${iframeComponentId}';
104
+ mount(App, { target: document.getElementById('app') });
105
+
106
+ // Listen for sdocs messages from the parent frame
107
+ window.addEventListener('message', (e) => {
108
+ if (e.data?.type === 'sdocs:update-stylesheet') {
109
+ const name = e.data.name;
110
+ document.querySelectorAll('link[data-sdocs-stylesheet]').forEach((link) => {
111
+ link.disabled = link.dataset.sdocsStylesheet !== name;
112
+ });
113
+ }
114
+ if (e.data?.type === 'sdocs:scroll-to') {
115
+ const el = document.getElementById(e.data.id);
116
+ if (el) el.scrollIntoView({ behavior: 'smooth' });
117
+ }
118
+ });`;
119
+ }
120
+ function previewHtmlShell(cssLinks, script) {
103
121
  return `<!DOCTYPE html>
104
122
  <html>
105
123
  <head>
@@ -110,28 +128,26 @@ export function generatePreviewHtml(iframeComponentId, css) {
110
128
  </head>
111
129
  <body>
112
130
  <div id="app"></div>
113
- <script type="module">
114
- import { mount } from 'svelte';
115
- import App from '${iframeComponentId}';
116
- mount(App, { target: document.getElementById('app') });
117
-
118
- // Listen for sdocs messages from the parent frame
119
- window.addEventListener('message', (e) => {
120
- if (e.data?.type === 'sdocs:update-stylesheet') {
121
- const name = e.data.name;
122
- document.querySelectorAll('link[data-sdocs-stylesheet]').forEach((link) => {
123
- link.disabled = link.dataset.sdocsStylesheet !== name;
124
- });
125
- }
126
- if (e.data?.type === 'sdocs:scroll-to') {
127
- const el = document.getElementById(e.data.id);
128
- if (el) el.scrollIntoView({ behavior: 'smooth' });
129
- }
130
- });
131
- </script>
131
+ ${script}
132
132
  </body>
133
133
  </html>`;
134
134
  }
135
+ /** Generate the HTML page served inside the iframe (dev / CLI-build inputs) */
136
+ export function generatePreviewHtml(iframeComponentId, css) {
137
+ return previewHtmlShell(generateCssLinks(css), `<script type="module">
138
+ ${generateMountScript(iframeComponentId)}
139
+ </script>`);
140
+ }
141
+ /** Generate the HTML page for a preview emitted into a host app's build. */
142
+ export function generateStaticPreviewHtml(scriptSrc, cssLinks) {
143
+ const links = cssLinks
144
+ .map(({ href, name, disabled }) => {
145
+ const named = name ? ` data-sdocs-stylesheet="${name}"` : '';
146
+ return `<link rel="stylesheet" href="${href}"${named}${disabled ? ' disabled' : ''}>`;
147
+ })
148
+ .join('\n\t');
149
+ return previewHtmlShell(links, `<script type="module" src="${scriptSrc}"></script>`);
150
+ }
135
151
  /** Build the virtual module ID for an iframe wrapper component */
136
152
  export function iframeVirtualId(docFilePath, snippetName) {
137
153
  return `/@sdocs/iframe/${base64urlEncode(docFilePath)}/${snippetName}.svelte`;
@@ -144,6 +160,20 @@ export function previewUrl(docFilePath, snippetName) {
144
160
  export function buildPreviewUrl(docFilePath, snippetName) {
145
161
  return `/previews/${base64urlEncode(docFilePath)}/${snippetName}.html`;
146
162
  }
163
+ /** Virtual module ID for a preview's mount script (embedded production builds) */
164
+ export function mountVirtualId(docFilePath, snippetName) {
165
+ return `/@sdocs/mount/${base64urlEncode(docFilePath)}/${snippetName}.js`;
166
+ }
167
+ /** Parse a mount virtual ID back into its parts */
168
+ export function parseMountId(id) {
169
+ const match = id.match(/^\/@sdocs\/mount\/([^/]+)\/(\w+)\.js$/);
170
+ if (!match)
171
+ return null;
172
+ return {
173
+ docFilePath: base64urlDecode(match[1]),
174
+ snippetName: match[2],
175
+ };
176
+ }
147
177
  /** Parse an iframe virtual ID back into its parts */
148
178
  export function parseIframeId(id) {
149
179
  const match = id.match(/^\/@sdocs\/iframe\/([^/]+)\/(\w+)\.svelte$/);
package/dist/vite.js CHANGED
@@ -6,11 +6,12 @@ import { parseComponent } from './server/prop-parser.js';
6
6
  import { extractSnippets, extractMarkupBody, hasDefaultSnippet, generateAutoDefault, } from './server/snippet-extractor.js';
7
7
  import { highlight, disposeHighlighter } from './server/highlighter.js';
8
8
  import { extractTocFromHtml } from './server/toc-extractor.js';
9
- import { parseIframeId, parsePreviewUrl, resolveImportsToAbsolute, generateIframeComponent, generatePreviewHtml, iframeVirtualId, previewUrl, buildPreviewUrl, } from './server/snippet-compiler.js';
9
+ import { parseIframeId, parseMountId, parsePreviewUrl, resolveImportsToAbsolute, generateIframeComponent, generateMountScript, generatePreviewHtml, generateStaticPreviewHtml, iframeVirtualId, mountVirtualId, previewUrl, buildPreviewUrl, base64urlEncode, } from './server/snippet-compiler.js';
10
10
  const VIRTUAL_MODULE_ID = 'virtual:sdocs';
11
11
  const RESOLVED_VIRTUAL_ID = '\0virtual:sdocs';
12
12
  const IFRAME_PREFIX = '/@sdocs/iframe/';
13
13
  const PREVIEW_PREFIX = '/@sdocs/preview/';
14
+ const MOUNT_PREFIX = '/@sdocs/mount/';
14
15
  export function sdocsPlugin(userConfig) {
15
16
  let config;
16
17
  let root;
@@ -18,10 +19,17 @@ export function sdocsPlugin(userConfig) {
18
19
  let docEntries = new Map();
19
20
  let docImportsCache = new Map();
20
21
  const buildMode = userConfig?._buildMode ?? false;
22
+ let isBuild = false;
23
+ let isSsrBuild = false;
24
+ // Previews planned for emission into a host app's build (embedded mode)
25
+ let plannedPreviews = [];
26
+ let emittedCssLinks = [];
21
27
  return {
22
28
  name: 'sdocs',
23
29
  async configResolved(resolvedConfig) {
24
30
  root = resolvedConfig.root;
31
+ isBuild = resolvedConfig.command === 'build';
32
+ isSsrBuild = !!resolvedConfig.build?.ssr;
25
33
  const fileConfig = await loadRawConfig(root);
26
34
  const merged = { ...fileConfig, ...userConfig };
27
35
  config = resolveAndFinalize(merged, root);
@@ -125,12 +133,85 @@ export function sdocsPlugin(userConfig) {
125
133
  server.watcher.add(dir);
126
134
  }
127
135
  }
136
+ // Embedded production build: emit each preview as its own chunk so the
137
+ // host app's build output contains working static preview pages. (The
138
+ // standalone CLI build passes _buildMode and provides HTML inputs itself;
139
+ // the SSR half of an app build has no use for browser preview pages.)
140
+ if (isBuild && !buildMode && !isSsrBuild) {
141
+ plannedPreviews = [];
142
+ emittedCssLinks = [];
143
+ const css = config.css;
144
+ if (typeof css === 'string') {
145
+ emittedCssLinks.push({ href: await emitCssAsset(this, css, 'preview') });
146
+ }
147
+ else if (css) {
148
+ for (const [i, name] of Object.keys(css).entries()) {
149
+ emittedCssLinks.push({
150
+ href: await emitCssAsset(this, css[name], name),
151
+ name,
152
+ disabled: i > 0,
153
+ });
154
+ }
155
+ }
156
+ for (const entry of docEntries.values()) {
157
+ const encoded = base64urlEncode(entry.filePath);
158
+ for (const snippet of entry.snippets) {
159
+ const jsFileName = `previews/${encoded}/${snippet.name}.js`;
160
+ this.emitFile({
161
+ type: 'chunk',
162
+ id: mountVirtualId(entry.filePath, snippet.name),
163
+ fileName: jsFileName,
164
+ });
165
+ plannedPreviews.push({
166
+ jsFileName,
167
+ htmlFileName: `previews/${encoded}/${snippet.name}.html`,
168
+ });
169
+ }
170
+ }
171
+ console.log(`[sdocs] Emitting ${plannedPreviews.length} static preview page(s)`);
172
+ }
173
+ },
174
+ generateBundle(_options, bundle) {
175
+ for (const preview of plannedPreviews) {
176
+ const chunk = bundle[preview.jsFileName];
177
+ if (!chunk || chunk.type !== 'chunk')
178
+ continue;
179
+ // Collect CSS emitted for this chunk and everything it imports.
180
+ const cssFiles = new Set();
181
+ const queue = [preview.jsFileName];
182
+ const seen = new Set();
183
+ while (queue.length) {
184
+ const fileName = queue.pop();
185
+ if (seen.has(fileName))
186
+ continue;
187
+ seen.add(fileName);
188
+ const mod = bundle[fileName];
189
+ if (!mod || mod.type !== 'chunk')
190
+ continue;
191
+ for (const css of mod.viteMetadata?.importedCss ?? [])
192
+ cssFiles.add(css);
193
+ queue.push(...mod.imports);
194
+ }
195
+ // The HTML sits at previews/<doc>/<name>.html — two levels deep.
196
+ const cssLinks = [
197
+ ...emittedCssLinks,
198
+ ...[...cssFiles].map((file) => ({ href: `../../${file}` })),
199
+ ];
200
+ this.emitFile({
201
+ type: 'asset',
202
+ fileName: preview.htmlFileName,
203
+ source: generateStaticPreviewHtml(`./${preview.jsFileName.split('/').pop()}`, cssLinks),
204
+ });
205
+ }
206
+ plannedPreviews = [];
128
207
  },
129
208
  resolveId(id) {
130
209
  if (id === VIRTUAL_MODULE_ID)
131
210
  return RESOLVED_VIRTUAL_ID;
132
211
  if (id.startsWith(IFRAME_PREFIX))
133
212
  return '\0' + id;
213
+ if (id.startsWith(MOUNT_PREFIX))
214
+ return '\0' + id;
134
215
  },
135
216
  load(id) {
136
217
  if (id === RESOLVED_VIRTUAL_ID) {
@@ -151,6 +232,13 @@ export function sdocsPlugin(userConfig) {
151
232
  const absoluteImports = docImportsCache.get(parsed.docFilePath) ?? [];
152
233
  return generateIframeComponent(absoluteImports, snippet.body);
153
234
  }
235
+ // Virtual mount script for an emitted preview page
236
+ if (id.startsWith('\0' + MOUNT_PREFIX)) {
237
+ const parsed = parseMountId(id.slice(1));
238
+ if (!parsed)
239
+ return null;
240
+ return generateMountScript(iframeVirtualId(parsed.docFilePath, parsed.snippetName));
241
+ }
154
242
  },
155
243
  async buildEnd() {
156
244
  await disposeHighlighter();
@@ -232,7 +320,9 @@ export function sdocsPlugin(userConfig) {
232
320
  name: s.name,
233
321
  body: s.body,
234
322
  highlightedHtml: s.highlightedHtml,
235
- previewUrl: buildMode ? buildPreviewUrl(e.filePath, s.name) : previewUrl(e.filePath, s.name),
323
+ previewUrl: buildMode || isBuild
324
+ ? buildPreviewUrl(e.filePath, s.name)
325
+ : previewUrl(e.filePath, s.name),
236
326
  })),
237
327
  highlightedSource: e.highlightedSource,
238
328
  toc: e.toc,
@@ -269,6 +359,15 @@ export function sdocsPlugin(userConfig) {
269
359
  function isDocFile(filePath) {
270
360
  return filePath.endsWith('.sdoc');
271
361
  }
362
+ /** Emit a user stylesheet as a build asset; returns its href relative to a preview page. */
363
+ async function emitCssAsset(ctx, href, name) {
364
+ if (href.startsWith('http'))
365
+ return href;
366
+ const source = await readFile(href, 'utf-8');
367
+ const fileName = `previews/_css/${name}.css`;
368
+ ctx.emitFile({ type: 'asset', fileName, source });
369
+ return `../../${fileName}`;
370
+ }
272
371
  function isComponentReferencedByDoc(filePath) {
273
372
  for (const entry of docEntries.values()) {
274
373
  if (entry.componentPath === filePath)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sdocs",
3
- "version": "0.0.25",
3
+ "version": "0.0.26",
4
4
  "description": "A lightweight documentation tool for Svelte 5 components",
5
5
  "type": "module",
6
6
  "license": "MIT",