Skip to content

Instantly share code, notes, and snippets.

@SokratisVidros
Last active April 17, 2024 10:06
Show Gist options
  • Save SokratisVidros/20a972c437f6806a57cde1c0852d0ff3 to your computer and use it in GitHub Desktop.
Save SokratisVidros/20a972c437f6806a57cde1c0852d0ff3 to your computer and use it in GitHub Desktop.
Claim your NPM package with an one-liner
#!/usr/bin/env zx
const args = process.argv.slice(2);
// Process CLI arguments
if (args.length < 2) {
console.log("Usage: npx zx https://dub.sh/npm-claim <package-name>");
process.exit(1);
}
const packageName = args[1];
// Check if package exists already in NPM
const exists = await spinner(
`Checking if ${packageName} is available...`,
async () => {
const res = await fetch(
`https://registry.npmjs.org/${encodeURIComponent(packageName)}`
);
return res.status === 200;
}
);
if (exists) {
console.log(`Package ${packageName} already exists`);
process.exit(0);
}
// Create the new package locally in 0.0.1-claimed version
const created = await spinner(`Creating ${packageName}...`, async () => {
await fs.ensureDir(packageName);
cd(packageName);
$.cwd = process.cwd();
if ((await $`npm init -y`.quiet().exitCode) !== 0) {
return false;
}
if (
(await $`sed -i -e 's/1\.0\.0/0\.0\.1-claimed/g' package.json`.quiet()
.exitCode) !== 0
) {
return false;
}
await fs.remove("package.json-e");
return true;
});
if (!created) {
cd("../");
await fs.remove(packageName);
console.log("Failed to create the package. Please try again.");
process.exit(1);
}
// Check if the npm CLI is logged in
const isLoggedIn = (await $`npm whoami`.quiet().exitCode) === 0;
if (!isLoggedIn) {
cd("../");
await fs.remove(packageName);
console.log(
"Please login to npm using `npm login` and rerun the tool to claim your package"
);
process.exit(1);
}
const otp = await question("Are you using 2FA? If yes, provide the OTP: ");
// Publish the package to NPM
const published = await spinner(`Registering ${packageName}...`, async () => {
$.cwd = process.cwd();
return (await $`npm publish --otp ${otp}`.quiet().exitCode) === 0;
});
if (!published) {
await fs.remove(packageName);
console.log(`${packageName} failed to register. Please try again.`);
process.exit(1);
}
console.log(`🔨 ${packageName} was registered successfully!`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment