@vizejs/vite-plugin-musea 0.440.0 → 0.442.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/a11y/index.d.mts +1 -1
- package/dist/a11y/index.mjs +1 -1
- package/dist/{a11y-BbFK942j.mjs → a11y-BU5kFNk-.mjs} +6 -5
- package/dist/a11y-BU5kFNk-.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 +110 -9
- package/dist/cli/index.mjs.map +1 -1
- package/dist/gallery/assets/MonacoEditor-DpMHG8uG.js +2 -0
- package/dist/gallery/assets/MonacoEditor-DxzpSKbC.css +1 -0
- package/dist/gallery/assets/{cssMode-Chlc2oby.js → cssMode-BhNXI_iH.js} +1 -1
- package/dist/gallery/assets/{editor.api-B0CSOuX7.js → editor.api-pyN3BEOj.js} +1 -1
- package/dist/gallery/assets/{freemarker2-UuwRuSuB.js → freemarker2-DDdeAW1l.js} +1 -1
- package/dist/gallery/assets/{handlebars-JBK-IQdb.js → handlebars-d_XLJufS.js} +1 -1
- package/dist/gallery/assets/{html-Ysiq-32p.js → html-pNQuOCmG.js} +1 -1
- package/dist/gallery/assets/{htmlMode-xYeJY9wj.js → htmlMode-C9_7c2MZ.js} +1 -1
- package/dist/gallery/assets/index-DpZpi0O6.css +1 -0
- package/dist/gallery/assets/{index-MXXeE4aD.js → index-qkpGvqJF.js} +24 -24
- package/dist/gallery/assets/{javascript-Ccrslpma.js → javascript-V9iW4BoD.js} +1 -1
- package/dist/gallery/assets/{jsonMode-v3sPHB9W.js → jsonMode-B_jKD9Gd.js} +1 -1
- package/dist/gallery/assets/{liquid-Dd_z8h_B.js → liquid-B5bf9QtA.js} +1 -1
- package/dist/gallery/assets/{lspLanguageFeatures-D9U1Gq1J.js → lspLanguageFeatures-DF8jpKLy.js} +1 -1
- package/dist/gallery/assets/{mdx-BV9KJmeU.js → mdx-B6b4WvnG.js} +1 -1
- package/dist/gallery/assets/{python-DpUI9NMf.js → python-C_8hKql2.js} +1 -1
- package/dist/gallery/assets/{razor-RzAxmhn_.js → razor-BK6Cp9pQ.js} +1 -1
- package/dist/gallery/assets/{register-CFx1KSfO.js → register-BcnlSPEw.js} +2 -2
- package/dist/gallery/assets/{toggleHighContrast-CSv0sacK.js → toggleHighContrast-D_Ox9lw9.js} +1 -1
- package/dist/gallery/assets/{tsMode-DpHP6oFd.js → tsMode-BODHbLZw.js} +1 -1
- package/dist/gallery/assets/{typescript-B-VbgG33.js → typescript-CdaOwWaG.js} +1 -1
- package/dist/gallery/assets/{vs-CzdsC1b2.js → vs-mnsDk7Q8.js} +3 -3
- package/dist/gallery/assets/{workers-HbLkgrxn.js → workers-DYnbCsrm.js} +1 -1
- package/dist/gallery/assets/{xml-CxjWwj-4.js → xml-ClcAB6Hf.js} +1 -1
- package/dist/gallery/assets/{yaml-q-dG9Lkk.js → yaml-mW5XIYQE.js} +1 -1
- package/dist/gallery/index.html +2 -2
- 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 +100 -1263
- package/dist/index.mjs.map +1 -1
- package/dist/options-DCuB_Fpu.mjs +1843 -0
- package/dist/options-DCuB_Fpu.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-DMGQGixL.js +0 -2
- package/dist/gallery/assets/MonacoEditor-Db3Q217Z.css +0 -1
- package/dist/gallery/assets/index-BCvwNnuC.css +0 -1
- package/dist/index-GkKsNzkf.d.mts.map +0 -1
- package/dist/options-CZYdDtTW.mjs +0 -581
- package/dist/options-CZYdDtTW.mjs.map +0 -1
- package/dist/vrt-DNNAFYv1.d.mts.map +0 -1
- package/dist/vrt-VuGK9wTX.mjs.map +0 -1
|
@@ -0,0 +1,1843 @@
|
|
|
1
|
+
import { E as loadNative, S as resolveTrustedSourcePath, T as analyzeSfcFallback, f as parseJsonBody, g as assertComponentSourcePath, s as toPascalCase, t as escapeHtml, v as decodeUrlComponent, w as HttpError, x as resolveInsideAny, y as isVueSourcePath } from "./utils-DeMLVlNS.mjs";
|
|
2
|
+
import { s as resolveSnapshotIdentity } from "./vrt-PuxpRuHa.mjs";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import crypto, { createHash } from "node:crypto";
|
|
6
|
+
import ts from "typescript";
|
|
7
|
+
//#region src/component-source.ts
|
|
8
|
+
function allowedSourceRoots(root, scanRoots = []) {
|
|
9
|
+
return [...new Set([root, ...scanRoots].map((sourceRoot) => path.resolve(sourceRoot)))];
|
|
10
|
+
}
|
|
11
|
+
function resolveReadableArtPath(root, scanRoots, artPath) {
|
|
12
|
+
return resolveTrustedSourcePath(root, scanRoots, artPath, "art path");
|
|
13
|
+
}
|
|
14
|
+
function resolveComponentSourcePath(art, artPath, sourceRoots) {
|
|
15
|
+
const componentPath = art.isInline && art.componentPath ? art.componentPath : art.metadata.component ? path.isAbsolute(art.metadata.component) ? art.metadata.component : path.resolve(path.dirname(artPath), art.metadata.component) : null;
|
|
16
|
+
const [projectRoot, ...extraRoots] = sourceRoots;
|
|
17
|
+
if (!componentPath) return null;
|
|
18
|
+
const resolved = resolveTrustedSourcePath(projectRoot ?? ".", extraRoots, componentPath, "component path");
|
|
19
|
+
assertComponentSourcePath(resolved, "component path");
|
|
20
|
+
return resolved;
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/art-module-vue2.ts
|
|
24
|
+
/**
|
|
25
|
+
* Legacy Vue 2 variant emission.
|
|
26
|
+
*
|
|
27
|
+
* Vue 2 has no `openBlock`/`createElementBlock` runtime, so the compiled Vue 3
|
|
28
|
+
* render functions the SFC pipeline produces cannot load there. Vue 2 galleries
|
|
29
|
+
* keep the runtime-compiled `template:` string they always had — the TypeScript
|
|
30
|
+
* fix in #3857 applies to Vue 3, which is what `.art.vue` with
|
|
31
|
+
* `<script setup lang="ts">` targets.
|
|
32
|
+
*/
|
|
33
|
+
function escapeTemplateLiteral(str) {
|
|
34
|
+
return str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
|
|
35
|
+
}
|
|
36
|
+
function emitLegacyVariant(context) {
|
|
37
|
+
const { variantComponentName, variantName, template, componentTagName, componentBindingName, scriptSetup, hasSetup, isolatedSetup, setupReturn, importDeclaresName } = context;
|
|
38
|
+
const escapedTemplate = escapeTemplateLiteral(template);
|
|
39
|
+
const fullTemplate = `<div data-variant="${escapeTemplateLiteral(escapeHtml(variantName))}">${escapedTemplate}</div>`;
|
|
40
|
+
const componentNames = /* @__PURE__ */ new Map();
|
|
41
|
+
if (componentTagName) componentNames.set(componentTagName, componentBindingName);
|
|
42
|
+
if (scriptSetup) {
|
|
43
|
+
for (const name of scriptSetup.returnNames) if (/^[A-Z]/.test(name) && scriptSetup.imports.some((imp) => importDeclaresName(imp, name))) componentNames.set(name, name);
|
|
44
|
+
}
|
|
45
|
+
const components = componentNames.size > 0 ? ` components: { ${[...componentNames].map(([name, value]) => `${JSON.stringify(name)}: ${value}`).join(", ")} },\n` : "";
|
|
46
|
+
if (scriptSetup && hasSetup && isolatedSetup) return `
|
|
47
|
+
export const ${variantComponentName} = __museaDefineComponent({
|
|
48
|
+
name: '${variantComponentName}',
|
|
49
|
+
${components} setup() {
|
|
50
|
+
${scriptSetup.setupBody.join("\n")}
|
|
51
|
+
return ${setupReturn};
|
|
52
|
+
},
|
|
53
|
+
template: \`${fullTemplate}\`,
|
|
54
|
+
});
|
|
55
|
+
`;
|
|
56
|
+
if (scriptSetup && hasSetup) return `
|
|
57
|
+
export const ${variantComponentName} = __museaDefineComponent({
|
|
58
|
+
name: '${variantComponentName}',
|
|
59
|
+
${components} setup() {
|
|
60
|
+
return __museaSharedSetup;
|
|
61
|
+
},
|
|
62
|
+
template: \`${fullTemplate}\`,
|
|
63
|
+
});
|
|
64
|
+
`;
|
|
65
|
+
return `
|
|
66
|
+
export const ${variantComponentName} = {
|
|
67
|
+
name: '${variantComponentName}',
|
|
68
|
+
${components} template: \`${fullTemplate}\`,
|
|
69
|
+
};
|
|
70
|
+
`;
|
|
71
|
+
}
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region src/art-component.ts
|
|
74
|
+
/**
|
|
75
|
+
* Resolve which component an art file demonstrates, and under what tag.
|
|
76
|
+
*
|
|
77
|
+
* Shared by the art module and by the per-variant SFC compiler (#3857) so both
|
|
78
|
+
* agree on the import path, the tag `<Self>` expands to, and the binding name.
|
|
79
|
+
* The parsed `<script setup>` is passed in rather than parsed here, so this
|
|
80
|
+
* module does not have to import back from `art-module.ts`.
|
|
81
|
+
*/
|
|
82
|
+
function componentNameFromSource$1(source) {
|
|
83
|
+
const withoutQuery = source.split(/[?#]/, 1)[0] || source;
|
|
84
|
+
const filename = path.basename(withoutQuery);
|
|
85
|
+
const extension = path.extname(filename);
|
|
86
|
+
const name = toPascalCase(extension ? filename.slice(0, -extension.length) : filename);
|
|
87
|
+
return name === "Variant" ? "MuseaComponent" : name;
|
|
88
|
+
}
|
|
89
|
+
function resolveArtComponent(art, filePath, scriptSetup, options = {}) {
|
|
90
|
+
let componentImportPath;
|
|
91
|
+
let componentTagName;
|
|
92
|
+
let componentBindingName = "__MuseaComponent";
|
|
93
|
+
const defineArtComponentName = scriptSetup?.defineArtComponentName;
|
|
94
|
+
const defineArtComponentSource = scriptSetup?.defineArtComponentSource;
|
|
95
|
+
if (art.isInline && art.componentPath) {
|
|
96
|
+
componentImportPath = options.root ? resolveComponentSourcePath(art, filePath, allowedSourceRoots(options.root, options.scanRoots ?? [])) ?? void 0 : art.componentPath;
|
|
97
|
+
componentTagName = "MuseaComponent";
|
|
98
|
+
componentBindingName = componentTagName;
|
|
99
|
+
} else if (defineArtComponentSource || art.metadata.component) {
|
|
100
|
+
const componentSource = defineArtComponentSource ?? art.metadata.component;
|
|
101
|
+
if (componentSource) {
|
|
102
|
+
const sourceArt = componentSource === art.metadata.component ? art : {
|
|
103
|
+
...art,
|
|
104
|
+
metadata: {
|
|
105
|
+
...art.metadata,
|
|
106
|
+
component: componentSource
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
componentImportPath = options.root ? resolveComponentSourcePath(sourceArt, filePath, allowedSourceRoots(options.root, options.scanRoots ?? [])) ?? void 0 : path.isAbsolute(componentSource) ? componentSource : path.resolve(path.dirname(filePath), componentSource);
|
|
110
|
+
}
|
|
111
|
+
componentTagName = defineArtComponentName ?? (art.metadata.component ? componentNameFromSource$1(art.metadata.component) : "MuseaComponent");
|
|
112
|
+
componentBindingName = componentTagName;
|
|
113
|
+
}
|
|
114
|
+
return {
|
|
115
|
+
componentImportPath,
|
|
116
|
+
componentTagName,
|
|
117
|
+
componentBindingName
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** Expand `<Self>` in a variant template to the resolved component tag. */
|
|
121
|
+
function expandSelfTag(template, componentTagName) {
|
|
122
|
+
if (!componentTagName) return template;
|
|
123
|
+
return template.replace(/<Self(?=[\s/>])/g, `<${componentTagName}`).replace(/<\/Self\s*>/g, `</${componentTagName}>`);
|
|
124
|
+
}
|
|
125
|
+
//#endregion
|
|
126
|
+
//#region src/art-module.ts
|
|
127
|
+
/**
|
|
128
|
+
* Art module generation for Musea.
|
|
129
|
+
*
|
|
130
|
+
* Generates the virtual ES modules that represent parsed `.art.vue` files,
|
|
131
|
+
* including variant component definitions and script setup handling.
|
|
132
|
+
*/
|
|
133
|
+
/**
|
|
134
|
+
* Extract the content of the first <script setup> block from a Vue SFC source.
|
|
135
|
+
*/
|
|
136
|
+
function extractScriptSetupContent(source) {
|
|
137
|
+
return source.match(/<script\s+[^>]*setup[^>]*>([\s\S]*?)<\/script>/)?.[1]?.trim();
|
|
138
|
+
}
|
|
139
|
+
function extractScriptSetupIsolated(source) {
|
|
140
|
+
const match = source.match(/<script\s+([^>]*)\bsetup\b([^>]*)>/);
|
|
141
|
+
if (!match) return true;
|
|
142
|
+
const isolate = `${match[1] ?? ""} ${match[2] ?? ""}`.match(/\bisolate\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/);
|
|
143
|
+
return (isolate?.[1] ?? isolate?.[2] ?? isolate?.[3]) !== "false";
|
|
144
|
+
}
|
|
145
|
+
function resolveRelativeSpecifier(specifier, artDir) {
|
|
146
|
+
if (!specifier.startsWith(".")) return specifier;
|
|
147
|
+
return path.resolve(artDir, specifier);
|
|
148
|
+
}
|
|
149
|
+
function rewriteRelativeImportStatement(statement, artDir) {
|
|
150
|
+
return statement.replace(/\bfrom\s+(['"])([^'"]+)\1/g, (_match, quote, specifier) => `from ${quote}${resolveRelativeSpecifier(specifier, artDir)}${quote}`).replace(/^(\s*import\s+)(['"])([^'"]+)\2(\s*;?\s*)$/s, (_match, prefix, quote, specifier, suffix) => `${prefix}${quote}${resolveRelativeSpecifier(specifier, artDir)}${quote}${suffix}`);
|
|
151
|
+
}
|
|
152
|
+
function countCharBalance(source, openChar, closeChar) {
|
|
153
|
+
let balance = 0;
|
|
154
|
+
for (const char of source) if (char === openChar) balance++;
|
|
155
|
+
else if (char === closeChar) balance--;
|
|
156
|
+
return balance;
|
|
157
|
+
}
|
|
158
|
+
function isCompleteImportStatement(statement) {
|
|
159
|
+
const trimmed = statement.trim();
|
|
160
|
+
if (!trimmed.startsWith("import ")) return false;
|
|
161
|
+
if (countCharBalance(statement, "{", "}") > 0) return false;
|
|
162
|
+
return /^import\s+[\s\S]+?\s+from\s+['"][^'"]+['"]\s*;?$/s.test(trimmed) || /^import\s+['"][^'"]+['"]\s*;?$/s.test(trimmed);
|
|
163
|
+
}
|
|
164
|
+
function splitTopLevelCommaList(source) {
|
|
165
|
+
const parts = [];
|
|
166
|
+
let current = "";
|
|
167
|
+
let braceDepth = 0;
|
|
168
|
+
let bracketDepth = 0;
|
|
169
|
+
let parenDepth = 0;
|
|
170
|
+
for (const char of source) {
|
|
171
|
+
if (char === "," && braceDepth === 0 && bracketDepth === 0 && parenDepth === 0) {
|
|
172
|
+
const trimmed = current.trim();
|
|
173
|
+
if (trimmed) parts.push(trimmed);
|
|
174
|
+
current = "";
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
current += char;
|
|
178
|
+
if (char === "{") braceDepth++;
|
|
179
|
+
else if (char === "}") braceDepth--;
|
|
180
|
+
else if (char === "[") bracketDepth++;
|
|
181
|
+
else if (char === "]") bracketDepth--;
|
|
182
|
+
else if (char === "(") parenDepth++;
|
|
183
|
+
else if (char === ")") parenDepth--;
|
|
184
|
+
}
|
|
185
|
+
const trimmed = current.trim();
|
|
186
|
+
if (trimmed) parts.push(trimmed);
|
|
187
|
+
return parts;
|
|
188
|
+
}
|
|
189
|
+
function collectImportedNames(statement, returnNames) {
|
|
190
|
+
const fromMatch = statement.replace(/\s+/g, " ").trim().replace(/;$/, "").match(/^import\s+(type\s+)?(.+?)\s+from\s+['"][^'"]+['"]$/);
|
|
191
|
+
if (!fromMatch) return;
|
|
192
|
+
if (fromMatch[1]) return;
|
|
193
|
+
const specifierParts = splitTopLevelCommaList(fromMatch[2].trim());
|
|
194
|
+
const defaultOrNamespace = specifierParts[0]?.trim() ?? "";
|
|
195
|
+
const trailing = specifierParts.slice(1).join(", ").trim();
|
|
196
|
+
if (defaultOrNamespace && !defaultOrNamespace.startsWith("{")) {
|
|
197
|
+
const namespaceMatch = defaultOrNamespace.match(/^\*\s+as\s+([A-Za-z_$][\w$]*)$/);
|
|
198
|
+
if (namespaceMatch) returnNames.add(namespaceMatch[1]);
|
|
199
|
+
else if (!defaultOrNamespace.startsWith("type ")) returnNames.add(defaultOrNamespace);
|
|
200
|
+
}
|
|
201
|
+
const namedBlock = defaultOrNamespace.startsWith("{") ? defaultOrNamespace : trailing.startsWith("{") ? trailing : "";
|
|
202
|
+
if (!namedBlock) return;
|
|
203
|
+
const namedContent = namedBlock.slice(1, -1);
|
|
204
|
+
for (const part of splitTopLevelCommaList(namedContent)) {
|
|
205
|
+
const trimmed = part.trim();
|
|
206
|
+
if (!trimmed || trimmed.startsWith("type ")) continue;
|
|
207
|
+
const alias = trimmed.split(/\s+as\s+/).pop()?.trim();
|
|
208
|
+
if (alias) returnNames.add(alias);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
function importDeclaresName(statement, name) {
|
|
212
|
+
const names = /* @__PURE__ */ new Set();
|
|
213
|
+
collectImportedNames(statement, names);
|
|
214
|
+
return names.has(name);
|
|
215
|
+
}
|
|
216
|
+
function collectObjectDestructuredNames(statement, returnNames) {
|
|
217
|
+
const match = statement.match(/^(?:export\s+)?(?:const|let|var)\s+\{([\s\S]*?)\}\s*=/);
|
|
218
|
+
if (!match) return;
|
|
219
|
+
for (const part of splitTopLevelCommaList(match[1])) {
|
|
220
|
+
let name = part.trim();
|
|
221
|
+
if (!name) continue;
|
|
222
|
+
if (name.startsWith("...")) name = name.slice(3).trim();
|
|
223
|
+
else if (name.includes(":")) name = name.split(":").pop().trim();
|
|
224
|
+
else if (name.includes("=")) name = name.split("=")[0].trim();
|
|
225
|
+
if (name.includes("=")) name = name.split("=")[0].trim();
|
|
226
|
+
if (/^[A-Za-z_$][\w$]*$/.test(name)) returnNames.add(name);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
function collectArrayDestructuredNames(statement, returnNames) {
|
|
230
|
+
const match = statement.match(/^(?:export\s+)?(?:const|let|var)\s+\[([\s\S]*?)\]\s*=/);
|
|
231
|
+
if (!match) return;
|
|
232
|
+
for (const part of splitTopLevelCommaList(match[1])) {
|
|
233
|
+
let name = part.trim();
|
|
234
|
+
if (!name) continue;
|
|
235
|
+
if (name.startsWith("...")) name = name.slice(3).trim();
|
|
236
|
+
if (name.includes("=")) name = name.split("=")[0].trim();
|
|
237
|
+
if (/^[A-Za-z_$][\w$]*$/.test(name)) returnNames.add(name);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
function collectTopLevelReturnNames(setupBody, returnNames) {
|
|
241
|
+
let braceDepth = 0;
|
|
242
|
+
for (let i = 0; i < setupBody.length; i++) {
|
|
243
|
+
const line = setupBody[i];
|
|
244
|
+
const trimmed = line.trim();
|
|
245
|
+
if (braceDepth === 0) {
|
|
246
|
+
if (/^(?:export\s+)?(?:const|let|var)\s+\{/.test(trimmed)) {
|
|
247
|
+
const statementLines = [line];
|
|
248
|
+
let balance = countCharBalance(line, "{", "}") + countCharBalance(line, "[", "]") + countCharBalance(line, "(", ")");
|
|
249
|
+
while (balance > 0 && i + 1 < setupBody.length) {
|
|
250
|
+
i++;
|
|
251
|
+
statementLines.push(setupBody[i]);
|
|
252
|
+
balance += countCharBalance(setupBody[i], "{", "}") + countCharBalance(setupBody[i], "[", "]") + countCharBalance(setupBody[i], "(", ")");
|
|
253
|
+
}
|
|
254
|
+
collectObjectDestructuredNames(statementLines.join("\n"), returnNames);
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
if (/^(?:export\s+)?(?:const|let|var)\s+\[/.test(trimmed)) {
|
|
258
|
+
const statementLines = [line];
|
|
259
|
+
let balance = countCharBalance(line, "{", "}") + countCharBalance(line, "[", "]") + countCharBalance(line, "(", ")");
|
|
260
|
+
while (balance > 0 && i + 1 < setupBody.length) {
|
|
261
|
+
i++;
|
|
262
|
+
statementLines.push(setupBody[i]);
|
|
263
|
+
balance += countCharBalance(setupBody[i], "{", "}") + countCharBalance(setupBody[i], "[", "]") + countCharBalance(setupBody[i], "(", ")");
|
|
264
|
+
}
|
|
265
|
+
collectArrayDestructuredNames(statementLines.join("\n"), returnNames);
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
const constMatch = trimmed.match(/^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)/);
|
|
269
|
+
if (constMatch) returnNames.add(constMatch[1]);
|
|
270
|
+
const functionMatch = trimmed.match(/^(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(/);
|
|
271
|
+
if (functionMatch) returnNames.add(functionMatch[1]);
|
|
272
|
+
const classMatch = trimmed.match(/^(?:export\s+)?class\s+([A-Za-z_$][\w$]*)\b/);
|
|
273
|
+
if (classMatch) returnNames.add(classMatch[1]);
|
|
274
|
+
}
|
|
275
|
+
braceDepth += countCharBalance(line, "{", "}");
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Parse script setup content into imports and setup body.
|
|
280
|
+
* Returns the import lines, setup body lines, and all identifiers to expose.
|
|
281
|
+
*/
|
|
282
|
+
function parseScriptSetupForArt(content) {
|
|
283
|
+
const lines = content.split("\n");
|
|
284
|
+
const imports = [];
|
|
285
|
+
const setupBody = [];
|
|
286
|
+
const returnNames = /* @__PURE__ */ new Set();
|
|
287
|
+
let currentImport = null;
|
|
288
|
+
const defineArtComponent = extractDefineArtComponent(content);
|
|
289
|
+
let defineArtBalance = 0;
|
|
290
|
+
for (const line of lines) {
|
|
291
|
+
const trimmed = line.trim();
|
|
292
|
+
if (defineArtBalance > 0) {
|
|
293
|
+
defineArtBalance += countCharBalance(line, "(", ")");
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
if (currentImport) {
|
|
297
|
+
currentImport.push(line);
|
|
298
|
+
const statement = currentImport.join("\n");
|
|
299
|
+
if (isCompleteImportStatement(statement)) {
|
|
300
|
+
imports.push(statement);
|
|
301
|
+
collectImportedNames(statement, returnNames);
|
|
302
|
+
currentImport = null;
|
|
303
|
+
}
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
if (trimmed.startsWith("import ")) {
|
|
307
|
+
currentImport = [line];
|
|
308
|
+
const statement = currentImport.join("\n");
|
|
309
|
+
if (isCompleteImportStatement(statement)) {
|
|
310
|
+
imports.push(statement);
|
|
311
|
+
collectImportedNames(statement, returnNames);
|
|
312
|
+
currentImport = null;
|
|
313
|
+
}
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
if (isDefineArtLine(trimmed)) {
|
|
317
|
+
defineArtBalance = Math.max(0, countCharBalance(line, "(", ")"));
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
setupBody.push(line);
|
|
321
|
+
}
|
|
322
|
+
if (currentImport) {
|
|
323
|
+
const statement = currentImport.join("\n");
|
|
324
|
+
imports.push(statement);
|
|
325
|
+
collectImportedNames(statement, returnNames);
|
|
326
|
+
}
|
|
327
|
+
collectTopLevelReturnNames(setupBody, returnNames);
|
|
328
|
+
returnNames.delete("type");
|
|
329
|
+
if (defineArtComponent.name) returnNames.delete(defineArtComponent.name);
|
|
330
|
+
return {
|
|
331
|
+
imports,
|
|
332
|
+
setupBody,
|
|
333
|
+
returnNames: [...returnNames],
|
|
334
|
+
defineArtComponentName: defineArtComponent.name,
|
|
335
|
+
defineArtComponentSource: defineArtComponent.source
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
function extractDefineArtComponent(content) {
|
|
339
|
+
const sourceMatch = content.match(/\bdefineArt\s*\(\s*(['"])([^'"]+)\1/);
|
|
340
|
+
if (sourceMatch) return {
|
|
341
|
+
name: componentNameFromSource(sourceMatch[2]),
|
|
342
|
+
source: sourceMatch[2]
|
|
343
|
+
};
|
|
344
|
+
return { name: content.match(/\bdefineArt\s*\(\s*([A-Za-z_$][\w$]*)/)?.[1] };
|
|
345
|
+
}
|
|
346
|
+
function componentNameFromSource(source) {
|
|
347
|
+
const withoutQuery = source.split(/[?#]/, 1)[0] || source;
|
|
348
|
+
const filename = path.basename(withoutQuery);
|
|
349
|
+
const extension = path.extname(filename);
|
|
350
|
+
const name = toPascalCase(extension ? filename.slice(0, -extension.length) : filename);
|
|
351
|
+
return name === "Variant" ? "MuseaComponent" : name;
|
|
352
|
+
}
|
|
353
|
+
function isDefineArtLine(trimmed) {
|
|
354
|
+
return /\bdefineArt\s*\(/.test(trimmed);
|
|
355
|
+
}
|
|
356
|
+
function generateArtModule(art, filePath, options = {}) {
|
|
357
|
+
let componentImportPath;
|
|
358
|
+
let componentTagName;
|
|
359
|
+
let componentBindingName = "__MuseaComponent";
|
|
360
|
+
const scriptSetup = art.scriptSetupContent ? parseScriptSetupForArt(art.scriptSetupContent) : null;
|
|
361
|
+
const defineArtComponentName = scriptSetup?.defineArtComponentName;
|
|
362
|
+
const defineArtComponentSource = scriptSetup?.defineArtComponentSource;
|
|
363
|
+
if (art.isInline && art.componentPath) {
|
|
364
|
+
componentImportPath = options.root ? resolveComponentSourcePath(art, filePath, allowedSourceRoots(options.root, options.scanRoots ?? [])) ?? void 0 : art.componentPath;
|
|
365
|
+
componentTagName = "MuseaComponent";
|
|
366
|
+
} else if (defineArtComponentSource || art.metadata.component) {
|
|
367
|
+
const componentSource = defineArtComponentSource ?? art.metadata.component;
|
|
368
|
+
if (componentSource) {
|
|
369
|
+
const sourceArt = componentSource === art.metadata.component ? art : {
|
|
370
|
+
...art,
|
|
371
|
+
metadata: {
|
|
372
|
+
...art.metadata,
|
|
373
|
+
component: componentSource
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
componentImportPath = options.root ? resolveComponentSourcePath(sourceArt, filePath, allowedSourceRoots(options.root, options.scanRoots ?? [])) ?? void 0 : path.isAbsolute(componentSource) ? componentSource : path.resolve(path.dirname(filePath), componentSource);
|
|
377
|
+
}
|
|
378
|
+
componentTagName = defineArtComponentName ?? (art.metadata.component ? componentNameFromSource(art.metadata.component) : "MuseaComponent");
|
|
379
|
+
componentBindingName = componentTagName;
|
|
380
|
+
}
|
|
381
|
+
const hasSetupBody = scriptSetup?.setupBody.some((line) => line.trim().length > 0) ?? false;
|
|
382
|
+
const hasSetup = !!scriptSetup && (hasSetupBody || scriptSetup.returnNames.length > 0);
|
|
383
|
+
let code = `
|
|
384
|
+
// Auto-generated module for: ${path.basename(filePath)}
|
|
385
|
+
`;
|
|
386
|
+
if (options.vueVersion === 2 && hasSetup) code += `import { defineComponent as __museaDefineComponent } from 'vue';\n`;
|
|
387
|
+
if (scriptSetup) {
|
|
388
|
+
const artDir = path.dirname(filePath);
|
|
389
|
+
for (const imp of scriptSetup.imports) {
|
|
390
|
+
const resolved = rewriteRelativeImportStatement(imp, artDir);
|
|
391
|
+
code += `${resolved}\n`;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
if (componentImportPath && componentTagName) {
|
|
395
|
+
if (!scriptSetup?.imports.some((imp) => importDeclaresName(imp, componentBindingName))) code += `import ${componentBindingName} from ${JSON.stringify(componentImportPath)};\n`;
|
|
396
|
+
code += `export const __component__ = ${componentBindingName};\n`;
|
|
397
|
+
}
|
|
398
|
+
code += `
|
|
399
|
+
export const metadata = ${JSON.stringify(art.metadata)};
|
|
400
|
+
export const variants = ${JSON.stringify(art.variants)};
|
|
401
|
+
export const __styles__ = ${JSON.stringify(art.styleBlocks ?? [])};
|
|
402
|
+
`;
|
|
403
|
+
const setupReturn = `{ ${scriptSetup?.returnNames.join(", ") ?? ""} }`;
|
|
404
|
+
const isolatedSetup = art.scriptSetupIsolated !== false;
|
|
405
|
+
if (scriptSetup && hasSetup && !isolatedSetup) code += `
|
|
406
|
+
const __museaSharedSetup = (() => {
|
|
407
|
+
${scriptSetup.setupBody.join("\n")}
|
|
408
|
+
return ${setupReturn};
|
|
409
|
+
})();
|
|
410
|
+
`;
|
|
411
|
+
for (const variant of art.variants) {
|
|
412
|
+
const variantComponentName = toPascalCase(variant.name);
|
|
413
|
+
const template = expandSelfTag(variant.template, componentTagName);
|
|
414
|
+
if (options.vueVersion === 2) {
|
|
415
|
+
code += emitLegacyVariant({
|
|
416
|
+
variantComponentName,
|
|
417
|
+
variantName: variant.name,
|
|
418
|
+
template,
|
|
419
|
+
componentTagName,
|
|
420
|
+
componentBindingName,
|
|
421
|
+
scriptSetup,
|
|
422
|
+
hasSetup,
|
|
423
|
+
isolatedSetup,
|
|
424
|
+
setupReturn,
|
|
425
|
+
importDeclaresName
|
|
426
|
+
});
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
const variantModuleId = `virtual:musea-variant:${filePath}:${encodeURIComponent(variant.name)}`;
|
|
430
|
+
code += `
|
|
431
|
+
import ${variantComponentName} from ${JSON.stringify(variantModuleId)};
|
|
432
|
+
export { ${variantComponentName} };
|
|
433
|
+
`;
|
|
434
|
+
}
|
|
435
|
+
const defaultVariant = art.variants.find((v) => v.isDefault) || art.variants[0];
|
|
436
|
+
if (defaultVariant) code += `
|
|
437
|
+
export default ${toPascalCase(defaultVariant.name)};
|
|
438
|
+
`;
|
|
439
|
+
return code;
|
|
440
|
+
}
|
|
441
|
+
//#endregion
|
|
442
|
+
//#region src/art-order.ts
|
|
443
|
+
function sortedArts(arts) {
|
|
444
|
+
return [...arts].sort(compareArtFiles);
|
|
445
|
+
}
|
|
446
|
+
function compareArtFiles(a, b) {
|
|
447
|
+
const order = compareOrder(a.metadata.order, b.metadata.order);
|
|
448
|
+
if (order !== 0) return order;
|
|
449
|
+
const title = a.metadata.title.localeCompare(b.metadata.title, void 0, { numeric: true });
|
|
450
|
+
if (title !== 0) return title;
|
|
451
|
+
return a.path.localeCompare(b.path, void 0, { numeric: true });
|
|
452
|
+
}
|
|
453
|
+
function compareOrder(a, b) {
|
|
454
|
+
if (a === void 0 && b === void 0) return 0;
|
|
455
|
+
if (a === void 0) return 1;
|
|
456
|
+
if (b === void 0) return -1;
|
|
457
|
+
return a - b;
|
|
458
|
+
}
|
|
459
|
+
//#endregion
|
|
460
|
+
//#region src/tokens/native.ts
|
|
461
|
+
function tokenNative() {
|
|
462
|
+
const native = loadNative();
|
|
463
|
+
return {
|
|
464
|
+
parseDesignTokensFromPath(path) {
|
|
465
|
+
return normalizeCategories(parseJsonResult(native.parseDesignTokensFromPath(path)));
|
|
466
|
+
},
|
|
467
|
+
buildDesignTokenMap(categories) {
|
|
468
|
+
return nullRecord(parseJsonResult(native.buildDesignTokenMap(JSON.stringify(categories))));
|
|
469
|
+
},
|
|
470
|
+
resolveDesignTokenReferences(categories) {
|
|
471
|
+
const resolved = parseJsonResult(native.resolveDesignTokenReferences(JSON.stringify(categories)));
|
|
472
|
+
return {
|
|
473
|
+
...resolved,
|
|
474
|
+
categories: normalizeCategories(resolved.categories),
|
|
475
|
+
tokenMap: nullRecord(resolved.tokenMap)
|
|
476
|
+
};
|
|
477
|
+
},
|
|
478
|
+
flattenDesignTokenCategories(categories) {
|
|
479
|
+
return parseJsonResult(native.flattenDesignTokenCategories(JSON.stringify(categories)));
|
|
480
|
+
},
|
|
481
|
+
generateDesignTokensMarkdown(categories, generatedAt) {
|
|
482
|
+
return native.generateDesignTokensMarkdown(JSON.stringify(categories), generatedAt);
|
|
483
|
+
},
|
|
484
|
+
validateDesignTokenReference(tokenMap, reference, selfPath) {
|
|
485
|
+
return parseJsonResult(native.validateDesignTokenReference(JSON.stringify(tokenMap), reference, selfPath));
|
|
486
|
+
},
|
|
487
|
+
findDependentDesignTokens(tokenMap, targetPath) {
|
|
488
|
+
return native.findDependentDesignTokens(JSON.stringify(tokenMap), targetPath);
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
function parseJsonResult(value) {
|
|
493
|
+
if (typeof value === "string") return JSON.parse(value);
|
|
494
|
+
return value;
|
|
495
|
+
}
|
|
496
|
+
function normalizeCategories(categories) {
|
|
497
|
+
for (const category of categories) {
|
|
498
|
+
category.tokens = nullRecord(Object.fromEntries(sortTokenEntries(category.tokens)));
|
|
499
|
+
if (category.subcategories) normalizeCategories(category.subcategories);
|
|
500
|
+
}
|
|
501
|
+
return categories;
|
|
502
|
+
}
|
|
503
|
+
function sortTokenEntries(tokens) {
|
|
504
|
+
return Object.entries(tokens).sort((a, b) => {
|
|
505
|
+
const order = compareTokenOrder(a[1], b[1]);
|
|
506
|
+
if (order !== 0) return order;
|
|
507
|
+
return a[0].localeCompare(b[0], void 0, { numeric: true });
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
function compareTokenOrder(a, b) {
|
|
511
|
+
const aOrder = tokenOrder(a);
|
|
512
|
+
const bOrder = tokenOrder(b);
|
|
513
|
+
if (aOrder === void 0 && bOrder === void 0) return 0;
|
|
514
|
+
if (aOrder === void 0) return 1;
|
|
515
|
+
if (bOrder === void 0) return -1;
|
|
516
|
+
return aOrder - bOrder;
|
|
517
|
+
}
|
|
518
|
+
function tokenOrder(token) {
|
|
519
|
+
const order = token.attributes?.order;
|
|
520
|
+
if (typeof order === "number" && Number.isFinite(order)) return order;
|
|
521
|
+
if (typeof order === "string") {
|
|
522
|
+
const parsed = Number(order);
|
|
523
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
function nullRecord(record) {
|
|
527
|
+
return Object.assign(Object.create(null), record);
|
|
528
|
+
}
|
|
529
|
+
//#endregion
|
|
530
|
+
//#region src/tokens/tailwind.ts
|
|
531
|
+
const TAILWIND_TOKEN_EXTENSIONS = new Set([
|
|
532
|
+
".css",
|
|
533
|
+
".pcss",
|
|
534
|
+
".postcss"
|
|
535
|
+
]);
|
|
536
|
+
const VARIABLE_DECLARATION_RE = /(--[A-Za-z0-9_-]+)\s*:\s*([^;{}]+);/g;
|
|
537
|
+
const CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//g;
|
|
538
|
+
const NAMESPACE_MAPPINGS = [
|
|
539
|
+
{
|
|
540
|
+
prefix: "inset-shadow",
|
|
541
|
+
category: "shadow",
|
|
542
|
+
pathPrefix: ["inset"],
|
|
543
|
+
type: "shadow"
|
|
544
|
+
},
|
|
545
|
+
{
|
|
546
|
+
prefix: "drop-shadow",
|
|
547
|
+
category: "shadow",
|
|
548
|
+
pathPrefix: ["drop"],
|
|
549
|
+
type: "shadow"
|
|
550
|
+
},
|
|
551
|
+
{
|
|
552
|
+
prefix: "font-weight",
|
|
553
|
+
category: "typography",
|
|
554
|
+
pathPrefix: ["fontWeight"],
|
|
555
|
+
type: "fontWeight"
|
|
556
|
+
},
|
|
557
|
+
{
|
|
558
|
+
prefix: "color",
|
|
559
|
+
category: "color",
|
|
560
|
+
type: "color"
|
|
561
|
+
},
|
|
562
|
+
{
|
|
563
|
+
prefix: "spacing",
|
|
564
|
+
category: "spacing",
|
|
565
|
+
type: "dimension"
|
|
566
|
+
},
|
|
567
|
+
{
|
|
568
|
+
prefix: "font",
|
|
569
|
+
category: "typography",
|
|
570
|
+
pathPrefix: ["font"],
|
|
571
|
+
type: "fontFamily"
|
|
572
|
+
},
|
|
573
|
+
{
|
|
574
|
+
prefix: "text",
|
|
575
|
+
category: "typography",
|
|
576
|
+
pathPrefix: ["fontSize"],
|
|
577
|
+
type: "dimension"
|
|
578
|
+
},
|
|
579
|
+
{
|
|
580
|
+
prefix: "leading",
|
|
581
|
+
category: "typography",
|
|
582
|
+
pathPrefix: ["lineHeight"],
|
|
583
|
+
type: "number"
|
|
584
|
+
},
|
|
585
|
+
{
|
|
586
|
+
prefix: "tracking",
|
|
587
|
+
category: "typography",
|
|
588
|
+
pathPrefix: ["letterSpacing"],
|
|
589
|
+
type: "dimension"
|
|
590
|
+
},
|
|
591
|
+
{
|
|
592
|
+
prefix: "radius",
|
|
593
|
+
category: "radius",
|
|
594
|
+
type: "dimension"
|
|
595
|
+
},
|
|
596
|
+
{
|
|
597
|
+
prefix: "shadow",
|
|
598
|
+
category: "shadow",
|
|
599
|
+
type: "shadow"
|
|
600
|
+
},
|
|
601
|
+
{
|
|
602
|
+
prefix: "breakpoint",
|
|
603
|
+
category: "breakpoint",
|
|
604
|
+
type: "dimension"
|
|
605
|
+
},
|
|
606
|
+
{
|
|
607
|
+
prefix: "container",
|
|
608
|
+
category: "container",
|
|
609
|
+
type: "dimension"
|
|
610
|
+
},
|
|
611
|
+
{
|
|
612
|
+
prefix: "ease",
|
|
613
|
+
category: "easing",
|
|
614
|
+
type: "cubicBezier"
|
|
615
|
+
},
|
|
616
|
+
{
|
|
617
|
+
prefix: "animate",
|
|
618
|
+
category: "animation",
|
|
619
|
+
type: "transition"
|
|
620
|
+
},
|
|
621
|
+
{
|
|
622
|
+
prefix: "blur",
|
|
623
|
+
category: "blur",
|
|
624
|
+
type: "dimension"
|
|
625
|
+
},
|
|
626
|
+
{
|
|
627
|
+
prefix: "perspective",
|
|
628
|
+
category: "perspective",
|
|
629
|
+
type: "dimension"
|
|
630
|
+
},
|
|
631
|
+
{
|
|
632
|
+
prefix: "aspect",
|
|
633
|
+
category: "aspectRatio",
|
|
634
|
+
type: "number"
|
|
635
|
+
}
|
|
636
|
+
];
|
|
637
|
+
async function isTailwindTokenPath(tokensPath) {
|
|
638
|
+
const stat = await fs.promises.stat(tokensPath).catch(() => null);
|
|
639
|
+
if (!stat) return false;
|
|
640
|
+
if (stat.isFile()) return TAILWIND_TOKEN_EXTENSIONS.has(path.extname(tokensPath));
|
|
641
|
+
if (!stat.isDirectory()) return false;
|
|
642
|
+
return (await fs.promises.readdir(tokensPath, { withFileTypes: true })).some((entry) => entry.isFile() && TAILWIND_TOKEN_EXTENSIONS.has(path.extname(entry.name)));
|
|
643
|
+
}
|
|
644
|
+
async function parseTailwindTokens(tokensPath) {
|
|
645
|
+
const files = await collectTailwindTokenFiles(tokensPath);
|
|
646
|
+
const candidates = [];
|
|
647
|
+
for (const file of files) {
|
|
648
|
+
const css = await fs.promises.readFile(file, "utf-8");
|
|
649
|
+
candidates.push(...extractTailwindTokenCandidates(css));
|
|
650
|
+
}
|
|
651
|
+
return normalizeCategories(buildCategories(candidates));
|
|
652
|
+
}
|
|
653
|
+
async function collectTailwindTokenFiles(tokensPath) {
|
|
654
|
+
if ((await fs.promises.stat(tokensPath)).isFile()) return [tokensPath];
|
|
655
|
+
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();
|
|
656
|
+
}
|
|
657
|
+
function extractTailwindTokenCandidates(css) {
|
|
658
|
+
const source = css.replace(CSS_COMMENT_RE, "");
|
|
659
|
+
const candidates = [];
|
|
660
|
+
let match;
|
|
661
|
+
VARIABLE_DECLARATION_RE.lastIndex = 0;
|
|
662
|
+
while ((match = VARIABLE_DECLARATION_RE.exec(source)) !== null) {
|
|
663
|
+
const variable = match[1];
|
|
664
|
+
const value = match[2].trim();
|
|
665
|
+
const mapped = mapTokenVariable(variable, value);
|
|
666
|
+
if (!mapped || !value) continue;
|
|
667
|
+
candidates.push({
|
|
668
|
+
variable,
|
|
669
|
+
value,
|
|
670
|
+
...mapped
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
return candidates;
|
|
674
|
+
}
|
|
675
|
+
function mapTokenVariable(variable, value) {
|
|
676
|
+
const tailwind = mapTailwindVariable(variable);
|
|
677
|
+
if (tailwind) return {
|
|
678
|
+
...tailwind,
|
|
679
|
+
description: `Tailwind theme variable ${variable}`
|
|
680
|
+
};
|
|
681
|
+
const segments = variable.replace(/^--/, "").split("-").filter(Boolean);
|
|
682
|
+
const category = segments[0];
|
|
683
|
+
if (!category) return null;
|
|
684
|
+
const rest = segments.slice(1).join("-");
|
|
685
|
+
return {
|
|
686
|
+
category,
|
|
687
|
+
path: rest ? [rest] : ["DEFAULT"],
|
|
688
|
+
type: inferCustomPropertyType(value),
|
|
689
|
+
description: `Custom property ${variable}`
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
function mapTailwindVariable(variable) {
|
|
693
|
+
const name = variable.replace(/^--/, "");
|
|
694
|
+
const mapping = NAMESPACE_MAPPINGS.find((candidate) => name === candidate.prefix || name.startsWith(`${candidate.prefix}-`));
|
|
695
|
+
if (!mapping) return null;
|
|
696
|
+
const rest = name === mapping.prefix ? "DEFAULT" : name.slice(mapping.prefix.length + 1);
|
|
697
|
+
const pathParts = [...mapping.pathPrefix ?? [], ...tailwindNameToPath(rest)];
|
|
698
|
+
if (pathParts.length === 0) return null;
|
|
699
|
+
return {
|
|
700
|
+
category: mapping.category,
|
|
701
|
+
path: pathParts,
|
|
702
|
+
type: mapping.type
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
function inferCustomPropertyType(value) {
|
|
706
|
+
const trimmed = value.trim();
|
|
707
|
+
if (/^(?:#|rgba?\(|hsla?\(|oklch\(|oklab\(|color-mix\(|color\()/i.test(trimmed)) return "color";
|
|
708
|
+
if (/^-?(?:\d+\.\d+|\d+)(?:px|rem|em|vh|vw|vmin|vmax|%)$/i.test(trimmed)) return "dimension";
|
|
709
|
+
if (/^-?(?:\d+\.\d+|\d+)$/.test(trimmed)) return "number";
|
|
710
|
+
return "other";
|
|
711
|
+
}
|
|
712
|
+
function tailwindNameToPath(name) {
|
|
713
|
+
if (!name || name === "DEFAULT") return ["DEFAULT"];
|
|
714
|
+
const parts = name.split("-").filter(Boolean);
|
|
715
|
+
if (parts.length <= 1) return parts;
|
|
716
|
+
const last = parts[parts.length - 1];
|
|
717
|
+
if (/^\d+$/.test(last)) return [...parts.slice(0, -1), last];
|
|
718
|
+
return [parts.join("-")];
|
|
719
|
+
}
|
|
720
|
+
function buildCategories(candidates) {
|
|
721
|
+
const variableToPath = /* @__PURE__ */ new Map();
|
|
722
|
+
for (const candidate of candidates) variableToPath.set(candidate.variable, [candidate.category, ...candidate.path].join("."));
|
|
723
|
+
const categoryMap = /* @__PURE__ */ new Map();
|
|
724
|
+
for (const candidate of candidates) {
|
|
725
|
+
const category = categoryMap.get(candidate.category) ?? {
|
|
726
|
+
name: candidate.category,
|
|
727
|
+
tokens: nullRecord({})
|
|
728
|
+
};
|
|
729
|
+
categoryMap.set(candidate.category, category);
|
|
730
|
+
const valueReference = parseTailwindVariableReference(candidate.value);
|
|
731
|
+
const referencedPath = valueReference ? variableToPath.get(valueReference) : void 0;
|
|
732
|
+
const token = {
|
|
733
|
+
value: referencedPath ? `{${referencedPath}}` : candidate.value,
|
|
734
|
+
type: candidate.type,
|
|
735
|
+
description: candidate.description,
|
|
736
|
+
attributes: { tailwindVariable: candidate.variable },
|
|
737
|
+
$tier: referencedPath ? "semantic" : "primitive",
|
|
738
|
+
...referencedPath ? { $reference: referencedPath } : {}
|
|
739
|
+
};
|
|
740
|
+
setCategoryToken(category, candidate.path, token);
|
|
741
|
+
}
|
|
742
|
+
return [...categoryMap.values()];
|
|
743
|
+
}
|
|
744
|
+
function parseTailwindVariableReference(value) {
|
|
745
|
+
return value.match(/^var\(\s*(--[A-Za-z0-9_-]+)\s*(?:,[^)]+)?\)$/)?.[1];
|
|
746
|
+
}
|
|
747
|
+
function setCategoryToken(category, pathParts, token) {
|
|
748
|
+
if (pathParts.length === 1) {
|
|
749
|
+
category.tokens[pathParts[0]] = token;
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
let current = category;
|
|
753
|
+
for (const part of pathParts.slice(0, -1)) {
|
|
754
|
+
current.subcategories ??= [];
|
|
755
|
+
let next = current.subcategories.find((subcategory) => subcategory.name === part);
|
|
756
|
+
if (!next) {
|
|
757
|
+
next = {
|
|
758
|
+
name: part,
|
|
759
|
+
tokens: nullRecord({})
|
|
760
|
+
};
|
|
761
|
+
current.subcategories.push(next);
|
|
762
|
+
}
|
|
763
|
+
current = next;
|
|
764
|
+
}
|
|
765
|
+
current.tokens[pathParts[pathParts.length - 1]] = token;
|
|
766
|
+
}
|
|
767
|
+
//#endregion
|
|
768
|
+
//#region src/tokens/parser.ts
|
|
769
|
+
/**
|
|
770
|
+
* Token parsing utilities for Style Dictionary integration.
|
|
771
|
+
*
|
|
772
|
+
* Thin native binding for design token files (JSON) and directories.
|
|
773
|
+
*/
|
|
774
|
+
/**
|
|
775
|
+
* Parse Style Dictionary tokens file/directory or Tailwind CSS theme variables.
|
|
776
|
+
*/
|
|
777
|
+
async function parseTokens(tokensPath) {
|
|
778
|
+
if (await isTailwindTokenPath(tokensPath)) return parseTailwindTokens(tokensPath);
|
|
779
|
+
return normalizeCategories(tokenNative().parseDesignTokensFromPath(tokensPath));
|
|
780
|
+
}
|
|
781
|
+
//#endregion
|
|
782
|
+
//#region src/tokens/usage.ts
|
|
783
|
+
/**
|
|
784
|
+
* Token usage scanning and value normalization.
|
|
785
|
+
*
|
|
786
|
+
* Scans art file `<style>` blocks for CSS property values that match
|
|
787
|
+
* design token values, and provides value normalization utilities.
|
|
788
|
+
*/
|
|
789
|
+
/**
|
|
790
|
+
* Normalize a token value for comparison.
|
|
791
|
+
* - Lowercase, trim
|
|
792
|
+
* - Leading-zero: `.5rem` -> `0.5rem`
|
|
793
|
+
* - Short hex: `#fff` -> `#ffffff`
|
|
794
|
+
*/
|
|
795
|
+
function normalizeTokenValue(value) {
|
|
796
|
+
let v = String(value).trim().toLowerCase();
|
|
797
|
+
const shortHex = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?$/);
|
|
798
|
+
if (shortHex) {
|
|
799
|
+
const [, r, g, b, a] = shortHex;
|
|
800
|
+
v = a ? `#${r}${r}${g}${g}${b}${b}${a}${a}` : `#${r}${r}${g}${g}${b}${b}`;
|
|
801
|
+
}
|
|
802
|
+
v = v.replace(/(?<![0-9])\.(\d)/g, "0.$1");
|
|
803
|
+
return v;
|
|
804
|
+
}
|
|
805
|
+
const STYLE_BLOCK_RE = /<style[^>]*>([\s\S]*?)<\/style>/g;
|
|
806
|
+
const CSS_PROPERTY_RE = /^\s*([\w-]+)\s*:\s*(.+?)\s*;?\s*$/;
|
|
807
|
+
/**
|
|
808
|
+
* Scan art file sources for token value matches in `<style>` blocks.
|
|
809
|
+
*/
|
|
810
|
+
function scanTokenUsage(artFiles, tokenMap) {
|
|
811
|
+
const valueLookup = /* @__PURE__ */ new Map();
|
|
812
|
+
for (const [tokenPath, token] of Object.entries(tokenMap)) {
|
|
813
|
+
const normalized = normalizeTokenValue(token.$resolvedValue ?? token.value);
|
|
814
|
+
if (!normalized) continue;
|
|
815
|
+
const existing = valueLookup.get(normalized);
|
|
816
|
+
if (existing) existing.push(tokenPath);
|
|
817
|
+
else valueLookup.set(normalized, [tokenPath]);
|
|
818
|
+
const tailwindVariable = token.attributes?.tailwindVariable;
|
|
819
|
+
if (typeof tailwindVariable === "string") {
|
|
820
|
+
const normalizedVariable = normalizeTokenValue(`var(${tailwindVariable})`);
|
|
821
|
+
const variableMatches = valueLookup.get(normalizedVariable);
|
|
822
|
+
if (variableMatches) variableMatches.push(tokenPath);
|
|
823
|
+
else valueLookup.set(normalizedVariable, [tokenPath]);
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
const usageMap = {};
|
|
827
|
+
for (const [artPath, artInfo] of artFiles) {
|
|
828
|
+
let source;
|
|
829
|
+
try {
|
|
830
|
+
source = fs.readFileSync(artPath, "utf-8");
|
|
831
|
+
} catch {
|
|
832
|
+
continue;
|
|
833
|
+
}
|
|
834
|
+
const allLines = source.split("\n");
|
|
835
|
+
const styleRegions = [];
|
|
836
|
+
let match;
|
|
837
|
+
STYLE_BLOCK_RE.lastIndex = 0;
|
|
838
|
+
while ((match = STYLE_BLOCK_RE.exec(source)) !== null) {
|
|
839
|
+
const beforeMatch = source.slice(0, match.index);
|
|
840
|
+
const startTag = source.slice(match.index, match.index + match[0].indexOf(match[1]));
|
|
841
|
+
const startLine = beforeMatch.split("\n").length + startTag.split("\n").length - 1;
|
|
842
|
+
styleRegions.push({
|
|
843
|
+
startLine,
|
|
844
|
+
content: match[1]
|
|
845
|
+
});
|
|
846
|
+
}
|
|
847
|
+
for (const region of styleRegions) {
|
|
848
|
+
const lines = region.content.split("\n");
|
|
849
|
+
for (let i = 0; i < lines.length; i++) {
|
|
850
|
+
const line = lines[i];
|
|
851
|
+
const propMatch = line.match(CSS_PROPERTY_RE);
|
|
852
|
+
if (!propMatch) continue;
|
|
853
|
+
const property = propMatch[1];
|
|
854
|
+
const valueParts = propMatch[2].split(/\s+/);
|
|
855
|
+
for (const part of valueParts) {
|
|
856
|
+
const normalizedPart = normalizeTokenValue(part);
|
|
857
|
+
const matchingTokens = valueLookup.get(normalizedPart);
|
|
858
|
+
if (!matchingTokens) continue;
|
|
859
|
+
const lineNumber = region.startLine + i;
|
|
860
|
+
const lineContent = allLines[lineNumber - 1]?.trim() ?? line.trim();
|
|
861
|
+
for (const tokenPath of matchingTokens) {
|
|
862
|
+
if (!usageMap[tokenPath]) usageMap[tokenPath] = [];
|
|
863
|
+
let entry = usageMap[tokenPath].find((e) => e.artPath === artPath);
|
|
864
|
+
if (!entry) {
|
|
865
|
+
entry = {
|
|
866
|
+
artPath,
|
|
867
|
+
artTitle: artInfo.metadata.title,
|
|
868
|
+
artCategory: artInfo.metadata.category,
|
|
869
|
+
matches: []
|
|
870
|
+
};
|
|
871
|
+
usageMap[tokenPath].push(entry);
|
|
872
|
+
}
|
|
873
|
+
if (!entry.matches.some((m) => m.line === lineNumber && m.property === property)) entry.matches.push({
|
|
874
|
+
line: lineNumber,
|
|
875
|
+
lineContent,
|
|
876
|
+
property
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
return usageMap;
|
|
884
|
+
}
|
|
885
|
+
//#endregion
|
|
886
|
+
//#region src/tokens/resolver.ts
|
|
887
|
+
/**
|
|
888
|
+
* Token resolution, CRUD operations, and validation.
|
|
889
|
+
*
|
|
890
|
+
* Handles building flat token maps from categories, resolving reference chains,
|
|
891
|
+
* reading/writing raw token files, and validating semantic references.
|
|
892
|
+
*/
|
|
893
|
+
const JSON_TOKEN_EXTENSIONS = new Set([".json", ".tokens.json"]);
|
|
894
|
+
const UNSAFE_TOKEN_PATH_SEGMENTS = new Set([
|
|
895
|
+
"__proto__",
|
|
896
|
+
"prototype",
|
|
897
|
+
"constructor"
|
|
898
|
+
]);
|
|
899
|
+
function parseTokenPath(dotPath) {
|
|
900
|
+
const parts = dotPath.split(".");
|
|
901
|
+
if (parts.length === 0 || parts.some((part) => part.trim() === "")) throw new Error(`Invalid token path "${dotPath}"`);
|
|
902
|
+
const unsafeSegment = parts.find((part) => UNSAFE_TOKEN_PATH_SEGMENTS.has(part));
|
|
903
|
+
if (unsafeSegment) throw new Error(`Token path segment "${unsafeSegment}" is not allowed`);
|
|
904
|
+
return parts;
|
|
905
|
+
}
|
|
906
|
+
/**
|
|
907
|
+
* Flatten nested categories into a flat map keyed by dot-path.
|
|
908
|
+
*/
|
|
909
|
+
function buildTokenMap(categories) {
|
|
910
|
+
return nullRecord(tokenNative().buildDesignTokenMap(categories));
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* Resolve references in categories, setting $tier, $reference, and $resolvedValue.
|
|
914
|
+
*/
|
|
915
|
+
function resolveReferences(categories, _tokenMap) {
|
|
916
|
+
const resolved = tokenNative().resolveDesignTokenReferences(categories);
|
|
917
|
+
categories.splice(0, categories.length, ...normalizeCategories(resolved.categories));
|
|
918
|
+
}
|
|
919
|
+
/**
|
|
920
|
+
* Read raw JSON token file.
|
|
921
|
+
*/
|
|
922
|
+
async function readRawTokenFile(tokensPath) {
|
|
923
|
+
if (!isJsonTokenPath(tokensPath)) throw new Error("Token editing is only supported for JSON token files");
|
|
924
|
+
const content = await fs.promises.readFile(tokensPath, "utf-8");
|
|
925
|
+
return JSON.parse(content);
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Write raw JSON token file atomically (write tmp, rename).
|
|
929
|
+
*/
|
|
930
|
+
async function writeRawTokenFile(tokensPath, data) {
|
|
931
|
+
if (!isJsonTokenPath(tokensPath)) throw new Error("Token editing is only supported for JSON token files");
|
|
932
|
+
const tmpPath = tokensPath + ".tmp";
|
|
933
|
+
await fs.promises.writeFile(tmpPath, JSON.stringify(data, null, 2) + "\n", "utf-8");
|
|
934
|
+
await fs.promises.rename(tmpPath, tokensPath);
|
|
935
|
+
}
|
|
936
|
+
function isJsonTokenPath(tokensPath) {
|
|
937
|
+
return JSON_TOKEN_EXTENSIONS.has(path.extname(tokensPath)) || tokensPath.endsWith(".tokens.json");
|
|
938
|
+
}
|
|
939
|
+
/**
|
|
940
|
+
* Set a token at a dot-separated path in the raw JSON structure.
|
|
941
|
+
*/
|
|
942
|
+
function setTokenAtPath(data, dotPath, token) {
|
|
943
|
+
const parts = parseTokenPath(dotPath);
|
|
944
|
+
let current = data;
|
|
945
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
946
|
+
const key = parts[i];
|
|
947
|
+
if (typeof current[key] !== "object" || current[key] === null) current[key] = {};
|
|
948
|
+
current = current[key];
|
|
949
|
+
}
|
|
950
|
+
const leafKey = parts[parts.length - 1];
|
|
951
|
+
const raw = { value: token.value };
|
|
952
|
+
if (token.type) raw.type = token.type;
|
|
953
|
+
if (token.description) raw.description = token.description;
|
|
954
|
+
if (token.$tier) raw.$tier = token.$tier;
|
|
955
|
+
if (token.$reference) raw.$reference = token.$reference;
|
|
956
|
+
if (token.attributes) raw.attributes = token.attributes;
|
|
957
|
+
current[leafKey] = raw;
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Delete a token at a dot-separated path, cleaning empty parents.
|
|
961
|
+
*/
|
|
962
|
+
function deleteTokenAtPath(data, dotPath) {
|
|
963
|
+
const parts = parseTokenPath(dotPath);
|
|
964
|
+
const parents = [];
|
|
965
|
+
let current = data;
|
|
966
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
967
|
+
const key = parts[i];
|
|
968
|
+
if (typeof current[key] !== "object" || current[key] === null) return false;
|
|
969
|
+
parents.push({
|
|
970
|
+
obj: current,
|
|
971
|
+
key
|
|
972
|
+
});
|
|
973
|
+
current = current[key];
|
|
974
|
+
}
|
|
975
|
+
const leafKey = parts[parts.length - 1];
|
|
976
|
+
if (!(leafKey in current)) return false;
|
|
977
|
+
delete current[leafKey];
|
|
978
|
+
for (let i = parents.length - 1; i >= 0; i--) {
|
|
979
|
+
const { obj, key } = parents[i];
|
|
980
|
+
const child = obj[key];
|
|
981
|
+
if (Object.keys(child).length === 0) delete obj[key];
|
|
982
|
+
else break;
|
|
983
|
+
}
|
|
984
|
+
return true;
|
|
985
|
+
}
|
|
986
|
+
/**
|
|
987
|
+
* Validate that a semantic reference points to an existing token and has no cycles.
|
|
988
|
+
*/
|
|
989
|
+
function validateSemanticReference(tokenMap, reference, selfPath) {
|
|
990
|
+
return tokenNative().validateDesignTokenReference(tokenMap, reference, selfPath);
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* Find all tokens that reference the given path.
|
|
994
|
+
*/
|
|
995
|
+
function findDependentTokens(tokenMap, targetPath) {
|
|
996
|
+
return tokenNative().findDependentDesignTokens(tokenMap, targetPath);
|
|
997
|
+
}
|
|
998
|
+
//#endregion
|
|
999
|
+
//#region src/api-tokens.ts
|
|
1000
|
+
function resolveTokensPath(ctx) {
|
|
1001
|
+
const allowedRoots = [ctx.config.root, ...ctx.scanRoots];
|
|
1002
|
+
if (ctx.projectRoot) allowedRoots.push(ctx.projectRoot);
|
|
1003
|
+
return resolveInsideAny(allowedRoots, ctx.tokensPath, "tokensPath");
|
|
1004
|
+
}
|
|
1005
|
+
function sendTokenMutationError(e, sendError) {
|
|
1006
|
+
if (e instanceof HttpError) {
|
|
1007
|
+
sendError(e.message, e.status);
|
|
1008
|
+
return;
|
|
1009
|
+
}
|
|
1010
|
+
if (e instanceof Error && /(token path|token editing)/i.test(e.message)) {
|
|
1011
|
+
sendError(e.message, 400);
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
1014
|
+
sendError(e instanceof Error ? e.message : String(e));
|
|
1015
|
+
}
|
|
1016
|
+
/** GET /api/tokens/usage */
|
|
1017
|
+
async function handleTokensUsage(ctx, sendJson) {
|
|
1018
|
+
if (!ctx.tokensPath) {
|
|
1019
|
+
sendJson({});
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
try {
|
|
1023
|
+
const categories = await parseTokens(resolveTokensPath(ctx));
|
|
1024
|
+
resolveReferences(categories, buildTokenMap(categories));
|
|
1025
|
+
const resolvedTokenMap = buildTokenMap(categories);
|
|
1026
|
+
sendJson(scanTokenUsage(ctx.artFiles, resolvedTokenMap));
|
|
1027
|
+
} catch (e) {
|
|
1028
|
+
console.error("[musea] Failed to scan token usage:", e);
|
|
1029
|
+
sendJson({});
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
/** GET /api/tokens */
|
|
1033
|
+
async function handleTokensGet(ctx, sendJson) {
|
|
1034
|
+
if (!ctx.tokensPath) {
|
|
1035
|
+
sendJson({
|
|
1036
|
+
categories: [],
|
|
1037
|
+
tokenMap: {},
|
|
1038
|
+
meta: {
|
|
1039
|
+
filePath: "",
|
|
1040
|
+
tokenCount: 0,
|
|
1041
|
+
primitiveCount: 0,
|
|
1042
|
+
semanticCount: 0
|
|
1043
|
+
}
|
|
1044
|
+
});
|
|
1045
|
+
return;
|
|
1046
|
+
}
|
|
1047
|
+
try {
|
|
1048
|
+
const absoluteTokensPath = resolveTokensPath(ctx);
|
|
1049
|
+
const categories = await parseTokens(absoluteTokensPath);
|
|
1050
|
+
resolveReferences(categories, buildTokenMap(categories));
|
|
1051
|
+
const resolvedTokenMap = buildTokenMap(categories);
|
|
1052
|
+
let primitiveCount = 0;
|
|
1053
|
+
let semanticCount = 0;
|
|
1054
|
+
for (const token of Object.values(resolvedTokenMap)) if (token.$tier === "semantic") semanticCount++;
|
|
1055
|
+
else primitiveCount++;
|
|
1056
|
+
sendJson({
|
|
1057
|
+
categories,
|
|
1058
|
+
tokenMap: resolvedTokenMap,
|
|
1059
|
+
meta: {
|
|
1060
|
+
filePath: absoluteTokensPath,
|
|
1061
|
+
tokenCount: Object.keys(resolvedTokenMap).length,
|
|
1062
|
+
primitiveCount,
|
|
1063
|
+
semanticCount
|
|
1064
|
+
}
|
|
1065
|
+
});
|
|
1066
|
+
} catch (e) {
|
|
1067
|
+
console.error("[musea] Failed to load tokens:", e);
|
|
1068
|
+
sendJson({
|
|
1069
|
+
categories: [],
|
|
1070
|
+
tokenMap: {},
|
|
1071
|
+
error: String(e)
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
/** POST /api/tokens (create) */
|
|
1076
|
+
async function handleTokensCreate(ctx, readBody, sendJson, sendError) {
|
|
1077
|
+
if (!ctx.tokensPath) {
|
|
1078
|
+
sendError("No tokens path configured", 400);
|
|
1079
|
+
return;
|
|
1080
|
+
}
|
|
1081
|
+
const body = await readBody();
|
|
1082
|
+
try {
|
|
1083
|
+
const { path: dotPath, token } = parseJsonBody(body);
|
|
1084
|
+
if (!dotPath || !token || token.value === void 0) {
|
|
1085
|
+
sendError("Missing required fields: path, token.value", 400);
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
const absoluteTokensPath = resolveTokensPath(ctx);
|
|
1089
|
+
const rawData = await readRawTokenFile(absoluteTokensPath);
|
|
1090
|
+
const currentMap = buildTokenMap(await parseTokens(absoluteTokensPath));
|
|
1091
|
+
if (currentMap[dotPath]) {
|
|
1092
|
+
sendError(`Token already exists at path "${dotPath}"`, 409);
|
|
1093
|
+
return;
|
|
1094
|
+
}
|
|
1095
|
+
if (token.$reference) {
|
|
1096
|
+
const validation = validateSemanticReference(currentMap, token.$reference, dotPath);
|
|
1097
|
+
if (!validation.valid) {
|
|
1098
|
+
sendError(validation.error, 400);
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
token.value = `{${token.$reference}}`;
|
|
1102
|
+
token.$tier = "semantic";
|
|
1103
|
+
}
|
|
1104
|
+
setTokenAtPath(rawData, dotPath, token);
|
|
1105
|
+
await writeRawTokenFile(absoluteTokensPath, rawData);
|
|
1106
|
+
const categories = await parseTokens(absoluteTokensPath);
|
|
1107
|
+
resolveReferences(categories, buildTokenMap(categories));
|
|
1108
|
+
sendJson({
|
|
1109
|
+
categories,
|
|
1110
|
+
tokenMap: buildTokenMap(categories)
|
|
1111
|
+
}, 201);
|
|
1112
|
+
} catch (e) {
|
|
1113
|
+
sendTokenMutationError(e, sendError);
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
/** PUT /api/tokens (update) */
|
|
1117
|
+
async function handleTokensUpdate(ctx, readBody, sendJson, sendError) {
|
|
1118
|
+
if (!ctx.tokensPath) {
|
|
1119
|
+
sendError("No tokens path configured", 400);
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
const body = await readBody();
|
|
1123
|
+
try {
|
|
1124
|
+
const { path: dotPath, token } = parseJsonBody(body);
|
|
1125
|
+
if (!dotPath || !token || token.value === void 0) {
|
|
1126
|
+
sendError("Missing required fields: path, token.value", 400);
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1129
|
+
const absoluteTokensPath = resolveTokensPath(ctx);
|
|
1130
|
+
if (token.$reference) {
|
|
1131
|
+
const validation = validateSemanticReference(buildTokenMap(await parseTokens(absoluteTokensPath)), token.$reference, dotPath);
|
|
1132
|
+
if (!validation.valid) {
|
|
1133
|
+
sendError(validation.error, 400);
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
token.value = `{${token.$reference}}`;
|
|
1137
|
+
token.$tier = "semantic";
|
|
1138
|
+
}
|
|
1139
|
+
const rawData = await readRawTokenFile(absoluteTokensPath);
|
|
1140
|
+
setTokenAtPath(rawData, dotPath, token);
|
|
1141
|
+
await writeRawTokenFile(absoluteTokensPath, rawData);
|
|
1142
|
+
const categories = await parseTokens(absoluteTokensPath);
|
|
1143
|
+
resolveReferences(categories, buildTokenMap(categories));
|
|
1144
|
+
sendJson({
|
|
1145
|
+
categories,
|
|
1146
|
+
tokenMap: buildTokenMap(categories)
|
|
1147
|
+
});
|
|
1148
|
+
} catch (e) {
|
|
1149
|
+
sendTokenMutationError(e, sendError);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
/** DELETE /api/tokens */
|
|
1153
|
+
async function handleTokensDelete(ctx, readBody, sendJson, sendError) {
|
|
1154
|
+
if (!ctx.tokensPath) {
|
|
1155
|
+
sendError("No tokens path configured", 400);
|
|
1156
|
+
return;
|
|
1157
|
+
}
|
|
1158
|
+
const body = await readBody();
|
|
1159
|
+
try {
|
|
1160
|
+
const { path: dotPath } = parseJsonBody(body);
|
|
1161
|
+
if (!dotPath) {
|
|
1162
|
+
sendError("Missing required field: path", 400);
|
|
1163
|
+
return;
|
|
1164
|
+
}
|
|
1165
|
+
const absoluteTokensPath = resolveTokensPath(ctx);
|
|
1166
|
+
const dependents = findDependentTokens(buildTokenMap(await parseTokens(absoluteTokensPath)), dotPath);
|
|
1167
|
+
const rawData = await readRawTokenFile(absoluteTokensPath);
|
|
1168
|
+
if (!deleteTokenAtPath(rawData, dotPath)) {
|
|
1169
|
+
sendError(`Token not found at path "${dotPath}"`, 404);
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
await writeRawTokenFile(absoluteTokensPath, rawData);
|
|
1173
|
+
const categories = await parseTokens(absoluteTokensPath);
|
|
1174
|
+
resolveReferences(categories, buildTokenMap(categories));
|
|
1175
|
+
sendJson({
|
|
1176
|
+
categories,
|
|
1177
|
+
tokenMap: buildTokenMap(categories),
|
|
1178
|
+
dependentsWarning: dependents.length > 0 ? dependents : void 0
|
|
1179
|
+
});
|
|
1180
|
+
} catch (e) {
|
|
1181
|
+
sendTokenMutationError(e, sendError);
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
//#endregion
|
|
1185
|
+
//#region src/script-component-analysis.ts
|
|
1186
|
+
/** Read a script component's runtime options without executing project code. */
|
|
1187
|
+
function scriptKind(filename) {
|
|
1188
|
+
if (filename.endsWith(".tsx")) return ts.ScriptKind.TSX;
|
|
1189
|
+
if (filename.endsWith(".jsx")) return ts.ScriptKind.JSX;
|
|
1190
|
+
if (filename.endsWith(".js")) return ts.ScriptKind.JS;
|
|
1191
|
+
return ts.ScriptKind.TS;
|
|
1192
|
+
}
|
|
1193
|
+
function unwrap(expression) {
|
|
1194
|
+
while (ts.isParenthesizedExpression(expression) || ts.isAsExpression(expression) || ts.isSatisfiesExpression(expression) || ts.isNonNullExpression(expression)) expression = expression.expression;
|
|
1195
|
+
return expression;
|
|
1196
|
+
}
|
|
1197
|
+
function nameOf(name) {
|
|
1198
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) return name.text;
|
|
1199
|
+
if (ts.isComputedPropertyName(name) && ts.isStringLiteral(name.expression)) return name.expression.text;
|
|
1200
|
+
}
|
|
1201
|
+
function variable(sourceFile, name) {
|
|
1202
|
+
for (const statement of sourceFile.statements) {
|
|
1203
|
+
if (!ts.isVariableStatement(statement)) continue;
|
|
1204
|
+
for (const declaration of statement.declarationList.declarations) if (ts.isIdentifier(declaration.name) && declaration.name.text === name) return declaration.initializer;
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
function resolved(expression, sourceFile) {
|
|
1208
|
+
expression = unwrap(expression);
|
|
1209
|
+
if (ts.isIdentifier(expression)) {
|
|
1210
|
+
const initializer = variable(sourceFile, expression.text);
|
|
1211
|
+
if (initializer) return unwrap(initializer);
|
|
1212
|
+
}
|
|
1213
|
+
return expression;
|
|
1214
|
+
}
|
|
1215
|
+
function option(object, name, sourceFile) {
|
|
1216
|
+
for (const property of object.properties) {
|
|
1217
|
+
if (ts.isPropertyAssignment(property) && nameOf(property.name) === name) return resolved(property.initializer, sourceFile);
|
|
1218
|
+
if (ts.isShorthandPropertyAssignment(property) && property.name.text === name) {
|
|
1219
|
+
const initializer = variable(sourceFile, name);
|
|
1220
|
+
if (initializer) return resolved(initializer, sourceFile);
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
function componentOptions(sourceFile) {
|
|
1225
|
+
const assignment = sourceFile.statements.find((statement) => ts.isExportAssignment(statement));
|
|
1226
|
+
if (!assignment || assignment.isExportEquals) return void 0;
|
|
1227
|
+
let expression = resolved(assignment.expression, sourceFile);
|
|
1228
|
+
if (ts.isCallExpression(expression)) {
|
|
1229
|
+
const callee = expression.expression;
|
|
1230
|
+
if (!(ts.isIdentifier(callee) && callee.text === "defineComponent" || ts.isPropertyAccessExpression(callee) && callee.name.text === "defineComponent") || !expression.arguments[0]) return void 0;
|
|
1231
|
+
expression = resolved(expression.arguments[0], sourceFile);
|
|
1232
|
+
}
|
|
1233
|
+
return ts.isObjectLiteralExpression(expression) ? expression : void 0;
|
|
1234
|
+
}
|
|
1235
|
+
function literal(expression) {
|
|
1236
|
+
expression = unwrap(expression);
|
|
1237
|
+
if (ts.isStringLiteral(expression) || ts.isNoSubstitutionTemplateLiteral(expression)) return expression.text;
|
|
1238
|
+
if (ts.isNumericLiteral(expression)) return Number(expression.text);
|
|
1239
|
+
if (expression.kind === ts.SyntaxKind.TrueKeyword) return true;
|
|
1240
|
+
if (expression.kind === ts.SyntaxKind.FalseKeyword) return false;
|
|
1241
|
+
if (expression.kind === ts.SyntaxKind.NullKeyword) return null;
|
|
1242
|
+
if (ts.isPrefixUnaryExpression(expression) && ts.isNumericLiteral(expression.operand)) {
|
|
1243
|
+
const value = Number(expression.operand.text);
|
|
1244
|
+
if (expression.operator === ts.SyntaxKind.MinusToken) return -value;
|
|
1245
|
+
if (expression.operator === ts.SyntaxKind.PlusToken) return value;
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
function propType(expression) {
|
|
1249
|
+
if (!expression) return "unknown";
|
|
1250
|
+
expression = unwrap(expression);
|
|
1251
|
+
if (ts.isArrayLiteralExpression(expression)) return expression.elements.map((element) => propType(element)).join(" | ") || "unknown";
|
|
1252
|
+
switch (ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : void 0) {
|
|
1253
|
+
case "String": return "string";
|
|
1254
|
+
case "Number": return "number";
|
|
1255
|
+
case "Boolean": return "boolean";
|
|
1256
|
+
case "Array": return "unknown[]";
|
|
1257
|
+
case "Object": return "Record<string, unknown>";
|
|
1258
|
+
default: return "unknown";
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
function analyzeProps(expression, sourceFile) {
|
|
1262
|
+
if (!expression) return [];
|
|
1263
|
+
if (ts.isArrayLiteralExpression(expression)) return expression.elements.flatMap((element) => ts.isStringLiteral(element) ? [{
|
|
1264
|
+
name: element.text,
|
|
1265
|
+
type: "unknown",
|
|
1266
|
+
required: false
|
|
1267
|
+
}] : []);
|
|
1268
|
+
if (!ts.isObjectLiteralExpression(expression)) return [];
|
|
1269
|
+
const props = [];
|
|
1270
|
+
for (const property of expression.properties) {
|
|
1271
|
+
if (!ts.isPropertyAssignment(property)) continue;
|
|
1272
|
+
const name = nameOf(property.name);
|
|
1273
|
+
if (!name) continue;
|
|
1274
|
+
const value = resolved(property.initializer, sourceFile);
|
|
1275
|
+
if (ts.isObjectLiteralExpression(value)) {
|
|
1276
|
+
const type = propType(option(value, "type", sourceFile));
|
|
1277
|
+
const required = option(value, "required", sourceFile)?.kind === ts.SyntaxKind.TrueKeyword;
|
|
1278
|
+
const defaultExpression = option(value, "default", sourceFile);
|
|
1279
|
+
const defaultValue = defaultExpression ? literal(defaultExpression) : void 0;
|
|
1280
|
+
props.push({
|
|
1281
|
+
name,
|
|
1282
|
+
type,
|
|
1283
|
+
required,
|
|
1284
|
+
...defaultValue !== void 0 ? { default_value: defaultValue } : {}
|
|
1285
|
+
});
|
|
1286
|
+
} else props.push({
|
|
1287
|
+
name,
|
|
1288
|
+
type: propType(value),
|
|
1289
|
+
required: false
|
|
1290
|
+
});
|
|
1291
|
+
}
|
|
1292
|
+
return props;
|
|
1293
|
+
}
|
|
1294
|
+
function analyzeEmits(expression) {
|
|
1295
|
+
if (!expression) return [];
|
|
1296
|
+
if (ts.isArrayLiteralExpression(expression)) return expression.elements.flatMap((element) => ts.isStringLiteral(element) ? [element.text] : []);
|
|
1297
|
+
if (ts.isObjectLiteralExpression(expression)) return expression.properties.flatMap((property) => (ts.isPropertyAssignment(property) || ts.isMethodDeclaration(property)) && nameOf(property.name) ? [nameOf(property.name)] : []);
|
|
1298
|
+
return [];
|
|
1299
|
+
}
|
|
1300
|
+
function analyzeScriptComponent(source, filename) {
|
|
1301
|
+
const sourceFile = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, scriptKind(filename));
|
|
1302
|
+
const options = componentOptions(sourceFile);
|
|
1303
|
+
if (!options) return {
|
|
1304
|
+
props: [],
|
|
1305
|
+
emits: []
|
|
1306
|
+
};
|
|
1307
|
+
return {
|
|
1308
|
+
props: analyzeProps(option(options, "props", sourceFile), sourceFile),
|
|
1309
|
+
emits: analyzeEmits(option(options, "emits", sourceFile))
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
//#endregion
|
|
1313
|
+
//#region src/api-routes/handler-palette.ts
|
|
1314
|
+
/**
|
|
1315
|
+
* Palette handler for the Musea gallery API.
|
|
1316
|
+
*
|
|
1317
|
+
* Handles GET /api/arts/:path/palette endpoint.
|
|
1318
|
+
*/
|
|
1319
|
+
/** GET /api/arts/:path/palette */
|
|
1320
|
+
async function handleArtPalette(ctx, match, sendJson, sendError) {
|
|
1321
|
+
const artPath = decodeUrlComponent(match[1], "art path");
|
|
1322
|
+
const art = ctx.artFiles.get(artPath);
|
|
1323
|
+
if (!art) {
|
|
1324
|
+
sendError("Art not found", 404);
|
|
1325
|
+
return;
|
|
1326
|
+
}
|
|
1327
|
+
try {
|
|
1328
|
+
const readableArtPath = resolveReadableArtPath(ctx.config.root, ctx.scanRoots, artPath);
|
|
1329
|
+
const source = await fs.promises.readFile(readableArtPath, "utf-8");
|
|
1330
|
+
const binding = loadNative();
|
|
1331
|
+
let palette;
|
|
1332
|
+
if (binding.generateArtPalette) palette = binding.generateArtPalette(source, { filename: readableArtPath });
|
|
1333
|
+
else palette = {
|
|
1334
|
+
title: art.metadata.title,
|
|
1335
|
+
controls: [],
|
|
1336
|
+
groups: [],
|
|
1337
|
+
json: "{}",
|
|
1338
|
+
typescript: ""
|
|
1339
|
+
};
|
|
1340
|
+
palette.componentTagName = resolveArtComponent(art, artPath, art.scriptSetupContent ? parseScriptSetupForArt(art.scriptSetupContent) : null, {
|
|
1341
|
+
root: ctx.config.root,
|
|
1342
|
+
scanRoots: ctx.scanRoots
|
|
1343
|
+
}).componentTagName;
|
|
1344
|
+
const resolvedComponentPath = resolveComponentSourcePath(art, artPath, allowedSourceRoots(ctx.config.root, ctx.scanRoots));
|
|
1345
|
+
if (!resolvedComponentPath) {
|
|
1346
|
+
sendJson(palette);
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1349
|
+
try {
|
|
1350
|
+
const componentSource = await fs.promises.readFile(resolvedComponentPath, "utf-8");
|
|
1351
|
+
const analysis = isVueSourcePath(resolvedComponentPath) ? binding.analyzeSfc ? binding.analyzeSfc(componentSource, { filename: resolvedComponentPath }) : analyzeSfcFallback(componentSource, { filename: resolvedComponentPath }) : analyzeScriptComponent(componentSource, resolvedComponentPath);
|
|
1352
|
+
if (analysis.props.length > 0) mergeSfcPropsIntoPalette(palette, analysis.props);
|
|
1353
|
+
} catch {}
|
|
1354
|
+
sendJson(palette);
|
|
1355
|
+
} catch (e) {
|
|
1356
|
+
if (e instanceof HttpError) {
|
|
1357
|
+
sendError(e.message, e.status);
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
sendError(e instanceof Error ? e.message : String(e));
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
function mergeSfcPropsIntoPalette(palette, props) {
|
|
1364
|
+
const controlsByName = /* @__PURE__ */ new Map();
|
|
1365
|
+
for (const control of palette.controls) controlsByName.set(normalizePropName(control.name), control);
|
|
1366
|
+
for (const prop of props) {
|
|
1367
|
+
const control = controlsByName.get(normalizePropName(prop.name));
|
|
1368
|
+
if (control) applyPropMetadata(control, prop);
|
|
1369
|
+
else palette.controls.push(controlFromProp(prop));
|
|
1370
|
+
}
|
|
1371
|
+
palette.json = JSON.stringify({
|
|
1372
|
+
title: palette.title,
|
|
1373
|
+
controls: palette.controls
|
|
1374
|
+
}, null, 2);
|
|
1375
|
+
palette.typescript = generateTypescript(palette);
|
|
1376
|
+
}
|
|
1377
|
+
function applyPropMetadata(control, prop) {
|
|
1378
|
+
const inferred = inferControl(prop.type);
|
|
1379
|
+
control.name = prop.name;
|
|
1380
|
+
control.required = prop.required;
|
|
1381
|
+
if (control.default_value === void 0 && prop.default_value !== void 0) control.default_value = parseDefault(prop.default_value);
|
|
1382
|
+
if (inferred.control !== "text" || control.control === "text") control.control = inferred.control;
|
|
1383
|
+
if (inferred.options.length > 0) control.options = inferred.options;
|
|
1384
|
+
}
|
|
1385
|
+
function controlFromProp(prop) {
|
|
1386
|
+
const inferred = inferControl(prop.type);
|
|
1387
|
+
return {
|
|
1388
|
+
name: prop.name,
|
|
1389
|
+
control: inferred.control,
|
|
1390
|
+
default_value: prop.default_value === void 0 ? void 0 : parseDefault(prop.default_value),
|
|
1391
|
+
description: void 0,
|
|
1392
|
+
required: prop.required,
|
|
1393
|
+
options: inferred.options,
|
|
1394
|
+
range: void 0,
|
|
1395
|
+
group: void 0
|
|
1396
|
+
};
|
|
1397
|
+
}
|
|
1398
|
+
function inferControl(type) {
|
|
1399
|
+
const normalized = type.trim();
|
|
1400
|
+
const options = literalOptions(normalized);
|
|
1401
|
+
if (options.length > 0) return {
|
|
1402
|
+
control: "select",
|
|
1403
|
+
options
|
|
1404
|
+
};
|
|
1405
|
+
if (normalized === "boolean") return {
|
|
1406
|
+
control: "boolean",
|
|
1407
|
+
options: []
|
|
1408
|
+
};
|
|
1409
|
+
if (normalized === "number") return {
|
|
1410
|
+
control: "number",
|
|
1411
|
+
options: []
|
|
1412
|
+
};
|
|
1413
|
+
if (normalized.includes("[]") || normalized.startsWith("Array<")) return {
|
|
1414
|
+
control: "array",
|
|
1415
|
+
options: []
|
|
1416
|
+
};
|
|
1417
|
+
if (normalized.startsWith("{") || normalized.startsWith("Record<")) return {
|
|
1418
|
+
control: "object",
|
|
1419
|
+
options: []
|
|
1420
|
+
};
|
|
1421
|
+
return {
|
|
1422
|
+
control: "text",
|
|
1423
|
+
options: []
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
function literalOptions(type) {
|
|
1427
|
+
if (!type.includes("|") || type.includes("=>")) return [];
|
|
1428
|
+
return type.split("|").map((part) => part.trim()).map((part) => {
|
|
1429
|
+
const stringMatch = part.match(/^["']([^"']+)["']$/);
|
|
1430
|
+
if (stringMatch) return stringMatch[1];
|
|
1431
|
+
if (part === "true") return true;
|
|
1432
|
+
if (part === "false") return false;
|
|
1433
|
+
const numberValue = Number(part);
|
|
1434
|
+
return Number.isFinite(numberValue) ? numberValue : void 0;
|
|
1435
|
+
}).filter((value) => value !== void 0).map((value) => ({
|
|
1436
|
+
label: String(value),
|
|
1437
|
+
value
|
|
1438
|
+
}));
|
|
1439
|
+
}
|
|
1440
|
+
function parseDefault(value) {
|
|
1441
|
+
if (typeof value !== "string") return value;
|
|
1442
|
+
if (value === "true") return true;
|
|
1443
|
+
if (value === "false") return false;
|
|
1444
|
+
if (/^-?\d+(?:\.\d+)?$/.test(value)) return Number(value);
|
|
1445
|
+
return value.replace(/^["']|["']$/g, "");
|
|
1446
|
+
}
|
|
1447
|
+
function normalizePropName(name) {
|
|
1448
|
+
return name.replace(/[-_]/g, "").toLowerCase();
|
|
1449
|
+
}
|
|
1450
|
+
function generateTypescript(palette) {
|
|
1451
|
+
const fields = palette.controls.map((control) => ` ${control.name}${control.required ? "" : "?"}: ${controlTsType(control)};`).join("\n");
|
|
1452
|
+
return `export interface ${pascalCase(palette.title)}Props {\n${fields}\n}\n`;
|
|
1453
|
+
}
|
|
1454
|
+
function controlTsType(control) {
|
|
1455
|
+
if (control.control === "boolean") return "boolean";
|
|
1456
|
+
if (control.control === "number" || control.control === "range") return "number";
|
|
1457
|
+
if (control.control === "array") return "unknown[]";
|
|
1458
|
+
if (control.control === "object") return "Record<string, unknown>";
|
|
1459
|
+
if (control.control === "select" && control.options.length > 0) return control.options.map((option) => JSON.stringify(option.value)).join(" | ");
|
|
1460
|
+
return "string";
|
|
1461
|
+
}
|
|
1462
|
+
function pascalCase(value) {
|
|
1463
|
+
return value.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
|
|
1464
|
+
}
|
|
1465
|
+
//#endregion
|
|
1466
|
+
//#region src/api-routes/handlers.ts
|
|
1467
|
+
/**
|
|
1468
|
+
* Individual route handler functions for the Musea gallery API.
|
|
1469
|
+
*
|
|
1470
|
+
* Extracted from api-routes.ts to keep file sizes manageable.
|
|
1471
|
+
* These handle GET /api/arts/:path/... sub-routes.
|
|
1472
|
+
*/
|
|
1473
|
+
function sendCaughtError(sendError, error) {
|
|
1474
|
+
if (error instanceof HttpError) {
|
|
1475
|
+
sendError(error.message, error.status);
|
|
1476
|
+
return;
|
|
1477
|
+
}
|
|
1478
|
+
sendError(error instanceof Error ? error.message : String(error));
|
|
1479
|
+
}
|
|
1480
|
+
/** GET /api/arts/:path/source */
|
|
1481
|
+
async function handleArtSource(ctx, match, sendJson, sendError) {
|
|
1482
|
+
const artPath = decodeUrlComponent(match[1], "art path");
|
|
1483
|
+
if (!ctx.artFiles.get(artPath)) {
|
|
1484
|
+
sendError("Art not found", 404);
|
|
1485
|
+
return;
|
|
1486
|
+
}
|
|
1487
|
+
try {
|
|
1488
|
+
const readableArtPath = resolveReadableArtPath(ctx.config.root, ctx.scanRoots, artPath);
|
|
1489
|
+
sendJson({
|
|
1490
|
+
source: await fs.promises.readFile(readableArtPath, "utf-8"),
|
|
1491
|
+
path: artPath
|
|
1492
|
+
});
|
|
1493
|
+
} catch (e) {
|
|
1494
|
+
sendCaughtError(sendError, e);
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
/** GET /api/arts/:path/analysis */
|
|
1498
|
+
async function handleArtAnalysis(ctx, match, sendJson, sendError) {
|
|
1499
|
+
const artPath = decodeUrlComponent(match[1], "art path");
|
|
1500
|
+
const art = ctx.artFiles.get(artPath);
|
|
1501
|
+
if (!art) {
|
|
1502
|
+
sendError("Art not found", 404);
|
|
1503
|
+
return;
|
|
1504
|
+
}
|
|
1505
|
+
try {
|
|
1506
|
+
const resolvedComponentPath = resolveComponentSourcePath(art, artPath, allowedSourceRoots(ctx.config.root, ctx.scanRoots));
|
|
1507
|
+
if (resolvedComponentPath) {
|
|
1508
|
+
const source = await fs.promises.readFile(resolvedComponentPath, "utf-8");
|
|
1509
|
+
if (isVueSourcePath(resolvedComponentPath)) {
|
|
1510
|
+
const binding = loadNative();
|
|
1511
|
+
sendJson(binding.analyzeSfc ? binding.analyzeSfc(source, { filename: resolvedComponentPath }) : analyzeSfcFallback(source, { filename: resolvedComponentPath }));
|
|
1512
|
+
} else sendJson(analyzeScriptComponent(source, resolvedComponentPath));
|
|
1513
|
+
} else sendJson({
|
|
1514
|
+
props: [],
|
|
1515
|
+
emits: []
|
|
1516
|
+
});
|
|
1517
|
+
} catch (e) {
|
|
1518
|
+
sendCaughtError(sendError, e);
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
/** GET /api/arts/:path/docs */
|
|
1522
|
+
async function handleArtDocs(ctx, match, sendJson, sendError) {
|
|
1523
|
+
const artPath = decodeUrlComponent(match[1], "art path");
|
|
1524
|
+
const art = ctx.artFiles.get(artPath);
|
|
1525
|
+
if (!art) {
|
|
1526
|
+
sendError("Art not found", 404);
|
|
1527
|
+
return;
|
|
1528
|
+
}
|
|
1529
|
+
try {
|
|
1530
|
+
const readableArtPath = resolveReadableArtPath(ctx.config.root, ctx.scanRoots, artPath);
|
|
1531
|
+
const source = await fs.promises.readFile(readableArtPath, "utf-8");
|
|
1532
|
+
const binding = loadNative();
|
|
1533
|
+
if (binding.generateArtDoc) {
|
|
1534
|
+
const doc = binding.generateArtDoc(source, { filename: readableArtPath });
|
|
1535
|
+
let markdown = doc.markdown || "";
|
|
1536
|
+
const componentName = art.metadata.title || "Component";
|
|
1537
|
+
markdown = markdown.replace(/<Self(\s|>|\/)/g, `<${componentName}$1`).replace(/<\/Self>/g, `</${componentName}>`);
|
|
1538
|
+
markdown = markdown.replace(/```(\w*)\n([\s\S]*?)```/g, (_match, lang, code) => {
|
|
1539
|
+
const lines = code.split("\n");
|
|
1540
|
+
let minIndent = Infinity;
|
|
1541
|
+
for (const line of lines) if (line.trim()) {
|
|
1542
|
+
const indent = line.match(/^(\s*)/)?.[1].length || 0;
|
|
1543
|
+
minIndent = Math.min(minIndent, indent);
|
|
1544
|
+
}
|
|
1545
|
+
if (minIndent === Infinity) minIndent = 0;
|
|
1546
|
+
let formatted;
|
|
1547
|
+
if (minIndent > 0) formatted = lines.map((line) => line.slice(minIndent)).join("\n");
|
|
1548
|
+
else {
|
|
1549
|
+
let restIndent = Infinity;
|
|
1550
|
+
for (let i = 1; i < lines.length; i++) if (lines[i].trim()) {
|
|
1551
|
+
const indent = lines[i].match(/^(\s*)/)?.[1].length || 0;
|
|
1552
|
+
restIndent = Math.min(restIndent, indent);
|
|
1553
|
+
}
|
|
1554
|
+
if (restIndent === Infinity || restIndent === 0) formatted = lines.join("\n");
|
|
1555
|
+
else formatted = lines.map((line, i) => i === 0 ? line : line.slice(restIndent)).join("\n");
|
|
1556
|
+
}
|
|
1557
|
+
return "```" + lang + "\n" + formatted + "```";
|
|
1558
|
+
});
|
|
1559
|
+
sendJson({
|
|
1560
|
+
...doc,
|
|
1561
|
+
markdown
|
|
1562
|
+
});
|
|
1563
|
+
} else sendJson({
|
|
1564
|
+
markdown: "",
|
|
1565
|
+
title: art.metadata.title,
|
|
1566
|
+
variant_count: art.variants.length
|
|
1567
|
+
});
|
|
1568
|
+
} catch (e) {
|
|
1569
|
+
sendCaughtError(sendError, e);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
/** GET /api/arts/:path/variants/:name/a11y */
|
|
1573
|
+
//#endregion
|
|
1574
|
+
//#region src/static-data.ts
|
|
1575
|
+
function staticPreviewId(artPath, variantName) {
|
|
1576
|
+
return crypto.createHash("sha256").update(artPath).update("\0").update(variantName).digest("hex").slice(0, 20);
|
|
1577
|
+
}
|
|
1578
|
+
function joinUrlPath(basePath, ...segments) {
|
|
1579
|
+
return `${basePath === "/" ? "" : basePath.replace(/\/+$/, "")}/${segments.map((segment) => segment.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/")}`;
|
|
1580
|
+
}
|
|
1581
|
+
async function createStaticGalleryPayload(ctx) {
|
|
1582
|
+
const apiCtx = createApiContext(ctx);
|
|
1583
|
+
const arts = sortedArts(ctx.artFiles.values());
|
|
1584
|
+
const previews = {};
|
|
1585
|
+
const details = {};
|
|
1586
|
+
const snapshotIdentities = Object.create(null);
|
|
1587
|
+
for (const art of arts) {
|
|
1588
|
+
snapshotIdentities[art.path] = resolveSnapshotIdentity(art.path, ctx.projectRoot ?? ctx.config.root);
|
|
1589
|
+
previews[art.path] = {};
|
|
1590
|
+
for (const variant of art.variants) {
|
|
1591
|
+
const id = staticPreviewId(art.path, variant.name);
|
|
1592
|
+
previews[art.path][variant.name] = joinUrlPath(ctx.basePath, "preview", `${id}.html`);
|
|
1593
|
+
}
|
|
1594
|
+
details[art.path] = {
|
|
1595
|
+
source: await captureJson((sendJson, sendError) => {
|
|
1596
|
+
return handleArtSource(apiCtx, artMatch(art.path), sendJson, sendError);
|
|
1597
|
+
}, {
|
|
1598
|
+
source: "",
|
|
1599
|
+
path: art.path
|
|
1600
|
+
}),
|
|
1601
|
+
palette: await captureJson((sendJson, sendError) => {
|
|
1602
|
+
return handleArtPalette(apiCtx, artMatch(art.path), sendJson, sendError);
|
|
1603
|
+
}, emptyPalette(art)),
|
|
1604
|
+
analysis: await captureJson((sendJson, sendError) => {
|
|
1605
|
+
return handleArtAnalysis(apiCtx, artMatch(art.path), sendJson, sendError);
|
|
1606
|
+
}, {
|
|
1607
|
+
props: [],
|
|
1608
|
+
emits: []
|
|
1609
|
+
}),
|
|
1610
|
+
docs: await captureJson((sendJson, sendError) => {
|
|
1611
|
+
return handleArtDocs(apiCtx, artMatch(art.path), sendJson, sendError);
|
|
1612
|
+
}, emptyDocs(art))
|
|
1613
|
+
};
|
|
1614
|
+
}
|
|
1615
|
+
return {
|
|
1616
|
+
arts,
|
|
1617
|
+
snapshotIdentityVersion: 1,
|
|
1618
|
+
snapshotIdentities,
|
|
1619
|
+
previews,
|
|
1620
|
+
details,
|
|
1621
|
+
tokens: await captureJson((sendJson) => handleTokensGet(apiCtx, sendJson), emptyTokens()),
|
|
1622
|
+
tokenUsage: await captureJson((sendJson) => handleTokensUsage(apiCtx, sendJson), {})
|
|
1623
|
+
};
|
|
1624
|
+
}
|
|
1625
|
+
function createApiContext(ctx) {
|
|
1626
|
+
return {
|
|
1627
|
+
config: ctx.config,
|
|
1628
|
+
artFiles: ctx.artFiles,
|
|
1629
|
+
scanRoots: ctx.scanRoots,
|
|
1630
|
+
tokensPath: ctx.tokensPath,
|
|
1631
|
+
projectRoot: ctx.projectRoot,
|
|
1632
|
+
basePath: ctx.basePath,
|
|
1633
|
+
resolvedPreviewCss: ctx.resolvedPreviewCss,
|
|
1634
|
+
resolvedPreviewSetup: ctx.resolvedPreviewSetup,
|
|
1635
|
+
devSessionToken: ctx.devSessionToken,
|
|
1636
|
+
processArtFile: async (filePath) => {
|
|
1637
|
+
await fs.promises.access(filePath);
|
|
1638
|
+
},
|
|
1639
|
+
getDevServerPort: () => 5173
|
|
1640
|
+
};
|
|
1641
|
+
}
|
|
1642
|
+
async function captureJson(run, fallback) {
|
|
1643
|
+
let captured = fallback;
|
|
1644
|
+
const sendJson = (data) => {
|
|
1645
|
+
captured = data;
|
|
1646
|
+
};
|
|
1647
|
+
const sendError = (message, status = 500) => {
|
|
1648
|
+
captured = {
|
|
1649
|
+
error: message,
|
|
1650
|
+
status
|
|
1651
|
+
};
|
|
1652
|
+
};
|
|
1653
|
+
await run(sendJson, sendError);
|
|
1654
|
+
return captured;
|
|
1655
|
+
}
|
|
1656
|
+
function artMatch(artPath) {
|
|
1657
|
+
return ["", encodeURIComponent(artPath)];
|
|
1658
|
+
}
|
|
1659
|
+
function emptyPalette(art) {
|
|
1660
|
+
return {
|
|
1661
|
+
title: art.metadata.title,
|
|
1662
|
+
controls: [],
|
|
1663
|
+
groups: [],
|
|
1664
|
+
json: "{}",
|
|
1665
|
+
typescript: ""
|
|
1666
|
+
};
|
|
1667
|
+
}
|
|
1668
|
+
function emptyDocs(art) {
|
|
1669
|
+
return {
|
|
1670
|
+
markdown: "",
|
|
1671
|
+
title: art.metadata.title,
|
|
1672
|
+
variant_count: art.variants.length
|
|
1673
|
+
};
|
|
1674
|
+
}
|
|
1675
|
+
function emptyTokens() {
|
|
1676
|
+
return {
|
|
1677
|
+
categories: [],
|
|
1678
|
+
tokenMap: {},
|
|
1679
|
+
meta: {
|
|
1680
|
+
filePath: "",
|
|
1681
|
+
tokenCount: 0,
|
|
1682
|
+
primitiveCount: 0,
|
|
1683
|
+
semanticCount: 0
|
|
1684
|
+
}
|
|
1685
|
+
};
|
|
1686
|
+
}
|
|
1687
|
+
//#endregion
|
|
1688
|
+
//#region src/static-base.ts
|
|
1689
|
+
const TEXT_GALLERY_ASSET_EXT = /\.(?:css|html|js|map|mjs)$/u;
|
|
1690
|
+
function rewriteGalleryBase(source, basePath) {
|
|
1691
|
+
return source.replaceAll("/__musea__/", `${basePath.replace(/\/?$/, "/")}`);
|
|
1692
|
+
}
|
|
1693
|
+
function rewriteGalleryTextAssetBase(source, relativePath, basePath) {
|
|
1694
|
+
if (!TEXT_GALLERY_ASSET_EXT.test(relativePath)) return source;
|
|
1695
|
+
return rewriteGalleryBase(Buffer.from(source).toString("utf-8"), basePath);
|
|
1696
|
+
}
|
|
1697
|
+
function publicBasePathFromViteBase(viteBase, basePath) {
|
|
1698
|
+
return viteBase && viteBase !== "/" && viteBase !== "./" ? joinUrlPath(viteBase, basePath) : basePath;
|
|
1699
|
+
}
|
|
1700
|
+
//#endregion
|
|
1701
|
+
//#region src/art-style.ts
|
|
1702
|
+
function artScopeAttribute(filePath) {
|
|
1703
|
+
return `data-v-${createHash("sha256").update(filePath).digest("hex").slice(0, 8)}`;
|
|
1704
|
+
}
|
|
1705
|
+
function stampScopeAttribute(template, scopeAttr) {
|
|
1706
|
+
return template.replace(/<([A-Za-z][\w:.-]*)([^<>]*?)>/g, (match, tag, rest) => {
|
|
1707
|
+
if (rest.includes(scopeAttr)) return match;
|
|
1708
|
+
const selfClosing = /\/\s*$/.test(rest);
|
|
1709
|
+
const attrs = selfClosing ? rest.replace(/\/\s*$/, "").trimEnd() : rest.trimEnd();
|
|
1710
|
+
return `<${tag}${`${attrs.length > 0 && !attrs.startsWith(" ") && !attrs.startsWith("\n") ? " " : ""}${attrs}`.trimEnd()} ${scopeAttr}${selfClosing ? " /" : ""}>`;
|
|
1711
|
+
});
|
|
1712
|
+
}
|
|
1713
|
+
//#endregion
|
|
1714
|
+
//#region src/plugin/art-processing.ts
|
|
1715
|
+
function extractArtTagAttributes(source) {
|
|
1716
|
+
const artTagMatch = source.match(/<art\b([\s\S]*?)>/i);
|
|
1717
|
+
if (!artTagMatch) return {};
|
|
1718
|
+
const attributes = {};
|
|
1719
|
+
for (const match of artTagMatch[1].matchAll(/([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'))?/g)) {
|
|
1720
|
+
const name = match[1];
|
|
1721
|
+
if (!name || name === "/") continue;
|
|
1722
|
+
attributes[name] = match[2] ?? match[3] ?? true;
|
|
1723
|
+
}
|
|
1724
|
+
return attributes;
|
|
1725
|
+
}
|
|
1726
|
+
function parseActionEvents(value) {
|
|
1727
|
+
if (typeof value !== "string") return void 0;
|
|
1728
|
+
const events = value.split(",").map((eventName) => eventName.trim().toLowerCase()).filter(Boolean);
|
|
1729
|
+
return events.length > 0 ? [...new Set(events)] : void 0;
|
|
1730
|
+
}
|
|
1731
|
+
function extractCustomArtMetadata(source) {
|
|
1732
|
+
const attrs = extractArtTagAttributes(source);
|
|
1733
|
+
const actionEvents = new Set(parseActionEvents(attrs["action-events"]) ?? []);
|
|
1734
|
+
const captureMousemove = attrs["capture-mousemove"];
|
|
1735
|
+
if (captureMousemove === true || captureMousemove === "true") actionEvents.add("mousemove");
|
|
1736
|
+
return { actionEvents: actionEvents.size > 0 ? [...actionEvents] : void 0 };
|
|
1737
|
+
}
|
|
1738
|
+
function extractStyleBlocks(source, filePath) {
|
|
1739
|
+
const styles = [];
|
|
1740
|
+
for (const match of source.matchAll(/<style\b([^>]*)>([\s\S]*?)<\/style>/gi)) {
|
|
1741
|
+
const attrs = match[1] ?? "";
|
|
1742
|
+
const content = match[2]?.trim();
|
|
1743
|
+
const lang = attrs.match(/\blang\s*=\s*["']([^"']+)["']/i)?.[1]?.toLowerCase();
|
|
1744
|
+
if (!content) continue;
|
|
1745
|
+
if (lang && lang !== "css") {
|
|
1746
|
+
console.warn(`[musea] ${filePath}: <style lang="${lang}"> is not processed. Art styles are plain CSS.`);
|
|
1747
|
+
continue;
|
|
1748
|
+
}
|
|
1749
|
+
styles.push({
|
|
1750
|
+
content,
|
|
1751
|
+
scoped: /\bscoped\b/i.test(attrs)
|
|
1752
|
+
});
|
|
1753
|
+
}
|
|
1754
|
+
if (!styles.some((style) => style.scoped)) return { blocks: styles.map((style) => style.content) };
|
|
1755
|
+
const scopeAttr = artScopeAttribute(filePath);
|
|
1756
|
+
const scope = loadNative().scopeViteCssForPipeline;
|
|
1757
|
+
return {
|
|
1758
|
+
scopeAttr,
|
|
1759
|
+
blocks: styles.map((style) => style.scoped && scope ? scope(style.content, scopeAttr) : style.content)
|
|
1760
|
+
};
|
|
1761
|
+
}
|
|
1762
|
+
function formatArtProcessingError(root, filePath, error) {
|
|
1763
|
+
const detail = error instanceof Error ? error.message || error.name : error == null ? "unknown error" : stringifyUnknown(error);
|
|
1764
|
+
return `[musea] Failed to process ${path.relative(root, filePath) || filePath}: ${detail}`;
|
|
1765
|
+
}
|
|
1766
|
+
function stringifyUnknown(value) {
|
|
1767
|
+
if (typeof value === "string") return value;
|
|
1768
|
+
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return value.toString();
|
|
1769
|
+
try {
|
|
1770
|
+
return JSON.stringify(value) ?? "unknown error";
|
|
1771
|
+
} catch {
|
|
1772
|
+
return "unknown error";
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
function reportArtStatusWarnings(binding, source, filename, warn = console.warn) {
|
|
1776
|
+
const warnings = binding.parseArtStatusWarnings?.(source, { filename });
|
|
1777
|
+
if (warnings == null) return;
|
|
1778
|
+
for (const warning of warnings) warn(`[musea] ${warning}`);
|
|
1779
|
+
}
|
|
1780
|
+
async function processMuseaArtFile(filePath, ctx) {
|
|
1781
|
+
try {
|
|
1782
|
+
const source = await fs.promises.readFile(filePath, "utf-8");
|
|
1783
|
+
const binding = loadNative();
|
|
1784
|
+
const parsed = binding.parseArt(source, { filename: filePath });
|
|
1785
|
+
reportArtStatusWarnings(binding, source, filePath);
|
|
1786
|
+
const customMetadata = extractCustomArtMetadata(source);
|
|
1787
|
+
if (!parsed.variants || parsed.variants.length === 0) return null;
|
|
1788
|
+
const isInline = !filePath.endsWith(".art.vue");
|
|
1789
|
+
const styles = isInline ? { blocks: [] } : extractStyleBlocks(source, filePath);
|
|
1790
|
+
return {
|
|
1791
|
+
path: filePath,
|
|
1792
|
+
metadata: {
|
|
1793
|
+
title: parsed.metadata.title || (isInline ? path.basename(filePath, ".vue") : ""),
|
|
1794
|
+
description: parsed.metadata.description,
|
|
1795
|
+
component: isInline ? void 0 : parsed.metadata.component,
|
|
1796
|
+
category: parsed.metadata.category,
|
|
1797
|
+
tags: parsed.metadata.tags,
|
|
1798
|
+
status: parsed.metadata.status,
|
|
1799
|
+
order: parsed.metadata.order,
|
|
1800
|
+
actionEvents: customMetadata.actionEvents ?? parsed.metadata.actionEvents
|
|
1801
|
+
},
|
|
1802
|
+
variants: parsed.variants.map((v) => ({
|
|
1803
|
+
name: v.name,
|
|
1804
|
+
template: styles.scopeAttr ? stampScopeAttribute(v.template, styles.scopeAttr) : v.template,
|
|
1805
|
+
isDefault: v.isDefault,
|
|
1806
|
+
skipVrt: v.skipVrt
|
|
1807
|
+
})),
|
|
1808
|
+
hasScriptSetup: isInline ? false : parsed.hasScriptSetup,
|
|
1809
|
+
scriptSetupContent: !isInline && parsed.hasScriptSetup ? extractScriptSetupContent(source) : void 0,
|
|
1810
|
+
scriptSetupIsolated: !isInline && parsed.hasScriptSetup ? extractScriptSetupIsolated(source) : true,
|
|
1811
|
+
hasScript: parsed.hasScript,
|
|
1812
|
+
styleCount: parsed.styleCount,
|
|
1813
|
+
styleBlocks: styles.blocks,
|
|
1814
|
+
isInline,
|
|
1815
|
+
componentPath: isInline ? filePath : void 0
|
|
1816
|
+
};
|
|
1817
|
+
} catch (error) {
|
|
1818
|
+
const message = formatArtProcessingError(ctx.root, filePath, error);
|
|
1819
|
+
if (ctx.command === "build") throw new Error(message);
|
|
1820
|
+
(ctx.onError ?? console.error)(message);
|
|
1821
|
+
return null;
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
//#endregion
|
|
1825
|
+
//#region src/plugin/options.ts
|
|
1826
|
+
const MUSEA_OPTIONS_KEY = "__vizeMuseaOptions";
|
|
1827
|
+
function attachMuseaOptions(plugin, options) {
|
|
1828
|
+
Object.defineProperty(plugin, MUSEA_OPTIONS_KEY, {
|
|
1829
|
+
configurable: false,
|
|
1830
|
+
enumerable: false,
|
|
1831
|
+
value: options,
|
|
1832
|
+
writable: false
|
|
1833
|
+
});
|
|
1834
|
+
return plugin;
|
|
1835
|
+
}
|
|
1836
|
+
function readMuseaOptions(plugin) {
|
|
1837
|
+
if (!plugin || typeof plugin !== "object") return void 0;
|
|
1838
|
+
return plugin[MUSEA_OPTIONS_KEY];
|
|
1839
|
+
}
|
|
1840
|
+
//#endregion
|
|
1841
|
+
export { tokenNative as C, rewriteRelativeImportStatement as D, parseScriptSetupForArt as E, expandSelfTag as O, parseTokens as S, generateArtModule as T, handleTokensUpdate as _, rewriteGalleryBase as a, resolveReferences as b, joinUrlPath as c, handleArtDocs as d, handleArtSource as f, handleTokensGet as g, handleTokensDelete as h, publicBasePathFromViteBase as i, resolveArtComponent as k, staticPreviewId as l, handleTokensCreate as m, readMuseaOptions as n, rewriteGalleryTextAssetBase as o, handleArtPalette as p, processMuseaArtFile as r, createStaticGalleryPayload as s, attachMuseaOptions as t, handleArtAnalysis as u, handleTokensUsage as v, sortedArts as w, scanTokenUsage as x, buildTokenMap as y };
|
|
1842
|
+
|
|
1843
|
+
//# sourceMappingURL=options-DCuB_Fpu.mjs.map
|