(rootPath: string)
| 118 | } |
| 119 | |
| 120 | async function startDatasetServer(rootPath: string): Promise<DatasetServer> { |
| 121 | const root = resolve(rootPath); |
| 122 | const rootPrefix = root.endsWith(sep) ? root : `${root}${sep}`; |
| 123 | const rootStat = await stat(root); |
| 124 | if (!rootStat.isDirectory()) { |
| 125 | throw new Error(`Bicycle dataset path is not a directory: ${root}`); |
| 126 | } |
| 127 | |
| 128 | const server = createServer(async (request, response) => { |
| 129 | response.setHeader('access-control-allow-origin', '*'); |
| 130 | response.setHeader('access-control-allow-methods', 'GET,HEAD,OPTIONS'); |
| 131 | |
| 132 | if (request.method === 'OPTIONS') { |
| 133 | response.writeHead(204); |
| 134 | response.end(); |
| 135 | return; |
| 136 | } |
| 137 | |
| 138 | if (request.method !== 'GET' && request.method !== 'HEAD') { |
| 139 | sendStatus(response, 405, 'Method not allowed'); |
| 140 | return; |
| 141 | } |
| 142 | |
| 143 | try { |
| 144 | const url = new URL(request.url ?? '/', 'http://127.0.0.1'); |
| 145 | const relativePath = decodeURIComponent(url.pathname) |
| 146 | .replace(/^\/+/, '') |
| 147 | .replace(/\//g, sep); |
| 148 | if (!relativePath || relativePath.includes('\0')) { |
| 149 | sendStatus(response, 404, 'Not found'); |
| 150 | return; |
| 151 | } |
| 152 | |
| 153 | const filePath = resolve(root, relativePath); |
| 154 | if (filePath !== root && !filePath.startsWith(rootPrefix)) { |
| 155 | sendStatus(response, 403, 'Forbidden'); |
| 156 | return; |
| 157 | } |
| 158 | |
| 159 | const fileStat = await stat(filePath); |
| 160 | if (!fileStat.isFile()) { |
| 161 | sendStatus(response, 404, 'Not found'); |
| 162 | return; |
| 163 | } |
| 164 | |
| 165 | response.writeHead(200, { |
| 166 | 'access-control-allow-origin': '*', |
| 167 | 'accept-ranges': 'bytes', |
| 168 | 'content-length': String(fileStat.size), |
| 169 | 'content-type': getContentType(filePath), |
| 170 | }); |
| 171 | if (request.method === 'HEAD') { |
| 172 | response.end(); |
| 173 | return; |
| 174 | } |
| 175 | |
| 176 | const stream = createReadStream(filePath); |
| 177 | stream.on('error', () => { |
no test coverage detected