@vizejs/vite-plugin-musea 0.781.0 → 0.783.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 (80) hide show
  1. package/README.md +10 -9
  2. package/client.d.ts +79 -2
  3. package/dist/a11y/index.d.mts +1 -1
  4. package/dist/a11y/index.mjs +2 -2
  5. package/dist/{report-identity-dHHBq0Ne.mjs → art-processing-BQ7OYXsq.mjs} +352 -985
  6. package/dist/art-processing-BQ7OYXsq.mjs.map +1 -0
  7. package/dist/autogen/index.mjs +1 -1
  8. package/dist/{autogen-D9K1av3V.mjs → autogen-DQVOrkzB.mjs} +8 -3
  9. package/dist/autogen-DQVOrkzB.mjs.map +1 -0
  10. package/dist/cli/index.d.mts +2 -2
  11. package/dist/cli/index.mjs +52 -7
  12. package/dist/cli/index.mjs.map +1 -1
  13. package/dist/gallery/assets/{MonacoEditor-TAa2JDXq.js → MonacoEditor-0o-tEf_d.js} +2 -2
  14. package/dist/gallery/assets/{cssMode-HbYMEqla.js → cssMode-CTeGZPsJ.js} +1 -1
  15. package/dist/gallery/assets/{editor.api-BnAmILmn.js → editor.api-By71ZNNJ.js} +1 -1
  16. package/dist/gallery/assets/{freemarker2-CUxx3K6C.js → freemarker2-PodIPOLZ.js} +1 -1
  17. package/dist/gallery/assets/{handlebars-D-tFxs03.js → handlebars-CxH85JIs.js} +1 -1
  18. package/dist/gallery/assets/{html-BvCZbWop.js → html-CLgd1G74.js} +1 -1
  19. package/dist/gallery/assets/{htmlMode-CtpLmhU0.js → htmlMode-CSxazmZ_.js} +1 -1
  20. package/dist/gallery/assets/{index-9Jbnkznu.js → index-CrdkHjj1.js} +28 -28
  21. package/dist/gallery/assets/index-DjzvBel3.css +1 -0
  22. package/dist/gallery/assets/{javascript-5Q8XUioJ.js → javascript-nMYU-ClU.js} +1 -1
  23. package/dist/gallery/assets/{jsonMode-meopLbOo.js → jsonMode-CR3wuGKP.js} +1 -1
  24. package/dist/gallery/assets/{liquid-XBHPlM5o.js → liquid-D0UrqjBJ.js} +1 -1
  25. package/dist/gallery/assets/{lspLanguageFeatures-uQPmNYRO.js → lspLanguageFeatures-Dd1uggns.js} +1 -1
  26. package/dist/gallery/assets/{mdx-DPlyNjoV.js → mdx-BL8lD8I3.js} +1 -1
  27. package/dist/gallery/assets/{python-BJGVh1ia.js → python-Ctx797mC.js} +1 -1
  28. package/dist/gallery/assets/{razor-tl_w-IGC.js → razor-Ba3xTj_L.js} +1 -1
  29. package/dist/gallery/assets/{register-B1Z_0Wj1.js → register-DS0poJDf.js} +2 -2
  30. package/dist/gallery/assets/{toggleHighContrast-CwaJX3-m.js → toggleHighContrast-Dd6XSMyb.js} +1 -1
  31. package/dist/gallery/assets/{tsMode-BTkaxugD.js → tsMode-BT2twH2C.js} +1 -1
  32. package/dist/gallery/assets/{typescript-BfDavZMU.js → typescript-C5pkGWfc.js} +1 -1
  33. package/dist/gallery/assets/{vs-yheCI45x.js → vs-BKqjpgpj.js} +3 -3
  34. package/dist/gallery/assets/{workers-CxTFpB1G.js → workers-Dw3ZZZ2Q.js} +1 -1
  35. package/dist/gallery/assets/{xml-BwtrP1DO.js → xml-DKxYmeMe.js} +1 -1
  36. package/dist/gallery/assets/{yaml-jwkm0mVv.js → yaml-BLz7QoYz.js} +1 -1
  37. package/dist/gallery/index.html +2 -2
  38. package/dist/{gallery-DNxzJA4V.mjs → gallery-CLjSInLi.mjs} +2 -2
  39. package/dist/{gallery-DNxzJA4V.mjs.map → gallery-CLjSInLi.mjs.map} +1 -1
  40. package/dist/{html-BW9Z7gL3.mjs → html-N6TFwUQB.mjs} +11 -4
  41. package/dist/html-N6TFwUQB.mjs.map +1 -0
  42. package/dist/{index-ELy0IbiZ.d.mts → index-DBZ6pHEP.d.mts} +3 -3
  43. package/dist/{index-ELy0IbiZ.d.mts.map → index-DBZ6pHEP.d.mts.map} +1 -1
  44. package/dist/{index-BemK8p6d.d.mts → index-s1-tayec.d.mts} +16 -3
  45. package/dist/{index-BemK8p6d.d.mts.map → index-s1-tayec.d.mts.map} +1 -1
  46. package/dist/index.d.mts +3 -3
  47. package/dist/index.mjs +6 -6
  48. package/dist/{module-BaxIBS_8.mjs → module-CUszeEyD.mjs} +2 -2
  49. package/dist/{module-BaxIBS_8.mjs.map → module-CUszeEyD.mjs.map} +1 -1
  50. package/dist/native-loader-T2dk9Xrf.mjs +304 -0
  51. package/dist/native-loader-T2dk9Xrf.mjs.map +1 -0
  52. package/dist/{plugin-D2KEfrj1.mjs → plugin-BhEarB-i.mjs} +301 -21
  53. package/dist/plugin-BhEarB-i.mjs.map +1 -0
  54. package/dist/{report-CHUEZNZA.mjs → report-BuvPnXYn.mjs} +2 -2
  55. package/dist/{report-CHUEZNZA.mjs.map → report-BuvPnXYn.mjs.map} +1 -1
  56. package/dist/{report-ZbXgDiN_.mjs → report-CNk-LzNl.mjs} +2 -2
  57. package/dist/{report-ZbXgDiN_.mjs.map → report-CNk-LzNl.mjs.map} +1 -1
  58. package/dist/report-identity-CvU6XOLJ.mjs +919 -0
  59. package/dist/report-identity-CvU6XOLJ.mjs.map +1 -0
  60. package/dist/{resolver-D8_4jxfT.mjs → resolver-DUipOWtm.mjs} +3 -254
  61. package/dist/resolver-DUipOWtm.mjs.map +1 -0
  62. package/dist/test-runner.d.mts +68 -0
  63. package/dist/test-runner.d.mts.map +1 -0
  64. package/dist/test-runner.mjs +160 -0
  65. package/dist/test-runner.mjs.map +1 -0
  66. package/dist/{vrt-CuAg5Eow.d.mts → vrt-DJwEoyjo.d.mts} +4 -3
  67. package/dist/vrt-DJwEoyjo.d.mts.map +1 -0
  68. package/dist/{vrt-B8j2yfiN.mjs → vrt-KEfbSnWX.mjs} +15 -5
  69. package/dist/vrt-KEfbSnWX.mjs.map +1 -0
  70. package/dist/vrt.d.mts +3 -3
  71. package/dist/vrt.mjs +4 -4
  72. package/package.json +8 -4
  73. package/dist/autogen-D9K1av3V.mjs.map +0 -1
  74. package/dist/gallery/assets/index-CT4hwaEG.css +0 -1
  75. package/dist/html-BW9Z7gL3.mjs.map +0 -1
  76. package/dist/plugin-D2KEfrj1.mjs.map +0 -1
  77. package/dist/report-identity-dHHBq0Ne.mjs.map +0 -1
  78. package/dist/resolver-D8_4jxfT.mjs.map +0 -1
  79. package/dist/vrt-B8j2yfiN.mjs.map +0 -1
  80. package/dist/vrt-CuAg5Eow.d.mts.map +0 -1
@@ -1,7 +1,9 @@
1
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";
2
+ import { f as attachMuseaOptions } from "./resolver-DUipOWtm.mjs";
3
+ import { n as assertStaticExpression, r as loadNative } from "./native-loader-T2dk9Xrf.mjs";
4
+ import { A as decodeUrlComponent, C as collectRequestBody, D as validateDevApiRequest, E as serializeScriptValue, F as resolveTrustedSourcePath, I as resolveUrlPathInside, L as HttpError, N as resolveInside, O as assertArtVueSourcePath, T as parseJsonBody, _ as matchGlob, a as parseScriptSetupForArt, b as shouldProcess, c as parseArtStyleRequest, g as generateStorybookFiles, h as escapeHtml, i as importDeclaresName, j as isTrustedSourcePath, k as assertVueSourcePath, l as transformPreprocessedArtStyle, m as variantComponentNames, n as sourceWithOptionalArtTitle, o as rewriteRelativeImportStatement, r as generateArtModule, s as loadArtStyle, t as processMuseaArtFile, u as resolveArtComponent, v as resolveScanRoots, w as createDevSessionToken, x as buildThemeConfig, y as scanArtFiles } from "./art-processing-BQ7OYXsq.mjs";
5
+ import { S as handleTokensUsage, _ 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, l as joinUrlPath, m as handleArtAnalysis, n as attachArtReportOwner, o as rewriteGalleryBase, p as sortedArts, r as resolveArtReportTarget, s as rewriteGalleryTextAssetBase, t as assertArtReportOwnership, u as resolveStaticArtIdentity, v as handleTokensCreate, x as handleTokensUpdate, y as handleTokensDelete } from "./report-identity-CvU6XOLJ.mjs";
6
+ import { a as generateGalleryScript, i as generateGalleryBody, n as generateDevGlobalsScript, r as generateGalleryGlobalsScript, t as generateGalleryModule } from "./module-CUszeEyD.mjs";
5
7
  import { createRequire } from "node:module";
6
8
  import path from "node:path";
7
9
  import fs, { existsSync } from "node:fs";
@@ -296,6 +298,10 @@ function __museaInitAddons(container, variantName, extraCaptureEvents = []) {
296
298
  if (!e.data?.type?.startsWith('musea:')) return;
297
299
  const { type, payload } = e.data;
298
300
  switch (type) {
301
+ case 'musea:request-ready': {
302
+ window.parent.postMessage({ type: 'musea:ready', payload: {} }, parentOrigin);
303
+ break;
304
+ }
299
305
  case 'musea:set-background': {
300
306
  if (payload.pattern === 'checkerboard') {
301
307
  document.body.style.background = '';
@@ -325,7 +331,7 @@ function __museaInitAddons(container, variantName, extraCaptureEvents = []) {
325
331
  case 'musea:set-props': {
326
332
  // Store props for remount - handled by preview module
327
333
  if (window.__museaSetProps) {
328
- window.__museaSetProps(payload.props || {});
334
+ window.__museaSetProps(payload.props || {}, payload.attrs || {});
329
335
  }
330
336
  break;
331
337
  }
@@ -413,6 +419,235 @@ function __museaInitAddons(container, variantName, extraCaptureEvents = []) {
413
419
  window.parent.postMessage({ type: 'musea:ready', payload: {} }, parentOrigin);
414
420
  }
415
421
  `;
422
+ /** Interaction-test bridge, emitted only for variants that author a play function. */
423
+ const MUSEA_PLAY_INIT_CODE = `
424
+ function __museaInitPlay(container, variantName) {
425
+ const parentOrigin = window.location.origin;
426
+ let playRunning = null;
427
+ window.__museaRunPlay = async () => {
428
+ if (typeof window.__museaPlay !== 'function') {
429
+ return { status: 'skipped', duration: 0 };
430
+ }
431
+ if (playRunning) return playRunning;
432
+ const startedAt = performance.now();
433
+ const context = __museaCreatePlayContext(container);
434
+ playRunning = Promise.resolve()
435
+ .then(() => window.__museaPlay(context))
436
+ .then(() => ({
437
+ status: 'passed',
438
+ duration: Math.round(performance.now() - startedAt),
439
+ report: context.__museaReport()
440
+ }))
441
+ .catch((error) => {
442
+ const failure = error instanceof Error ? error : new Error(String(error));
443
+ failure.museaDuration = Math.round(performance.now() - startedAt);
444
+ failure.museaReport = context.__museaReport();
445
+ throw failure;
446
+ })
447
+ .finally(() => { playRunning = null; });
448
+ return playRunning;
449
+ };
450
+
451
+ window.addEventListener('message', (event) => {
452
+ if (event.source !== window.parent || event.origin !== parentOrigin) return;
453
+ if (event.data?.type !== 'musea:run-play') return;
454
+ const payload = event.data.payload;
455
+ const requestId = typeof payload?.requestId === 'string' ? payload.requestId : undefined;
456
+ (async () => {
457
+ try {
458
+ const result = await window.__museaRunPlay();
459
+ window.parent.postMessage({
460
+ type: 'musea:play-result',
461
+ payload: { requestId, variantName, ...result }
462
+ }, parentOrigin);
463
+ } catch (error) {
464
+ window.parent.postMessage({
465
+ type: 'musea:play-result',
466
+ payload: {
467
+ requestId,
468
+ variantName,
469
+ status: 'failed',
470
+ duration: Number(error?.museaDuration) || 0,
471
+ error: error instanceof Error ? error.message : String(error),
472
+ stack: error instanceof Error ? error.stack : undefined,
473
+ report: error?.museaReport
474
+ }
475
+ }, parentOrigin);
476
+ }
477
+ })();
478
+ });
479
+ }
480
+ `;
481
+ //#endregion
482
+ //#region src/preview/play.ts
483
+ /** Browser-side interaction helpers injected into every isolated preview. */
484
+ const MUSEA_PLAY_RUNTIME_CODE = String.raw`
485
+ function __museaCreatePlayContext(canvasElement) {
486
+ const trace = [];
487
+ const describeTarget = (element) => {
488
+ if (!(element instanceof Element)) return undefined;
489
+ const id = element.id ? '#' + element.id : '';
490
+ const classes = [...element.classList].slice(0, 3).map((name) => '.' + name).join('');
491
+ return element.tagName.toLowerCase() + id + classes;
492
+ };
493
+ const record = async (kind, name, target, run) => {
494
+ const startedAt = performance.now();
495
+ const entry = { kind, name, target: describeTarget(target), status: 'running', duration: 0 };
496
+ trace.push(entry);
497
+ try {
498
+ const value = await run();
499
+ entry.status = 'passed';
500
+ entry.duration = Math.round((performance.now() - startedAt) * 100) / 100;
501
+ return value;
502
+ } catch (error) {
503
+ entry.status = 'failed';
504
+ entry.duration = Math.round((performance.now() - startedAt) * 100) / 100;
505
+ entry.error = error instanceof Error ? error.message : String(error);
506
+ throw error;
507
+ }
508
+ };
509
+ const matchesText = (value, matcher) => {
510
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim();
511
+ if (matcher instanceof RegExp) {
512
+ matcher.lastIndex = 0;
513
+ return matcher.test(text);
514
+ }
515
+ return text === String(matcher);
516
+ };
517
+ const accessibleName = (element) => {
518
+ const labelledBy = element.getAttribute?.('aria-labelledby');
519
+ if (labelledBy) {
520
+ return labelledBy.split(/\s+/).map((id) => document.getElementById(id)?.textContent || '').join(' ');
521
+ }
522
+ return element.getAttribute?.('aria-label')
523
+ || element.getAttribute?.('alt')
524
+ || element.getAttribute?.('title')
525
+ || element.textContent
526
+ || '';
527
+ };
528
+ const implicitRole = (element) => {
529
+ const tag = element.tagName?.toLowerCase();
530
+ if (tag === 'button') return 'button';
531
+ if (tag === 'a' && element.hasAttribute('href')) return 'link';
532
+ if (tag === 'img') return 'img';
533
+ if (tag === 'select') return 'combobox';
534
+ if (tag === 'textarea') return 'textbox';
535
+ if (tag === 'input') {
536
+ const type = (element.getAttribute('type') || 'text').toLowerCase();
537
+ if (type === 'checkbox') return 'checkbox';
538
+ if (type === 'radio') return 'radio';
539
+ if (type === 'button' || type === 'submit' || type === 'reset') return 'button';
540
+ return 'textbox';
541
+ }
542
+ if (/^h[1-6]$/.test(tag || '')) return 'heading';
543
+ if (tag === 'ul' || tag === 'ol') return 'list';
544
+ if (tag === 'li') return 'listitem';
545
+ return null;
546
+ };
547
+ const allElements = () => [canvasElement, ...canvasElement.querySelectorAll('*')];
548
+ const queryAllByRole = (role, options = {}) => allElements().filter((element) => {
549
+ const actual = element.getAttribute?.('role') || implicitRole(element);
550
+ return actual === role && (options.name === undefined || matchesText(accessibleName(element), options.name));
551
+ });
552
+ const queryAllByText = (matcher) => allElements().filter((element) =>
553
+ matchesText(element.textContent, matcher)
554
+ && ![...element.children].some((child) => matchesText(child.textContent, matcher))
555
+ );
556
+ const queryAllByLabelText = (matcher) => [...canvasElement.querySelectorAll('label')]
557
+ .filter((label) => matchesText(label.textContent, matcher))
558
+ .map((label) => label.htmlFor ? document.getElementById(label.htmlFor) : label.querySelector('input,select,textarea,button'))
559
+ .filter(Boolean);
560
+ const one = (kind, matcher, values) => {
561
+ if (values.length !== 1) throw new Error('Expected one element for ' + kind + ' ' + String(matcher) + ', found ' + values.length);
562
+ return values[0];
563
+ };
564
+ const canvas = {
565
+ element: canvasElement,
566
+ queryByRole: (role, options) => queryAllByRole(role, options)[0] || null,
567
+ queryAllByRole,
568
+ getByRole: (role, options) => one('role', role, queryAllByRole(role, options)),
569
+ getAllByRole: (role, options) => {
570
+ const values = queryAllByRole(role, options);
571
+ if (!values.length) throw new Error('No elements found for role ' + role);
572
+ return values;
573
+ },
574
+ queryByText: (matcher) => queryAllByText(matcher)[0] || null,
575
+ queryAllByText,
576
+ getByText: (matcher) => one('text', matcher, queryAllByText(matcher)),
577
+ getAllByText: (matcher) => {
578
+ const values = queryAllByText(matcher);
579
+ if (!values.length) throw new Error('No elements found for text ' + String(matcher));
580
+ return values;
581
+ },
582
+ queryByLabelText: (matcher) => queryAllByLabelText(matcher)[0] || null,
583
+ getByLabelText: (matcher) => one('label', matcher, queryAllByLabelText(matcher)),
584
+ querySelector: (selector) => canvasElement.querySelector(selector),
585
+ querySelectorAll: (selector) => [...canvasElement.querySelectorAll(selector)],
586
+ };
587
+ const dispatch = (element, type, init = {}) => element.dispatchEvent(new Event(type, { bubbles: true, cancelable: true, ...init }));
588
+ const userEvent = {
589
+ click: (element) => record('action', 'click', element, async () => { element.focus?.(); element.click(); await Promise.resolve(); }),
590
+ dblClick: (element) => record('action', 'double click', element, async () => { element.focus?.(); element.click(); element.click(); element.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })); await Promise.resolve(); }),
591
+ clear: (element) => record('action', 'clear', element, async () => { element.focus?.(); element.value = ''; dispatch(element, 'input'); dispatch(element, 'change'); await Promise.resolve(); }),
592
+ type: (element, text) => record('action', 'type ' + JSON.stringify(String(text)), element, async () => {
593
+ element.focus?.();
594
+ for (const character of String(text)) {
595
+ element.dispatchEvent(new KeyboardEvent('keydown', { key: character, bubbles: true }));
596
+ element.value = String(element.value ?? '') + character;
597
+ element.dispatchEvent(new InputEvent('input', { data: character, inputType: 'insertText', bubbles: true }));
598
+ element.dispatchEvent(new KeyboardEvent('keyup', { key: character, bubbles: true }));
599
+ await Promise.resolve();
600
+ }
601
+ dispatch(element, 'change');
602
+ }),
603
+ selectOptions: (element, values) => record('action', 'select options', element, async () => {
604
+ const selected = new Set((Array.isArray(values) ? values : [values]).map(String));
605
+ for (const option of element.options || []) option.selected = selected.has(option.value);
606
+ dispatch(element, 'input'); dispatch(element, 'change'); await Promise.resolve();
607
+ }),
608
+ };
609
+ const deepEqual = (left, right) => {
610
+ if (Object.is(left, right)) return true;
611
+ try { return JSON.stringify(left) === JSON.stringify(right); } catch { return false; }
612
+ };
613
+ const createExpectation = (actual, negate = false) => {
614
+ const check = (pass, message) => {
615
+ const passed = negate ? !pass : pass;
616
+ const detail = (negate ? 'Expected not: ' : 'Expected: ') + message;
617
+ trace.push({ kind: 'assertion', name: detail, status: passed ? 'passed' : 'failed', duration: 0 });
618
+ if (!passed) throw new Error(detail);
619
+ };
620
+ const api = {
621
+ get not() { return createExpectation(actual, !negate); },
622
+ toBe: (expected) => check(Object.is(actual, expected), String(actual) + ' to be ' + String(expected)),
623
+ toEqual: (expected) => check(deepEqual(actual, expected), JSON.stringify(actual) + ' to equal ' + JSON.stringify(expected)),
624
+ toBeTruthy: () => check(Boolean(actual), String(actual) + ' to be truthy'),
625
+ toBeFalsy: () => check(!actual, String(actual) + ' to be falsy'),
626
+ toContain: (expected) => check(actual?.includes?.(expected) === true, String(actual) + ' to contain ' + String(expected)),
627
+ toBeInTheDocument: () => check(actual instanceof Node && document.contains(actual), 'element to be in the document'),
628
+ toBeVisible: () => {
629
+ const style = actual instanceof Element ? getComputedStyle(actual) : null;
630
+ check(Boolean(style && style.display !== 'none' && style.visibility !== 'hidden' && actual.getClientRects().length), 'element to be visible');
631
+ },
632
+ toHaveTextContent: (expected) => check(matchesText(actual?.textContent, expected), JSON.stringify(actual?.textContent) + ' to match ' + String(expected)),
633
+ toHaveValue: (expected) => check(Object.is(actual?.value, expected), String(actual?.value) + ' to be ' + String(expected)),
634
+ toBeChecked: () => check(actual?.checked === true, 'element to be checked'),
635
+ toHaveAttribute: (name, value) => check(actual?.hasAttribute?.(name) && (value === undefined || actual.getAttribute(name) === String(value)), 'element to have attribute ' + name),
636
+ toHaveClass: (...names) => check(names.every((name) => actual?.classList?.contains(name)), 'element to have classes ' + names.join(', ')),
637
+ };
638
+ return api;
639
+ };
640
+ return {
641
+ canvas,
642
+ canvasElement,
643
+ user: userEvent,
644
+ userEvent,
645
+ expect: (actual) => createExpectation(actual),
646
+ step: (name, run) => record('step', String(name), undefined, run),
647
+ __museaReport: () => ({ trace: trace.map((entry) => ({ ...entry })) }),
648
+ };
649
+ }
650
+ `;
416
651
  //#endregion
417
652
  //#region src/preview/html.ts
418
653
  function generatePreviewHtml(art, variant, _basePath, viteBase) {
@@ -537,6 +772,9 @@ function generatePreviewModule(art, variantComponentName, variantName, cssImport
537
772
  const globals = toolbar.length > 0;
538
773
  const setupCall = previewSetup ? `await __museaPreviewSetup(app${globals ? ", { globals: __museaGlobals }" : ""});` : "";
539
774
  const actionEvents = JSON.stringify(art.metadata.actionEvents ?? []);
775
+ const hasPlay = Boolean(art.variants?.find((variant) => variant.name === variantName)?.play);
776
+ const playRuntime = hasPlay ? MUSEA_PLAY_RUNTIME_CODE + MUSEA_PLAY_INIT_CODE : "";
777
+ const playInit = hasPlay ? `\n __museaInitPlay(container, ${variantNameLiteral});` : "";
540
778
  const legacyVue = isLegacyVueVersion(vueVersion);
541
779
  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
780
  const destroyCurrentApp = legacyVue ? "currentApp.$destroy();" : "currentApp.unmount();";
@@ -552,11 +790,12 @@ import * as artModule from ${artModuleIdLiteral};
552
790
 
553
791
  const container = document.getElementById('app');
554
792
 
555
- ${MUSEA_ADDONS_INIT_CODE}${generatePreviewGlobals(toolbar)}
793
+ ${playRuntime}${MUSEA_ADDONS_INIT_CODE}${generatePreviewGlobals(toolbar)}
556
794
 
557
795
  let currentApp = null;
558
796
  // Replace raw JSON snapshots so every literal prop name stays an own key.
559
797
  const propsOverride = shallowRef({});
798
+ const attrsOverride = shallowRef({});
560
799
  const slotsOverride = reactive({ default: '' });
561
800
 
562
801
  function renderError(title, error) {
@@ -585,8 +824,9 @@ function renderError(title, error) {
585
824
 
586
825
  ${mountHelper}
587
826
 
588
- window.__museaSetProps = (props) => {
827
+ window.__museaSetProps = (props, attrs = {}) => {
589
828
  propsOverride.value = { ...props };
829
+ attrsOverride.value = { ...attrs };
590
830
  };
591
831
 
592
832
  window.__museaSetSlots = (slots) => {
@@ -614,12 +854,13 @@ async function mount() {
614
854
  ${mountCurrentApp}
615
855
 
616
856
  console.log('[musea-preview] Mounted variant:', ${variantNameLiteral});
617
- __museaInitAddons(container, ${variantNameLiteral}, ${actionEvents});
857
+ __museaInitAddons(container, ${variantNameLiteral}, ${actionEvents});${playInit}
618
858
 
619
859
  // Override set-props to remount with raw component + props
620
860
  const TargetComponent = RawComponent || VariantComponent;
621
- window.__museaSetProps = (props) => {
861
+ window.__museaSetProps = (props, attrs = {}) => {
622
862
  propsOverride.value = { ...props };
863
+ attrsOverride.value = { ...attrs };
623
864
  remountWithProps(TargetComponent);
624
865
  };
625
866
  window.__museaSetSlots = (slots) => {
@@ -671,7 +912,7 @@ function vue2RemountAppSnippet() {
671
912
  slotFns[name] = slot;
672
913
  if (name === 'default') children.push(...slot());
673
914
  }
674
- return h(Component, { props: { ...propsOverride.value }, scopedSlots: slotFns }, children);
915
+ return h(Component, { props: { ...propsOverride.value }, attrs: { ...attrsOverride.value }, scopedSlots: slotFns }, children);
675
916
  }
676
917
  });`;
677
918
  }
@@ -683,7 +924,7 @@ function vue3RemountAppSnippet() {
683
924
  for (const [name, content] of Object.entries(slotsOverride)) {
684
925
  if (content) slotFns[name] = () => h('span', String(content));
685
926
  }
686
- return h(Component, { ...propsOverride.value }, slotFns);
927
+ return h(Component, { ...attrsOverride.value, ...propsOverride.value }, slotFns);
687
928
  };
688
929
  }
689
930
  });`;
@@ -699,6 +940,9 @@ function generatePreviewModuleWithProps(art, variantComponentName, variantName,
699
940
  const globals = toolbar.length > 0;
700
941
  const setupCall = previewSetup ? `await __museaPreviewSetup(app${globals ? ", { globals: __museaGlobals }" : ""});` : "";
701
942
  const actionEvents = JSON.stringify(art.metadata.actionEvents ?? []);
943
+ const hasPlay = Boolean(art.variants?.find((variant) => variant.name === variantName)?.play);
944
+ const playRuntime = hasPlay ? MUSEA_PLAY_RUNTIME_CODE + MUSEA_PLAY_INIT_CODE : "";
945
+ const playInit = hasPlay ? `\n __museaInitPlay(container, ${variantNameLiteral});` : "";
702
946
  const legacyVue = isLegacyVueVersion(vueVersion);
703
947
  const vueImport = legacyVue ? `import Vue${globals ? ", { ref as __museaCreateGlobalsRef }" : ""} from 'vue';` : `import { createApp, h${globals ? ", ref as __museaCreateGlobalsRef" : ""} } from 'vue';`;
704
948
  const wrappedComponent = legacyVue ? `const WrappedComponent = {
@@ -721,7 +965,7 @@ import * as artModule from ${artModuleIdLiteral};
721
965
  const container = document.getElementById('app');
722
966
  const propsOverride = JSON.parse(${JSON.stringify(propsJson)});
723
967
 
724
- ${MUSEA_ADDONS_INIT_CODE}${generatePreviewGlobals(toolbar)}
968
+ ${playRuntime}${MUSEA_ADDONS_INIT_CODE}${generatePreviewGlobals(toolbar)}
725
969
 
726
970
  function renderError(title, error) {
727
971
  container.textContent = '';
@@ -755,7 +999,7 @@ async function mount() {
755
999
  container.className = 'musea-variant';
756
1000
  ${appMount}
757
1001
  console.log('[musea-preview] Mounted variant with props override:', ${variantNameLiteral});
758
- __museaInitAddons(container, ${variantNameLiteral}, ${actionEvents});
1002
+ __museaInitAddons(container, ${variantNameLiteral}, ${actionEvents});${playInit}
759
1003
  } catch (error) {
760
1004
  console.error('[musea-preview] Failed to mount:', error);
761
1005
  renderError('Failed to render', error);
@@ -838,7 +1082,7 @@ async function tryLoadSourceGalleryHtml(devServer, url, basePath, devSessionToke
838
1082
  return devServer.transformIndexHtml(url, html);
839
1083
  }
840
1084
  async function generateFallbackGalleryHtml(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar) {
841
- const { generateGalleryHtml } = await import("./gallery-DNxzJA4V.mjs");
1085
+ const { generateGalleryHtml } = await import("./gallery-CLjSInLi.mjs");
842
1086
  return generateGalleryHtml(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar);
843
1087
  }
844
1088
  async function serveGalleryAsset(galleryDistDir, requestUrl, res, basePath = "/__musea__") {
@@ -1322,13 +1566,42 @@ function rebaseScriptSetup(scriptSetup, artDir) {
1322
1566
  * carried over so the pipeline strips TypeScript from template expressions.
1323
1567
  */
1324
1568
  function buildVariantSfcSource(art, variantTemplate, variantName, options = {}) {
1569
+ const playRegistration = createPlayRegistration(options.play);
1570
+ const variantContracts = createVariantContracts(options.props, options.attrs, options.componentBindingName);
1571
+ const boundTemplate = injectVariantBindings(variantTemplate, options.componentBindingName, Boolean(options.props || options.attrs));
1325
1572
  if (options.sharedBindings && options.sharedBindings.names.length > 0) {
1326
1573
  const { moduleId, names } = options.sharedBindings;
1327
1574
  const escapedShared = variantName.replace(/"/g, """);
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`;
1575
+ return `<script setup lang="ts">\n` + (options.componentBindingName && !names.includes(options.componentBindingName) ? componentImportCode(options) : "") + `import { ${names.join(", ")} } from ${JSON.stringify(moduleId)}\n` + variantContracts + playRegistration + `<\/script>\n<template><div data-variant="${escapedShared}">${boundTemplate}</div></template>\n`;
1329
1576
  }
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`;
1577
+ const authoredScriptSetup = options.scriptSetup ?? art.scriptSetupContent ?? "";
1578
+ const parsedScriptSetup = authoredScriptSetup.trim() ? parseScriptSetupForArt(authoredScriptSetup) : null;
1579
+ const scriptSetup = rebaseScriptSetup(authoredScriptSetup, path.dirname(options.artFilePath ?? art.path));
1580
+ const componentAlreadyImported = options.componentBindingName && parsedScriptSetup?.imports.some((statement) => importDeclaresName(statement, options.componentBindingName));
1581
+ return `${`<script setup lang="ts">\n${`${options.componentImportStatement || componentAlreadyImported ? "" : componentImportCode(options)}${scriptSetup.trim()}${variantContracts}${playRegistration}`.trim()}\n<\/script>\n`}<template><div data-variant="${variantName.replace(/"/g, "&quot;")}">${boundTemplate}</div></template>\n`;
1582
+ }
1583
+ function componentImportCode(options) {
1584
+ if (options.componentImportStatement) return `${rewriteRelativeImportStatement(options.componentImportStatement, path.dirname(options.artFilePath ?? "."))}\n`;
1585
+ return options.componentImportPath && options.componentBindingName ? `import ${options.componentBindingName} from ${JSON.stringify(options.componentImportPath)}\n` : "";
1586
+ }
1587
+ function createPlayRegistration(play) {
1588
+ if (!play) return "";
1589
+ return `
1590
+ const __museaVariantPlay: MuseaPlay = (${assertStaticExpression(play, "play")});
1591
+ if (typeof window !== "undefined") { (window as any).__museaPlay = __museaVariantPlay; }
1592
+ `;
1593
+ }
1594
+ function createVariantContracts(props, attrs, componentBindingName) {
1595
+ const propType = componentBindingName ? `MuseaComponentProps<typeof ${componentBindingName}>` : "Record<string, unknown>";
1596
+ const propsCheck = props ? `\nconst __museaVariantProps = ${serializeScriptValue(props)} satisfies Partial<${propType}>;\n` : "";
1597
+ const attrsCheck = attrs ? `\nconst __museaVariantAttrs = ${serializeScriptValue(attrs)} satisfies ${componentBindingName ? `MuseaComponentAttrs<typeof ${componentBindingName}>` : "MuseaAttrs"};\n` : "";
1598
+ const bindings = props || attrs ? `\nconst __museaVariantBindings = { ...${attrs ? "__museaVariantAttrs" : "{}"}, ...${props ? "__museaVariantProps" : "{}"} };\n` : "";
1599
+ return propsCheck + attrsCheck + bindings;
1600
+ }
1601
+ function injectVariantBindings(template, componentBindingName, hasBindings) {
1602
+ if (!componentBindingName || !hasBindings) return template;
1603
+ const escaped = componentBindingName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1604
+ return template.replace(new RegExp(`<${escaped}(?=[\\s/>])`), `<${componentBindingName} v-bind="__museaVariantBindings"`);
1332
1605
  }
1333
1606
  /**
1334
1607
  * Compile a variant to a self-contained ES module exporting the component.
@@ -1342,12 +1615,16 @@ function compileVariantSfc(art, variantTemplate, variantName, filename, options
1342
1615
  root: options.root,
1343
1616
  scanRoots: options.scanRoots
1344
1617
  });
1345
- const source = buildVariantSfcSource(art, expandSelfTag(variantTemplate, component.componentTagName), variantName, {
1618
+ const source = buildVariantSfcSource(art, variantTemplate, variantName, {
1346
1619
  scriptSetup: options.scriptSetup,
1347
1620
  componentImportPath: component.componentImportPath,
1348
1621
  componentBindingName: component.componentBindingName,
1622
+ componentImportStatement: component.componentImportStatement,
1349
1623
  artFilePath: filename,
1350
- sharedBindings: options.sharedBindings
1624
+ sharedBindings: options.sharedBindings,
1625
+ play: options.play,
1626
+ props: options.props,
1627
+ attrs: options.attrs
1351
1628
  });
1352
1629
  const result = loadNative().compileSfc(source, { filename });
1353
1630
  return {
@@ -1514,7 +1791,10 @@ function createLoad(state) {
1514
1791
  parsedScriptSetup,
1515
1792
  root: state.getConfigRoot(),
1516
1793
  scanRoots: state.getScanRoots(),
1517
- sharedBindings: shared
1794
+ sharedBindings: shared,
1795
+ play: variant.play,
1796
+ props: variant.props,
1797
+ attrs: variant.attrs
1518
1798
  });
1519
1799
  if (compiled.errors.length > 0) throw new Error(`Failed to compile <art> variant "${variantName}" in ${artPath}:\n${compiled.errors.join("\n")}`);
1520
1800
  if (!compiled.code) throw new Error(`The compiler produced no code for <art> variant "${variantName}" in ${artPath}.`);
@@ -2027,7 +2307,7 @@ function createRawArtInputOwner(config) {
2027
2307
  if (!file.endsWith(".art.vue") || !shouldProcess(file, include, exclude, root) || !isTrustedSourcePath(root, scanRoots, file)) return false;
2028
2308
  const native = loadNative();
2029
2309
  if (!native.parseSfc(source, { filename: file }).customBlocks.some((block) => block.type === "art")) return false;
2030
- return native.parseArt(source, { filename: file }).variants.length > 0;
2310
+ return native.parseArt(sourceWithOptionalArtTitle(source), { filename: file }).variants.length > 0;
2031
2311
  } });
2032
2312
  }
2033
2313
  //#endregion
@@ -2282,4 +2562,4 @@ function resolveProjectRoot(projectRoot, viteRoot) {
2282
2562
  //#endregion
2283
2563
  export { musea };
2284
2564
 
2285
- //# sourceMappingURL=plugin-D2KEfrj1.mjs.map
2565
+ //# sourceMappingURL=plugin-BhEarB-i.mjs.map