@hamur/blob 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +51 -2
  3. package/dist/src/client/index.js +158 -0
  4. package/dist/src/index.js +220 -0
  5. package/dist/src/server/index.js +498 -0
  6. package/dist/types/src/build/setup.d.ts +7 -0
  7. package/dist/types/src/client/index.d.ts +28 -0
  8. package/dist/types/src/drivers/cloudflare-r2.d.ts +75 -0
  9. package/dist/types/src/drivers/fs.d.ts +14 -0
  10. package/dist/types/src/drivers/s3.d.ts +12 -0
  11. package/dist/types/src/drivers/suite.d.ts +9 -0
  12. package/dist/types/src/index.d.ts +2 -0
  13. package/dist/types/src/module.d.ts +3 -0
  14. package/dist/types/src/options.d.ts +19 -0
  15. package/dist/types/src/runtime/choose.d.ts +3 -0
  16. package/dist/types/src/runtime/driver.d.ts +29 -0
  17. package/dist/types/src/runtime/mime.d.ts +6 -0
  18. package/dist/types/src/runtime/multipart.d.ts +34 -0
  19. package/dist/types/src/runtime/store.d.ts +10 -0
  20. package/dist/types/src/server/blob.d.ts +3 -0
  21. package/dist/types/src/server/ensure.d.ts +22 -0
  22. package/dist/types/src/server/index.d.ts +12 -0
  23. package/dist/types/src/types.d.ts +152 -0
  24. package/package.json +32 -4
  25. package/src/build/setup.ts +137 -0
  26. package/src/client/index.ts +206 -0
  27. package/src/drivers/cloudflare-r2.ts +232 -0
  28. package/src/drivers/fs.ts +398 -0
  29. package/src/drivers/s3.ts +311 -0
  30. package/src/drivers/suite.ts +314 -0
  31. package/src/env.d.ts +16 -0
  32. package/src/index.ts +10 -0
  33. package/src/module.ts +11 -0
  34. package/src/options.ts +102 -0
  35. package/src/runtime/choose.ts +18 -0
  36. package/src/runtime/driver.ts +82 -0
  37. package/src/runtime/mime.ts +18 -0
  38. package/src/runtime/multipart.ts +319 -0
  39. package/src/runtime/store.ts +190 -0
  40. package/src/server/blob.ts +26 -0
  41. package/src/server/ensure.ts +52 -0
  42. package/src/server/index.ts +20 -0
  43. package/src/types.ts +155 -0
@@ -0,0 +1,206 @@
1
+ import type { BlobObject } from "../types.ts"
2
+
3
+ export interface MultipartUploadClientOptions {
4
+ /** Bytes per part, 5 MiB to 5 GiB (S3's limits); the last part may be smaller. Default 10 MiB. */
5
+ partSize?: number
6
+ /** Parts in flight at once, default 1. */
7
+ concurrency?: number
8
+ }
9
+
10
+ export interface MultipartFileOptions {
11
+ /** The name sent at `create`, default the file's name; the handler maps it to the stored pathname. */
12
+ pathname?: string
13
+ /** Called after each part is stored: the bytes of the stored parts, and the file's size. */
14
+ onProgress?: (sent: number, total: number) => void
15
+ }
16
+
17
+ export interface MultipartUpload {
18
+ completed: Promise<BlobObject>
19
+ /**
20
+ * Before `complete` is sent: stops the parts in flight, removes the upload's stored parts, and `completed` rejects with an
21
+ * `AbortError`. Once `complete` is sent the upload is no longer stopped: it resolves when `completed` settles. It never rejects.
22
+ */
23
+ abort(): Promise<void>
24
+ }
25
+
26
+ const MiB = 1024 * 1024
27
+ const MIN_PART_SIZE = 5 * MiB
28
+ const MAX_PART_SIZE = 5 * 1024 * MiB
29
+ const MAX_PARTS = 10_000
30
+
31
+ interface Created {
32
+ pathname: string
33
+ uploadId: string
34
+ partSize: number
35
+ direct?: boolean
36
+ }
37
+
38
+ /** An answer that is not 2xx as an `Error` with its `status` and, from Hamur's error body, its `message`. */
39
+ async function failure(response: Response): Promise<Error> {
40
+ const text = await response.text().catch(() => "")
41
+ let message = `${response.status} ${response.statusText}`.trim()
42
+ try {
43
+ const body = JSON.parse(text) as { message?: unknown }
44
+ if (typeof body.message === "string" && body.message) message = body.message
45
+ } catch {}
46
+ return Object.assign(new Error(message), { status: response.status })
47
+ }
48
+
49
+ async function answer<T>(response: Response): Promise<T> {
50
+ if (!response.ok) throw await failure(response)
51
+ return (await response.json()) as T
52
+ }
53
+
54
+ const json = (method: string, body: unknown, signal?: AbortSignal): RequestInit => ({
55
+ method,
56
+ headers: { "content-type": "application/json" },
57
+ body: JSON.stringify(body),
58
+ ...(signal ? { signal } : {}),
59
+ })
60
+
61
+ /** A network failure or a 5xx may pass on a second try; a 4xx is the request's own fault. */
62
+ const retryable = (error: unknown) => {
63
+ const status = (error as { status?: unknown }).status
64
+ return typeof status !== "number" || status >= 500
65
+ }
66
+
67
+ /**
68
+ * Uploads a file in parts through the steps of `handleMultipartUpload` at `url` (`<url>/create`, `<url>/upload`,
69
+ * `<url>/complete`, `<url>/abort`); when the handler answers a part with a storage URL, the part goes there. A part that
70
+ * fails on the network or with a 5xx is sent once more, then the upload is aborted. Plain `fetch`, no UI library: the same in
71
+ * every adapter.
72
+ */
73
+ export function useMultipartUpload(
74
+ url: string,
75
+ options: MultipartUploadClientOptions = {},
76
+ ): (file: File, fileOptions?: MultipartFileOptions) => MultipartUpload {
77
+ const { partSize = 10 * MiB, concurrency = 1 } = options
78
+ if (!Number.isSafeInteger(partSize) || partSize < MIN_PART_SIZE || partSize > MAX_PART_SIZE) {
79
+ throw new RangeError(
80
+ `useMultipartUpload partSize must be a whole number of bytes from 5 MiB to 5 GiB (got ${partSize})`,
81
+ )
82
+ }
83
+ if (!Number.isSafeInteger(concurrency) || concurrency < 1)
84
+ throw new RangeError(`useMultipartUpload concurrency must be a whole number from 1 (got ${concurrency})`)
85
+ const base = url.replace(/\/+$/, "")
86
+ const stepUrl = (step: string, query?: Record<string, string>) =>
87
+ `${base}/${step}${query ? `?${new URLSearchParams(query)}` : ""}`
88
+
89
+ return (file, fileOptions = {}) => {
90
+ const controller = new AbortController()
91
+ const { signal } = controller
92
+ let created: Promise<Created> | undefined
93
+ let aborting: Promise<void> | undefined
94
+ let completing = false
95
+
96
+ const removeUpload = async () => {
97
+ const session = await created?.catch(() => undefined)
98
+ if (!session) return
99
+ const response = await fetch(stepUrl("abort", { pathname: session.pathname, uploadId: session.uploadId }), {
100
+ method: "DELETE",
101
+ })
102
+ await response.body?.cancel()
103
+ }
104
+
105
+ const sendPart = async (session: Created, partNumber: number, part: Blob): Promise<string> => {
106
+ const target = { pathname: session.pathname, uploadId: session.uploadId }
107
+ if (!session.direct) {
108
+ const sent = await fetch(stepUrl("upload", { ...target, partNumber: String(partNumber) }), {
109
+ method: "PUT",
110
+ body: part,
111
+ signal,
112
+ })
113
+ return (await answer<{ etag: string }>(sent)).etag
114
+ }
115
+ const { url: partUrl } = await answer<{ url: string }>(
116
+ await fetch(stepUrl("upload"), json("POST", { ...target, partNumber, size: part.size }, signal)),
117
+ )
118
+ const stored = await fetch(partUrl, { method: "PUT", body: part, signal })
119
+ if (!stored.ok) throw await failure(stored)
120
+ await stored.body?.cancel()
121
+ const etag = stored.headers.get("etag")
122
+ if (!etag)
123
+ throw new Error(
124
+ `Storage answered part ${partNumber} without a readable ETag; expose ETag in the bucket's CORS rules`,
125
+ )
126
+ return etag
127
+ }
128
+
129
+ const run = async (): Promise<BlobObject> => {
130
+ const parts = Math.max(1, Math.ceil(file.size / partSize))
131
+ if (parts > MAX_PARTS)
132
+ throw new RangeError(
133
+ `A file of ${file.size} bytes needs more than ${MAX_PARTS} parts of ${partSize} bytes; raise partSize`,
134
+ )
135
+ created = fetch(
136
+ stepUrl("create"),
137
+ json("POST", {
138
+ pathname: fileOptions.pathname ?? file.name,
139
+ ...(file.type ? { contentType: file.type } : {}),
140
+ size: file.size,
141
+ partSize,
142
+ }),
143
+ ).then((response) => answer<Created>(response))
144
+ const session = await created
145
+ signal.throwIfAborted()
146
+ const size = session.partSize
147
+ const count = Math.max(1, Math.ceil(file.size / size))
148
+ const etags: string[] = new Array(count)
149
+ let next = 0
150
+ let sent = 0
151
+ const worker = async () => {
152
+ while (next < count) {
153
+ const partNumber = ++next
154
+ const part = file.slice((partNumber - 1) * size, Math.min(file.size, partNumber * size))
155
+ etags[partNumber - 1] = await sendPart(session, partNumber, part).catch((error: unknown) => {
156
+ if (signal.aborted || !retryable(error)) throw error
157
+ return sendPart(session, partNumber, part)
158
+ })
159
+ sent += part.size
160
+ fileOptions.onProgress?.(sent, file.size)
161
+ }
162
+ }
163
+ try {
164
+ await Promise.all(Array.from({ length: Math.min(concurrency, count) }, worker))
165
+ } catch (error) {
166
+ controller.abort()
167
+ throw error
168
+ }
169
+ signal.throwIfAborted()
170
+ completing = true
171
+ const body = {
172
+ pathname: session.pathname,
173
+ uploadId: session.uploadId,
174
+ parts: etags.map((etag, at) => ({ partNumber: at + 1, etag })),
175
+ }
176
+ const object = await answer<BlobObject>(await fetch(stepUrl("complete"), json("POST", body)))
177
+ return { ...object, uploadedAt: new Date(object.uploadedAt) }
178
+ }
179
+
180
+ const completed = run().catch(async (error: unknown) => {
181
+ if (aborting) {
182
+ await aborting
183
+ throw new DOMException("The upload was aborted", "AbortError")
184
+ }
185
+ if (!completing) await (aborting = removeUpload().catch(() => undefined))
186
+ throw error
187
+ })
188
+
189
+ return {
190
+ completed,
191
+ abort() {
192
+ if (completing) {
193
+ return completed.then(
194
+ () => undefined,
195
+ () => undefined,
196
+ )
197
+ }
198
+ if (!aborting) {
199
+ aborting = removeUpload().catch(() => undefined)
200
+ controller.abort()
201
+ }
202
+ return aborting
203
+ },
204
+ }
205
+ }
206
+ }
@@ -0,0 +1,232 @@
1
+ import { outsideWorker } from "hamur/server"
2
+ import { firstPart, invalidUpload, presignUnavailable, uploadNotFound, type OpenDriver } from "../runtime/driver.ts"
3
+ import type { BlobDriver, BlobObject, BlobWrite, ResolvedBlobDriver } from "../types.ts"
4
+
5
+ /** The part of an R2 object the driver reads. */
6
+ export interface R2Object {
7
+ key: string
8
+ size: number
9
+ httpEtag: string
10
+ uploaded: Date
11
+ httpMetadata?: { contentType?: string }
12
+ customMetadata?: Record<string, string>
13
+ }
14
+
15
+ interface R2ObjectBody extends R2Object {
16
+ body: ReadableStream<Uint8Array>
17
+ arrayBuffer(): Promise<ArrayBuffer>
18
+ }
19
+
20
+ interface R2PutOptions {
21
+ httpMetadata?: { contentType?: string }
22
+ customMetadata?: Record<string, string>
23
+ }
24
+
25
+ interface R2MultipartUpload {
26
+ readonly uploadId: string
27
+ uploadPart(partNumber: number, value: Uint8Array): Promise<{ partNumber: number; etag: string }>
28
+ complete(parts: { partNumber: number; etag: string }[]): Promise<R2Object>
29
+ abort(): Promise<void>
30
+ }
31
+
32
+ /** The part of an R2 bucket binding the driver uses. */
33
+ export interface R2Bucket {
34
+ head(key: string): Promise<R2Object | null>
35
+ /** With `onlyIf` not met, the object without a `body`. */
36
+ get(
37
+ key: string,
38
+ options?: { onlyIf?: { etagMatches: string }; range?: { offset: number; length: number } },
39
+ ): Promise<R2ObjectBody | R2Object | null>
40
+ put(key: string, value: Uint8Array | Blob, options?: R2PutOptions): Promise<R2Object | null>
41
+ createMultipartUpload(key: string, options?: R2PutOptions): Promise<R2MultipartUpload>
42
+ resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload
43
+ delete(keys: string | string[]): Promise<void>
44
+ list(options?: {
45
+ prefix?: string
46
+ cursor?: string
47
+ limit?: number
48
+ delimiter?: string
49
+ }): Promise<{ objects: R2Object[]; truncated: boolean; cursor?: string; delimitedPrefixes?: string[] }>
50
+ }
51
+
52
+ type R2Config = Extract<ResolvedBlobDriver, { driver: "cloudflare-r2" }>
53
+
54
+ /** R2's error for an upload it does not hold (code 10024). */
55
+ const isMissingUpload = (error: unknown) => /\(10024\)|does not exist/i.test(String((error as Error)?.message))
56
+ /** R2's errors for a part list it refuses: an unknown part or ETag, a part too small, parts out of order. */
57
+ const isRefusedParts = (error: unknown) => /\bpart|etag/i.test(String((error as Error)?.message))
58
+
59
+ /** R2 deletes at most 1000 keys in one call. */
60
+ const DELETE_BATCH = 1000
61
+
62
+ /** `env` of `cloudflare:workers`, imported at first use through a specifier the bundler leaves alone; on Bun (`hamur task run --prod`) the error names the binding and, in a task, `tasks.http`. */
63
+ async function workersEnv(binding: string): Promise<Record<string, unknown>> {
64
+ const specifier = "cloudflare:workers"
65
+ try {
66
+ return ((await import(specifier)) as { env: Record<string, unknown> }).env
67
+ } catch {
68
+ return outsideWorker(`blob uses the cloudflare-r2 binding ${JSON.stringify(binding)}`)
69
+ }
70
+ }
71
+
72
+ /**
73
+ * One object per pathname at `<base><pathname>` in the bucket `env[binding]`, its type in `httpMetadata` and its
74
+ * metadata in `customMetadata`. A stream that does not end within 10 MiB is written as a multipart upload in 10 MiB parts
75
+ * (`put` needs a known length).
76
+ */
77
+ export function createR2Driver(
78
+ config: R2Config,
79
+ env: () => Promise<Record<string, unknown>> = () => workersEnv(config.binding),
80
+ ): BlobDriver {
81
+ const { base, binding } = config
82
+ let resolved: Promise<R2Bucket> | undefined
83
+ const bucket = () =>
84
+ (resolved ??= env()
85
+ .then((values) => {
86
+ const found = values[binding] as R2Bucket | undefined
87
+ if (!found || typeof found.get !== "function" || typeof found.createMultipartUpload !== "function") {
88
+ throw new Error(
89
+ `The cloudflare-r2 blob driver found no R2 binding "${binding}" in env (blob.binding; declare it in r2_buckets of the wrangler config)`,
90
+ )
91
+ }
92
+ return found
93
+ })
94
+ .catch((error: unknown) => {
95
+ // A failed lookup is not kept, so the error of a later use names the task that met it.
96
+ resolved = undefined
97
+ throw error
98
+ }))
99
+
100
+ const objectOf = (object: R2Object): BlobObject => ({
101
+ pathname: object.key.slice(base.length),
102
+ contentType: object.httpMetadata?.contentType ?? "application/octet-stream",
103
+ size: object.size,
104
+ etag: object.httpEtag,
105
+ uploadedAt: new Date(object.uploaded),
106
+ customMetadata: { ...object.customMetadata },
107
+ })
108
+
109
+ const options = (write: BlobWrite): R2PutOptions => ({
110
+ httpMetadata: { contentType: write.contentType },
111
+ customMetadata: write.customMetadata,
112
+ })
113
+
114
+ async function putParts(
115
+ key: string,
116
+ first: Uint8Array,
117
+ rest: AsyncGenerator<Uint8Array>,
118
+ write: BlobWrite,
119
+ ): Promise<R2Object> {
120
+ const upload = await (await bucket()).createMultipartUpload(key, options(write))
121
+ const uploaded: { partNumber: number; etag: string }[] = []
122
+ try {
123
+ let part: Uint8Array | undefined = first
124
+ while (part) {
125
+ uploaded.push(await upload.uploadPart(uploaded.length + 1, part))
126
+ const next = await rest.next()
127
+ part = next.done ? undefined : next.value
128
+ }
129
+ return await upload.complete(uploaded)
130
+ } catch (error) {
131
+ await upload.abort().catch(() => {})
132
+ throw error
133
+ }
134
+ }
135
+
136
+ const resumed = async (pathname: string, uploadId: string) =>
137
+ (await bucket()).resumeMultipartUpload(`${base}${pathname}`, uploadId)
138
+ const notFound = (error: unknown): never => {
139
+ throw isMissingUpload(error) ? uploadNotFound() : error
140
+ }
141
+
142
+ return {
143
+ name: "cloudflare-r2",
144
+ async put(pathname, body, write) {
145
+ const key = `${base}${pathname}`
146
+ let stored: R2Object | null
147
+ if (body instanceof ReadableStream) {
148
+ const { first, rest } = await firstPart(body)
149
+ stored = rest ? await putParts(key, first, rest, write) : await (await bucket()).put(key, first, options(write))
150
+ } else {
151
+ stored = await (await bucket()).put(key, body, options(write))
152
+ }
153
+ if (!stored) throw new Error(`R2 put of "${key}" stored nothing`)
154
+ return objectOf(stored)
155
+ },
156
+ async get(pathname) {
157
+ const object = await (await bucket()).get(`${base}${pathname}`)
158
+ if (!object || !("arrayBuffer" in object)) return undefined
159
+ return new Blob([await object.arrayBuffer()], {
160
+ type: object.httpMetadata?.contentType ?? "application/octet-stream",
161
+ })
162
+ },
163
+ async head(pathname) {
164
+ const object = await (await bucket()).head(`${base}${pathname}`)
165
+ return object ? objectOf(object) : undefined
166
+ },
167
+ async list({ prefix, limit, cursor, folded }) {
168
+ const page = await (
169
+ await bucket()
170
+ ).list({
171
+ prefix: `${base}${prefix}`,
172
+ limit,
173
+ ...(cursor ? { cursor } : {}),
174
+ ...(folded ? { delimiter: "/" } : {}),
175
+ })
176
+ const next = page.truncated ? page.cursor : undefined
177
+ return {
178
+ blobs: page.objects.map((object) => ({
179
+ pathname: object.key.slice(base.length),
180
+ size: object.size,
181
+ etag: object.httpEtag,
182
+ uploadedAt: new Date(object.uploaded),
183
+ })),
184
+ hasMore: next !== undefined,
185
+ ...(next ? { cursor: next } : {}),
186
+ ...(folded ? { folders: (page.delimitedPrefixes ?? []).map((name) => name.slice(base.length)) } : {}),
187
+ }
188
+ },
189
+ async delete(paths) {
190
+ const keys = paths.map((pathname) => `${base}${pathname}`)
191
+ for (let at = 0; at < keys.length; at += DELETE_BATCH)
192
+ await (await bucket()).delete(keys.slice(at, at + DELETE_BATCH))
193
+ },
194
+ async open(pathname, etag, range) {
195
+ const object = await (
196
+ await bucket()
197
+ ).get(`${base}${pathname}`, {
198
+ onlyIf: { etagMatches: etag.replace(/^"|"$/g, "") },
199
+ ...(range ? { range: { offset: range.start, length: range.end - range.start + 1 } } : {}),
200
+ })
201
+ if (!object) return undefined
202
+ return "body" in object ? object.body : "changed"
203
+ },
204
+ async presign() {
205
+ throw presignUnavailable("cloudflare-r2")
206
+ },
207
+ multipart: {
208
+ async create(pathname, write) {
209
+ return (await (await bucket()).createMultipartUpload(`${base}${pathname}`, options(write))).uploadId
210
+ },
211
+ async uploadPart(pathname, uploadId, partNumber, body) {
212
+ return (await (await resumed(pathname, uploadId)).uploadPart(partNumber, body).catch(notFound)).etag
213
+ },
214
+ async complete(pathname, uploadId, parts) {
215
+ const stored = await (await resumed(pathname, uploadId)).complete(parts).catch((error: unknown) => {
216
+ if (isMissingUpload(error)) throw uploadNotFound()
217
+ throw isRefusedParts(error) ? invalidUpload(error) : error
218
+ })
219
+ return objectOf(stored)
220
+ },
221
+ async abort(pathname, uploadId) {
222
+ await (await resumed(pathname, uploadId)).abort().catch((error: unknown) => {
223
+ if (!isMissingUpload(error)) throw error
224
+ })
225
+ },
226
+ },
227
+ }
228
+ }
229
+
230
+ export const openR2Driver: OpenDriver<R2Config> = (config) => createR2Driver(config)
231
+
232
+ export default openR2Driver