| 10 | } |
| 11 | |
| 12 | function createAdapter(client: AwsClient, endpoint: string, bucket: string): Adapter { |
| 13 | const base = `${endpoint}/${bucket}` |
| 14 | return { |
| 15 | async read(path: string): Promise<string | undefined> { |
| 16 | const response = await client.fetch(`${base}/${path}`) |
| 17 | if (response.status === 404) return undefined |
| 18 | if (!response.ok) throw new Error(`Failed to read ${path}: ${response.status}`) |
| 19 | return response.text() |
| 20 | }, |
| 21 | |
| 22 | async write(path: string, value: string): Promise<void> { |
| 23 | const response = await client.fetch(`${base}/${path}`, { |
| 24 | method: "PUT", |
| 25 | body: value, |
| 26 | headers: { |
| 27 | "Content-Type": "application/json", |
| 28 | }, |
| 29 | }) |
| 30 | if (!response.ok) throw new Error(`Failed to write ${path}: ${response.status}`) |
| 31 | }, |
| 32 | |
| 33 | async remove(path: string): Promise<void> { |
| 34 | const response = await client.fetch(`${base}/${path}`, { |
| 35 | method: "DELETE", |
| 36 | }) |
| 37 | if (!response.ok) throw new Error(`Failed to remove ${path}: ${response.status}`) |
| 38 | }, |
| 39 | |
| 40 | async list(options?: { prefix?: string; limit?: number; after?: string; before?: string }): Promise<string[]> { |
| 41 | const prefix = options?.prefix || "" |
| 42 | const params = new URLSearchParams({ "list-type": "2", prefix }) |
| 43 | if (options?.limit) params.set("max-keys", options.limit.toString()) |
| 44 | if (options?.after) { |
| 45 | const afterPath = prefix + options.after + ".json" |
| 46 | params.set("start-after", afterPath) |
| 47 | } |
| 48 | const response = await client.fetch(`${base}?${params}`) |
| 49 | if (!response.ok) throw new Error(`Failed to list ${prefix}: ${response.status}`) |
| 50 | const xml = await response.text() |
| 51 | const keys: string[] = [] |
| 52 | const regex = /<Key>([^<]+)<\/Key>/g |
| 53 | let match |
| 54 | while ((match = regex.exec(xml)) !== null) { |
| 55 | keys.push(match[1]) |
| 56 | } |
| 57 | if (options?.before) { |
| 58 | const beforePath = prefix + options.before + ".json" |
| 59 | return keys.filter((key) => key < beforePath) |
| 60 | } |
| 61 | return keys |
| 62 | }, |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | function s3(): Adapter { |
| 67 | const bucket = process.env.OPENCODE_STORAGE_BUCKET! |