Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 78 additions & 68 deletions packages/create-suid/src/actions/init.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import appFile from "../files/appFile.js";
import entryFile from "../files/entryFile.js";
import htmlFile from "../files/htmlFile.js";
import pkgFile from "../files/pkgFile.js";
import tsconfigFile from "../files/tsconfigFile.js";
import viteConfigFile from "../files/viteConfigFile.js";
import { randomArrayValue } from "../utils/array.js";
import appFile from "./../files/appFile.js";
import entryFile from "./../files/entryFile.js";
import htmlFile from "./../files/htmlFile.js";
import pkgFile from "./../files/pkgFile.js";
import tsconfigFile from "./../files/tsconfigFile.js";
import viteConfigFile from "./../files/viteConfigFile.js";
import { createFiles, isEmptyDir } from "./../utils/fs.js";
import { createFiles, isEmptyDir } from "../utils/fs.js";
import chalk from "chalk";
import inquirer from "inquirer";
import { basename, join } from "path";
import inquirer, { Answers } from "inquirer";
import { basename, join as pathJoin } from "path";

export default async function init(defaultOutputDir?: string) {
export default async function init(outputDir?: string) {
const cwd = process.cwd();
let workingDir: string | undefined;
const excluded = [
".history",
"node_modules",
Expand All @@ -21,75 +20,75 @@ export default async function init(defaultOutputDir?: string) {
"README.md",
"LICENSE",
];
if (!defaultOutputDir)
defaultOutputDir = (await isEmptyDir(cwd, excluded))
? "./"
: "./suid-project";
outputDir ||= (await isEmptyDir(cwd, excluded)) ? "./" : "./suid-project";

while (typeof workingDir !== "string") {
const answer: { value: string } = await inquirer.prompt({
type: "input",
name: "value",
message: "Output dir",
default: defaultOutputDir,
});
const path = join(cwd, (defaultOutputDir = answer.value));
let workingDir: string | undefined;
while (!workingDir) {
outputDir = await inquirer
.prompt({
type: "input",
name: "outputDir",
message: "Output dir",
default: outputDir,
})
.then(({ outputDir }: Answers) => outputDir);

const path = pathJoin(cwd, outputDir ?? "");
if (await isEmptyDir(path, excluded)) {
workingDir = path;
} else {
console.info(`Output dir is not empty`);
}
}

const projectName = await inquirer.prompt({
type: "input",
name: "value",
message: "Project name",
default: basename(workingDir),
});

const pkgManager = await inquirer.prompt({
type: "list",
name: "value",
message: "Select a package manager",
default: "pnpm",
choices: [
{
name: "npm",
},
{
name: "pnpm",
},
],
});

const pkgs = await inquirer.prompt({
type: "checkbox",
name: "value",
message: "Select the packages",
choices: [
{
name: "@suid/material",
checked: true,
},
{
name: "@suid/icons-material",
checked: true,
},
],
});

const { projectName, pkgManager, pkgs } = await inquirer.prompt([
{
type: "input",
name: "projectName",
message: "Project name",
default: basename(workingDir),
},
{
type: "list",
name: "pkgManager",
message: "Select a package manager",
default: "pnpm",
choices: [
{
name: "npm",
},
{
name: "pnpm",
},
],
},
{
type: "checkbox",
name: "pkgs",
message: "Select the packages",
choices: [
{
name: "@suid/material",
checked: true,
},
{
name: "@suid/icons-material",
checked: true,
},
],
},
]);
await createFiles(
{
"src/index.tsx": entryFile(),
"src/App.tsx": appFile(),
"index.html": htmlFile({
title: projectName.value,
title: projectName,
}),
"tsconfig.json": tsconfigFile(),
"package.json": await pkgFile({
name: projectName.value,
deps: pkgs.value,
name: projectName,
deps: pkgs,
devDeps: ["@suid/vite-plugin"],
}),
"vite.config.ts": viteConfigFile(),
Expand All @@ -102,11 +101,22 @@ export default async function init(defaultOutputDir?: string) {
console.info();
console.info("Run the next commands:");
console.info();
console.info(chalk.cyan(` cd ${defaultOutputDir}`));
console.info(chalk.cyan(` ${pkgManager.value} install`));
console.info(chalk.cyan(` ${pkgManager.value} start`));
console.info(chalk.cyan(` cd ${outputDir}`));
console.info(chalk.cyan(` ${pkgManager} install`));
console.info(chalk.cyan(` ${pkgManager} start`));
console.info();
console.info(
`And have a ${randomArrayValue(["happy", "good", "nice", "great"])} day! 😃`
`And have a ${randomArrayValue([
"great",
"wonderful",
"fantastic",
"amazing",
"lovely",
"splendid",
"marvelous",
"fabulous",
"terrific",
"delightful",
])} day! 😃`
);
}
35 changes: 15 additions & 20 deletions packages/create-suid/src/files/pkgFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@ export default async function pkgFile(options: {
devDeps?: string[];
}) {
const siteManifest = await fetchLatestManifest("@suid/site");
const dependencies = siteManifest.dependencies ?? {};
const devDependencies = siteManifest.devDependencies ?? {};

const dep = (name: string, caret?: boolean) => {
const ver =
siteManifest.dependencies?.[name] ??
siteManifest.devDependencies?.[name] ??
"*";
const ver = dependencies[name] ?? devDependencies[name] ?? "*";
return {
[name]: caret && /^\d/.test(ver) ? `^${ver}` : ver,
};
Expand All @@ -26,22 +25,18 @@ export default async function pkgFile(options: {
build: "vite build",
start: "vite",
},
dependencies: {
...options.deps?.reduce(
(deps, name) => ({ ...deps, ...dep(name, true) }),
{} as Record<string, string>
),
...dep("solid-js"),
},
devDependencies: {
...options.devDeps?.reduce(
(deps, name) => ({ ...deps, ...dep(name, true) }),
{} as Record<string, string>
),
typescript: "^4.8.2",
...dep("vite"),
...dep("vite-plugin-solid"),
},
dependencies: Object.assign(
{},
...(options.deps ?? []).map((name) => dep(name, true)),
dep("solid-js")
),
devDependencies: Object.assign(
{},
...(options.devDeps ?? []).map((name) => dep(name, true)),
{ typescript: "^4.8.2" },
dep("vite"),
dep("vite-plugin-solid")
),
},
null,
2
Expand Down
40 changes: 21 additions & 19 deletions packages/create-suid/src/utils/fs.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,38 @@
import { mkdir, readdir, stat, writeFile } from "fs/promises";
import { dirname, join } from "path";
import { dirname, join as pathJoin } from "path";

export async function safeStat(path: string) {
try {
return await stat(path);
// eslint-disable-next-line no-empty
} catch (error) {}
} catch (error) {
// Do nothing
}
}

export async function isEmptyDir(path: string, exclude?: string[]) {
const info = await safeStat(path);
if (!info) return true;
if (info.isFile()) return false;
const files = await readdir(path);
for (const file of files) {
if (exclude && exclude.includes(file)) {
continue;
} else {
return false;
}
if (!info) {
return true;
}

if (info.isFile()) {
return false;
}
return true;

const files = await readdir(path);
return files.every((file) => exclude?.includes(file));
}

export async function createFiles(
files: Record<string, string>,
baseDir = process.cwd()
) {
for (const name in files) {
const path = join(baseDir, name);
const dir = dirname(path);
await mkdir(dir, { recursive: true });
await writeFile(path, files[name]);
}
await Promise.all(
Object.entries(files).map(async ([name, content]) => {
const path = pathJoin(baseDir, name);
const dir = dirname(path);
await mkdir(dir, { recursive: true });
await writeFile(path, content);
})
);
}
12 changes: 5 additions & 7 deletions packages/create-suid/src/utils/npm.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { request } from "https";
import { get } from "https";

export async function fetchLatestManifest(name: string) {
const url = `https://registry.npmjs.org/${name}/latest`;
Expand All @@ -8,13 +8,11 @@ export async function fetchLatestManifest(name: string) {
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
}>((resolve, reject) => {
let json = "";
const req = request(url, (res) => {
get(url, (res) => {
let json = "";
res.on("data", (chunk) => (json += chunk));
res.on("close", () => resolve(JSON.parse(json)));
});
req.on("error", reject);
req.end();
res.on("end", () => resolve(JSON.parse(json)));
}).on("error", reject);
});
}

Expand Down