-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathPackageVersionFileController.ts
More file actions
346 lines (325 loc) · 9.96 KB
/
PackageVersionFileController.ts
File metadata and controls
346 lines (325 loc) · 9.96 KB
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import { join } from 'node:path';
import {
type EggContext,
Context,
HTTPController,
HTTPMethod,
HTTPMethodEnum,
HTTPParam,
HTTPQuery,
Inject,
Middleware,
} from '@eggjs/tegg';
import { NotFoundError } from 'egg-errors';
import { AbstractController } from './AbstractController.js';
import { AdminAccess } from '../middleware/AdminAccess.js';
import {
FULLNAME_REG_STRING,
getScopeAndName,
} from '../../common/PackageUtil.js';
import type { PackageVersionFileService } from '../../core/service/PackageVersionFileService.js';
import type { PackageManagerService } from '../../core/service/PackageManagerService.js';
import type { PackageVersionFile } from '../../core/entity/PackageVersionFile.js';
import type { PackageVersion } from '../../core/entity/PackageVersion.js';
import type { DistRepository } from '../../repository/DistRepository.js';
import { Spec } from '../typebox.js';
import { ensureContentType } from '../../common/FileUtil.js';
interface FileItem {
path: string;
type: 'file';
contentType: string;
integrity: string;
lastModified: Date;
size: number;
}
interface DirectoryItem {
path: string;
type: 'directory';
files: (DirectoryItem | FileItem)[];
}
function formatFileItem(file: PackageVersionFile): FileItem {
return {
path: file.path,
type: 'file',
contentType: file.contentType,
integrity: file.dist.integrity,
lastModified: file.mtime,
size: file.dist.size,
};
}
const META_CACHE_CONTROL = 'public, s-maxage=600, max-age=60';
const FILE_CACHE_CONTROL = 'public, max-age=31536000';
@HTTPController()
export class PackageVersionFileController extends AbstractController {
@Inject()
private packageManagerService: PackageManagerService;
@Inject()
private packageVersionFileService: PackageVersionFileService;
@Inject()
private distRepository: DistRepository;
#requireUnpkgEnable() {
if (!this.config.cnpmcore.enableUnpkg) {
throw new NotFoundError();
}
}
@HTTPMethod({
// PUT /:fullname/:versionSpec/files
path: `/:fullname(${FULLNAME_REG_STRING})/:versionSpec/files`,
method: HTTPMethodEnum.PUT,
})
@Middleware(AdminAccess)
async sync(
@Context() ctx: EggContext,
@HTTPParam() fullname: string,
@HTTPParam() versionSpec: string
) {
ctx.tValidate(Spec, `${fullname}@${versionSpec}`);
this.#requireUnpkgEnable();
const [scope, name] = getScopeAndName(fullname);
const { packageVersion } =
await this.packageManagerService.showPackageVersionByVersionOrTag(
scope,
name,
versionSpec
);
if (!packageVersion) {
throw new NotFoundError(`${fullname}@${versionSpec} not found`);
}
const files =
await this.packageVersionFileService.syncPackageVersionFiles(
packageVersion
);
return files.map(file => formatFileItem(file));
}
@HTTPMethod({
// DELETE /:fullname/:versionSpec/files
path: `/:fullname(${FULLNAME_REG_STRING})/:versionSpec/files`,
method: HTTPMethodEnum.DELETE,
})
@Middleware(AdminAccess)
async removeFiles(
@Context() ctx: EggContext,
@HTTPParam() fullname: string,
@HTTPParam() versionSpec: string
) {
ctx.tValidate(Spec, `${fullname}@${versionSpec}`);
this.#requireUnpkgEnable();
const [scope, name] = getScopeAndName(fullname);
const { packageVersion } =
await this.packageManagerService.showPackageVersionByVersionOrTag(
scope,
name,
versionSpec
);
if (!packageVersion) {
throw new NotFoundError(`${fullname}@${versionSpec} not found`);
}
const files =
await this.packageVersionFileService.removePackageVersionFiles(
packageVersion
);
return files.map(file => formatFileItem(file));
}
@HTTPMethod({
// GET /:fullname/:versionSpec/files => /:fullname/:versionSpec/files/${pkg.main}
// GET /:fullname/:versionSpec/files?meta
// GET /:fullname/:versionSpec/files/
path: `/:fullname(${FULLNAME_REG_STRING})/:versionSpec/files`,
method: HTTPMethodEnum.GET,
})
async listFiles(
@Context() ctx: EggContext,
@HTTPParam() fullname: string,
@HTTPParam() versionSpec: string,
@HTTPQuery() meta: string
) {
this.#requireUnpkgEnable();
ctx.tValidate(Spec, `${fullname}@${versionSpec}`);
ctx.vary(this.config.cnpmcore.cdnVaryHeader);
const [scope, name] = getScopeAndName(fullname);
const packageVersion = await this.#getPackageVersion(
ctx,
fullname,
scope,
name,
versionSpec
);
ctx.set('cache-control', META_CACHE_CONTROL);
const hasMeta = typeof meta === 'string' || ctx.path.endsWith('/files/');
// meta request
if (hasMeta) {
const files = await this.#listFilesByDirectory(packageVersion, '/');
if (!files) {
throw new NotFoundError(`${fullname}@${versionSpec}/files not found`);
}
return files;
}
const { manifest } =
await this.packageManagerService.showPackageVersionManifest(
scope,
name,
versionSpec,
false,
true
);
// GET /foo/1.0.0/files => /foo/1.0.0/files/{main}
// ignore empty entry exp: @types/node@20.2.5/
const indexFile = manifest?.main || 'index.js';
ctx.redirect(join(ctx.path, indexFile));
}
@HTTPMethod({
// GET /:fullname/:versionSpec/files/:path
// GET /:fullname/:versionSpec/files/:path?meta
path: `/:fullname(${FULLNAME_REG_STRING})/:versionSpec/files/:path(.+)`,
method: HTTPMethodEnum.GET,
})
async raw(
@Context() ctx: EggContext,
@HTTPParam() fullname: string,
@HTTPParam() versionSpec: string,
@HTTPParam() path: string,
@HTTPQuery() meta: string
) {
this.#requireUnpkgEnable();
ctx.tValidate(Spec, `${fullname}@${versionSpec}`);
ctx.vary(this.config.cnpmcore.cdnVaryHeader);
const [scope, name] = getScopeAndName(fullname);
path = `/${path}`;
const packageVersion = await this.#getPackageVersion(
ctx,
fullname,
scope,
name,
versionSpec
);
if (path.endsWith('/')) {
const directory = path.slice(0, -1);
const files = await this.#listFilesByDirectory(packageVersion, directory);
if (!files) {
throw new NotFoundError(
`${fullname}@${versionSpec}/files${directory} not found`
);
}
ctx.set('cache-control', META_CACHE_CONTROL);
return files;
}
await this.packageVersionFileService.checkPackageVersionInUnpkgWhiteList(
scope,
name,
packageVersion.version
);
const file = await this.packageVersionFileService.showPackageVersionFile(
packageVersion,
path
);
const hasMeta = typeof meta === 'string';
if (!file) {
const possibleFile = await this.#searchPossibleEntries(
packageVersion,
path
);
if (possibleFile) {
const route = `/${fullname}/${versionSpec}/files${possibleFile.path}${hasMeta ? '?meta' : ''}`;
ctx.redirect(route);
return;
}
throw new NotFoundError(
`File ${fullname}@${versionSpec}${path} not found`
);
}
if (hasMeta) {
ctx.set('cache-control', META_CACHE_CONTROL);
return formatFileItem(file);
}
ctx.set('cache-control', FILE_CACHE_CONTROL);
// https://github.com/cnpm/cnpmcore/issues/693#issuecomment-2955268229
ctx.type = ensureContentType(file.contentType);
return await this.distRepository.getDistStream(file.dist);
}
/**
* compatibility with unpkg
* 1. try to match alias entry. e.g. accessing `index.js` or `index.json` using /index
* 2. if given path is directory and has `index.js` file, redirect to it. e.g. using `lib` alias to access `lib/index.js` or `lib/index.json`
* @param {PackageVersion} packageVersion packageVersion
* @param {String} path filepath
* @returns {Promise<PackageVersionFile | undefined>} return packageVersionFile or null
*/
async #searchPossibleEntries(packageVersion: PackageVersion, path: string) {
const possiblePath = [
`${path}.js`,
`${path}.json`,
`${path}/index.js`,
`${path}/index.json`,
];
for (const pathItem of possiblePath) {
const file = await this.packageVersionFileService.showPackageVersionFile(
packageVersion,
pathItem
);
if (file) {
return file;
}
}
}
async #getPackageVersion(
ctx: EggContext,
fullname: string,
scope: string,
name: string,
versionSpec: string
) {
const { blockReason, packageVersion } =
await this.packageManagerService.showPackageVersionByVersionOrTag(
scope,
name,
versionSpec
);
if (blockReason) {
this.setCDNHeaders(ctx);
throw this.createPackageBlockError(blockReason, fullname, versionSpec);
}
if (!packageVersion) {
throw new NotFoundError(`${fullname}@${versionSpec} not found`);
}
if (packageVersion.version !== versionSpec) {
ctx.set('cache-control', META_CACHE_CONTROL);
let location = ctx.url.replace(
`/${fullname}/${versionSpec}/files`,
`/${fullname}/${packageVersion.version}/files`
);
location = location.replace(
`/${fullname}/${encodeURIComponent(versionSpec)}/files`,
`/${fullname}/${packageVersion.version}/files`
);
throw this.createControllerRedirectError(location);
}
return packageVersion;
}
async #listFilesByDirectory(
packageVersion: PackageVersion,
directory: string
) {
const { files, directories } =
await this.packageVersionFileService.listPackageVersionFiles(
packageVersion,
directory
);
if (files.length === 0 && directories.length === 0) return null;
const info: DirectoryItem = {
path: directory,
type: 'directory',
files: [],
};
for (const file of files) {
info.files.push(formatFileItem(file));
}
for (const name of directories) {
info.files.push({
path: name,
type: 'directory',
files: [],
} as DirectoryItem);
}
return info;
}
}