@erudit-js/cli 3.0.0-dev.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/README.md ADDED
@@ -0,0 +1,12 @@
1
+ # 📟 Erudit CLI
2
+
3
+ Command Line Interface for [Erudit](https://github.com/erudit-js/erudit).
4
+
5
+ CLI is accessible via `erudit` or `erudit-cli` commands.
6
+
7
+ ## Commands
8
+
9
+ - `init`
10
+ - `dev`
11
+ - `build`
12
+ - `preview`
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { run } from '../dist/index.mjs';
4
+
5
+ run();
@@ -0,0 +1,3 @@
1
+ declare function run(): void;
2
+
3
+ export { run };
@@ -0,0 +1,3 @@
1
+ declare function run(): void;
2
+
3
+ export { run };
package/dist/index.mjs ADDED
@@ -0,0 +1,389 @@
1
+ import { defineCommand, runMain } from 'citty';
2
+ import { brandColorLogotype } from '@erudit-js/cog/utils/brandNode';
3
+ import { consola } from 'consola';
4
+ import chalk from 'chalk';
5
+ import { existsSync, lstatSync, readdirSync, rmSync, mkdirSync, writeFileSync } from 'node:fs';
6
+ import { resolvePaths } from '@erudit-js/cog/kit';
7
+ import * as fs from 'node:fs/promises';
8
+ import * as path from 'node:path';
9
+ import { spawn } from 'node:child_process';
10
+
11
+ const version = "3.0.0-dev.6";
12
+
13
+ function resolvePath(path) {
14
+ path = resolvePaths(path);
15
+ path = path.endsWith("/") ? path.slice(0, -1) : path;
16
+ if (existsSync(path) && !lstatSync(path).isDirectory())
17
+ throw new Error(
18
+ `Path "${chalk.yellowBright(path)}" is not a directory!`
19
+ );
20
+ return path;
21
+ }
22
+
23
+ const init = defineCommand({
24
+ meta: {
25
+ name: "Init",
26
+ description: "Creates a new Erudit project at specified path"
27
+ },
28
+ args: {
29
+ path: {
30
+ type: "positional",
31
+ description: "Path for the new Erudit project",
32
+ required: true,
33
+ valueHint: chalk.gray(
34
+ `"${chalk.greenBright(".")}" OR "${chalk.greenBright("path/to/project")}"`
35
+ )
36
+ }
37
+ },
38
+ async run({ args }) {
39
+ consola.start("Resolving project path...");
40
+ const projectPath = resolvePath(args.path);
41
+ if (projectPath === void 0) return;
42
+ if (existsSync(projectPath) && readdirSync(projectPath).length > 0)
43
+ throw new Error(
44
+ `Directory "${chalk.yellowBright(projectPath)}" is not empty!`
45
+ );
46
+ consola.success(
47
+ "Resolved project path:",
48
+ chalk.greenBright(projectPath)
49
+ );
50
+ consola.start("Creating project directory...");
51
+ try {
52
+ try {
53
+ rmSync(projectPath, { recursive: true });
54
+ } catch (error) {
55
+ if (error?.code !== "ENOENT") {
56
+ throw error;
57
+ }
58
+ }
59
+ mkdirSync(projectPath, { recursive: true });
60
+ } catch (error) {
61
+ throw new Error(
62
+ `Failed to prepare project directory "${chalk.yellowBright(projectPath)}"!
63
+
64
+ ${error}`
65
+ );
66
+ }
67
+ consola.success("Project directory created!");
68
+ consola.start("Creating project files...");
69
+ consola.success("Project files created!");
70
+ }
71
+ });
72
+
73
+ function logCommand(command) {
74
+ consola.info(`Running command: ${chalk.cyanBright(command)}`);
75
+ console.log();
76
+ }
77
+
78
+ async function alias2Relative(rootDir) {
79
+ rootDir = resolvePaths(rootDir);
80
+ if (!existsSync(rootDir)) {
81
+ return;
82
+ }
83
+ const ALIASES_RESOLVED_FILE = path.join(rootDir, "ALIASES_RESOLVED");
84
+ if (existsSync(ALIASES_RESOLVED_FILE)) {
85
+ console.log("Aliases already resolved. Skipping...");
86
+ return;
87
+ }
88
+ const replaceMap = {
89
+ "@erudit": "./",
90
+ "@module": "./module",
91
+ "@server": "./server/plugin",
92
+ "@shared": "./shared",
93
+ "@app": "./app"
94
+ };
95
+ const allFiles = await findAllFiles(rootDir);
96
+ for (const filePath of allFiles) {
97
+ await processFile(filePath, rootDir, replaceMap);
98
+ }
99
+ await fs.writeFile(ALIASES_RESOLVED_FILE, (/* @__PURE__ */ new Date()).toISOString());
100
+ console.log("All aliases resolved successfully");
101
+ }
102
+ async function findAllFiles(dir) {
103
+ const results = [];
104
+ try {
105
+ const entries = await fs.readdir(dir, { withFileTypes: true });
106
+ for (const entry of entries) {
107
+ const fullPath = path.join(dir, entry.name);
108
+ if (entry.isDirectory()) {
109
+ if (![".git", "dist", "build"].includes(entry.name)) {
110
+ results.push(...await findAllFiles(fullPath));
111
+ }
112
+ } else if (entry.isFile() && /\.(js|ts|vue)$/.test(entry.name)) {
113
+ results.push(fullPath);
114
+ }
115
+ }
116
+ } catch (error) {
117
+ console.error(`Error reading directory ${dir}:`, error);
118
+ }
119
+ return results;
120
+ }
121
+ async function processFile(filePath, rootDir, replaceMap) {
122
+ try {
123
+ let content = await fs.readFile(filePath, "utf8");
124
+ let modified = false;
125
+ for (const [alias, targetBasePath] of Object.entries(replaceMap)) {
126
+ const staticAliasPattern = new RegExp(
127
+ `(import|from)\\s+(['"])${alias}/([^'"]+)(['"])`,
128
+ "g"
129
+ );
130
+ const dynamicAliasPattern = new RegExp(
131
+ `(import\\s*\\()\\s*(['"])${alias}/([^'"]+)(['"])\\s*\\)`,
132
+ "g"
133
+ );
134
+ const calculateRelativePath = (importPath) => {
135
+ const currentFileDir = path.dirname(filePath);
136
+ const targetAbsoluteDir = path.join(
137
+ rootDir,
138
+ targetBasePath.replace(/^\.\//, "")
139
+ );
140
+ const targetAbsolutePath = path.join(
141
+ targetAbsoluteDir,
142
+ importPath
143
+ );
144
+ let relativePath = path.relative(
145
+ currentFileDir,
146
+ targetAbsolutePath
147
+ );
148
+ if (!relativePath.startsWith(".")) {
149
+ relativePath = "./" + relativePath;
150
+ }
151
+ return relativePath.replace(/\\/g, "/");
152
+ };
153
+ content = content.replace(
154
+ staticAliasPattern,
155
+ (match, statement, openQuote, importPath, closeQuote) => {
156
+ const relativePath = calculateRelativePath(importPath);
157
+ modified = true;
158
+ return `${statement} ${openQuote}${relativePath}${closeQuote}`;
159
+ }
160
+ );
161
+ content = content.replace(
162
+ dynamicAliasPattern,
163
+ (match, importStatement, openQuote, importPath, closeQuote) => {
164
+ const relativePath = calculateRelativePath(importPath);
165
+ modified = true;
166
+ return `${importStatement}${openQuote}${relativePath}${closeQuote})`;
167
+ }
168
+ );
169
+ }
170
+ if (modified) {
171
+ await fs.writeFile(filePath, content, "utf8");
172
+ console.log(`Updated aliases in: ${filePath}`);
173
+ }
174
+ } catch (error) {
175
+ console.error(`Error processing file ${filePath}:`, error);
176
+ }
177
+ }
178
+
179
+ async function prepare$1(projectPath, eruditPath) {
180
+ const eruditBuildDir = `${projectPath}/.erudit`;
181
+ const distDir = `${projectPath}/dist`;
182
+ const nodeModulesErudit = `${projectPath}/node_modules/erudit`;
183
+ await alias2Relative(nodeModulesErudit);
184
+ consola.start("Cleaning up...");
185
+ if (existsSync(distDir)) rmSync(distDir, { recursive: true });
186
+ if (existsSync(eruditBuildDir)) rmSync(eruditBuildDir, { recursive: true });
187
+ consola.success("Cleaned up!");
188
+ consola.start("Generating Erudit build files...");
189
+ mkdirSync(eruditBuildDir, { recursive: true });
190
+ mkdirSync(eruditBuildDir + "/nuxt", { recursive: true });
191
+ writeFileSync(
192
+ `${eruditBuildDir}/nuxt/nuxt.config.ts`,
193
+ `
194
+ export default {
195
+ compatibilityDate: '2025-01-01',
196
+ extends: ['${eruditPath}'],
197
+ future: {
198
+ compatibilityVersion: 4,
199
+ },
200
+ }
201
+ `
202
+ );
203
+ consola.success("Erudit build files ready!");
204
+ }
205
+
206
+ async function spawnNuxt(command, projectPath) {
207
+ return new Promise((resolve) => {
208
+ const onClose = (exitCode) => {
209
+ if (exitCode === 1337) _spawnNuxt();
210
+ else if (exitCode !== 0)
211
+ throw new Error(`Nuxt exited with code ${exitCode}!`);
212
+ else resolve();
213
+ };
214
+ const _spawnNuxt = () => {
215
+ const nuxtProcess = spawn(
216
+ `nuxt ${command} ${projectPath}/.erudit/nuxt`,
217
+ {
218
+ shell: true,
219
+ stdio: "inherit",
220
+ env: {
221
+ ...process.env,
222
+ //ERUDIT_PACKAGE_DIR: eruditPackagePath,
223
+ ERUDIT_PROJECT_DIR: projectPath
224
+ }
225
+ }
226
+ );
227
+ nuxtProcess.on("close", onClose);
228
+ };
229
+ _spawnNuxt();
230
+ });
231
+ }
232
+
233
+ const eruditPathArg = {
234
+ eruditPath: {
235
+ type: "string",
236
+ description: "Custom Erudit Nuxt Layer location",
237
+ required: false,
238
+ default: "erudit"
239
+ // Let `nuxi` find erudit in project dependencies
240
+ }
241
+ };
242
+ const projectPathArg = {
243
+ projectPath: {
244
+ type: "positional",
245
+ description: "Erudit project location",
246
+ required: false,
247
+ default: "."
248
+ }
249
+ };
250
+ function resolveArgPaths(projectPath, eruditPath) {
251
+ consola.start("Resolving project path...");
252
+ projectPath = resolvePath(projectPath);
253
+ consola.success("Resolved project path:", chalk.greenBright(projectPath));
254
+ consola.start("Resolving Erudit Nuxt Layer path...");
255
+ if (eruditPath === "erudit") {
256
+ consola.success(`'nuxi' will find Erudit in your dependencies!`);
257
+ } else {
258
+ eruditPath = resolvePath(eruditPath);
259
+ consola.warn(
260
+ "Custom Erudit Nuxt Layer path will be used: " + chalk.yellowBright(eruditPath)
261
+ );
262
+ }
263
+ return {
264
+ projectPath,
265
+ eruditPath
266
+ };
267
+ }
268
+
269
+ const prepare = defineCommand({
270
+ meta: {
271
+ name: "Prepare",
272
+ description: "Creates a .erudit directory in your project and generates build files"
273
+ },
274
+ args: {
275
+ ...projectPathArg,
276
+ ...eruditPathArg
277
+ },
278
+ async run({ args }) {
279
+ logCommand("prepare");
280
+ const { projectPath, eruditPath } = resolveArgPaths(
281
+ args.projectPath,
282
+ args.eruditPath
283
+ );
284
+ await prepare$1(projectPath, eruditPath);
285
+ consola.start("Generating Nuxt build files...");
286
+ await spawnNuxt("prepare", projectPath);
287
+ consola.success("Nuxt is prepared!");
288
+ }
289
+ });
290
+
291
+ const dev = defineCommand({
292
+ meta: {
293
+ name: "Dev",
294
+ description: "Runs Erudit project in development mode"
295
+ },
296
+ args: {
297
+ ...projectPathArg,
298
+ ...eruditPathArg
299
+ },
300
+ async run({ args }) {
301
+ logCommand("dev");
302
+ const { projectPath, eruditPath } = resolveArgPaths(
303
+ args.projectPath,
304
+ args.eruditPath
305
+ );
306
+ await prepare$1(projectPath, eruditPath);
307
+ consola.start("Starting Nuxt dev...");
308
+ await spawnNuxt("dev", projectPath);
309
+ }
310
+ });
311
+
312
+ const build = defineCommand({
313
+ meta: {
314
+ name: "Build",
315
+ description: "Generates fully static Erudit site"
316
+ },
317
+ args: {
318
+ ...projectPathArg,
319
+ ...eruditPathArg
320
+ },
321
+ async run({ args }) {
322
+ logCommand("build");
323
+ const { projectPath, eruditPath } = resolveArgPaths(
324
+ args.projectPath,
325
+ args.eruditPath
326
+ );
327
+ await prepare$1(projectPath, eruditPath);
328
+ consola.start("Starting Nuxt build...");
329
+ await spawnNuxt("generate", projectPath);
330
+ }
331
+ });
332
+
333
+ const preview = defineCommand({
334
+ meta: {
335
+ name: "Preview",
336
+ description: "Preview created static Erudit site"
337
+ },
338
+ args: {
339
+ project: {
340
+ type: "positional",
341
+ description: "Project path",
342
+ required: false,
343
+ default: "."
344
+ }
345
+ },
346
+ async run({ args }) {
347
+ consola.start("Resolving project path...");
348
+ const projectPath = resolvePath(args.project);
349
+ consola.success(
350
+ "Resolved project path:",
351
+ chalk.greenBright(projectPath)
352
+ );
353
+ const distPath = `${projectPath}/dist`;
354
+ if (!existsSync(distPath))
355
+ throw new Error(
356
+ `No 'dist' folder found! Did you run 'erudit build'?`
357
+ );
358
+ spawn("npx http-server . -p 3000", {
359
+ shell: true,
360
+ stdio: "inherit",
361
+ env: process.env,
362
+ cwd: distPath
363
+ });
364
+ }
365
+ });
366
+
367
+ const main = defineCommand({
368
+ meta: {
369
+ name: "Erudit CLI",
370
+ description: "Command Line Interface for Erudit!",
371
+ version
372
+ },
373
+ subCommands: {
374
+ init,
375
+ prepare,
376
+ dev,
377
+ build,
378
+ preview
379
+ },
380
+ setup() {
381
+ console.log(brandColorLogotype);
382
+ }
383
+ });
384
+
385
+ function run() {
386
+ runMain(main);
387
+ }
388
+
389
+ export { run };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@erudit-js/cli",
3
+ "version": "3.0.0-dev.6",
4
+ "type": "module",
5
+ "description": "📟 Command Line Interface for Erudit",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/erudit-js/erudit.git",
10
+ "directory": "packages/cli"
11
+ },
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": "./dist/index.mjs",
15
+ "./cli": "./bin/erudit-cli.mjs"
16
+ },
17
+ "bin": {
18
+ "erudit-cli": "bin/erudit-cli.mjs",
19
+ "erudit": "bin/erudit-cli.mjs"
20
+ },
21
+ "scripts": {
22
+ "dev": "bun unbuild --stub",
23
+ "build": "bun run prepack",
24
+ "prepack": "bun unbuild"
25
+ },
26
+ "files": [
27
+ "bin",
28
+ "dist"
29
+ ],
30
+ "dependencies": {
31
+ "@erudit-js/cog": "3.0.0-dev.6",
32
+ "chalk": "^5.4.1",
33
+ "citty": "^0.1.6",
34
+ "consola": "^3.4.0"
35
+ },
36
+ "devDependencies": {
37
+ "unbuild": "^3.3.1"
38
+ }
39
+ }