@thedatagrid/docs-kit 0.0.0-stage → 0.1.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.
Files changed (175) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +123 -2
  3. package/dist/code/demoFiles.d.ts +14 -0
  4. package/dist/code/demoFiles.d.ts.map +1 -0
  5. package/dist/code/demoFiles.js +46 -0
  6. package/dist/code/demoFiles.js.map +1 -0
  7. package/dist/code/heights.d.ts +17 -0
  8. package/dist/code/heights.d.ts.map +1 -0
  9. package/dist/code/heights.js +40 -0
  10. package/dist/code/heights.js.map +1 -0
  11. package/dist/code/highlightSpec.d.ts +34 -0
  12. package/dist/code/highlightSpec.d.ts.map +1 -0
  13. package/dist/code/highlightSpec.js +119 -0
  14. package/dist/code/highlightSpec.js.map +1 -0
  15. package/dist/code/imports.d.ts +5 -0
  16. package/dist/code/imports.d.ts.map +1 -0
  17. package/dist/code/imports.js +17 -0
  18. package/dist/code/imports.js.map +1 -0
  19. package/dist/code/index.d.ts +8 -0
  20. package/dist/code/index.d.ts.map +1 -0
  21. package/dist/code/index.js +8 -0
  22. package/dist/code/index.js.map +1 -0
  23. package/dist/code/lineRanges.d.ts +5 -0
  24. package/dist/code/lineRanges.d.ts.map +1 -0
  25. package/dist/code/lineRanges.js +35 -0
  26. package/dist/code/lineRanges.js.map +1 -0
  27. package/dist/code/regions.d.ts +53 -0
  28. package/dist/code/regions.d.ts.map +1 -0
  29. package/dist/code/regions.js +237 -0
  30. package/dist/code/regions.js.map +1 -0
  31. package/dist/code/shiki.d.ts +58 -0
  32. package/dist/code/shiki.d.ts.map +1 -0
  33. package/dist/code/shiki.js +244 -0
  34. package/dist/code/shiki.js.map +1 -0
  35. package/dist/demos/build.d.ts +17 -0
  36. package/dist/demos/build.d.ts.map +1 -0
  37. package/dist/demos/build.js +426 -0
  38. package/dist/demos/build.js.map +1 -0
  39. package/dist/demos/cli.d.ts +3 -0
  40. package/dist/demos/cli.d.ts.map +1 -0
  41. package/dist/demos/cli.js +68 -0
  42. package/dist/demos/cli.js.map +1 -0
  43. package/dist/demos/client.d.ts +27 -0
  44. package/dist/demos/client.d.ts.map +1 -0
  45. package/dist/demos/client.js +61 -0
  46. package/dist/demos/client.js.map +1 -0
  47. package/dist/demos/compile/core.d.ts +64 -0
  48. package/dist/demos/compile/core.d.ts.map +1 -0
  49. package/dist/demos/compile/core.js +174 -0
  50. package/dist/demos/compile/core.js.map +1 -0
  51. package/dist/demos/config.d.ts +108 -0
  52. package/dist/demos/config.d.ts.map +1 -0
  53. package/dist/demos/config.js +4 -0
  54. package/dist/demos/config.js.map +1 -0
  55. package/dist/demos/devEvents.d.ts +13 -0
  56. package/dist/demos/devEvents.d.ts.map +1 -0
  57. package/dist/demos/devEvents.js +45 -0
  58. package/dist/demos/devEvents.js.map +1 -0
  59. package/dist/demos/html.d.ts +21 -0
  60. package/dist/demos/html.d.ts.map +1 -0
  61. package/dist/demos/html.js +57 -0
  62. package/dist/demos/html.js.map +1 -0
  63. package/dist/demos/index.d.ts +8 -0
  64. package/dist/demos/index.d.ts.map +1 -0
  65. package/dist/demos/index.js +6 -0
  66. package/dist/demos/index.js.map +1 -0
  67. package/dist/demos/pages.d.ts +15 -0
  68. package/dist/demos/pages.d.ts.map +1 -0
  69. package/dist/demos/pages.js +71 -0
  70. package/dist/demos/pages.js.map +1 -0
  71. package/dist/demos/runtime/iframe.d.ts +50 -0
  72. package/dist/demos/runtime/iframe.d.ts.map +1 -0
  73. package/dist/demos/runtime/iframe.js +245 -0
  74. package/dist/demos/runtime/iframe.js.map +1 -0
  75. package/dist/demos/runtime/react.d.ts +3 -0
  76. package/dist/demos/runtime/react.d.ts.map +1 -0
  77. package/dist/demos/runtime/react.js +17 -0
  78. package/dist/demos/runtime/react.js.map +1 -0
  79. package/dist/demos/slug.d.ts +3 -0
  80. package/dist/demos/slug.d.ts.map +1 -0
  81. package/dist/demos/slug.js +11 -0
  82. package/dist/demos/slug.js.map +1 -0
  83. package/dist/demos/vendor.d.ts +32 -0
  84. package/dist/demos/vendor.d.ts.map +1 -0
  85. package/dist/demos/vendor.js +127 -0
  86. package/dist/demos/vendor.js.map +1 -0
  87. package/dist/demos/worker/compile.worker.d.ts +2 -0
  88. package/dist/demos/worker/compile.worker.d.ts.map +1 -0
  89. package/dist/demos/worker/compile.worker.js +27 -0
  90. package/dist/demos/worker/compile.worker.js.map +1 -0
  91. package/dist/fork/codesandbox.d.ts +39 -0
  92. package/dist/fork/codesandbox.d.ts.map +1 -0
  93. package/dist/fork/codesandbox.js +156 -0
  94. package/dist/fork/codesandbox.js.map +1 -0
  95. package/dist/fork/index.d.ts +2 -0
  96. package/dist/fork/index.d.ts.map +1 -0
  97. package/dist/fork/index.js +2 -0
  98. package/dist/fork/index.js.map +1 -0
  99. package/dist/react/Demo.d.ts +80 -0
  100. package/dist/react/Demo.d.ts.map +1 -0
  101. package/dist/react/Demo.js +156 -0
  102. package/dist/react/Demo.js.map +1 -0
  103. package/dist/react/DemoIframe.d.ts +22 -0
  104. package/dist/react/DemoIframe.d.ts.map +1 -0
  105. package/dist/react/DemoIframe.js +123 -0
  106. package/dist/react/DemoIframe.js.map +1 -0
  107. package/dist/react/DemoShell.d.ts +47 -0
  108. package/dist/react/DemoShell.d.ts.map +1 -0
  109. package/dist/react/DemoShell.js +341 -0
  110. package/dist/react/DemoShell.js.map +1 -0
  111. package/dist/react/devEvents.d.ts +17 -0
  112. package/dist/react/devEvents.d.ts.map +1 -0
  113. package/dist/react/devEvents.js +30 -0
  114. package/dist/react/devEvents.js.map +1 -0
  115. package/dist/react/editor.d.ts +8 -0
  116. package/dist/react/editor.d.ts.map +1 -0
  117. package/dist/react/editor.js +52 -0
  118. package/dist/react/editor.js.map +1 -0
  119. package/dist/react/fork.d.ts +10 -0
  120. package/dist/react/fork.d.ts.map +1 -0
  121. package/dist/react/fork.js +30 -0
  122. package/dist/react/fork.js.map +1 -0
  123. package/dist/react/index.d.ts +4 -0
  124. package/dist/react/index.d.ts.map +1 -0
  125. package/dist/react/index.js +4 -0
  126. package/dist/react/index.js.map +1 -0
  127. package/dist/react/styles.css +493 -0
  128. package/dist/remark/index.d.ts +3 -0
  129. package/dist/remark/index.d.ts.map +1 -0
  130. package/dist/remark/index.js +3 -0
  131. package/dist/remark/index.js.map +1 -0
  132. package/dist/remark/meta.d.ts +7 -0
  133. package/dist/remark/meta.d.ts.map +1 -0
  134. package/dist/remark/meta.js +20 -0
  135. package/dist/remark/meta.js.map +1 -0
  136. package/dist/remark/remarkDemoFences.d.ts +77 -0
  137. package/dist/remark/remarkDemoFences.d.ts.map +1 -0
  138. package/dist/remark/remarkDemoFences.js +259 -0
  139. package/dist/remark/remarkDemoFences.js.map +1 -0
  140. package/package.json +106 -4
  141. package/src/code/demoFiles.ts +54 -0
  142. package/src/code/heights.ts +47 -0
  143. package/src/code/highlightSpec.ts +139 -0
  144. package/src/code/imports.ts +18 -0
  145. package/src/code/index.ts +46 -0
  146. package/src/code/lineRanges.ts +31 -0
  147. package/src/code/regions.ts +270 -0
  148. package/src/code/shiki.ts +271 -0
  149. package/src/demos/build.ts +477 -0
  150. package/src/demos/cli.ts +64 -0
  151. package/src/demos/client.ts +82 -0
  152. package/src/demos/compile/core.ts +228 -0
  153. package/src/demos/config.ts +106 -0
  154. package/src/demos/devEvents.ts +45 -0
  155. package/src/demos/html.ts +74 -0
  156. package/src/demos/index.ts +25 -0
  157. package/src/demos/pages.ts +79 -0
  158. package/src/demos/runtime/iframe.ts +262 -0
  159. package/src/demos/runtime/react.ts +19 -0
  160. package/src/demos/slug.ts +10 -0
  161. package/src/demos/vendor.ts +142 -0
  162. package/src/demos/worker/compile.worker.ts +35 -0
  163. package/src/fork/codesandbox.ts +189 -0
  164. package/src/fork/index.ts +10 -0
  165. package/src/react/Demo.tsx +250 -0
  166. package/src/react/DemoIframe.tsx +165 -0
  167. package/src/react/DemoShell.tsx +592 -0
  168. package/src/react/devEvents.ts +34 -0
  169. package/src/react/editor.ts +61 -0
  170. package/src/react/fork.ts +31 -0
  171. package/src/react/index.ts +10 -0
  172. package/src/react/styles.css +493 -0
  173. package/src/remark/index.ts +2 -0
  174. package/src/remark/meta.ts +20 -0
  175. package/src/remark/remarkDemoFences.ts +330 -0
@@ -0,0 +1,262 @@
1
+ /**
2
+ * Runs inside every demo iframe (bundled by the builder together with the
3
+ * framework adapter and the site's bootstrap module).
4
+ *
5
+ * Parent → iframe messages:
6
+ * { type: 'set-theme', theme } docs light/dark changed
7
+ * { type: 'demo-reset' } unmount + clear persisted keys
8
+ * { type: 'demo-update', js, css } run an edited build in place
9
+ * { type: 'demo-compile-error', message } show compile errors
10
+ * Iframe → parent:
11
+ * demo-ready, demo-error { message }, demo-escape, demo-reset-done
12
+ */
13
+
14
+ export type DocsTheme = 'light' | 'dark';
15
+
16
+ export type MountedDemo = { unmount(): void };
17
+
18
+ /** Framework glue: renders a demo module's default export into an element. */
19
+ export type DemoAdapter = {
20
+ render(target: HTMLElement, component: unknown, onError: (error: unknown) => void): MountedDemo;
21
+ };
22
+
23
+ /** The site's bootstrap module (`bootstrap` in docs-kit.config). All hooks are optional. */
24
+ export type SiteBootstrap = {
25
+ /** Called once, before the first mount. */
26
+ setup?(context: { theme: DocsTheme }): void | Promise<void>;
27
+ /** Called on load and whenever the docs theme changes. */
28
+ applyTheme?(theme: DocsTheme): void;
29
+ };
30
+
31
+ export type RuntimeOptions = {
32
+ adapter: DemoAdapter;
33
+ site: SiteBootstrap;
34
+ /** localStorage key the docs site keeps its theme under. */
35
+ themeStorageKey?: string;
36
+ defaultTheme?: DocsTheme;
37
+ /** Classes on `<html>` per theme. */
38
+ themeClasses?: { light?: string[]; dark?: string[] };
39
+ };
40
+
41
+ const post = (message: Record<string, unknown>) => {
42
+ try {
43
+ parent.postMessage(message, '*');
44
+ } catch {
45
+ // standalone page without a parent - nothing to tell
46
+ }
47
+ };
48
+
49
+ export function resolveTheme(storageKey: string | undefined, fallback: DocsTheme): DocsTheme {
50
+ try {
51
+ const fromQuery = new URLSearchParams(location.search).get('theme');
52
+ if (fromQuery === 'dark' || fromQuery === 'light') return fromQuery;
53
+ const stored = storageKey ? localStorage.getItem(storageKey) : null;
54
+ if (stored === 'dark' || stored === 'light') return stored;
55
+ if (window.matchMedia?.('(prefers-color-scheme: dark)').matches) return 'dark';
56
+ } catch {
57
+ // storage blocked
58
+ }
59
+ return fallback;
60
+ }
61
+
62
+ let overlay: HTMLDivElement | null = null;
63
+
64
+ function showOverlay(title: string, message: string) {
65
+ if (!overlay) {
66
+ overlay = document.createElement('div');
67
+ overlay.id = 'dk-error-overlay';
68
+ overlay.setAttribute('role', 'alert');
69
+ document.body.appendChild(overlay);
70
+ }
71
+ overlay.replaceChildren();
72
+ const heading = document.createElement('div');
73
+ heading.className = 'dk-error-title';
74
+ heading.textContent = title;
75
+ const close = document.createElement('button');
76
+ close.type = 'button';
77
+ close.textContent = '×';
78
+ close.title = 'Dismiss';
79
+ close.addEventListener('click', hideOverlay);
80
+ heading.appendChild(close);
81
+ const body = document.createElement('pre');
82
+ body.textContent = message;
83
+ overlay.append(heading, body);
84
+ }
85
+
86
+ function hideOverlay() {
87
+ overlay?.remove();
88
+ overlay = null;
89
+ }
90
+
91
+ function errorText(error: unknown): string {
92
+ if (error instanceof Error) return error.stack || `${error.name}: ${error.message}`;
93
+ return String(error);
94
+ }
95
+
96
+ export function createRuntime(options: RuntimeOptions) {
97
+ const { adapter, site, themeStorageKey, defaultTheme = 'light', themeClasses = {} } = options;
98
+ const root = () => document.getElementById('root')!;
99
+
100
+ const applyTheme = (theme: DocsTheme) => {
101
+ const html = document.documentElement;
102
+ html.setAttribute('data-theme', theme);
103
+ html.style.colorScheme = theme;
104
+ html.classList.remove(...(themeClasses.light ?? []), ...(themeClasses.dark ?? []));
105
+ html.classList.add(...(themeClasses[theme] ?? []));
106
+ site.applyTheme?.(theme);
107
+ };
108
+
109
+ // Every localStorage key the demo writes, so "reset" can clear them. Patched
110
+ // on the prototype: assigning localStorage.setItem would store an item
111
+ // named "setItem".
112
+ const writtenKeys = new Set<string>();
113
+ let resetting = false;
114
+ try {
115
+ const setItem = Storage.prototype.setItem;
116
+ Storage.prototype.setItem = function (this: Storage, key: string, value: string) {
117
+ if (this === localStorage) {
118
+ if (resetting) return;
119
+ writtenKeys.add(String(key));
120
+ }
121
+ return setItem.call(this, key, value);
122
+ };
123
+ } catch {
124
+ // storage unavailable
125
+ }
126
+
127
+ window.addEventListener('error', (event) => {
128
+ const message = errorText(event.error ?? event.message);
129
+ showOverlay('Runtime error', message);
130
+ post({ type: 'demo-error', message });
131
+ });
132
+ window.addEventListener('unhandledrejection', (event) => {
133
+ const message = errorText(event.reason);
134
+ showOverlay('Unhandled promise rejection', message);
135
+ post({ type: 'demo-error', message });
136
+ });
137
+ window.addEventListener(
138
+ 'keydown',
139
+ (event) => {
140
+ if (event.key === 'Escape') post({ type: 'demo-escape' });
141
+ },
142
+ true,
143
+ );
144
+
145
+ let mounted: MountedDemo | null = null;
146
+ let editedStyle: HTMLStyleElement | null = null;
147
+ let editedUrl: string | null = null;
148
+ let generation = 0;
149
+
150
+ const render = (component: unknown) => {
151
+ try {
152
+ mounted?.unmount();
153
+ } catch {
154
+ // a broken demo can throw on unmount; the next render replaces it anyway
155
+ }
156
+ mounted = null;
157
+ root().replaceChildren();
158
+ mounted = adapter.render(root(), component, (error) => {
159
+ const message = errorText(error);
160
+ showOverlay('Render error', message);
161
+ post({ type: 'demo-error', message });
162
+ });
163
+ };
164
+
165
+ const runEdited = async (js: string, css: string) => {
166
+ const current = ++generation;
167
+ const url = URL.createObjectURL(new Blob([js], { type: 'text/javascript' }));
168
+ try {
169
+ // Bare imports in the edited module resolve through this document's import map.
170
+ const mod = (await import(/* @vite-ignore */ url)) as { default?: unknown };
171
+ if (current !== generation) return;
172
+ if (!mod.default) throw new Error('The demo entry file has no default export');
173
+ if (editedStyle) editedStyle.remove();
174
+ editedStyle = null;
175
+ // The prebuilt demo's own stylesheet no longer matches the edited code.
176
+ document.querySelectorAll('link[data-demo-css]').forEach((link) => link.remove());
177
+ if (css) {
178
+ editedStyle = document.createElement('style');
179
+ editedStyle.dataset.demoEdited = '';
180
+ editedStyle.textContent = css;
181
+ document.head.appendChild(editedStyle);
182
+ }
183
+ hideOverlay();
184
+ render(mod.default);
185
+ } catch (error) {
186
+ if (current !== generation) return;
187
+ const message = errorText(error);
188
+ showOverlay('Runtime error', message);
189
+ post({ type: 'demo-error', message });
190
+ } finally {
191
+ if (editedUrl) URL.revokeObjectURL(editedUrl);
192
+ editedUrl = url;
193
+ }
194
+ };
195
+
196
+ window.addEventListener('message', (event) => {
197
+ const data = event.data as { type?: string; [key: string]: unknown } | null;
198
+ if (!data || typeof data.type !== 'string') return;
199
+ switch (data.type) {
200
+ case 'set-theme':
201
+ applyTheme(data.theme === 'dark' ? 'dark' : 'light');
202
+ break;
203
+ case 'demo-reset':
204
+ resetting = true;
205
+ try {
206
+ mounted?.unmount();
207
+ } catch {
208
+ // ignore
209
+ }
210
+ mounted = null;
211
+ for (const key of writtenKeys) {
212
+ try {
213
+ localStorage.removeItem(key);
214
+ } catch {
215
+ // ignore
216
+ }
217
+ }
218
+ post({ type: 'demo-reset-done' });
219
+ break;
220
+ case 'demo-update':
221
+ void runEdited(String(data.js ?? ''), String(data.css ?? ''));
222
+ break;
223
+ case 'demo-compile-error':
224
+ showOverlay('Compile error', String(data.message ?? 'Unknown error'));
225
+ break;
226
+ }
227
+ });
228
+
229
+ return {
230
+ /** The demo module failed to load (syntax/runtime error at import). */
231
+ fail(error: unknown) {
232
+ const message = errorText(error);
233
+ showOverlay('The demo failed to load', message);
234
+ post({ type: 'demo-error', message });
235
+ post({ type: 'demo-ready' });
236
+ },
237
+ async mount(component: unknown) {
238
+ const theme = resolveTheme(themeStorageKey, defaultTheme);
239
+ applyTheme(theme);
240
+ try {
241
+ await site.setup?.({ theme });
242
+ render(component);
243
+ } catch (error) {
244
+ const message = errorText(error);
245
+ showOverlay('Runtime error', message);
246
+ post({ type: 'demo-error', message });
247
+ }
248
+ requestAnimationFrame(() => requestAnimationFrame(() => post({ type: 'demo-ready' })));
249
+ },
250
+ };
251
+ }
252
+
253
+ /** Styles for the error overlay (inlined into every demo page). */
254
+ export const OVERLAY_CSS = `
255
+ #dk-error-overlay { position: fixed; inset: 8px; z-index: 2147483600; display: flex; flex-direction: column;
256
+ background: rgba(20, 20, 24, 0.94); color: #ffd7d7; border: 1px solid #ff6b6b; border-radius: 8px;
257
+ font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; overflow: hidden; }
258
+ #dk-error-overlay .dk-error-title { display: flex; justify-content: space-between; align-items: center;
259
+ padding: 8px 12px; font-weight: 600; color: #ff8b8b; border-bottom: 1px solid rgba(255, 107, 107, 0.35); }
260
+ #dk-error-overlay button { all: unset; cursor: pointer; font-size: 18px; line-height: 1; padding: 0 4px; color: #ffd7d7; }
261
+ #dk-error-overlay pre { margin: 0; padding: 12px; overflow: auto; white-space: pre-wrap; flex: 1; }
262
+ `;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * React adapter for the iframe runtime. `react` and `react-dom/client` stay
3
+ * bare imports: the builder externalizes them, so the iframe's import map
4
+ * hands the runtime and the demo the same React instance.
5
+ */
6
+ import { createElement, type ComponentType } from 'react';
7
+ import { createRoot } from 'react-dom/client';
8
+
9
+ import type { DemoAdapter } from './iframe.ts';
10
+
11
+ export const reactAdapter: DemoAdapter = {
12
+ render(target, component, onError) {
13
+ const root = createRoot(target, {
14
+ onUncaughtError: (error: unknown) => onError(error),
15
+ } as Parameters<typeof createRoot>[1]);
16
+ root.render(createElement(component as ComponentType));
17
+ return { unmount: () => root.unmount() };
18
+ },
19
+ };
@@ -0,0 +1,10 @@
1
+ /** URL hash slug of a demo card: "Your first grid" → `your-first-grid`, `basic.demo.tsx` → `basic-demo`. */
2
+ export function slugifyDemoTitle(text: string): string {
3
+ return text
4
+ .trim()
5
+ .replace(/\.[jt]sx?$/i, '')
6
+ .toLowerCase()
7
+ .replace(/['’]/g, '')
8
+ .replace(/[^a-z0-9]+/g, '-')
9
+ .replace(/^-+|-+$/g, '');
10
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The import-map side of the demo build: every package the demos (and the
3
+ * iframe runtime) import becomes one ESM entry under `<outDir>/_lib/`, built
4
+ * in a single esbuild pass with code splitting, so React and friends exist
5
+ * once and are shared by every entry, demo and edited rebuild.
6
+ */
7
+ import fs from 'node:fs';
8
+ import { createRequire } from 'node:module';
9
+ import path from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+ import type { Plugin } from 'esbuild';
12
+
13
+ import { matchesStub } from './compile/core.ts';
14
+ import type { LibrarySource } from './config.ts';
15
+
16
+ const VALID_IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
17
+ const RESERVED = new Set(
18
+ 'break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await'.split(
19
+ ' ',
20
+ ),
21
+ );
22
+
23
+ /** `@scope/pkg/sub` → `scope__pkg__sub`, safe as an output file name. */
24
+ export function entryNameFor(specifier: string): string {
25
+ return specifier.replace(/^@/, '').replace(/\//g, '__').replace(/[^\w.-]/g, '_');
26
+ }
27
+
28
+ type ExportShape = { names: string[]; hasDefault: boolean } | null;
29
+
30
+ /**
31
+ * Export names of an npm package, read by loading it in Node. CommonJS
32
+ * packages (React…) have no static ESM names, so the wrapper entry lists them.
33
+ */
34
+ async function readExportShape(specifier: string, root: string, nodePaths: string[]): Promise<ExportShape> {
35
+ const require = createRequire(path.join(root, 'package.json'));
36
+ let resolved: string;
37
+ try {
38
+ resolved = require.resolve(specifier, { paths: [root, ...nodePaths.map((p) => path.dirname(p))] });
39
+ } catch {
40
+ return null;
41
+ }
42
+ let mod: unknown;
43
+ try {
44
+ mod = require(resolved);
45
+ } catch {
46
+ try {
47
+ mod = await import(pathToFileURL(resolved).href);
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+ if (mod == null || (typeof mod !== 'object' && typeof mod !== 'function')) {
53
+ return { names: [], hasDefault: true };
54
+ }
55
+ const isNamespace = (mod as { [Symbol.toStringTag]?: string })[Symbol.toStringTag] === 'Module';
56
+ const names = Object.keys(mod).filter(
57
+ (name) => name !== 'default' && name !== '__esModule' && VALID_IDENTIFIER.test(name) && !RESERVED.has(name),
58
+ );
59
+ return { names, hasDefault: isNamespace ? 'default' in (mod as object) : true };
60
+ }
61
+
62
+ export type VendorEntries = {
63
+ /** esbuild entry name → wrapper file. */
64
+ entryPoints: Record<string, string>;
65
+ /** esbuild entry name → specifier. */
66
+ specifierByEntry: Record<string, string>;
67
+ };
68
+
69
+ /** Writes one wrapper module per specifier into `workDir`. */
70
+ export async function writeVendorEntries(options: {
71
+ specifiers: string[];
72
+ libraries: Record<string, LibrarySource>;
73
+ root: string;
74
+ nodePaths: string[];
75
+ workDir: string;
76
+ warn: (message: string) => void;
77
+ }): Promise<VendorEntries> {
78
+ const { specifiers, libraries, root, nodePaths, workDir, warn } = options;
79
+ fs.mkdirSync(workDir, { recursive: true });
80
+ const entryPoints: Record<string, string> = {};
81
+ const specifierByEntry: Record<string, string> = {};
82
+
83
+ for (const specifier of [...specifiers].sort()) {
84
+ const name = entryNameFor(specifier);
85
+ const file = path.join(workDir, `${name}.mjs`);
86
+ let contents: string;
87
+ const library = libraries[specifier];
88
+ if (library) {
89
+ contents = `export * from ${JSON.stringify(path.resolve(root, library.entry))};\n`;
90
+ } else {
91
+ const shape = await readExportShape(specifier, root, nodePaths);
92
+ if (!shape) {
93
+ warn(`could not load "${specifier}" in Node to list its exports; re-exporting with \`export *\``);
94
+ contents = `export * from ${JSON.stringify(specifier)};\n`;
95
+ } else {
96
+ const lines = [`import * as __dk from ${JSON.stringify(specifier)};`];
97
+ if (shape.names.length) lines.push(`export const { ${shape.names.join(', ')} } = __dk;`);
98
+ if (shape.hasDefault) lines.push('export default __dk.default;');
99
+ contents = `${lines.join('\n')}\n`;
100
+ }
101
+ }
102
+ fs.writeFileSync(file, contents);
103
+ entryPoints[name] = file;
104
+ specifierByEntry[name] = specifier;
105
+ }
106
+ return { entryPoints, specifierByEntry };
107
+ }
108
+
109
+ /**
110
+ * Resolves libraries to their source entries, stubs `stubImports`, and pins
111
+ * every import-map package to the copy resolved from the site root — a
112
+ * library built from another folder (e.g. `../source/src`) would otherwise
113
+ * bundle its own React.
114
+ */
115
+ export function vendorResolvePlugin(options: {
116
+ libraries: Record<string, LibrarySource>;
117
+ canonical: Set<string>;
118
+ stubImports: string[];
119
+ root: string;
120
+ }): Plugin {
121
+ const { libraries, canonical, stubImports, root } = options;
122
+ return {
123
+ name: 'docs-kit:vendor-resolve',
124
+ setup(build) {
125
+ build.onResolve({ filter: /^[^./]/ }, async (args) => {
126
+ if (args.pluginData?.docsKitCanonical) return undefined;
127
+ const library = libraries[args.path];
128
+ if (library) return { path: path.resolve(root, library.entry) };
129
+ if (matchesStub(args.path, stubImports)) return { path: args.path, namespace: 'docs-kit-stub' };
130
+ if (!canonical.has(args.path)) return undefined;
131
+ const result = await build.resolve(args.path, {
132
+ kind: args.kind,
133
+ resolveDir: root,
134
+ pluginData: { docsKitCanonical: true },
135
+ });
136
+ if (result.errors.length) return { errors: result.errors };
137
+ return { path: result.path, namespace: result.namespace, sideEffects: result.sideEffects };
138
+ });
139
+ build.onLoad({ filter: /.*/, namespace: 'docs-kit-stub' }, () => ({ contents: '', loader: 'js' }));
140
+ },
141
+ };
142
+ }
@@ -0,0 +1,35 @@
1
+ /// <reference lib="webworker" />
2
+ /**
3
+ * Module worker that rebuilds edited demo files with esbuild-wasm. Bundled by
4
+ * the demo builder into `<outDir>/_editor/compile-worker-[hash].js`; the
5
+ * wasm binary is passed in with the first request, so it's only downloaded
6
+ * when someone edits a demo.
7
+ */
8
+ import * as esbuild from 'esbuild-wasm';
9
+
10
+ import { compileDemo, type CompileOptions, type CompileRequest } from '../compile/core.ts';
11
+
12
+ type WorkerRequest = {
13
+ id: number;
14
+ wasmURL: string;
15
+ request: CompileRequest;
16
+ options: CompileOptions;
17
+ };
18
+
19
+ let ready: Promise<void> | null = null;
20
+
21
+ self.addEventListener('message', async (event: MessageEvent<WorkerRequest>) => {
22
+ const { id, wasmURL, request, options } = event.data;
23
+ try {
24
+ ready ??= esbuild.initialize({ wasmURL, worker: false });
25
+ await ready;
26
+ const result = await compileDemo(esbuild, request, options);
27
+ self.postMessage({ id, result });
28
+ } catch (error) {
29
+ ready = null;
30
+ self.postMessage({
31
+ id,
32
+ result: { ok: false, errors: [{ text: `The editor's compiler failed to start: ${String(error)}` }] },
33
+ });
34
+ }
35
+ });
@@ -0,0 +1,189 @@
1
+ /**
2
+ * CodeSandbox fork payloads (the `define` API that Sandpack's own "Open in
3
+ * CodeSandbox" button posts to).
4
+ *
5
+ * The demo's files keep their folder structure: they are placed under `src/`
6
+ * relative to their common ancestor folder, so imports that leave the demo's
7
+ * folder (`../shared/data`) still resolve. The entry (`src/index.tsx`) imports
8
+ * the demo by its relative path.
9
+ */
10
+ import LZString from 'lz-string';
11
+
12
+ import { bareImports, packageName } from '../code/imports.ts';
13
+
14
+ export const CODESANDBOX_DEFINE_URL = 'https://codesandbox.io/api/v1/sandboxes/define';
15
+
16
+ export type ForkFile = {
17
+ /** POSIX path relative to any shared root (e.g. the content folder). */
18
+ path: string;
19
+ content: string;
20
+ };
21
+
22
+ export type ForkTemplateOptions = {
23
+ title: string;
24
+ /** Path of the demo entry in `files`. */
25
+ entry: string;
26
+ /**
27
+ * Versions to pin. Every package the files import is added to the sandbox's
28
+ * `dependencies` (with its version from here, or `latest`).
29
+ */
30
+ dependencies?: Record<string, string>;
31
+ devDependencies?: Record<string, string>;
32
+ /** Top of `src/index.tsx`, e.g. `import '@pkg/index.css';`. */
33
+ entryPrelude?: string;
34
+ /** Appended to `src/styles.css`. */
35
+ styles?: string;
36
+ /** Literal replacements applied to every demo file. */
37
+ sourceReplacements?: Record<string, string>;
38
+ };
39
+
40
+ export type SandboxFiles = Record<string, { content: string | Record<string, unknown> }>;
41
+
42
+ function dirSegments(filePath: string): string[] {
43
+ const segments = filePath.split('/').filter(Boolean);
44
+ segments.pop();
45
+ return segments;
46
+ }
47
+
48
+ /** Longest shared folder of the given POSIX paths. */
49
+ export function commonDir(paths: string[]): string {
50
+ if (!paths.length) return '';
51
+ let common = dirSegments(paths[0]);
52
+ for (const filePath of paths.slice(1)) {
53
+ const segments = dirSegments(filePath);
54
+ let i = 0;
55
+ while (i < common.length && i < segments.length && common[i] === segments[i]) i++;
56
+ common = common.slice(0, i);
57
+ }
58
+ return common.join('/');
59
+ }
60
+
61
+ function replaceAll(source: string, replacements: Record<string, string> | undefined): string {
62
+ if (!replacements) return source;
63
+ let result = source;
64
+ for (const [search, replacement] of Object.entries(replacements)) result = result.split(search).join(replacement);
65
+ return result;
66
+ }
67
+
68
+ const BASE_STYLES = `html,
69
+ body,
70
+ #root {
71
+ height: 100%;
72
+ margin: 0;
73
+ }
74
+
75
+ * {
76
+ box-sizing: border-box;
77
+ }
78
+
79
+ body {
80
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
81
+ }
82
+
83
+ #root {
84
+ display: flex;
85
+ flex-flow: column;
86
+ overflow: hidden;
87
+ }
88
+ `;
89
+
90
+ const INDEX_HTML = (title: string) => `<!DOCTYPE html>
91
+ <html lang="en">
92
+ <head>
93
+ <meta charset="UTF-8" />
94
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
95
+ <title>${title.replace(/</g, '&lt;')}</title>
96
+ </head>
97
+ <body>
98
+ <div id="root"></div>
99
+ </body>
100
+ </html>
101
+ `;
102
+
103
+ /** The sandbox file tree for a React demo (create-react-app + TypeScript). */
104
+ export function reactSandboxFiles(files: ForkFile[], options: ForkTemplateOptions): SandboxFiles {
105
+ if (!files.some((file) => file.path === options.entry)) {
106
+ throw new Error(`fork: the entry "${options.entry}" is not one of the files`);
107
+ }
108
+ const root = commonDir(files.map((file) => file.path));
109
+ const inSrc = (filePath: string) => `src/${root ? filePath.slice(root.length + 1) : filePath}`;
110
+ const entryInSrc = inSrc(options.entry);
111
+ const entryImport = `./${entryInSrc.slice('src/'.length).replace(/\.[cm]?[jt]sx?$/, '')}`;
112
+
113
+ const imported: Record<string, string> = {};
114
+ for (const file of files) {
115
+ for (const specifier of bareImports(file.content)) {
116
+ const name = packageName(specifier);
117
+ imported[name] = options.dependencies?.[name] ?? 'latest';
118
+ }
119
+ }
120
+
121
+ const sandbox: SandboxFiles = {
122
+ 'package.json': {
123
+ content: {
124
+ name: 'docs-demo',
125
+ description: options.title,
126
+ main: 'src/index.tsx',
127
+ dependencies: {
128
+ ...imported,
129
+ react: '^19.0.0',
130
+ 'react-dom': '^19.0.0',
131
+ 'react-scripts': '^5.0.1',
132
+ ...options.dependencies,
133
+ },
134
+ devDependencies: {
135
+ typescript: '^5.4.0',
136
+ '@types/react': '^19.0.0',
137
+ '@types/react-dom': '^19.0.0',
138
+ ...options.devDependencies,
139
+ },
140
+ scripts: { start: 'react-scripts start', build: 'react-scripts build' },
141
+ browserslist: ['>0.2%', 'not dead'],
142
+ },
143
+ },
144
+ 'public/index.html': { content: INDEX_HTML(options.title) },
145
+ 'sandbox.config.json': { content: { infiniteLoopProtection: true } },
146
+ 'src/styles.css': { content: `${BASE_STYLES}${options.styles ? `\n${options.styles}\n` : ''}` },
147
+ 'src/index.tsx': {
148
+ content: `import { StrictMode } from 'react';
149
+ import { createRoot } from 'react-dom/client';
150
+ ${options.entryPrelude ? `${options.entryPrelude.trim()}\n` : ''}
151
+ import './styles.css';
152
+ import App from ${JSON.stringify(entryImport)};
153
+
154
+ createRoot(document.getElementById('root')!).render(
155
+ <StrictMode>
156
+ <App />
157
+ </StrictMode>,
158
+ );
159
+ `,
160
+ },
161
+ };
162
+
163
+ for (const file of files) {
164
+ const target = inSrc(file.path);
165
+ if (sandbox[target]) throw new Error(`fork: "${target}" clashes with a template file`);
166
+ sandbox[target] = { content: replaceAll(file.content, options.sourceReplacements) };
167
+ }
168
+ return sandbox;
169
+ }
170
+
171
+ /** lz-string base64, URL-safe — the encoding the define API expects. */
172
+ export function encodeSandboxParameters(files: SandboxFiles): string {
173
+ return LZString.compressToBase64(JSON.stringify({ files }))
174
+ .replace(/\+/g, '-')
175
+ .replace(/\//g, '_')
176
+ .replace(/=+$/, '');
177
+ }
178
+
179
+ /** Form fields for a POST to `CODESANDBOX_DEFINE_URL`. */
180
+ export function codeSandboxForm(files: ForkFile[], options: ForkTemplateOptions) {
181
+ const sandbox = reactSandboxFiles(files, options);
182
+ const root = commonDir(files.map((file) => file.path));
183
+ const entryInSrc = `src/${root ? options.entry.slice(root.length + 1) : options.entry}`;
184
+ return {
185
+ action: CODESANDBOX_DEFINE_URL,
186
+ parameters: encodeSandboxParameters(sandbox),
187
+ query: `file=/${entryInSrc}`,
188
+ };
189
+ }
@@ -0,0 +1,10 @@
1
+ export {
2
+ CODESANDBOX_DEFINE_URL,
3
+ codeSandboxForm,
4
+ commonDir,
5
+ encodeSandboxParameters,
6
+ reactSandboxFiles,
7
+ type ForkFile,
8
+ type ForkTemplateOptions,
9
+ type SandboxFiles,
10
+ } from './codesandbox.ts';