@fanwang/pack-util 3.0.1 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
1
  {
2
2
  "cSpell.words": [
3
+ "antfu",
3
4
  "bumpp",
4
5
  "deduped",
5
6
  "execa",
package/README.md CHANGED
@@ -1,19 +1,19 @@
1
- # pack-util
1
+ # pack-util
2
2
 
3
- **中文** | [English](./README.en-US.md)
3
+ **中文** | [English](./README.en-US.md)
4
4
 
5
5
  一个打包工具,可以在互联网网机器上将项目 ./node_modules 中安装的包遍历后打包,并放在 ./node_modules_pack 文件夹中,并批量上传到 nexus 搭建的 npm 私服上。支持 `pnpm`/`yarn`/`npm` 打包工具。
6
6
 
7
- ## 安装
7
+ ## 安装
8
8
 
9
9
  全局安装即可。
10
10
  ```sh
11
11
  npm install -g @fanwang/pack-util
12
12
  ```
13
13
 
14
- ## 使用
14
+ ## 使用
15
15
 
16
- **使用说明**
16
+ **使用说明**
17
17
 
18
18
  如果使用控制台命令的时候提示电脑禁止运行脚本,用管理员身份运行 cmd 或者 vscode 等然后在命令行输入:
19
19
 
@@ -23,11 +23,11 @@ Set-ExecutionPolicy RemoteSigned
23
23
 
24
24
  建议先将源仓库设为阿里镜像仓库,这样打包速度更快(yarn 和 npm 需要同时设置):
25
25
  ```sh
26
- yarn config set registry https://registry.npmmirror.com
27
- npm config set registry https://registry.npmmirror.com
26
+ yarn config set registry https://registry.npmmirror.com
27
+ npm config set registry https://registry.npmmirror.com
28
28
  ```
29
29
 
30
- ### 第一步. 将项目所有依赖包下载至 ./node_modules_pack 文件夹
30
+ ### 第一步. 将项目所有依赖包下载至 ./node_modules_pack 文件夹
31
31
  ```sh
32
32
  cd your_project
33
33
  pack-util pack
@@ -35,13 +35,14 @@ pack-util pack
35
35
  ```
36
36
  **解释:**
37
37
  工具是根据你使用的包管理工具来检索项目的所有依赖包。
38
- - pnpm: 根据 pnpm-lock.yaml 文件来检索
39
- - yarn: 根据 yarn.lock 文件来检索
40
- - npm: 根据 npm list --all 的输出来检索
38
+ - pnpm: 根据 `pnpm-lock.yaml` 文件来检索
39
+ - yarn: 根据 `yarn.lock` 文件来检索
40
+ - npm: 根据 `npm list --all` 的输出来检索
41
+
41
42
  因此,如果单纯的想从互联网下载一些包,可以仅凭一个 package.json 文件,利用不同的包管理工具执行 install 得到相应的检索文件后,就可以执行 pack 操作了。甚至建立一个空文件夹,然后通过 `yarn add` | `pnpm add` | `npm install` 添加自己需要的包来直接得到检索文件,也是可以的。
42
43
 
43
- ### 第二步. 将依赖包批量上传到 nexus 搭建的 npm 私服上
44
- 1. 将 ./node_modules_pack 文件夹和你的项目一起拷贝至内网机器上,然后执行上传。
44
+ ### 第二步. 将依赖包批量上传到 nexus 搭建的 npm 私服上
45
+ 1. 将 ./node_modules_pack 文件夹和你的项目一起拷贝至内网机器上,然后执行上传。
45
46
  ```sh
46
47
  cd your_project
47
48
  pack-util upload
@@ -49,7 +50,7 @@ pack-util upload
49
50
  **解释:**
50
51
  工具是在命令执行目录下查找 ./node_modules_pack 文件夹,然后把文件夹中的包批量上传,所以只需要把 ./node_modules_pack 文件夹拷贝到命令执行目录即可。
51
52
 
52
- 2. 输入参数
53
+ 2. 输入参数
53
54
  ```
54
55
  ? Please input your Nexus url host (eg: http://xx.xx.xx.xx:xxxx): http://xx.xx.xx.xx:8081/
55
56
  ? Please input your Nexus npm repository (eg: localNpm): localNpm
@@ -57,26 +58,25 @@ pack-util upload
57
58
  ? password: [hidden]
58
59
  ```
59
60
 
60
- 3. 如果出现上传失败,删除其他成功上传的包,然后重新执行上传(也可以直接重试上传)。
61
+ 3. 如果出现上传失败,删除其他成功上传的包,然后重新执行上传(也可以直接重试上传)。
61
62
 
62
- ### 第三步. 在内网机器上执行包依赖安装
63
+ ### 第三步. 在内网机器上执行包依赖安装
63
64
  先删除 `yarn.lock` / `package-lock.json` / `pnpm-lock.yaml` 文件。
64
65
 
65
- **PNPM**
66
+ **PNPM**
66
67
  ```
67
68
  pnpm config set registry http://xx.xx.xx.xx:xxxx/repository/localNpm/
68
69
  pnpm install
69
70
  ```
70
71
 
71
- **YARN**
72
+ **YARN**
72
73
  ```
73
74
  yarn config set registry http://xx.xx.xx.xx:xxxx/repository/localNpm/
74
75
  yarn install
75
76
  ```
76
77
 
77
- **NPM**
78
+ **NPM**
78
79
  ```
79
80
  npm config set registry http://xx.xx.xx.xx:xxxx/repository/localNpm/
80
81
  npm install --save --legacy-peer-deps # 注意:在私网上安装 npm 包需要忽略对 peer 依赖
81
82
  ```
82
-
package/bin/index.js CHANGED
@@ -1,49 +1,67 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { execa } from 'execa'
4
- import { mkdirSync, readdirSync, createReadStream, createWriteStream, readFileSync } from 'fs'
3
+ import { createReadStream, createWriteStream, mkdirSync, readdirSync, readFileSync } from 'node:fs'
4
+ import process from 'node:process'
5
+ import url from 'node:url'
5
6
  import { Command } from 'commander'
6
- import inquirer from 'inquirer'
7
+ import { execa } from 'execa'
7
8
  import FormData from 'form-data'
9
+ import inquirer from 'inquirer'
8
10
  import fetch from 'node-fetch'
9
- import url from 'url'
10
- import yaml from 'yaml'
11
11
  import pLimit from 'p-limit'
12
+ import yaml from 'yaml'
12
13
 
13
14
  const program = new Command()
14
15
 
15
16
  program
16
17
  .name('pack-util')
17
18
  .description('Pack all installed package in ./node_modules, and publish to Nexus self-hosted Registry.')
18
- .version('3.0.1')
19
-
19
+ .version('3.2.0')
20
20
 
21
21
  const limit = pLimit(10)
22
- const getPackageInfos = async (packageManager) => {
22
+ async function getPackageInfos(packageManager) {
23
23
  // 使用 yarn
24
24
  if (packageManager === 'yarn') {
25
25
  const fileData = readFileSync('./yarn.lock')
26
- return fileData.toString().split(/\r?\n/)
27
- .filter(line => line.startsWith(' resolved'))
28
- .map(line => line.substring(12, line.length - 1))
26
+ return fileData.toString().split(/\r?\n/).filter(line => line.startsWith(' resolved')).map(line => line.substring(12, line.length - 1))
29
27
  }
28
+ // 使用 pnpm
30
29
  else if (packageManager === 'pnpm') {
31
30
  const fileData = readFileSync('./pnpm-lock.yaml', 'utf8')
32
31
  const pnpmLock = yaml.parse(fileData)
33
- // 直接使用 `packages` 下的键作为包名和版本
34
- const packages = Object.keys(pnpmLock.packages)
35
- return Array.from(new Set(packages)) // 去掉重复项
32
+ // 直接使用 `packages` 下的键作为包名和版本,同时处理其下的 `peerDependencies`
33
+ const packages = Object.keys(pnpmLock.packages).reduce((acc, key) => {
34
+ const pkg = pnpmLock.packages[key]
35
+ // 将当前包加入列表
36
+ acc.add(key)
37
+ if (pkg.peerDependencies) {
38
+ Object.keys(pkg.peerDependencies).forEach((peer) => {
39
+ const peerVersion = pkg.peerDependencies[peer]
40
+ // 只匹配版本号
41
+ const versionRegex = /(\d+\.\d+\.\d+)/
42
+ const versionMatch = peerVersion.match(versionRegex)
43
+ if (versionMatch && versionMatch[1]) {
44
+ const exactVersion = versionMatch[1]
45
+ const peerPackageKey = `${peer}@${exactVersion}`
46
+ acc.add(peerPackageKey)
47
+ }
48
+ })
49
+ }
50
+ return acc
51
+ }, new Set())
52
+ return Array.from(packages) // 返回去重后的包
36
53
  }
37
54
  // 使用 npm
38
55
  else {
39
56
  const { stdout } = await execa('npm', ['list', '--all'])
40
57
  let packages = stdout.split('\n')
41
- packages.splice(0, 1) //去掉首行路径字符串
58
+ packages.splice(0, 1) // 去掉首行路径字符串
42
59
  packages = packages.filter(item => !item.includes('deduped')) // 去掉标记重复的包
43
- .map(name => {
60
+ .map((name) => {
44
61
  const nameRegex = /(\S+@.+)/g
45
62
  const nameParse = name.match(nameRegex)
46
- if (nameParse && nameParse.length > 0) return nameParse[0]
63
+ if (nameParse && nameParse.length > 0)
64
+ return nameParse[0]
47
65
  else return ''
48
66
  }) // 解析每行的包名称
49
67
  .filter(packageName => packageName.length > 0) // 去掉空行
@@ -51,33 +69,36 @@ const getPackageInfos = async (packageManager) => {
51
69
  }
52
70
  }
53
71
 
72
+ let index = 0
54
73
  // 利用 npm pack 在外网上对 dependencies 中的所有包打包。
55
- var index = 0
56
- const packPackage = async (packageName) => {
57
- const { stdout } = await execa('npm', ['pack', packageName, '--pack-destination=./node_modules_pack'])
58
- index++
59
- // console.log(`${index}: ${stdout}`)
60
- process.stdout.clearLine()
61
- process.stdout.cursorTo(0)
62
- process.stdout.write(`${index}: ${stdout}`) // 在同一行打印处理进度
63
- return stdout
64
- }
74
+ // const packPackage = async (packageName) => {
75
+ // const { stdout } = await execa('npm', ['pack', packageName, '--pack-destination=./node_modules_pack'])
76
+ // index++
77
+ // // console.log(`${index}: ${stdout}`)
78
+ // process.stdout.clearLine()
79
+ // process.stdout.cursorTo(0)
80
+ // process.stdout.write(`${index}: ${stdout}`) // 在同一行打印处理进度
81
+ // return stdout
82
+ // }
65
83
 
66
- const downloadPackage = async (packageUrl) => {
67
- const urlObj = url.parse(packageUrl)
84
+ // 直接利用依赖包的下载地址进行下载
85
+ async function downloadPackage(packageUrl) {
86
+ const urlObj = new url.URL(packageUrl)
68
87
  const filename = urlObj.pathname.substring(urlObj.pathname.lastIndexOf('/') + 1)
69
- const fileStream = createWriteStream('./node_modules_pack/' + filename)
88
+ const fileStream = createWriteStream(`./node_modules_pack/${filename}`)
70
89
  let res
71
90
  try {
72
91
  res = await fetch(packageUrl)
73
- } catch (error) {
74
- console.error(`Failed to download package ${packageUrl}: ${error.message}`)
92
+ }
93
+ catch (error) {
94
+ console.error(`\nWARN: Failed to download package ${packageUrl}: ${error.message}`)
75
95
  return filename
76
96
  }
77
97
  if (!res?.ok) {
78
- console.error(`Failed to download package ${filename}: ${res.status} ${res.statusText}`)
98
+ console.error(`\nWARN: Failed to download package ${filename}: ${res.status} ${res.statusText}`)
79
99
  return filename
80
- } else {
100
+ }
101
+ else {
81
102
  res.body.pipe(fileStream)
82
103
  await new Promise((resolve, reject) => {
83
104
  fileStream.on('finish', () => {
@@ -95,17 +116,19 @@ const downloadPackage = async (packageUrl) => {
95
116
  }
96
117
 
97
118
  // 通过 nexus 的 components upload API 上传 npm 包,有时候会报 statusCode 500,暂不知道原因,重新上传即可。
98
- const uploadPackage = async (packageName, options) => {
119
+ async function uploadPackage(packageName, options) {
99
120
  const { host, repository, username, password } = options
100
121
  const form = new FormData()
101
- form.append('npm.asset', createReadStream('./node_modules_pack/' + packageName))
122
+ form.append('npm.asset', createReadStream(`./node_modules_pack/${packageName}`))
102
123
  form.submit({
103
124
  hostname: new URL(host).hostname,
104
125
  port: new URL(host).port,
105
126
  path: `/service/rest/v1/components?repository=${repository}`,
106
- auth: `${username}:${password}`
107
- }, function (err, res) {
108
- if (err) console.log(err.message)
127
+ auth: `${username}:${password}`,
128
+ }, (err, res) => {
129
+ if (err) {
130
+ process.stdout.write(`\n${err.message}`)
131
+ }
109
132
  else {
110
133
  if (res.statusCode > 200 && res.statusCode < 300) {
111
134
  // upload success
@@ -114,7 +137,9 @@ const uploadPackage = async (packageName, options) => {
114
137
  process.stdout.cursorTo(0)
115
138
  process.stdout.write(`${index}: ${packageName}`) // 在同一行打印处理进度
116
139
  }
117
- else console.log(`${packageName} : UPLOAD ERROR -- code ${res.statusCode} -- ${res.statusMessage}`) //打印上传失败的包
140
+ else {
141
+ process.stdout.write(`\n${packageName} : UPLOAD ERROR -- code ${res.statusCode} -- ${res.statusMessage}`)
142
+ } // 打印上传失败的包
118
143
  }
119
144
  })
120
145
  }
@@ -129,30 +154,37 @@ program
129
154
  name: 'packageManager',
130
155
  message: 'Please select your package manager:',
131
156
  choices: ['pnpm', 'yarn', 'npm'],
132
- default: 'pnpm'
157
+ default: 'pnpm',
133
158
  },
134
159
  ]
135
160
  inquirer.prompt(questions).then((options) => {
136
161
  getPackageInfos(options.packageManager).then(async (packages) => {
137
- console.log(`Total ${packages.length} packages to be packed, please wait...`)
162
+ process.stdout.write(`Total ${packages.length} packages to be packed, please wait...\n`)
138
163
  mkdirSync('./node_modules_pack', { recursive: true })
139
164
  if (options.packageManager === 'yarn') {
140
- const downloadTasks = packages.map((packageUrl) =>
141
- limit(() => downloadPackage(packageUrl))
165
+ const downloadTasks = packages.map(packageUrl =>
166
+ limit(() => downloadPackage(packageUrl)),
142
167
  )
143
168
  await Promise.all(downloadTasks)
144
- } else {
145
- const packTasks = packages.map((packageName) =>
146
- limit(() => packPackage(packageName))
147
- )
169
+ }
170
+ else {
171
+ const { stdout } = await execa('npm', ['config', 'get', 'registry'])
172
+ const registryUrl = stdout.endsWith('/') ? stdout : `${stdout}/`
173
+ const packTasks = packages.map((packageName) => {
174
+ const atIndex = packageName.lastIndexOf('@')
175
+ const fullname = packageName.substring(0, atIndex)
176
+ const name = fullname.includes('/') ? fullname.split('/')[1] : fullname
177
+ const version = packageName.substring(atIndex + 1)
178
+ const packageUrl = `${registryUrl}${fullname}/-/${name}-${version}.tgz`
179
+ return limit(() => downloadPackage(packageUrl))
180
+ })
148
181
  await Promise.all(packTasks)
149
182
  }
150
- console.log('\nAll packages are successfully packed in ./node_modules_pack!')
183
+ process.stdout.write('\nAll packages are successfully packed in ./node_modules_pack!')
151
184
  })
152
185
  })
153
186
  })
154
187
 
155
-
156
188
  program
157
189
  .command('upload')
158
190
  .description('Upload all packed packages in ./node_modules_pack to Nexus self-hosted Registry')
@@ -161,29 +193,29 @@ program
161
193
  {
162
194
  type: 'input',
163
195
  name: 'host',
164
- message: 'Please input your Nexus url host (eg: http://xx.xx.xx.xx:xxxx): '
196
+ message: 'Please input your Nexus url host (eg: http://xx.xx.xx.xx:xxxx): ',
165
197
  },
166
198
  {
167
199
  type: 'input',
168
200
  name: 'repository',
169
201
  message: 'Please input your Nexus npm repository (eg: localNpm): ',
170
- default: 'localNpm'
202
+ default: 'localNpm',
171
203
  },
172
204
  {
173
205
  type: 'input',
174
206
  name: 'username',
175
207
  message: 'login to Nexus by username: ',
176
- default: 'admin'
208
+ default: 'admin',
177
209
  },
178
210
  {
179
211
  type: 'password',
180
212
  name: 'password',
181
- message: 'password: '
213
+ message: 'password: ',
182
214
  },
183
215
  ]
184
- inquirer.prompt(questions).then(options => {
216
+ inquirer.prompt(questions).then((options) => {
185
217
  const packages = readdirSync('./node_modules_pack')
186
- console.log(`Total ${packages.length} packages to be uploaded, please wait...`)
218
+ process.stdout.write(`\nTotal ${packages.length} packages to be uploaded, please wait...`)
187
219
  for (const packageName of packages) {
188
220
  uploadPackage(packageName, options)
189
221
  }
@@ -0,0 +1,3 @@
1
+ import antfu from '@antfu/eslint-config'
2
+
3
+ export default antfu()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fanwang/pack-util",
3
- "version": "3.0.1",
3
+ "version": "3.2.0",
4
4
  "description": "Pack all installed package in ./node_modules, and publish to Nexus self-hosted Registry.",
5
5
  "bin": {
6
6
  "pack-util": "./bin/index.js"
@@ -38,6 +38,7 @@
38
38
  "yaml": "^2.5.1"
39
39
  },
40
40
  "devDependencies": {
41
+ "@antfu/eslint-config": "^3.7.3",
41
42
  "bumpp": "^9.6.1",
42
43
  "czg": "^1.10.1",
43
44
  "taze": "^0.17.2"