( cg: CodeGraph, projectRoot: string, query: URLSearchParams )
| 340 | } |
| 341 | |
| 342 | export async function buildSource( |
| 343 | cg: CodeGraph, |
| 344 | projectRoot: string, |
| 345 | query: URLSearchParams |
| 346 | ): Promise<SourceResult> { |
| 347 | const requested = textParam(query, 'file'); |
| 348 | // Refusal first, index lookup second — see `resolveRequestedFile`. |
| 349 | const { record, storedPath, absolute } = resolveRequestedFile(cg, projectRoot, requested); |
| 350 | |
| 351 | const from = intParam(query, 'from', { min: 1, max: 5_000_000, default: 1 }); |
| 352 | const to = intParam(query, 'to', { min: 1, max: 5_000_000, default: 0 }); |
| 353 | if (to !== 0 && to < from) { |
| 354 | throw badRequest(`Parameter "to" (${to}) must not be before "from" (${from}).`); |
| 355 | } |
| 356 | const onDrift = parseOnDrift(query); |
| 357 | |
| 358 | const base: SourceResult = { |
| 359 | file: storedPath.replace(/\\/g, '/'), |
| 360 | language: record.language, |
| 361 | drift: false, |
| 362 | showing: 'indexed', |
| 363 | contentHash: record.contentHash, |
| 364 | indexedAt: record.indexedAt, |
| 365 | generated: record.generated === true, |
| 366 | totalLines: null, |
| 367 | }; |
| 368 | |
| 369 | let stats: fs.Stats; |
| 370 | try { |
| 371 | stats = fs.statSync(absolute); |
| 372 | } catch { |
| 373 | // Indexed but gone. That IS drift, and the strongest kind: nothing on disk |
| 374 | // corresponds to the ranges the graph holds — and `ondrift=current` has |
| 375 | // nothing to fall back to either. |
| 376 | return { |
| 377 | ...base, |
| 378 | drift: true, |
| 379 | showing: 'none', |
| 380 | reason: 'The file is in the index but no longer on disk.', |
| 381 | }; |
| 382 | } |
| 383 | if (stats.size > MAX_SOURCE_BYTES) { |
| 384 | throw badRequest( |
| 385 | `${base.file} is ${Math.round(stats.size / 1024 / 1024)} MB — too large to serve as source.` |
| 386 | ); |
| 387 | } |
| 388 | |
| 389 | let content: string; |
| 390 | try { |
| 391 | content = fs.readFileSync(absolute, 'utf-8'); |
| 392 | } catch (err) { |
| 393 | throw new ApiError( |
| 394 | 'internal', |
| 395 | `Could not read ${base.file}: ${err instanceof Error ? err.message : String(err)}` |
| 396 | ); |
| 397 | } |
| 398 | |
| 399 | // Byte-identical to extraction's `hashContent` (sha256 over the utf-8 |
no test coverage detected