@vizejs/vite-plugin-musea 0.441.0 → 0.442.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 (61) hide show
  1. package/dist/a11y/index.d.mts +1 -1
  2. package/dist/a11y/index.mjs +1 -1
  3. package/dist/{a11y-BbFK942j.mjs → a11y-BU5kFNk-.mjs} +6 -5
  4. package/dist/a11y-BU5kFNk-.mjs.map +1 -0
  5. package/dist/cli/index.d.mts +7 -1
  6. package/dist/cli/index.d.mts.map +1 -1
  7. package/dist/cli/index.mjs +110 -9
  8. package/dist/cli/index.mjs.map +1 -1
  9. package/dist/gallery/assets/MonacoEditor-DpMHG8uG.js +2 -0
  10. package/dist/gallery/assets/MonacoEditor-DxzpSKbC.css +1 -0
  11. package/dist/gallery/assets/{cssMode-D6nK_kDe.js → cssMode-BhNXI_iH.js} +1 -1
  12. package/dist/gallery/assets/{editor.api-Bs4-VZ3V.js → editor.api-pyN3BEOj.js} +1 -1
  13. package/dist/gallery/assets/{freemarker2-rDjl8685.js → freemarker2-DDdeAW1l.js} +1 -1
  14. package/dist/gallery/assets/{handlebars-OkqFmHQQ.js → handlebars-d_XLJufS.js} +1 -1
  15. package/dist/gallery/assets/{html-Bq6Ai15v.js → html-pNQuOCmG.js} +1 -1
  16. package/dist/gallery/assets/{htmlMode-H8XqFg_c.js → htmlMode-C9_7c2MZ.js} +1 -1
  17. package/dist/gallery/assets/index-DpZpi0O6.css +1 -0
  18. package/dist/gallery/assets/{index-V774j4nI.js → index-qkpGvqJF.js} +5 -5
  19. package/dist/gallery/assets/{javascript-DY3JGgzg.js → javascript-V9iW4BoD.js} +1 -1
  20. package/dist/gallery/assets/{jsonMode-CYaDarn3.js → jsonMode-B_jKD9Gd.js} +1 -1
  21. package/dist/gallery/assets/{liquid-DSwk2doy.js → liquid-B5bf9QtA.js} +1 -1
  22. package/dist/gallery/assets/{lspLanguageFeatures-CThGg67f.js → lspLanguageFeatures-DF8jpKLy.js} +1 -1
  23. package/dist/gallery/assets/{mdx-B9XzBagU.js → mdx-B6b4WvnG.js} +1 -1
  24. package/dist/gallery/assets/{python-sRU_mC7d.js → python-C_8hKql2.js} +1 -1
  25. package/dist/gallery/assets/{razor-CUHkZDIN.js → razor-BK6Cp9pQ.js} +1 -1
  26. package/dist/gallery/assets/{register-BRx-S1So.js → register-BcnlSPEw.js} +2 -2
  27. package/dist/gallery/assets/{toggleHighContrast-tYUHUcTT.js → toggleHighContrast-D_Ox9lw9.js} +1 -1
  28. package/dist/gallery/assets/{tsMode-C0mNxmwK.js → tsMode-BODHbLZw.js} +1 -1
  29. package/dist/gallery/assets/{typescript-Ba_YUPxA.js → typescript-CdaOwWaG.js} +1 -1
  30. package/dist/gallery/assets/{vs-omjQMPuv.js → vs-mnsDk7Q8.js} +3 -3
  31. package/dist/gallery/assets/{workers-BOTkt7rp.js → workers-DYnbCsrm.js} +1 -1
  32. package/dist/gallery/assets/{xml-CGK9gfdX.js → xml-ClcAB6Hf.js} +1 -1
  33. package/dist/gallery/assets/{yaml-CA-jHXc3.js → yaml-mW5XIYQE.js} +1 -1
  34. package/dist/gallery/index.html +2 -2
  35. package/dist/{index-GkKsNzkf.d.mts → index-BU4-FGUC.d.mts} +3 -4
  36. package/dist/index-BU4-FGUC.d.mts.map +1 -0
  37. package/dist/{index-CtvsGVFJ.d.mts → index-ZFHsOEPD.d.mts} +6 -1
  38. package/dist/{index-CtvsGVFJ.d.mts.map → index-ZFHsOEPD.d.mts.map} +1 -1
  39. package/dist/index.d.mts +3 -3
  40. package/dist/index.mjs +100 -1263
  41. package/dist/index.mjs.map +1 -1
  42. package/dist/options-DCuB_Fpu.mjs +1843 -0
  43. package/dist/options-DCuB_Fpu.mjs.map +1 -0
  44. package/dist/utils-ChmPv0qc.mjs +55 -0
  45. package/dist/utils-ChmPv0qc.mjs.map +1 -0
  46. package/dist/{vrt-DNNAFYv1.d.mts → vrt-DtcnqPhF.d.mts} +22 -3
  47. package/dist/vrt-DtcnqPhF.d.mts.map +1 -0
  48. package/dist/{vrt-VuGK9wTX.mjs → vrt-PuxpRuHa.mjs} +392 -97
  49. package/dist/vrt-PuxpRuHa.mjs.map +1 -0
  50. package/dist/vrt.d.mts +1 -1
  51. package/dist/vrt.mjs +1 -1
  52. package/package.json +4 -4
  53. package/dist/a11y-BbFK942j.mjs.map +0 -1
  54. package/dist/gallery/assets/MonacoEditor-B2gyQ5TW.js +0 -2
  55. package/dist/gallery/assets/MonacoEditor-Db3Q217Z.css +0 -1
  56. package/dist/gallery/assets/index-DTMv-5r0.css +0 -1
  57. package/dist/index-GkKsNzkf.d.mts.map +0 -1
  58. package/dist/options-Bjo4e_75.mjs +0 -582
  59. package/dist/options-Bjo4e_75.mjs.map +0 -1
  60. package/dist/vrt-DNNAFYv1.d.mts.map +0 -1
  61. package/dist/vrt-VuGK9wTX.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,15 +1,15 @@
1
- import { C as resolveUrlPathInside, E as loadNative, S as resolveTrustedSourcePath, T as analyzeSfcFallback, _ as assertVueSourcePath, a as scanArtFiles, b as resolveInside, c as buildThemeConfig, d as createDevSessionToken, f as parseJsonBody, h as assertArtVueSourcePath, i as resolveScanRoots, m as validateDevApiRequest, n as generateStorybookFiles, o as shouldProcess, p as serializeScriptValue, r as matchGlob, s as toPascalCase, t as escapeHtml, u as collectRequestBody, v as decodeUrlComponent, w as HttpError, x as resolveInsideAny, y as isVueSourcePath } from "./utils-DeMLVlNS.mjs";
2
- import { a as parseScriptSetupForArt, c as resolveArtComponent, d as resolveReadableArtPath, i as generateArtModule, l as allowedSourceRoots, o as rewriteRelativeImportStatement, r as processMuseaArtFile, s as expandSelfTag, t as attachMuseaOptions, u as resolveComponentSourcePath } from "./options-Bjo4e_75.mjs";
1
+ import { C as resolveUrlPathInside, E as loadNative, S as resolveTrustedSourcePath, _ as assertVueSourcePath, a as scanArtFiles, b as resolveInside, c as buildThemeConfig, d as createDevSessionToken, f as parseJsonBody, h as assertArtVueSourcePath, i as resolveScanRoots, m as validateDevApiRequest, n as generateStorybookFiles, o as shouldProcess, p as serializeScriptValue, r as matchGlob, s as toPascalCase, t as escapeHtml, u as collectRequestBody, v as decodeUrlComponent, w as HttpError } from "./utils-DeMLVlNS.mjs";
2
+ import { C as tokenNative, D as rewriteRelativeImportStatement, E as parseScriptSetupForArt, O as expandSelfTag, S as parseTokens, T as generateArtModule, _ as handleTokensUpdate, a as rewriteGalleryBase, b as resolveReferences, c as joinUrlPath, d as handleArtDocs, f as handleArtSource, g as handleTokensGet, h as handleTokensDelete, i as publicBasePathFromViteBase, k as resolveArtComponent, l as staticPreviewId, m as handleTokensCreate, o as rewriteGalleryTextAssetBase, p as handleArtPalette, r as processMuseaArtFile, s as createStaticGalleryPayload, t as attachMuseaOptions, u as handleArtAnalysis, v as handleTokensUsage, w as sortedArts, x as scanTokenUsage, y as buildTokenMap } from "./options-DCuB_Fpu.mjs";
3
3
  import { a as generateGalleryGlobalsScript, i as generateDevGlobalsScript, n as generateGalleryScript, r as generateGalleryModule, t as generateGalleryBody } from "./template-BgBSA10_.mjs";
4
- import { i as MuseaVrtRunner, n as generateVrtJsonReport, r as generateVrtReport } from "./vrt-VuGK9wTX.mjs";
5
- import { t as MuseaA11yRunner } from "./a11y-BbFK942j.mjs";
4
+ import { i as MuseaVrtRunner, n as generateVrtJsonReport, r as generateVrtReport, s as resolveSnapshotIdentity } from "./vrt-PuxpRuHa.mjs";
5
+ import { t as MuseaA11yRunner } from "./a11y-BU5kFNk-.mjs";
6
6
  import { n as writeArtFile, t as generateArtFile } from "./autogen-B-N0cJbZ.mjs";
7
7
  import { createRequire } from "node:module";
8
8
  import fs from "node:fs";
9
9
  import path from "node:path";
10
- import crypto from "node:crypto";
10
+ import { createHash } from "node:crypto";
11
11
  import { fileURLToPath } from "node:url";
12
- import ts from "typescript";
12
+ import { lstat, readFile, readdir } from "node:fs/promises";
13
13
  import { VIZE_CONFIG_FILE_ENV, loadConfig } from "@vizejs/vite-plugin";
14
14
  import { getResolvedVizeConfigRegistration } from "@vizejs/vite-plugin/internal/config-bridge";
15
15
  import * as vite from "vite";
@@ -543,7 +543,7 @@ function generatePreviewModule(art, variantComponentName, variantName, cssImport
543
543
  const artStyleId = `musea-art-styles-${art.path.replace(/[^\w-]+/g, "_")}`;
544
544
  const artStyleIdLiteral = JSON.stringify(artStyleId);
545
545
  const legacyVue = isLegacyVueVersion(vueVersion);
546
- const vueImport = legacyVue ? `import Vue, { reactive${globals ? ", ref as __museaCreateGlobalsRef" : ""} } from 'vue';` : `import { createApp, reactive, h${globals ? ", ref as __museaCreateGlobalsRef" : ""} } from 'vue';`;
546
+ const vueImport = legacyVue ? `import Vue, { reactive, shallowRef${globals ? ", ref as __museaCreateGlobalsRef" : ""} } from 'vue';` : `import { createApp, reactive, shallowRef, h${globals ? ", ref as __museaCreateGlobalsRef" : ""} } from 'vue';`;
547
547
  const destroyCurrentApp = legacyVue ? "currentApp.$destroy();" : "currentApp.unmount();";
548
548
  const mountInitialApp = legacyVue ? "const app = new Vue({ render: (h) => h(VariantComponent) });" : "const app = createApp(VariantComponent);";
549
549
  const mountCurrentApp = legacyVue ? "mountVue2App(app);" : "app.mount(container);\n currentApp = app;";
@@ -560,7 +560,8 @@ const container = document.getElementById('app');
560
560
  ${MUSEA_ADDONS_INIT_CODE}${generatePreviewGlobals(toolbar)}
561
561
 
562
562
  let currentApp = null;
563
- const propsOverride = reactive({});
563
+ // Replace raw JSON snapshots so every literal prop name stays an own key.
564
+ const propsOverride = shallowRef({});
564
565
  const slotsOverride = reactive({ default: '' });
565
566
 
566
567
  function ensureArtStyles(styles) {
@@ -608,11 +609,7 @@ function renderError(title, error) {
608
609
  ${mountHelper}
609
610
 
610
611
  window.__museaSetProps = (props) => {
611
- // Clear old keys
612
- for (const key of Object.keys(propsOverride)) {
613
- delete propsOverride[key];
614
- }
615
- Object.assign(propsOverride, props);
612
+ propsOverride.value = { ...props };
616
613
  };
617
614
 
618
615
  window.__museaSetSlots = (slots) => {
@@ -646,10 +643,7 @@ async function mount() {
646
643
  // Override set-props to remount with raw component + props
647
644
  const TargetComponent = RawComponent || VariantComponent;
648
645
  window.__museaSetProps = (props) => {
649
- for (const key of Object.keys(propsOverride)) {
650
- delete propsOverride[key];
651
- }
652
- Object.assign(propsOverride, props);
646
+ propsOverride.value = { ...props };
653
647
  remountWithProps(TargetComponent);
654
648
  };
655
649
  window.__museaSetSlots = (slots) => {
@@ -702,7 +696,7 @@ function vue2RemountAppSnippet() {
702
696
  slotFns[name] = slot;
703
697
  if (name === 'default') children.push(...slot());
704
698
  }
705
- return h(Component, { props: { ...propsOverride }, scopedSlots: slotFns }, children);
699
+ return h(Component, { props: { ...propsOverride.value }, scopedSlots: slotFns }, children);
706
700
  }
707
701
  });`;
708
702
  }
@@ -714,7 +708,7 @@ function vue3RemountAppSnippet() {
714
708
  for (const [name, content] of Object.entries(slotsOverride)) {
715
709
  if (content) slotFns[name] = () => h('span', String(content));
716
710
  }
717
- return h(Component, { ...propsOverride }, slotFns);
711
+ return h(Component, { ...propsOverride.value }, slotFns);
718
712
  };
719
713
  }
720
714
  });`;
@@ -752,7 +746,7 @@ ${vueImport}
752
746
  import * as artModule from ${artModuleIdLiteral};
753
747
 
754
748
  const container = document.getElementById('app');
755
- const propsOverride = ${propsJson};
749
+ const propsOverride = JSON.parse(${JSON.stringify(propsJson)});
756
750
 
757
751
  ${MUSEA_ADDONS_INIT_CODE}${generatePreviewGlobals(toolbar)}
758
752
 
@@ -1030,563 +1024,6 @@ function registerMiddleware(devServer, ctx) {
1030
1024
  });
1031
1025
  }
1032
1026
  //#endregion
1033
- //#region src/art-order.ts
1034
- function sortedArts(arts) {
1035
- return [...arts].sort(compareArtFiles);
1036
- }
1037
- function compareArtFiles(a, b) {
1038
- const order = compareOrder(a.metadata.order, b.metadata.order);
1039
- if (order !== 0) return order;
1040
- const title = a.metadata.title.localeCompare(b.metadata.title, void 0, { numeric: true });
1041
- if (title !== 0) return title;
1042
- return a.path.localeCompare(b.path, void 0, { numeric: true });
1043
- }
1044
- function compareOrder(a, b) {
1045
- if (a === void 0 && b === void 0) return 0;
1046
- if (a === void 0) return 1;
1047
- if (b === void 0) return -1;
1048
- return a - b;
1049
- }
1050
- //#endregion
1051
- //#region src/tokens/native.ts
1052
- function tokenNative() {
1053
- const native = loadNative();
1054
- return {
1055
- parseDesignTokensFromPath(path) {
1056
- return normalizeCategories(parseJsonResult(native.parseDesignTokensFromPath(path)));
1057
- },
1058
- buildDesignTokenMap(categories) {
1059
- return nullRecord(parseJsonResult(native.buildDesignTokenMap(JSON.stringify(categories))));
1060
- },
1061
- resolveDesignTokenReferences(categories) {
1062
- const resolved = parseJsonResult(native.resolveDesignTokenReferences(JSON.stringify(categories)));
1063
- return {
1064
- ...resolved,
1065
- categories: normalizeCategories(resolved.categories),
1066
- tokenMap: nullRecord(resolved.tokenMap)
1067
- };
1068
- },
1069
- flattenDesignTokenCategories(categories) {
1070
- return parseJsonResult(native.flattenDesignTokenCategories(JSON.stringify(categories)));
1071
- },
1072
- generateDesignTokensMarkdown(categories, generatedAt) {
1073
- return native.generateDesignTokensMarkdown(JSON.stringify(categories), generatedAt);
1074
- },
1075
- validateDesignTokenReference(tokenMap, reference, selfPath) {
1076
- return parseJsonResult(native.validateDesignTokenReference(JSON.stringify(tokenMap), reference, selfPath));
1077
- },
1078
- findDependentDesignTokens(tokenMap, targetPath) {
1079
- return native.findDependentDesignTokens(JSON.stringify(tokenMap), targetPath);
1080
- }
1081
- };
1082
- }
1083
- function parseJsonResult(value) {
1084
- if (typeof value === "string") return JSON.parse(value);
1085
- return value;
1086
- }
1087
- function normalizeCategories(categories) {
1088
- for (const category of categories) {
1089
- category.tokens = nullRecord(Object.fromEntries(sortTokenEntries(category.tokens)));
1090
- if (category.subcategories) normalizeCategories(category.subcategories);
1091
- }
1092
- return categories;
1093
- }
1094
- function sortTokenEntries(tokens) {
1095
- return Object.entries(tokens).sort((a, b) => {
1096
- const order = compareTokenOrder(a[1], b[1]);
1097
- if (order !== 0) return order;
1098
- return a[0].localeCompare(b[0], void 0, { numeric: true });
1099
- });
1100
- }
1101
- function compareTokenOrder(a, b) {
1102
- const aOrder = tokenOrder(a);
1103
- const bOrder = tokenOrder(b);
1104
- if (aOrder === void 0 && bOrder === void 0) return 0;
1105
- if (aOrder === void 0) return 1;
1106
- if (bOrder === void 0) return -1;
1107
- return aOrder - bOrder;
1108
- }
1109
- function tokenOrder(token) {
1110
- const order = token.attributes?.order;
1111
- if (typeof order === "number" && Number.isFinite(order)) return order;
1112
- if (typeof order === "string") {
1113
- const parsed = Number(order);
1114
- if (Number.isFinite(parsed)) return parsed;
1115
- }
1116
- }
1117
- function nullRecord(record) {
1118
- return Object.assign(Object.create(null), record);
1119
- }
1120
- //#endregion
1121
- //#region src/tokens/tailwind.ts
1122
- const TAILWIND_TOKEN_EXTENSIONS = new Set([
1123
- ".css",
1124
- ".pcss",
1125
- ".postcss"
1126
- ]);
1127
- const VARIABLE_DECLARATION_RE = /(--[A-Za-z0-9_-]+)\s*:\s*([^;{}]+);/g;
1128
- const CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
1129
- const NAMESPACE_MAPPINGS = [
1130
- {
1131
- prefix: "inset-shadow",
1132
- category: "shadow",
1133
- pathPrefix: ["inset"],
1134
- type: "shadow"
1135
- },
1136
- {
1137
- prefix: "drop-shadow",
1138
- category: "shadow",
1139
- pathPrefix: ["drop"],
1140
- type: "shadow"
1141
- },
1142
- {
1143
- prefix: "font-weight",
1144
- category: "typography",
1145
- pathPrefix: ["fontWeight"],
1146
- type: "fontWeight"
1147
- },
1148
- {
1149
- prefix: "color",
1150
- category: "color",
1151
- type: "color"
1152
- },
1153
- {
1154
- prefix: "spacing",
1155
- category: "spacing",
1156
- type: "dimension"
1157
- },
1158
- {
1159
- prefix: "font",
1160
- category: "typography",
1161
- pathPrefix: ["font"],
1162
- type: "fontFamily"
1163
- },
1164
- {
1165
- prefix: "text",
1166
- category: "typography",
1167
- pathPrefix: ["fontSize"],
1168
- type: "dimension"
1169
- },
1170
- {
1171
- prefix: "leading",
1172
- category: "typography",
1173
- pathPrefix: ["lineHeight"],
1174
- type: "number"
1175
- },
1176
- {
1177
- prefix: "tracking",
1178
- category: "typography",
1179
- pathPrefix: ["letterSpacing"],
1180
- type: "dimension"
1181
- },
1182
- {
1183
- prefix: "radius",
1184
- category: "radius",
1185
- type: "dimension"
1186
- },
1187
- {
1188
- prefix: "shadow",
1189
- category: "shadow",
1190
- type: "shadow"
1191
- },
1192
- {
1193
- prefix: "breakpoint",
1194
- category: "breakpoint",
1195
- type: "dimension"
1196
- },
1197
- {
1198
- prefix: "container",
1199
- category: "container",
1200
- type: "dimension"
1201
- },
1202
- {
1203
- prefix: "ease",
1204
- category: "easing",
1205
- type: "cubicBezier"
1206
- },
1207
- {
1208
- prefix: "animate",
1209
- category: "animation",
1210
- type: "transition"
1211
- },
1212
- {
1213
- prefix: "blur",
1214
- category: "blur",
1215
- type: "dimension"
1216
- },
1217
- {
1218
- prefix: "perspective",
1219
- category: "perspective",
1220
- type: "dimension"
1221
- },
1222
- {
1223
- prefix: "aspect",
1224
- category: "aspectRatio",
1225
- type: "number"
1226
- }
1227
- ];
1228
- async function isTailwindTokenPath(tokensPath) {
1229
- const stat = await fs.promises.stat(tokensPath).catch(() => null);
1230
- if (!stat) return false;
1231
- if (stat.isFile()) return TAILWIND_TOKEN_EXTENSIONS.has(path.extname(tokensPath));
1232
- if (!stat.isDirectory()) return false;
1233
- return (await fs.promises.readdir(tokensPath, { withFileTypes: true })).some((entry) => entry.isFile() && TAILWIND_TOKEN_EXTENSIONS.has(path.extname(entry.name)));
1234
- }
1235
- async function parseTailwindTokens(tokensPath) {
1236
- const files = await collectTailwindTokenFiles(tokensPath);
1237
- const candidates = [];
1238
- for (const file of files) {
1239
- const css = await fs.promises.readFile(file, "utf-8");
1240
- candidates.push(...extractTailwindTokenCandidates(css));
1241
- }
1242
- return normalizeCategories(buildCategories(candidates));
1243
- }
1244
- async function collectTailwindTokenFiles(tokensPath) {
1245
- if ((await fs.promises.stat(tokensPath)).isFile()) return [tokensPath];
1246
- return (await fs.promises.readdir(tokensPath, { withFileTypes: true })).filter((entry) => entry.isFile() && TAILWIND_TOKEN_EXTENSIONS.has(path.extname(entry.name))).map((entry) => path.join(tokensPath, entry.name)).sort();
1247
- }
1248
- function extractTailwindTokenCandidates(css) {
1249
- const source = css.replace(CSS_COMMENT_RE, "");
1250
- const candidates = [];
1251
- let match;
1252
- VARIABLE_DECLARATION_RE.lastIndex = 0;
1253
- while ((match = VARIABLE_DECLARATION_RE.exec(source)) !== null) {
1254
- const variable = match[1];
1255
- const value = match[2].trim();
1256
- const mapped = mapTokenVariable(variable, value);
1257
- if (!mapped || !value) continue;
1258
- candidates.push({
1259
- variable,
1260
- value,
1261
- ...mapped
1262
- });
1263
- }
1264
- return candidates;
1265
- }
1266
- function mapTokenVariable(variable, value) {
1267
- const tailwind = mapTailwindVariable(variable);
1268
- if (tailwind) return {
1269
- ...tailwind,
1270
- description: `Tailwind theme variable ${variable}`
1271
- };
1272
- const segments = variable.replace(/^--/, "").split("-").filter(Boolean);
1273
- const category = segments[0];
1274
- if (!category) return null;
1275
- const rest = segments.slice(1).join("-");
1276
- return {
1277
- category,
1278
- path: rest ? [rest] : ["DEFAULT"],
1279
- type: inferCustomPropertyType(value),
1280
- description: `Custom property ${variable}`
1281
- };
1282
- }
1283
- function mapTailwindVariable(variable) {
1284
- const name = variable.replace(/^--/, "");
1285
- const mapping = NAMESPACE_MAPPINGS.find((candidate) => name === candidate.prefix || name.startsWith(`${candidate.prefix}-`));
1286
- if (!mapping) return null;
1287
- const rest = name === mapping.prefix ? "DEFAULT" : name.slice(mapping.prefix.length + 1);
1288
- const pathParts = [...mapping.pathPrefix ?? [], ...tailwindNameToPath(rest)];
1289
- if (pathParts.length === 0) return null;
1290
- return {
1291
- category: mapping.category,
1292
- path: pathParts,
1293
- type: mapping.type
1294
- };
1295
- }
1296
- function inferCustomPropertyType(value) {
1297
- const trimmed = value.trim();
1298
- if (/^(?:#|rgba?\(|hsla?\(|oklch\(|oklab\(|color-mix\(|color\()/i.test(trimmed)) return "color";
1299
- if (/^-?(?:\d+\.\d+|\d+)(?:px|rem|em|vh|vw|vmin|vmax|%)$/i.test(trimmed)) return "dimension";
1300
- if (/^-?(?:\d+\.\d+|\d+)$/.test(trimmed)) return "number";
1301
- return "other";
1302
- }
1303
- function tailwindNameToPath(name) {
1304
- if (!name || name === "DEFAULT") return ["DEFAULT"];
1305
- const parts = name.split("-").filter(Boolean);
1306
- if (parts.length <= 1) return parts;
1307
- const last = parts[parts.length - 1];
1308
- if (/^\d+$/.test(last)) return [...parts.slice(0, -1), last];
1309
- return [parts.join("-")];
1310
- }
1311
- function buildCategories(candidates) {
1312
- const variableToPath = /* @__PURE__ */ new Map();
1313
- for (const candidate of candidates) variableToPath.set(candidate.variable, [candidate.category, ...candidate.path].join("."));
1314
- const categoryMap = /* @__PURE__ */ new Map();
1315
- for (const candidate of candidates) {
1316
- const category = categoryMap.get(candidate.category) ?? {
1317
- name: candidate.category,
1318
- tokens: nullRecord({})
1319
- };
1320
- categoryMap.set(candidate.category, category);
1321
- const valueReference = parseTailwindVariableReference(candidate.value);
1322
- const referencedPath = valueReference ? variableToPath.get(valueReference) : void 0;
1323
- const token = {
1324
- value: referencedPath ? `{${referencedPath}}` : candidate.value,
1325
- type: candidate.type,
1326
- description: candidate.description,
1327
- attributes: { tailwindVariable: candidate.variable },
1328
- $tier: referencedPath ? "semantic" : "primitive",
1329
- ...referencedPath ? { $reference: referencedPath } : {}
1330
- };
1331
- setCategoryToken(category, candidate.path, token);
1332
- }
1333
- return [...categoryMap.values()];
1334
- }
1335
- function parseTailwindVariableReference(value) {
1336
- return value.match(/^var\(\s*(--[A-Za-z0-9_-]+)\s*(?:,[^)]+)?\)$/)?.[1];
1337
- }
1338
- function setCategoryToken(category, pathParts, token) {
1339
- if (pathParts.length === 1) {
1340
- category.tokens[pathParts[0]] = token;
1341
- return;
1342
- }
1343
- let current = category;
1344
- for (const part of pathParts.slice(0, -1)) {
1345
- current.subcategories ??= [];
1346
- let next = current.subcategories.find((subcategory) => subcategory.name === part);
1347
- if (!next) {
1348
- next = {
1349
- name: part,
1350
- tokens: nullRecord({})
1351
- };
1352
- current.subcategories.push(next);
1353
- }
1354
- current = next;
1355
- }
1356
- current.tokens[pathParts[pathParts.length - 1]] = token;
1357
- }
1358
- //#endregion
1359
- //#region src/tokens/parser.ts
1360
- /**
1361
- * Token parsing utilities for Style Dictionary integration.
1362
- *
1363
- * Thin native binding for design token files (JSON) and directories.
1364
- */
1365
- /**
1366
- * Parse Style Dictionary tokens file/directory or Tailwind CSS theme variables.
1367
- */
1368
- async function parseTokens(tokensPath) {
1369
- if (await isTailwindTokenPath(tokensPath)) return parseTailwindTokens(tokensPath);
1370
- return normalizeCategories(tokenNative().parseDesignTokensFromPath(tokensPath));
1371
- }
1372
- //#endregion
1373
- //#region src/tokens/usage.ts
1374
- /**
1375
- * Token usage scanning and value normalization.
1376
- *
1377
- * Scans art file `<style>` blocks for CSS property values that match
1378
- * design token values, and provides value normalization utilities.
1379
- */
1380
- /**
1381
- * Normalize a token value for comparison.
1382
- * - Lowercase, trim
1383
- * - Leading-zero: `.5rem` -> `0.5rem`
1384
- * - Short hex: `#fff` -> `#ffffff`
1385
- */
1386
- function normalizeTokenValue(value) {
1387
- let v = String(value).trim().toLowerCase();
1388
- const shortHex = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?$/);
1389
- if (shortHex) {
1390
- const [, r, g, b, a] = shortHex;
1391
- v = a ? `#${r}${r}${g}${g}${b}${b}${a}${a}` : `#${r}${r}${g}${g}${b}${b}`;
1392
- }
1393
- v = v.replace(/(?<![0-9])\.(\d)/g, "0.$1");
1394
- return v;
1395
- }
1396
- const STYLE_BLOCK_RE = /<style[^>]*>([\s\S]*?)<\/style>/g;
1397
- const CSS_PROPERTY_RE = /^\s*([\w-]+)\s*:\s*(.+?)\s*;?\s*$/;
1398
- /**
1399
- * Scan art file sources for token value matches in `<style>` blocks.
1400
- */
1401
- function scanTokenUsage(artFiles, tokenMap) {
1402
- const valueLookup = /* @__PURE__ */ new Map();
1403
- for (const [tokenPath, token] of Object.entries(tokenMap)) {
1404
- const normalized = normalizeTokenValue(token.$resolvedValue ?? token.value);
1405
- if (!normalized) continue;
1406
- const existing = valueLookup.get(normalized);
1407
- if (existing) existing.push(tokenPath);
1408
- else valueLookup.set(normalized, [tokenPath]);
1409
- const tailwindVariable = token.attributes?.tailwindVariable;
1410
- if (typeof tailwindVariable === "string") {
1411
- const normalizedVariable = normalizeTokenValue(`var(${tailwindVariable})`);
1412
- const variableMatches = valueLookup.get(normalizedVariable);
1413
- if (variableMatches) variableMatches.push(tokenPath);
1414
- else valueLookup.set(normalizedVariable, [tokenPath]);
1415
- }
1416
- }
1417
- const usageMap = {};
1418
- for (const [artPath, artInfo] of artFiles) {
1419
- let source;
1420
- try {
1421
- source = fs.readFileSync(artPath, "utf-8");
1422
- } catch {
1423
- continue;
1424
- }
1425
- const allLines = source.split("\n");
1426
- const styleRegions = [];
1427
- let match;
1428
- STYLE_BLOCK_RE.lastIndex = 0;
1429
- while ((match = STYLE_BLOCK_RE.exec(source)) !== null) {
1430
- const beforeMatch = source.slice(0, match.index);
1431
- const startTag = source.slice(match.index, match.index + match[0].indexOf(match[1]));
1432
- const startLine = beforeMatch.split("\n").length + startTag.split("\n").length - 1;
1433
- styleRegions.push({
1434
- startLine,
1435
- content: match[1]
1436
- });
1437
- }
1438
- for (const region of styleRegions) {
1439
- const lines = region.content.split("\n");
1440
- for (let i = 0; i < lines.length; i++) {
1441
- const line = lines[i];
1442
- const propMatch = line.match(CSS_PROPERTY_RE);
1443
- if (!propMatch) continue;
1444
- const property = propMatch[1];
1445
- const valueParts = propMatch[2].split(/\s+/);
1446
- for (const part of valueParts) {
1447
- const normalizedPart = normalizeTokenValue(part);
1448
- const matchingTokens = valueLookup.get(normalizedPart);
1449
- if (!matchingTokens) continue;
1450
- const lineNumber = region.startLine + i;
1451
- const lineContent = allLines[lineNumber - 1]?.trim() ?? line.trim();
1452
- for (const tokenPath of matchingTokens) {
1453
- if (!usageMap[tokenPath]) usageMap[tokenPath] = [];
1454
- let entry = usageMap[tokenPath].find((e) => e.artPath === artPath);
1455
- if (!entry) {
1456
- entry = {
1457
- artPath,
1458
- artTitle: artInfo.metadata.title,
1459
- artCategory: artInfo.metadata.category,
1460
- matches: []
1461
- };
1462
- usageMap[tokenPath].push(entry);
1463
- }
1464
- if (!entry.matches.some((m) => m.line === lineNumber && m.property === property)) entry.matches.push({
1465
- line: lineNumber,
1466
- lineContent,
1467
- property
1468
- });
1469
- }
1470
- }
1471
- }
1472
- }
1473
- }
1474
- return usageMap;
1475
- }
1476
- //#endregion
1477
- //#region src/tokens/resolver.ts
1478
- /**
1479
- * Token resolution, CRUD operations, and validation.
1480
- *
1481
- * Handles building flat token maps from categories, resolving reference chains,
1482
- * reading/writing raw token files, and validating semantic references.
1483
- */
1484
- const JSON_TOKEN_EXTENSIONS = new Set([".json", ".tokens.json"]);
1485
- const UNSAFE_TOKEN_PATH_SEGMENTS = new Set([
1486
- "__proto__",
1487
- "prototype",
1488
- "constructor"
1489
- ]);
1490
- function parseTokenPath(dotPath) {
1491
- const parts = dotPath.split(".");
1492
- if (parts.length === 0 || parts.some((part) => part.trim() === "")) throw new Error(`Invalid token path "${dotPath}"`);
1493
- const unsafeSegment = parts.find((part) => UNSAFE_TOKEN_PATH_SEGMENTS.has(part));
1494
- if (unsafeSegment) throw new Error(`Token path segment "${unsafeSegment}" is not allowed`);
1495
- return parts;
1496
- }
1497
- /**
1498
- * Flatten nested categories into a flat map keyed by dot-path.
1499
- */
1500
- function buildTokenMap(categories) {
1501
- return nullRecord(tokenNative().buildDesignTokenMap(categories));
1502
- }
1503
- /**
1504
- * Resolve references in categories, setting $tier, $reference, and $resolvedValue.
1505
- */
1506
- function resolveReferences(categories, _tokenMap) {
1507
- const resolved = tokenNative().resolveDesignTokenReferences(categories);
1508
- categories.splice(0, categories.length, ...normalizeCategories(resolved.categories));
1509
- }
1510
- /**
1511
- * Read raw JSON token file.
1512
- */
1513
- async function readRawTokenFile(tokensPath) {
1514
- if (!isJsonTokenPath(tokensPath)) throw new Error("Token editing is only supported for JSON token files");
1515
- const content = await fs.promises.readFile(tokensPath, "utf-8");
1516
- return JSON.parse(content);
1517
- }
1518
- /**
1519
- * Write raw JSON token file atomically (write tmp, rename).
1520
- */
1521
- async function writeRawTokenFile(tokensPath, data) {
1522
- if (!isJsonTokenPath(tokensPath)) throw new Error("Token editing is only supported for JSON token files");
1523
- const tmpPath = tokensPath + ".tmp";
1524
- await fs.promises.writeFile(tmpPath, JSON.stringify(data, null, 2) + "\n", "utf-8");
1525
- await fs.promises.rename(tmpPath, tokensPath);
1526
- }
1527
- function isJsonTokenPath(tokensPath) {
1528
- return JSON_TOKEN_EXTENSIONS.has(path.extname(tokensPath)) || tokensPath.endsWith(".tokens.json");
1529
- }
1530
- /**
1531
- * Set a token at a dot-separated path in the raw JSON structure.
1532
- */
1533
- function setTokenAtPath(data, dotPath, token) {
1534
- const parts = parseTokenPath(dotPath);
1535
- let current = data;
1536
- for (let i = 0; i < parts.length - 1; i++) {
1537
- const key = parts[i];
1538
- if (typeof current[key] !== "object" || current[key] === null) current[key] = {};
1539
- current = current[key];
1540
- }
1541
- const leafKey = parts[parts.length - 1];
1542
- const raw = { value: token.value };
1543
- if (token.type) raw.type = token.type;
1544
- if (token.description) raw.description = token.description;
1545
- if (token.$tier) raw.$tier = token.$tier;
1546
- if (token.$reference) raw.$reference = token.$reference;
1547
- if (token.attributes) raw.attributes = token.attributes;
1548
- current[leafKey] = raw;
1549
- }
1550
- /**
1551
- * Delete a token at a dot-separated path, cleaning empty parents.
1552
- */
1553
- function deleteTokenAtPath(data, dotPath) {
1554
- const parts = parseTokenPath(dotPath);
1555
- const parents = [];
1556
- let current = data;
1557
- for (let i = 0; i < parts.length - 1; i++) {
1558
- const key = parts[i];
1559
- if (typeof current[key] !== "object" || current[key] === null) return false;
1560
- parents.push({
1561
- obj: current,
1562
- key
1563
- });
1564
- current = current[key];
1565
- }
1566
- const leafKey = parts[parts.length - 1];
1567
- if (!(leafKey in current)) return false;
1568
- delete current[leafKey];
1569
- for (let i = parents.length - 1; i >= 0; i--) {
1570
- const { obj, key } = parents[i];
1571
- const child = obj[key];
1572
- if (Object.keys(child).length === 0) delete obj[key];
1573
- else break;
1574
- }
1575
- return true;
1576
- }
1577
- /**
1578
- * Validate that a semantic reference points to an existing token and has no cycles.
1579
- */
1580
- function validateSemanticReference(tokenMap, reference, selfPath) {
1581
- return tokenNative().validateDesignTokenReference(tokenMap, reference, selfPath);
1582
- }
1583
- /**
1584
- * Find all tokens that reference the given path.
1585
- */
1586
- function findDependentTokens(tokenMap, targetPath) {
1587
- return tokenNative().findDependentDesignTokens(tokenMap, targetPath);
1588
- }
1589
- //#endregion
1590
1027
  //#region src/tokens/generator.ts
1591
1028
  /**
1592
1029
  * Token documentation generators for Style Dictionary integration.
@@ -1889,577 +1326,83 @@ function toArray(value) {
1889
1326
  return Array.isArray(value) ? value : [value];
1890
1327
  }
1891
1328
  //#endregion
1892
- //#region src/api-tokens.ts
1893
- function resolveTokensPath(ctx) {
1894
- const allowedRoots = [ctx.config.root, ...ctx.scanRoots];
1895
- if (ctx.projectRoot) allowedRoots.push(ctx.projectRoot);
1896
- return resolveInsideAny(allowedRoots, ctx.tokensPath, "tokensPath");
1897
- }
1898
- function sendTokenMutationError(e, sendError) {
1899
- if (e instanceof HttpError) {
1900
- sendError(e.message, e.status);
1901
- return;
1902
- }
1903
- if (e instanceof Error && /(token path|token editing)/i.test(e.message)) {
1904
- sendError(e.message, 400);
1905
- return;
1906
- }
1907
- sendError(e instanceof Error ? e.message : String(e));
1908
- }
1909
- /** GET /api/tokens/usage */
1910
- async function handleTokensUsage(ctx, sendJson) {
1911
- if (!ctx.tokensPath) {
1912
- sendJson({});
1913
- return;
1914
- }
1915
- try {
1916
- const categories = await parseTokens(resolveTokensPath(ctx));
1917
- resolveReferences(categories, buildTokenMap(categories));
1918
- const resolvedTokenMap = buildTokenMap(categories);
1919
- sendJson(scanTokenUsage(ctx.artFiles, resolvedTokenMap));
1920
- } catch (e) {
1921
- console.error("[musea] Failed to scan token usage:", e);
1922
- sendJson({});
1923
- }
1924
- }
1925
- /** GET /api/tokens */
1926
- async function handleTokensGet(ctx, sendJson) {
1927
- if (!ctx.tokensPath) {
1928
- sendJson({
1929
- categories: [],
1930
- tokenMap: {},
1931
- meta: {
1932
- filePath: "",
1933
- tokenCount: 0,
1934
- primitiveCount: 0,
1935
- semanticCount: 0
1936
- }
1937
- });
1938
- return;
1939
- }
1940
- try {
1941
- const absoluteTokensPath = resolveTokensPath(ctx);
1942
- const categories = await parseTokens(absoluteTokensPath);
1943
- resolveReferences(categories, buildTokenMap(categories));
1944
- const resolvedTokenMap = buildTokenMap(categories);
1945
- let primitiveCount = 0;
1946
- let semanticCount = 0;
1947
- for (const token of Object.values(resolvedTokenMap)) if (token.$tier === "semantic") semanticCount++;
1948
- else primitiveCount++;
1949
- sendJson({
1950
- categories,
1951
- tokenMap: resolvedTokenMap,
1952
- meta: {
1953
- filePath: absoluteTokensPath,
1954
- tokenCount: Object.keys(resolvedTokenMap).length,
1955
- primitiveCount,
1956
- semanticCount
1957
- }
1958
- });
1959
- } catch (e) {
1960
- console.error("[musea] Failed to load tokens:", e);
1961
- sendJson({
1962
- categories: [],
1963
- tokenMap: {},
1964
- error: String(e)
1965
- });
1966
- }
1329
+ //#region src/vrt/report-identity.ts
1330
+ /** Reserve one qualified namespace and compare legacy names on case-insensitive filesystems. */
1331
+ function legacyName(identity) {
1332
+ const basename = path.posix.basename(identity, ".art.vue");
1333
+ return /^[a-z0-9._-]{1,200}$/i.test(basename) && !/^art-[0-9a-f]{64}$/i.test(basename) ? `vrt-${basename}` : void 0;
1334
+ }
1335
+ /** The complete discovered Art set decides collisions, even for a single-Art request. */
1336
+ function resolveArtReportTarget(artPath, artPaths, projectRoot, reportDir) {
1337
+ const identities = Array.from(artPaths, (item) => resolveSnapshotIdentity(item, projectRoot));
1338
+ const identity = resolveSnapshotIdentity(artPath, projectRoot);
1339
+ if (!identities.includes(identity)) throw new Error(`Report Art not found: ${artPath}`);
1340
+ const candidates = identities.map(legacyName);
1341
+ const counts = /* @__PURE__ */ new Map();
1342
+ for (const name of candidates) if (name) counts.set(name.toLowerCase(), (counts.get(name.toLowerCase()) ?? 0) + 1);
1343
+ const names = identities.map((item, index) => {
1344
+ const candidate = candidates[index];
1345
+ const colliding = candidate && counts.get(candidate.toLowerCase()) > 1;
1346
+ return candidate && !colliding ? candidate : `vrt-art-${createHash("sha256").update(JSON.stringify([1, item])).digest("hex")}`;
1347
+ });
1348
+ if (new Set(names.map((name) => name.toLowerCase())).size !== names.length) throw new Error("Ambiguous VRT report identities");
1349
+ const base = names[identities.indexOf(identity)];
1350
+ return {
1351
+ identity,
1352
+ jsonReportPath: path.join(reportDir, `${base}-report.json`),
1353
+ htmlReportPath: path.join(reportDir, `${base}-report.html`)
1354
+ };
1967
1355
  }
1968
- /** POST /api/tokens (create) */
1969
- async function handleTokensCreate(ctx, readBody, sendJson, sendError) {
1970
- if (!ctx.tokensPath) {
1971
- sendError("No tokens path configured", 400);
1972
- return;
1973
- }
1974
- const body = await readBody();
1356
+ async function existsRegularFile(file) {
1975
1357
  try {
1976
- const { path: dotPath, token } = parseJsonBody(body);
1977
- if (!dotPath || !token || token.value === void 0) {
1978
- sendError("Missing required fields: path, token.value", 400);
1979
- return;
1980
- }
1981
- const absoluteTokensPath = resolveTokensPath(ctx);
1982
- const rawData = await readRawTokenFile(absoluteTokensPath);
1983
- const currentMap = buildTokenMap(await parseTokens(absoluteTokensPath));
1984
- if (currentMap[dotPath]) {
1985
- sendError(`Token already exists at path "${dotPath}"`, 409);
1986
- return;
1987
- }
1988
- if (token.$reference) {
1989
- const validation = validateSemanticReference(currentMap, token.$reference, dotPath);
1990
- if (!validation.valid) {
1991
- sendError(validation.error, 400);
1992
- return;
1993
- }
1994
- token.value = `{${token.$reference}}`;
1995
- token.$tier = "semantic";
1996
- }
1997
- setTokenAtPath(rawData, dotPath, token);
1998
- await writeRawTokenFile(absoluteTokensPath, rawData);
1999
- const categories = await parseTokens(absoluteTokensPath);
2000
- resolveReferences(categories, buildTokenMap(categories));
2001
- sendJson({
2002
- categories,
2003
- tokenMap: buildTokenMap(categories)
2004
- }, 201);
2005
- } catch (e) {
2006
- sendTokenMutationError(e, sendError);
1358
+ if (!(await lstat(file)).isFile()) throw new Error(`VRT report is not a regular file: ${file}`);
1359
+ return true;
1360
+ } catch (error) {
1361
+ if (error.code === "ENOENT") return false;
1362
+ throw error;
2007
1363
  }
2008
1364
  }
2009
- /** PUT /api/tokens (update) */
2010
- async function handleTokensUpdate(ctx, readBody, sendJson, sendError) {
2011
- if (!ctx.tokensPath) {
2012
- sendError("No tokens path configured", 400);
2013
- return;
2014
- }
2015
- const body = await readBody();
1365
+ /** Fail before capture or writes; legacy adoption requires every recorded result to have this owner. */
1366
+ async function assertArtReportOwnership(target, projectRoot) {
1367
+ const refusal = `Ambiguous VRT report ownership: ${target.jsonReportPath}. Archive or move the existing reports before retrying.`;
1368
+ const names = [path.basename(target.jsonReportPath), path.basename(target.htmlReportPath)];
1369
+ let existingNames;
2016
1370
  try {
2017
- const { path: dotPath, token } = parseJsonBody(body);
2018
- if (!dotPath || !token || token.value === void 0) {
2019
- sendError("Missing required fields: path, token.value", 400);
2020
- return;
2021
- }
2022
- const absoluteTokensPath = resolveTokensPath(ctx);
2023
- if (token.$reference) {
2024
- const validation = validateSemanticReference(buildTokenMap(await parseTokens(absoluteTokensPath)), token.$reference, dotPath);
2025
- if (!validation.valid) {
2026
- sendError(validation.error, 400);
2027
- return;
2028
- }
2029
- token.value = `{${token.$reference}}`;
2030
- token.$tier = "semantic";
2031
- }
2032
- const rawData = await readRawTokenFile(absoluteTokensPath);
2033
- setTokenAtPath(rawData, dotPath, token);
2034
- await writeRawTokenFile(absoluteTokensPath, rawData);
2035
- const categories = await parseTokens(absoluteTokensPath);
2036
- resolveReferences(categories, buildTokenMap(categories));
2037
- sendJson({
2038
- categories,
2039
- tokenMap: buildTokenMap(categories)
2040
- });
2041
- } catch (e) {
2042
- sendTokenMutationError(e, sendError);
2043
- }
2044
- }
2045
- /** DELETE /api/tokens */
2046
- async function handleTokensDelete(ctx, readBody, sendJson, sendError) {
2047
- if (!ctx.tokensPath) {
2048
- sendError("No tokens path configured", 400);
2049
- return;
1371
+ existingNames = await readdir(path.dirname(target.jsonReportPath));
1372
+ } catch (error) {
1373
+ if (error.code === "ENOENT") return;
1374
+ throw error;
2050
1375
  }
2051
- const body = await readBody();
1376
+ if (existingNames.some((item) => names.some((name) => item !== name && item.toLowerCase() === name.toLowerCase()))) throw new Error(refusal);
1377
+ const jsonExists = await existsRegularFile(target.jsonReportPath);
1378
+ const htmlExists = await existsRegularFile(target.htmlReportPath);
1379
+ if (!jsonExists && !htmlExists) return;
1380
+ if (!jsonExists) throw new Error(refusal);
2052
1381
  try {
2053
- const { path: dotPath } = parseJsonBody(body);
2054
- if (!dotPath) {
2055
- sendError("Missing required field: path", 400);
2056
- return;
2057
- }
2058
- const absoluteTokensPath = resolveTokensPath(ctx);
2059
- const dependents = findDependentTokens(buildTokenMap(await parseTokens(absoluteTokensPath)), dotPath);
2060
- const rawData = await readRawTokenFile(absoluteTokensPath);
2061
- if (!deleteTokenAtPath(rawData, dotPath)) {
2062
- sendError(`Token not found at path "${dotPath}"`, 404);
2063
- return;
2064
- }
2065
- await writeRawTokenFile(absoluteTokensPath, rawData);
2066
- const categories = await parseTokens(absoluteTokensPath);
2067
- resolveReferences(categories, buildTokenMap(categories));
2068
- sendJson({
2069
- categories,
2070
- tokenMap: buildTokenMap(categories),
2071
- dependentsWarning: dependents.length > 0 ? dependents : void 0
2072
- });
2073
- } catch (e) {
2074
- sendTokenMutationError(e, sendError);
2075
- }
2076
- }
2077
- //#endregion
2078
- //#region src/script-component-analysis.ts
2079
- /** Read a script component's runtime options without executing project code. */
2080
- function scriptKind(filename) {
2081
- if (filename.endsWith(".tsx")) return ts.ScriptKind.TSX;
2082
- if (filename.endsWith(".jsx")) return ts.ScriptKind.JSX;
2083
- if (filename.endsWith(".js")) return ts.ScriptKind.JS;
2084
- return ts.ScriptKind.TS;
2085
- }
2086
- function unwrap(expression) {
2087
- while (ts.isParenthesizedExpression(expression) || ts.isAsExpression(expression) || ts.isSatisfiesExpression(expression) || ts.isNonNullExpression(expression)) expression = expression.expression;
2088
- return expression;
2089
- }
2090
- function nameOf(name) {
2091
- if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) return name.text;
2092
- if (ts.isComputedPropertyName(name) && ts.isStringLiteral(name.expression)) return name.expression.text;
2093
- }
2094
- function variable(sourceFile, name) {
2095
- for (const statement of sourceFile.statements) {
2096
- if (!ts.isVariableStatement(statement)) continue;
2097
- for (const declaration of statement.declarationList.declarations) if (ts.isIdentifier(declaration.name) && declaration.name.text === name) return declaration.initializer;
2098
- }
2099
- }
2100
- function resolved(expression, sourceFile) {
2101
- expression = unwrap(expression);
2102
- if (ts.isIdentifier(expression)) {
2103
- const initializer = variable(sourceFile, expression.text);
2104
- if (initializer) return unwrap(initializer);
2105
- }
2106
- return expression;
2107
- }
2108
- function option(object, name, sourceFile) {
2109
- for (const property of object.properties) {
2110
- if (ts.isPropertyAssignment(property) && nameOf(property.name) === name) return resolved(property.initializer, sourceFile);
2111
- if (ts.isShorthandPropertyAssignment(property) && property.name.text === name) {
2112
- const initializer = variable(sourceFile, name);
2113
- if (initializer) return resolved(initializer, sourceFile);
1382
+ const report = JSON.parse(await readFile(target.jsonReportPath, "utf8"));
1383
+ if (!report || typeof report !== "object" || Array.isArray(report)) throw new Error(refusal);
1384
+ if (Object.hasOwn(report, "reportOwner")) {
1385
+ const owner = report.reportOwner;
1386
+ if (!owner || typeof owner !== "object" || owner.version !== 1 || owner.artIdentity !== target.identity) throw new Error(refusal);
1387
+ } else {
1388
+ const results = report.results;
1389
+ if (!Array.isArray(results) || !results.length || results.some((item) => !item || typeof item !== "object" || typeof item.artPath !== "string" || resolveSnapshotIdentity(item.artPath, projectRoot) !== target.identity)) throw new Error(refusal);
2114
1390
  }
1391
+ } catch {
1392
+ throw new Error(refusal);
2115
1393
  }
2116
1394
  }
2117
- function componentOptions(sourceFile) {
2118
- const assignment = sourceFile.statements.find((statement) => ts.isExportAssignment(statement));
2119
- if (!assignment || assignment.isExportEquals) return void 0;
2120
- let expression = resolved(assignment.expression, sourceFile);
2121
- if (ts.isCallExpression(expression)) {
2122
- const callee = expression.expression;
2123
- if (!(ts.isIdentifier(callee) && callee.text === "defineComponent" || ts.isPropertyAccessExpression(callee) && callee.name.text === "defineComponent") || !expression.arguments[0]) return void 0;
2124
- expression = resolved(expression.arguments[0], sourceFile);
2125
- }
2126
- return ts.isObjectLiteralExpression(expression) ? expression : void 0;
2127
- }
2128
- function literal(expression) {
2129
- expression = unwrap(expression);
2130
- if (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression)) return expression.text;
2131
- if (ts.isNumericLiteral(expression)) return Number(expression.text);
2132
- if (expression.kind === ts.SyntaxKind.TrueKeyword) return true;
2133
- if (expression.kind === ts.SyntaxKind.FalseKeyword) return false;
2134
- if (expression.kind === ts.SyntaxKind.NullKeyword) return null;
2135
- if (ts.isPrefixUnaryExpression(expression) && ts.isNumericLiteral(expression.operand)) {
2136
- const value = Number(expression.operand.text);
2137
- if (expression.operator === ts.SyntaxKind.MinusToken) return -value;
2138
- if (expression.operator === ts.SyntaxKind.PlusToken) return value;
2139
- }
2140
- }
2141
- function propType(expression) {
2142
- if (!expression) return "unknown";
2143
- expression = unwrap(expression);
2144
- if (ts.isArrayLiteralExpression(expression)) return expression.elements.map((element) => propType(element)).join(" | ") || "unknown";
2145
- switch (ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : void 0) {
2146
- case "String": return "string";
2147
- case "Number": return "number";
2148
- case "Boolean": return "boolean";
2149
- case "Array": return "unknown[]";
2150
- case "Object": return "Record<string, unknown>";
2151
- default: return "unknown";
2152
- }
2153
- }
2154
- function analyzeProps(expression, sourceFile) {
2155
- if (!expression) return [];
2156
- if (ts.isArrayLiteralExpression(expression)) return expression.elements.flatMap((element) => ts.isStringLiteral(element) ? [{
2157
- name: element.text,
2158
- type: "unknown",
2159
- required: false
2160
- }] : []);
2161
- if (!ts.isObjectLiteralExpression(expression)) return [];
2162
- const props = [];
2163
- for (const property of expression.properties) {
2164
- if (!ts.isPropertyAssignment(property)) continue;
2165
- const name = nameOf(property.name);
2166
- if (!name) continue;
2167
- const value = resolved(property.initializer, sourceFile);
2168
- if (ts.isObjectLiteralExpression(value)) {
2169
- const type = propType(option(value, "type", sourceFile));
2170
- const required = option(value, "required", sourceFile)?.kind === ts.SyntaxKind.TrueKeyword;
2171
- const defaultExpression = option(value, "default", sourceFile);
2172
- const defaultValue = defaultExpression ? literal(defaultExpression) : void 0;
2173
- props.push({
2174
- name,
2175
- type,
2176
- required,
2177
- ...defaultValue !== void 0 ? { default_value: defaultValue } : {}
2178
- });
2179
- } else props.push({
2180
- name,
2181
- type: propType(value),
2182
- required: false
2183
- });
2184
- }
2185
- return props;
2186
- }
2187
- function analyzeEmits(expression) {
2188
- if (!expression) return [];
2189
- if (ts.isArrayLiteralExpression(expression)) return expression.elements.flatMap((element) => ts.isStringLiteral(element) ? [element.text] : []);
2190
- if (ts.isObjectLiteralExpression(expression)) return expression.properties.flatMap((property) => (ts.isPropertyAssignment(property) || ts.isMethodDeclaration(property)) && nameOf(property.name) ? [nameOf(property.name)] : []);
2191
- return [];
2192
- }
2193
- function analyzeScriptComponent(source, filename) {
2194
- const sourceFile = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, scriptKind(filename));
2195
- const options = componentOptions(sourceFile);
2196
- if (!options) return {
2197
- props: [],
2198
- emits: []
2199
- };
2200
- return {
2201
- props: analyzeProps(option(options, "props", sourceFile), sourceFile),
2202
- emits: analyzeEmits(option(options, "emits", sourceFile))
2203
- };
2204
- }
2205
- //#endregion
2206
- //#region src/api-routes/handler-palette.ts
2207
- /**
2208
- * Palette handler for the Musea gallery API.
2209
- *
2210
- * Handles GET /api/arts/:path/palette endpoint.
2211
- */
2212
- /** GET /api/arts/:path/palette */
2213
- async function handleArtPalette(ctx, match, sendJson, sendError) {
2214
- const artPath = decodeUrlComponent(match[1], "art path");
2215
- const art = ctx.artFiles.get(artPath);
2216
- if (!art) {
2217
- sendError("Art not found", 404);
2218
- return;
2219
- }
2220
- try {
2221
- const readableArtPath = resolveReadableArtPath(ctx.config.root, ctx.scanRoots, artPath);
2222
- const source = await fs.promises.readFile(readableArtPath, "utf-8");
2223
- const binding = loadNative();
2224
- let palette;
2225
- if (binding.generateArtPalette) palette = binding.generateArtPalette(source, { filename: readableArtPath });
2226
- else palette = {
2227
- title: art.metadata.title,
2228
- controls: [],
2229
- groups: [],
2230
- json: "{}",
2231
- typescript: ""
2232
- };
2233
- const resolvedComponentPath = resolveComponentSourcePath(art, artPath, allowedSourceRoots(ctx.config.root, ctx.scanRoots));
2234
- if (!resolvedComponentPath) {
2235
- sendJson(palette);
2236
- return;
2237
- }
2238
- try {
2239
- const componentSource = await fs.promises.readFile(resolvedComponentPath, "utf-8");
2240
- const analysis = isVueSourcePath(resolvedComponentPath) ? binding.analyzeSfc ? binding.analyzeSfc(componentSource, { filename: resolvedComponentPath }) : analyzeSfcFallback(componentSource, { filename: resolvedComponentPath }) : analyzeScriptComponent(componentSource, resolvedComponentPath);
2241
- if (analysis.props.length > 0) mergeSfcPropsIntoPalette(palette, analysis.props);
2242
- } catch {}
2243
- sendJson(palette);
2244
- } catch (e) {
2245
- if (e instanceof HttpError) {
2246
- sendError(e.message, e.status);
2247
- return;
1395
+ /** Keep ownership portable when a report directory moves to another machine. */
1396
+ function attachArtReportOwner(json, target) {
1397
+ return JSON.stringify({
1398
+ ...JSON.parse(json),
1399
+ reportOwner: {
1400
+ version: 1,
1401
+ artIdentity: target.identity
2248
1402
  }
2249
- sendError(e instanceof Error ? e.message : String(e));
2250
- }
2251
- }
2252
- function mergeSfcPropsIntoPalette(palette, props) {
2253
- const controlsByName = /* @__PURE__ */ new Map();
2254
- for (const control of palette.controls) controlsByName.set(normalizePropName(control.name), control);
2255
- for (const prop of props) {
2256
- const control = controlsByName.get(normalizePropName(prop.name));
2257
- if (control) applyPropMetadata(control, prop);
2258
- else palette.controls.push(controlFromProp(prop));
2259
- }
2260
- palette.json = JSON.stringify({
2261
- title: palette.title,
2262
- controls: palette.controls
2263
1403
  }, null, 2);
2264
- palette.typescript = generateTypescript(palette);
2265
- }
2266
- function applyPropMetadata(control, prop) {
2267
- const inferred = inferControl(prop.type);
2268
- control.name = prop.name;
2269
- control.required = prop.required;
2270
- if (control.default_value === void 0 && prop.default_value !== void 0) control.default_value = parseDefault(prop.default_value);
2271
- if (inferred.control !== "text" || control.control === "text") control.control = inferred.control;
2272
- if (inferred.options.length > 0) control.options = inferred.options;
2273
- }
2274
- function controlFromProp(prop) {
2275
- const inferred = inferControl(prop.type);
2276
- return {
2277
- name: prop.name,
2278
- control: inferred.control,
2279
- default_value: prop.default_value === void 0 ? void 0 : parseDefault(prop.default_value),
2280
- description: void 0,
2281
- required: prop.required,
2282
- options: inferred.options,
2283
- range: void 0,
2284
- group: void 0
2285
- };
2286
- }
2287
- function inferControl(type) {
2288
- const normalized = type.trim();
2289
- const options = literalOptions(normalized);
2290
- if (options.length > 0) return {
2291
- control: "select",
2292
- options
2293
- };
2294
- if (normalized === "boolean") return {
2295
- control: "boolean",
2296
- options: []
2297
- };
2298
- if (normalized === "number") return {
2299
- control: "number",
2300
- options: []
2301
- };
2302
- if (normalized.includes("[]") || normalized.startsWith("Array<")) return {
2303
- control: "array",
2304
- options: []
2305
- };
2306
- if (normalized.startsWith("{") || normalized.startsWith("Record<")) return {
2307
- control: "object",
2308
- options: []
2309
- };
2310
- return {
2311
- control: "text",
2312
- options: []
2313
- };
2314
- }
2315
- function literalOptions(type) {
2316
- if (!type.includes("|") || type.includes("=>")) return [];
2317
- return type.split("|").map((part) => part.trim()).map((part) => {
2318
- const stringMatch = part.match(/^["']([^"']+)["']$/);
2319
- if (stringMatch) return stringMatch[1];
2320
- if (part === "true") return true;
2321
- if (part === "false") return false;
2322
- const numberValue = Number(part);
2323
- return Number.isFinite(numberValue) ? numberValue : void 0;
2324
- }).filter((value) => value !== void 0).map((value) => ({
2325
- label: String(value),
2326
- value
2327
- }));
2328
- }
2329
- function parseDefault(value) {
2330
- if (typeof value !== "string") return value;
2331
- if (value === "true") return true;
2332
- if (value === "false") return false;
2333
- if (/^-?\d+(?:\.\d+)?$/.test(value)) return Number(value);
2334
- return value.replace(/^["']|["']$/g, "");
2335
- }
2336
- function normalizePropName(name) {
2337
- return name.replace(/[-_]/g, "").toLowerCase();
2338
- }
2339
- function generateTypescript(palette) {
2340
- const fields = palette.controls.map((control) => ` ${control.name}${control.required ? "" : "?"}: ${controlTsType(control)};`).join("\n");
2341
- return `export interface ${pascalCase(palette.title)}Props {\n${fields}\n}\n`;
2342
- }
2343
- function controlTsType(control) {
2344
- if (control.control === "boolean") return "boolean";
2345
- if (control.control === "number" || control.control === "range") return "number";
2346
- if (control.control === "array") return "unknown[]";
2347
- if (control.control === "object") return "Record<string, unknown>";
2348
- if (control.control === "select" && control.options.length > 0) return control.options.map((option) => JSON.stringify(option.value)).join(" | ");
2349
- return "string";
2350
- }
2351
- function pascalCase(value) {
2352
- return value.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
2353
1404
  }
2354
1405
  //#endregion
2355
- //#region src/api-routes/handlers.ts
2356
- /**
2357
- * Individual route handler functions for the Musea gallery API.
2358
- *
2359
- * Extracted from api-routes.ts to keep file sizes manageable.
2360
- * These handle GET /api/arts/:path/... sub-routes.
2361
- */
2362
- function sendCaughtError(sendError, error) {
2363
- if (error instanceof HttpError) {
2364
- sendError(error.message, error.status);
2365
- return;
2366
- }
2367
- sendError(error instanceof Error ? error.message : String(error));
2368
- }
2369
- /** GET /api/arts/:path/source */
2370
- async function handleArtSource(ctx, match, sendJson, sendError) {
2371
- const artPath = decodeUrlComponent(match[1], "art path");
2372
- if (!ctx.artFiles.get(artPath)) {
2373
- sendError("Art not found", 404);
2374
- return;
2375
- }
2376
- try {
2377
- const readableArtPath = resolveReadableArtPath(ctx.config.root, ctx.scanRoots, artPath);
2378
- sendJson({
2379
- source: await fs.promises.readFile(readableArtPath, "utf-8"),
2380
- path: artPath
2381
- });
2382
- } catch (e) {
2383
- sendCaughtError(sendError, e);
2384
- }
2385
- }
2386
- /** GET /api/arts/:path/analysis */
2387
- async function handleArtAnalysis(ctx, match, sendJson, sendError) {
2388
- const artPath = decodeUrlComponent(match[1], "art path");
2389
- const art = ctx.artFiles.get(artPath);
2390
- if (!art) {
2391
- sendError("Art not found", 404);
2392
- return;
2393
- }
2394
- try {
2395
- const resolvedComponentPath = resolveComponentSourcePath(art, artPath, allowedSourceRoots(ctx.config.root, ctx.scanRoots));
2396
- if (resolvedComponentPath) {
2397
- const source = await fs.promises.readFile(resolvedComponentPath, "utf-8");
2398
- if (isVueSourcePath(resolvedComponentPath)) {
2399
- const binding = loadNative();
2400
- sendJson(binding.analyzeSfc ? binding.analyzeSfc(source, { filename: resolvedComponentPath }) : analyzeSfcFallback(source, { filename: resolvedComponentPath }));
2401
- } else sendJson(analyzeScriptComponent(source, resolvedComponentPath));
2402
- } else sendJson({
2403
- props: [],
2404
- emits: []
2405
- });
2406
- } catch (e) {
2407
- sendCaughtError(sendError, e);
2408
- }
2409
- }
2410
- /** GET /api/arts/:path/docs */
2411
- async function handleArtDocs(ctx, match, sendJson, sendError) {
2412
- const artPath = decodeUrlComponent(match[1], "art path");
2413
- const art = ctx.artFiles.get(artPath);
2414
- if (!art) {
2415
- sendError("Art not found", 404);
2416
- return;
2417
- }
2418
- try {
2419
- const readableArtPath = resolveReadableArtPath(ctx.config.root, ctx.scanRoots, artPath);
2420
- const source = await fs.promises.readFile(readableArtPath, "utf-8");
2421
- const binding = loadNative();
2422
- if (binding.generateArtDoc) {
2423
- const doc = binding.generateArtDoc(source, { filename: readableArtPath });
2424
- let markdown = doc.markdown || "";
2425
- const componentName = art.metadata.title || "Component";
2426
- markdown = markdown.replace(/<Self(\s|>|\/)/g, `<${componentName}$1`).replace(/<\/Self>/g, `</${componentName}>`);
2427
- markdown = markdown.replace(/```(\w*)\n([\s\S]*?)```/g, (_match, lang, code) => {
2428
- const lines = code.split("\n");
2429
- let minIndent = Infinity;
2430
- for (const line of lines) if (line.trim()) {
2431
- const indent = line.match(/^(\s*)/)?.[1].length || 0;
2432
- minIndent = Math.min(minIndent, indent);
2433
- }
2434
- if (minIndent === Infinity) minIndent = 0;
2435
- let formatted;
2436
- if (minIndent > 0) formatted = lines.map((line) => line.slice(minIndent)).join("\n");
2437
- else {
2438
- let restIndent = Infinity;
2439
- for (let i = 1; i < lines.length; i++) if (lines[i].trim()) {
2440
- const indent = lines[i].match(/^(\s*)/)?.[1].length || 0;
2441
- restIndent = Math.min(restIndent, indent);
2442
- }
2443
- if (restIndent === Infinity || restIndent === 0) formatted = lines.join("\n");
2444
- else formatted = lines.map((line, i) => i === 0 ? line : line.slice(restIndent)).join("\n");
2445
- }
2446
- return "```" + lang + "\n" + formatted + "```";
2447
- });
2448
- sendJson({
2449
- ...doc,
2450
- markdown
2451
- });
2452
- } else sendJson({
2453
- markdown: "",
2454
- title: art.metadata.title,
2455
- variant_count: art.variants.length
2456
- });
2457
- } catch (e) {
2458
- sendCaughtError(sendError, e);
2459
- }
2460
- }
2461
- /** GET /api/arts/:path/variants/:name/a11y */
2462
- //#endregion
2463
1406
  //#region src/api-routes/post-handlers.ts
2464
1407
  /** POST /api/preview-with-props */
2465
1408
  function handlePreviewWithProps(ctx, body, res, sendJson, sendError) {
@@ -2520,10 +1463,25 @@ async function handleGenerate(ctx, body, sendJson, sendError) {
2520
1463
  async function handleRunVrt(ctx, body, sendJson, sendError) {
2521
1464
  try {
2522
1465
  const { artPath, updateSnapshots } = parseJsonBody(body);
1466
+ if (artPath !== void 0 && typeof artPath !== "string") throw new HttpError("artPath must be a string", 400);
1467
+ if (artPath !== void 0 && !ctx.artFiles.has(artPath)) throw new HttpError("Art not found", 404);
2523
1468
  const { MuseaVrtRunner, generateVrtJsonReport, generateVrtReport } = await import("./vrt.mjs");
2524
- const snapshotDir = path.resolve(ctx.config.root, ".vize/snapshots");
1469
+ const { a11y: _a11y, ...configured } = ctx.vrt ?? {};
1470
+ const snapshotDir = path.resolve(ctx.config.root, configured.snapshotDir ?? ".vize/snapshots");
2525
1471
  const reportDir = path.resolve(ctx.config.root, ".vize/reports");
2526
- const runner = new MuseaVrtRunner({ snapshotDir });
1472
+ const projectRoot = ctx.projectRoot ?? ctx.config.root;
1473
+ const reportTarget = artPath === void 0 ? void 0 : resolveArtReportTarget(artPath, ctx.artFiles.keys(), projectRoot, reportDir);
1474
+ if (reportTarget) await assertArtReportOwnership(reportTarget, projectRoot);
1475
+ const runner = new MuseaVrtRunner({
1476
+ ...configured,
1477
+ capture: {
1478
+ ...configured.capture,
1479
+ waitForPreviewReady: true
1480
+ },
1481
+ snapshotDir,
1482
+ projectRoot,
1483
+ previewBasePath: publicBasePathFromViteBase(ctx.config.base, ctx.basePath)
1484
+ });
2527
1485
  const baseUrl = `http://localhost:${ctx.getDevServerPort()}`;
2528
1486
  let artsToTest = Array.from(ctx.artFiles.values());
2529
1487
  if (artPath) artsToTest = artsToTest.filter((a) => a.path === artPath);
@@ -2539,11 +1497,11 @@ async function handleRunVrt(ctx, body, sendJson, sendError) {
2539
1497
  await runner.stop();
2540
1498
  }
2541
1499
  })();
2542
- const reportBaseName = typeof artPath === "string" ? `vrt-${path.basename(artPath, ".art.vue")}` : "vrt";
2543
- const jsonReportPath = path.join(reportDir, `${reportBaseName}-report.json`);
2544
- const htmlReportPath = path.join(reportDir, `${reportBaseName}-report.html`);
1500
+ const jsonReportPath = reportTarget?.jsonReportPath ?? path.join(reportDir, "vrt-report.json");
1501
+ const htmlReportPath = reportTarget?.htmlReportPath ?? path.join(reportDir, "vrt-report.html");
1502
+ const jsonReport = generateVrtJsonReport(results, summary);
2545
1503
  await fs.promises.mkdir(reportDir, { recursive: true });
2546
- await fs.promises.writeFile(jsonReportPath, generateVrtJsonReport(results, summary), "utf-8");
1504
+ await fs.promises.writeFile(jsonReportPath, reportTarget ? attachArtReportOwner(jsonReport, reportTarget) : jsonReport, "utf-8");
2547
1505
  await fs.promises.writeFile(htmlReportPath, generateVrtReport(results, summary), "utf-8");
2548
1506
  sendJson({
2549
1507
  success: true,
@@ -3065,129 +2023,6 @@ function relativePath(root, filePath) {
3065
2023
  return path.relative(root, filePath).split(path.sep).join("/");
3066
2024
  }
3067
2025
  //#endregion
3068
- //#region src/static-data.ts
3069
- function staticPreviewId(artPath, variantName) {
3070
- return crypto.createHash("sha256").update(artPath).update("\0").update(variantName).digest("hex").slice(0, 20);
3071
- }
3072
- function joinUrlPath(basePath, ...segments) {
3073
- return `${basePath === "/" ? "" : basePath.replace(/\/+$/, "")}/${segments.map((segment) => segment.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/")}`;
3074
- }
3075
- async function createStaticGalleryPayload(ctx) {
3076
- const apiCtx = createApiContext(ctx);
3077
- const arts = sortedArts(ctx.artFiles.values());
3078
- const previews = {};
3079
- const details = {};
3080
- for (const art of arts) {
3081
- previews[art.path] = {};
3082
- for (const variant of art.variants) {
3083
- const id = staticPreviewId(art.path, variant.name);
3084
- previews[art.path][variant.name] = joinUrlPath(ctx.basePath, "preview", `${id}.html`);
3085
- }
3086
- details[art.path] = {
3087
- source: await captureJson((sendJson, sendError) => {
3088
- return handleArtSource(apiCtx, artMatch(art.path), sendJson, sendError);
3089
- }, {
3090
- source: "",
3091
- path: art.path
3092
- }),
3093
- palette: await captureJson((sendJson, sendError) => {
3094
- return handleArtPalette(apiCtx, artMatch(art.path), sendJson, sendError);
3095
- }, emptyPalette(art)),
3096
- analysis: await captureJson((sendJson, sendError) => {
3097
- return handleArtAnalysis(apiCtx, artMatch(art.path), sendJson, sendError);
3098
- }, {
3099
- props: [],
3100
- emits: []
3101
- }),
3102
- docs: await captureJson((sendJson, sendError) => {
3103
- return handleArtDocs(apiCtx, artMatch(art.path), sendJson, sendError);
3104
- }, emptyDocs(art))
3105
- };
3106
- }
3107
- return {
3108
- arts,
3109
- previews,
3110
- details,
3111
- tokens: await captureJson((sendJson) => handleTokensGet(apiCtx, sendJson), emptyTokens()),
3112
- tokenUsage: await captureJson((sendJson) => handleTokensUsage(apiCtx, sendJson), {})
3113
- };
3114
- }
3115
- function createApiContext(ctx) {
3116
- return {
3117
- config: ctx.config,
3118
- artFiles: ctx.artFiles,
3119
- scanRoots: ctx.scanRoots,
3120
- tokensPath: ctx.tokensPath,
3121
- projectRoot: ctx.projectRoot,
3122
- basePath: ctx.basePath,
3123
- resolvedPreviewCss: ctx.resolvedPreviewCss,
3124
- resolvedPreviewSetup: ctx.resolvedPreviewSetup,
3125
- devSessionToken: ctx.devSessionToken,
3126
- processArtFile: async (filePath) => {
3127
- await fs.promises.access(filePath);
3128
- },
3129
- getDevServerPort: () => 5173
3130
- };
3131
- }
3132
- async function captureJson(run, fallback) {
3133
- let captured = fallback;
3134
- const sendJson = (data) => {
3135
- captured = data;
3136
- };
3137
- const sendError = (message, status = 500) => {
3138
- captured = {
3139
- error: message,
3140
- status
3141
- };
3142
- };
3143
- await run(sendJson, sendError);
3144
- return captured;
3145
- }
3146
- function artMatch(artPath) {
3147
- return ["", encodeURIComponent(artPath)];
3148
- }
3149
- function emptyPalette(art) {
3150
- return {
3151
- title: art.metadata.title,
3152
- controls: [],
3153
- groups: [],
3154
- json: "{}",
3155
- typescript: ""
3156
- };
3157
- }
3158
- function emptyDocs(art) {
3159
- return {
3160
- markdown: "",
3161
- title: art.metadata.title,
3162
- variant_count: art.variants.length
3163
- };
3164
- }
3165
- function emptyTokens() {
3166
- return {
3167
- categories: [],
3168
- tokenMap: {},
3169
- meta: {
3170
- filePath: "",
3171
- tokenCount: 0,
3172
- primitiveCount: 0,
3173
- semanticCount: 0
3174
- }
3175
- };
3176
- }
3177
- //#endregion
3178
- //#region src/static-base.ts
3179
- const TEXT_GALLERY_ASSET_EXT = /\.(?:css|html|js|map|mjs)$/u;
3180
- function rewriteGalleryBase(source, basePath) {
3181
- return source.replaceAll("/__musea__/", `${basePath.replace(/\/?$/, "/")}`);
3182
- }
3183
- function rewriteGalleryTextAssetBase(source, relativePath, basePath) {
3184
- if (!TEXT_GALLERY_ASSET_EXT.test(relativePath)) return source;
3185
- return rewriteGalleryBase(Buffer.from(source).toString("utf-8"), basePath);
3186
- }
3187
- function publicBasePathFromViteBase(viteBase, basePath) {
3188
- return viteBase && viteBase !== "/" && viteBase !== "./" ? joinUrlPath(viteBase, basePath) : basePath;
3189
- }
3190
- //#endregion
3191
2026
  //#region src/static-gallery-shell.ts
3192
2027
  const moduleDir = path.dirname(fileURLToPath(import.meta.url));
3193
2028
  function joinFileName(...parts) {
@@ -3571,6 +2406,7 @@ function musea(options = {}) {
3571
2406
  },
3572
2407
  configureServer(devServer) {
3573
2408
  server = devServer;
2409
+ devServer.watcher.unwatch(path.resolve(config.root, ".vize/reports"));
3574
2410
  registerMiddleware(devServer, {
3575
2411
  basePath,
3576
2412
  devSessionToken,
@@ -3592,6 +2428,7 @@ function musea(options = {}) {
3592
2428
  resolvedPreviewCss,
3593
2429
  resolvedPreviewSetup,
3594
2430
  toolbar,
2431
+ vrt: options.vrt,
3595
2432
  devSessionToken,
3596
2433
  processArtFile,
3597
2434
  getDevServerPort: () => devServer.config.server.port || 5173