Skip to content

Commit

Permalink
format code (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
ry authored Feb 28, 2024
1 parent 322661c commit 37c8573
Show file tree
Hide file tree
Showing 12 changed files with 138 additions and 106 deletions.
9 changes: 9 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ on:
branches: [main]

jobs:
lint-and-format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: denoland/setup-deno@v1
- run: deno fmt --check
# TODO
# - run: deno lint

test:
strategy:
matrix:
Expand Down
28 changes: 19 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# JSR npm command line tool

The JSR npm CLI integrates JSR (JavaScript Registry) packages with npm-based projects, facilitating the use of JSR packages in environments that traditionally rely on npm. Learn more about JSR at [jsr.io](https://jsr.io).
The JSR npm CLI integrates JSR (JavaScript Registry) packages with npm-based
projects, facilitating the use of JSR packages in environments that
traditionally rely on npm. Learn more about JSR at [jsr.io](https://jsr.io).

## Quick Start

Expand All @@ -10,7 +12,8 @@ Add a JSR package to your project:
npx jsr add @package/name # 'install' and 'i' are also supported
```

This command auto-updates your `package.json` and installs the package, automatically detecting and using your project's package manager.
This command auto-updates your `package.json` and installs the package,
automatically detecting and using your project's package manager.

## How It Works

Expand All @@ -20,9 +23,11 @@ The CLI creates or updates a `.npmrc` file in your project with:
@jsr:registry=https://npm.jsr.io
```

This line redirects npm to fetch JSR packages from the JSR registry instead of the default npm registry.
This line redirects npm to fetch JSR packages from the JSR registry instead of
the default npm registry.

Packages are added to `package.json` with an alias, mapping the JSR package name to the npm registry URL hosted by JSR, like so:
Packages are added to `package.json` with an alias, mapping the JSR package name
to the npm registry URL hosted by JSR, like so:

```json
{
Expand All @@ -32,7 +37,8 @@ Packages are added to `package.json` with an alias, mapping the JSR package name
}
```

This ensures that the package is fetched from JSR when you run npm install commands.
This ensures that the package is fetched from JSR when you run npm install
commands.

## Commands

Expand All @@ -43,14 +49,18 @@ This ensures that the package is fetched from JSR when you run npm install comma
## Limitations

- `jsr:` import specifiers are not supported.
- Due to transpilation, the developer experience in editors might differ from native JSR usage.
- Due to transpilation, the developer experience in editors might differ from
native JSR usage.

For the best developer experience and to fully leverage JSR's capabilities, consider environments with native JSR support like Deno.
For the best developer experience and to fully leverage JSR's capabilities,
consider environments with native JSR support like Deno.

## Contributing

We welcome contributions and feedback. Visit our GitHub repository to contribute or report issues.
We welcome contributions and feedback. Visit our GitHub repository to contribute
or report issues.

## License

This CLI is available under the [MIT License](https://opensource.org/licenses/MIT).
This CLI is available under the
[MIT License](https://opensource.org/licenses/MIT).
88 changes: 49 additions & 39 deletions src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,52 +26,62 @@ function printHelp() {
console.log(`jsr.io cli for node
Usage:
${prettyPrintRow([
["jsr add @std/log", 'Install the "@std/log" package from jsr.io'],
["jsr remove @std/log", 'Remove the "@std/log" package from the project'],
])}
${
prettyPrintRow([
["jsr add @std/log", 'Install the "@std/log" package from jsr.io'],
["jsr remove @std/log", 'Remove the "@std/log" package from the project'],
])
}
Commands:
${prettyPrintRow([
["i, install, add", "Install one or more jsr packages"],
["r, uninstall, remove", "Remove one or more jsr packages"],
["publish", "Publish a package to the JSR registry."],
])}
${
prettyPrintRow([
["i, install, add", "Install one or more jsr packages"],
["r, uninstall, remove", "Remove one or more jsr packages"],
["publish", "Publish a package to the JSR registry."],
])
}
Options:
${prettyPrintRow([
[
"-P, --save-prod",
"Package will be added to dependencies. This is the default.",
],
["-D, --save-dev", "Package will be added to devDependencies."],
["-O, --save-optional", "Package will be added to optionalDependencies."],
["--npm", "Use npm to remove and install packages."],
["--yarn", "Use yarn to remove and install packages."],
["--pnpm", "Use pnpm to remove and install packages."],
["--bun", "Use bun to remove and install packages."],
["--verbose", "Show additional debugging information."],
["-h, --help", "Show this help text."],
["--version", "Print the version number."],
])}
${
prettyPrintRow([
[
"-P, --save-prod",
"Package will be added to dependencies. This is the default.",
],
["-D, --save-dev", "Package will be added to devDependencies."],
["-O, --save-optional", "Package will be added to optionalDependencies."],
["--npm", "Use npm to remove and install packages."],
["--yarn", "Use yarn to remove and install packages."],
["--pnpm", "Use pnpm to remove and install packages."],
["--bun", "Use bun to remove and install packages."],
["--verbose", "Show additional debugging information."],
["-h, --help", "Show this help text."],
["--version", "Print the version number."],
])
}
Publish Options:
${prettyPrintRow([
[
"--token <Token>",
"The API token to use when publishing. If unset, interactive authentication is be used.",
],
[
"--dry-run",
"Prepare the package for publishing performing all checks and validations without uploading.",
],
["--allow-slow-types", "Allow publishing with slow types."],
])}
${
prettyPrintRow([
[
"--token <Token>",
"The API token to use when publishing. If unset, interactive authentication is be used.",
],
[
"--dry-run",
"Prepare the package for publishing performing all checks and validations without uploading.",
],
["--allow-slow-types", "Allow publishing with slow types."],
])
}
Environment variables:
${prettyPrintRow([
["JSR_URL", "Use a different registry url for the publish command"],
])}
${
prettyPrintRow([
["JSR_URL", "Use a different registry url for the publish command"],
])
}
`);
}

Expand Down Expand Up @@ -122,7 +132,7 @@ if (args.length === 0) {
process.exit(0);
} else if (options.values.version) {
const version = JSON.parse(
fs.readFileSync(path.join(__dirname, "..", "package.json"), "utf-8")
fs.readFileSync(path.join(__dirname, "..", "package.json"), "utf-8"),
).version as string;
console.log(version);
process.exit(0);
Expand Down
6 changes: 3 additions & 3 deletions src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
import * as path from "node:path";
import * as fs from "node:fs";
import * as kl from "kolorist";
import { JsrPackage, exec, fileExists } from "./utils";
import { Bun, PkgManagerName, getPkgManager } from "./pkg_manager";
import { exec, fileExists, JsrPackage } from "./utils";
import { Bun, getPkgManager, PkgManagerName } from "./pkg_manager";
import { downloadDeno, getDenoDownloadUrl } from "./download";

const NPMRC_FILE = ".npmrc";
Expand Down Expand Up @@ -112,7 +112,7 @@ export async function publish(cwd: string, options: PublishOptions) {
// in case jsr gets added to a project as a dependency where
// developers use multiple OSes
process.platform,
process.platform === "win32" ? "deno.exe" : "deno"
process.platform === "win32" ? "deno.exe" : "deno",
);

// Check if deno executable is available, download it if not.
Expand Down
12 changes: 6 additions & 6 deletions src/download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export async function getDenoDownloadUrl(): Promise<DownloadInfo> {
if (!res.ok) {
await res.body?.cancel();
throw new Error(
`${res.status}: Unable to retrieve canary version information from ${DENO_CANARY_INFO_URL}.`
`${res.status}: Unable to retrieve canary version information from ${DENO_CANARY_INFO_URL}.`,
);
}
const sha = (await res.text()).trim();
Expand All @@ -54,7 +54,7 @@ export async function getDenoDownloadUrl(): Promise<DownloadInfo> {

export async function downloadDeno(
binPath: string,
info: DownloadInfo
info: DownloadInfo,
): Promise<void> {
const binFolder = path.dirname(binPath);

Expand Down Expand Up @@ -93,13 +93,13 @@ export async function downloadDeno(
// Delete downloaded file
await fs.promises.rm(file);
},
{ max: contentLen }
{ max: contentLen },
);
}

async function withProgressBar<T>(
fn: (tick: (n: number) => void) => Promise<T>,
options: { max: number }
options: { max: number },
): Promise<T> {
let current = 0;
let start = Date.now();
Expand All @@ -123,7 +123,7 @@ async function withProgressBar<T>(

const bar = "#".repeat((barLength / 100) * percent) + ">";
const remaining = kl.blue(
"-".repeat(Math.max(barLength - bar.length, 0))
"-".repeat(Math.max(barLength - bar.length, 0)),
);
s += ` [${kl.cyan(bar)}${remaining}] `;
}
Expand Down Expand Up @@ -152,7 +152,7 @@ async function withProgressBar<T>(
}

async function* streamToAsyncIterable<T>(
stream: ReadableStream<T>
stream: ReadableStream<T>,
): AsyncIterable<T> {
const reader = stream.getReader();
try {
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// Copyright 2024 the JSR authors. MIT license.
export {
install,
remove,
type InstallOptions,
publish,
type PublishOptions,
remove,
} from "./commands";
export { JsrPackage, JsrPackageNameError } from "./utils";
21 changes: 11 additions & 10 deletions src/pkg_manager.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright 2024 the JSR authors. MIT license.
import { InstallOptions } from "./commands";
import { JsrPackage, exec, findProjectDir } from "./utils";
import { exec, findProjectDir, JsrPackage } from "./utils";
import * as kl from "kolorist";

async function execWithLog(cmd: string, args: string[], cwd: string) {
Expand All @@ -18,7 +18,7 @@ function modeToFlag(mode: InstallOptions["mode"]): string {

function toPackageArgs(pkgs: JsrPackage[]): string[] {
return pkgs.map(
(pkg) => `@${pkg.scope}/${pkg.name}@npm:${pkg.toNpmPackage()}`
(pkg) => `@${pkg.scope}/${pkg.name}@npm:${pkg.toNpmPackage()}`,
);
}

Expand Down Expand Up @@ -46,7 +46,7 @@ class Npm implements PackageManager {
await execWithLog(
"npm",
["remove", ...packages.map((pkg) => pkg.toString())],
this.cwd
this.cwd,
);
}
}
Expand All @@ -68,7 +68,7 @@ class Yarn implements PackageManager {
await execWithLog(
"yarn",
["remove", ...packages.map((pkg) => pkg.toString())],
this.cwd
this.cwd,
);
}
}
Expand All @@ -90,7 +90,7 @@ class Pnpm implements PackageManager {
await execWithLog(
"yarn",
["remove", ...packages.map((pkg) => pkg.toString())],
this.cwd
this.cwd,
);
}
}
Expand All @@ -112,7 +112,7 @@ export class Bun implements PackageManager {
await execWithLog(
"bun",
["remove", ...packages.map((pkg) => pkg.toString())],
this.cwd
this.cwd,
);
}
}
Expand All @@ -129,14 +129,15 @@ function getPkgManagerFromEnv(value: string): PkgManagerName | null {

export async function getPkgManager(
cwd: string,
pkgManagerName: PkgManagerName | null
pkgManagerName: PkgManagerName | null,
) {
const envPkgManager = process.env.npm_config_user_agent;
const fromEnv =
envPkgManager !== undefined ? getPkgManagerFromEnv(envPkgManager) : null;
const fromEnv = envPkgManager !== undefined
? getPkgManagerFromEnv(envPkgManager)
: null;

const { projectDir, pkgManagerName: fromLockfile } = await findProjectDir(
cwd
cwd,
);

const result = pkgManagerName || fromEnv || fromLockfile || "npm";
Expand Down
8 changes: 4 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ export class JsrPackage {
}

throw new JsrPackageNameError(
`Invalid jsr package name: A jsr package name must have the format @<scope>/<name>, but got "${input}"`
`Invalid jsr package name: A jsr package name must have the format @<scope>/<name>, but got "${input}"`,
);
}

private constructor(
public scope: string,
public name: string,
public version: string | null
public version: string | null,
) {}

toNpmPackage(): string {
Expand Down Expand Up @@ -80,7 +80,7 @@ export async function findProjectDir(
projectDir: cwd,
pkgManagerName: null,
pkgJsonPath: null,
}
},
): Promise<ProjectInfo> {
const npmLockfile = path.join(dir, "package-lock.json");
if (await fileExists(npmLockfile)) {
Expand Down Expand Up @@ -154,7 +154,7 @@ export async function exec(
cmd: string,
args: string[],
cwd: string,
env?: Record<string, string | undefined>
env?: Record<string, string | undefined>,
) {
const cp = spawn(cmd, args, { stdio: "inherit", cwd, shell: true, env });

Expand Down
Loading

0 comments on commit 37c8573

Please sign in to comment.