| 1 | import * as fs from "node:fs"; |
| 2 | import * as path from "node:path"; |
| 3 | import { Registry } from "./interfaces/index.js"; |
| 4 | import { FullSlug, PackageIdentifier } from "./interfaces/slugs.js"; |
| 5 | |
| 6 | interface RegistryClientOptions { |
| 7 | accessToken?: string; |
| 8 | apiBase?: string; |
| 9 | rootPath?: string; |
| 10 | } |
| 11 | |
| 12 | export class RegistryClient implements Registry { |
| 13 | private readonly accessToken?: string; |
| 14 | private readonly apiBase: string; |
| 15 | private readonly rootPath?: string; |
| 16 | |
| 17 | constructor(options: RegistryClientOptions = {}) { |
| 18 | this.accessToken = options.accessToken; |
| 19 | this.apiBase = options.apiBase ?? "https://api.continue.dev/"; |
| 20 | this.rootPath = options.rootPath; |
| 21 | if (!this.apiBase.endsWith("/")) { |
| 22 | this.apiBase += "/"; |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | async getContent(id: PackageIdentifier): Promise<string> { |
| 27 | switch (id.uriType) { |
| 28 | case "file": |
| 29 | return this.getContentFromFilePath(id.fileUri); |
| 30 | case "slug": |
| 31 | return this.getContentFromSlug(id.fullSlug); |
| 32 | default: |
| 33 | throw new Error( |
| 34 | `Unknown package identifier type: ${(id as any).uriType}`, |
| 35 | ); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | private getContentFromFilePath(filepath: string): string { |
| 40 | if (filepath.startsWith("file://")) { |
| 41 | // For Windows file:///C:/path/to/file, we need to handle it properly |
| 42 | // On other systems, we might have file:///path/to/file |
| 43 | return fs.readFileSync(new URL(filepath), "utf8"); |
| 44 | } else if (path.isAbsolute(filepath)) { |
| 45 | return fs.readFileSync(filepath, "utf8"); |
| 46 | } else if (this.rootPath) { |
| 47 | return fs.readFileSync(path.join(this.rootPath, filepath), "utf8"); |
| 48 | } else { |
| 49 | throw new Error("No rootPath provided for relative file path"); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | private async getContentFromSlug(fullSlug: FullSlug): Promise<string> { |
| 54 | const response = await fetch( |
| 55 | `${this.apiBase}registry/v1/${fullSlug.ownerSlug}/${fullSlug.packageSlug}/${fullSlug.versionSlug}`, |
| 56 | { |
| 57 | headers: { |
| 58 | ...(this.accessToken |
| 59 | ? { Authorization: `Bearer ${this.accessToken}` } |
| 60 | : {}), |
| 61 | }, |
| 62 | }, |
| 63 | ); |
| 64 | const data = await response.json(); |
| 65 | return data.content; |
| 66 | } |
| 67 | } |