-
Notifications
You must be signed in to change notification settings - Fork 10
/
package.ts
214 lines (187 loc) · 5.34 KB
/
package.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/*
* @Author: Cphayim
* @Date: 2021-07-27 15:31:50
* @Description: package manager
*/
import path from 'node:path'
import { execa } from 'execa'
import fs from 'fs-extra'
import { logger } from '@vrn-deco/cli-log'
import { NPMRegistry, PackageManager } from '@vrn-deco/cli-shared'
import { DistTag } from './common.js'
import { type InstallOptions, installPackage } from './install.js'
import { queryPackageVersion } from './querier.js'
import { isDistTagVersion, isPackage, parseModuleMap } from './utils.js'
type PackageOptions = InstallOptions & {
//
}
/**
* Default:
* install modules via npm registry
* - if an exact version number is specified
* - find the module in baseDir, install it if not found
* - if a dist tag is specified
* - query the exact version corresponding to the dist tag
* - find the module in baseDir, install it if not found
*
* Local:
* use the specified local module
*/
enum Mode {
Default,
Local,
}
export class NPMPackage {
private loaded = false
/**
* mode
*/
private mode: Mode = Mode.Default
/**
* package name
*/
private name: string
/**
* package version or dist tag
*/
private versionOrDistTag: string
/**
* base directory
*
* if the module is not installed, install it to `${baseDir}/node_modules/${name}`
*/
private baseDir: string
/**
* npm registry
*/
private registry: string
/**
* package manager
*/
private packageManager: PackageManager
/**
* local modules mapping
*/
private localMap: Record<string, string>
constructor(options: PackageOptions) {
this.name = options.name
this.versionOrDistTag = options.versionOrDistTag ?? DistTag.Latest
this.baseDir = options.baseDir ?? process.cwd()
this.registry = options.registry ?? NPMRegistry.NPM
this.packageManager = options.packageManager ?? PackageManager.NPM
this.localMap = parseModuleMap()
if (this.localMap[this.name]) {
this.mode = Mode.Local
}
}
/**
* package directory absolute path
*/
get packageDir(): string {
this.requireLoaded()
return this.mode === Mode.Local ? this.localMap[this.name] : this.cachePackageDir
}
private get cachePackageDir() {
return path.join(this.baseDir, 'node_modules', this.name)
}
/**
* package.json parse object
*/
get packageJSON(): Record<string, string> {
return fs.readJsonSync(path.join(this.packageDir, 'package.json'))
}
/**
* package.json main field absolute path
*/
get mainScript(): string {
const pkg = this.packageJSON
if (pkg && pkg['main']) {
return path.join(this.packageDir, pkg['main'])
} else {
throw new Error(`${this.name} package.main field not exists`)
}
}
/**
* load package
*
* must be called after create instance, it will inspect and install modules based on mode rules.
*/
async load(): Promise<this> {
if (this.loaded) return this
logger.verbose(`init package: ${this.name}@${this.versionOrDistTag}`)
if (this.mode === Mode.Local) {
await this.loadLocal()
} else {
await this.loadExternal()
}
this.loaded = true
return this
}
/**
* load external package
*
* check package on local cache. if not found, install it
*/
private async loadExternal() {
logger.verbose(`init external package...`)
if (!fs.pathExistsSync(this.baseDir)) {
fs.mkdirpSync(this.baseDir)
}
await this.standardizeVersion()
await this.installOrUpdate()
}
/**
* load local package
*/
private async loadLocal() {
logger.verbose(`init local package...`)
if (!isPackage(this.localMap[this.name])) {
throw new Error(`path ${this.localMap[this.name]} is not a package`)
}
}
/**
* standardize version
*
* if version is a dist tag, query the corresponding version.
* it is a preparation to load external modules and should be used when Mode.Default.
*/
private async standardizeVersion() {
const spinner = logger.createSpinner(`inspect package ${this.name} ...`)
try {
// 当传递的 version 是个 tag 时,获取对应的版本号替换 version
if (isDistTagVersion(this.versionOrDistTag)) {
const version = await queryPackageVersion(this.name, this.versionOrDistTag, this.registry)
if (!version) throw new Error(`${this.name}@${this.versionOrDistTag} not found at ${this.registry}`)
this.versionOrDistTag = version
}
} finally {
spinner.stop()
}
}
/**
* install or update package
*/
private async installOrUpdate() {
// here the unified use of `npm list`
const { stdout } = await execa(PackageManager.NPM, ['list', '--depth=0', '--json'], { cwd: this.baseDir })
const result = JSON.parse(stdout)
const installed =
result.dependencies?.[this.name] && result.dependencies[this.name].version === this.versionOrDistTag
if (installed) return
const spinner = logger.createSpinner(`install package ${this.name}@${this.versionOrDistTag} ...`)
try {
await installPackage({
name: this.name,
versionOrDistTag: this.versionOrDistTag,
baseDir: this.baseDir,
registry: this.registry,
packageManager: this.packageManager,
})
} finally {
spinner.stop()
}
}
private requireLoaded() {
if (!this.loaded) throw new Error(`please call and await the \`load\` is complete`)
}
}