| 15 | } |
| 16 | |
| 17 | export class MockCdn { |
| 18 | private app: FastifyInstance; |
| 19 | private packages: Array<MockCdnPackage>; |
| 20 | private _url?: string; |
| 21 | |
| 22 | constructor(options: MockCdnOptions) { |
| 23 | this.packages = options.packages; |
| 24 | |
| 25 | this.app = setupApp(); |
| 26 | this.app.log.level = 'error'; |
| 27 | |
| 28 | this.app.get('/', (req, res) => { |
| 29 | res.send(`This is a mock CDN for testing purposes.`); |
| 30 | }); |
| 31 | this.app.get('/v2/deps/:query', this.dependencyQueryMiddleware.bind(this)); |
| 32 | this.app.get('/v2/mod/:query', this.moduleQueryMiddleware.bind(this)); |
| 33 | } |
| 34 | |
| 35 | private respondWith(res: FastifyReply, data: unknown) { |
| 36 | res.type('application/octet-stream'); |
| 37 | res.send(Buffer.from(encode(data))); |
| 38 | } |
| 39 | |
| 40 | private dependencyQueryMiddleware(req: FastifyRequest, res: FastifyReply): void { |
| 41 | res.header('access-control-allow-origin', '*'); |
| 42 | |
| 43 | const responseJson: Record<string, string> = {}; |
| 44 | |
| 45 | for (const pkg of this.packages) { |
| 46 | const pkgMajorVersion = pkg.version.split('.')[0]; |
| 47 | responseJson[`${pkg.name}@${pkgMajorVersion}`] = pkg.version; |
| 48 | } |
| 49 | |
| 50 | this.respondWith(res, responseJson); |
| 51 | } |
| 52 | |
| 53 | private moduleQueryMiddleware(req: FastifyRequest<{ Params: { query: string } }>, res: FastifyReply): void { |
| 54 | res.header('access-control-allow-origin', '*'); |
| 55 | const parsedQuery = atob(req.params.query); |
| 56 | |
| 57 | for (const pkg of this.packages) { |
| 58 | const pkgPragma = this.getPackagePragma(pkg.name, pkg.version); |
| 59 | |
| 60 | if (parsedQuery === pkgPragma) { |
| 61 | this.respondWith(res, pkg.files); |
| 62 | return; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | // Otherwise, respond with a 404. |
| 67 | res.status(401).send(`Unknown dependency "${parsedQuery}"`); |
| 68 | } |
| 69 | |
| 70 | private getPackagePragma(pkgName: string, packageVersion: string): string { |
| 71 | return `${pkgName}@${packageVersion}`; |
| 72 | } |
| 73 | |
| 74 | get url(): string { |
nothing calls this directly
no outgoing calls
no test coverage detected