@serene-pub/ui-preview 0.6.0-pr-1

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.
@@ -0,0 +1,371 @@
1
+ /**
2
+ * The Vite half of the surface harness.
3
+ *
4
+ * 13 §11 draws the line this plugin sits on: *"loading, watching and
5
+ * cache-busting are the host's job — it owns the module cache, the watcher and
6
+ * the process."* Here the host is Vite, and that is the whole reason the
7
+ * harness is a Vite plugin rather than a bespoke loader: the module cache, the
8
+ * watcher and the invalidation already exist and are better than anything
9
+ * written for this. The SDK stays a pure reader (`previewManifest`), exactly as
10
+ * `devOverlay` takes an already-evaluated extension rather than a path.
11
+ *
12
+ * What crosses into the browser is one virtual module:
13
+ *
14
+ * virtual:serene-pub/surfaces
15
+ * manifest what the package announces, read tolerantly
16
+ * frames target id → dev URL of the frame document
17
+ * components target id → () => import(…), a real static import expression
18
+ * so Vite analyses it and Svelte HMR applies
19
+ * fixtures the data the harness pushes down the frame channel
20
+ *
21
+ * ## What is hot, and what reloads
22
+ *
23
+ * `dev.ts` already ruled this and the harness does not get a second opinion:
24
+ * **a component is always hot** — "components render; they do not participate
25
+ * in a run" — so a component edit is Svelte HMR and nothing else. The one
26
+ * thing that cannot be hot-patched is the *declaration set*: if the announce
27
+ * file changes, which surfaces exist may have changed, so the virtual module
28
+ * is invalidated and the page reloads. Editing a surface's code never triggers
29
+ * that; editing what the package announces always does.
30
+ */
31
+ import { existsSync } from 'node:fs'
32
+ import { readFile, readdir } from 'node:fs/promises'
33
+ import { createRequire } from 'node:module'
34
+ import { resolve, isAbsolute, dirname, join } from 'node:path'
35
+ import type { Plugin, ViteDevServer, ModuleNode } from 'vite'
36
+ import { ENTRY_CANDIDATES, previewManifest, type PreviewManifest } from '@serene-pub/sdk'
37
+
38
+ const VIRTUAL = 'virtual:serene-pub/surfaces'
39
+ const RESOLVED = '\0' + VIRTUAL
40
+
41
+ export interface SurfacesPluginOptions {
42
+ /** The package being previewed. */
43
+ pluginDir: string
44
+ /** Optional JSON file replacing the built-in fixtures. */
45
+ fixtures?: string
46
+ /** Resolved `@serene-pub/controls` root — required, see vite.config.ts. */
47
+ controlsDir: string
48
+ }
49
+
50
+ /** Where the harness serves the frame-tier token stylesheet. */
51
+ export const THEME_CSS_PATH = '/@serene-pub/themes.css'
52
+
53
+ /**
54
+ * Core's frame CSP (`frameHost.frameCsp`), with the one relaxation a dev
55
+ * server cannot do without: `connect-src` has to reach Vite's HMR socket, and
56
+ * `script-src` has to admit the client module Vite injects. Everything else is
57
+ * production's, on purpose — a harness that served frames with no CSP at all
58
+ * (as this one previously did) would let an author build against inline
59
+ * scripts that core will refuse the day they install.
60
+ */
61
+ function frameCsp(): string {
62
+ return [
63
+ "default-src 'none'",
64
+ "script-src 'self'",
65
+ "style-src 'self' 'unsafe-inline'",
66
+ "img-src 'self' data: blob:",
67
+ "font-src 'self' data:",
68
+ "media-src 'self' blob:",
69
+ // Production is `connect-src <granted hosts>` or `'none'`; dev must
70
+ // additionally reach the HMR socket or nothing hot-reloads.
71
+ "connect-src 'self' ws: wss:",
72
+ "form-action 'none'",
73
+ "base-uri 'none'",
74
+ ].join('; ')
75
+ }
76
+
77
+ /**
78
+ * The stock Skeleton themes, read off the installed package rather than
79
+ * listed here. A new Skeleton release adds a theme and the picker grows one;
80
+ * nothing in this repo has to be edited to keep up, which is the only way a
81
+ * list like this stays true.
82
+ */
83
+ async function themeNames(themesDir: string | undefined): Promise<string[]> {
84
+ if (!themesDir) return []
85
+ try {
86
+ return (await readdir(themesDir))
87
+ .filter((f) => f.endsWith('.css'))
88
+ .map((f) => f.slice(0, -4))
89
+ .sort()
90
+ } catch {
91
+ return []
92
+ }
93
+ }
94
+
95
+ /** The installed Skeleton package's themes directory, if it is resolvable. */
96
+ function skeletonThemesDir(from: string): string | undefined {
97
+ try {
98
+ const require = createRequire(join(from, 'noop.js'))
99
+ return join(
100
+ dirname(require.resolve('@skeletonlabs/skeleton/package.json')),
101
+ 'src',
102
+ 'themes',
103
+ )
104
+ } catch {
105
+ return undefined
106
+ }
107
+ }
108
+
109
+ /**
110
+ * One separator convention for every path comparison. Vite reports watcher and
111
+ * module-graph paths with forward slashes on every platform; Node's `resolve`
112
+ * uses backslashes on Windows. Comparing the two raw meant a Windows harness
113
+ * silently never matched, and so never noticed a single change.
114
+ */
115
+ const posix = (p: string) => p.replace(/\\/g, '/')
116
+
117
+ /** `/@fs/<abs>` — how Vite serves a file outside its root. */
118
+ const fsUrl = (abs: string) =>
119
+ '/@fs' +
120
+ abs.replace(/\\/g, '/').replace(/^\/?/, '/').split('/').map(encodeURIComponent).join('/')
121
+
122
+ function findEntry(dir: string): string | undefined {
123
+ for (const candidate of ENTRY_CANDIDATES) {
124
+ const p = resolve(dir, candidate)
125
+ if (existsSync(p)) return p
126
+ }
127
+ return undefined
128
+ }
129
+
130
+ /**
131
+ * Every file the announcement was built from. Kept so a save can be classified
132
+ * — declaration change (reload) or surface code (HMR) — instead of reloading
133
+ * the page on every keystroke in the package, which is the failure mode that
134
+ * makes people turn a harness off.
135
+ */
136
+ function declarationFiles(server: ViteDevServer, entry: string): Set<string> {
137
+ // Stored posix-normalised, because that is how they are looked up.
138
+ const files = new Set<string>()
139
+ const root = server.moduleGraph.getModulesByFile(entry)
140
+ const walk = (mod: ModuleNode, depth: number) => {
141
+ if (!mod.file || depth > 24) return
142
+ const key = posix(mod.file)
143
+ if (files.has(key)) return
144
+ files.add(key)
145
+ for (const dep of mod.importedModules) walk(dep, depth + 1)
146
+ }
147
+ for (const mod of root ?? []) walk(mod, 0)
148
+ return files
149
+ }
150
+
151
+ export function serenePubSurfaces(options: SurfacesPluginOptions): Plugin {
152
+ const pluginDir = resolve(options.pluginDir)
153
+ const themesDir = skeletonThemesDir(import.meta.dirname ?? process.cwd())
154
+ let server: ViteDevServer | undefined
155
+ let declFiles = new Set<string>()
156
+ let themeCss: string | undefined
157
+
158
+ return {
159
+ name: 'serene-pub:surfaces',
160
+ enforce: 'pre',
161
+
162
+ configureServer(s) {
163
+ server = s
164
+ // The package is outside the harness's root, so chokidar is not
165
+ // watching it yet. Without this the harness is a snapshot.
166
+ s.watcher.add(pluginDir)
167
+
168
+ /**
169
+ * The frame-tier token stylesheet (RESEARCH §7b: *"a core-served
170
+ * token stylesheet (iframe tier)"*).
171
+ *
172
+ * Tokens only — every stock theme's custom-property block, served
173
+ * whole, plus the four lines of `color-scheme` that make
174
+ * `light-dark()` resolve. Deliberately **no utilities**: linking
175
+ * the harness's compiled Tailwind into a frame would make rules
176
+ * appear that the plugin's own build never emitted, so a surface
177
+ * would look styled here and unstyled after install — 10 §6's
178
+ * exact misdiagnosis. And deliberately no hand-written token
179
+ * list: §7b refuses an SP-published token artifact, so this ships
180
+ * the theme files or it ships nothing.
181
+ *
182
+ * All themes in one document on purpose: the frame links it once
183
+ * and a theme switch is an attribute flip inside the frame — no
184
+ * refetch, no new `src`, and therefore no reload. Reloading is the
185
+ * one thing the frame tier is built not to do (21 §4).
186
+ */
187
+ s.middlewares.use(THEME_CSS_PATH, async (_req, res) => {
188
+ if (!themeCss) {
189
+ try {
190
+ if (!themesDir) throw new Error('@skeletonlabs/skeleton is not installed')
191
+ const files = (await readdir(themesDir))
192
+ .filter((f) => f.endsWith('.css'))
193
+ .sort()
194
+ if (!files.length) throw new Error(`no theme files in ${themesDir}`)
195
+ const blocks = await Promise.all(
196
+ files.map((f) => readFile(join(themesDir, f), 'utf8')),
197
+ )
198
+ themeCss =
199
+ `/* Serene Pub — frame token stylesheet.\n` +
200
+ ` Every stock Skeleton theme's custom properties, served whole.\n` +
201
+ ` Apply one with data-theme="<name>" on your root element.\n` +
202
+ `\n` +
203
+ ` WHAT THIS GIVES YOU: the theme's palette — --color-primary-500,\n` +
204
+ ` --color-surface-50..950, the contrast tokens, and the rest of the\n` +
205
+ ` ramp. These follow the THEME.\n` +
206
+ `\n` +
207
+ ` WHAT IT DOES NOT: the semantic mode-aware tokens Skeleton builds\n` +
208
+ ` on top with light-dark() live in its base layer, which is written\n` +
209
+ ` in Tailwind at-rules and cannot be served as plain CSS. Compiling\n` +
210
+ ` it here would also drag in utility classes your own build never\n` +
211
+ ` emitted, which is worse than not having it.\n` +
212
+ `\n` +
213
+ ` So MODE IS YOURS. data-mode is set on your root and color-scheme\n` +
214
+ ` follows it; pick your own sides of the ramp:\n` +
215
+ `\n` +
216
+ ` body { background: var(--color-surface-50) }\n` +
217
+ ` [data-mode="dark"] body { background: var(--color-surface-950) }\n` +
218
+ `\n` +
219
+ ` Tokens only: no utility classes, because your own build owns\n` +
220
+ ` those (10 §6). */\n` +
221
+ `:root { color-scheme: light }\n` +
222
+ `[data-mode="dark"] { color-scheme: dark }\n` +
223
+ blocks.join('\n')
224
+ } catch (e) {
225
+ // A missing or restructured Skeleton is a frame with no
226
+ // tokens, not a dead dev server — and the message belongs
227
+ // in the stylesheet, where the author is already looking
228
+ // when the styling is absent.
229
+ themeCss =
230
+ `/* Serene Pub — no theme tokens available.\n` +
231
+ ` ${(e as Error).message}\n` +
232
+ ` Frames render with their own defaults only. */\n`
233
+ }
234
+ }
235
+ res.setHeader('Content-Type', 'text/css; charset=utf-8')
236
+ // A frame is an opaque origin and sends no credentials; the
237
+ // stylesheet must therefore be reachable without one, exactly
238
+ // as core's plugin-ui route is.
239
+ res.setHeader('Cache-Control', 'no-cache')
240
+ res.end(themeCss)
241
+ })
242
+
243
+ /**
244
+ * Frame documents get core's CSP. Vite would otherwise serve them
245
+ * bare, and "it worked in the harness" would stop meaning anything
246
+ * the first time an author leaned on an inline <script> — which
247
+ * core's `script-src 'self'` refuses.
248
+ */
249
+ s.middlewares.use((req, res, next) => {
250
+ const url = req.url ?? ''
251
+ if (url.startsWith('/@fs') && /\.html(\?|$)/.test(url))
252
+ res.setHeader('Content-Security-Policy', frameCsp())
253
+ next()
254
+ })
255
+ },
256
+
257
+ resolveId(id) {
258
+ if (id === VIRTUAL) return RESOLVED
259
+ },
260
+
261
+ async load(id) {
262
+ if (id !== RESOLVED) return
263
+ const entry = findEntry(pluginDir)
264
+ let manifest: PreviewManifest
265
+ if (!entry) {
266
+ manifest = {
267
+ id: 'unknown',
268
+ title: pluginDir,
269
+ targets: [],
270
+ problems: [
271
+ `no entry module in ${pluginDir} — the harness looks for ` +
272
+ ENTRY_CANDIDATES.join(', '),
273
+ ],
274
+ }
275
+ } else if (!server) {
276
+ // Config-time load (build, or a probe before the server exists).
277
+ manifest = { id: 'unknown', title: pluginDir, targets: [], problems: [] }
278
+ } else {
279
+ try {
280
+ const mod = await server.ssrLoadModule(entry)
281
+ manifest = previewManifest(
282
+ mod.default ?? (mod as Record<string, unknown>).extension,
283
+ )
284
+ } catch (e) {
285
+ // A syntax error in the announce file must show *in the
286
+ // harness*, not as a blank page and a terminal nobody is
287
+ // looking at.
288
+ manifest = {
289
+ id: 'unknown',
290
+ title: pluginDir,
291
+ targets: [],
292
+ problems: [`could not load ${entry}:\n${(e as Error).message}`],
293
+ }
294
+ } finally {
295
+ // Recorded even when the load threw, and always including the
296
+ // entry itself. A syntax error produces no module graph, so a
297
+ // success-only record would leave the harness unable to notice
298
+ // the fix — the one save that matters most would be ignored.
299
+ declFiles = declarationFiles(server, entry)
300
+ declFiles.add(posix(entry))
301
+ }
302
+ }
303
+
304
+ const frames: Record<string, string> = {}
305
+ const components: string[] = []
306
+ for (const t of manifest.targets) {
307
+ const abs = isAbsolute(t.entry) ? t.entry : resolve(pluginDir, t.entry)
308
+ if (!existsSync(abs)) {
309
+ manifest.problems.push(
310
+ `${t.id}: '${t.entry}' does not exist — declared entries are resolved ` +
311
+ `from the package root (${pluginDir})`,
312
+ )
313
+ continue
314
+ }
315
+ if (t.kind === 'frame') frames[t.id] = fsUrl(abs)
316
+ else
317
+ components.push(
318
+ `\t${JSON.stringify(t.id)}: () => import(${JSON.stringify(fsUrl(abs))}),`,
319
+ )
320
+ }
321
+
322
+ let fixtures: unknown = null
323
+ if (options.fixtures) {
324
+ try {
325
+ fixtures = JSON.parse(await readFile(resolve(options.fixtures), 'utf8'))
326
+ } catch (e) {
327
+ manifest.problems.push(
328
+ `--fixtures ${options.fixtures}: ${(e as Error).message}`,
329
+ )
330
+ }
331
+ }
332
+
333
+ return [
334
+ `export const manifest = ${JSON.stringify(manifest)}`,
335
+ `export const packageDir = ${JSON.stringify(pluginDir)}`,
336
+ `export const themes = ${JSON.stringify(await themeNames(themesDir))}`,
337
+ `export const themeCssPath = ${JSON.stringify(THEME_CSS_PATH)}`,
338
+ `export const frames = ${JSON.stringify(frames)}`,
339
+ `export const fixtureOverride = ${JSON.stringify(fixtures)}`,
340
+ // Written as real import() expressions, not a path string handed
341
+ // to a variable import — that is what puts these in Vite's graph
342
+ // and gets them Svelte HMR instead of a page reload.
343
+ `export const components = {\n${components.join('\n')}\n}`,
344
+ ].join('\n')
345
+ },
346
+
347
+ handleHotUpdate({ file, server: s }) {
348
+ // Compared in one separator convention. Vite hands watcher paths
349
+ // with forward slashes even on Windows, while `resolve()` produces
350
+ // backslashes there — so a raw `startsWith` never matched and the
351
+ // harness silently stopped noticing any change at all.
352
+ if (!posix(file).startsWith(posix(pluginDir))) return
353
+ // A declaration change can add or remove surfaces, so the list the
354
+ // harness is rendering may no longer be the list that exists.
355
+ if (declFiles.has(posix(file))) {
356
+ const mod = s.moduleGraph.getModuleById(RESOLVED)
357
+ if (mod) s.moduleGraph.invalidateModule(mod)
358
+ s.ws.send({ type: 'full-reload' })
359
+ return []
360
+ }
361
+ // Frame documents are their own browsing context; Vite's HMR client
362
+ // inside them handles their own modules, but an edit to the .html
363
+ // itself needs the frame reloaded, and only that frame.
364
+ if (file.endsWith('.html')) {
365
+ s.ws.send({ type: 'custom', event: 'serene-pub:frame-changed', data: { file } })
366
+ return []
367
+ }
368
+ // Everything else is surface code: hot by ruling (dev.ts).
369
+ },
370
+ }
371
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,55 @@
1
+ import { sveltekit } from '@sveltejs/kit/vite'
2
+ import tailwindcss from '@tailwindcss/vite'
3
+ import { createRequire } from 'node:module'
4
+ import { dirname } from 'node:path'
5
+ import { defineConfig } from 'vite'
6
+ import { serenePubSurfaces } from './vite/surfaces'
7
+
8
+ /**
9
+ * The package under preview is passed in by `serene-pub ui` through the
10
+ * environment rather than a config file, because the harness is one installed
11
+ * copy serving whichever package the modder points it at — writing a config
12
+ * into their repo to say "preview me" would be a file they then have to
13
+ * maintain and gitignore.
14
+ */
15
+ const pluginDir = process.env.SERENE_PUB_PACKAGE_DIR ?? process.cwd()
16
+
17
+ /**
18
+ * Where `@serene-pub/controls` actually is. It is raw Svelte source rather
19
+ * than a build, so Vite has to be allowed to *serve* it — and inside the SDK
20
+ * workspace it is hoisted a directory above this app, which is outside the
21
+ * root Vite would otherwise permit. Resolved rather than hardcoded because
22
+ * the answer differs between the workspace and a modder's install.
23
+ */
24
+ const require = createRequire(import.meta.url)
25
+ let controlsDir: string
26
+ try {
27
+ controlsDir = dirname(require.resolve('@serene-pub/controls/package.json'))
28
+ } catch {
29
+ // Not optional: the sandbox and every generated form import it statically,
30
+ // so a missing install is a broken harness. Failing here with the reason
31
+ // beats failing later with a module-resolution stack trace.
32
+ throw new Error(
33
+ '@serene-pub/ui-preview requires @serene-pub/controls, which did not resolve. ' +
34
+ 'Reinstall the harness (npm i @serene-pub/ui-preview).',
35
+ )
36
+ }
37
+
38
+ export default defineConfig({
39
+ plugins: [
40
+ serenePubSurfaces({
41
+ pluginDir,
42
+ fixtures: process.env.SERENE_PUB_FIXTURES,
43
+ controlsDir,
44
+ }),
45
+ tailwindcss(),
46
+ sveltekit(),
47
+ ],
48
+ server: {
49
+ // The package lives outside this app's root; without this Vite refuses
50
+ // to serve a single one of its files.
51
+ fs: { allow: [pluginDir, controlsDir] },
52
+ },
53
+ // One Svelte identity, even when the previewed package carries its own copy.
54
+ resolve: { dedupe: ['svelte'] },
55
+ })