@recursica/mantine-adapter 0.9.2 → 0.9.3

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/main.js ADDED
@@ -0,0 +1,922 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+
5
+ /**
6
+ * Checks if a given directory contains files with either theme-tokens or ui-kit suffix
7
+ * @param directoryPath - The path to check for files
8
+ * @returns FileCheckResult - Object containing boolean result and array of matching files with full paths
9
+ */
10
+ function hasThemeOrKitFiles(directoryPath) {
11
+ try {
12
+ const files = fs.readdirSync(directoryPath);
13
+ const matchingFiles = files.find((file) => {
14
+ const fileName = file.toLowerCase();
15
+ return fileName === "recursica-bundle.json";
16
+ });
17
+ return matchingFiles ? path.join(directoryPath, matchingFiles) : undefined;
18
+ }
19
+ catch (error) {
20
+ console.error(`Error checking directory ${directoryPath}:`, error);
21
+ return undefined;
22
+ }
23
+ }
24
+ function hasIconsJsonFiles(directoryPath) {
25
+ try {
26
+ const files = fs.readdirSync(directoryPath);
27
+ const matchingFiles = files
28
+ .filter((file) => {
29
+ const fileName = file.toLowerCase();
30
+ return fileName === "recursica-icons.json";
31
+ })
32
+ .map((file) => path.join(directoryPath, file));
33
+ return matchingFiles.length > 0 ? matchingFiles[0] : undefined;
34
+ }
35
+ catch (error) {
36
+ console.error(`Error checking directory ${directoryPath}:`, error);
37
+ return undefined;
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Loads and validates the configuration from recursicaConfig.json
43
+ *
44
+ * @throws {Error} If the config file is not found or required fields are missing
45
+ * @returns {Object} Configuration object with the following properties:
46
+ * - jsons: Path to the themes-tokens and ui-kit directories
47
+ * - srcPath: Path to the source directory
48
+ * - project: Project name
49
+ */
50
+ function loadConfig() {
51
+ let rootPath = getRootPath();
52
+ const configPath = path.join(rootPath, "recursica.json");
53
+ if (!fs.existsSync(configPath)) {
54
+ throw new Error("Config file not found at: " + configPath);
55
+ }
56
+ const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
57
+ if (typeof config.project === "object" && config.project?.root) {
58
+ rootPath = path.join(rootPath, config.project.root);
59
+ }
60
+ const bundledJson = hasThemeOrKitFiles(rootPath);
61
+ const iconsJson = hasIconsJsonFiles(rootPath);
62
+ const project = config.project;
63
+ if (!project) {
64
+ throw new Error("project is required in config file");
65
+ }
66
+ return {
67
+ rootPath,
68
+ srcPath: path.join(rootPath, "src"),
69
+ project,
70
+ bundledJson,
71
+ iconsJson,
72
+ overrides: config.overrides,
73
+ iconsConfig: config.icons,
74
+ };
75
+ }
76
+ function getRootPath() {
77
+ // recursively search for the package.json file starting from the current working directory
78
+ let currentDir = process.cwd();
79
+ let level = 0;
80
+ while (!fs.existsSync(path.join(currentDir, "recursica.json"))) {
81
+ currentDir = path.join(currentDir, "..");
82
+ level++;
83
+ if (level > 10) {
84
+ throw new Error("Could not find recursica.json");
85
+ }
86
+ }
87
+ return currentDir;
88
+ }
89
+
90
+ /**
91
+ * Type guard function to check if a token is a FontFamilyToken
92
+ *
93
+ * @param token - The token to check
94
+ * @returns True if the token has fontFamily and variableName properties, indicating it's a FontFamilyToken
95
+ */
96
+ function isFontFamilyToken(token) {
97
+ return "fontFamily" in token && "variableName" in token;
98
+ }
99
+ /**
100
+ * Type guard function to check if a token is an EffectToken
101
+ *
102
+ * @param token - The token to check
103
+ * @returns True if the token has effects and variableName properties, indicating it's an EffectToken
104
+ */
105
+ function isEffectToken(token) {
106
+ return "effects" in token && "variableName" in token;
107
+ }
108
+ /**
109
+ * Type guard function to check if a token is a basic Token (color or float)
110
+ *
111
+ * @param token - The token to check
112
+ * @returns True if the token has mode, type, name, and value properties, indicating it's a basic Token
113
+ */
114
+ function isColorOrFloatToken(token) {
115
+ return ("mode" in token && "type" in token && "name" in token && "value" in token);
116
+ }
117
+
118
+ function autoGeneratedFile() {
119
+ return `/* prettier-ignore */
120
+ /* eslint-disable */
121
+ /* tslint:disable */
122
+ /*
123
+ Auto-generated by Recursica.
124
+ Do NOT edit these files directly\n
125
+ For more information about Recursica, go to https://recursica.com
126
+ */
127
+ `;
128
+ }
129
+
130
+ function capitalize(str) {
131
+ return str.replace(/-/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
132
+ }
133
+
134
+ class ProcessTokens {
135
+ constructor(overrides) {
136
+ this.tokens = {};
137
+ this.themes = {};
138
+ this.breakpoints = {};
139
+ this.colors = [];
140
+ this.spacers = [];
141
+ this.borderRadius = [];
142
+ this.uiKit = {};
143
+ this.processValue = (target, token) => {
144
+ if (typeof token.value === "string") {
145
+ target[token.name] = token.value;
146
+ return true;
147
+ }
148
+ if (typeof token.value === "number") {
149
+ target[token.name] = `${token.value}px`;
150
+ return true;
151
+ }
152
+ if (typeof token.value === "object") {
153
+ target[token.name] = token.value;
154
+ return true;
155
+ }
156
+ return false;
157
+ };
158
+ this.overrides = overrides;
159
+ }
160
+ processTokenValue(token, modeName, jsonThemeName) {
161
+ if (token.collection === "Breakpoints") {
162
+ this.processValue(this.breakpoints, token);
163
+ // Add breakpoints to uiKit with 'breakpoints/' prefix
164
+ const uiKitTarget = {};
165
+ this.processValue(uiKitTarget, token);
166
+ Object.entries(uiKitTarget).forEach(([key, value]) => {
167
+ // Ensure we only store string values
168
+ if (typeof value === "string") {
169
+ this.uiKit[`breakpoint/${key}`] = value;
170
+ }
171
+ else if (typeof value === "number") {
172
+ this.uiKit[`breakpoint/${key}`] = `${value.toString()}px`;
173
+ }
174
+ });
175
+ }
176
+ else if (token.collection === "UI Kit") {
177
+ this.processValue(this.uiKit, token);
178
+ }
179
+ else if (token.collection === "Tokens") {
180
+ this.processValue(this.tokens, token);
181
+ }
182
+ else {
183
+ if (!jsonThemeName)
184
+ return;
185
+ if (!this.themes[jsonThemeName])
186
+ this.themes[jsonThemeName] = {};
187
+ if (!this.themes[jsonThemeName][modeName])
188
+ this.themes[jsonThemeName][modeName] = {};
189
+ this.processValue(this.themes[jsonThemeName][modeName], token);
190
+ }
191
+ }
192
+ processTokens(variables, jsonThemeName) {
193
+ // Process tokens collection
194
+ for (const token of Object.values(variables)) {
195
+ if (isFontFamilyToken(token)) {
196
+ if (!jsonThemeName)
197
+ continue;
198
+ if (!this.tokens[jsonThemeName])
199
+ this.tokens[jsonThemeName] = {};
200
+ if (typeof this.tokens[jsonThemeName] !== "object")
201
+ this.tokens[jsonThemeName] = {};
202
+ this.tokens[jsonThemeName][`typography/${token.variableName}`] =
203
+ this.overrides?.fontFamily?.[token.fontFamily] ?? token.fontFamily;
204
+ this.tokens[jsonThemeName][`typography/${token.variableName}-size`] =
205
+ `${token.fontSize.toString()}px`;
206
+ // check if overrides.fontWeight is defined
207
+ if (this.overrides?.fontWeight) {
208
+ const weight = this.overrides.fontWeight.find((weight) => weight.alias === token.fontWeight.alias &&
209
+ weight.fontFamily === token.fontFamily);
210
+ // check if there's a weight that matches the alias and fontFamily
211
+ // if there is, use the value from the overrides
212
+ // if there isn't, use the value from the token
213
+ if (weight) {
214
+ this.tokens[jsonThemeName][`typography/${token.variableName}-weight`] = weight.value.toString();
215
+ }
216
+ else {
217
+ this.tokens[jsonThemeName][`typography/${token.variableName}-weight`] = token.fontWeight.value.toString();
218
+ }
219
+ }
220
+ else {
221
+ this.tokens[jsonThemeName][`typography/${token.variableName}-weight`] = token.fontWeight.value.toString();
222
+ }
223
+ if (token.lineHeight.unit === "PERCENT") {
224
+ this.tokens[jsonThemeName][`typography/${token.variableName}-line-height`] = `${token.lineHeight.value.toString()}%`;
225
+ }
226
+ else {
227
+ this.tokens[jsonThemeName][`typography/${token.variableName}-line-height`] = "1.2";
228
+ }
229
+ this.tokens[jsonThemeName][`typography/${token.variableName}-letter-spacing`] =
230
+ token.letterSpacing.unit === "PIXELS"
231
+ ? `${token.letterSpacing.value.toString()}px`
232
+ : `${token.letterSpacing.value.toString()}%`;
233
+ this.tokens[jsonThemeName][`typography/${token.variableName}-text-case`] = token.textCase;
234
+ this.tokens[jsonThemeName][`typography/${token.variableName}-text-decoration`] = token.textDecoration;
235
+ continue;
236
+ }
237
+ if (isEffectToken(token)) {
238
+ const effectValue = [];
239
+ token.effects.forEach((effect) => {
240
+ const { color: { r, g, b, a }, offset: { x, y }, radius, spread, } = effect;
241
+ effectValue.push(`${x.toString()}px ${y.toString()}px ${radius.toString()}px ${spread.toString()}px rgba(${r.toString()}, ${g.toString()}, ${b.toString()}, ${a.toString()})`);
242
+ });
243
+ this.tokens[`effect/${token.variableName}`] = effectValue.join(", ");
244
+ continue;
245
+ }
246
+ if (isColorOrFloatToken(token)) {
247
+ const modeName = capitalize(token.mode)
248
+ .replace(/[()/]/g, "-")
249
+ .replace(/\s/g, "")
250
+ .replace(/-$/, "");
251
+ if (modeName !== "mode1")
252
+ this.themes[modeName] = {};
253
+ if (token.type === "color" && !this.colors.includes(token.name)) {
254
+ this.colors.push(token.name);
255
+ }
256
+ if (token.name.startsWith("size/spacer/") &&
257
+ !this.spacers.includes(token.name)) {
258
+ this.spacers.push(token.name);
259
+ }
260
+ if (token.name.startsWith("size/border-radius/") &&
261
+ !this.borderRadius.includes(token.name)) {
262
+ this.borderRadius.push(token.name);
263
+ }
264
+ this.processTokenValue(token, modeName, jsonThemeName);
265
+ }
266
+ else {
267
+ console.warn(`${JSON.stringify(token, null, 2)} could not be processed`);
268
+ }
269
+ }
270
+ }
271
+ }
272
+
273
+ function parseValue(value, recursicaTokens) {
274
+ if (typeof value === "object") {
275
+ if (value.collection === "Tokens") {
276
+ return `${recursicaTokens}["${value.name}"]`;
277
+ }
278
+ if (value.collection === "Themes") {
279
+ return `themeVars["${value.name}"]`;
280
+ }
281
+ }
282
+ else if (!isNaN(Number(value))) {
283
+ return `"${value}"`;
284
+ }
285
+ return `"${value.toString()}"`;
286
+ }
287
+ function generateTypeDefinitions(themeDef) {
288
+ // Extract all unique theme modes from themeDef
289
+ const allThemeModes = new Set();
290
+ Object.values(themeDef).forEach((themeVariants) => {
291
+ Object.keys(themeVariants).forEach((mode) => {
292
+ allThemeModes.add(mode);
293
+ });
294
+ });
295
+ // Generate the ThemeVariant interface dynamically
296
+ const themeVariantProperties = Array.from(allThemeModes)
297
+ .sort() // Sort for consistent output
298
+ .map((mode) => ` ${mode}: string;`)
299
+ .join("\n");
300
+ return `${autoGeneratedFile()}
301
+ import { THEMES } from "./RecursicaThemes";
302
+
303
+ export interface ThemeVariant {
304
+ ${themeVariantProperties}
305
+ }
306
+
307
+ // TypeScript will automatically infer this as a union of literal types
308
+ export type ThemeType = typeof THEMES[keyof typeof THEMES];
309
+
310
+ export type ThemeDictionary = Record<ThemeType, ThemeVariant>;
311
+ `;
312
+ }
313
+ function generateVanillaExtractThemes(tokens, themes, recursicaTokensFilename, { outputPath, project }) {
314
+ const themesContent = [];
315
+ // Contract tokens
316
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
317
+ const themeContractFilename = `Recursica${projectName}ContractTheme.css`;
318
+ const contractThemeOutputPath = outputPath + "/" + `${themeContractFilename}.ts`;
319
+ const contractTokens = {};
320
+ const themeDef = {};
321
+ for (const [rawThemeName, currentTheme] of Object.entries(themes)) {
322
+ for (const [key, theme] of Object.entries(currentTheme)) {
323
+ const currentThemeName = capitalize(rawThemeName);
324
+ const recursicaTokens = `Recursica${projectName}Tokens`;
325
+ const themeKey = key.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
326
+ const themeName = `${currentThemeName}${themeKey}Theme`;
327
+ if (!themeDef[currentThemeName]) {
328
+ themeDef[currentThemeName] = {};
329
+ }
330
+ themeDef[currentThemeName][themeKey] = themeName;
331
+ const generatedThemeContent = `${autoGeneratedFile()}
332
+ import { createTheme } from '@vanilla-extract/css';
333
+
334
+ import { themeVars } from './${themeContractFilename.replace(".ts", "")}'
335
+ import { ${recursicaTokens} } from './${recursicaTokensFilename.replace(".ts", "")}'
336
+
337
+ export const ${themeName} = createTheme(themeVars,{
338
+ ${Object.entries(theme)
339
+ .map(([key, value]) => {
340
+ contractTokens[key] = null;
341
+ return `'${key}': ${parseValue(value, recursicaTokens)}`;
342
+ })
343
+ .join(",\n\t")},
344
+ ${Object.entries(tokens?.[rawThemeName] ?? {})
345
+ .map(([key, value]) => {
346
+ contractTokens[key] = null;
347
+ return `'${key}': ${parseValue(value, recursicaTokens)}`;
348
+ })
349
+ .join(",\n\t")}
350
+ })`;
351
+ themesContent.push({
352
+ name: themeName,
353
+ content: generatedThemeContent,
354
+ });
355
+ }
356
+ }
357
+ let themesFileContent = autoGeneratedFile();
358
+ const vanillaExtractThemes = [];
359
+ for (const theme of themesContent) {
360
+ const themeName = `Recursica${projectName}${theme.name}`;
361
+ const autoGeneratedThemeFilename = `${themeName}.css.ts`;
362
+ const themeFilePath = outputPath + "/" + autoGeneratedThemeFilename;
363
+ vanillaExtractThemes.push({
364
+ content: theme.content,
365
+ path: themeFilePath,
366
+ filename: autoGeneratedThemeFilename,
367
+ });
368
+ // generate a theme.css.ts where we import all the themes using just 1 variables (1 export)
369
+ themesFileContent += `export { ${theme.name} } from './${autoGeneratedThemeFilename.replace(".ts", "")}';\n`;
370
+ themesFileContent += `import { ${theme.name} } from './${autoGeneratedThemeFilename.replace(".ts", "")}';\n`;
371
+ }
372
+ themesFileContent += `\nexport const Themes = {
373
+ ${Object.entries(themeDef)
374
+ .map(([key, value]) => `'${key}': {
375
+ ${Object.entries(value)
376
+ .map(([key, value]) => `'${key}': ${value}`)
377
+ .join(",\n\t\t")}`)
378
+ .join("\n\t},\n\t")}
379
+ }
380
+ }`;
381
+ // create the themes.ts file
382
+ const availableThemesContent = `${autoGeneratedFile()}
383
+ export const AvailableThemes = [${themesContent.map((theme) => `"${theme.name}"`).join(", ")}] as const;
384
+ export type AvailableThemesType = (typeof AvailableThemes)[number];
385
+ `;
386
+ const availableThemesPath = outputPath + "/types.ts";
387
+ const themeContractContent = `${autoGeneratedFile()}
388
+ import { createThemeContract } from '@vanilla-extract/css';
389
+
390
+ export const themeVars = createThemeContract(${JSON.stringify(contractTokens, null, 2)});
391
+ `;
392
+ const themesFilename = `Recursica${projectName}Themes.css.ts`;
393
+ const themesFilePath = outputPath + "/" + themesFilename;
394
+ // Generate type definitions in types.d.ts
395
+ const typeDefinitionsContent = generateTypeDefinitions(themeDef);
396
+ const typesPath = outputPath + "/types.d.ts";
397
+ return {
398
+ typeDefinitions: {
399
+ content: typeDefinitionsContent,
400
+ path: typesPath,
401
+ filename: "types.d.ts",
402
+ },
403
+ themesFileContent: {
404
+ content: themesFileContent,
405
+ path: themesFilePath,
406
+ filename: themesFilename,
407
+ },
408
+ availableThemes: {
409
+ content: availableThemesContent,
410
+ path: availableThemesPath,
411
+ filename: "types.ts",
412
+ },
413
+ vanillaExtractThemes,
414
+ themeContract: {
415
+ content: themeContractContent,
416
+ path: contractThemeOutputPath,
417
+ filename: themeContractFilename,
418
+ },
419
+ contractTokens,
420
+ };
421
+ }
422
+
423
+ function generateRecursicaTokens(baseTokens, { outputPath, project }) {
424
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
425
+ const recursicaTokensFilename = `Recursica${projectName}Tokens.ts`;
426
+ const recursicaTokensPath = outputPath + "/" + recursicaTokensFilename;
427
+ const recursicaTokensContent = `${autoGeneratedFile()}
428
+ export const Recursica${projectName}Tokens = {
429
+ ${Object.entries(baseTokens)
430
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
431
+ .filter(([_, value]) => typeof value === "string")
432
+ .map(([key, value]) => `"${key}": "${value}"`)
433
+ .join(",\n ")}
434
+ };
435
+ `;
436
+ return {
437
+ content: recursicaTokensContent,
438
+ path: recursicaTokensPath,
439
+ filename: recursicaTokensFilename,
440
+ };
441
+ }
442
+
443
+ function generateUiKit(uiKit, { recursicaTokensFilename, themeContractFilename }, { outputPath, project }) {
444
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
445
+ const uiKitFilename = `Recursica${projectName}UiKit.ts`;
446
+ const uiKitPath = outputPath + "/" + uiKitFilename;
447
+ const recursicaTokens = `Recursica${projectName}Tokens`;
448
+ const uiKitContent = `${autoGeneratedFile()}
449
+ import { themeVars } from './${themeContractFilename.replace(".ts", "")}'
450
+ import { ${recursicaTokens} } from './${recursicaTokensFilename.replace(".ts", "")}'
451
+
452
+ export const uiKit = {
453
+ ${Object.entries(uiKit)
454
+ .map(([key, value]) => `'${key}': ${parseValue(value, recursicaTokens)}`)
455
+ .join(",\n\t")}\n\t}`;
456
+ return {
457
+ content: uiKitContent,
458
+ path: uiKitPath,
459
+ filename: uiKitFilename,
460
+ };
461
+ }
462
+
463
+ function parseKey(key) {
464
+ return key.replaceAll("/", "-");
465
+ }
466
+ function generateMantineTheme({ mantineThemeOverride, tokens, breakpoints, contractTokens: { tokens: contractTokens, filename: contractFilename }, exportingProps: { outputPath, project, rootPath }, }) {
467
+ const themeTokens = {
468
+ colors: {},
469
+ radius: {},
470
+ fontSizes: {},
471
+ primaryColor: mantineThemeOverride?.["1-scale"],
472
+ white: mantineThemeOverride?.background,
473
+ };
474
+ for (const [key, value] of Object.entries(tokens)) {
475
+ if (typeof value === "object")
476
+ continue;
477
+ if (key.includes("border-radius")) {
478
+ themeTokens.radius[parseKey(key)] = value;
479
+ }
480
+ if (key.includes("font/size")) {
481
+ themeTokens.fontSizes[parseKey(key)] = `"${value}"`;
482
+ }
483
+ }
484
+ for (const [key] of Object.entries(contractTokens)) {
485
+ if (key.includes("color/") || key.includes("color-on/")) {
486
+ themeTokens.colors[parseKey(key)] = `themeVars['${key}']`;
487
+ }
488
+ if (/font\/(\w+)\/size/.test(key)) {
489
+ themeTokens.fontSizes[parseKey(key)] = `themeVars['${key}']`;
490
+ }
491
+ }
492
+ const postCssFilename = "postcss.config.cjs";
493
+ let postCssContent = `${autoGeneratedFile()}\n`;
494
+ postCssContent += `module.exports = {
495
+ plugins: {
496
+ 'postcss-preset-mantine': {},
497
+ 'postcss-simple-vars': {
498
+ variables: {`;
499
+ for (const [key, value] of Object.entries(breakpoints)) {
500
+ postCssContent += `\n\t\t\t\t'mantine-breakpoint-${key}': '${value}',`;
501
+ }
502
+ postCssContent += `
503
+ }
504
+ }
505
+ }
506
+ }`;
507
+ const postCssFileContent = {
508
+ content: postCssContent,
509
+ path: rootPath ? rootPath + "/" + postCssFilename : postCssFilename,
510
+ filename: postCssFilename,
511
+ };
512
+ const fileContent = `${autoGeneratedFile()}
513
+ import { colorsTuple, createTheme } from '@mantine/core'
514
+ import { themeVars } from './${contractFilename.replace(".ts", "")}'
515
+
516
+ export const mantineTheme = createTheme({
517
+ ${themeTokens.primaryColor ? `primaryColor: ${themeTokens.primaryColor},` : ""}
518
+ ${themeTokens.white ? `white: ${themeTokens.white},` : ""}
519
+ breakpoints: {
520
+ ${Object.entries(breakpoints)
521
+ .map(([key, value]) => `'${key}': '${value}'`)
522
+ .join(",\n\t\t")}
523
+ },
524
+ colors: {
525
+ ${Object.entries(themeTokens.colors)
526
+ .map(([key, value]) => `"${key}": colorsTuple(${value})`)
527
+ .join(",\n\t\t")}
528
+ },
529
+ radius: {
530
+ ${Object.entries(themeTokens.radius)
531
+ .map(([key, value]) => `"${key}": "${value}"`)
532
+ .join(",\n\t\t")}
533
+ },
534
+ fontSizes: {
535
+ ${Object.entries(themeTokens.fontSizes)
536
+ .map(([key, value]) => `"${key}": ${value}`)
537
+ .join(",\n\t\t")}
538
+ }
539
+ })`;
540
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
541
+ const filename = `Recursica${projectName}MantineTheme.ts`;
542
+ const mantineThemeFileContent = {
543
+ content: fileContent,
544
+ path: outputPath + "/" + filename,
545
+ filename,
546
+ };
547
+ return { mantineTheme: mantineThemeFileContent, postCss: postCssFileContent };
548
+ }
549
+
550
+ function createRecursicaObject(project, outputPath) {
551
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
552
+ const tokens = `Recursica${projectName}Tokens`;
553
+ const contract = `Recursica${projectName}ContractTheme`;
554
+ const uiKit = `Recursica${projectName}UiKit`;
555
+ const recursicaObjectContent = `${autoGeneratedFile()}
556
+ import { ${tokens} } from './${tokens}';
557
+ import { themeVars } from './${contract}.css';
558
+ import { uiKit } from './${uiKit}';
559
+
560
+ export const recursica = {
561
+ ...uiKit,
562
+ ...themeVars,
563
+ ...${tokens},
564
+ }
565
+ `;
566
+ return {
567
+ content: recursicaObjectContent,
568
+ path: outputPath + "/Recursica.ts",
569
+ filename: "Recursica.ts",
570
+ };
571
+ }
572
+
573
+ function generateColorsType(colorTokens, outputPath) {
574
+ const colorsType = `${autoGeneratedFile()}
575
+ export type RecursicaColors = \n\t"${colorTokens.join('" |\n\t"')}";\n`;
576
+ return {
577
+ content: colorsType,
578
+ path: `${outputPath}/RecursicaColorsType.ts`,
579
+ filename: "RecursicaColorsType.ts",
580
+ };
581
+ }
582
+
583
+ function generateIcons(icons, srcPath, config) {
584
+ let iconsPath;
585
+ if (!config?.output) {
586
+ iconsPath = srcPath + "/components" + "/Icons";
587
+ }
588
+ else {
589
+ iconsPath = srcPath + "/" + config.output;
590
+ }
591
+ const svgPath = iconsPath + "/Svg";
592
+ const exportedIcons = [];
593
+ // Generate svg files
594
+ for (const [rawIconName, iconPath] of Object.entries(icons)) {
595
+ const [iconName, variant] = rawIconName.split("[");
596
+ let cleanIconName = iconName.replaceAll("-", "_");
597
+ // check if the iconName is in the names array, if not, skip
598
+ if (!config?.include?.names?.includes(cleanIconName)) {
599
+ continue;
600
+ }
601
+ // detect if the iconName starts with a number, if so, add an underscore to the beginning
602
+ if (cleanIconName.match(/^\d/)) {
603
+ cleanIconName = `_${cleanIconName}`;
604
+ }
605
+ const cleanVariant = variant.replace("]", "").replace("Style=", "");
606
+ const codedVariant = cleanVariant.replaceAll(" ", "_");
607
+ // check if the codedVariant is in the variants array, if not, skip
608
+ if (!config?.include?.variants?.includes(codedVariant)) {
609
+ continue;
610
+ }
611
+ const finalIconName = `${cleanIconName}_${codedVariant}`;
612
+ exportedIcons.push({
613
+ content: iconPath
614
+ .replaceAll('fill="black"', "")
615
+ .replaceAll('fill="none"', ""),
616
+ path: `${svgPath}/${finalIconName}.svg`,
617
+ filename: `${finalIconName}`,
618
+ });
619
+ }
620
+ // Generate icon exports file
621
+ const exportsPath = iconsPath + "/icon_exports.ts";
622
+ let exportsContent = `${autoGeneratedFile()}
623
+ /// <reference types="vite-plugin-svgr/client" />\n`;
624
+ for (const icon of exportedIcons) {
625
+ exportsContent += `import ${icon.filename} from './Svg/${icon.filename}.svg?react';\n`;
626
+ exportsContent += `export { ${icon.filename} };\n`;
627
+ }
628
+ // Generate icon map file
629
+ const mapPath = iconsPath + "/icon_resource_map.ts";
630
+ let mapContent = `${autoGeneratedFile()}\nimport * as IconExports from './icon_exports';\n\n`;
631
+ mapContent += "export const IconResourceMap = {";
632
+ mapContent += exportedIcons
633
+ .map((icon) => `\n\t'${icon.filename}': IconExports.${icon.filename},`)
634
+ .join("");
635
+ mapContent += "\n};\n";
636
+ return {
637
+ exportedIcons,
638
+ iconExports: {
639
+ content: exportsContent,
640
+ path: exportsPath,
641
+ filename: "icon_exports.ts",
642
+ },
643
+ iconResourceMap: {
644
+ content: mapContent,
645
+ path: mapPath,
646
+ filename: "icon_resource_map.ts",
647
+ },
648
+ };
649
+ }
650
+
651
+ function generateSpacersType(spacerTokens, outputPath) {
652
+ const spacersType = `${autoGeneratedFile()}
653
+ export type RecursicaSpacersType = \n\t"${spacerTokens.join('" |\n\t"')}";\n`;
654
+ return {
655
+ content: spacersType,
656
+ path: `${outputPath}/RecursicaSpacersType.ts`,
657
+ filename: "RecursicaSpacersType.ts",
658
+ };
659
+ }
660
+
661
+ function generateBorderRadiusType(borderRadius, outputPath) {
662
+ const borderRadiusTypeContent = `${autoGeneratedFile()}
663
+ export type RecursicaBorderRadiusType = ${borderRadius
664
+ .map((key) => `'${key}'`)
665
+ .join(" | ")};
666
+ `;
667
+ return {
668
+ content: borderRadiusTypeContent,
669
+ path: `${outputPath}/RecursicaBorderRadiusType.ts`,
670
+ filename: "RecursicaBorderRadiusType.ts",
671
+ };
672
+ }
673
+
674
+ /**
675
+ * Generates the RecursicaThemes.ts file that contains the THEMES constant
676
+ * based on the theme dictionary
677
+ */
678
+ function generateRecursicaThemes({ outputPath, themes, }) {
679
+ const themeDef = {};
680
+ // Build themeDef object similar to generateVanillaExtractThemes
681
+ for (const [rawThemeName, currentTheme] of Object.entries(themes)) {
682
+ for (const [key] of Object.entries(currentTheme)) {
683
+ const currentThemeName = capitalize(rawThemeName);
684
+ const themeKey = key.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
685
+ themeDef[currentThemeName] ?? (themeDef[currentThemeName] = {});
686
+ themeDef[currentThemeName][themeKey] = currentThemeName;
687
+ }
688
+ }
689
+ const content = `/* prettier-ignore */
690
+ /* eslint-disable */
691
+ /* tslint:disable */
692
+ /*
693
+ Auto-generated by Recursica.
694
+ Do NOT edit these files directly
695
+
696
+ For more information about Recursica, go to https://recursica.com
697
+ */
698
+
699
+ // Auto-generated THEMES constant from ThemeType
700
+ export const THEMES = {
701
+ ${Object.entries(themeDef)
702
+ .map(([key]) => ` ${key}: '${key}'`)
703
+ .join(",\n")}
704
+ } as const;
705
+ `;
706
+ return {
707
+ content,
708
+ path: outputPath + "/RecursicaThemes.ts",
709
+ filename: "RecursicaThemes.ts",
710
+ };
711
+ }
712
+
713
+ function generatePrettierignore() {
714
+ return {
715
+ filename: ".prettierignore",
716
+ path: ".prettierignore",
717
+ content: `recursica/
718
+ recursica.json
719
+ recursica-bundle.json
720
+ recursica-icons.json
721
+ icon_exports.ts
722
+ icon_resource_map.ts`,
723
+ };
724
+ }
725
+
726
+ function runAdapter({ rootPath, overrides, srcPath, project, icons, iconsConfig, processTokens, }) {
727
+ const outputPath = srcPath + "/recursica";
728
+ const recursicaTokens = generateRecursicaTokens(processTokens.tokens, {
729
+ outputPath,
730
+ project,
731
+ });
732
+ const vanillaExtractThemes = generateVanillaExtractThemes(processTokens.tokens, processTokens.themes, recursicaTokens.filename, {
733
+ outputPath,
734
+ project,
735
+ });
736
+ const mantineTheme = generateMantineTheme({
737
+ mantineThemeOverride: overrides?.mantineTheme,
738
+ tokens: processTokens.tokens,
739
+ breakpoints: processTokens.breakpoints,
740
+ contractTokens: {
741
+ tokens: vanillaExtractThemes.contractTokens,
742
+ filename: vanillaExtractThemes.themeContract.filename,
743
+ },
744
+ exportingProps: {
745
+ outputPath,
746
+ project,
747
+ rootPath,
748
+ },
749
+ });
750
+ const uiKitObject = generateUiKit(processTokens.uiKit, {
751
+ recursicaTokensFilename: recursicaTokens.filename,
752
+ themeContractFilename: vanillaExtractThemes.themeContract.filename,
753
+ }, { outputPath, project });
754
+ const recursicaObject = createRecursicaObject(project, outputPath);
755
+ const colorsType = generateColorsType(processTokens.colors, outputPath);
756
+ const spacersType = generateSpacersType(processTokens.spacers, outputPath);
757
+ const borderRadiusType = generateBorderRadiusType(processTokens.borderRadius, outputPath);
758
+ let iconsObject;
759
+ if (icons) {
760
+ iconsObject = generateIcons(icons, srcPath, iconsConfig);
761
+ }
762
+ const recursicaThemes = generateRecursicaThemes({
763
+ outputPath,
764
+ themes: processTokens.themes,
765
+ });
766
+ const prettierignore = generatePrettierignore();
767
+ const fileContents = {
768
+ recursicaTokens,
769
+ vanillaExtractThemes,
770
+ mantineTheme,
771
+ uiKitObject,
772
+ recursicaObject,
773
+ colorsType,
774
+ spacersType,
775
+ borderRadiusType,
776
+ iconsObject,
777
+ recursicaThemes,
778
+ prettierignore,
779
+ };
780
+ return fileContents;
781
+ }
782
+
783
+ /**
784
+ * Processes JSON content and creates ProcessTokens instance
785
+ * This is shared logic between CLI and WebWorker
786
+ */
787
+ function processJsonContent(jsonFileContent, { project, overrides }) {
788
+ const jsonContent = JSON.parse(jsonFileContent);
789
+ const jsonProjectId = jsonContent.projectId;
790
+ if (!jsonProjectId) {
791
+ throw new Error("project-id is required in the json file");
792
+ }
793
+ if (jsonProjectId.toLowerCase() !==
794
+ (typeof project === "string"
795
+ ? project.toLowerCase()
796
+ : project.name?.toLowerCase())) {
797
+ throw new Error("project-id does not match the project in the config file");
798
+ }
799
+ const processTokens = new ProcessTokens(overrides);
800
+ processTokens.processTokens(jsonContent.tokens);
801
+ for (const theme of Object.keys(jsonContent.themes)) {
802
+ processTokens.processTokens(jsonContent.themes[theme], theme);
803
+ }
804
+ processTokens.processTokens(jsonContent.uiKit);
805
+ return processTokens;
806
+ }
807
+ /**
808
+ * Processes icons JSON content and returns icons object
809
+ * This is shared logic between CLI and WebWorker
810
+ */
811
+ function processIcons(iconsJsonContent) {
812
+ const icons = {};
813
+ const iconsJsonParsed = JSON.parse(iconsJsonContent);
814
+ for (const [iconName, iconPath] of Object.entries(iconsJsonParsed)) {
815
+ icons[iconName] = iconPath;
816
+ }
817
+ return icons;
818
+ }
819
+ /**
820
+ * Core adapter processing logic shared between CLI and WebWorker
821
+ * This function handles the main processing workflow
822
+ */
823
+ function processAdapter({ rootPath, bundledJsonContent, project, overrides, srcPath, iconsJsonContent, iconsConfig, }) {
824
+ let icons = {};
825
+ // Process icons if provided
826
+ if (iconsJsonContent) {
827
+ icons = processIcons(iconsJsonContent);
828
+ }
829
+ if (!bundledJsonContent) {
830
+ throw new Error("bundledJson content not found");
831
+ }
832
+ // Process the main JSON content
833
+ const processTokens = processJsonContent(bundledJsonContent, {
834
+ project,
835
+ overrides,
836
+ });
837
+ // Run the adapter
838
+ const files = runAdapter({
839
+ rootPath,
840
+ overrides,
841
+ srcPath,
842
+ icons,
843
+ processTokens,
844
+ project,
845
+ iconsConfig,
846
+ });
847
+ return files;
848
+ }
849
+
850
+ /**
851
+ * Main CLI function that can be called programmatically
852
+ * This is the same logic as main.ts but exported as a function
853
+ */
854
+ async function runMain() {
855
+ try {
856
+ const { rootPath, bundledJson, srcPath, project, iconsJson, overrides, iconsConfig, } = loadConfig();
857
+ if (!bundledJson)
858
+ throw new Error("bundledJson not found");
859
+ // Read file contents
860
+ const bundledJsonContent = fs.readFileSync(bundledJson, "utf-8");
861
+ const iconsJsonContent = iconsJson
862
+ ? fs.readFileSync(iconsJson, "utf-8")
863
+ : undefined;
864
+ // Use shared processing logic
865
+ const files = processAdapter({
866
+ bundledJsonContent,
867
+ project,
868
+ overrides,
869
+ rootPath,
870
+ srcPath,
871
+ iconsJsonContent,
872
+ iconsConfig,
873
+ });
874
+ const { recursicaTokens, vanillaExtractThemes, mantineTheme, uiKitObject, recursicaObject, colorsType, iconsObject, spacersType, borderRadiusType, recursicaThemes, prettierignore, } = files;
875
+ const filesToWrite = [
876
+ recursicaTokens,
877
+ vanillaExtractThemes.availableThemes,
878
+ vanillaExtractThemes.themeContract,
879
+ vanillaExtractThemes.themesFileContent,
880
+ vanillaExtractThemes.typeDefinitions,
881
+ mantineTheme.mantineTheme,
882
+ mantineTheme.postCss,
883
+ uiKitObject,
884
+ recursicaObject,
885
+ colorsType,
886
+ spacersType,
887
+ borderRadiusType,
888
+ recursicaThemes,
889
+ prettierignore,
890
+ ];
891
+ // check if src/recursica folder exists, if not create it
892
+ const outputPath = srcPath + "/recursica";
893
+ if (!fs.existsSync(outputPath)) {
894
+ fs.mkdirSync(outputPath);
895
+ }
896
+ for (const file of filesToWrite) {
897
+ fs.writeFileSync(file.path, file.content);
898
+ }
899
+ for (const theme of vanillaExtractThemes.vanillaExtractThemes) {
900
+ fs.writeFileSync(theme.path, theme.content);
901
+ }
902
+ if (iconsObject) {
903
+ fs.writeFileSync(iconsObject.iconExports.path, iconsObject.iconExports.content);
904
+ fs.writeFileSync(iconsObject.iconResourceMap.path, iconsObject.iconResourceMap.content);
905
+ for (const icon of iconsObject.exportedIcons) {
906
+ fs.writeFileSync(icon.path, icon.content);
907
+ }
908
+ }
909
+ console.log("Theme generated successfully");
910
+ }
911
+ catch (error) {
912
+ console.error("Error generating theme:", error);
913
+ throw error;
914
+ }
915
+ }
916
+
917
+ // Run the CLI
918
+ runMain().catch((error) => {
919
+ console.error("Error running recursica mantine adapter:", error);
920
+ process.exit(1);
921
+ });
922
+ //# sourceMappingURL=main.js.map