@vizejs/vite-plugin-musea 0.731.0 → 0.732.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 (51) hide show
  1. package/dist/a11y/index.d.mts +1 -1
  2. package/dist/a11y/index.mjs +200 -1
  3. package/dist/a11y/index.mjs.map +1 -0
  4. package/dist/apply-DIAnotZa.mjs +8 -0
  5. package/dist/apply-DIAnotZa.mjs.map +1 -0
  6. package/dist/autogen/index.mjs +1 -1
  7. package/dist/{autogen-B-N0cJbZ.mjs → autogen-D9K1av3V.mjs} +2 -2
  8. package/dist/{autogen-B-N0cJbZ.mjs.map → autogen-D9K1av3V.mjs.map} +1 -1
  9. package/dist/browser-launch-DCUbOf0d.mjs +29 -0
  10. package/dist/browser-launch-DCUbOf0d.mjs.map +1 -0
  11. package/dist/cli/index.mjs +9 -7
  12. package/dist/cli/index.mjs.map +1 -1
  13. package/dist/{gallery-DLl3pMOF.mjs → gallery-DNxzJA4V.mjs} +2 -2
  14. package/dist/{gallery-DLl3pMOF.mjs.map → gallery-DNxzJA4V.mjs.map} +1 -1
  15. package/dist/{browser-launch-L43ulIaZ.mjs → html-BW9Z7gL3.mjs} +5 -26
  16. package/dist/html-BW9Z7gL3.mjs.map +1 -0
  17. package/dist/{index-Dh4IXacU.d.mts → index-ELy0IbiZ.d.mts} +2 -2
  18. package/dist/{index-Dh4IXacU.d.mts.map → index-ELy0IbiZ.d.mts.map} +1 -1
  19. package/dist/index.d.mts +67 -3
  20. package/dist/index.d.mts.map +1 -1
  21. package/dist/index.mjs +505 -2232
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/{template-D12HYJCn.mjs → module-BaxIBS_8.mjs} +39 -39
  24. package/dist/module-BaxIBS_8.mjs.map +1 -0
  25. package/dist/plugin-D2KEfrj1.mjs +2285 -0
  26. package/dist/plugin-D2KEfrj1.mjs.map +1 -0
  27. package/dist/{a11y-CR7bHK1d.mjs → report-CHUEZNZA.mjs} +3 -199
  28. package/dist/report-CHUEZNZA.mjs.map +1 -0
  29. package/dist/report-ZbXgDiN_.mjs +300 -0
  30. package/dist/report-ZbXgDiN_.mjs.map +1 -0
  31. package/dist/{options-DLFcpXwQ.mjs → report-identity-dHHBq0Ne.mjs} +502 -956
  32. package/dist/report-identity-dHHBq0Ne.mjs.map +1 -0
  33. package/dist/resolver-D8_4jxfT.mjs +812 -0
  34. package/dist/resolver-D8_4jxfT.mjs.map +1 -0
  35. package/dist/snapshot-identity-Cm-t65Kl.mjs +63 -0
  36. package/dist/snapshot-identity-Cm-t65Kl.mjs.map +1 -0
  37. package/dist/{vrt-CUz4NxKK.mjs → vrt-B8j2yfiN.mjs} +8 -363
  38. package/dist/vrt-B8j2yfiN.mjs.map +1 -0
  39. package/dist/{vrt-JoCQcFDG.d.mts → vrt-CuAg5Eow.d.mts} +2 -3
  40. package/dist/vrt-CuAg5Eow.d.mts.map +1 -0
  41. package/dist/vrt.d.mts +1 -1
  42. package/dist/vrt.mjs +3 -2
  43. package/package.json +5 -5
  44. package/dist/a11y-CR7bHK1d.mjs.map +0 -1
  45. package/dist/browser-launch-L43ulIaZ.mjs.map +0 -1
  46. package/dist/options-DLFcpXwQ.mjs.map +0 -1
  47. package/dist/template-D12HYJCn.mjs.map +0 -1
  48. package/dist/utils-BQi1club.mjs +0 -654
  49. package/dist/utils-BQi1club.mjs.map +0 -1
  50. package/dist/vrt-CUz4NxKK.mjs.map +0 -1
  51. package/dist/vrt-JoCQcFDG.d.mts.map +0 -1
@@ -0,0 +1,2285 @@
1
+ import { t as shouldApplyMuseaPlugin } from "./apply-DIAnotZa.mjs";
2
+ import { m as attachMuseaOptions, p as loadNative } from "./resolver-D8_4jxfT.mjs";
3
+ import { $ as HttpError, A as expandSelfTag, C as processMuseaArtFile, D as loadArtStyle, E as rewriteRelativeImportStatement, F as matchGlob, G as validateDevApiRequest, H as createDevSessionToken, I as resolveScanRoots, J as decodeUrlComponent, K as assertArtVueSourcePath, L as scanArtFiles, M as variantComponentNames, N as escapeHtml, O as parseArtStyleRequest, P as generateStorybookFiles, Q as resolveUrlPathInside, R as shouldProcess, S as handleTokensUsage, T as parseScriptSetupForArt, U as parseJsonBody, V as collectRequestBody, W as serializeScriptValue, X as resolveInside, Y as isTrustedSourcePath, Z as resolveTrustedSourcePath, _ as handleArtPalette, a as rewriteDevGalleryAsset, b as handleTokensGet, c as createStaticGalleryPayload, d as resolveStaticIdentityRoot, f as staticPreviewId, g as handleArtSource, h as handleArtDocs, i as publicBasePathFromViteBase, j as resolveArtComponent, k as transformPreprocessedArtStyle, l as joinUrlPath, m as handleArtAnalysis, n as attachArtReportOwner, o as rewriteGalleryBase, p as sortedArts, q as assertVueSourcePath, r as resolveArtReportTarget, s as rewriteGalleryTextAssetBase, t as assertArtReportOwnership, u as resolveStaticArtIdentity, v as handleTokensCreate, w as generateArtModule, x as handleTokensUpdate, y as handleTokensDelete, z as buildThemeConfig } from "./report-identity-dHHBq0Ne.mjs";
4
+ import { a as generateGalleryScript, i as generateGalleryBody, n as generateDevGlobalsScript, r as generateGalleryGlobalsScript, t as generateGalleryModule } from "./module-BaxIBS_8.mjs";
5
+ import { createRequire } from "node:module";
6
+ import path from "node:path";
7
+ import fs, { existsSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
9
+ import * as vite from "vite";
10
+ import { normalizePath } from "vite";
11
+ import { VIZE_CONFIG_FILE_ENV, loadConfig, resolveViteConfigExport } from "@vizejs/vite-plugin";
12
+ import { getResolvedVizeConfigRegistration } from "@vizejs/vite-plugin/internal/config-bridge";
13
+ //#region src/toolbar.ts
14
+ function normalizeToolbar(toolbar = []) {
15
+ const ids = /* @__PURE__ */ new Set();
16
+ return toolbar.map((control) => {
17
+ const fail = (reason) => {
18
+ throw new Error(`[musea] Invalid toolbar control ${JSON.stringify(control.id)}: ${reason}`);
19
+ };
20
+ if (!/^[a-zA-Z][\w-]*$/.test(control.id) || ids.has(control.id)) fail("ids must be unique and start with a letter");
21
+ ids.add(control.id);
22
+ if (!control.title?.trim()) fail("title is required");
23
+ if (control.type !== "select" && control.type !== "toggle") fail("unknown control type");
24
+ if (!Array.isArray(control.options) || control.options.length === 0) fail("options are required");
25
+ if (control.type === "toggle" && control.options.length !== 2) fail("toggles need two options");
26
+ const values = /* @__PURE__ */ new Set();
27
+ const options = control.options.map((option) => {
28
+ const item = typeof option === "string" ? {
29
+ value: option,
30
+ label: option
31
+ } : option;
32
+ if (!item || ![
33
+ "string",
34
+ "boolean",
35
+ "number"
36
+ ].includes(typeof item.value) || typeof item.value === "number" && !Number.isFinite(item.value) || typeof item.label !== "string" || !item.label.trim() || item.icon !== void 0 && typeof item.icon !== "string") fail("options require a finite primitive value and a label");
37
+ if (values.has(item.value)) fail("option values must be unique");
38
+ values.add(item.value);
39
+ return {
40
+ value: item.value,
41
+ label: item.label,
42
+ ...item.icon ? { icon: item.icon } : {}
43
+ };
44
+ });
45
+ if (!values.has(control.default)) fail("default must match an option value");
46
+ return {
47
+ id: control.id,
48
+ title: control.title,
49
+ type: control.type,
50
+ options,
51
+ default: control.default
52
+ };
53
+ });
54
+ }
55
+ //#endregion
56
+ //#region src/preview/globals.ts
57
+ /** Generated only for configured controls; the default preview stays unchanged. */
58
+ function generatePreviewGlobals(toolbar) {
59
+ if (toolbar.length === 0) return "";
60
+ return `
61
+ const __museaToolbar = ${JSON.stringify(toolbar)};
62
+ function __museaResolveGlobals(input) {
63
+ const record = input && typeof input === 'object' ? input : {};
64
+ return Object.fromEntries(__museaToolbar.map((control) => {
65
+ const value = Object.hasOwn(record, control.id) ? record[control.id] : undefined;
66
+ return [control.id, control.options.some((option) => option.value === value) ? value : control.default];
67
+ }));
68
+ }
69
+ let __museaInitialGlobals;
70
+ try {
71
+ __museaInitialGlobals = JSON.parse(new URL(window.location.href).searchParams.get('museaGlobals'));
72
+ } catch {}
73
+ const __museaGlobals = __museaCreateGlobalsRef(__museaResolveGlobals(__museaInitialGlobals));
74
+ function __museaUpdateGlobals(event) {
75
+ if (event.origin !== window.location.origin || event.source !== window.parent) return;
76
+ if (event.data?.type !== 'musea:set-globals') return;
77
+ const next = __museaResolveGlobals(event.data.payload);
78
+ if (__museaToolbar.some((control) => next[control.id] !== __museaGlobals.value[control.id])) {
79
+ __museaGlobals.value = next;
80
+ }
81
+ }
82
+ window.addEventListener('message', __museaUpdateGlobals);
83
+ window.addEventListener('pagehide', (event) => {
84
+ if (!event.persisted) window.removeEventListener('message', __museaUpdateGlobals);
85
+ });
86
+ `;
87
+ }
88
+ //#endregion
89
+ //#region src/preview/addons.ts
90
+ /**
91
+ * Addon initialization code for Musea preview iframes.
92
+ *
93
+ * Contains DOM event capture, measure overlay, and message handler logic
94
+ * injected into preview modules.
95
+ *
96
+ * Extracted from preview.ts to keep file sizes manageable.
97
+ */
98
+ /**
99
+ * Addon initialization code injected into preview iframe modules.
100
+ * Shared between generatePreviewModule and generatePreviewModuleWithProps.
101
+ */
102
+ const MUSEA_ADDONS_INIT_CODE = `
103
+ function __museaInitAddons(container, variantName, extraCaptureEvents = []) {
104
+ const parentOrigin = window.location.origin;
105
+ // === DOM event capture ===
106
+ // Note: wheel and hover-style events are excluded by default because they are too noisy.
107
+ const BASE_CAPTURE_EVENTS = ['click','dblclick','input','change','submit','focus','blur','keydown','keyup','mousedown','mouseup','contextmenu','pointerdown','pointerup'];
108
+ const CAPTURE_EVENTS = [...new Set([
109
+ ...BASE_CAPTURE_EVENTS,
110
+ ...((Array.isArray(extraCaptureEvents) ? extraCaptureEvents : [])
111
+ .filter((eventName) => typeof eventName === 'string')
112
+ .map((eventName) => eventName.trim())
113
+ .filter(Boolean))
114
+ ])];
115
+ for (const evt of CAPTURE_EVENTS) {
116
+ container.addEventListener(evt, (e) => {
117
+ // Extract raw event properties
118
+ const rawEvent = {
119
+ type: e.type,
120
+ bubbles: e.bubbles,
121
+ cancelable: e.cancelable,
122
+ composed: e.composed,
123
+ defaultPrevented: e.defaultPrevented,
124
+ eventPhase: e.eventPhase,
125
+ isTrusted: e.isTrusted,
126
+ timeStamp: e.timeStamp,
127
+ };
128
+ // Mouse/Pointer event properties
129
+ if ('clientX' in e) {
130
+ rawEvent.clientX = e.clientX;
131
+ rawEvent.clientY = e.clientY;
132
+ rawEvent.screenX = e.screenX;
133
+ rawEvent.screenY = e.screenY;
134
+ rawEvent.pageX = e.pageX;
135
+ rawEvent.pageY = e.pageY;
136
+ rawEvent.offsetX = e.offsetX;
137
+ rawEvent.offsetY = e.offsetY;
138
+ rawEvent.button = e.button;
139
+ rawEvent.buttons = e.buttons;
140
+ rawEvent.altKey = e.altKey;
141
+ rawEvent.ctrlKey = e.ctrlKey;
142
+ rawEvent.metaKey = e.metaKey;
143
+ rawEvent.shiftKey = e.shiftKey;
144
+ }
145
+ // Keyboard event properties
146
+ if ('key' in e) {
147
+ rawEvent.key = e.key;
148
+ rawEvent.code = e.code;
149
+ rawEvent.repeat = e.repeat;
150
+ rawEvent.altKey = e.altKey;
151
+ rawEvent.ctrlKey = e.ctrlKey;
152
+ rawEvent.metaKey = e.metaKey;
153
+ rawEvent.shiftKey = e.shiftKey;
154
+ }
155
+ // Input event properties
156
+ if ('inputType' in e) {
157
+ rawEvent.inputType = e.inputType;
158
+ rawEvent.data = e.data;
159
+ }
160
+ // Wheel event properties
161
+ if ('deltaX' in e) {
162
+ rawEvent.deltaX = e.deltaX;
163
+ rawEvent.deltaY = e.deltaY;
164
+ rawEvent.deltaZ = e.deltaZ;
165
+ rawEvent.deltaMode = e.deltaMode;
166
+ }
167
+ const payload = {
168
+ name: e.type,
169
+ target: e.target?.tagName,
170
+ timestamp: Date.now(),
171
+ source: 'dom',
172
+ rawEvent,
173
+ variantName
174
+ };
175
+ if (e.target && 'value' in e.target) {
176
+ payload.value = e.target.value;
177
+ }
178
+ window.parent.postMessage({ type: 'musea:event', payload }, parentOrigin);
179
+ }, true);
180
+ }
181
+
182
+ // === Message handler for parent commands ===
183
+ let measureActive = false;
184
+ let measureOverlay = null;
185
+ let measureLabel = null;
186
+
187
+ function toggleStyleById(id, enabled, css) {
188
+ let el = document.getElementById(id);
189
+ if (enabled) {
190
+ if (!el) {
191
+ el = document.createElement('style');
192
+ el.id = id;
193
+ el.textContent = css;
194
+ document.head.appendChild(el);
195
+ }
196
+ } else {
197
+ if (el) el.remove();
198
+ }
199
+ }
200
+
201
+ function createMeasureOverlay() {
202
+ if (measureOverlay) return;
203
+ measureOverlay = document.createElement('div');
204
+ measureOverlay.id = 'musea-measure-overlay';
205
+ measureOverlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:99999;';
206
+ document.body.appendChild(measureOverlay);
207
+
208
+ measureLabel = document.createElement('div');
209
+ measureLabel.className = 'musea-measure-label';
210
+ measureLabel.style.cssText = 'position:fixed;background:#333;color:#fff;font-size:11px;padding:2px 6px;border-radius:3px;pointer-events:none;z-index:100000;display:none;';
211
+ document.body.appendChild(measureLabel);
212
+ }
213
+
214
+ function removeMeasureOverlay() {
215
+ if (measureOverlay) { measureOverlay.remove(); measureOverlay = null; }
216
+ if (measureLabel) { measureLabel.remove(); measureLabel = null; }
217
+ }
218
+
219
+ function onMeasureMouseMove(e) {
220
+ if (!measureActive || !measureOverlay) return;
221
+ const el = document.elementFromPoint(e.clientX, e.clientY);
222
+ if (!el || el === measureOverlay || el === measureLabel) return;
223
+
224
+ const rect = el.getBoundingClientRect();
225
+ const cs = getComputedStyle(el);
226
+ const mt = parseFloat(cs.marginTop) || 0;
227
+ const mr = parseFloat(cs.marginRight) || 0;
228
+ const mb = parseFloat(cs.marginBottom) || 0;
229
+ const ml = parseFloat(cs.marginLeft) || 0;
230
+ const bt = parseFloat(cs.borderTopWidth) || 0;
231
+ const br = parseFloat(cs.borderRightWidth) || 0;
232
+ const bb = parseFloat(cs.borderBottomWidth) || 0;
233
+ const blw = parseFloat(cs.borderLeftWidth) || 0;
234
+ const pt = parseFloat(cs.paddingTop) || 0;
235
+ const pr = parseFloat(cs.paddingRight) || 0;
236
+ const pb = parseFloat(cs.paddingBottom) || 0;
237
+ const pl = parseFloat(cs.paddingLeft) || 0;
238
+
239
+ const cw = rect.width - blw - br - pl - pr;
240
+ const ch = rect.height - bt - bb - pt - pb;
241
+
242
+ measureOverlay.innerHTML = ''
243
+ // Margin
244
+ + '<div style="position:fixed;background:rgba(255,165,0,0.3);'
245
+ + 'left:' + (rect.left - ml) + 'px;top:' + (rect.top - mt) + 'px;'
246
+ + 'width:' + (rect.width + ml + mr) + 'px;height:' + mt + 'px;"></div>'
247
+ + '<div style="position:fixed;background:rgba(255,165,0,0.3);'
248
+ + 'left:' + (rect.left - ml) + 'px;top:' + (rect.bottom) + 'px;'
249
+ + 'width:' + (rect.width + ml + mr) + 'px;height:' + mb + 'px;"></div>'
250
+ + '<div style="position:fixed;background:rgba(255,165,0,0.3);'
251
+ + 'left:' + (rect.left - ml) + 'px;top:' + rect.top + 'px;'
252
+ + 'width:' + ml + 'px;height:' + rect.height + 'px;"></div>'
253
+ + '<div style="position:fixed;background:rgba(255,165,0,0.3);'
254
+ + 'left:' + rect.right + 'px;top:' + rect.top + 'px;'
255
+ + 'width:' + mr + 'px;height:' + rect.height + 'px;"></div>'
256
+ // Border
257
+ + '<div style="position:fixed;background:rgba(255,255,0,0.3);'
258
+ + 'left:' + rect.left + 'px;top:' + rect.top + 'px;'
259
+ + 'width:' + rect.width + 'px;height:' + bt + 'px;"></div>'
260
+ + '<div style="position:fixed;background:rgba(255,255,0,0.3);'
261
+ + 'left:' + rect.left + 'px;top:' + (rect.bottom - bb) + 'px;'
262
+ + 'width:' + rect.width + 'px;height:' + bb + 'px;"></div>'
263
+ + '<div style="position:fixed;background:rgba(255,255,0,0.3);'
264
+ + 'left:' + rect.left + 'px;top:' + (rect.top + bt) + 'px;'
265
+ + 'width:' + blw + 'px;height:' + (rect.height - bt - bb) + 'px;"></div>'
266
+ + '<div style="position:fixed;background:rgba(255,255,0,0.3);'
267
+ + 'left:' + (rect.right - br) + 'px;top:' + (rect.top + bt) + 'px;'
268
+ + 'width:' + br + 'px;height:' + (rect.height - bt - bb) + 'px;"></div>'
269
+ // Padding
270
+ + '<div style="position:fixed;background:rgba(144,238,144,0.3);'
271
+ + 'left:' + (rect.left + blw) + 'px;top:' + (rect.top + bt) + 'px;'
272
+ + 'width:' + (rect.width - blw - br) + 'px;height:' + pt + 'px;"></div>'
273
+ + '<div style="position:fixed;background:rgba(144,238,144,0.3);'
274
+ + 'left:' + (rect.left + blw) + 'px;top:' + (rect.bottom - bb - pb) + 'px;'
275
+ + 'width:' + (rect.width - blw - br) + 'px;height:' + pb + 'px;"></div>'
276
+ + '<div style="position:fixed;background:rgba(144,238,144,0.3);'
277
+ + 'left:' + (rect.left + blw) + 'px;top:' + (rect.top + bt + pt) + 'px;'
278
+ + 'width:' + pl + 'px;height:' + (rect.height - bt - bb - pt - pb) + 'px;"></div>'
279
+ + '<div style="position:fixed;background:rgba(144,238,144,0.3);'
280
+ + 'left:' + (rect.right - br - pr) + 'px;top:' + (rect.top + bt + pt) + 'px;'
281
+ + 'width:' + pr + 'px;height:' + (rect.height - bt - bb - pt - pb) + 'px;"></div>'
282
+ // Content
283
+ + '<div style="position:fixed;background:rgba(100,149,237,0.3);'
284
+ + 'left:' + (rect.left + blw + pl) + 'px;top:' + (rect.top + bt + pt) + 'px;'
285
+ + 'width:' + cw + 'px;height:' + ch + 'px;"></div>';
286
+
287
+ // Label
288
+ measureLabel.textContent = Math.round(rect.width) + ' x ' + Math.round(rect.height);
289
+ measureLabel.style.display = 'block';
290
+ measureLabel.style.left = (rect.right + 8) + 'px';
291
+ measureLabel.style.top = rect.top + 'px';
292
+ }
293
+
294
+ window.addEventListener('message', (e) => {
295
+ if (e.origin !== window.location.origin) return;
296
+ if (!e.data?.type?.startsWith('musea:')) return;
297
+ const { type, payload } = e.data;
298
+ switch (type) {
299
+ case 'musea:set-background': {
300
+ if (payload.pattern === 'checkerboard') {
301
+ document.body.style.background = '';
302
+ document.body.classList.add('musea-bg-checkerboard');
303
+ } else {
304
+ document.body.classList.remove('musea-bg-checkerboard');
305
+ document.body.style.background = payload.color || '';
306
+ }
307
+ break;
308
+ }
309
+ case 'musea:toggle-outline': {
310
+ toggleStyleById('musea-outline', payload.enabled,
311
+ '* { outline: 1px solid rgba(255, 0, 0, 0.3) !important; }');
312
+ break;
313
+ }
314
+ case 'musea:toggle-measure': {
315
+ measureActive = payload.enabled;
316
+ if (measureActive) {
317
+ createMeasureOverlay();
318
+ document.addEventListener('mousemove', onMeasureMouseMove);
319
+ } else {
320
+ document.removeEventListener('mousemove', onMeasureMouseMove);
321
+ removeMeasureOverlay();
322
+ }
323
+ break;
324
+ }
325
+ case 'musea:set-props': {
326
+ // Store props for remount - handled by preview module
327
+ if (window.__museaSetProps) {
328
+ window.__museaSetProps(payload.props || {});
329
+ }
330
+ break;
331
+ }
332
+ case 'musea:set-slots': {
333
+ // Store slots for remount - handled by preview module
334
+ if (window.__museaSetSlots) {
335
+ window.__museaSetSlots(payload.slots || {});
336
+ }
337
+ break;
338
+ }
339
+ case 'musea:run-a11y': {
340
+ // Run axe-core a11y test
341
+ const requestId = typeof payload?.requestId === 'string' ? payload.requestId : undefined;
342
+ (async () => {
343
+ try {
344
+ // Dynamically load axe-core from local vendor route if not already loaded
345
+ if (!window.axe) {
346
+ const script = document.createElement('script');
347
+ const _basePath = window.__MUSEA_BASE_PATH__
348
+ || location.pathname.replace(/\\/preview(?:\\/[^/]+\\.html)?$/, '');
349
+ script.src = _basePath + '/vendor/axe-core.min.js';
350
+ await new Promise((resolve, reject) => {
351
+ script.onload = resolve;
352
+ script.onerror = reject;
353
+ document.head.appendChild(script);
354
+ });
355
+ // A load event is not proof the vendor script exists. axe-core is
356
+ // an optional peer, so a static export can ship without it, and a
357
+ // static host is free to answer the missing asset with an SPA
358
+ // fallback: 200 plus HTML. The script tag then "loads" fine and
359
+ // window.axe is still undefined, which surfaced downstream as an
360
+ // opaque "cannot read properties of undefined" instead of the real
361
+ // cause.
362
+ if (!window.axe) {
363
+ throw new Error(
364
+ 'axe-core did not load from ' + script.src +
365
+ ' - install axe-core so the gallery can ship it, and check that the path is served as JavaScript rather than an SPA fallback'
366
+ );
367
+ }
368
+ }
369
+ // Run axe-core on the .musea-variant container only (not the full document)
370
+ const context = document.querySelector('.musea-variant') || document;
371
+ const results = await window.axe.run(context, {
372
+ // Run all rules without restrictions for comprehensive testing
373
+ resultTypes: ['violations', 'incomplete', 'passes']
374
+ });
375
+ window.parent.postMessage({
376
+ type: 'musea:a11y-result',
377
+ payload: {
378
+ requestId,
379
+ violations: results.violations.map(v => ({
380
+ id: v.id,
381
+ impact: v.impact,
382
+ description: v.description,
383
+ helpUrl: v.helpUrl,
384
+ nodes: v.nodes.map(n => ({
385
+ html: n.html,
386
+ target: n.target,
387
+ failureSummary: n.failureSummary
388
+ }))
389
+ })),
390
+ passes: results.passes.length,
391
+ incomplete: results.incomplete.length
392
+ }
393
+ }, parentOrigin);
394
+ } catch (err) {
395
+ window.parent.postMessage({
396
+ type: 'musea:a11y-result',
397
+ payload: {
398
+ requestId,
399
+ error: err instanceof Error ? err.message : String(err),
400
+ violations: [],
401
+ passes: 0,
402
+ incomplete: 0
403
+ }
404
+ }, parentOrigin);
405
+ }
406
+ })();
407
+ break;
408
+ }
409
+ }
410
+ });
411
+
412
+ // Notify parent that iframe is ready
413
+ window.parent.postMessage({ type: 'musea:ready', payload: {} }, parentOrigin);
414
+ }
415
+ `;
416
+ //#endregion
417
+ //#region src/preview/html.ts
418
+ function generatePreviewHtml(art, variant, _basePath, viteBase) {
419
+ const previewModuleUrl = `${_basePath}/preview-module?art=${encodeURIComponent(art.path)}&variant=${encodeURIComponent(variant.name)}`;
420
+ const base = (viteBase || "/").replace(/\/$/, "");
421
+ return `<!DOCTYPE html>
422
+ <html lang="en">
423
+ <head>
424
+ <meta charset="UTF-8">
425
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
426
+ <title>${escapeHtml(art.metadata.title)} - ${escapeHtml(variant.name)}</title>
427
+ <script type="module" src="${base}/@vite/client"><\/script>
428
+ <style>
429
+ @layer musea-preview {
430
+ *,
431
+ *::before,
432
+ *::after {
433
+ box-sizing: border-box;
434
+ }
435
+ :root {
436
+ --musea-preview-padding: clamp(1rem, 2vw, 1.5rem);
437
+ }
438
+ html, body {
439
+ width: 100%;
440
+ min-height: 100%;
441
+ margin: 0;
442
+ }
443
+ body {
444
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
445
+ background: #ffffff;
446
+ padding: var(--musea-preview-padding);
447
+ }
448
+ .musea-variant {
449
+ width: 100%;
450
+ min-height: calc(100vh - (var(--musea-preview-padding) * 2));
451
+ }
452
+ .musea-error {
453
+ color: #dc2626;
454
+ background: #fef2f2;
455
+ border: 1px solid #fecaca;
456
+ border-radius: 8px;
457
+ padding: 1rem;
458
+ font-size: 0.875rem;
459
+ max-width: 400px;
460
+ }
461
+ .musea-error-title {
462
+ font-weight: 600;
463
+ margin-bottom: 0.5rem;
464
+ }
465
+ .musea-error pre {
466
+ font-family: monospace;
467
+ font-size: 0.75rem;
468
+ white-space: pre-wrap;
469
+ word-break: break-all;
470
+ margin-top: 0.5rem;
471
+ padding: 0.5rem;
472
+ background: #fff;
473
+ border-radius: 4px;
474
+ }
475
+ .musea-loading {
476
+ display: flex;
477
+ align-items: center;
478
+ gap: 0.75rem;
479
+ color: #6b7280;
480
+ font-size: 0.875rem;
481
+ }
482
+ .musea-spinner {
483
+ width: 20px;
484
+ height: 20px;
485
+ border: 2px solid #e5e7eb;
486
+ border-top-color: #3b82f6;
487
+ border-radius: 50%;
488
+ animation: musea-preview-spin 0.8s linear infinite;
489
+ }
490
+ }
491
+ @keyframes musea-preview-spin { to { transform: rotate(360deg); } }
492
+
493
+ /* Musea Addons: Checkerboard background for transparent mode */
494
+ .musea-bg-checkerboard {
495
+ background-image:
496
+ linear-gradient(45deg, #ccc 25%, transparent 25%),
497
+ linear-gradient(-45deg, #ccc 25%, transparent 25%),
498
+ linear-gradient(45deg, transparent 75%, #ccc 75%),
499
+ linear-gradient(-45deg, transparent 75%, #ccc 75%) !important;
500
+ background-size: 20px 20px !important;
501
+ background-position: 0 0, 0 10px, 10px -10px, -10px 0 !important;
502
+ }
503
+
504
+ /* Musea Addons: Measure label */
505
+ .musea-measure-label {
506
+ position: fixed;
507
+ background: #333;
508
+ color: #fff;
509
+ font-size: 11px;
510
+ padding: 2px 6px;
511
+ border-radius: 3px;
512
+ pointer-events: none;
513
+ z-index: 100000;
514
+ }
515
+ </style>
516
+ </head>
517
+ <body>
518
+ <div id="app" class="musea-variant" data-art="${escapeHtml(art.path)}" data-variant="${escapeHtml(variant.name)}">
519
+ <div class="musea-loading">
520
+ <div class="musea-spinner"></div>
521
+ Loading component...
522
+ </div>
523
+ </div>
524
+ <script type="module" src="${previewModuleUrl}"><\/script>
525
+ </body>
526
+ </html>`;
527
+ }
528
+ //#endregion
529
+ //#region src/preview/index.ts
530
+ function generatePreviewModule(art, variantComponentName, variantName, cssImports = [], previewSetup = null, vueVersion = 3, toolbar = []) {
531
+ const artModuleId = `virtual:musea-art:${art.path}`;
532
+ const artModuleIdLiteral = JSON.stringify(artModuleId);
533
+ const variantNameLiteral = JSON.stringify(variantName);
534
+ const variantComponentNameLiteral = JSON.stringify(variantComponentName);
535
+ const cssImportStatements = cssImports.map((cssPath) => `import ${JSON.stringify(cssPath)};`).join("\n");
536
+ const setupImport = previewSetup ? `import __museaPreviewSetup from ${JSON.stringify(previewSetup)};` : "";
537
+ const globals = toolbar.length > 0;
538
+ const setupCall = previewSetup ? `await __museaPreviewSetup(app${globals ? ", { globals: __museaGlobals }" : ""});` : "";
539
+ const actionEvents = JSON.stringify(art.metadata.actionEvents ?? []);
540
+ const legacyVue = isLegacyVueVersion(vueVersion);
541
+ const vueImport = legacyVue ? `import Vue, { reactive, shallowRef${globals ? ", ref as __museaCreateGlobalsRef" : ""} } from 'vue';` : `import { createApp, reactive, shallowRef, h${globals ? ", ref as __museaCreateGlobalsRef" : ""} } from 'vue';`;
542
+ const destroyCurrentApp = legacyVue ? "currentApp.$destroy();" : "currentApp.unmount();";
543
+ const mountInitialApp = legacyVue ? "const app = new Vue({ render: (h) => h(VariantComponent) });" : "const app = createApp(VariantComponent);";
544
+ const mountCurrentApp = legacyVue ? "mountVue2App(app);" : "app.mount(container);\n currentApp = app;";
545
+ const mountHelper = legacyVue ? vue2MountHelperSnippet() : "";
546
+ const remountApp = legacyVue ? vue2RemountAppSnippet() : vue3RemountAppSnippet();
547
+ return `
548
+ ${cssImportStatements}
549
+ ${setupImport}
550
+ ${vueImport}
551
+ import * as artModule from ${artModuleIdLiteral};
552
+
553
+ const container = document.getElementById('app');
554
+
555
+ ${MUSEA_ADDONS_INIT_CODE}${generatePreviewGlobals(toolbar)}
556
+
557
+ let currentApp = null;
558
+ // Replace raw JSON snapshots so every literal prop name stays an own key.
559
+ const propsOverride = shallowRef({});
560
+ const slotsOverride = reactive({ default: '' });
561
+
562
+ function renderError(title, error) {
563
+ container.textContent = '';
564
+ const root = document.createElement('div');
565
+ root.className = 'musea-error';
566
+
567
+ const titleEl = document.createElement('div');
568
+ titleEl.className = 'musea-error-title';
569
+ titleEl.textContent = title;
570
+ root.appendChild(titleEl);
571
+
572
+ const messageEl = document.createElement('div');
573
+ messageEl.textContent = error instanceof Error ? error.message : String(error);
574
+ root.appendChild(messageEl);
575
+
576
+ const stack = error instanceof Error ? error.stack : '';
577
+ if (stack) {
578
+ const stackEl = document.createElement('pre');
579
+ stackEl.textContent = stack;
580
+ root.appendChild(stackEl);
581
+ }
582
+
583
+ container.appendChild(root);
584
+ }
585
+
586
+ ${mountHelper}
587
+
588
+ window.__museaSetProps = (props) => {
589
+ propsOverride.value = { ...props };
590
+ };
591
+
592
+ window.__museaSetSlots = (slots) => {
593
+ for (const key of Object.keys(slotsOverride)) {
594
+ delete slotsOverride[key];
595
+ }
596
+ Object.assign(slotsOverride, slots);
597
+ };
598
+
599
+ async function mount() {
600
+ try {
601
+ // Get the specific variant component
602
+ const VariantComponent = artModule[${variantComponentNameLiteral}];
603
+ const RawComponent = artModule.__component__;
604
+
605
+ if (!VariantComponent) {
606
+ throw new Error('Variant component ' + ${variantComponentNameLiteral} + ' not found in art module');
607
+ }
608
+
609
+ // Create and mount the app
610
+ ${mountInitialApp}
611
+ ${setupCall}
612
+ container.innerHTML = '';
613
+ container.className = 'musea-variant';
614
+ ${mountCurrentApp}
615
+
616
+ console.log('[musea-preview] Mounted variant:', ${variantNameLiteral});
617
+ __museaInitAddons(container, ${variantNameLiteral}, ${actionEvents});
618
+
619
+ // Override set-props to remount with raw component + props
620
+ const TargetComponent = RawComponent || VariantComponent;
621
+ window.__museaSetProps = (props) => {
622
+ propsOverride.value = { ...props };
623
+ remountWithProps(TargetComponent);
624
+ };
625
+ window.__museaSetSlots = (slots) => {
626
+ for (const key of Object.keys(slotsOverride)) {
627
+ delete slotsOverride[key];
628
+ }
629
+ Object.assign(slotsOverride, slots);
630
+ remountWithProps(TargetComponent);
631
+ };
632
+ } catch (error) {
633
+ console.error('[musea-preview] Failed to mount:', error);
634
+ renderError('Failed to render component', error);
635
+ }
636
+ }
637
+
638
+ async function remountWithProps(Component) {
639
+ if (currentApp) {
640
+ ${destroyCurrentApp}
641
+ }
642
+ ${remountApp}
643
+ ${setupCall}
644
+ container.innerHTML = '';
645
+ ${mountCurrentApp}
646
+ }
647
+
648
+ mount();
649
+ `;
650
+ }
651
+ function isLegacyVueVersion(version) {
652
+ return version === .11 || version === 1 || version === 2 || version === "2.7" || version === "legacy";
653
+ }
654
+ function vue2MountHelperSnippet() {
655
+ return `function mountVue2App(app) {
656
+ container.innerHTML = '';
657
+ const mountPoint = document.createElement('div');
658
+ container.appendChild(mountPoint);
659
+ app.$mount(mountPoint);
660
+ currentApp = app;
661
+ }`;
662
+ }
663
+ function vue2RemountAppSnippet() {
664
+ return `const app = new Vue({
665
+ render(h) {
666
+ const slotFns = {};
667
+ const children = [];
668
+ for (const [name, content] of Object.entries(slotsOverride)) {
669
+ if (!content) continue;
670
+ const slot = () => [h('span', String(content))];
671
+ slotFns[name] = slot;
672
+ if (name === 'default') children.push(...slot());
673
+ }
674
+ return h(Component, { props: { ...propsOverride.value }, scopedSlots: slotFns }, children);
675
+ }
676
+ });`;
677
+ }
678
+ function vue3RemountAppSnippet() {
679
+ return `const app = createApp({
680
+ setup() {
681
+ return () => {
682
+ const slotFns = {};
683
+ for (const [name, content] of Object.entries(slotsOverride)) {
684
+ if (content) slotFns[name] = () => h('span', String(content));
685
+ }
686
+ return h(Component, { ...propsOverride.value }, slotFns);
687
+ };
688
+ }
689
+ });`;
690
+ }
691
+ function generatePreviewModuleWithProps(art, variantComponentName, variantName, propsOverride, cssImports = [], previewSetup = null, vueVersion = 3, toolbar = []) {
692
+ const artModuleId = `virtual:musea-art:${art.path}`;
693
+ const artModuleIdLiteral = JSON.stringify(artModuleId);
694
+ const variantNameLiteral = JSON.stringify(variantName);
695
+ const variantComponentNameLiteral = JSON.stringify(variantComponentName);
696
+ const propsJson = JSON.stringify(propsOverride);
697
+ const cssImportStatements = cssImports.map((cssPath) => `import ${JSON.stringify(cssPath)};`).join("\n");
698
+ const setupImport = previewSetup ? `import __museaPreviewSetup from ${JSON.stringify(previewSetup)};` : "";
699
+ const globals = toolbar.length > 0;
700
+ const setupCall = previewSetup ? `await __museaPreviewSetup(app${globals ? ", { globals: __museaGlobals }" : ""});` : "";
701
+ const actionEvents = JSON.stringify(art.metadata.actionEvents ?? []);
702
+ const legacyVue = isLegacyVueVersion(vueVersion);
703
+ const vueImport = legacyVue ? `import Vue${globals ? ", { ref as __museaCreateGlobalsRef }" : ""} from 'vue';` : `import { createApp, h${globals ? ", ref as __museaCreateGlobalsRef" : ""} } from 'vue';`;
704
+ const wrappedComponent = legacyVue ? `const WrappedComponent = {
705
+ render(h) {
706
+ return h(VariantComponent, { props: propsOverride });
707
+ }
708
+ };` : `const WrappedComponent = {
709
+ render() {
710
+ return h(VariantComponent, propsOverride);
711
+ }
712
+ };`;
713
+ const appCreate = legacyVue ? "const app = new Vue(WrappedComponent);" : "const app = createApp(WrappedComponent);";
714
+ const appMount = legacyVue ? "const mountPoint = document.createElement('div');\n container.appendChild(mountPoint);\n app.$mount(mountPoint);" : "app.mount(container);";
715
+ return `
716
+ ${cssImportStatements}
717
+ ${setupImport}
718
+ ${vueImport}
719
+ import * as artModule from ${artModuleIdLiteral};
720
+
721
+ const container = document.getElementById('app');
722
+ const propsOverride = JSON.parse(${JSON.stringify(propsJson)});
723
+
724
+ ${MUSEA_ADDONS_INIT_CODE}${generatePreviewGlobals(toolbar)}
725
+
726
+ function renderError(title, error) {
727
+ container.textContent = '';
728
+ const root = document.createElement('div');
729
+ root.className = 'musea-error';
730
+
731
+ const titleEl = document.createElement('div');
732
+ titleEl.className = 'musea-error-title';
733
+ titleEl.textContent = title;
734
+ root.appendChild(titleEl);
735
+
736
+ const messageEl = document.createElement('div');
737
+ messageEl.textContent = error instanceof Error ? error.message : String(error);
738
+ root.appendChild(messageEl);
739
+
740
+ container.appendChild(root);
741
+ }
742
+
743
+ async function mount() {
744
+ try {
745
+ const VariantComponent = artModule[${variantComponentNameLiteral}];
746
+ if (!VariantComponent) {
747
+ throw new Error('Variant component ' + ${variantComponentNameLiteral} + ' not found');
748
+ }
749
+
750
+ ${wrappedComponent}
751
+
752
+ ${appCreate}
753
+ ${setupCall}
754
+ container.innerHTML = '';
755
+ container.className = 'musea-variant';
756
+ ${appMount}
757
+ console.log('[musea-preview] Mounted variant with props override:', ${variantNameLiteral});
758
+ __museaInitAddons(container, ${variantNameLiteral}, ${actionEvents});
759
+ } catch (error) {
760
+ console.error('[musea-preview] Failed to mount:', error);
761
+ renderError('Failed to render', error);
762
+ }
763
+ }
764
+
765
+ mount();
766
+ `;
767
+ }
768
+ //#endregion
769
+ //#region src/preview-module-id.ts
770
+ /** Keep the final colon delimiter unambiguous while retaining ordinary module IDs. */
771
+ function previewModuleId(artPath, variantName) {
772
+ return `virtual:musea-preview:${artPath}:${variantName.replaceAll("%", "%25").replaceAll(":", "%3A")}`;
773
+ }
774
+ //#endregion
775
+ //#region src/middleware-response.ts
776
+ /** Both transformed and fallback previews keep the same response contract. */
777
+ function sendPreviewModule(response, code) {
778
+ response.setHeader("Content-Type", "application/javascript");
779
+ response.setHeader("Cache-Control", "no-cache");
780
+ response.end(code);
781
+ }
782
+ function sendPreviewError(response, error) {
783
+ response.statusCode = 500;
784
+ response.end(error instanceof Error ? error.message : String(error));
785
+ }
786
+ /** Art fallbacks retain their existing headers and bound generation failures. */
787
+ function sendArtModuleFallback(response, generate) {
788
+ try {
789
+ const code = generate();
790
+ response.setHeader("Content-Type", "application/javascript");
791
+ response.end(code);
792
+ } catch (error) {
793
+ sendPreviewError(response, error);
794
+ }
795
+ }
796
+ //#endregion
797
+ //#region src/server-middleware.ts
798
+ const moduleDir$2 = path.dirname(fileURLToPath(import.meta.url));
799
+ const galleryAssetMimeTypes = {
800
+ ".js": "application/javascript",
801
+ ".css": "text/css",
802
+ ".svg": "image/svg+xml",
803
+ ".png": "image/png",
804
+ ".ico": "image/x-icon",
805
+ ".woff2": "font/woff2",
806
+ ".woff": "font/woff"
807
+ };
808
+ function resolveGalleryDistDir$1() {
809
+ return path.resolve(moduleDir$2, "gallery");
810
+ }
811
+ function resolveGallerySourceDir() {
812
+ return path.resolve(moduleDir$2, "../gallery");
813
+ }
814
+ function toViteFsPath(filePath) {
815
+ return encodeURI(`/@fs${filePath.split(path.sep).join("/")}`);
816
+ }
817
+ function ignorePackedGalleryAssetTransforms(html, basePath) {
818
+ const assetPrefix = `${basePath.replace(/\/+$/, "")}/assets/`;
819
+ return html.replace(/<script\b[^>]*>/giu, (tag) => {
820
+ const type = /\btype\s*=\s*(["'])module\1/iu.exec(tag);
821
+ const src = /\bsrc\s*=\s*(["'])([^"']+)\1/iu.exec(tag);
822
+ if (!type || !src || !src[2].startsWith(assetPrefix) || /\bvite-ignore\b/iu.test(tag)) return tag;
823
+ return tag.replace(/^<script\b/iu, "<script vite-ignore");
824
+ });
825
+ }
826
+ async function tryLoadSourceGalleryHtml(devServer, url, basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar) {
827
+ const gallerySourceDir = resolveGallerySourceDir();
828
+ const indexHtmlPath = path.join(gallerySourceDir, "index.html");
829
+ try {
830
+ await fs.promises.access(indexHtmlPath);
831
+ } catch {
832
+ return null;
833
+ }
834
+ const sourceEntryPath = toViteFsPath(path.join(gallerySourceDir, "main.ts"));
835
+ let html = await fs.promises.readFile(indexHtmlPath, "utf-8");
836
+ html = html.replace("src=\"./main.ts\"", `src="${sourceEntryPath}"`);
837
+ html = html.replace("</head>", `<script>${generateDevGlobalsScript(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar)}<\/script></head>`);
838
+ return devServer.transformIndexHtml(url, html);
839
+ }
840
+ async function generateFallbackGalleryHtml(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar) {
841
+ const { generateGalleryHtml } = await import("./gallery-DNxzJA4V.mjs");
842
+ return generateGalleryHtml(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar);
843
+ }
844
+ async function serveGalleryAsset(galleryDistDir, requestUrl, res, basePath = "/__musea__") {
845
+ try {
846
+ const filePath = resolveUrlPathInside(galleryDistDir, requestUrl, "asset path");
847
+ if (!(await fs.promises.stat(filePath)).isFile()) return false;
848
+ const content = await fs.promises.readFile(filePath);
849
+ const ext = path.extname(filePath);
850
+ res.setHeader("Content-Type", galleryAssetMimeTypes[ext] || "application/octet-stream");
851
+ res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
852
+ res.end(rewriteDevGalleryAsset(content, filePath, basePath));
853
+ return true;
854
+ } catch (error) {
855
+ if (error instanceof HttpError) {
856
+ res.statusCode = error.status;
857
+ res.end(error.message);
858
+ return true;
859
+ }
860
+ return false;
861
+ }
862
+ }
863
+ function registerMiddleware(devServer, ctx) {
864
+ const { basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar, artFiles } = ctx;
865
+ devServer.middlewares.use(basePath, async (req, res, next) => {
866
+ const url = req.url || "/";
867
+ if (url === "/" || url === "/index.html" || url.startsWith("/tokens") || url.startsWith("/component/") || url.startsWith("/tests")) {
868
+ const galleryDistDir = resolveGalleryDistDir$1();
869
+ const indexHtmlPath = path.join(galleryDistDir, "index.html");
870
+ try {
871
+ await fs.promises.access(indexHtmlPath);
872
+ let html = rewriteGalleryBase(await fs.promises.readFile(indexHtmlPath, "utf-8"), basePath);
873
+ html = html.replace("</head>", `<script>${generateDevGlobalsScript(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar)}<\/script></head>`);
874
+ res.setHeader("Content-Type", "text/html");
875
+ res.end(await devServer.transformIndexHtml(url, ignorePackedGalleryAssetTransforms(html, basePath)));
876
+ return;
877
+ } catch {
878
+ const sourceHtml = await tryLoadSourceGalleryHtml(devServer, url, basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar);
879
+ if (sourceHtml) {
880
+ res.setHeader("Content-Type", "text/html");
881
+ res.end(sourceHtml);
882
+ return;
883
+ }
884
+ const html = await generateFallbackGalleryHtml(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar);
885
+ res.setHeader("Content-Type", "text/html");
886
+ res.end(html);
887
+ return;
888
+ }
889
+ }
890
+ if (url.startsWith("/assets/")) {
891
+ if (await serveGalleryAsset(resolveGalleryDistDir$1(), url, res, basePath)) return;
892
+ }
893
+ next();
894
+ });
895
+ devServer.middlewares.use(`${basePath}/vendor/axe-core.min.js`, async (_req, res, _next) => {
896
+ try {
897
+ const axeCorePath = createRequire(import.meta.url).resolve("axe-core/axe.min.js");
898
+ const content = await fs.promises.readFile(axeCorePath, "utf-8");
899
+ res.setHeader("Content-Type", "application/javascript");
900
+ res.setHeader("Cache-Control", "public, max-age=86400");
901
+ res.end(content);
902
+ } catch {
903
+ res.statusCode = 404;
904
+ res.end("axe-core not installed");
905
+ }
906
+ });
907
+ devServer.middlewares.use(`${basePath}/preview-module`, async (req, res, _next) => {
908
+ const url = new URL(req.url || "", `http://localhost`);
909
+ const artPath = url.searchParams.get("art");
910
+ const variantName = url.searchParams.get("variant");
911
+ if (!artPath || !variantName) {
912
+ res.statusCode = 400;
913
+ res.end("Missing art or variant parameter");
914
+ return;
915
+ }
916
+ const art = artFiles.get(artPath);
917
+ if (!art) {
918
+ res.statusCode = 404;
919
+ res.end("Art not found");
920
+ return;
921
+ }
922
+ const variant = art.variants.find((v) => v.name === variantName);
923
+ if (!variant) {
924
+ res.statusCode = 404;
925
+ res.end("Variant not found");
926
+ return;
927
+ }
928
+ let variantComponentName;
929
+ try {
930
+ variantComponentName = variantComponentNames(art.variants).get(variant.name);
931
+ } catch (error) {
932
+ sendPreviewError(res, error);
933
+ return;
934
+ }
935
+ const moduleCode = generatePreviewModule(art, variantComponentName, variant.name, ctx.resolvedPreviewCss, ctx.resolvedPreviewSetup, 3, ctx.toolbar);
936
+ try {
937
+ const result = await devServer.transformRequest(previewModuleId(artPath, variantName));
938
+ if (result) {
939
+ sendPreviewModule(res, result.code);
940
+ return;
941
+ }
942
+ } catch {}
943
+ sendPreviewModule(res, moduleCode);
944
+ });
945
+ devServer.middlewares.use(`${basePath}/preview`, async (req, res, _next) => {
946
+ const url = new URL(req.url || "", `http://localhost`);
947
+ const artPath = url.searchParams.get("art");
948
+ const variantName = url.searchParams.get("variant");
949
+ if (!artPath || !variantName) {
950
+ res.statusCode = 400;
951
+ res.end("Missing art or variant parameter");
952
+ return;
953
+ }
954
+ const art = artFiles.get(artPath);
955
+ if (!art) {
956
+ res.statusCode = 404;
957
+ res.end("Art not found");
958
+ return;
959
+ }
960
+ const variant = art.variants.find((v) => v.name === variantName);
961
+ if (!variant) {
962
+ res.statusCode = 404;
963
+ res.end("Variant not found");
964
+ return;
965
+ }
966
+ const config = devServer.config;
967
+ const html = generatePreviewHtml(art, variant, basePath, config.base);
968
+ res.setHeader("Content-Type", "text/html");
969
+ res.end(html);
970
+ });
971
+ devServer.middlewares.use(`${basePath}/art`, async (req, res, next) => {
972
+ const url = new URL(req.url || "", "http://localhost");
973
+ let artPath;
974
+ try {
975
+ artPath = decodeUrlComponent(url.pathname.slice(1), "art path");
976
+ } catch (error) {
977
+ if (error instanceof HttpError) {
978
+ res.statusCode = error.status;
979
+ res.end(error.message);
980
+ return;
981
+ }
982
+ throw error;
983
+ }
984
+ if (!artPath) {
985
+ next();
986
+ return;
987
+ }
988
+ const art = artFiles.get(artPath);
989
+ if (!art) {
990
+ res.statusCode = 404;
991
+ res.end("Art not found: " + artPath);
992
+ return;
993
+ }
994
+ try {
995
+ const virtualId = `virtual:musea-art:${artPath}`;
996
+ const result = await devServer.transformRequest(virtualId);
997
+ if (result) sendPreviewModule(res, result.code);
998
+ else sendArtModuleFallback(res, () => generateArtModule(art, artPath, {
999
+ root: devServer.config.root,
1000
+ scanRoots: ctx.scanRoots
1001
+ }));
1002
+ } catch (err) {
1003
+ console.error("[musea] Failed to transform art module:", err);
1004
+ sendArtModuleFallback(res, () => generateArtModule(art, artPath, {
1005
+ root: devServer.config.root,
1006
+ scanRoots: ctx.scanRoots
1007
+ }));
1008
+ }
1009
+ });
1010
+ }
1011
+ //#endregion
1012
+ //#region src/api-routes/post-handlers.ts
1013
+ /** POST /api/preview-with-props */
1014
+ function handlePreviewWithProps(ctx, body, res, sendJson, sendError) {
1015
+ try {
1016
+ const { artPath: reqArtPath, variantName, props: propsOverride } = parseJsonBody(body);
1017
+ const art = ctx.artFiles.get(reqArtPath);
1018
+ if (!art) {
1019
+ sendError("Art not found", 404);
1020
+ return;
1021
+ }
1022
+ const variant = art.variants.find((v) => v.name === variantName);
1023
+ if (!variant) {
1024
+ sendError("Variant not found", 404);
1025
+ return;
1026
+ }
1027
+ const moduleCode = generatePreviewModuleWithProps(art, variantComponentNames(art.variants).get(variant.name), variant.name, propsOverride, ctx.resolvedPreviewCss, ctx.resolvedPreviewSetup, 3, ctx.toolbar);
1028
+ res.setHeader("Content-Type", "application/javascript");
1029
+ res.end(moduleCode);
1030
+ } catch (e) {
1031
+ if (e instanceof HttpError) {
1032
+ sendError(e.message, e.status);
1033
+ return;
1034
+ }
1035
+ sendError(e instanceof Error ? e.message : String(e));
1036
+ }
1037
+ }
1038
+ /** POST /api/generate */
1039
+ async function handleGenerate(ctx, body, sendJson, sendError) {
1040
+ try {
1041
+ const { componentPath: reqComponentPath, options: autogenOptions } = parseJsonBody(body);
1042
+ if (typeof reqComponentPath !== "string") {
1043
+ sendError("Missing required field: componentPath", 400);
1044
+ return;
1045
+ }
1046
+ if (!reqComponentPath.toLowerCase().endsWith(".vue")) {
1047
+ sendError("componentPath must be a .vue file", 400);
1048
+ return;
1049
+ }
1050
+ const componentPath = resolveInside(ctx.config.root, reqComponentPath, "componentPath");
1051
+ assertVueSourcePath(componentPath, "componentPath");
1052
+ const { generateArtFile: genArt } = await import("./autogen/index.mjs");
1053
+ const result = await genArt(componentPath, autogenOptions);
1054
+ sendJson({
1055
+ generated: true,
1056
+ componentName: result.componentName,
1057
+ variants: result.variants,
1058
+ artFileContent: result.artFileContent
1059
+ });
1060
+ } catch (e) {
1061
+ if (e instanceof HttpError) {
1062
+ sendError(e.message, e.status);
1063
+ return;
1064
+ }
1065
+ sendError(e instanceof Error ? e.message : String(e));
1066
+ }
1067
+ }
1068
+ /** POST /api/run-vrt */
1069
+ async function handleRunVrt(ctx, body, sendJson, sendError) {
1070
+ try {
1071
+ const { artPath, updateSnapshots } = parseJsonBody(body);
1072
+ if (artPath !== void 0 && typeof artPath !== "string") throw new HttpError("artPath must be a string", 400);
1073
+ if (artPath !== void 0 && !ctx.artFiles.has(artPath)) throw new HttpError("Art not found", 404);
1074
+ const { MuseaVrtRunner, generateVrtJsonReport, generateVrtReport } = await import("./vrt.mjs");
1075
+ const { a11y: _a11y, ...configured } = ctx.vrt ?? {};
1076
+ const snapshotDir = path.resolve(ctx.config.root, configured.snapshotDir ?? ".vize/snapshots");
1077
+ const reportDir = path.resolve(ctx.config.root, ".vize/reports");
1078
+ const projectRoot = ctx.projectRoot ?? ctx.config.root;
1079
+ const reportTarget = artPath === void 0 ? void 0 : resolveArtReportTarget(artPath, ctx.artFiles.keys(), projectRoot, reportDir);
1080
+ if (reportTarget) await assertArtReportOwnership(reportTarget, projectRoot);
1081
+ const runner = new MuseaVrtRunner({
1082
+ ...configured,
1083
+ capture: {
1084
+ ...configured.capture,
1085
+ waitForPreviewReady: true
1086
+ },
1087
+ snapshotDir,
1088
+ projectRoot,
1089
+ previewBasePath: publicBasePathFromViteBase(ctx.config.base, ctx.basePath)
1090
+ });
1091
+ const baseUrl = `http://localhost:${ctx.getDevServerPort()}`;
1092
+ let artsToTest = Array.from(ctx.artFiles.values());
1093
+ if (artPath) artsToTest = artsToTest.filter((a) => a.path === artPath);
1094
+ const { results, summary } = await (async () => {
1095
+ await runner.start();
1096
+ try {
1097
+ const results = await runner.runTests(artsToTest, baseUrl, { updateSnapshots });
1098
+ return {
1099
+ results,
1100
+ summary: runner.getSummary(results)
1101
+ };
1102
+ } finally {
1103
+ await runner.stop();
1104
+ }
1105
+ })();
1106
+ const jsonReportPath = reportTarget?.jsonReportPath ?? path.join(reportDir, "vrt-report.json");
1107
+ const htmlReportPath = reportTarget?.htmlReportPath ?? path.join(reportDir, "vrt-report.html");
1108
+ const jsonReport = generateVrtJsonReport(results, summary);
1109
+ await fs.promises.mkdir(reportDir, { recursive: true });
1110
+ await fs.promises.writeFile(jsonReportPath, reportTarget ? attachArtReportOwner(jsonReport, reportTarget) : jsonReport, "utf-8");
1111
+ await fs.promises.writeFile(htmlReportPath, generateVrtReport(results, summary), "utf-8");
1112
+ sendJson({
1113
+ success: true,
1114
+ summary,
1115
+ results: results.map((r) => ({
1116
+ artPath: r.artPath,
1117
+ variantName: r.variantName,
1118
+ viewport: r.viewport.name,
1119
+ passed: r.passed,
1120
+ isNew: r.isNew,
1121
+ diffPercentage: r.diffPercentage,
1122
+ snapshotPath: r.snapshotPath,
1123
+ currentPath: r.currentPath,
1124
+ diffPath: r.diffPath,
1125
+ diffStyle: r.diffStyle,
1126
+ error: r.error
1127
+ })),
1128
+ artifacts: {
1129
+ reportDir,
1130
+ htmlReportPath,
1131
+ jsonReportPath,
1132
+ snapshotDir,
1133
+ currentDir: path.join(snapshotDir, "current"),
1134
+ diffDir: path.join(snapshotDir, "diff")
1135
+ }
1136
+ });
1137
+ } catch (e) {
1138
+ if (e instanceof HttpError) {
1139
+ sendError(e.message, e.status);
1140
+ return;
1141
+ }
1142
+ sendError(e instanceof Error ? e.message : String(e));
1143
+ }
1144
+ }
1145
+ //#endregion
1146
+ //#region src/api-routes/index.ts
1147
+ /**
1148
+ * Create the API middleware handler for the Musea gallery.
1149
+ *
1150
+ * Returns a Connect-compatible middleware function that handles all
1151
+ * `/api/...` sub-routes under the configured basePath.
1152
+ */
1153
+ function createApiMiddleware(ctx) {
1154
+ return async (req, res, next) => {
1155
+ const sendJson = (data, status = 200) => {
1156
+ res.statusCode = status;
1157
+ res.setHeader("Content-Type", "application/json");
1158
+ res.end(JSON.stringify(data));
1159
+ };
1160
+ const sendError = (message, status = 500) => {
1161
+ sendJson({ error: message }, status);
1162
+ };
1163
+ const readBody = () => collectRequestBody(req, ctx.apiBodyLimit ?? 1048576);
1164
+ const url = req.url || "/";
1165
+ try {
1166
+ const requestError = validateDevApiRequest(req, ctx.devSessionToken);
1167
+ if (requestError) {
1168
+ sendError(requestError.message, requestError.status);
1169
+ return;
1170
+ }
1171
+ if (url === "/arts" && req.method === "GET") {
1172
+ sendJson(sortedArts(ctx.artFiles.values()));
1173
+ return;
1174
+ }
1175
+ if (url === "/tokens/usage" && req.method === "GET") {
1176
+ await handleTokensUsage(ctx, sendJson);
1177
+ return;
1178
+ }
1179
+ if (url === "/tokens" && req.method === "GET") {
1180
+ await handleTokensGet(ctx, sendJson);
1181
+ return;
1182
+ }
1183
+ if (url === "/tokens" && req.method === "POST") {
1184
+ await handleTokensCreate(ctx, readBody, sendJson, sendError);
1185
+ return;
1186
+ }
1187
+ if (url === "/tokens" && req.method === "PUT") {
1188
+ await handleTokensUpdate(ctx, readBody, sendJson, sendError);
1189
+ return;
1190
+ }
1191
+ if (url === "/tokens" && req.method === "DELETE") {
1192
+ await handleTokensDelete(ctx, readBody, sendJson, sendError);
1193
+ return;
1194
+ }
1195
+ if (url?.startsWith("/arts/") && req.method === "PUT") {
1196
+ const sourceMatch = url.slice(6).match(/^(.+)\/source$/);
1197
+ if (sourceMatch) {
1198
+ const artPath = decodeUrlComponent(sourceMatch[1], "art path");
1199
+ if (!ctx.artFiles.get(artPath)) {
1200
+ sendError("Art not found", 404);
1201
+ return;
1202
+ }
1203
+ const safeArtPath = resolveInside(ctx.config.root, artPath, "art path");
1204
+ assertArtVueSourcePath(safeArtPath);
1205
+ const { source } = parseJsonBody(await readBody());
1206
+ if (typeof source !== "string") {
1207
+ sendError("Missing required field: source", 400);
1208
+ return;
1209
+ }
1210
+ await fs.promises.writeFile(safeArtPath, source, "utf-8");
1211
+ await ctx.processArtFile(safeArtPath);
1212
+ sendJson({ success: true });
1213
+ return;
1214
+ }
1215
+ next();
1216
+ return;
1217
+ }
1218
+ if (url?.startsWith("/arts/") && req.method === "GET") {
1219
+ const rest = url.slice(6);
1220
+ const sourceMatch = rest.match(/^(.+)\/source$/);
1221
+ const paletteMatch = rest.match(/^(.+)\/palette$/);
1222
+ const analysisMatch = rest.match(/^(.+)\/analysis$/);
1223
+ const docsMatch = rest.match(/^(.+)\/docs$/);
1224
+ if (sourceMatch) {
1225
+ await handleArtSource(ctx, sourceMatch, sendJson, sendError);
1226
+ return;
1227
+ }
1228
+ if (paletteMatch) {
1229
+ await handleArtPalette(ctx, paletteMatch, sendJson, sendError);
1230
+ return;
1231
+ }
1232
+ if (analysisMatch) {
1233
+ await handleArtAnalysis(ctx, analysisMatch, sendJson, sendError);
1234
+ return;
1235
+ }
1236
+ if (docsMatch) {
1237
+ await handleArtDocs(ctx, docsMatch, sendJson, sendError);
1238
+ return;
1239
+ }
1240
+ const artPath = decodeUrlComponent(rest, "art path");
1241
+ const art = ctx.artFiles.get(artPath);
1242
+ if (art) sendJson(art);
1243
+ else sendError("Art not found", 404);
1244
+ return;
1245
+ }
1246
+ if (req.method === "POST") {
1247
+ const body = await readBody();
1248
+ if (url === "/preview-with-props") {
1249
+ handlePreviewWithProps(ctx, body, res, sendJson, sendError);
1250
+ return;
1251
+ }
1252
+ if (url === "/generate") {
1253
+ await handleGenerate(ctx, body, sendJson, sendError);
1254
+ return;
1255
+ }
1256
+ if (url === "/run-vrt") {
1257
+ await handleRunVrt(ctx, body, sendJson, sendError);
1258
+ return;
1259
+ }
1260
+ }
1261
+ next();
1262
+ } catch (e) {
1263
+ if (e instanceof HttpError) {
1264
+ sendError(e.message, e.status);
1265
+ return;
1266
+ }
1267
+ sendError(e instanceof Error ? e.message : String(e));
1268
+ }
1269
+ };
1270
+ }
1271
+ //#endregion
1272
+ //#region src/manifest.ts
1273
+ /**
1274
+ * Generate the virtual manifest module code containing all art file metadata.
1275
+ */
1276
+ function generateManifestModule(artFiles) {
1277
+ const arts = sortedArts(artFiles.values());
1278
+ return `export const arts = ${JSON.stringify(arts, null, 2)};`;
1279
+ }
1280
+ //#endregion
1281
+ //#region src/art-variant-sfc.ts
1282
+ /**
1283
+ * Compile an `<art>` variant through the SFC pipeline.
1284
+ *
1285
+ * Variants used to be emitted as `template:` strings for Vue's runtime
1286
+ * compiler, which never sees the SFC pipeline. Any template expression relying
1287
+ * on SFC-time compilation therefore failed at render time — most importantly
1288
+ * TypeScript, even though `.art.vue` files are authored with
1289
+ * `<script setup lang="ts">` (#3857).
1290
+ *
1291
+ * Compiling the raw template with the template compiler is not enough: it
1292
+ * leaves TypeScript in place *and* its identifier prefixer gives up on TS
1293
+ * syntax, so `items[0]!.isValid` stays unprefixed and throws at runtime. Only
1294
+ * the SFC pipeline handles both, which is what the issue asks for — the variant
1295
+ * is compiled the same way the enclosing SFC is:
1296
+ *
1297
+ * :disabled="items[0]!.isValid" -> disabled: $setup.items[0].isValid
1298
+ * @u="(f: File | null) => …" -> onU: (f) => $setup.file = f
1299
+ *
1300
+ * The generated module render function receives setup state through Vue's
1301
+ * proxy-unwrapped `$setup` argument, so refs intentionally do not retain an
1302
+ * explicit `.value` access in this output mode.
1303
+ */
1304
+ /**
1305
+ * Rebase the art file's `<script setup>` for a virtual module.
1306
+ *
1307
+ * A variant compiles into a virtual module, and a relative specifier cannot be
1308
+ * resolved from one — the art module rebases its own imports for exactly this
1309
+ * reason, and the variant needs the same treatment or every relative import in
1310
+ * an art file fails to resolve.
1311
+ */
1312
+ function rebaseScriptSetup(scriptSetup, artDir) {
1313
+ if (!scriptSetup.trim()) return "";
1314
+ const parsed = parseScriptSetupForArt(scriptSetup);
1315
+ return [...parsed.imports.map((statement) => rewriteRelativeImportStatement(statement, artDir)), ...parsed.setupBody].join("\n").trim();
1316
+ }
1317
+ /**
1318
+ * Build the synthetic SFC source for one variant.
1319
+ *
1320
+ * The art file's own `<script setup>` becomes the variant's setup block, so
1321
+ * bindings resolve exactly as they do in the authored file, and `lang="ts"` is
1322
+ * carried over so the pipeline strips TypeScript from template expressions.
1323
+ */
1324
+ function buildVariantSfcSource(art, variantTemplate, variantName, options = {}) {
1325
+ if (options.sharedBindings && options.sharedBindings.names.length > 0) {
1326
+ const { moduleId, names } = options.sharedBindings;
1327
+ const escapedShared = variantName.replace(/"/g, "&quot;");
1328
+ return `<script setup lang="ts">\n` + (options.componentImportPath && options.componentBindingName && !names.includes(options.componentBindingName) ? `import ${options.componentBindingName} from ${JSON.stringify(options.componentImportPath)}\n` : "") + `import { ${names.join(", ")} } from ${JSON.stringify(moduleId)}\n<\/script>\n<template><div data-variant="${escapedShared}">${variantTemplate}</div></template>\n`;
1329
+ }
1330
+ const scriptSetup = rebaseScriptSetup(options.scriptSetup ?? art.scriptSetupContent ?? "", path.dirname(options.artFilePath ?? art.path));
1331
+ return `${`<script setup lang="ts">\n${`${options.componentImportPath && options.componentBindingName ? `import ${options.componentBindingName} from ${JSON.stringify(options.componentImportPath)}\n` : ""}${scriptSetup.trim()}`.trim()}\n<\/script>\n`}<template><div data-variant="${variantName.replace(/"/g, "&quot;")}">${variantTemplate}</div></template>\n`;
1332
+ }
1333
+ /**
1334
+ * Compile a variant to a self-contained ES module exporting the component.
1335
+ *
1336
+ * Each variant compiles to its own module because `compileSfc` emits a complete
1337
+ * module with its own `export default` and imports; concatenating several into
1338
+ * one art module would redeclare bindings and collide on the default export.
1339
+ */
1340
+ function compileVariantSfc(art, variantTemplate, variantName, filename, options = {}) {
1341
+ const component = resolveArtComponent(art, filename, options.parsedScriptSetup ?? null, {
1342
+ root: options.root,
1343
+ scanRoots: options.scanRoots
1344
+ });
1345
+ const source = buildVariantSfcSource(art, expandSelfTag(variantTemplate, component.componentTagName), variantName, {
1346
+ scriptSetup: options.scriptSetup,
1347
+ componentImportPath: component.componentImportPath,
1348
+ componentBindingName: component.componentBindingName,
1349
+ artFilePath: filename,
1350
+ sharedBindings: options.sharedBindings
1351
+ });
1352
+ const result = loadNative().compileSfc(source, { filename });
1353
+ return {
1354
+ code: result.code ?? "",
1355
+ errors: (result.errors ?? []).map((error) => typeof error === "string" ? error : error.message ?? JSON.stringify(error))
1356
+ };
1357
+ }
1358
+ //#endregion
1359
+ //#region src/art-shared-setup.ts
1360
+ /**
1361
+ * One shared `<script setup>` instance for an art file's variants.
1362
+ *
1363
+ * `scriptSetupIsolated: false` opts an art file out of per-variant isolation:
1364
+ * every variant sees the same setup instance, so state written in one variant is
1365
+ * visible in the next. Compiling each variant as its own SFC (#3857) would give
1366
+ * each one its own setup and silently drop that, so the shared case hoists the
1367
+ * setup into this module and the variants import its bindings instead of
1368
+ * declaring them.
1369
+ *
1370
+ * A dedicated module rather than the art module itself, because the art module
1371
+ * imports the variants — routing the shared state through it would make that a
1372
+ * cycle.
1373
+ */
1374
+ /**
1375
+ * The binding names a variant SFC should import from the shared module.
1376
+ *
1377
+ * `<script setup>` resolves template identifiers from its own bindings, and an
1378
+ * import is a binding, so importing each name by hand is what makes the shared
1379
+ * state reachable from the variant's template.
1380
+ */
1381
+ function sharedBindingNames(parsed) {
1382
+ return [...new Set(parsed.returnNames)].filter((name) => /^[A-Za-z_$][\w$]*$/.test(name));
1383
+ }
1384
+ function generateSharedSetupModule(art, filePath) {
1385
+ const parsed = parseSharedScriptSetup(art);
1386
+ if (!parsed) return "export {};\n";
1387
+ const artDir = path.dirname(filePath);
1388
+ const imports = parsed.imports.map((statement) => rewriteRelativeImportStatement(statement, artDir)).join("\n");
1389
+ const names = sharedBindingNames(parsed);
1390
+ return [
1391
+ imports,
1392
+ parsed.setupBody.join("\n"),
1393
+ names.length > 0 ? `export { ${names.join(", ")} };` : "export {};",
1394
+ ""
1395
+ ].join("\n");
1396
+ }
1397
+ function parseSharedScriptSetup(art) {
1398
+ if (!art.scriptSetupContent) return null;
1399
+ return parseScriptSetupForArt(art.scriptSetupContent);
1400
+ }
1401
+ //#endregion
1402
+ //#region src/plugin/inline-art-query.ts
1403
+ /** Consume only the custom block already registered as this instance's inline Art. */
1404
+ function loadInlineArtCustomBlock(state, id) {
1405
+ if (!state.inlineArt) return null;
1406
+ const queryStart = id.indexOf("?");
1407
+ if (queryStart === -1) return null;
1408
+ const requestPath = id.slice(0, queryStart);
1409
+ const file = requestPath.startsWith("/@fs/") ? requestPath.slice(4) : requestPath;
1410
+ if (!file.endsWith(".vue") || file.endsWith(".art.vue")) return null;
1411
+ const query = new URLSearchParams(id.slice(queryStart + 1));
1412
+ if (query.getAll("vue").length !== 1 || query.get("vue") !== "" || query.getAll("type").length !== 1 || query.get("type") !== "art" || query.getAll("index").length !== 1) return null;
1413
+ const indexText = query.get("index");
1414
+ if (!/^(?:0|[1-9]\d*)$/.test(indexText)) return null;
1415
+ const index = Number(indexText);
1416
+ if (!Number.isSafeInteger(index)) return null;
1417
+ const art = state.artFiles.get(file);
1418
+ if (!art?.isInline || art.path !== file || art.componentPath !== file || art.inlineArtBlockIndex !== index || !isTrustedSourcePath(state.getConfigRoot(), state.getScanRoots(), file)) return null;
1419
+ return "export default {};\n";
1420
+ }
1421
+ //#endregion
1422
+ //#region src/plugin/virtual.ts
1423
+ /**
1424
+ * Virtual module handling for the Musea Vite plugin.
1425
+ *
1426
+ * Contains `resolveId`, `load`, and `handleHotUpdate` hooks that
1427
+ * manage virtual modules for gallery, manifest, preview, and art files.
1428
+ */
1429
+ const VIRTUAL_MUSEA_PREFIX = "\0musea:";
1430
+ const VIRTUAL_GALLERY = "\0musea-gallery";
1431
+ const VIRTUAL_MANIFEST = "\0musea-manifest";
1432
+ /**
1433
+ * Recover a variant name from a virtual module id.
1434
+ *
1435
+ * `generateArtModule` percent-encodes it, so a hand-written import with an
1436
+ * invalid escape still falls back to the raw text instead of throwing a
1437
+ * `URIError` out of `load`.
1438
+ */
1439
+ function decodeVariantName(encoded) {
1440
+ try {
1441
+ return decodeURIComponent(encoded);
1442
+ } catch {
1443
+ return encoded;
1444
+ }
1445
+ }
1446
+ function createResolveId(state) {
1447
+ return function resolveId(id) {
1448
+ const root = state.getConfigRoot();
1449
+ const styleRequest = parseArtStyleRequest(id);
1450
+ if (styleRequest && state.artFiles.has(styleRequest.filePath)) return id.startsWith("\0") ? id : `\0${id}`;
1451
+ if (id === "\0musea-gallery") return VIRTUAL_GALLERY;
1452
+ if (id === "\0musea-manifest") return VIRTUAL_MANIFEST;
1453
+ if (id.startsWith("virtual:musea-preview:")) return "\0musea-preview:" + id.slice(22);
1454
+ if (id.startsWith("virtual:musea-variant:")) return "\0musea-variant:" + id.slice(22) + "?musea-virtual";
1455
+ if (id.startsWith("virtual:musea-shared:")) return "\0musea-shared:" + id.slice(21) + "?musea-virtual";
1456
+ if (id.startsWith("virtual:musea-art:")) {
1457
+ const artPath = id.slice(18);
1458
+ if (state.artFiles.has(artPath)) return "\0musea-art:" + artPath + "?musea-virtual";
1459
+ }
1460
+ if (id.endsWith(".art.vue")) {
1461
+ const resolved = path.resolve(root, id);
1462
+ if (state.artFiles.has(resolved)) return VIRTUAL_MUSEA_PREFIX + resolved + "?musea-virtual";
1463
+ }
1464
+ if (state.inlineArt && id.endsWith(".vue") && !id.endsWith(".art.vue")) {
1465
+ const resolved = path.resolve(root, id);
1466
+ if (state.artFiles.has(resolved)) return VIRTUAL_MUSEA_PREFIX + resolved + "?musea-virtual";
1467
+ }
1468
+ return null;
1469
+ };
1470
+ }
1471
+ function createLoad(state) {
1472
+ return function load(id) {
1473
+ const inlineArtBlock = loadInlineArtCustomBlock(state, id);
1474
+ if (inlineArtBlock !== null) return inlineArtBlock;
1475
+ const styleRequest = parseArtStyleRequest(id);
1476
+ if (styleRequest) return loadArtStyle(state.artFiles.get(styleRequest.filePath), styleRequest);
1477
+ if (id === "\0musea-gallery") return generateGalleryModule(state.basePath);
1478
+ if (id === "\0musea-manifest") return generateManifestModule(state.artFiles);
1479
+ if (id.startsWith("\0musea-preview:")) {
1480
+ const rest = id.slice(15);
1481
+ const lastColonIndex = rest.lastIndexOf(":");
1482
+ if (lastColonIndex !== -1) {
1483
+ const artPath = rest.slice(0, lastColonIndex);
1484
+ const variantName = decodeVariantName(rest.slice(lastColonIndex + 1));
1485
+ const art = state.artFiles.get(artPath);
1486
+ if (art) {
1487
+ const variantComponentName = variantComponentNames(art.variants).get(variantName);
1488
+ if (!variantComponentName) return null;
1489
+ return generatePreviewModule(art, variantComponentName, variantName, state.resolvedPreviewCss, state.resolvedPreviewSetup, state.getVueVersion(), state.toolbar);
1490
+ }
1491
+ }
1492
+ }
1493
+ if (id.startsWith("\0musea-shared:")) {
1494
+ const artPath = id.slice(14).replace(/\?musea-virtual$/, "");
1495
+ const art = state.artFiles.get(artPath);
1496
+ if (art) return generateSharedSetupModule(art, artPath);
1497
+ }
1498
+ if (id.startsWith("\0musea-variant:")) {
1499
+ const rest = id.slice(15).replace(/\?musea-virtual$/, "");
1500
+ const lastColonIndex = rest.lastIndexOf(":");
1501
+ if (lastColonIndex !== -1) {
1502
+ const artPath = rest.slice(0, lastColonIndex);
1503
+ const variantName = decodeVariantName(rest.slice(lastColonIndex + 1));
1504
+ const art = state.artFiles.get(artPath);
1505
+ const variant = art?.variants.find((candidate) => candidate.name === variantName);
1506
+ if (art && variant) {
1507
+ const parsedScriptSetup = art.scriptSetupContent ? parseScriptSetupForArt(art.scriptSetupContent) : null;
1508
+ const shared = art.scriptSetupIsolated === false && parsedScriptSetup ? {
1509
+ moduleId: `virtual:musea-shared:${artPath}`,
1510
+ names: sharedBindingNames(parsedScriptSetup)
1511
+ } : void 0;
1512
+ const compiled = compileVariantSfc(art, variant.template, variant.name, artPath, {
1513
+ scriptSetup: art.scriptSetupContent,
1514
+ parsedScriptSetup,
1515
+ root: state.getConfigRoot(),
1516
+ scanRoots: state.getScanRoots(),
1517
+ sharedBindings: shared
1518
+ });
1519
+ if (compiled.errors.length > 0) throw new Error(`Failed to compile <art> variant "${variantName}" in ${artPath}:\n${compiled.errors.join("\n")}`);
1520
+ if (!compiled.code) throw new Error(`The compiler produced no code for <art> variant "${variantName}" in ${artPath}.`);
1521
+ return compiled.code;
1522
+ }
1523
+ }
1524
+ }
1525
+ if (id.startsWith("\0musea-art:")) {
1526
+ const artPath = id.slice(11).replace(/\?musea-virtual$/, "");
1527
+ const art = state.artFiles.get(artPath);
1528
+ if (art) return generateArtModule(art, artPath, {
1529
+ root: state.getConfigRoot(),
1530
+ scanRoots: state.getScanRoots(),
1531
+ vueVersion: state.getVueVersion()
1532
+ });
1533
+ }
1534
+ if (id.startsWith("\0musea:")) {
1535
+ const realPath = id.slice(7).replace(/\?musea-virtual$/, "");
1536
+ const art = state.artFiles.get(realPath);
1537
+ if (art) return generateArtModule(art, realPath, {
1538
+ root: state.getConfigRoot(),
1539
+ scanRoots: state.getScanRoots(),
1540
+ vueVersion: state.getVueVersion()
1541
+ });
1542
+ }
1543
+ return null;
1544
+ };
1545
+ }
1546
+ function createHandleHotUpdate(state) {
1547
+ return async function handleHotUpdate(ctx) {
1548
+ const { file } = ctx;
1549
+ if (file.endsWith(".art.vue") && state.artFiles.has(file)) {
1550
+ await state.processArtFile(file);
1551
+ return artHotUpdateModules(state, file, ctx.modules);
1552
+ }
1553
+ if (state.inlineArt && file.endsWith(".vue") && !file.endsWith(".art.vue") && state.artFiles.has(file)) {
1554
+ await state.processArtFile(file);
1555
+ return artHotUpdateModules(state, file, ctx.modules);
1556
+ }
1557
+ };
1558
+ }
1559
+ function artHotUpdateModules(state, file, sourceModules) {
1560
+ const modules = new Set(sourceModules);
1561
+ const graph = state.getServer()?.moduleGraph;
1562
+ if (!graph) return [...modules];
1563
+ const exactIds = new Set([
1564
+ `${VIRTUAL_MUSEA_PREFIX}${file}?musea-virtual`,
1565
+ `\0musea-art:${file}?musea-virtual`,
1566
+ `\0musea-shared:${file}?musea-virtual`
1567
+ ]);
1568
+ const derivedPrefixes = [
1569
+ `\0musea-variant:${file}:`,
1570
+ `\0musea-preview:${file}:`,
1571
+ `\0${file}.__musea_style_`
1572
+ ];
1573
+ for (const [id, module] of graph.idToModuleMap) if (exactIds.has(id) || derivedPrefixes.some((prefix) => id.startsWith(prefix))) modules.add(module);
1574
+ return [...modules];
1575
+ }
1576
+ //#endregion
1577
+ //#region src/plugin/watch.ts
1578
+ function createMuseaWatchTargets(files) {
1579
+ return [...new Set(files)];
1580
+ }
1581
+ function watchMuseaArtFiles(watcher, files) {
1582
+ const targets = createMuseaWatchTargets(files);
1583
+ if (targets.length === 0) return;
1584
+ watcher.add(targets);
1585
+ }
1586
+ //#endregion
1587
+ //#region src/plugin/vue-alias.ts
1588
+ const require = createRequire(import.meta.url);
1589
+ function createVueRuntimeCompilerAlias(options = {}) {
1590
+ return {
1591
+ find: /^vue$/,
1592
+ replacement: resolveVueRuntimeCompiler(options)
1593
+ };
1594
+ }
1595
+ function resolveVueRuntimeCompiler(options) {
1596
+ if (options.runtimeCompiler) return normalizeRuntimeCompilerOverride(options.runtimeCompiler, options.root);
1597
+ const root = options.root ?? process.cwd();
1598
+ const projectRequire = createRequire(path.join(root, "package.json"));
1599
+ try {
1600
+ return projectRequire.resolve("vue/dist/vue.esm-bundler.js");
1601
+ } catch {}
1602
+ try {
1603
+ return require.resolve("vue/dist/vue.esm-bundler.js");
1604
+ } catch {
1605
+ return "vue/dist/vue.esm-bundler.js";
1606
+ }
1607
+ }
1608
+ function normalizeRuntimeCompilerOverride(value, root) {
1609
+ if (path.isAbsolute(value) || !value.startsWith(".")) return value;
1610
+ return path.resolve(root ?? process.cwd(), value);
1611
+ }
1612
+ //#endregion
1613
+ //#region src/plugin/storybook-inputs.ts
1614
+ function isStorybookTsxInput(filePath) {
1615
+ return /\.(?:stories|story)\.tsx$/i.test(filePath);
1616
+ }
1617
+ async function scanStorybookTsxInputs(root, include, exclude) {
1618
+ const files = /* @__PURE__ */ new Set();
1619
+ const visitedDirs = /* @__PURE__ */ new Set();
1620
+ async function scan(dir) {
1621
+ const resolvedDir = path.resolve(dir);
1622
+ if (visitedDirs.has(resolvedDir)) return;
1623
+ visitedDirs.add(resolvedDir);
1624
+ let entries;
1625
+ try {
1626
+ entries = await fs.promises.readdir(resolvedDir, { withFileTypes: true });
1627
+ } catch {
1628
+ return;
1629
+ }
1630
+ for (const entry of entries) {
1631
+ const fullPath = path.join(resolvedDir, entry.name);
1632
+ if (isExcluded(fullPath, entry.name, exclude, root)) continue;
1633
+ if (entry.isDirectory()) await scan(fullPath);
1634
+ else if (entry.isFile() && isStorybookTsxInput(entry.name) && shouldProcess(fullPath, include, exclude, root)) files.add(fullPath);
1635
+ }
1636
+ }
1637
+ for (const scanRoot of resolveScanRoots(root, include)) await scan(scanRoot);
1638
+ return [...files].sort();
1639
+ }
1640
+ async function assertNoUnsupportedStorybookTsxInputs(root, include, exclude) {
1641
+ const files = await scanStorybookTsxInputs(root, include, exclude);
1642
+ if (files.length > 0) throw new Error(formatUnsupportedStorybookTsxInputError(root, files));
1643
+ }
1644
+ function formatUnsupportedStorybookTsxInputError(root, files) {
1645
+ return [
1646
+ "[musea] Storybook TSX files matched by include are not supported as Musea art inputs yet.",
1647
+ "Remove *.stories.tsx from musea.include or migrate those stories to .art.vue files.",
1648
+ "Matched files:",
1649
+ `${files.slice(0, 5).map((file) => ` - ${relativePath(root, file)}`).join("\n")}${files.length > 5 ? `\n ... and ${files.length - 5} more` : ""}`
1650
+ ].join("\n");
1651
+ }
1652
+ function isExcluded(filePath, name, exclude, root) {
1653
+ return exclude.some((pattern) => matchesPathPattern(filePath, pattern, root) || matchGlob(name, pattern));
1654
+ }
1655
+ function matchesPathPattern(filePath, pattern, root) {
1656
+ return matchGlob(path.isAbsolute(pattern) ? path.resolve(filePath) : path.relative(root, filePath), pattern);
1657
+ }
1658
+ function relativePath(root, filePath) {
1659
+ return path.relative(root, filePath).split(path.sep).join("/");
1660
+ }
1661
+ //#endregion
1662
+ //#region src/static-gallery-shell.ts
1663
+ const moduleDir$1 = path.dirname(fileURLToPath(import.meta.url));
1664
+ function joinFileName(...parts) {
1665
+ return parts.filter(Boolean).join("/");
1666
+ }
1667
+ async function emitGalleryShell(emitFile, staticRoot, ctx, payload, galleryDistDir = resolveGalleryDistDir()) {
1668
+ if (!galleryDistDir) {
1669
+ const html = injectStaticGlobals(generateStaticFallbackGalleryHtml(ctx.basePath), ctx, payload);
1670
+ emitFile({
1671
+ type: "asset",
1672
+ fileName: joinFileName(staticRoot, "index.html"),
1673
+ source: html
1674
+ });
1675
+ return;
1676
+ }
1677
+ for (const filePath of await collectFiles(galleryDistDir)) {
1678
+ const relative = path.relative(galleryDistDir, filePath).split(path.sep).join("/");
1679
+ const target = joinFileName(staticRoot, relative);
1680
+ const content = await fs.promises.readFile(filePath);
1681
+ if (relative === "index.html") emitFile({
1682
+ type: "asset",
1683
+ fileName: target,
1684
+ source: injectStaticGlobals(rewriteGalleryBase(content.toString("utf-8"), ctx.basePath), ctx, payload)
1685
+ });
1686
+ else emitFile({
1687
+ type: "asset",
1688
+ fileName: target,
1689
+ source: rewriteGalleryTextAssetBase(content, relative, ctx.basePath)
1690
+ });
1691
+ }
1692
+ }
1693
+ function injectStaticGlobals(html, ctx, payload) {
1694
+ const script = `<script>${generateGalleryGlobalsScript({
1695
+ basePath: ctx.basePath,
1696
+ staticPreviews: payload.previews,
1697
+ themeConfig: ctx.themeConfig,
1698
+ tokenPreviewConfig: ctx.tokenPreviewConfig,
1699
+ toolbar: ctx.toolbar
1700
+ })}<\/script>`;
1701
+ return html.includes("</head>") ? html.replace("</head>", `${script}</head>`) : `${script}${html}`;
1702
+ }
1703
+ function generateStaticFallbackGalleryHtml(basePath) {
1704
+ return `<!DOCTYPE html>
1705
+ <html lang="en">
1706
+ <head>
1707
+ <meta charset="UTF-8">
1708
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1709
+ <title>Musea - Component Gallery</title>
1710
+ <style>html,body{min-height:100%;margin:0}body{font-family:system-ui,sans-serif}</style>
1711
+ </head>
1712
+ <body>${generateGalleryBody(basePath)}
1713
+
1714
+ <script type="module">${generateGalleryScript(basePath)}
1715
+ <\/script>
1716
+ </body>
1717
+ </html>`;
1718
+ }
1719
+ function resolveGalleryDistDir() {
1720
+ return [path.join(moduleDir$1, "gallery"), path.resolve(moduleDir$1, "../dist/gallery")].find((candidate) => fs.existsSync(path.join(candidate, "index.html"))) ?? null;
1721
+ }
1722
+ async function collectFiles(dir) {
1723
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
1724
+ const files = [];
1725
+ for (const entry of entries) {
1726
+ const filePath = path.join(dir, entry.name);
1727
+ if (entry.isDirectory()) files.push(...await collectFiles(filePath));
1728
+ else files.push(filePath);
1729
+ }
1730
+ return files;
1731
+ }
1732
+ //#endregion
1733
+ //#region src/static-export.ts
1734
+ const MUSEA_STATIC_BUILD_ENV = "VIZE_MUSEA_STATIC_BUILD";
1735
+ const VIRTUAL_STATIC_RUNTIME = "virtual:musea-static-runtime";
1736
+ const RESOLVED_STATIC_RUNTIME = "\0musea-static-runtime";
1737
+ const STATIC_RUNTIME_INPUT_NAME = "musea-static-runtime";
1738
+ const STATIC_USER_INPUT_NAME = "musea-static-entry";
1739
+ function isMuseaStaticBuild() {
1740
+ return process.env[MUSEA_STATIC_BUILD_ENV] === "1";
1741
+ }
1742
+ function shouldEnableMuseaStaticBuild(command) {
1743
+ return isMuseaStaticBuild() || command === "build";
1744
+ }
1745
+ function shouldEmitMuseaStaticGallery(command, storybookCompat) {
1746
+ if (isMuseaStaticBuild()) return true;
1747
+ return shouldEnableMuseaStaticBuild(command) && !storybookCompat;
1748
+ }
1749
+ function museaStaticBuildInput(input) {
1750
+ const entries = {};
1751
+ if (typeof input === "string") entries[STATIC_USER_INPUT_NAME] = input;
1752
+ else if (Array.isArray(input)) input.forEach((value, index) => {
1753
+ entries[`${STATIC_USER_INPUT_NAME}-${index + 1}`] = value;
1754
+ });
1755
+ else if (input) Object.assign(entries, input);
1756
+ entries[STATIC_RUNTIME_INPUT_NAME] = VIRTUAL_STATIC_RUNTIME;
1757
+ return entries;
1758
+ }
1759
+ function applyMuseaStaticBuildInput(options) {
1760
+ if (!isMuseaStaticBuild()) return null;
1761
+ options.input = museaStaticBuildInput(options.input);
1762
+ return null;
1763
+ }
1764
+ function museaStaticBuildConfig(input) {
1765
+ return { build: { rollupOptions: { input: museaStaticBuildInput(input) } } };
1766
+ }
1767
+ function resolveStaticRuntimeId(id) {
1768
+ return id === "virtual:musea-static-runtime" ? RESOLVED_STATIC_RUNTIME : null;
1769
+ }
1770
+ function loadStaticRuntimeModule(id, artFiles, identityRoot) {
1771
+ if (id !== RESOLVED_STATIC_RUNTIME) return null;
1772
+ return `
1773
+ const loaders = { ${Array.from(artFiles.values()).flatMap((art) => art.variants.map((variant) => {
1774
+ const key = staticPreviewId(identityRoot ? resolveStaticArtIdentity(art.path, identityRoot) : art.path, variant.name);
1775
+ const moduleId = previewModuleId(art.path, variant.name);
1776
+ return `${JSON.stringify(key)}: () => import(${JSON.stringify(moduleId)})`;
1777
+ })).join(",\n")} };
1778
+
1779
+ export async function loadMuseaPreview(id) {
1780
+ const load = loaders[id];
1781
+ if (!load) throw new Error("Musea preview not found: " + id);
1782
+ await load();
1783
+ }
1784
+
1785
+ if (typeof window !== "undefined") {
1786
+ window.__MUSEA_LOAD_PREVIEW__ = loadMuseaPreview;
1787
+ }
1788
+ `;
1789
+ }
1790
+ async function emitStaticGallery(emitFile, bundle, ctx) {
1791
+ const runtimeFileName = findRuntimeFileName(bundle);
1792
+ if (!runtimeFileName) throw new Error("musea static build could not find its generated runtime entry");
1793
+ const staticRoot = staticRootFromBasePath(ctx.basePath);
1794
+ const publicBasePath = publicBasePathFromViteBase(ctx.config.base, ctx.basePath);
1795
+ const publicCtx = {
1796
+ ...ctx,
1797
+ basePath: publicBasePath
1798
+ };
1799
+ const publicPayload = await createStaticGalleryPayload(publicCtx);
1800
+ await emitGalleryShell(emitFile, staticRoot, publicCtx, publicPayload);
1801
+ emitFile({
1802
+ type: "asset",
1803
+ fileName: joinFileName(staticRoot, "api", "static.json"),
1804
+ source: JSON.stringify(publicPayload, null, 2)
1805
+ });
1806
+ emitFile({
1807
+ type: "asset",
1808
+ fileName: joinFileName(staticRoot, "api", "arts"),
1809
+ source: JSON.stringify(publicPayload.arts, null, 2)
1810
+ });
1811
+ await emitAxeVendor(emitFile, staticRoot);
1812
+ emitPreviewHtml(emitFile, staticRoot, runtimeFileName, publicBasePath, new Map(publicPayload.arts.map((art) => [art.path, art])));
1813
+ emitRootRedirect(emitFile, staticRoot, publicBasePath);
1814
+ }
1815
+ function findRuntimeFileName(bundle) {
1816
+ for (const item of Object.values(bundle)) if (item.type === "chunk" && item.name === "musea-static-runtime") return item.fileName;
1817
+ return null;
1818
+ }
1819
+ function emitPreviewHtml(emitFile, staticRoot, runtimeFileName, basePath, artFiles) {
1820
+ const previewDir = joinFileName(staticRoot, "preview");
1821
+ const runtimeUrl = relativeUrl(previewDir, runtimeFileName);
1822
+ for (const art of artFiles.values()) for (const variant of art.variants) {
1823
+ const id = staticPreviewId(art.path, variant.name);
1824
+ const html = generateStaticPreviewHtml(art, variant.name, id, basePath, runtimeUrl);
1825
+ emitFile({
1826
+ type: "asset",
1827
+ fileName: joinFileName(previewDir, `${id}.html`),
1828
+ source: html
1829
+ });
1830
+ }
1831
+ }
1832
+ function generateStaticPreviewHtml(art, variantName, previewId, basePath, runtimeUrl) {
1833
+ return `<!DOCTYPE html>
1834
+ <html lang="en">
1835
+ <head>
1836
+ <meta charset="UTF-8">
1837
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1838
+ <title>${escapeHtml(art.metadata.title)} - ${escapeHtml(variantName)}</title>
1839
+ <script>window.__MUSEA_BASE_PATH__=${serializeScriptValue(basePath)};<\/script>
1840
+ <style>html,body{width:100%;height:100%;margin:0}body{font-family:system-ui,sans-serif;background:#fff;padding:1rem;overflow:auto;box-sizing:border-box}.musea-variant{min-height:calc(100vh - 2rem)}.musea-error{color:#dc2626;background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:1rem;font-size:.875rem}.musea-loading{color:#6b7280;font-size:.875rem}.musea-bg-checkerboard{background-image:linear-gradient(45deg,#ccc 25%,transparent 25%),linear-gradient(-45deg,#ccc 25%,transparent 25%),linear-gradient(45deg,transparent 75%,#ccc 75%),linear-gradient(-45deg,transparent 75%,#ccc 75%)!important;background-size:20px 20px!important;background-position:0 0,0 10px,10px -10px,-10px 0!important}</style>
1841
+ </head>
1842
+ <body>
1843
+ <div id="app" class="musea-variant" data-art="${escapeHtml(art.path)}" data-variant="${escapeHtml(variantName)}">
1844
+ <div class="musea-loading">Loading component...</div>
1845
+ </div>
1846
+ <script type="module">
1847
+ import ${JSON.stringify(runtimeUrl)};
1848
+ Promise.resolve().then(() => {
1849
+ const loadMuseaPreview = window.__MUSEA_LOAD_PREVIEW__;
1850
+ if (typeof loadMuseaPreview !== "function") {
1851
+ throw new Error("Musea preview runtime failed to load");
1852
+ }
1853
+ return loadMuseaPreview(${JSON.stringify(previewId)});
1854
+ }).catch((error) => {
1855
+ const el = document.getElementById("app");
1856
+ if (el) el.textContent = error instanceof Error ? error.message : String(error);
1857
+ });
1858
+ <\/script>
1859
+ </body>
1860
+ </html>`;
1861
+ }
1862
+ function emitRootRedirect(emitFile, staticRoot, basePath) {
1863
+ if (!staticRoot) return;
1864
+ const target = joinUrlPath(basePath, "");
1865
+ emitFile({
1866
+ type: "asset",
1867
+ fileName: "index.html",
1868
+ source: `<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0; url=${target}"><script>location.replace(${JSON.stringify(target)}+location.search+location.hash)<\/script>`
1869
+ });
1870
+ }
1871
+ async function emitAxeVendor(emitFile, staticRoot) {
1872
+ try {
1873
+ const axePath = createRequire(import.meta.url).resolve("axe-core/axe.min.js");
1874
+ const source = await fs.promises.readFile(axePath);
1875
+ emitFile({
1876
+ type: "asset",
1877
+ fileName: joinFileName(staticRoot, "vendor/axe-core.min.js"),
1878
+ source
1879
+ });
1880
+ } catch {
1881
+ console.warn("[musea] axe-core is not installed, so the exported gallery cannot run accessibility checks.\n Install it to enable the A11y panel in the static build: vp install -D axe-core");
1882
+ }
1883
+ }
1884
+ function staticRootFromBasePath(basePath) {
1885
+ return basePath.replace(/^\/+|\/+$/g, "");
1886
+ }
1887
+ function relativeUrl(fromDir, toFile) {
1888
+ const relative = path.posix.relative(fromDir || ".", toFile);
1889
+ return relative.startsWith(".") ? relative : `./${relative}`;
1890
+ }
1891
+ //#endregion
1892
+ //#region src/plugin/config.ts
1893
+ async function resolveMuseaSharedConfig(resolvedConfig, loadConfigFile = loadConfig, projectViteConfig = resolveViteConfigExport) {
1894
+ let registration = getResolvedVizeConfigRegistration(resolvedConfig);
1895
+ if (!registration.registered) {
1896
+ await Promise.resolve();
1897
+ registration = getResolvedVizeConfigRegistration(resolvedConfig);
1898
+ }
1899
+ if (registration.registered) return await registration.config;
1900
+ const configFile = process.env[VIZE_CONFIG_FILE_ENV];
1901
+ try {
1902
+ const env = {
1903
+ mode: resolvedConfig.mode,
1904
+ command: resolvedConfig.command === "build" ? "build" : "serve",
1905
+ isSsrBuild: !!resolvedConfig.build?.ssr
1906
+ };
1907
+ return await loadConfigFile(resolvedConfig.root, {
1908
+ configFile,
1909
+ viteConfig: false,
1910
+ env
1911
+ }) ?? await projectViteConfig(resolvedConfig, env);
1912
+ } catch (error) {
1913
+ throw new Error(`[musea] Failed to load Vize config from ${configFile ?? resolvedConfig.root}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1914
+ }
1915
+ }
1916
+ //#endregion
1917
+ //#region src/plugin/virtual-transform.ts
1918
+ const VIRTUAL_ART_PREFIX = "\0musea-art:";
1919
+ const VIRTUAL_INLINE_ART_PREFIX = "\0musea:";
1920
+ /**
1921
+ * Give Vite's TypeScript transformer a filename beside the authored art file.
1922
+ * OXC uses this filename to select a tsconfig, so a synthetic filename under
1923
+ * the Vite root can accidentally select an unrelated ancestor config.
1924
+ */
1925
+ function museaVirtualTransformId(id) {
1926
+ const prefix = id.startsWith(VIRTUAL_ART_PREFIX) ? VIRTUAL_ART_PREFIX : id.startsWith(VIRTUAL_INLINE_ART_PREFIX) ? VIRTUAL_INLINE_ART_PREFIX : null;
1927
+ if (!prefix) return null;
1928
+ return `${id.slice(prefix.length).replace(/\?musea-virtual$/, "")}.ts`;
1929
+ }
1930
+ function createMuseaVirtualTransformer(viteApi) {
1931
+ return async (code, id, sourcemap) => {
1932
+ if (typeof viteApi.transformWithOxc === "function") return viteApi.transformWithOxc(code, id, {
1933
+ lang: "ts",
1934
+ sourcemap,
1935
+ target: "esnext"
1936
+ });
1937
+ if (typeof viteApi.transformWithEsbuild === "function") return viteApi.transformWithEsbuild(code, id, {
1938
+ loader: "ts",
1939
+ format: "esm",
1940
+ sourcemap,
1941
+ target: "esnext"
1942
+ });
1943
+ throw new Error("Installed Vite does not expose transformWithOxc or transformWithEsbuild");
1944
+ };
1945
+ }
1946
+ const transformMuseaVirtualModule = createMuseaVirtualTransformer(vite);
1947
+ //#endregion
1948
+ //#region src/plugin/preview-css.ts
1949
+ /**
1950
+ * Resolve a `previewCss` entry.
1951
+ *
1952
+ * Relative and project-root files stay filesystem paths. Bare specifiers
1953
+ * (`normalize.css`, `@fontsource/inter/index.css`) are left for Vite.
1954
+ */
1955
+ function resolvePreviewCssPath(root, cssPath) {
1956
+ if (path.isAbsolute(cssPath)) return cssPath;
1957
+ const rooted = path.resolve(root, cssPath);
1958
+ if (cssPath.startsWith(".") || fs.existsSync(rooted)) return rooted;
1959
+ return cssPath;
1960
+ }
1961
+ //#endregion
1962
+ //#region src/plugin/static-preview.ts
1963
+ function resolveStaticPreviewVueVersion(configured, plugins) {
1964
+ if (configured !== void 0) return configured;
1965
+ if (hasLegacyVueSfcCompilerPlugin(plugins)) return 2;
1966
+ return 3;
1967
+ }
1968
+ function hasLegacyVueSfcCompilerPlugin(plugins) {
1969
+ return plugins.some((plugin) => {
1970
+ const name = plugin.name ?? "";
1971
+ return name === "vite:vue2" || name.includes("plugin-vue2") || name.includes("vue2");
1972
+ });
1973
+ }
1974
+ //#endregion
1975
+ //#region src/gallery-dependencies.ts
1976
+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));
1977
+ const globPath = (entry) => normalizePath(entry).replace(/([*?{}[\]()!])/g, "\\$1");
1978
+ async function registerSourceGalleryDependencies(config) {
1979
+ const client = config.environments.client;
1980
+ const optimizer = client.optimizeDeps;
1981
+ const gallery = path.join(moduleDir, "../gallery/index.html");
1982
+ if (config.command !== "serve" || optimizer.disabled === true || optimizer.disabled === "dev" || optimizer.noDiscovery || existsSync(path.join(moduleDir, "gallery/index.html")) || !existsSync(gallery)) return;
1983
+ let entries = optimizer.entries;
1984
+ if (!entries) {
1985
+ const input = client.build.rollupOptions.input;
1986
+ if (input) {
1987
+ const inputs = typeof input === "string" ? [input] : Array.isArray(input) ? input : Object.values(input);
1988
+ const resolve = config.createResolver();
1989
+ entries = await Promise.all(inputs.map(async (entry) => {
1990
+ const resolved = await resolve(entry, path.join(process.cwd(), "*"));
1991
+ if (!resolved) throw new Error(`Failed to resolve gallery dependency scan input: ${entry}`);
1992
+ return globPath(resolved);
1993
+ }));
1994
+ } else entries = [
1995
+ "**/*.html",
1996
+ "!**/__tests__/**",
1997
+ "!**/coverage/**"
1998
+ ];
1999
+ }
2000
+ optimizer.entries = [...new Set([...typeof entries === "string" ? [entries] : entries, globPath(gallery)])];
2001
+ }
2002
+ //#endregion
2003
+ //#region src/plugin/gallery-url.ts
2004
+ function resolveMuseaGalleryUrls(resolvedUrls, fallback, basePath) {
2005
+ const origins = [...resolvedUrls?.local ?? [], ...resolvedUrls?.network ?? []];
2006
+ if (origins.length === 0) {
2007
+ const host = ["::", "0.0.0.0"].includes(fallback.address) ? "localhost" : fallback.address === "::1" ? "[::1]" : fallback.address;
2008
+ origins.push(`${fallback.protocol}://${host}:${fallback.port}/`);
2009
+ }
2010
+ return [...new Set(origins)].map((origin) => {
2011
+ const url = new URL(origin);
2012
+ url.pathname = basePath;
2013
+ url.search = "";
2014
+ url.hash = "";
2015
+ return url.href;
2016
+ });
2017
+ }
2018
+ //#endregion
2019
+ //#region src/plugin/raw-input-owner.ts
2020
+ /** Only the active Musea instance may delegate raw Art to its virtual SFC route. */
2021
+ function createRawArtInputOwner(config) {
2022
+ const root = config.root;
2023
+ const include = [...config.include];
2024
+ const exclude = [...config.exclude];
2025
+ const scanRoots = [...config.scanRoots];
2026
+ return Object.freeze({ ownsInput(file, source) {
2027
+ if (!file.endsWith(".art.vue") || !shouldProcess(file, include, exclude, root) || !isTrustedSourcePath(root, scanRoots, file)) return false;
2028
+ const native = loadNative();
2029
+ if (!native.parseSfc(source, { filename: file }).customBlocks.some((block) => block.type === "art")) return false;
2030
+ return native.parseArt(source, { filename: file }).variants.length > 0;
2031
+ } });
2032
+ }
2033
+ //#endregion
2034
+ //#region src/plugin/index.ts
2035
+ function musea(options = {}) {
2036
+ let include = options.include ?? ["**/*.art.vue"];
2037
+ let exclude = options.exclude ?? ["node_modules/**", "dist/**"];
2038
+ let basePath = options.basePath ?? "/__musea__";
2039
+ let storybookCompat = options.storybookCompat ?? false;
2040
+ const storybookOutDir = options.storybookOutDir ?? ".storybook/stories";
2041
+ let inlineArt = options.inlineArt ?? false;
2042
+ const tokensPath = options.tokensPath;
2043
+ let tokenPreviewConfig = options.tokenPreviews;
2044
+ const projectRootOption = options.projectRoot;
2045
+ const themeConfig = buildThemeConfig(options.theme);
2046
+ const previewCss = options.previewCss ?? [];
2047
+ const previewSetup = options.previewSetup;
2048
+ const toolbar = normalizeToolbar(options.toolbar);
2049
+ let vueVersion = options.vueVersion;
2050
+ const devSessionToken = createDevSessionToken();
2051
+ let config;
2052
+ const rawInputOwners = /* @__PURE__ */ new WeakMap();
2053
+ let server = null;
2054
+ const artFiles = /* @__PURE__ */ new Map();
2055
+ let resolvedPreviewCss = [];
2056
+ let resolvedPreviewSetup = null;
2057
+ let scanRoots = [];
2058
+ let staticBuildEnabled = isMuseaStaticBuild();
2059
+ const virtualState = {
2060
+ basePath,
2061
+ get inlineArt() {
2062
+ return inlineArt;
2063
+ },
2064
+ artFiles,
2065
+ resolvedPreviewCss,
2066
+ resolvedPreviewSetup,
2067
+ toolbar,
2068
+ getConfigRoot: () => config.root,
2069
+ getScanRoots: () => scanRoots,
2070
+ getVueVersion: () => vueVersion,
2071
+ getServer: () => server,
2072
+ processArtFile
2073
+ };
2074
+ const virtualResolveId = createResolveId(virtualState);
2075
+ const virtualLoad = createLoad(virtualState);
2076
+ const handleHotUpdate = createHandleHotUpdate(virtualState);
2077
+ const mainPlugin = {
2078
+ name: "vite-plugin-musea",
2079
+ api: { vizePrecompileInputOwner: Object.freeze({
2080
+ version: 1,
2081
+ forConfig: (resolved) => rawInputOwners.get(resolved)
2082
+ }) },
2083
+ enforce: "pre",
2084
+ apply(_config, env) {
2085
+ return shouldApplyMuseaPlugin(env);
2086
+ },
2087
+ config(userConfig, env) {
2088
+ staticBuildEnabled = shouldEmitMuseaStaticGallery(env.command, storybookCompat);
2089
+ const staticBuildConfig = staticBuildEnabled ? museaStaticBuildConfig(userConfig.build?.rollupOptions?.input) : {};
2090
+ return {
2091
+ resolve: { alias: [createVueRuntimeCompilerAlias({
2092
+ root: userConfig.root ? path.resolve(userConfig.root) : process.cwd(),
2093
+ runtimeCompiler: options.vueRuntimeCompiler
2094
+ })] },
2095
+ ...staticBuildConfig
2096
+ };
2097
+ },
2098
+ options: applyMuseaStaticBuildInput,
2099
+ async configResolved(resolvedConfig) {
2100
+ config = resolvedConfig;
2101
+ await registerSourceGalleryDependencies(resolvedConfig);
2102
+ const vizeConfig = await resolveMuseaSharedConfig(resolvedConfig);
2103
+ if (vizeConfig?.musea) {
2104
+ const mc = vizeConfig.musea;
2105
+ if (!options.include && mc.include) include = mc.include;
2106
+ if (!options.exclude && mc.exclude) exclude = mc.exclude;
2107
+ if (!options.basePath && mc.basePath) basePath = mc.basePath;
2108
+ if (options.storybookCompat === void 0 && mc.storybookCompat !== void 0) storybookCompat = mc.storybookCompat;
2109
+ if (options.inlineArt === void 0 && mc.inlineArt !== void 0) inlineArt = mc.inlineArt;
2110
+ if (options.tokenPreviews === void 0 && mc.tokenPreviews !== void 0) tokenPreviewConfig = mc.tokenPreviews;
2111
+ }
2112
+ if (basePath !== "/") basePath = basePath.replace(/\/+$/, "");
2113
+ vueVersion = resolveStaticPreviewVueVersion(vueVersion, resolvedConfig.plugins);
2114
+ if (toolbar.length > 0 && vueVersion !== 3 && vueVersion !== "2.7") throw new Error("[musea] Global toolbar controls require Vue 3 or Vue 2.7");
2115
+ staticBuildEnabled = shouldEmitMuseaStaticGallery(resolvedConfig.command, storybookCompat);
2116
+ virtualState.basePath = basePath;
2117
+ resolvedPreviewCss = previewCss.map((cssPath) => resolvePreviewCssPath(resolvedConfig.root, cssPath));
2118
+ if (previewSetup) resolvedPreviewSetup = path.isAbsolute(previewSetup) ? previewSetup : path.resolve(resolvedConfig.root, previewSetup);
2119
+ virtualState.resolvedPreviewCss = resolvedPreviewCss;
2120
+ virtualState.resolvedPreviewSetup = resolvedPreviewSetup;
2121
+ scanRoots = resolveScanRoots(resolvedConfig.root, include);
2122
+ rawInputOwners.set(resolvedConfig, createRawArtInputOwner({
2123
+ root: resolvedConfig.root,
2124
+ include,
2125
+ exclude,
2126
+ scanRoots
2127
+ }));
2128
+ },
2129
+ configureServer(devServer) {
2130
+ server = devServer;
2131
+ devServer.watcher.unwatch(path.resolve(config.root, ".vize/reports"));
2132
+ registerMiddleware(devServer, {
2133
+ basePath,
2134
+ devSessionToken,
2135
+ themeConfig,
2136
+ tokenPreviewConfig,
2137
+ artFiles,
2138
+ scanRoots,
2139
+ resolvedPreviewCss,
2140
+ resolvedPreviewSetup,
2141
+ toolbar
2142
+ });
2143
+ devServer.middlewares.use(`${basePath}/api`, createApiMiddleware({
2144
+ config,
2145
+ artFiles,
2146
+ scanRoots,
2147
+ tokensPath,
2148
+ projectRoot: resolveProjectRoot(projectRootOption, config.root),
2149
+ basePath,
2150
+ resolvedPreviewCss,
2151
+ resolvedPreviewSetup,
2152
+ toolbar,
2153
+ vrt: options.vrt,
2154
+ devSessionToken,
2155
+ processArtFile,
2156
+ getDevServerPort: () => devServer.config.server.port || 5173
2157
+ }));
2158
+ devServer.watcher.on("change", async (file) => {
2159
+ if (file.endsWith(".art.vue") && shouldProcess(file, include, exclude, config.root)) {
2160
+ await processArtFile(file);
2161
+ console.log(`[musea] Reloaded: ${path.relative(config.root, file)}`);
2162
+ }
2163
+ if (inlineArt && file.endsWith(".vue") && !file.endsWith(".art.vue")) {
2164
+ const hadArt = artFiles.has(file);
2165
+ if ((await fs.promises.readFile(file, "utf-8")).includes("<art")) {
2166
+ await processArtFile(file);
2167
+ console.log(`[musea] Reloaded inline art: ${path.relative(config.root, file)}`);
2168
+ } else if (hadArt) {
2169
+ artFiles.delete(file);
2170
+ console.log(`[musea] Removed inline art: ${path.relative(config.root, file)}`);
2171
+ }
2172
+ }
2173
+ });
2174
+ devServer.watcher.on("add", async (file) => {
2175
+ if (file.endsWith(".art.vue") && shouldProcess(file, include, exclude, config.root)) {
2176
+ await processArtFile(file);
2177
+ console.log(`[musea] Added: ${path.relative(config.root, file)}`);
2178
+ }
2179
+ if (inlineArt && file.endsWith(".vue") && !file.endsWith(".art.vue")) {
2180
+ if ((await fs.promises.readFile(file, "utf-8")).includes("<art")) {
2181
+ await processArtFile(file);
2182
+ console.log(`[musea] Added inline art: ${path.relative(config.root, file)}`);
2183
+ }
2184
+ }
2185
+ });
2186
+ devServer.watcher.on("unlink", (file) => {
2187
+ if (artFiles.has(file)) {
2188
+ artFiles.delete(file);
2189
+ console.log(`[musea] Removed: ${path.relative(config.root, file)}`);
2190
+ }
2191
+ });
2192
+ return () => {
2193
+ devServer.httpServer?.once("listening", () => {
2194
+ const address = devServer.httpServer?.address();
2195
+ if (address && typeof address === "object") {
2196
+ const protocol = devServer.config.server.https ? "https" : "http";
2197
+ console.log();
2198
+ for (const url of resolveMuseaGalleryUrls(devServer.resolvedUrls, {
2199
+ protocol,
2200
+ address: address.address,
2201
+ port: address.port
2202
+ }, basePath)) console.log(` \x1b[36m➜\x1b[0m \x1b[1mMusea Gallery:\x1b[0m \x1b[36m${url}\x1b[0m`);
2203
+ }
2204
+ });
2205
+ };
2206
+ },
2207
+ async buildStart() {
2208
+ console.log(`[musea] config.root: ${config.root}, include: ${JSON.stringify(include)}`);
2209
+ if (storybookCompat && staticBuildEnabled) await assertNoUnsupportedStorybookTsxInputs(config.root, include, exclude);
2210
+ const files = await scanArtFiles(config.root, include, exclude, inlineArt);
2211
+ console.log(`[musea] Found ${files.length} art files`);
2212
+ if (server) watchMuseaArtFiles(server.watcher, files);
2213
+ for (const file of files) await processArtFile(file);
2214
+ if (storybookCompat) await generateStorybookFiles(artFiles, config.root, storybookOutDir);
2215
+ },
2216
+ resolveId(id) {
2217
+ return resolveStaticRuntimeId(id) ?? virtualResolveId(id);
2218
+ },
2219
+ load(id) {
2220
+ return loadStaticRuntimeModule(id, artFiles, staticBuildEnabled ? resolveStaticIdentityRoot(config.root, artFiles.keys(), resolveProjectRoot(projectRootOption, config.root)) : void 0) ?? virtualLoad(id);
2221
+ },
2222
+ async generateBundle(_options, bundle) {
2223
+ if (!staticBuildEnabled) return;
2224
+ await emitStaticGallery((asset) => void this.emitFile(asset), bundle, {
2225
+ config,
2226
+ artFiles,
2227
+ scanRoots,
2228
+ tokensPath,
2229
+ projectRoot: resolveProjectRoot(projectRootOption, config.root),
2230
+ basePath,
2231
+ resolvedPreviewCss,
2232
+ resolvedPreviewSetup,
2233
+ toolbar,
2234
+ devSessionToken,
2235
+ themeConfig,
2236
+ tokenPreviewConfig
2237
+ });
2238
+ },
2239
+ async transform(code, id) {
2240
+ const inlineArtBlock = loadInlineArtCustomBlock(virtualState, id);
2241
+ if (inlineArtBlock !== null) return {
2242
+ code: inlineArtBlock,
2243
+ map: null
2244
+ };
2245
+ if (!id.includes("?musea-virtual")) return null;
2246
+ if (!id.includes("musea-art:") && !id.includes("\0musea:")) return null;
2247
+ const loaderId = museaVirtualTransformId(id);
2248
+ if (!loaderId) return null;
2249
+ return transformMuseaVirtualModule(code, loaderId, config.command === "serve");
2250
+ },
2251
+ handleHotUpdate
2252
+ };
2253
+ async function processArtFile(filePath) {
2254
+ try {
2255
+ resolveTrustedSourcePath(config.root, scanRoots, filePath, "art path");
2256
+ } catch {
2257
+ return;
2258
+ }
2259
+ const info = await processMuseaArtFile(filePath, {
2260
+ root: config.root,
2261
+ command: config.command
2262
+ });
2263
+ if (info) artFiles.set(filePath, info);
2264
+ else if (artFiles.get(filePath)?.isInline) artFiles.delete(filePath);
2265
+ }
2266
+ return [attachMuseaOptions(mainPlugin, options), {
2267
+ name: "vite-plugin-musea:style-post-transform",
2268
+ transform(code, id) {
2269
+ const transformed = transformPreprocessedArtStyle(code, id);
2270
+ return transformed === null ? null : {
2271
+ code: transformed,
2272
+ map: null
2273
+ };
2274
+ }
2275
+ }];
2276
+ }
2277
+ function resolveProjectRoot(projectRoot, viteRoot) {
2278
+ if (!projectRoot) return void 0;
2279
+ const absolute = path.isAbsolute(projectRoot) ? projectRoot : path.resolve(viteRoot, projectRoot);
2280
+ return absolute === path.resolve(viteRoot) ? void 0 : absolute;
2281
+ }
2282
+ //#endregion
2283
+ export { musea };
2284
+
2285
+ //# sourceMappingURL=plugin-D2KEfrj1.mjs.map