@salty-css/core 0.1.0-alpha.5 → 0.1.0-alpha.6

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/bin/main.js CHANGED
@@ -1,14 +1,43 @@
1
1
  import { Command } from "commander";
2
2
  import { existsSync, watch } from "fs";
3
- import { mkdir, readFile, writeFile } from "fs/promises";
4
- import { join, relative, parse, format } from "path";
5
- import ejs from "ejs";
6
- import { p as pascalCase } from "../pascal-case-F3Usi5Wf.js";
7
3
  import { l as logger, a as logError, SaltyCompiler } from "../compiler/salty-compiler.js";
4
+ import { isSaltyFile } from "../compiler/helpers.js";
5
+ import { c as checkShouldRestart } from "../should-restart-CXIO0jxY.js";
6
+ import { join, relative, parse, format } from "path";
7
+ import { readFile, writeFile, mkdir } from "fs/promises";
8
8
  import { exec } from "child_process";
9
9
  import ora from "ora";
10
- import { c as checkShouldRestart } from "../should-restart-CXIO0jxY.js";
11
- import { isSaltyFile } from "../compiler/helpers.js";
10
+ import { p as pascalCase } from "../pascal-case-F3Usi5Wf.js";
11
+ import ejs from "ejs";
12
+ const defaultPackageJsonPath = join(process.cwd(), "package.json");
13
+ const readPackageJson = async (filePath = defaultPackageJsonPath) => {
14
+ const content = await readFile(filePath, "utf-8").then(JSON.parse).catch(() => void 0);
15
+ if (!content) throw "Could not read package.json file!";
16
+ return content;
17
+ };
18
+ const updatePackageJson = async (content, filePath = defaultPackageJsonPath) => {
19
+ if (typeof content === "object") content = JSON.stringify(content, null, 2);
20
+ await writeFile(filePath, content);
21
+ };
22
+ const readThisPackageJson = async () => {
23
+ const packageJsonPath = new URL("../package.json", import.meta.url);
24
+ return readPackageJson(packageJsonPath);
25
+ };
26
+ const corePackages = {
27
+ core: (version) => `@salty-css/core@${version}`,
28
+ eslintConfigCore: (version) => `@salty-css/eslint-config-core@${version}`
29
+ };
30
+ const addPrepareScript = (pkg) => {
31
+ if (!pkg.scripts) pkg.scripts = {};
32
+ const current = pkg.scripts["prepare"];
33
+ if (current) {
34
+ if (current.includes("salty-css")) return { changed: false, pkg };
35
+ pkg.scripts["prepare"] = current + " && npx salty-css build";
36
+ } else {
37
+ pkg.scripts["prepare"] = "npx salty-css build";
38
+ }
39
+ return { changed: true, pkg };
40
+ };
12
41
  const execAsync = (command) => {
13
42
  return new Promise((resolve, reject) => {
14
43
  exec(command, (error) => {
@@ -37,365 +66,539 @@ async function formatWithPrettier(filePath) {
37
66
  logger.error(`Error formatting ${filePath} with Prettier:`, error);
38
67
  }
39
68
  }
40
- async function main() {
41
- const program = new Command();
42
- program.name("salty-css").description("Salty-CSS CLI tool to help with annoying configuration tasks.");
43
- const files = {
44
- // Core files
45
- "salty.config.ts": import("../salty.config-DjosWdPw.js"),
46
- "saltygen/index.css": import("../index-DKz1QXqs.js"),
47
- // React
48
- "react/react-styled-file.ts": import("../react-styled-file-B99mwk0w.js"),
49
- "react/react-vanilla-file.ts": import("../react-vanilla-file-D9px70iK.js")
50
- };
51
- const readTemplate = async (fileName, options) => {
52
- const { default: file } = await files[fileName];
53
- const content = ejs.render(file, options);
54
- return { fileName, content };
55
- };
56
- const readRCFile = async () => {
57
- const rcPath = join(process.cwd(), ".saltyrc.json");
58
- const rcContent = await readFile(rcPath, "utf-8").then(JSON.parse).catch(() => ({}));
59
- return rcContent;
60
- };
61
- const defaultPackageJsonPath = join(process.cwd(), "package.json");
62
- const readPackageJson = async (filePath = defaultPackageJsonPath) => {
63
- const packageJsonContent = await readFile(filePath, "utf-8").then(JSON.parse).catch(() => void 0);
64
- if (!packageJsonContent) throw "Could not read package.json file!";
65
- return packageJsonContent;
66
- };
67
- const updatePackageJson = async (content, filePath = defaultPackageJsonPath) => {
68
- if (typeof content === "object") content = JSON.stringify(content, null, 2);
69
- await writeFile(filePath, content);
70
- };
71
- const readThisPackageJson = async () => {
72
- const packageJsonPath = new URL("../package.json", import.meta.url);
73
- return readPackageJson(packageJsonPath);
74
- };
75
- const getDefaultProject = async () => {
76
- const rcContent = await readRCFile();
77
- return rcContent.defaultProject;
78
- };
79
- const defaultProject = await getDefaultProject();
80
- const currentPackageJson = await readThisPackageJson();
81
- const packages = {
82
- core: `@salty-css/core@${currentPackageJson.version}`,
83
- react: `@salty-css/react@${currentPackageJson.version}`,
84
- eslintConfigCore: `@salty-css/eslint-config-core@${currentPackageJson.version}`,
85
- vite: `@salty-css/vite@${currentPackageJson.version}`,
86
- next: `@salty-css/next@${currentPackageJson.version}`
87
- };
88
- const resolveProjectDir = (dir) => {
89
- const dirName = dir === "." ? "" : dir;
90
- const rootDir = process.cwd();
91
- const projectDir = join(rootDir, dirName);
92
- return projectDir;
93
- };
94
- program.command("init [directory]").description("Initialize a new Salty-CSS project.").option("-d, --dir <dir>", "Project directory to initialize the project in.").option("--css-file <css-file>", "Existing CSS file where to import the generated CSS. Path must be relative to the given project directory.").option("--skip-install", "Skip installing dependencies.").action(async function(_dir = ".") {
95
- const packageJson = await readPackageJson().catch(() => void 0);
96
- if (!packageJson) return logError("Salty CSS project must be initialized in a directory with a package.json file.");
97
- logger.info("Initializing a new Salty-CSS project!");
98
- const { dir = _dir, cssFile, skipInstall } = this.opts();
99
- if (!dir) return logError("Project directory must be provided. Add it as the first argument after init command or use the --dir option.");
100
- if (!skipInstall) await npmInstall(packages.core, packages.react);
101
- const rootDir = process.cwd();
102
- const projectDir = resolveProjectDir(dir);
103
- const projectFiles = await Promise.all([readTemplate("salty.config.ts"), readTemplate("saltygen/index.css")]);
104
- const saltyCompiler = new SaltyCompiler(projectDir);
105
- await mkdir(projectDir, { recursive: true });
106
- const writeFiles = projectFiles.map(async ({ fileName, content }) => {
107
- const filePath = join(projectDir, fileName);
108
- const existingContent = await readFile(filePath, "utf-8").catch(() => void 0);
109
- if (existingContent !== void 0) {
110
- logger.debug("File already exists: " + filePath);
111
- return;
112
- }
113
- const additionalFolders = fileName.split("/").slice(0, -1).join("/");
114
- if (additionalFolders) await mkdir(join(projectDir, additionalFolders), { recursive: true });
115
- logger.info("Creating file: " + filePath);
116
- await writeFile(filePath, content);
117
- await formatWithPrettier(filePath);
118
- });
119
- await Promise.all(writeFiles);
120
- const relativeProjectPath = relative(rootDir, projectDir) || ".";
121
- const saltyrcPath = join(rootDir, ".saltyrc.json");
122
- const existingSaltyrc = await readFile(saltyrcPath, "utf-8").catch(() => void 0);
123
- if (existingSaltyrc === void 0) {
124
- logger.info("Creating file: " + saltyrcPath);
125
- const rcContent = {
126
- $schema: "./node_modules/@salty-css/core/.saltyrc.schema.json",
127
- info: "This file is used to define projects and their configurations for Salty CSS cli. Do not delete, modify or add this file to .gitignore.",
128
- defaultProject: relativeProjectPath,
129
- projects: [
130
- {
131
- dir: relativeProjectPath,
132
- framework: "react"
133
- }
134
- ]
135
- };
136
- const content = JSON.stringify(rcContent, null, 2);
137
- await writeFile(saltyrcPath, content);
138
- await formatWithPrettier(saltyrcPath);
139
- } else {
140
- const rcContent = JSON.parse(existingSaltyrc);
141
- const projects = (rcContent == null ? void 0 : rcContent.projects) || [];
142
- const projectIndex = projects.findIndex((p) => p.dir === relativeProjectPath);
143
- if (projectIndex === -1) {
144
- projects.push({ dir: relativeProjectPath, framework: "react" });
145
- rcContent.projects = [...projects];
146
- const content = JSON.stringify(rcContent, null, 2);
147
- if (content !== existingSaltyrc) {
148
- logger.info("Edit file: " + saltyrcPath);
149
- await writeFile(saltyrcPath, content);
150
- await formatWithPrettier(saltyrcPath);
151
- }
152
- }
153
- }
154
- const gitIgnorePath = join(rootDir, ".gitignore");
155
- const gitIgnoreContent = await readFile(gitIgnorePath, "utf-8").catch(() => void 0);
156
- if (gitIgnoreContent !== void 0) {
157
- const alreadyIgnoresSaltygen = gitIgnoreContent.includes("saltygen");
158
- if (!alreadyIgnoresSaltygen) {
159
- logger.info("Edit file: " + gitIgnorePath);
160
- await writeFile(gitIgnorePath, gitIgnoreContent + "\n\n# Salty-CSS\nsaltygen\n");
161
- }
162
- }
163
- const cssFileFoldersToLookFor = ["src", "public", "assets", "styles", "css", "app"];
164
- const secondLevelFolders = ["styles", "css", "app", "pages"];
165
- const cssFilesToLookFor = ["index", "styles", "main", "app", "global", "globals"];
166
- const cssFileExtensions = [".css", ".scss", ".sass"];
167
- const getTargetCssFile = async () => {
168
- if (cssFile) return cssFile;
169
- for (const folder of cssFileFoldersToLookFor) {
170
- for (const file of cssFilesToLookFor) {
171
- for (const ext of cssFileExtensions) {
172
- const filePath = join(projectDir, folder, file + ext);
173
- const fileContent = await readFile(filePath, "utf-8").catch(() => void 0);
174
- if (fileContent !== void 0) return relative(projectDir, filePath);
175
- for (const secondLevelFolder of secondLevelFolders) {
176
- const filePath2 = join(projectDir, folder, secondLevelFolder, file + ext);
177
- const fileContent2 = await readFile(filePath2, "utf-8").catch(() => void 0);
178
- if (fileContent2 !== void 0) return relative(projectDir, filePath2);
179
- }
180
- }
181
- }
182
- }
183
- return void 0;
184
- };
185
- const targetCSSFile = await getTargetCssFile();
186
- if (targetCSSFile) {
187
- const cssFilePath = join(projectDir, targetCSSFile);
188
- const cssFileContent = await readFile(cssFilePath, "utf-8").catch(() => void 0);
189
- if (cssFileContent !== void 0) {
190
- const alreadyImportsSaltygen = cssFileContent.includes("saltygen");
191
- if (!alreadyImportsSaltygen) {
192
- const cssFileFolder = join(cssFilePath, "..");
193
- const relativePath = relative(cssFileFolder, join(projectDir, "saltygen/index.css"));
194
- const importStatement = `@import '${relativePath}';`;
195
- logger.info("Adding global import statement to CSS file: " + cssFilePath);
196
- await writeFile(cssFilePath, importStatement + "\n" + cssFileContent);
197
- await formatWithPrettier(cssFilePath);
198
- }
199
- }
200
- } else {
201
- logger.warn("Could not find a CSS file to import the generated CSS. Please add it manually.");
202
- }
203
- const eslintConfigs = {
204
- projectJs: join(projectDir, "eslint.config.js"),
205
- rootJs: join(rootDir, "eslint.config.js"),
206
- projectMjs: join(projectDir, "eslint.config.mjs"),
207
- rootMjs: join(rootDir, "eslint.config.mjs"),
208
- projectJson: join(projectDir, ".eslintrc.json"),
209
- rootJson: join(rootDir, ".eslintrc.json")
69
+ const SALTYRC_FILENAME = ".saltyrc.json";
70
+ const SALTYRC_SCHEMA = "./node_modules/@salty-css/core/.saltyrc.schema.json";
71
+ const SALTYRC_INFO = "This file is used to define projects and their configurations for Salty CSS cli. Do not delete, modify or add this file to .gitignore.";
72
+ const saltyrcPath = (rootDir = process.cwd()) => join(rootDir, SALTYRC_FILENAME);
73
+ const readRc = async (rootDir = process.cwd()) => {
74
+ const content = await readFile(saltyrcPath(rootDir), "utf-8").then(JSON.parse).catch(() => ({}));
75
+ return content;
76
+ };
77
+ const readRawRc = async (rootDir = process.cwd()) => {
78
+ return readFile(saltyrcPath(rootDir), "utf-8").catch(() => void 0);
79
+ };
80
+ const getDefaultProject = async (rootDir = process.cwd()) => {
81
+ const rc = await readRc(rootDir);
82
+ return rc.defaultProject;
83
+ };
84
+ const upsertProjectInRc = (existingRaw, relativeProjectPath, framework) => {
85
+ if (existingRaw === void 0) {
86
+ const fresh = {
87
+ $schema: SALTYRC_SCHEMA,
88
+ info: SALTYRC_INFO,
89
+ defaultProject: relativeProjectPath,
90
+ projects: [{ dir: relativeProjectPath, framework }]
210
91
  };
211
- const eslintConfigToUse = Object.values(eslintConfigs).find((path) => existsSync(path));
212
- if (eslintConfigToUse) {
213
- if (!skipInstall) await npmInstall(packages.eslintConfigCore);
214
- const eslintConfigContent = await readFile(eslintConfigToUse, "utf-8").catch(() => void 0);
215
- if (!eslintConfigContent) return logError("Could not read ESLint config file.");
216
- const alreadyHasSaltyConfig = eslintConfigContent.includes("salty-css");
217
- if (!alreadyHasSaltyConfig) {
218
- logger.info("Edit file: " + eslintConfigToUse);
219
- if (eslintConfigToUse.endsWith("js")) {
220
- const importStatement = 'import saltyCss from "@salty-css/eslint-config-core/flat";';
221
- let newContent = `${importStatement}
222
- ${eslintConfigContent}`;
223
- const isTsEslint = eslintConfigContent.includes("typescript-eslint");
224
- if (isTsEslint) {
225
- if (newContent.includes(".config(")) newContent = newContent.replace(".config(", ".config(saltyCss,");
226
- else logger.warn("Could not find the correct place to add the Salty-CSS config for ESLint. Please add it manually.");
227
- } else {
228
- if (newContent.includes("export default [")) newContent = newContent.replace("export default [", "export default [ saltyCss,");
229
- else if (newContent.includes("eslintConfig = [")) newContent = newContent.replace("eslintConfig = [", "eslintConfig = [ saltyCss,");
230
- else logger.warn("Could not find the correct place to add the Salty-CSS config for ESLint. Please add it manually.");
231
- }
232
- await writeFile(eslintConfigToUse, newContent);
233
- await formatWithPrettier(eslintConfigToUse);
234
- } else {
235
- const eslintConfigJson = JSON.parse(eslintConfigContent);
236
- if (!eslintConfigJson.extends) eslintConfigJson.extends = [];
237
- eslintConfigJson.extends.push("@salty-css/core");
238
- const modifiedEslintConfigContent = JSON.stringify(eslintConfigJson, null, 2);
239
- await writeFile(eslintConfigToUse, modifiedEslintConfigContent);
240
- await formatWithPrettier(eslintConfigToUse);
241
- }
242
- }
243
- }
244
- const viteConfigPath = join(projectDir, "vite.config.ts");
245
- const viteConfigContent = await readFile(viteConfigPath, "utf-8").catch(() => void 0);
246
- if (viteConfigContent !== void 0) {
247
- const alreadyHasPlugin = viteConfigContent.includes("saltyPlugin");
248
- if (!alreadyHasPlugin) {
249
- logger.info("Edit file: " + viteConfigPath);
250
- const pluginImport = "import { saltyPlugin } from '@salty-css/vite';\n";
251
- const pluginConfig = "saltyPlugin(__dirname),";
252
- const newContent = viteConfigContent.replace(/(plugins: \[)/, `$1
253
- ${pluginConfig}`);
254
- if (!skipInstall) await npmInstall(`-D ${packages.vite}`);
255
- logger.info("Adding Salty-CSS plugin to Vite config...");
256
- await writeFile(viteConfigPath, pluginImport + newContent);
257
- await formatWithPrettier(viteConfigPath);
258
- }
259
- }
260
- const nextConfigFiles = ["next.config.js", "next.config.cjs", "next.config.ts", "next.config.mjs"];
261
- const nextConfigPath = nextConfigFiles.map((file) => join(projectDir, file)).find((path) => existsSync(path));
262
- if (nextConfigPath) {
263
- let nextConfigContent = await readFile(nextConfigPath, "utf-8").catch(() => void 0);
264
- if (nextConfigContent !== void 0) {
265
- const alreadyHasPlugin = nextConfigContent.includes("withSaltyCss");
266
- if (!alreadyHasPlugin) {
267
- let saltyCssAppended = false;
268
- const hasPluginsArray = /\splugins([^=]*)=[^[]\[/.test(nextConfigContent);
269
- if (hasPluginsArray && !saltyCssAppended) {
270
- nextConfigContent = nextConfigContent.replace(/\splugins([^=]*)=[^[]\[/, (_, config) => {
271
- return ` plugins${config}= [withSaltyCss,`;
272
- });
273
- saltyCssAppended = true;
274
- }
275
- const useRequire = nextConfigContent.includes("module.exports");
276
- const pluginImport = useRequire ? "const { withSaltyCss } = require('@salty-css/next');\n" : "import { withSaltyCss } from '@salty-css/next';\n";
277
- if (useRequire && !saltyCssAppended) {
278
- nextConfigContent = nextConfigContent.replace(/module.exports = ([^;]+)/, (_, config) => {
279
- return `module.exports = withSaltyCss(${config})`;
280
- });
281
- saltyCssAppended = true;
282
- } else if (!saltyCssAppended) {
283
- nextConfigContent = nextConfigContent.replace(/export default ([^;]+)/, (_, config) => {
284
- return `export default withSaltyCss(${config})`;
285
- });
286
- }
287
- if (!skipInstall) await npmInstall(`-D ${packages.next}`);
288
- logger.info("Adding Salty-CSS plugin to Next.js config...");
289
- await writeFile(nextConfigPath, pluginImport + nextConfigContent);
290
- await formatWithPrettier(nextConfigPath);
291
- }
292
- }
293
- }
294
- const packageJsonContent = await readPackageJson().catch(() => logError("Could not read package.json file.")).then((content) => {
295
- if (!content.scripts) content.scripts = {};
296
- if (content.scripts.prepare) {
297
- const alreadyHasSaltyCss = content.scripts.prepare.includes("salty-css");
298
- if (!alreadyHasSaltyCss) {
299
- logger.info("Edit file: " + defaultPackageJsonPath);
300
- content.scripts.prepare = content.scripts.prepare + " && npx salty-css build";
301
- }
302
- } else {
303
- logger.info("Edit file: " + defaultPackageJsonPath);
304
- content.scripts.prepare = "npx salty-css build";
305
- }
306
- return content;
307
- });
308
- await updatePackageJson(packageJsonContent);
309
- logger.info("Running the build to generate initial CSS...");
310
- await saltyCompiler.generateCss();
311
- logger.info("🎉 Salty CSS project initialized successfully!");
312
- logger.info("Next steps:");
313
- logger.info("1. Configure variables and templates in `salty.config.ts`");
314
- logger.info("2. Create a new component with `npx salty-css generate [component-name]`");
315
- logger.info("3. Run `npx salty-css build` to generate the CSS");
316
- logger.info("4. Read about the features in the documentation: https://salty-css.dev");
317
- logger.info("5. Star the project on GitHub: https://github.com/margarita-form/salty-css ⭐");
318
- });
92
+ return { content: JSON.stringify(fresh, null, 2), changed: true, created: true };
93
+ }
94
+ const rc = JSON.parse(existingRaw);
95
+ const projects = rc.projects || [];
96
+ const exists = projects.some((p) => p.dir === relativeProjectPath);
97
+ if (exists) return { content: existingRaw, changed: false, created: false };
98
+ projects.push({ dir: relativeProjectPath, framework });
99
+ rc.projects = [...projects];
100
+ const next = JSON.stringify(rc, null, 2);
101
+ return { content: next, changed: next !== existingRaw, created: false };
102
+ };
103
+ const writeProjectToRc = async (rootDir, relativeProjectPath, framework) => {
104
+ const path = saltyrcPath(rootDir);
105
+ const existing = await readRawRc(rootDir);
106
+ const { content, changed, created } = upsertProjectInRc(existing, relativeProjectPath, framework);
107
+ if (!changed) return false;
108
+ if (created) logger.info("Creating file: " + path);
109
+ else logger.info("Edit file: " + path);
110
+ await writeFile(path, content);
111
+ await formatWithPrettier(path);
112
+ return true;
113
+ };
114
+ const getProjectFramework = (rc, relativeProjectPath) => {
115
+ const projects = rc.projects || [];
116
+ const entry = projects.find((p) => p.dir === relativeProjectPath);
117
+ return entry == null ? void 0 : entry.framework;
118
+ };
119
+ const resolveProjectDir = (dir, rootDir = process.cwd()) => {
120
+ const dirName = dir === "." ? "" : dir;
121
+ return join(rootDir, dirName);
122
+ };
123
+ const buildContext = async (opts) => {
124
+ const rootDir = process.cwd();
125
+ const projectDir = resolveProjectDir(opts.dir, rootDir);
126
+ const relativeProjectPath = relative(rootDir, projectDir) || ".";
127
+ const packageJson = await readPackageJson().catch(() => void 0);
128
+ if (opts.requirePackageJson !== false && !packageJson) {
129
+ throw new Error("Salty CSS project must be initialized in a directory with a package.json file.");
130
+ }
131
+ const rcFile = await readRc(rootDir);
132
+ const cliPackageJson = await readThisPackageJson();
133
+ return {
134
+ rootDir,
135
+ projectDir,
136
+ relativeProjectPath,
137
+ packageJson,
138
+ rcFile,
139
+ cliVersion: cliPackageJson.version || "0.0.0",
140
+ skipInstall: !!opts.skipInstall
141
+ };
142
+ };
143
+ const registerBuildCommand = (program, defaultProject) => {
319
144
  program.command("build [directory]").alias("b").description("Build the Salty-CSS project.").option("-d, --dir <dir>", "Project directory to build the project in.").option("--watch", "Watch for changes and rebuild the project.").action(async function(_dir = defaultProject) {
320
145
  logger.info("Building the Salty-CSS project...");
321
146
  const { dir = _dir, watch: watch$1 } = this.opts();
322
- if (!dir) return logError("Project directory must be provided. Add it as the first argument after build command or use the --dir option.");
323
- const projectDir = resolveProjectDir(dir);
324
- const saltyCompiler = new SaltyCompiler(projectDir);
325
- await saltyCompiler.generateCss();
147
+ const resolved = dir ?? await getDefaultProject();
148
+ if (!resolved) return logError("Project directory must be provided. Add it as the first argument after build command or use the --dir option.");
149
+ const projectDir = resolveProjectDir(resolved);
150
+ const compiler = new SaltyCompiler(projectDir);
151
+ await compiler.generateCss();
326
152
  if (watch$1) {
327
153
  logger.info("Watching for changes in the project directory...");
328
- watch(projectDir, { recursive: true }, async (event, filePath) => {
154
+ watch(projectDir, { recursive: true }, async (_event, filePath) => {
329
155
  const shouldRestart = await checkShouldRestart(filePath);
330
156
  if (shouldRestart) {
331
- await saltyCompiler.generateCss(false);
332
- } else {
333
- const saltyFile = isSaltyFile(filePath);
334
- if (saltyFile) await saltyCompiler.generateFile(filePath);
157
+ await compiler.generateCss(false);
158
+ } else if (isSaltyFile(filePath)) {
159
+ await compiler.generateFile(filePath);
335
160
  }
336
161
  });
337
162
  }
338
163
  });
339
- program.command("generate [file] [directory]").alias("g").description("Generate a new component file.").option("-f, --file <file>", "File to generate.").option("-d, --dir <dir>", "Project directory to generate the file in.").option("-t, --tag <tag>", "HTML tag of the component.", "div").option("-n, --name <name>", "Name of the component.").option("-c, --className <className>", "CSS class of the component.").option("-r, --reactComponent", "Generate a React component as well.").action(async function(_file, _dir = defaultProject) {
164
+ };
165
+ const astroConfigFiles = ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.cjs"];
166
+ const findAstroConfig = (projectDir) => {
167
+ for (const name of astroConfigFiles) {
168
+ const path = join(projectDir, name);
169
+ if (existsSync(path)) return path;
170
+ }
171
+ return null;
172
+ };
173
+ const hasAstroDependency = (ctx) => {
174
+ const pkg = ctx.packageJson;
175
+ if (!pkg) return false;
176
+ const all = { ...pkg.dependencies, ...pkg.devDependencies };
177
+ return Object.prototype.hasOwnProperty.call(all, "astro");
178
+ };
179
+ const astroFramework = {
180
+ name: "astro",
181
+ detect: (ctx) => Boolean(findAstroConfig(ctx.projectDir)) || hasAstroDependency(ctx),
182
+ runtimePackage: (version) => `@salty-css/astro@${version}`,
183
+ templates: {
184
+ styled: "astro/styled-file.ts",
185
+ component: {
186
+ styled: "astro/styled-file.ts",
187
+ wrapper: "astro/component.astro",
188
+ wrapperExt: ".astro"
189
+ }
190
+ }
191
+ };
192
+ const reactFramework = {
193
+ name: "react",
194
+ detect: () => true,
195
+ // default fallback — evaluated last in the registry
196
+ runtimePackage: (version) => `@salty-css/react@${version}`,
197
+ templates: {
198
+ styled: "react/styled-file.ts",
199
+ component: {
200
+ styled: "react/styled-file.ts",
201
+ wrapper: "react/vanilla-file.ts",
202
+ wrapperExt: ".tsx"
203
+ }
204
+ }
205
+ };
206
+ const frameworkRegistry = [astroFramework, reactFramework];
207
+ const frameworksByName = {
208
+ astro: astroFramework,
209
+ react: reactFramework
210
+ };
211
+ const detectFramework = async (ctx) => {
212
+ for (const adapter of frameworkRegistry) {
213
+ if (await adapter.detect(ctx)) return adapter;
214
+ }
215
+ return reactFramework;
216
+ };
217
+ const getFramework = (name) => {
218
+ if (!name) return void 0;
219
+ return frameworksByName[name];
220
+ };
221
+ const templateLoaders = {
222
+ "salty.config.ts": () => import("../salty.config-DjosWdPw.js"),
223
+ "saltygen/index.css": () => import("../index-DKz1QXqs.js"),
224
+ "react/styled-file.ts": () => import("../styled-file-Cda3EeR6.js"),
225
+ "react/vanilla-file.ts": () => import("../vanilla-file-1kOqbCIM.js"),
226
+ "astro/styled-file.ts": () => import("../styled-file-DLcgYmGN.js"),
227
+ "astro/component.astro": () => import("../astro-component-5hrNTCJ5.js")
228
+ };
229
+ const readTemplate = async (key, options) => {
230
+ const { default: file } = await templateLoaders[key]();
231
+ const content = ejs.render(file, options);
232
+ return { fileName: key, content };
233
+ };
234
+ const registerGenerateCommand = (program, defaultProject) => {
235
+ program.command("generate [file] [directory]").alias("g").description("Generate a new component file.").option("-f, --file <file>", "File to generate.").option("-d, --dir <dir>", "Project directory to generate the file in.").option("-t, --tag <tag>", "HTML tag of the component.", "div").option("-n, --name <name>", "Name of the component.").option("-c, --className <className>", "CSS class of the component.").option("-r, --reactComponent", "Generate a wrapper component file alongside the styled definition.").action(async function(_file, _dir = defaultProject) {
340
236
  const { file = _file, dir = _dir, tag, name, className, reactComponent = false } = this.opts();
341
237
  if (!file) return logError("File to generate must be provided. Add it as the first argument after generate command or use the --file option.");
342
238
  if (!dir) return logError("Project directory must be provided. Add it as the second argument after generate command or use the --dir option.");
343
- const projectDir = resolveProjectDir(dir);
239
+ let ctx;
240
+ try {
241
+ ctx = await buildContext({ dir, requirePackageJson: false });
242
+ } catch (err) {
243
+ return logError(err instanceof Error ? err.message : String(err));
244
+ }
245
+ const rcFramework = getFramework(getProjectFramework(ctx.rcFile, ctx.relativeProjectPath));
246
+ const framework = rcFramework ?? await detectFramework(ctx);
344
247
  const additionalFolders = file.split("/").slice(0, -1).join("/");
345
- if (additionalFolders) await mkdir(join(projectDir, additionalFolders), { recursive: true });
346
- const filePath = join(projectDir, file);
248
+ if (additionalFolders) await mkdir(join(ctx.projectDir, additionalFolders), { recursive: true });
249
+ const filePath = join(ctx.projectDir, file);
347
250
  const parsedFilePath = parse(filePath);
348
- if (!parsedFilePath.ext) {
349
- parsedFilePath.ext = ".ts";
350
- }
351
- if (!parsedFilePath.name.endsWith(".css")) {
352
- parsedFilePath.name = parsedFilePath.name + ".css";
353
- }
251
+ if (!parsedFilePath.ext) parsedFilePath.ext = ".ts";
252
+ if (!parsedFilePath.name.endsWith(".css")) parsedFilePath.name = parsedFilePath.name + ".css";
354
253
  parsedFilePath.base = parsedFilePath.name + parsedFilePath.ext;
355
254
  const formattedStyledFilePath = format(parsedFilePath);
356
255
  const alreadyExists = await readFile(formattedStyledFilePath, "utf-8").catch(() => void 0);
357
256
  if (alreadyExists !== void 0) {
358
- logger.error("File already exists:", formattedStyledFilePath);
257
+ logger.error("File already exists: " + formattedStyledFilePath);
359
258
  return;
360
259
  }
361
260
  let styledComponentName = pascalCase(name || parsedFilePath.base.replace(/\.css\.\w+$/, ""));
362
261
  if (reactComponent) {
262
+ if (!framework.templates.component) {
263
+ return logError(`--reactComponent is not supported for the ${framework.name} framework.`);
264
+ }
363
265
  const componentName = styledComponentName + "Component";
364
266
  styledComponentName = styledComponentName + "Wrapper";
365
267
  const fileName = parsedFilePath.base.replace(/\.css\.\w+$/, "");
366
- const { content: reactContent } = await readTemplate("react/react-vanilla-file.ts", { tag, componentName, styledComponentName, className, fileName });
268
+ const { content: wrapperContent } = await readTemplate(framework.templates.component.wrapper, {
269
+ tag,
270
+ componentName,
271
+ styledComponentName,
272
+ className,
273
+ fileName
274
+ });
367
275
  parsedFilePath.name = fileName.replace(/\.css$/, "");
368
- parsedFilePath.ext = ".tsx";
276
+ parsedFilePath.ext = framework.templates.component.wrapperExt;
369
277
  parsedFilePath.base = parsedFilePath.name + parsedFilePath.ext;
370
- const formattedReactFilePath = format(parsedFilePath);
371
- logger.info("Generating a new file: " + formattedReactFilePath);
372
- await writeFile(formattedReactFilePath, reactContent);
373
- await formatWithPrettier(formattedReactFilePath);
278
+ const formattedWrapperPath = format(parsedFilePath);
279
+ logger.info("Generating a new file: " + formattedWrapperPath);
280
+ await writeFile(formattedWrapperPath, wrapperContent);
281
+ await formatWithPrettier(formattedWrapperPath);
374
282
  }
375
- const { content } = await readTemplate("react/react-styled-file.ts", { tag, name: styledComponentName, className });
283
+ const styledKey = reactComponent && framework.templates.component ? framework.templates.component.styled : framework.templates.styled;
284
+ const { content } = await readTemplate(styledKey, { tag, name: styledComponentName, className });
376
285
  logger.info("Generating a new file: " + formattedStyledFilePath);
377
286
  await writeFile(formattedStyledFilePath, content);
378
287
  await formatWithPrettier(formattedStyledFilePath);
379
288
  });
380
- const getSaltyCssPackages = async () => {
381
- const packageJSONPath = join(process.cwd(), "package.json");
382
- const packageJson = await readPackageJson(packageJSONPath).catch((err) => logError(err));
383
- if (!packageJson) return logError("Could not read package.json file.");
384
- const allDependencies = { ...packageJson.dependencies, ...packageJson.devDependencies };
385
- const saltyCssPackages = Object.entries(allDependencies).filter(([name]) => name === "salty-css" || name.startsWith("@salty-css/"));
386
- if (!saltyCssPackages.length) {
387
- return logError(
388
- "No Salty-CSS packages found in package.json. Make sure you are running update command in the same directory! Used package.json path: " + packageJSONPath
389
- );
289
+ };
290
+ const CSS_FILE_FOLDERS = ["src", "public", "assets", "styles", "css", "app"];
291
+ const CSS_SECOND_LEVEL_FOLDERS = ["styles", "css", "app", "pages"];
292
+ const CSS_FILE_NAMES = ["index", "styles", "main", "app", "global", "globals"];
293
+ const CSS_FILE_EXTENSIONS = [".css", ".scss", ".sass"];
294
+ const findGlobalCssFile = async (projectDir) => {
295
+ for (const folder of CSS_FILE_FOLDERS) {
296
+ for (const file of CSS_FILE_NAMES) {
297
+ for (const ext of CSS_FILE_EXTENSIONS) {
298
+ const filePath = join(projectDir, folder, file + ext);
299
+ const fileContent = await readFile(filePath, "utf-8").catch(() => void 0);
300
+ if (fileContent !== void 0) return relative(projectDir, filePath);
301
+ for (const second of CSS_SECOND_LEVEL_FOLDERS) {
302
+ const nestedPath = join(projectDir, folder, second, file + ext);
303
+ const nestedContent = await readFile(nestedPath, "utf-8").catch(() => void 0);
304
+ if (nestedContent !== void 0) return relative(projectDir, nestedPath);
305
+ }
306
+ }
390
307
  }
391
- return saltyCssPackages;
392
- };
308
+ }
309
+ return void 0;
310
+ };
311
+ const astroPackage = (version) => `@salty-css/astro@${version}`;
312
+ const SALTY_ASTRO_IMPORT = "import saltyIntegration from '@salty-css/astro/integration';\n";
313
+ const editAstroConfig = (existing) => {
314
+ if (existing.includes("@salty-css/astro")) return { content: null };
315
+ let next = existing;
316
+ let inserted = false;
317
+ if (/integrations\s*:\s*\[/.test(next)) {
318
+ next = next.replace(/integrations\s*:\s*\[/, (m) => `${m}saltyIntegration(),`);
319
+ inserted = true;
320
+ } else if (/defineConfig\s*\(\s*\{/.test(next)) {
321
+ next = next.replace(/defineConfig\s*\(\s*\{/, (m) => `${m}
322
+ integrations: [saltyIntegration()],`);
323
+ inserted = true;
324
+ }
325
+ if (!inserted) {
326
+ return {
327
+ content: null,
328
+ warning: "Could not find a place to add saltyIntegration() in the Astro config. Please add it manually."
329
+ };
330
+ }
331
+ return { content: SALTY_ASTRO_IMPORT + next };
332
+ };
333
+ const astroIntegration = {
334
+ name: "astro",
335
+ detect: (ctx) => findAstroConfig(ctx.projectDir),
336
+ apply: async (ctx, configPath) => {
337
+ const existing = await readFile(configPath, "utf-8").catch(() => void 0);
338
+ if (existing === void 0) return { changed: false };
339
+ const result = editAstroConfig(existing);
340
+ if (result.warning) logger.warn(result.warning);
341
+ if (result.content === null) return { changed: false };
342
+ if (!ctx.skipInstall) await npmInstall(`-D ${astroPackage(ctx.cliVersion)}`);
343
+ logger.info("Adding Salty-CSS integration to Astro config: " + configPath);
344
+ await writeFile(configPath, result.content);
345
+ await formatWithPrettier(configPath);
346
+ return { changed: true };
347
+ }
348
+ };
349
+ const ESLINT_CONFIG_CANDIDATES = [
350
+ // Project-local candidates first, then root-level.
351
+ ["projectJs", "eslint.config.js"],
352
+ ["rootJs", "eslint.config.js"],
353
+ ["projectMjs", "eslint.config.mjs"],
354
+ ["rootMjs", "eslint.config.mjs"],
355
+ ["projectJson", ".eslintrc.json"],
356
+ ["rootJson", ".eslintrc.json"]
357
+ ];
358
+ const eslintConfigCandidates = (projectDir, rootDir) => {
359
+ return ESLINT_CONFIG_CANDIDATES.map(([scope, name]) => {
360
+ const base = scope.startsWith("root") ? rootDir : projectDir;
361
+ return join(base, name);
362
+ });
363
+ };
364
+ const editEslintConfig = (existing, isJsFlat) => {
365
+ if (existing.includes("salty-css")) return { content: null };
366
+ if (isJsFlat) {
367
+ const importStatement = 'import saltyCss from "@salty-css/eslint-config-core/flat";';
368
+ let newContent = `${importStatement}
369
+ ${existing}`;
370
+ const isTsEslint = existing.includes("typescript-eslint");
371
+ if (isTsEslint) {
372
+ if (newContent.includes(".config(")) {
373
+ newContent = newContent.replace(".config(", ".config(saltyCss,");
374
+ } else {
375
+ return {
376
+ content: null,
377
+ warning: "Could not find the correct place to add the Salty-CSS config for ESLint. Please add it manually."
378
+ };
379
+ }
380
+ } else {
381
+ if (newContent.includes("export default [")) {
382
+ newContent = newContent.replace("export default [", "export default [ saltyCss,");
383
+ } else if (newContent.includes("eslintConfig = [")) {
384
+ newContent = newContent.replace("eslintConfig = [", "eslintConfig = [ saltyCss,");
385
+ } else {
386
+ return {
387
+ content: null,
388
+ warning: "Could not find the correct place to add the Salty-CSS config for ESLint. Please add it manually."
389
+ };
390
+ }
391
+ }
392
+ return { content: newContent };
393
+ }
394
+ const json = JSON.parse(existing);
395
+ if (!json.extends) json.extends = [];
396
+ if (!json.extends.includes("@salty-css/core")) json.extends.push("@salty-css/core");
397
+ return { content: JSON.stringify(json, null, 2) };
398
+ };
399
+ const eslintIntegration = {
400
+ name: "eslint",
401
+ detect: (ctx) => {
402
+ const candidates = eslintConfigCandidates(ctx.projectDir, ctx.rootDir);
403
+ return candidates.find((p) => existsSync(p)) ?? null;
404
+ },
405
+ apply: async (ctx, configPath) => {
406
+ const existing = await readFile(configPath, "utf-8").catch(() => void 0);
407
+ if (existing === void 0) {
408
+ logger.error("Could not read ESLint config file.");
409
+ return { changed: false };
410
+ }
411
+ if (!ctx.skipInstall) await npmInstall(corePackages.eslintConfigCore(ctx.cliVersion));
412
+ const result = editEslintConfig(existing, configPath.endsWith("js"));
413
+ if (result.warning) logger.warn(result.warning);
414
+ if (result.content === null) return { changed: false };
415
+ logger.info("Edit file: " + configPath);
416
+ await writeFile(configPath, result.content);
417
+ await formatWithPrettier(configPath);
418
+ return { changed: true };
419
+ }
420
+ };
421
+ const nextConfigFiles = ["next.config.js", "next.config.cjs", "next.config.ts", "next.config.mjs"];
422
+ const nextPackage = (version) => `@salty-css/next@${version}`;
423
+ const editNextConfig = (existing) => {
424
+ if (existing.includes("withSaltyCss")) return { content: null };
425
+ let next = existing;
426
+ let saltyCssAppended = false;
427
+ const hasPluginsArray = /\splugins([^=]*)=[^[]\[/.test(next);
428
+ if (hasPluginsArray) {
429
+ next = next.replace(/\splugins([^=]*)=[^[]\[/, (_, config) => ` plugins${config}= [withSaltyCss,`);
430
+ saltyCssAppended = true;
431
+ }
432
+ const useRequire = next.includes("module.exports");
433
+ const pluginImport = useRequire ? "const { withSaltyCss } = require('@salty-css/next');\n" : "import { withSaltyCss } from '@salty-css/next';\n";
434
+ if (useRequire && !saltyCssAppended) {
435
+ next = next.replace(/module.exports = ([^;]+)/, (_, config) => `module.exports = withSaltyCss(${config})`);
436
+ saltyCssAppended = true;
437
+ } else if (!saltyCssAppended) {
438
+ next = next.replace(/export default ([^;]+)/, (_, config) => `export default withSaltyCss(${config})`);
439
+ }
440
+ return { content: pluginImport + next };
441
+ };
442
+ const nextIntegration = {
443
+ name: "next",
444
+ detect: (ctx) => {
445
+ const found = nextConfigFiles.map((file) => join(ctx.projectDir, file)).find((p) => existsSync(p));
446
+ return found ?? null;
447
+ },
448
+ apply: async (ctx, configPath) => {
449
+ const existing = await readFile(configPath, "utf-8").catch(() => void 0);
450
+ if (existing === void 0) return { changed: false };
451
+ const { content } = editNextConfig(existing);
452
+ if (content === null) return { changed: false };
453
+ if (!ctx.skipInstall) await npmInstall(`-D ${nextPackage(ctx.cliVersion)}`);
454
+ logger.info("Adding Salty-CSS plugin to Next.js config...");
455
+ await writeFile(configPath, content);
456
+ await formatWithPrettier(configPath);
457
+ return { changed: true };
458
+ }
459
+ };
460
+ const vitePackage = (version) => `@salty-css/vite@${version}`;
461
+ const editViteConfig = (existing) => {
462
+ if (existing.includes("saltyPlugin")) return { content: null };
463
+ const pluginImport = "import { saltyPlugin } from '@salty-css/vite';\n";
464
+ const pluginConfig = "saltyPlugin(__dirname),";
465
+ const withPlugin = existing.replace(/(plugins: \[)/, `$1
466
+ ${pluginConfig}`);
467
+ return { content: pluginImport + withPlugin };
468
+ };
469
+ const viteIntegration = {
470
+ name: "vite",
471
+ detect: (ctx) => {
472
+ const path = join(ctx.projectDir, "vite.config.ts");
473
+ return existsSync(path) ? path : null;
474
+ },
475
+ apply: async (ctx, configPath) => {
476
+ const existing = await readFile(configPath, "utf-8").catch(() => void 0);
477
+ if (existing === void 0) return { changed: false };
478
+ const { content } = editViteConfig(existing);
479
+ if (content === null) return { changed: false };
480
+ logger.info("Edit file: " + configPath);
481
+ if (!ctx.skipInstall) await npmInstall(`-D ${vitePackage(ctx.cliVersion)}`);
482
+ logger.info("Adding Salty-CSS plugin to Vite config...");
483
+ await writeFile(configPath, content);
484
+ await formatWithPrettier(configPath);
485
+ return { changed: true };
486
+ }
487
+ };
488
+ const buildIntegrationRegistry = [eslintIntegration, viteIntegration, nextIntegration, astroIntegration];
489
+ const detectAndApplyIntegrations = async (ctx) => {
490
+ const results = [];
491
+ for (const integration of buildIntegrationRegistry) {
492
+ const configPath = await integration.detect(ctx);
493
+ if (!configPath) continue;
494
+ const result = await integration.apply(ctx, configPath);
495
+ results.push({ name: integration.name, configPath, changed: result.changed });
496
+ }
497
+ return results;
498
+ };
499
+ const writeProjectFile = async (projectDir, fileName, content) => {
500
+ const filePath = join(projectDir, fileName);
501
+ if (existsSync(filePath)) {
502
+ logger.debug("File already exists: " + filePath);
503
+ return;
504
+ }
505
+ const additionalFolders = fileName.split("/").slice(0, -1).join("/");
506
+ if (additionalFolders) await mkdir(join(projectDir, additionalFolders), { recursive: true });
507
+ logger.info("Creating file: " + filePath);
508
+ await writeFile(filePath, content);
509
+ await formatWithPrettier(filePath);
510
+ };
511
+ const ensureGitignoreSaltygen = async (rootDir) => {
512
+ const path = join(rootDir, ".gitignore");
513
+ const existing = await readFile(path, "utf-8").catch(() => void 0);
514
+ if (existing === void 0) return;
515
+ if (existing.includes("saltygen")) return;
516
+ logger.info("Edit file: " + path);
517
+ await writeFile(path, existing + "\n\n# Salty-CSS\nsaltygen\n");
518
+ };
519
+ const importSaltygenIntoCss = async (projectDir, explicitCssFile) => {
520
+ const target = explicitCssFile ?? await findGlobalCssFile(projectDir);
521
+ if (!target) {
522
+ logger.warn("Could not find a CSS file to import the generated CSS. Please add it manually.");
523
+ return;
524
+ }
525
+ const cssFilePath = join(projectDir, target);
526
+ const cssFileContent = await readFile(cssFilePath, "utf-8").catch(() => void 0);
527
+ if (cssFileContent === void 0) return;
528
+ if (cssFileContent.includes("saltygen")) return;
529
+ const cssFileFolder = join(cssFilePath, "..");
530
+ const relPath = relative(cssFileFolder, join(projectDir, "saltygen/index.css"));
531
+ logger.info("Adding global import statement to CSS file: " + cssFilePath);
532
+ await writeFile(cssFilePath, `@import '${relPath}';
533
+ ` + cssFileContent);
534
+ await formatWithPrettier(cssFilePath);
535
+ };
536
+ const wirePrepareScript = async () => {
537
+ const pkg = await readPackageJson().catch(() => {
538
+ logError("Could not read package.json file.");
539
+ return void 0;
540
+ });
541
+ if (!pkg) return;
542
+ const { pkg: next } = addPrepareScript(pkg);
543
+ await updatePackageJson(next);
544
+ };
545
+ const registerInitCommand = (program) => {
546
+ program.command("init [directory]").description("Initialize a new Salty-CSS project.").option("-d, --dir <dir>", "Project directory to initialize the project in.").option("--css-file <css-file>", "Existing CSS file where to import the generated CSS. Path must be relative to the given project directory.").option("--skip-install", "Skip installing dependencies.").action(async function(_dir = ".") {
547
+ try {
548
+ const opts = this.opts();
549
+ const dir = opts.dir ?? _dir;
550
+ if (!dir) return logError("Project directory must be provided. Add it as the first argument after init command or use the --dir option.");
551
+ const ctx = await buildContext({ dir, skipInstall: opts.skipInstall });
552
+ logger.info("Initializing a new Salty-CSS project!");
553
+ const framework = await detectFramework(ctx);
554
+ logger.info(`Detected framework: ${framework.name}`);
555
+ if (!ctx.skipInstall) {
556
+ await npmInstall(corePackages.core(ctx.cliVersion), framework.runtimePackage(ctx.cliVersion));
557
+ }
558
+ const projectFiles = await Promise.all([readTemplate("salty.config.ts"), readTemplate("saltygen/index.css")]);
559
+ await mkdir(ctx.projectDir, { recursive: true });
560
+ await Promise.all(projectFiles.map(({ fileName, content }) => writeProjectFile(ctx.projectDir, fileName, content)));
561
+ await writeProjectToRc(ctx.rootDir, ctx.relativeProjectPath, framework.name);
562
+ await ensureGitignoreSaltygen(ctx.rootDir);
563
+ await importSaltygenIntoCss(ctx.projectDir, opts.cssFile);
564
+ await detectAndApplyIntegrations(ctx);
565
+ await wirePrepareScript();
566
+ logger.info("Running the build to generate initial CSS...");
567
+ const compiler = new SaltyCompiler(ctx.projectDir);
568
+ await compiler.generateCss();
569
+ logger.info("🎉 Salty CSS project initialized successfully!");
570
+ logger.info("Next steps:");
571
+ logger.info("1. Configure variables and templates in `salty.config.ts`");
572
+ logger.info("2. Create a new component with `npx salty-css generate [component-name]`");
573
+ logger.info("3. Run `npx salty-css build` to generate the CSS");
574
+ logger.info("4. Read about the features in the documentation: https://salty-css.dev");
575
+ logger.info("5. Star the project on GitHub: https://github.com/margarita-form/salty-css ⭐");
576
+ } catch (err) {
577
+ return logError(err instanceof Error ? err.message : String(err));
578
+ }
579
+ });
580
+ };
581
+ const getSaltyCssPackages = async () => {
582
+ const packageJSONPath = join(process.cwd(), "package.json");
583
+ const packageJson = await readPackageJson(packageJSONPath).catch((err) => logError(err));
584
+ if (!packageJson) return logError("Could not read package.json file.");
585
+ const allDependencies = { ...packageJson.dependencies, ...packageJson.devDependencies };
586
+ const saltyCssPackages = Object.entries(allDependencies).filter(([name]) => name === "salty-css" || name.startsWith("@salty-css/"));
587
+ if (!saltyCssPackages.length) {
588
+ return logError(
589
+ "No Salty-CSS packages found in package.json. Make sure you are running update command in the same directory! Used package.json path: " + packageJSONPath
590
+ );
591
+ }
592
+ return saltyCssPackages;
593
+ };
594
+ const registerUpdateCommand = (program) => {
393
595
  program.command("update [version]").alias("up").description("Update Salty-CSS packages to the latest or specified version.").option("-v, --version <version>", "Version to update to.").option("--legacy-peer-deps <legacyPeerDeps>", "Use legacy peer dependencies (not recommended).", false).action(async function(_version = "latest") {
394
596
  const { legacyPeerDeps, version = _version } = this.opts();
395
597
  const saltyCssPackages = await getSaltyCssPackages();
396
598
  if (!saltyCssPackages) return logError("Could not update Salty-CSS packages as any were found in package.json.");
599
+ const cli = await readThisPackageJson();
397
600
  const packagesToUpdate = saltyCssPackages.map(([name]) => {
398
- if (version === "@") return `${name}@${currentPackageJson.version}`;
601
+ if (version === "@") return `${name}@${cli.version}`;
399
602
  return `${name}@${version.replace(/^@/, "")}`;
400
603
  });
401
604
  if (legacyPeerDeps) {
@@ -413,19 +616,19 @@ ${eslintConfigContent}`;
413
616
  }, {});
414
617
  const versionsCount = Object.keys(mappedByVersions).length;
415
618
  if (versionsCount === 1) {
416
- const version2 = Object.keys(mappedByVersions)[0];
417
- const versionString = version2.replace(/^\^/, "");
418
- logger.info(`Updated to all Salty CSS packages successfully to ${versionString}`);
619
+ const v = Object.keys(mappedByVersions)[0];
620
+ logger.info(`Updated to all Salty CSS packages successfully to ${v.replace(/^\^/, "")}`);
419
621
  } else {
420
- for (const [version2, names] of Object.entries(mappedByVersions)) {
421
- const versionString = version2.replace(/^\^/, "");
422
- logger.info(`Updated to ${versionString}: ${names.join(", ")}`);
622
+ for (const [v, names] of Object.entries(mappedByVersions)) {
623
+ logger.info(`Updated to ${v.replace(/^\^/, "")}: ${names.join(", ")}`);
423
624
  }
424
625
  }
425
626
  });
627
+ };
628
+ const registerVersionOption = (program) => {
426
629
  program.option("-v, --version", "Show the current version of Salty-CSS.").action(async function() {
427
- const currentPackageJson2 = await readThisPackageJson();
428
- logger.info("CLI is running: " + currentPackageJson2.version);
630
+ const cli = await readThisPackageJson();
631
+ logger.info("CLI is running: " + cli.version);
429
632
  const packageJSONPath = join(process.cwd(), "package.json");
430
633
  const packageJson = await readPackageJson(packageJSONPath).catch((err) => logError(err));
431
634
  if (!packageJson) return;
@@ -440,6 +643,16 @@ ${eslintConfigContent}`;
440
643
  logger.info(`${dep}: ${allDependencies[dep]}`);
441
644
  }
442
645
  });
646
+ };
647
+ async function main() {
648
+ const program = new Command();
649
+ program.name("salty-css").description("Salty-CSS CLI tool to help with annoying configuration tasks.");
650
+ const defaultProject = await getDefaultProject();
651
+ registerInitCommand(program);
652
+ registerBuildCommand(program, defaultProject);
653
+ registerGenerateCommand(program, defaultProject);
654
+ registerUpdateCommand(program);
655
+ registerVersionOption(program);
443
656
  program.parseAsync(process.argv);
444
657
  }
445
658
  export {