Skip to content

Commit

Permalink
reliverse→@reliverse/cli, fix all issues, etc
Browse files Browse the repository at this point in the history
  • Loading branch information
blefnk committed Nov 26, 2024
1 parent c0709a7 commit f022a02
Show file tree
Hide file tree
Showing 85 changed files with 4,425 additions and 148 deletions.
6 changes: 4 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
dist/
output/
.venv/
dist-jsr/
dist-npm/
.DS_Store
merged.txt
.eslintcache
node_modules/
addons/premium/
Expand Down
4 changes: 3 additions & 1 deletion .putout.json
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,9 @@
"nodejs/remove-useless-strict-mode": "off",
"browserlist": "off",
"filesystem": "off",
"conditions/apply-consistent-blocks": "off"
"conditions/apply-consistent-blocks": "off",
"sort-imports-by-specifiers": "off",
"group-imports-by-source": "off"
},
"plugins": [
"apply-at",
Expand Down
23 changes: 23 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"recommendations": [
"aaron-bond.better-comments",
"astro-build.houston",
"biomejs.biome",
"bradlc.vscode-tailwindcss",
"charliermarsh.ruff",
"chunsen.bracket-select",
"davidanson.vscode-markdownlint",
"dbaeumer.vscode-eslint",
"fabiospampinato.vscode-open-multiple-files",
"github.github-vscode-theme",
"lokalise.i18n-ally",
"mikekscholz.pop-icon-theme",
"ms-python.python",
"neptunedesign.vs-sequential-number",
"streetsidesoftware.code-spell-checker",
"unifiedjs.vscode-mdx",
"usernamehw.errorlens",
"usernamehw.remove-empty-lines",
"yzhang.markdown-all-in-one"
]
}
18 changes: 10 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
# Reliverse

[GitHub](https://github.com/reliverse/cli), [npmjs](https://npmjs.com/package/reliverse), [Discord](https://discord.gg/Pb8uKbwpsJ)
[npmjs](https://npmjs.com/package/@reliverse/cli), [GitHub](https://github.com/reliverse/cli), [Discord](https://discord.gg/Pb8uKbwpsJ)

![Reliverse Cover Image](./reliverse.webp)

## Introduction

👋 Welcome! This tool can help you easily create new web projects and automatically make advanced codebase modifications, with more features coming soon.

**Reliverse** is a CLI tool designed to streamline the setup of JavaScript, TypeScript, and other types of projects, with a primary focus on Next.js templates, though it is not limited to them.

![Reliverse Cover Image](./reliverse.webp)

It allows you to effortlessly bootstrap projects, including the [Relivator Next.js template](https://github.com/blefnk/relivator-nextjs-template) or any other template from GitHub or other Git-based sources. Additionally, Reliverse assists in managing configuration files and resolving potential conflicts between tools like ESLint, Prettier, and Biome.

Reliverse is more than just the easiest way to install Relivator. It’s also the most convenient new way to download any repository from GitHub and automatically prepare it for work. Especially if it’s a project from the JavaScript ecosystem.
Expand Down Expand Up @@ -44,10 +46,10 @@ By the way, you might think that a CLI doing so many things would become bloated

You should install [Git](https://git-scm.com), [VSCode](https://code.visualstudio.com), and [Node.js LTS](https://nodejs.org/en/download/package-manager) first. Then use one of the following commands to install **Reliverse**:

- With [bun ](<https://bun> .sh): `bun i -g reliverse`
- With [pnpm](https://pnpm.io/installation#using-corepack): `bun add -g reliverse`
- With [yarn](https://yarnpkg.com): `yarn global add reliverse`
- With [npm](https://nodejs.org/en/learn/getting-started/an-introduction-to-the-npm-package-manager): `npm i -g reliverse`
- With [bun](https://bun.sh): `bun i -g @reliverse/cli`
- With [pnpm](https://pnpm.io/installation#using-corepack): `pnpm add -g @reliverse/cli`
- With [yarn](https://yarnpkg.com): `yarn global add @reliverse/cli`
- With [npm](https://nodejs.org/en/learn/getting-started/an-introduction-to-the-npm-package-manager): `npm i -g @reliverse/cli`

## Usage

Expand Down Expand Up @@ -255,7 +257,7 @@ This project is licensed under the MIT License—see the [LICENSE](LICENSE) file

This project wouldn’t exist without the amazing work of the following projects:

[@inquirer/prompts](https://github.com/SBoudrias/Inquirer.js#readme) | [terkelg/prompts](https://github.com/lu-jiejie/prompts-plus#readme#readme) | [@clack/prompts](https://github.com/bombshell-dev/clack#readme) | [create-t3-app](https://github.com/t3-oss/create-t3-app#readme) | [create-astro](https://github.com/withastro/astro/tree/main/packages/create-astro#readme) | [cronvel/terminal-kit](https://github.com/cronvel/terminal-kit#readme) | [unjs/consola](https://github.com/unjs/consola#readme)
[@reliverse/relinka](https://github.com/SBoudrias/Inquirer.js#readme) | [terkelg/prompts](https://github.com/lu-jiejie/prompts-plus#readme#readme) | [@reliverse/relinka](https://github.com/bombshell-dev/clack#readme) | [create-t3-app](https://github.com/t3-oss/create-t3-app#readme) | [create-astro](https://github.com/withastro/astro/tree/main/packages/create-astro#readme) | [cronvel/terminal-kit](https://github.com/cronvel/terminal-kit#readme) | [unjs/relinka](https://github.com/unjs/relinka#readme)

## Wrap-Up

Expand Down
92 changes: 69 additions & 23 deletions build.optim.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { errorHandler, spinner } from "@reliverse/relinka";
import { errorHandler, msg, spinner } from "@reliverse/prompts";
import glob from "fast-glob";
import fs from "fs-extra";
import path from "pathe";
import strip from "strip-comments";

// Verbose logging
const debug = true;
const debug = false;

// Parse command-line arguments to check for '--jsr' flag
const args: string[] = process.argv.slice(2);
Expand All @@ -26,7 +26,7 @@ const npmFilesToDelete: string[] = [
"types/internal.d.ts",
];

const jsrFilesToDelete: string[] = ["**/*.test.ts", "types/internal.ts"];
const jsrFilesToDelete: string[] = ["**/*.test.ts"];

/**
* Deletes files matching the provided patterns within the base directory.
Expand Down Expand Up @@ -62,17 +62,20 @@ async function deleteFiles(patterns: string[], baseDir: string): Promise<void> {

/**
* Replaces import paths that use '~/' with relative paths.
* If `isJSR` is true, also replaces '.js' extensions with '.ts'.
* @param content - The file content.
* @param fileDir - The directory of the current file.
* @param rootDir - The root directory to resolve relative paths.
* @param isJSR - Flag indicating whether to apply JSR-specific transformations.
* @returns The updated file content with modified import paths.
*/
function replaceImportPaths(
content: string,
fileDir: string,
rootDir: string,
isJSR: boolean,
): string {
return content.replace(
let updatedContent = content.replace(
// Matches both static and dynamic imports
/(from\s+['"]|import\s*\(\s*['"])(~\/?[^'"]*)(['"]\s*\)?)/g,
(
Expand All @@ -94,28 +97,39 @@ function replaceImportPaths(
return `${prefix}${newPath}${suffix}`;
},
);

if (isJSR) {
// Replace '.js' extensions with '.ts' in import paths
// @see https://jsr.io/docs/publishing-packages#relative-imports
updatedContent = updatedContent.replace(/(\.js)(?=['";])/g, ".ts");

if (debug) {
console.log("Replaced '.js' with '.ts' in import paths.");
}
}

return updatedContent;
}

/**
* Removes comments from the given content string using strip-comments.
* Removes comments from the given content string.
* - Strips block comments using `strip-comments`.
* @param content - The file content.
* @param filePath - The path of the file being processed.
* @returns The content without comments.
* @returns The content without unwanted comments.
*/
function removeComments(content: string, filePath: string): string {
const stripped: string = strip(content);
// When not in JSR mode, strip all comments using strip-comments
const stripped = strip(content, {
line: true,
block: true,
keepProtected: true,
preserveNewlines: false,
});

if (debug) {
// Extract comments for comparison
const originalComments: string = (
content.match(/\/\*[\s\S]*?\*\/|\/\/.*/g) || []
).join("\n");
const strippedComments: string = (
stripped.match(/\/\*[\s\S]*?\*\/|\/\/.*/g) || []
).join("\n");
console.log(`\nProcessing file: ${filePath}`);
console.log("Original Comments:\n", originalComments);
console.log("Stripped Comments:\n", strippedComments);
console.log("Stripped all comments.");
}

return stripped;
Expand Down Expand Up @@ -156,9 +170,12 @@ async function processFiles(dir: string): Promise<void> {
content,
path.dirname(filePath),
outputDir,
isJSR,
);

updatedContent = removeComments(updatedContent, filePath);
if (!isJSR) {
updatedContent = removeComments(updatedContent, filePath);
}

if (content !== updatedContent) {
await fs.writeFile(filePath, updatedContent, "utf8");
Expand Down Expand Up @@ -242,9 +259,38 @@ async function optimizeBuildForProduction(dir: string): Promise<void> {
});
}

await optimizeBuildForProduction(outputDir).catch((error: Error) =>
errorHandler(
error,
"If this issue is related to Reliverse CLI itself, please\n│ report the details at https://github.com/blefnk/reliverse",
),
);
async function getDirectorySize(dirPath: string): Promise<number> {
const files = await fs.readdir(dirPath);
let totalSize = 0;

for (const file of files) {
const filePath = path.join(dirPath, file);
const stats = await fs.stat(filePath);

if (stats.isDirectory()) {
totalSize += await getDirectorySize(filePath);
} else {
totalSize += stats.size;
}
}

return totalSize;
}

await optimizeBuildForProduction(outputDir)
.then(() => {
getDirectorySize(outputDir)
.then((size) => {
msg({
type: "M_INFO",
title: `Total size of ${outputDir}: ${size} bytes`,
});
})
.catch((error) => {
msg({
type: "M_ERROR",
title: `Error calculating directory size for ${outputDir}: ${error instanceof Error ? error.message : "Unknown error"}`,
});
});
})
.catch((error: Error) => errorHandler(error));
111 changes: 111 additions & 0 deletions build.publish.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import relinka from "@reliverse/relinka";
import { execa } from "execa";
import fs from "fs-extra";
import mri from "mri";

function showHelp() {
relinka.info(`Usage: bun build.publish.ts [options]
Options:
no options Publish to npm registry
--jsr Publish to JSR registry
--dry-run Perform a dry run of the publish process
-h, --help Show help
`);
}

const argv = mri(process.argv.slice(2), {
alias: {
h: "help",
},
boolean: ["jsr", "dry-run", "help"],
default: {
jsr: false,
"dry-run": false,
help: false,
},
});

// If help flag is present, display help and exit
if (argv.help) {
showHelp();
process.exit(0);
}

// Handle flags
const validFlags = ["jsr", "dry-run", "help", "h"];
const unknownFlags = Object.keys(argv).filter(
(key) => !validFlags.includes(key) && key !== "_",
);

if (unknownFlags.length > 0) {
relinka.error(`❌ Unknown flag(s): ${unknownFlags.join(", ")}`);
showHelp();
process.exit(1);
}

async function publishNpm(dryRun: boolean) {
try {
if (dryRun) {
await execa("bun publish --dry-run", { stdio: "inherit" });
} else {
await execa("bun build:npm", { stdio: "inherit" });
await execa("bun publish", { stdio: "inherit" });
}
relinka.success("Published to npm successfully.");
} catch (error) {
relinka.error("❌ Failed to publish to npm:", error);
process.exit(1);
}
}

async function publishJsr(dryRun: boolean) {
try {
if (dryRun) {
await execa(
"bunx jsr publish --allow-slow-types --allow-dirty --dry-run",
{ stdio: "inherit" },
);
} else {
await execa("bun build:jsr", { stdio: "inherit" });
await execa("bunx jsr publish --allow-slow-types --allow-dirty", {
stdio: "inherit",
});
}
relinka.success("Published to JSR successfully.");
} catch (error) {
relinka.error("❌ Failed to publish to JSR:", error);
process.exit(1);
}
}

async function bumpJsrVersion(disable?: boolean) {
if (disable) {
return;
}
const pkg = JSON.parse(await fs.readFile("package.json", "utf-8"));
const jsrConfig = JSON.parse(await fs.readFile("jsr.jsonc", "utf-8"));
// @ts-expect-error TODO: fix ts
jsrConfig.version = pkg.version;
await fs.writeFile("jsr.jsonc", JSON.stringify(jsrConfig, null, 2));
}

async function bumpNpmVersion() {
await execa("bun bumpp", { stdio: "inherit" });
}

async function main() {
const { jsr, "dry-run": dryRun } = argv;
if (jsr) {
// await bumpJsrVersion();
await publishJsr(dryRun);
} else {
// await bumpNpmVersion();
await publishNpm(dryRun);
}
}

main().catch((error) => {
relinka.error("❌ An unexpected error occurred:", error);
process.exit(1);
});
6 changes: 6 additions & 0 deletions bump.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { defineConfig } from "bumpp";

export default defineConfig({
push: false,
commit: false,
});
Binary file modified bun.lockb
Binary file not shown.
Loading

0 comments on commit f022a02

Please sign in to comment.