Browse Source

大更新

ZaiZai 1 year ago
parent
commit
7217496fe9
25 changed files with 3958 additions and 1073 deletions
  1. 8 0
      .eslintrc
  2. 4 0
      dist/chunk-MN5DIFVJ.js
  3. 4 0
      dist/chunk-XVZDMLED.js
  4. 6 0
      dist/index.js
  5. 5 0
      dist/multipart-parser-YOS7MX5H.js
  6. 6 0
      dist/prm.js
  7. 6 0
      dist/yrm.js
  8. 0 3
      index.js
  9. 52 38
      package.json
  10. 3427 704
      pnpm-lock.yaml
  11. 0 3
      prm.js
  12. 4 0
      src/index.ts
  13. 4 0
      src/prm.ts
  14. 6 0
      src/shims.d.ts
  15. 8 0
      src/types.ts
  16. 239 0
      src/utils/index.ts
  17. 73 0
      src/utils/registries.ts
  18. 4 0
      src/yrm.ts
  19. 69 27
      test/basic.test.ts
  20. 14 0
      tsconfig.json
  21. 19 0
      tsup.config.ts
  22. 0 218
      utils/index.js
  23. 0 75
      utils/registries.js
  24. 0 2
      utils/require.js
  25. 0 3
      yrm.js

+ 8 - 0
.eslintrc

@@ -0,0 +1,8 @@
+{
+  "extends": [
+    "@antfu"
+  ],
+  "rules": {
+    "no-console": "off"
+  }
+}

File diff suppressed because it is too large
+ 4 - 0
dist/chunk-MN5DIFVJ.js


File diff suppressed because it is too large
+ 4 - 0
dist/chunk-XVZDMLED.js


+ 6 - 0
dist/index.js

@@ -0,0 +1,6 @@
+#!/usr/bin/env node
+
+    import { createRequire as topLevelCreateRequire } from 'module';
+    const require = topLevelCreateRequire(import.meta.url);
+    
+import{a as n}from"./chunk-MN5DIFVJ.js";import"./chunk-XVZDMLED.js";n("npm");

File diff suppressed because it is too large
+ 5 - 0
dist/multipart-parser-YOS7MX5H.js


+ 6 - 0
dist/prm.js

@@ -0,0 +1,6 @@
+#!/usr/bin/env node
+
+    import { createRequire as topLevelCreateRequire } from 'module';
+    const require = topLevelCreateRequire(import.meta.url);
+    
+import{a as n}from"./chunk-MN5DIFVJ.js";import"./chunk-XVZDMLED.js";n("pnpm");

+ 6 - 0
dist/yrm.js

@@ -0,0 +1,6 @@
+#!/usr/bin/env node
+
+    import { createRequire as topLevelCreateRequire } from 'module';
+    const require = topLevelCreateRequire(import.meta.url);
+    
+import{a as n}from"./chunk-MN5DIFVJ.js";import"./chunk-XVZDMLED.js";n("yarn");

+ 0 - 3
index.js

@@ -1,3 +0,0 @@
-#!/usr/bin/env node
-import { main } from "./utils/index.js";
-main("npm");

+ 52 - 38
package.json

@@ -1,56 +1,70 @@
 {
   "name": "hcny",
-  "version": "0.1.1",
   "type": "module",
+  "version": "0.2.1",
+  "packageManager": "pnpm@8.6.0",
   "description": "npm、yarn的 私有npm仓库的镜像源切换工具",
-  "main": "index.js",
-  "packageManager": "pnpm@7.10.0",
-  "bin": {
-    "hcny": "index.js",
-    "hnrm": "index.js",
-    "hprm": "prm.js",
-    "hyrm": "yrm.js"
-  },
-  "engines": {
-    "node": ">=12.x"
-  },
-  "files": [
-    "index.js",
-    "yrm.js",
-    "prm.js",
-    "utils",
-    "registries.json"
-  ],
+  "license": "MIT",
   "keywords": [
     "npm",
     "registry",
     "toggle",
     "yarn"
   ],
-  "license": "MIT",
+  "main": "./dist/index.js",
+  "module": "./dist/index.js",
+  "bin": {
+    "hcny": "dist/index.js",
+    "hnrm": "dist/index.js",
+    "hyrm": "dist/yrm.js",
+    "hprm": "dist/prm.js"
+  },
+  "files": [
+    "dist",
+    "LICENSE",
+    "README.md",
+    "registries.json"
+  ],
+  "engines": {
+    "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+  },
   "scripts": {
+    "build": "tsup",
     "coverage": "vitest run --coverage",
-    "dev": "node index.js",
-    "ls": "node index.js ls",
-    "test": "npm run ls && npm run test:add && npm run test:remove && npm run test:test",
-    "test:add": "node index.js add yyj https://www.yunyoujun.cn",
-    "test:remove": "node index.js remove yyj",
-    "test:test": "node index.js test",
-    "test:use": "node index.js use taobao",
-    "vitest": "vitest",
-    "postinstall": "node index.js ls",
+    "dev": "tsup --watch",
+    "lint": "eslint .",
+    "ls": "node dist/index.js ls",
+    "play": "node dist/index.js",
+    "test": "npm run ls && npm run test:add && npm run test:remove && npm run test:use && npm run test:test",
+    "test:add": "node dist/index.js add yyj https://www.yunyoujun.cn",
+    "test:remove": "node dist/index.js remove yyj",
+    "test:test": "node dist/index.js test",
+    "test:use": "node dist/index.js use 0x3f && node dist/index.js use taobao",
+    "test:unit": "vitest",
+    "typecheck": "tsc --noEmit",
+    "prepublishOnly": "npm run build",
+    "postinstall": "echo '`\\x1b[33mnnrm -h\\x1b[0m` to see usage \n`\\x1b[33mnnrm ls\\x1b[0m` to see registries'",
     "release": "bumpp --commit --push --tag"
   },
-  "dependencies": {
+  "devDependencies": {
+    "@antfu/eslint-config": "^0.39.4",
+    "@vitest/coverage-c8": "^0.31.3",
+    "bumpp": "^9.1.0",
     "cac": "^6.7.14",
-    "execa": "^6.1.0",
-    "node-fetch": "^3.2.10",
-    "picocolors": "^1.0.0"
+    "eslint": "^8.41.0",
+    "execa": "^7.1.1",
+    "lint-staged": "^13.2.2",
+    "node-fetch": "^3.3.1",
+    "picocolors": "^1.0.0",
+    "simple-git-hooks": "^2.8.1",
+    "tsup": "^6.7.0",
+    "typescript": "^5.0.4",
+    "vitest": "^0.31.3"
   },
-  "devDependencies": {
-    "@vitest/coverage-c8": "^0.24.3",
-    "bumpp": "^8.2.1",
-    "vite": "^3.2.0",
-    "vitest": "^0.24.3"
+  "simple-git-hooks": {
+    "pre-commit": "pnpm lint-staged"
+  },
+  "lint-staged": {
+    "*": "eslint --fix"
   }
 }

File diff suppressed because it is too large
+ 3427 - 704
pnpm-lock.yaml


+ 0 - 3
prm.js

@@ -1,3 +0,0 @@
-#!/usr/bin/env node
-import { main } from "./utils/index.js";
-main("pnpm");

+ 4 - 0
src/index.ts

@@ -0,0 +1,4 @@
+#!/usr/bin/env node
+import { main } from './utils'
+
+main('npm')

+ 4 - 0
src/prm.ts

@@ -0,0 +1,4 @@
+#!/usr/bin/env node
+import { main } from './utils/index.js'
+
+main('pnpm')

+ 6 - 0
src/shims.d.ts

@@ -0,0 +1,6 @@
+declare namespace NodeJS {
+  interface ProcessEnv {
+    HOME: string;
+    USERPROFILE: string;
+  }
+}

+ 8 - 0
src/types.ts

@@ -0,0 +1,8 @@
+export type RegistryName = 'npm' | 'yarn' | 'taobao' | 'tencent' | 'github' | 'npmMirror' | 'hcxxy' | string
+
+export interface Registry {
+  registry: string
+  home: string
+}
+
+export type Registries = Record<RegistryName, Registry>

+ 239 - 0
src/utils/index.ts

@@ -0,0 +1,239 @@
+import { existsSync, promises as fs } from 'node:fs'
+
+import { $ } from 'execa'
+import { green, red, yellow } from 'picocolors'
+import fetch from 'node-fetch'
+
+import { cac } from 'cac'
+
+import pkg from '../../package.json'
+
+// init default and custom registries
+import defaultRegistries from '../../registries.json'
+import {
+  addCustomRegistry,
+  getCustomRegistry,
+  removeCustomRegistry,
+} from './registries'
+
+export * from './registries'
+
+// init default and custom registries
+
+const cli = cac()
+
+// init in main
+export const store: {
+  pkgManager: 'npm' | 'yarn' | 'pnpm' | string
+  registries: Record<string, any>
+} = {
+  pkgManager: 'npm',
+  registries: {},
+}
+
+/**
+ * generate equal width name with dashline
+ * @returns
+ */
+function dashline(str: string) {
+  const maxCharWidth
+    = Math.max(...Object.keys(store.registries).map(key => key.length)) + 3
+
+  const line = new Array(Math.max(1, maxCharWidth - str.length)).join('-')
+  return `${str} ${line}`
+}
+
+/**
+ * Ensure suffix of a string
+ */
+function ensureSuffix(suffix: string, str: string) {
+  if (!str.endsWith(suffix))
+    return str + suffix
+  return str
+}
+
+/**
+ * get default and custom registries
+ * @returns
+ */
+export async function getAllRegistries() {
+  const customRegistries = await getCustomRegistry()
+  return Object.assign({}, defaultRegistries, customRegistries)
+}
+
+export async function getRegistriesList() {
+  let list = ''
+  const currentRegistry = await getCurrentRegistry(store.pkgManager)
+
+  let inList = false
+
+  Object.keys(store.registries).forEach((key) => {
+    const isCurrentRegistry = key === currentRegistry
+    if (isCurrentRegistry)
+      inList = true
+    const prefix = isCurrentRegistry ? '*' : ' '
+    const item = `\n ${prefix} ${dashline(key)} ${store.registries[key].registry}`
+    list += isCurrentRegistry ? green(item) : item
+  })
+
+  return {
+    inList,
+    list,
+    currentRegistry,
+  }
+}
+
+/**
+ * Show all npm registries
+ */
+export async function listRegistries() {
+  const { inList, list, currentRegistry } = await getRegistriesList()
+
+  if (!inList)
+    console.log(`\n  ${red('Unknown')} registry: ${yellow(currentRegistry)}`)
+  console.log(`${list}\n`)
+  return list
+}
+
+export async function getCurrentRegistry(pkgManager = 'npm') {
+  let registry = ''
+  try {
+    const { stdout = '' } = await $`${pkgManager} config get registry`
+    registry = stdout.trim()
+  }
+  catch {
+    // for yarn v3
+    const { stdout = '' } = await $`${pkgManager} config get npmRegistryServer`
+    registry = stdout.trim()
+  }
+
+  for (const name in store.registries) {
+    if (store.registries[name].registry === ensureSuffix('/', registry))
+      return name
+  }
+  return registry
+}
+
+/**
+ * https://docs.npmjs.com/cli/v7/commands/npm-config
+ * @param pkgManager
+ * @returns
+ */
+export async function setCurrentRegistry(name: string, pkgManager = 'npm') {
+  if (!store.registries[name]) {
+    console.log(`\n  ${red('Unknown')} registry: ${yellow(name)}`)
+    return
+  }
+
+  await $`${pkgManager} config set registry ${store.registries[name].registry}`
+}
+
+/**
+ * delay time
+ */
+async function getDelayTime(url: string) {
+  const start = +new Date()
+  return fetch(url)
+    .then(() => {
+      const time = +(new Date()) - start
+      const msg = `${time} ms`
+      if (time < 500)
+        return green(msg)
+
+      else if (time < 1000)
+        return yellow(msg)
+
+      else
+        return red(msg)
+    })
+    .catch((_e) => {
+      return red('Timeout')
+    })
+}
+
+/**
+ * list registries delay time
+ * @returns
+ */
+export async function listDelayTime() {
+  return await Promise.all(
+    Object.keys(store.registries).map(async (key) => {
+      const delayTime = await getDelayTime(store.registries[key].registry)
+      const item = ` ${dashline(key)} ${delayTime}`
+      console.log(item)
+    }),
+  )
+}
+
+/**
+ * @param pkgManager npm|yarn
+ */
+export async function main(pkgManager = 'npm') {
+  // init
+  store.registries = await getAllRegistries()
+  store.pkgManager = pkgManager
+
+  const onLs = async () => {
+    await listRegistries()
+  }
+  cli.command('ls', 'List all the registries').action(onLs)
+
+  cli
+    .command('use [registry]', 'Change registry')
+    .option('-l, --local', 'set \'.npmrc\' for local')
+    .action(async (registry, options) => {
+      if (!registry) {
+        console.log(
+          `\n  nnrm use <registry>\n  Example: ${yellow(
+            'nnrm use taobao',
+          )}\n`,
+        )
+      }
+      else if (options.l || options.local) {
+        const registryText = `registry=${store.registries[registry].registry}`
+        if (existsSync('.npmrc')) {
+          const content = await fs.readFile('.npmrc', 'utf-8')
+          await fs.writeFile(
+            '.npmrc',
+            content.replace(/^registry=.*/gm, registryText),
+          )
+        }
+        else {
+          await fs.writeFile('.npmrc', registryText)
+          await listRegistries()
+        }
+      }
+      else {
+        await setCurrentRegistry(registry, pkgManager)
+        await listRegistries()
+      }
+    })
+
+  cli
+    .command('test', 'Show response time for all registries')
+    .action(async () => {
+      console.log()
+      await listDelayTime()
+      console.log()
+    })
+
+  cli
+    .command('add <registry> <url> [home]', 'Add a custom registry')
+    .action(async (name, url, home) => {
+      await addCustomRegistry(name, url, home)
+      store.registries = await getAllRegistries()
+      await listRegistries()
+    })
+
+  cli
+    .command('remove <registry>', 'Remove a custom registry')
+    .action(async (name) => {
+      await removeCustomRegistry(name)
+      store.registries = await getAllRegistries()
+      await listRegistries()
+    })
+
+  cli.help()
+  cli.version(pkg.version)
+  cli.parse()
+}

+ 73 - 0
src/utils/registries.ts

@@ -0,0 +1,73 @@
+import { existsSync, promises as fs } from 'node:fs'
+import path from 'node:path'
+
+import { yellow } from 'picocolors'
+import { $ } from 'execa'
+import type { Registries, RegistryName } from '../types'
+
+const NNRM = path.join(process.env.HOME || process.env.USERPROFILE, '.nnrm')
+const NNRM_REGISTRIES = path.join(NNRM, 'registries.json')
+
+export async function getCustomRegistry() {
+  let customRegistries: Registries = {}
+  try {
+    const registriesText = await fs.readFile(NNRM_REGISTRIES, 'utf-8')
+    customRegistries = JSON.parse(registriesText.trim() || '{}')
+  }
+  catch (e) {
+    const msg = `\nWe will create '${yellow(
+      NNRM_REGISTRIES,
+    )}' to record your custom registries.\n`
+    console.log(msg)
+
+    if (!existsSync(NNRM)) {
+      try {
+        await fs.mkdir(NNRM, { recursive: true })
+      }
+      catch (e: any) {
+        // permission denied
+        console.log(e.message)
+        await $`mkdir ${NNRM}`.catch((e) => {
+          console.log(e.message)
+        })
+      }
+    }
+    await setCustomRegistry(customRegistries)
+  }
+  return customRegistries
+}
+
+/**
+ * write ~/.nnrm/registries.json
+ */
+async function setCustomRegistry(registries: Registries) {
+  return fs.writeFile(NNRM_REGISTRIES, JSON.stringify(registries, null, 2))
+}
+
+/**
+ * add custom registry
+ */
+export async function addCustomRegistry(name: RegistryName, url: string, home?: string) {
+  const customRegistries = await getCustomRegistry()
+
+  // npm config set registry auto add '/'
+  if (url.slice(-1) !== '/')
+    url += '/'
+
+  customRegistries[name] = {
+    home: home || url,
+    registry: url,
+  }
+  await setCustomRegistry(customRegistries)
+}
+
+/**
+ * remove a custom registry
+ */
+export async function removeCustomRegistry(name: string) {
+  const customRegistries = await getCustomRegistry()
+  if (customRegistries[name])
+    delete customRegistries[name]
+
+  await setCustomRegistry(customRegistries)
+}

+ 4 - 0
src/yrm.ts

@@ -0,0 +1,4 @@
+#!/usr/bin/env node
+import { main } from './utils/index.js'
+
+main('yarn')

+ 69 - 27
test/basic.test.ts

@@ -1,41 +1,83 @@
-import { execa } from 'execa'
-import { expect, test } from 'vitest'
+import { $ } from 'execa'
+import { beforeAll, describe, expect, it } from 'vitest'
 import registries from '../registries.json'
+import { addCustomRegistry, getAllRegistries, getCurrentRegistry, getRegistriesList, removeCustomRegistry, setCurrentRegistry, store } from '../src/utils'
 
-const nnrmCommand = async (...args: string[]) => {
-  return await execa('node', ['index.js', ...args])
+async function nnrmCommand(...args: string[]) {
+  return await $`node dist/index.js ${args.join(' ')}`
 }
 
-test('nnrm ls', async () => {
+const customRegistry = {
+  name: 'yyj',
+  url: 'https://www.yunyoujun.cn',
+  urlWithSlash: 'https://www.yunyoujun.cn/',
+}
+
+describe('hnrm ls', () => {
+  beforeAll(async () => {
+    // init
+    store.registries = await getAllRegistries()
+    store.pkgManager = 'npm'
+  })
+
   const name = 'npm'
-  const { stdout } = await nnrmCommand('ls')
-  expect(stdout.includes(name) && stdout.includes(registries[name].registry)).toBe(true)
+
+  it('command', async () => {
+    const { stdout } = await nnrmCommand('ls')
+    expect(stdout.includes(name) && stdout.includes(registries[name].registry)).toBe(true)
+  })
+
+  it('list', async () => {
+    const { list } = await getRegistriesList()
+    expect(list.includes(name) && list.includes(registries[name].registry)).toBe(true)
+  })
 })
 
-// test('nnrm use', async () => {
-//   const checkUse = async (registry: string) => {
-//     const { stdout } = await nnrmCommand('use', registry)
-//     // to debug, why this can not affect global registry?
-//     // had removed .npmrc
-//     expect(stdout.includes(`* ${registry}`)).toBe(true)
-//   }
+describe('hnrm use', () => {
+  async function useRegistry(registry: string) {
+    await setCurrentRegistry(registry, 'npm')
+  }
 
-//   await checkUse('yarn')
-//   await checkUse('taobao')
-// })
+  // use setTimeout to wait `npm config set` `npm config get`
+  it('use toggle', async () => {
+    await useRegistry('taobao')
+    setTimeout(async () => {
+      expect(await getCurrentRegistry()).toBe('taobao')
+    }, 50)
 
-const name = 'yyj'
+    setTimeout(async () => {
+      await useRegistry('npm')
+      setTimeout(async () => {
+        expect(await getCurrentRegistry()).toBe('npm')
+      }, 50)
+    }, 50)
+  })
+})
 
-test('nnrm add', async () => {
-  const url = 'https://www.yunyoujun.cn'
-  const { stdout } = await nnrmCommand('add', name, url)
-  expect(stdout.includes(name) && stdout.includes(url)).toBe(true)
+describe('hnrm add', () => {
+  it('add', async () => {
+    const { name, url, urlWithSlash } = customRegistry
+    await addCustomRegistry(name, url)
+    store.registries = await getAllRegistries()
+    expect(store.registries[name]).toStrictEqual({
+      home: urlWithSlash,
+      registry: urlWithSlash,
+    })
+  })
 
-  // const test = await nnrmCommand('remove', name)
-  // console.log(test.stdout)
+  it('list after add', async () => {
+    const { name, url } = customRegistry
+    const { inList, list } = await getRegistriesList()
+    expect(inList).toBe(true)
+    expect(list.includes(name) && list.includes(url)).toBe(true)
+  })
 })
 
-test('nnrm remove', async () => {
-  const { stdout } = await nnrmCommand('remove', name)
-  expect(stdout.includes(name)).toBe(false)
+describe('hnrm remove', () => {
+  it('utils', async () => {
+    expect(store.registries[customRegistry.name]).not.toBeUndefined()
+    await removeCustomRegistry(customRegistry.name)
+    store.registries = await getAllRegistries()
+    expect(store.registries[customRegistry.name]).toBeUndefined()
+  })
 })

+ 14 - 0
tsconfig.json

@@ -0,0 +1,14 @@
+{
+  "compilerOptions": {
+    "target": "es2018",
+    "module": "esnext",
+    "lib": ["esnext"],
+    "moduleResolution": "node",
+    "esModuleInterop": true,
+    "strict": true,
+    "strictNullChecks": true,
+    "resolveJsonModule": true,
+    "skipLibCheck": true,
+    "skipDefaultLibCheck": true
+  }
+}

+ 19 - 0
tsup.config.ts

@@ -0,0 +1,19 @@
+import { defineConfig } from 'tsup'
+
+export default defineConfig(options => ({
+  entry: [
+    'src/index.ts',
+    'src/prm.ts',
+    'src/yrm.ts',
+  ],
+  clean: true,
+  minify: !options.watch,
+  format: ['esm'],
+  // require shims
+  banner: {
+    js: `
+    import { createRequire as topLevelCreateRequire } from 'module';
+    const require = topLevelCreateRequire(import.meta.url);
+    `,
+  },
+}))

+ 0 - 218
utils/index.js

@@ -1,218 +0,0 @@
-import fs from "fs";
-
-import { execa } from "execa";
-import pc from "picocolors";
-import fetch from "node-fetch";
-
-import { cac } from "cac";
-// ES Module doesn't have require
-import { require } from "./require.js";
-
-const pkg = require("../package.json");
-const cli = cac();
-
-import {
-  getCustomRegistry,
-  addCustomRegistry,
-  removeCustomRegistry,
-} from "./registries.js";
-
-// init default and custom registries
-const defaultRegistries = require("../registries.json");
-// init in main
-let registries;
-
-/**
- * generate equal width name with dashline
- * @param {string} str
- * @returns
- */
-function dashline(str) {
-  const maxCharWidth =
-    Math.max(...Object.keys(registries).map((key) => key.length)) + 3;
-
-  const line = new Array(Math.max(1, maxCharWidth - str.length)).join("-");
-  return str + " " + line;
-}
-
-/**
- * Ensure suffix of a string
- * @param {string} suffix
- * @param {string} str
- */
-function ensureSuffix(suffix, str) {
-  if (!str.endsWith(suffix))
-    return str + suffix
-  return str
-}
-
-/**
- * get default and custom registries
- * @returns
- */
-async function getAllRegistries() {
-  const customRegistries = await getCustomRegistry();
-  return Object.assign({}, defaultRegistries, customRegistries);
-}
-
-/**
- * Show all npm registries
- */
-export async function listRegistries(pkgManager = "npm") {
-  let list = "";
-  const currentRegistry = await getCurrentRegistry(pkgManager);
-
-  let inList = false
-
-  Object.keys(registries).forEach((key) => {
-    const isCurrentRegistry = key === currentRegistry;
-    if (isCurrentRegistry) inList = true
-    const prefix = isCurrentRegistry ? "*" : " ";
-    const item = `\n ${prefix} ${dashline(key)} ${registries[key].registry}`;
-    list += isCurrentRegistry ? pc.green(item) : item;
-  });
-  if (!inList) console.log(`\n  ${pc.red('Unknown')} registry: ${pc.yellow(currentRegistry)}`) 
-  console.log(list + "\n");
-  return list;
-}
-
-async function getCurrentRegistry(pkgManager = "npm") {
-  let registry = ''
-  try {
-    const { stdout = '' } = await execa(pkgManager, ["config", "get", "registry"]);
-    registry = stdout.trim();
-  } catch {
-    // for yarn v3
-    const { stdout = '' } = await execa(pkgManager, ["config", "get", "npmRegistryServer"]);
-    registry = stdout.trim();
-  }
-
-  for (const name in registries) {
-    if (registries[name].registry === ensureSuffix('/', registry)) {
-      return name;
-    }
-  }
-  return registry
-}
-
-/**
- * https://docs.npmjs.com/cli/v7/commands/npm-config
- * @param {string} name
- * @param {*} pkgManager
- * @returns
- */
-export async function setCurrentRegistry(name, pkgManager = "npm") {
-  await execa(pkgManager, [
-    "config",
-    "set",
-    "registry",
-    registries[name].registry
-  ]);
-}
-
-/**
- * delay time
- * @param {string} url
- */
-async function getDelayTime(url) {
-  const start = +new Date();
-  return fetch(url)
-    .then(() => {
-      const time = new Date() - start;
-      const msg = `${time} ms`;
-      if (time < 500) {
-        return pc.green(msg);
-      } else if (time < 1000) {
-        return pc.yellow(msg);
-      } else {
-        return pc.red(msg);
-      }
-    })
-    .catch((e) => {
-      return pc.red("Timeout");
-    });
-}
-
-/**
- * list registries delay time
- * @returns
- */
-export async function listDelayTime() {
-  return await Promise.all(
-    Object.keys(registries).map(async (key) => {
-      const delayTime = await getDelayTime(registries[key].registry);
-      const item = ` ${dashline(key)} ${delayTime}`;
-      console.log(item);
-    })
-  );
-}
-
-/**
- * @param {string} pkgManager npm|yarn
- */
-export async function main(pkgManager = "npm") {
-  // init
-  registries = await getAllRegistries();
-
-  const onLs = async () => {
-    await listRegistries(pkgManager);
-  }
-  cli.command("ls", "List all the registries").action(onLs);
-
-  cli
-    .command("use [registry]", "Change registry")
-    .option("-l, --local", "set '.npmrc' for local")
-    .action(async (registry, options) => {
-      if (!registry) {
-        console.log(
-          `\n  nnrm use <registry>\n  Example: ${pc.yellow(
-            "nnrm use taobao"
-          )}\n`
-        );
-      } else {
-        await setCurrentRegistry(registry, pkgManager)
-        await listRegistries(pkgManager)
-      }
-
-      if (options.l || options.local) {
-        const registryText = `registry=${registries[registry].registry}`;
-        if (fs.existsSync(".npmrc")) {
-          const content = fs.readFileSync(".npmrc", "utf-8");
-          fs.writeFileSync(
-            ".npmrc",
-            content.replace(/^registry=.*/gm, registryText)
-          );
-        } else {
-          fs.writeFileSync(".npmrc", registryText);
-        }
-      }
-    });
-
-  cli
-    .command("test", "Show response time for all registries")
-    .action(async () => {
-      console.log();
-      await listDelayTime();
-      console.log();
-    });
-
-  cli
-    .command("add <registry> <url> [home]", "Add a custom registry")
-    .action(async (name, url, home) => {
-      await addCustomRegistry(name, url, home);
-      registries = await getAllRegistries();
-      await listRegistries(pkgManager);
-    });
-
-  cli
-    .command("remove <registry>", "Remove a custom registry")
-    .action(async (name) => {
-      await removeCustomRegistry(name);
-      registries = await getAllRegistries();
-      await listRegistries(pkgManager);
-    });
-
-  cli.help();
-  cli.version(pkg.version);
-  cli.parse();
-}

+ 0 - 75
utils/registries.js

@@ -1,75 +0,0 @@
-import fs from "fs";
-import path from "path";
-
-import pc from "picocolors";
-import { execa } from "execa";
-
-const NNRM = path.join(process.env.HOME || process.env.USERPROFILE, ".hcny");
-const NNRM_REGISTRIES = path.join(NNRM, "registries.json");
-
-export async function getCustomRegistry() {
-  let customRegistries = {};
-  try {
-    customRegistries = JSON.parse(fs.readFileSync(NNRM_REGISTRIES));
-  } catch (e) {
-    const msg = `\nWe will create '${pc.yellow(
-      NNRM_REGISTRIES
-    )}' to record your custom registries.\n`;
-    console.log(msg);
-
-    if (!fs.existsSync(NNRM)) {
-      try {
-        fs.mkdirSync(NNRM, { recursive: true });
-      } catch (e) {
-        // permission denied
-        console.log(e.message);
-        await execa("mkdir", [NNRM]).catch((e) => {
-          console.log(e.message);
-        });
-      }
-    }
-    setCustomRegistry(customRegistries);
-  }
-  return customRegistries;
-}
-
-/**
- * write ~/.nnrm/registries.json
- * @param {object} registries
- */
-function setCustomRegistry(registries) {
-  return fs.writeFileSync(NNRM_REGISTRIES, JSON.stringify(registries, null, 2));
-}
-
-/**
- * add custom registry
- * @param {string} name
- * @param {string} registry url
- * @param {string} home
- */
-export async function addCustomRegistry(name, url, home) {
-  let customRegistries = await getCustomRegistry();
-
-  // npm config set registry auto add '/'
-  if (url.slice(-1) !== "/") {
-    url += "/";
-  }
-
-  customRegistries[name] = {
-    home,
-    registry: url,
-  };
-  setCustomRegistry(customRegistries);
-}
-
-/**
- * remove a custom registry
- * @param {string} name
- */
-export async function removeCustomRegistry(name) {
-  let customRegistries = await getCustomRegistry();
-  if (customRegistries[name]) {
-    delete customRegistries[name];
-  }
-  setCustomRegistry(customRegistries);
-}

+ 0 - 2
utils/require.js

@@ -1,2 +0,0 @@
-import { createRequire } from "module";
-export const require = createRequire(import.meta.url);

+ 0 - 3
yrm.js

@@ -1,3 +0,0 @@
-#!/usr/bin/env node
-import { main } from "./utils/index.js";
-main("yarn");

Some files were not shown because too many files changed in this diff