@vizejs/vite-plugin-musea 0.441.0 → 0.443.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.
- package/dist/a11y/index.d.mts +1 -1
- package/dist/a11y/index.mjs +1 -1
- package/dist/{a11y-BbFK942j.mjs → a11y-DuFu75hl.mjs} +7 -6
- package/dist/a11y-DuFu75hl.mjs.map +1 -0
- package/dist/cli/index.d.mts +7 -1
- package/dist/cli/index.d.mts.map +1 -1
- package/dist/cli/index.mjs +111 -10
- package/dist/cli/index.mjs.map +1 -1
- package/dist/gallery/assets/MonacoEditor-CmjDtbrI.js +2 -0
- package/dist/gallery/assets/MonacoEditor-DxzpSKbC.css +1 -0
- package/dist/gallery/assets/{cssMode-D6nK_kDe.js → cssMode-B16oWKdO.js} +1 -1
- package/dist/gallery/assets/{editor.api-Bs4-VZ3V.js → editor.api-CfYscGcC.js} +1 -1
- package/dist/gallery/assets/{freemarker2-rDjl8685.js → freemarker2-Bsla50n3.js} +1 -1
- package/dist/gallery/assets/{handlebars-OkqFmHQQ.js → handlebars-CS_Y5cXs.js} +1 -1
- package/dist/gallery/assets/{html-Bq6Ai15v.js → html-DagAGhpS.js} +1 -1
- package/dist/gallery/assets/{htmlMode-H8XqFg_c.js → htmlMode-CiuL2Y-P.js} +1 -1
- package/dist/gallery/assets/index-BaRljRmN.css +1 -0
- package/dist/gallery/assets/{index-V774j4nI.js → index-Bma1gCA8.js} +6 -6
- package/dist/gallery/assets/{javascript-DY3JGgzg.js → javascript-BQYQMq9R.js} +1 -1
- package/dist/gallery/assets/{jsonMode-CYaDarn3.js → jsonMode-C5lyVqru.js} +1 -1
- package/dist/gallery/assets/{liquid-DSwk2doy.js → liquid-qbEuwx0o.js} +1 -1
- package/dist/gallery/assets/{lspLanguageFeatures-CThGg67f.js → lspLanguageFeatures-Dqts9s1L.js} +1 -1
- package/dist/gallery/assets/{mdx-B9XzBagU.js → mdx-DN6uw21R.js} +1 -1
- package/dist/gallery/assets/{python-sRU_mC7d.js → python-Cbp5CGeG.js} +1 -1
- package/dist/gallery/assets/{razor-CUHkZDIN.js → razor-BXu36P7p.js} +1 -1
- package/dist/gallery/assets/{register-BRx-S1So.js → register-vvpXemvQ.js} +2 -2
- package/dist/gallery/assets/{toggleHighContrast-tYUHUcTT.js → toggleHighContrast-9EQLxoB9.js} +1 -1
- package/dist/gallery/assets/{tsMode-C0mNxmwK.js → tsMode-DakVvyMV.js} +1 -1
- package/dist/gallery/assets/{typescript-Ba_YUPxA.js → typescript-DEY4mnQU.js} +1 -1
- package/dist/gallery/assets/{vs-omjQMPuv.js → vs-Cd8KAJDG.js} +3 -3
- package/dist/gallery/assets/{workers-BOTkt7rp.js → workers-GvANOwSC.js} +1 -1
- package/dist/gallery/assets/{xml-CGK9gfdX.js → xml-cZMAcMEr.js} +1 -1
- package/dist/gallery/assets/{yaml-CA-jHXc3.js → yaml-CReFeuuC.js} +1 -1
- package/dist/gallery/index.html +2 -2
- package/dist/{gallery-CLe_4-XW.mjs → gallery-LgVvVp28.mjs} +2 -2
- package/dist/{gallery-CLe_4-XW.mjs.map → gallery-LgVvVp28.mjs.map} +1 -1
- package/dist/{index-GkKsNzkf.d.mts → index-BU4-FGUC.d.mts} +3 -4
- package/dist/index-BU4-FGUC.d.mts.map +1 -0
- package/dist/{index-CtvsGVFJ.d.mts → index-ZFHsOEPD.d.mts} +6 -1
- package/dist/{index-CtvsGVFJ.d.mts.map → index-ZFHsOEPD.d.mts.map} +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +153 -1592
- package/dist/index.mjs.map +1 -1
- package/dist/options-DnKPMMPV.mjs +2159 -0
- package/dist/options-DnKPMMPV.mjs.map +1 -0
- package/dist/{template-BgBSA10_.mjs → template-CpNUvZPp.mjs} +5 -3
- package/dist/template-CpNUvZPp.mjs.map +1 -0
- package/dist/{utils-DeMLVlNS.mjs → utils-BloA9YP9.mjs} +35 -29
- package/dist/utils-BloA9YP9.mjs.map +1 -0
- package/dist/utils-ChmPv0qc.mjs +55 -0
- package/dist/utils-ChmPv0qc.mjs.map +1 -0
- package/dist/{vrt-DNNAFYv1.d.mts → vrt-DtcnqPhF.d.mts} +22 -3
- package/dist/vrt-DtcnqPhF.d.mts.map +1 -0
- package/dist/{vrt-VuGK9wTX.mjs → vrt-PuxpRuHa.mjs} +392 -97
- package/dist/vrt-PuxpRuHa.mjs.map +1 -0
- package/dist/vrt.d.mts +1 -1
- package/dist/vrt.mjs +1 -1
- package/package.json +4 -4
- package/dist/a11y-BbFK942j.mjs.map +0 -1
- package/dist/gallery/assets/MonacoEditor-B2gyQ5TW.js +0 -2
- package/dist/gallery/assets/MonacoEditor-Db3Q217Z.css +0 -1
- package/dist/gallery/assets/index-DTMv-5r0.css +0 -1
- package/dist/index-GkKsNzkf.d.mts.map +0 -1
- package/dist/options-Bjo4e_75.mjs +0 -582
- package/dist/options-Bjo4e_75.mjs.map +0 -1
- package/dist/template-BgBSA10_.mjs.map +0 -1
- package/dist/utils-DeMLVlNS.mjs.map +0 -1
- package/dist/vrt-DNNAFYv1.d.mts.map +0 -1
- 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,
|
|
2
|
-
import { a as
|
|
3
|
-
import { a as generateGalleryGlobalsScript, i as generateDevGlobalsScript, n as generateGalleryScript, r as generateGalleryModule, t as generateGalleryBody } from "./template-
|
|
4
|
-
import { i as MuseaVrtRunner, n as generateVrtJsonReport, r as generateVrtReport } from "./vrt-
|
|
5
|
-
import { t as MuseaA11yRunner } from "./a11y-
|
|
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, t as escapeHtml, u as collectRequestBody, v as decodeUrlComponent, w as HttpError } from "./utils-BloA9YP9.mjs";
|
|
2
|
+
import { A as rewriteRelativeImportStatement, C as buildTokenMap, D as sortedArts, E as parseTokens, M as resolveArtComponent, N as variantComponentNames, O as generateArtModule, S as processStyleDictionary, T as scanTokenUsage, _ as handleTokensUpdate, a as rewriteGalleryBase, b as generateTokensHtml, c as joinUrlPath, d as handleArtDocs, f as handleArtSource, g as handleTokensGet, h as handleTokensDelete, i as publicBasePathFromViteBase, j as expandSelfTag, k as parseScriptSetupForArt, 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 resolveReferences, x as generateTokensMarkdown, y as resolveTokenPreview } from "./options-DnKPMMPV.mjs";
|
|
3
|
+
import { a as generateGalleryGlobalsScript, i as generateDevGlobalsScript, n as generateGalleryScript, r as generateGalleryModule, t as generateGalleryBody } from "./template-CpNUvZPp.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-DuFu75hl.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
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
11
|
import { fileURLToPath } from "node:url";
|
|
12
|
-
import
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
|
@@ -818,6 +812,34 @@ mount();
|
|
|
818
812
|
`;
|
|
819
813
|
}
|
|
820
814
|
//#endregion
|
|
815
|
+
//#region src/preview-module-id.ts
|
|
816
|
+
/** Keep the final colon delimiter unambiguous while retaining ordinary module IDs. */
|
|
817
|
+
function previewModuleId(artPath, variantName) {
|
|
818
|
+
return `virtual:musea-preview:${artPath}:${variantName.replaceAll("%", "%25").replaceAll(":", "%3A")}`;
|
|
819
|
+
}
|
|
820
|
+
//#endregion
|
|
821
|
+
//#region src/middleware-response.ts
|
|
822
|
+
/** Both transformed and fallback previews keep the same response contract. */
|
|
823
|
+
function sendPreviewModule(response, code) {
|
|
824
|
+
response.setHeader("Content-Type", "application/javascript");
|
|
825
|
+
response.setHeader("Cache-Control", "no-cache");
|
|
826
|
+
response.end(code);
|
|
827
|
+
}
|
|
828
|
+
function sendPreviewError(response, error) {
|
|
829
|
+
response.statusCode = 500;
|
|
830
|
+
response.end(error instanceof Error ? error.message : String(error));
|
|
831
|
+
}
|
|
832
|
+
/** Art fallbacks retain their existing headers and bound generation failures. */
|
|
833
|
+
function sendArtModuleFallback(response, generate) {
|
|
834
|
+
try {
|
|
835
|
+
const code = generate();
|
|
836
|
+
response.setHeader("Content-Type", "application/javascript");
|
|
837
|
+
response.end(code);
|
|
838
|
+
} catch (error) {
|
|
839
|
+
sendPreviewError(response, error);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
//#endregion
|
|
821
843
|
//#region src/server-middleware.ts
|
|
822
844
|
const moduleDir$1 = path.dirname(fileURLToPath(import.meta.url));
|
|
823
845
|
const galleryAssetMimeTypes = {
|
|
@@ -853,7 +875,7 @@ async function tryLoadSourceGalleryHtml(devServer, url, basePath, devSessionToke
|
|
|
853
875
|
return devServer.transformIndexHtml(url, html);
|
|
854
876
|
}
|
|
855
877
|
async function generateFallbackGalleryHtml(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar) {
|
|
856
|
-
const { generateGalleryHtml } = await import("./gallery-
|
|
878
|
+
const { generateGalleryHtml } = await import("./gallery-LgVvVp28.mjs");
|
|
857
879
|
return generateGalleryHtml(basePath, devSessionToken, themeConfig, tokenPreviewConfig, toolbar);
|
|
858
880
|
}
|
|
859
881
|
async function serveGalleryAsset(galleryDistDir, requestUrl, res) {
|
|
@@ -940,19 +962,22 @@ function registerMiddleware(devServer, ctx) {
|
|
|
940
962
|
res.end("Variant not found");
|
|
941
963
|
return;
|
|
942
964
|
}
|
|
943
|
-
|
|
965
|
+
let variantComponentName;
|
|
944
966
|
try {
|
|
945
|
-
|
|
967
|
+
variantComponentName = variantComponentNames(art.variants).get(variant.name);
|
|
968
|
+
} catch (error) {
|
|
969
|
+
sendPreviewError(res, error);
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
const moduleCode = generatePreviewModule(art, variantComponentName, variant.name, ctx.resolvedPreviewCss, ctx.resolvedPreviewSetup, 3, ctx.toolbar);
|
|
973
|
+
try {
|
|
974
|
+
const result = await devServer.transformRequest(previewModuleId(artPath, variantName));
|
|
946
975
|
if (result) {
|
|
947
|
-
res
|
|
948
|
-
res.setHeader("Cache-Control", "no-cache");
|
|
949
|
-
res.end(result.code);
|
|
976
|
+
sendPreviewModule(res, result.code);
|
|
950
977
|
return;
|
|
951
978
|
}
|
|
952
979
|
} catch {}
|
|
953
|
-
res
|
|
954
|
-
res.setHeader("Cache-Control", "no-cache");
|
|
955
|
-
res.end(moduleCode);
|
|
980
|
+
sendPreviewModule(res, moduleCode);
|
|
956
981
|
});
|
|
957
982
|
devServer.middlewares.use(`${basePath}/preview`, async (req, res, _next) => {
|
|
958
983
|
const url = new URL(req.url || "", `http://localhost`);
|
|
@@ -1006,1460 +1031,98 @@ function registerMiddleware(devServer, ctx) {
|
|
|
1006
1031
|
try {
|
|
1007
1032
|
const virtualId = `virtual:musea-art:${artPath}`;
|
|
1008
1033
|
const result = await devServer.transformRequest(virtualId);
|
|
1009
|
-
if (result)
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
}
|
|
1014
|
-
const moduleCode = generateArtModule(art, artPath, {
|
|
1015
|
-
root: devServer.config.root,
|
|
1016
|
-
scanRoots: ctx.scanRoots
|
|
1017
|
-
});
|
|
1018
|
-
res.setHeader("Content-Type", "application/javascript");
|
|
1019
|
-
res.end(moduleCode);
|
|
1020
|
-
}
|
|
1034
|
+
if (result) sendPreviewModule(res, result.code);
|
|
1035
|
+
else sendArtModuleFallback(res, () => generateArtModule(art, artPath, {
|
|
1036
|
+
root: devServer.config.root,
|
|
1037
|
+
scanRoots: ctx.scanRoots
|
|
1038
|
+
}));
|
|
1021
1039
|
} catch (err) {
|
|
1022
1040
|
console.error("[musea] Failed to transform art module:", err);
|
|
1023
|
-
|
|
1041
|
+
sendArtModuleFallback(res, () => generateArtModule(art, artPath, {
|
|
1024
1042
|
root: devServer.config.root,
|
|
1025
1043
|
scanRoots: ctx.scanRoots
|
|
1026
|
-
});
|
|
1027
|
-
res.setHeader("Content-Type", "application/javascript");
|
|
1028
|
-
res.end(moduleCode);
|
|
1044
|
+
}));
|
|
1029
1045
|
}
|
|
1030
1046
|
});
|
|
1031
1047
|
}
|
|
1032
1048
|
//#endregion
|
|
1033
|
-
//#region src/
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
if (
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
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 });
|
|
1049
|
+
//#region src/vrt/report-identity.ts
|
|
1050
|
+
/** Reserve one qualified namespace and compare legacy names on case-insensitive filesystems. */
|
|
1051
|
+
function legacyName(identity) {
|
|
1052
|
+
const basename = path.posix.basename(identity, ".art.vue");
|
|
1053
|
+
return /^[a-z0-9._-]{1,200}$/i.test(basename) && !/^art-[0-9a-f]{64}$/i.test(basename) ? `vrt-${basename}` : void 0;
|
|
1054
|
+
}
|
|
1055
|
+
/** The complete discovered Art set decides collisions, even for a single-Art request. */
|
|
1056
|
+
function resolveArtReportTarget(artPath, artPaths, projectRoot, reportDir) {
|
|
1057
|
+
const identities = Array.from(artPaths, (item) => resolveSnapshotIdentity(item, projectRoot));
|
|
1058
|
+
const identity = resolveSnapshotIdentity(artPath, projectRoot);
|
|
1059
|
+
if (!identities.includes(identity)) throw new Error(`Report Art not found: ${artPath}`);
|
|
1060
|
+
const candidates = identities.map(legacyName);
|
|
1061
|
+
const counts = /* @__PURE__ */ new Map();
|
|
1062
|
+
for (const name of candidates) if (name) counts.set(name.toLowerCase(), (counts.get(name.toLowerCase()) ?? 0) + 1);
|
|
1063
|
+
const names = identities.map((item, index) => {
|
|
1064
|
+
const candidate = candidates[index];
|
|
1065
|
+
const colliding = candidate && counts.get(candidate.toLowerCase()) > 1;
|
|
1066
|
+
return candidate && !colliding ? candidate : `vrt-art-${createHash("sha256").update(JSON.stringify([1, item])).digest("hex")}`;
|
|
1099
1067
|
});
|
|
1100
|
-
|
|
1101
|
-
|
|
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("-");
|
|
1068
|
+
if (new Set(names.map((name) => name.toLowerCase())).size !== names.length) throw new Error("Ambiguous VRT report identities");
|
|
1069
|
+
const base = names[identities.indexOf(identity)];
|
|
1276
1070
|
return {
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
description: `Custom property ${variable}`
|
|
1071
|
+
identity,
|
|
1072
|
+
jsonReportPath: path.join(reportDir, `${base}-report.json`),
|
|
1073
|
+
htmlReportPath: path.join(reportDir, `${base}-report.html`)
|
|
1281
1074
|
};
|
|
1282
1075
|
}
|
|
1283
|
-
function
|
|
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
|
-
//#region src/tokens/generator.ts
|
|
1591
|
-
/**
|
|
1592
|
-
* Token documentation generators for Style Dictionary integration.
|
|
1593
|
-
*
|
|
1594
|
-
* Generates HTML, Markdown, and JSON documentation from parsed token categories,
|
|
1595
|
-
* and provides the main processStyleDictionary orchestrator function.
|
|
1596
|
-
*/
|
|
1597
|
-
const SAFE_CSS_COLOR_PATTERN = /^(?:#[0-9a-fA-F]{3,8}|(?:rgb|hsl)a?\(\s*[-+.\d,%\s/]+\)|(?:oklch|oklab|lab|lch)\(\s*[-+.\d,%\s/]+\))$/;
|
|
1598
|
-
const DANGEROUS_PROTOCOL_PATTERN = /\b(javascript|vbscript):/gi;
|
|
1599
|
-
function escapeTokenText(value) {
|
|
1600
|
-
return escapeHtml(value).replace(DANGEROUS_PROTOCOL_PATTERN, "$1:");
|
|
1601
|
-
}
|
|
1602
|
-
function safeCssColor(value, type) {
|
|
1603
|
-
if (typeof value !== "string") return null;
|
|
1604
|
-
const trimmed = value.trim();
|
|
1605
|
-
return (type === "color" || trimmed.startsWith("#") || trimmed.startsWith("rgb") || trimmed.startsWith("hsl")) && SAFE_CSS_COLOR_PATTERN.test(trimmed) ? trimmed : null;
|
|
1606
|
-
}
|
|
1607
|
-
/**
|
|
1608
|
-
* Generate HTML documentation for tokens.
|
|
1609
|
-
*/
|
|
1610
|
-
function generateTokensHtml(categories) {
|
|
1611
|
-
const renderToken = (name, token) => {
|
|
1612
|
-
const color = safeCssColor(token.value, token.type);
|
|
1613
|
-
return `
|
|
1614
|
-
<div class="token">
|
|
1615
|
-
<div class="token-preview">
|
|
1616
|
-
${color ? `<div class="color-swatch" style="background: ${color}"></div>` : ""}
|
|
1617
|
-
</div>
|
|
1618
|
-
<div class="token-info">
|
|
1619
|
-
<div class="token-name">${escapeTokenText(name)}</div>
|
|
1620
|
-
<div class="token-value">${escapeTokenText(String(token.value))}</div>
|
|
1621
|
-
${token.description ? `<div class="token-description">${escapeTokenText(token.description)}</div>` : ""}
|
|
1622
|
-
</div>
|
|
1623
|
-
</div>
|
|
1624
|
-
`;
|
|
1625
|
-
};
|
|
1626
|
-
const renderCategory = (category, level = 2) => {
|
|
1627
|
-
const heading = `h${Math.min(level, 6)}`;
|
|
1628
|
-
let html = `<${heading}>${escapeTokenText(category.name)}</${heading}>`;
|
|
1629
|
-
html += "<div class=\"tokens-grid\">";
|
|
1630
|
-
for (const [name, token] of Object.entries(category.tokens)) html += renderToken(name, token);
|
|
1631
|
-
html += "</div>";
|
|
1632
|
-
if (category.subcategories) for (const sub of category.subcategories) html += renderCategory(sub, level + 1);
|
|
1633
|
-
return html;
|
|
1634
|
-
};
|
|
1635
|
-
return `<!DOCTYPE html>
|
|
1636
|
-
<html lang="en">
|
|
1637
|
-
<head>
|
|
1638
|
-
<meta charset="UTF-8">
|
|
1639
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1640
|
-
<title>Design Tokens - Musea</title>
|
|
1641
|
-
<style>
|
|
1642
|
-
:root {
|
|
1643
|
-
--musea-bg: #0d0d0d;
|
|
1644
|
-
--musea-bg-secondary: #1a1815;
|
|
1645
|
-
--musea-text: #e6e9f0;
|
|
1646
|
-
--musea-text-muted: #7b8494;
|
|
1647
|
-
--musea-accent: #a34828;
|
|
1648
|
-
--musea-border: #3a3530;
|
|
1649
|
-
}
|
|
1650
|
-
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
1651
|
-
body {
|
|
1652
|
-
font-family: 'Inter', -apple-system, sans-serif;
|
|
1653
|
-
background: var(--musea-bg);
|
|
1654
|
-
color: var(--musea-text);
|
|
1655
|
-
line-height: 1.6;
|
|
1656
|
-
padding: 2rem;
|
|
1657
|
-
}
|
|
1658
|
-
h1 { margin-bottom: 2rem; color: var(--musea-accent); }
|
|
1659
|
-
h2 { margin: 2rem 0 1rem; padding-bottom: 0.5rem; border-bottom: 1px solid var(--musea-border); }
|
|
1660
|
-
h3, h4, h5, h6 { margin: 1.5rem 0 0.75rem; }
|
|
1661
|
-
.tokens-grid {
|
|
1662
|
-
display: grid;
|
|
1663
|
-
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
|
1664
|
-
gap: 1rem;
|
|
1665
|
-
margin-bottom: 1.5rem;
|
|
1666
|
-
}
|
|
1667
|
-
.token {
|
|
1668
|
-
background: var(--musea-bg-secondary);
|
|
1669
|
-
border: 1px solid var(--musea-border);
|
|
1670
|
-
border-radius: 8px;
|
|
1671
|
-
padding: 1rem;
|
|
1672
|
-
display: flex;
|
|
1673
|
-
gap: 1rem;
|
|
1674
|
-
align-items: center;
|
|
1675
|
-
}
|
|
1676
|
-
.token-preview {
|
|
1677
|
-
flex-shrink: 0;
|
|
1678
|
-
width: 48px;
|
|
1679
|
-
height: 48px;
|
|
1680
|
-
display: flex;
|
|
1681
|
-
align-items: center;
|
|
1682
|
-
justify-content: center;
|
|
1683
|
-
}
|
|
1684
|
-
.color-swatch {
|
|
1685
|
-
width: 48px;
|
|
1686
|
-
height: 48px;
|
|
1687
|
-
border-radius: 8px;
|
|
1688
|
-
border: 1px solid var(--musea-border);
|
|
1689
|
-
}
|
|
1690
|
-
.token-info {
|
|
1691
|
-
flex: 1;
|
|
1692
|
-
min-width: 0;
|
|
1693
|
-
}
|
|
1694
|
-
.token-name {
|
|
1695
|
-
font-weight: 600;
|
|
1696
|
-
font-family: 'JetBrains Mono', monospace;
|
|
1697
|
-
font-size: 0.875rem;
|
|
1698
|
-
}
|
|
1699
|
-
.token-value {
|
|
1700
|
-
color: var(--musea-text-muted);
|
|
1701
|
-
font-family: 'JetBrains Mono', monospace;
|
|
1702
|
-
font-size: 0.75rem;
|
|
1703
|
-
word-break: break-all;
|
|
1704
|
-
}
|
|
1705
|
-
.token-description {
|
|
1706
|
-
color: var(--musea-text-muted);
|
|
1707
|
-
font-size: 0.75rem;
|
|
1708
|
-
margin-top: 0.25rem;
|
|
1709
|
-
}
|
|
1710
|
-
</style>
|
|
1711
|
-
</head>
|
|
1712
|
-
<body>
|
|
1713
|
-
<h1>Design Tokens</h1>
|
|
1714
|
-
${categories.map((cat) => renderCategory(cat)).join("")}
|
|
1715
|
-
</body>
|
|
1716
|
-
</html>`;
|
|
1717
|
-
}
|
|
1718
|
-
/**
|
|
1719
|
-
* Generate Markdown documentation for tokens.
|
|
1720
|
-
*/
|
|
1721
|
-
function generateTokensMarkdown(categories) {
|
|
1722
|
-
return tokenNative().generateDesignTokensMarkdown(categories, (/* @__PURE__ */ new Date()).toISOString());
|
|
1723
|
-
}
|
|
1724
|
-
/**
|
|
1725
|
-
* Style Dictionary plugin for Musea.
|
|
1726
|
-
* Parses tokens and generates documentation in the specified format.
|
|
1727
|
-
*/
|
|
1728
|
-
async function processStyleDictionary(config) {
|
|
1729
|
-
const categories = await parseTokens(config.tokensPath);
|
|
1730
|
-
const outputDir = config.outputDir ?? ".vize/tokens";
|
|
1731
|
-
const outputFormat = config.outputFormat ?? "html";
|
|
1732
|
-
await fs.promises.mkdir(outputDir, { recursive: true });
|
|
1733
|
-
let content;
|
|
1734
|
-
let filename;
|
|
1735
|
-
switch (outputFormat) {
|
|
1736
|
-
case "html":
|
|
1737
|
-
content = generateTokensHtml(categories);
|
|
1738
|
-
filename = "tokens.html";
|
|
1739
|
-
break;
|
|
1740
|
-
case "markdown":
|
|
1741
|
-
content = generateTokensMarkdown(categories);
|
|
1742
|
-
filename = "tokens.md";
|
|
1743
|
-
break;
|
|
1744
|
-
default:
|
|
1745
|
-
content = JSON.stringify({ categories }, null, 2);
|
|
1746
|
-
filename = "tokens.json";
|
|
1747
|
-
}
|
|
1748
|
-
const outputPath = path.join(outputDir, filename);
|
|
1749
|
-
await fs.promises.writeFile(outputPath, content, "utf-8");
|
|
1750
|
-
console.log(`[musea] Generated token documentation: ${outputPath}`);
|
|
1751
|
-
return {
|
|
1752
|
-
categories,
|
|
1753
|
-
metadata: {
|
|
1754
|
-
name: path.basename(config.tokensPath),
|
|
1755
|
-
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1756
|
-
}
|
|
1757
|
-
};
|
|
1758
|
-
}
|
|
1759
|
-
//#endregion
|
|
1760
|
-
//#region src/tokens/preview.ts
|
|
1761
|
-
function resolveTokenPreview(input) {
|
|
1762
|
-
const reference = resolveReference(input.token, input.tokenMap);
|
|
1763
|
-
const value = input.token.$resolvedValue ?? reference?.value ?? input.token.value;
|
|
1764
|
-
const candidates = buildCandidates(input.tokenPath, input.token, reference);
|
|
1765
|
-
const kind = resolveCustomKind(candidates, reference?.path, input.config?.rules) ?? inferPreviewKind(candidates, value);
|
|
1766
|
-
return {
|
|
1767
|
-
kind: new Set(input.config?.disabledKinds ?? []).has(kind) ? "generic" : kind,
|
|
1768
|
-
value,
|
|
1769
|
-
tokenPath: input.tokenPath,
|
|
1770
|
-
reference
|
|
1771
|
-
};
|
|
1772
|
-
}
|
|
1773
|
-
function resolveReference(token, tokenMap) {
|
|
1774
|
-
if (!token.$reference) return void 0;
|
|
1775
|
-
const referencedToken = tokenMap?.[token.$reference];
|
|
1776
|
-
return {
|
|
1777
|
-
path: token.$reference,
|
|
1778
|
-
token: referencedToken,
|
|
1779
|
-
value: referencedToken ? referencedToken.$resolvedValue ?? referencedToken.value : void 0
|
|
1780
|
-
};
|
|
1781
|
-
}
|
|
1782
|
-
function buildCandidates(tokenPath, token, reference) {
|
|
1783
|
-
const candidates = [{
|
|
1784
|
-
tokenPath,
|
|
1785
|
-
name: pathName(tokenPath),
|
|
1786
|
-
token
|
|
1787
|
-
}];
|
|
1788
|
-
if (reference?.token) candidates.push({
|
|
1789
|
-
tokenPath: reference.path,
|
|
1790
|
-
name: pathName(reference.path),
|
|
1791
|
-
token: reference.token
|
|
1792
|
-
});
|
|
1793
|
-
return candidates;
|
|
1794
|
-
}
|
|
1795
|
-
function resolveCustomKind(candidates, referencePath, rules) {
|
|
1796
|
-
for (const rule of rules ?? []) if (matchesRule(rule, candidates, referencePath)) return rule.kind;
|
|
1797
|
-
}
|
|
1798
|
-
function matchesRule(rule, candidates, referencePath) {
|
|
1799
|
-
const checks = [];
|
|
1800
|
-
if (rule.type !== void 0) checks.push(candidates.some((candidate) => typeMatches(candidate, rule.type)));
|
|
1801
|
-
if (rule.pathIncludes !== void 0) checks.push(candidates.some((candidate) => includesAny(candidate.tokenPath, rule.pathIncludes)));
|
|
1802
|
-
if (rule.nameIncludes !== void 0) checks.push(candidates.some((candidate) => includesAny(candidate.name, rule.nameIncludes)));
|
|
1803
|
-
if (rule.referencePathIncludes !== void 0) checks.push(referencePath !== void 0 && includesAny(referencePath, rule.referencePathIncludes));
|
|
1804
|
-
return checks.length > 0 && checks.every(Boolean);
|
|
1805
|
-
}
|
|
1806
|
-
function inferPreviewKind(candidates, value) {
|
|
1807
|
-
if (hasType(candidates, ["color"]) || isColorValue(value)) return "color";
|
|
1808
|
-
if (hasType(candidates, ["shadow", "box-shadow"]) || hasSignal(candidates, ["shadow", "box-shadow"])) return "shadow";
|
|
1809
|
-
if (hasType(candidates, [
|
|
1810
|
-
"z-index",
|
|
1811
|
-
"zindex",
|
|
1812
|
-
"zIndex"
|
|
1813
|
-
]) || hasSignal(candidates, [
|
|
1814
|
-
"z-index",
|
|
1815
|
-
"zindex",
|
|
1816
|
-
"stacking-order"
|
|
1817
|
-
])) return "zIndex";
|
|
1818
|
-
if (hasType(candidates, ["opacity"]) || hasSignal(candidates, ["opacity", "alpha"])) return "opacity";
|
|
1819
|
-
if (hasType(candidates, [
|
|
1820
|
-
"border-radius",
|
|
1821
|
-
"borderradius",
|
|
1822
|
-
"radius"
|
|
1823
|
-
]) || hasSignal(candidates, [
|
|
1824
|
-
"border-radius",
|
|
1825
|
-
"borderradius",
|
|
1826
|
-
"radius",
|
|
1827
|
-
"round",
|
|
1828
|
-
"rounded"
|
|
1829
|
-
])) return "radius";
|
|
1830
|
-
if (hasType(candidates, ["letterspacing", "letter-spacing"]) || hasSignal(candidates, [
|
|
1831
|
-
"letter-spacing",
|
|
1832
|
-
"letterspacing",
|
|
1833
|
-
"tracking"
|
|
1834
|
-
])) return "letterSpacing";
|
|
1835
|
-
if (hasType(candidates, ["spacing", "space"]) || hasSignal(candidates, [
|
|
1836
|
-
"spacing",
|
|
1837
|
-
"spasing",
|
|
1838
|
-
"space",
|
|
1839
|
-
"gap",
|
|
1840
|
-
"padding",
|
|
1841
|
-
"margin",
|
|
1842
|
-
"inset"
|
|
1843
|
-
])) return "spacing";
|
|
1844
|
-
if (hasSignal(candidates, [
|
|
1845
|
-
"font-size",
|
|
1846
|
-
"fontsize",
|
|
1847
|
-
"text-size"
|
|
1848
|
-
])) return "fontSize";
|
|
1849
|
-
if (hasType(candidates, ["fontweight", "font-weight"]) || hasSignal(candidates, [
|
|
1850
|
-
"font-weight",
|
|
1851
|
-
"fontweight",
|
|
1852
|
-
"weight"
|
|
1853
|
-
])) return "fontWeight";
|
|
1854
|
-
if (hasType(candidates, ["lineheight", "line-height"]) || hasSignal(candidates, ["line-height", "lineheight"])) return "lineHeight";
|
|
1855
|
-
return "generic";
|
|
1856
|
-
}
|
|
1857
|
-
function hasType(candidates, terms) {
|
|
1858
|
-
return candidates.some((candidate) => typeMatches(candidate, terms));
|
|
1859
|
-
}
|
|
1860
|
-
function hasSignal(candidates, terms) {
|
|
1861
|
-
return candidates.some((candidate) => includesAny(candidate.tokenPath, terms) || includesAny(candidate.name, terms) || candidate.token.type !== void 0 && includesAny(candidate.token.type, terms));
|
|
1862
|
-
}
|
|
1863
|
-
function typeMatches(candidate, expected) {
|
|
1864
|
-
if (!candidate.token.type) return false;
|
|
1865
|
-
return toArray(expected).some((term) => normalize(candidate.token.type) === normalize(term));
|
|
1866
|
-
}
|
|
1867
|
-
function includesAny(value, expected) {
|
|
1868
|
-
const normalizedValue = normalize(value);
|
|
1869
|
-
const compactValue = compact(normalizedValue);
|
|
1870
|
-
return toArray(expected).some((term) => {
|
|
1871
|
-
const normalizedTerm = normalize(term);
|
|
1872
|
-
return normalizedValue.includes(normalizedTerm) || compactValue.includes(compact(normalizedTerm));
|
|
1873
|
-
});
|
|
1874
|
-
}
|
|
1875
|
-
function isColorValue(value) {
|
|
1876
|
-
if (typeof value !== "string") return false;
|
|
1877
|
-
return /^(#|rgb\(|rgba\(|hsl\(|hsla\(|oklch\(|oklab\(|lab\(|lch\(|color\()/i.test(value.trim());
|
|
1878
|
-
}
|
|
1879
|
-
function pathName(tokenPath) {
|
|
1880
|
-
return tokenPath.split(".").at(-1) ?? tokenPath;
|
|
1881
|
-
}
|
|
1882
|
-
function normalize(value) {
|
|
1883
|
-
return value.trim().toLowerCase().replace(/[_\s]+/g, "-");
|
|
1884
|
-
}
|
|
1885
|
-
function compact(value) {
|
|
1886
|
-
return value.replace(/[-.]/g, "");
|
|
1887
|
-
}
|
|
1888
|
-
function toArray(value) {
|
|
1889
|
-
return Array.isArray(value) ? value : [value];
|
|
1890
|
-
}
|
|
1891
|
-
//#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
|
-
}
|
|
1967
|
-
}
|
|
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();
|
|
1076
|
+
async function existsRegularFile(file) {
|
|
1975
1077
|
try {
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
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);
|
|
1078
|
+
if (!(await lstat(file)).isFile()) throw new Error(`VRT report is not a regular file: ${file}`);
|
|
1079
|
+
return true;
|
|
1080
|
+
} catch (error) {
|
|
1081
|
+
if (error.code === "ENOENT") return false;
|
|
1082
|
+
throw error;
|
|
2007
1083
|
}
|
|
2008
1084
|
}
|
|
2009
|
-
/**
|
|
2010
|
-
async function
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
}
|
|
2015
|
-
const body = await readBody();
|
|
1085
|
+
/** Fail before capture or writes; legacy adoption requires every recorded result to have this owner. */
|
|
1086
|
+
async function assertArtReportOwnership(target, projectRoot) {
|
|
1087
|
+
const refusal = `Ambiguous VRT report ownership: ${target.jsonReportPath}. Archive or move the existing reports before retrying.`;
|
|
1088
|
+
const names = [path.basename(target.jsonReportPath), path.basename(target.htmlReportPath)];
|
|
1089
|
+
let existingNames;
|
|
2016
1090
|
try {
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
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;
|
|
1091
|
+
existingNames = await readdir(path.dirname(target.jsonReportPath));
|
|
1092
|
+
} catch (error) {
|
|
1093
|
+
if (error.code === "ENOENT") return;
|
|
1094
|
+
throw error;
|
|
2050
1095
|
}
|
|
2051
|
-
|
|
1096
|
+
if (existingNames.some((item) => names.some((name) => item !== name && item.toLowerCase() === name.toLowerCase()))) throw new Error(refusal);
|
|
1097
|
+
const jsonExists = await existsRegularFile(target.jsonReportPath);
|
|
1098
|
+
const htmlExists = await existsRegularFile(target.htmlReportPath);
|
|
1099
|
+
if (!jsonExists && !htmlExists) return;
|
|
1100
|
+
if (!jsonExists) throw new Error(refusal);
|
|
2052
1101
|
try {
|
|
2053
|
-
const
|
|
2054
|
-
if (!
|
|
2055
|
-
|
|
2056
|
-
|
|
1102
|
+
const report = JSON.parse(await readFile(target.jsonReportPath, "utf8"));
|
|
1103
|
+
if (!report || typeof report !== "object" || Array.isArray(report)) throw new Error(refusal);
|
|
1104
|
+
if (Object.hasOwn(report, "reportOwner")) {
|
|
1105
|
+
const owner = report.reportOwner;
|
|
1106
|
+
if (!owner || typeof owner !== "object" || owner.version !== 1 || owner.artIdentity !== target.identity) throw new Error(refusal);
|
|
1107
|
+
} else {
|
|
1108
|
+
const results = report.results;
|
|
1109
|
+
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);
|
|
2057
1110
|
}
|
|
2058
|
-
|
|
2059
|
-
|
|
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);
|
|
2114
|
-
}
|
|
2115
|
-
}
|
|
2116
|
-
}
|
|
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
|
-
});
|
|
1111
|
+
} catch {
|
|
1112
|
+
throw new Error(refusal);
|
|
2184
1113
|
}
|
|
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
1114
|
}
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
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;
|
|
1115
|
+
/** Keep ownership portable when a report directory moves to another machine. */
|
|
1116
|
+
function attachArtReportOwner(json, target) {
|
|
1117
|
+
return JSON.stringify({
|
|
1118
|
+
...JSON.parse(json),
|
|
1119
|
+
reportOwner: {
|
|
1120
|
+
version: 1,
|
|
1121
|
+
artIdentity: target.identity
|
|
2248
1122
|
}
|
|
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
1123
|
}, 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
1124
|
}
|
|
2354
1125
|
//#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
1126
|
//#region src/api-routes/post-handlers.ts
|
|
2464
1127
|
/** POST /api/preview-with-props */
|
|
2465
1128
|
function handlePreviewWithProps(ctx, body, res, sendJson, sendError) {
|
|
@@ -2475,7 +1138,7 @@ function handlePreviewWithProps(ctx, body, res, sendJson, sendError) {
|
|
|
2475
1138
|
sendError("Variant not found", 404);
|
|
2476
1139
|
return;
|
|
2477
1140
|
}
|
|
2478
|
-
const moduleCode = generatePreviewModuleWithProps(art,
|
|
1141
|
+
const moduleCode = generatePreviewModuleWithProps(art, variantComponentNames(art.variants).get(variant.name), variant.name, propsOverride, ctx.resolvedPreviewCss, ctx.resolvedPreviewSetup, 3, ctx.toolbar);
|
|
2479
1142
|
res.setHeader("Content-Type", "application/javascript");
|
|
2480
1143
|
res.end(moduleCode);
|
|
2481
1144
|
} catch (e) {
|
|
@@ -2520,10 +1183,25 @@ async function handleGenerate(ctx, body, sendJson, sendError) {
|
|
|
2520
1183
|
async function handleRunVrt(ctx, body, sendJson, sendError) {
|
|
2521
1184
|
try {
|
|
2522
1185
|
const { artPath, updateSnapshots } = parseJsonBody(body);
|
|
1186
|
+
if (artPath !== void 0 && typeof artPath !== "string") throw new HttpError("artPath must be a string", 400);
|
|
1187
|
+
if (artPath !== void 0 && !ctx.artFiles.has(artPath)) throw new HttpError("Art not found", 404);
|
|
2523
1188
|
const { MuseaVrtRunner, generateVrtJsonReport, generateVrtReport } = await import("./vrt.mjs");
|
|
2524
|
-
const
|
|
1189
|
+
const { a11y: _a11y, ...configured } = ctx.vrt ?? {};
|
|
1190
|
+
const snapshotDir = path.resolve(ctx.config.root, configured.snapshotDir ?? ".vize/snapshots");
|
|
2525
1191
|
const reportDir = path.resolve(ctx.config.root, ".vize/reports");
|
|
2526
|
-
const
|
|
1192
|
+
const projectRoot = ctx.projectRoot ?? ctx.config.root;
|
|
1193
|
+
const reportTarget = artPath === void 0 ? void 0 : resolveArtReportTarget(artPath, ctx.artFiles.keys(), projectRoot, reportDir);
|
|
1194
|
+
if (reportTarget) await assertArtReportOwnership(reportTarget, projectRoot);
|
|
1195
|
+
const runner = new MuseaVrtRunner({
|
|
1196
|
+
...configured,
|
|
1197
|
+
capture: {
|
|
1198
|
+
...configured.capture,
|
|
1199
|
+
waitForPreviewReady: true
|
|
1200
|
+
},
|
|
1201
|
+
snapshotDir,
|
|
1202
|
+
projectRoot,
|
|
1203
|
+
previewBasePath: publicBasePathFromViteBase(ctx.config.base, ctx.basePath)
|
|
1204
|
+
});
|
|
2527
1205
|
const baseUrl = `http://localhost:${ctx.getDevServerPort()}`;
|
|
2528
1206
|
let artsToTest = Array.from(ctx.artFiles.values());
|
|
2529
1207
|
if (artPath) artsToTest = artsToTest.filter((a) => a.path === artPath);
|
|
@@ -2539,11 +1217,11 @@ async function handleRunVrt(ctx, body, sendJson, sendError) {
|
|
|
2539
1217
|
await runner.stop();
|
|
2540
1218
|
}
|
|
2541
1219
|
})();
|
|
2542
|
-
const
|
|
2543
|
-
const
|
|
2544
|
-
const
|
|
1220
|
+
const jsonReportPath = reportTarget?.jsonReportPath ?? path.join(reportDir, "vrt-report.json");
|
|
1221
|
+
const htmlReportPath = reportTarget?.htmlReportPath ?? path.join(reportDir, "vrt-report.html");
|
|
1222
|
+
const jsonReport = generateVrtJsonReport(results, summary);
|
|
2545
1223
|
await fs.promises.mkdir(reportDir, { recursive: true });
|
|
2546
|
-
await fs.promises.writeFile(jsonReportPath,
|
|
1224
|
+
await fs.promises.writeFile(jsonReportPath, reportTarget ? attachArtReportOwner(jsonReport, reportTarget) : jsonReport, "utf-8");
|
|
2547
1225
|
await fs.promises.writeFile(htmlReportPath, generateVrtReport(results, summary), "utf-8");
|
|
2548
1226
|
sendJson({
|
|
2549
1227
|
success: true,
|
|
@@ -2890,9 +1568,13 @@ function createLoad(state) {
|
|
|
2890
1568
|
const lastColonIndex = rest.lastIndexOf(":");
|
|
2891
1569
|
if (lastColonIndex !== -1) {
|
|
2892
1570
|
const artPath = rest.slice(0, lastColonIndex);
|
|
2893
|
-
const variantName = rest.slice(lastColonIndex + 1);
|
|
1571
|
+
const variantName = decodeVariantName(rest.slice(lastColonIndex + 1));
|
|
2894
1572
|
const art = state.artFiles.get(artPath);
|
|
2895
|
-
if (art)
|
|
1573
|
+
if (art) {
|
|
1574
|
+
const variantComponentName = variantComponentNames(art.variants).get(variantName);
|
|
1575
|
+
if (!variantComponentName) return null;
|
|
1576
|
+
return generatePreviewModule(art, variantComponentName, variantName, state.resolvedPreviewCss, state.resolvedPreviewSetup, state.getVueVersion(), state.toolbar);
|
|
1577
|
+
}
|
|
2896
1578
|
}
|
|
2897
1579
|
}
|
|
2898
1580
|
if (id.startsWith("\0musea-shared:")) {
|
|
@@ -3065,129 +1747,6 @@ function relativePath(root, filePath) {
|
|
|
3065
1747
|
return path.relative(root, filePath).split(path.sep).join("/");
|
|
3066
1748
|
}
|
|
3067
1749
|
//#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
1750
|
//#region src/static-gallery-shell.ts
|
|
3192
1751
|
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
|
3193
1752
|
function joinFileName(...parts) {
|
|
@@ -3301,7 +1860,7 @@ function loadStaticRuntimeModule(id, artFiles) {
|
|
|
3301
1860
|
return `
|
|
3302
1861
|
const loaders = { ${Array.from(artFiles.values()).flatMap((art) => art.variants.map((variant) => {
|
|
3303
1862
|
const key = staticPreviewId(art.path, variant.name);
|
|
3304
|
-
const moduleId =
|
|
1863
|
+
const moduleId = previewModuleId(art.path, variant.name);
|
|
3305
1864
|
return `${JSON.stringify(key)}: () => import(${JSON.stringify(moduleId)})`;
|
|
3306
1865
|
})).join(",\n")} };
|
|
3307
1866
|
|
|
@@ -3571,6 +2130,7 @@ function musea(options = {}) {
|
|
|
3571
2130
|
},
|
|
3572
2131
|
configureServer(devServer) {
|
|
3573
2132
|
server = devServer;
|
|
2133
|
+
devServer.watcher.unwatch(path.resolve(config.root, ".vize/reports"));
|
|
3574
2134
|
registerMiddleware(devServer, {
|
|
3575
2135
|
basePath,
|
|
3576
2136
|
devSessionToken,
|
|
@@ -3592,6 +2152,7 @@ function musea(options = {}) {
|
|
|
3592
2152
|
resolvedPreviewCss,
|
|
3593
2153
|
resolvedPreviewSetup,
|
|
3594
2154
|
toolbar,
|
|
2155
|
+
vrt: options.vrt,
|
|
3595
2156
|
devSessionToken,
|
|
3596
2157
|
processArtFile,
|
|
3597
2158
|
getDevServerPort: () => devServer.config.server.port || 5173
|