@hamur/blob 0.0.0-stage → 0.0.2

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 +41 -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,311 @@
1
+ import { presignS3, signS3Request, type S3Credentials } from "hamur/server"
2
+ import { firstPart, invalidUpload, uploadNotFound, type OpenDriver } from "../runtime/driver.ts"
3
+ import type { BlobDriver, BlobListItem, BlobObject, BlobUploadedPart, BlobWrite, ResolvedBlobDriver } from "../types.ts"
4
+
5
+ type S3Config = Extract<ResolvedBlobDriver, { driver: "s3" }>
6
+
7
+ const META_PREFIX = "x-amz-meta-"
8
+ const CONCURRENCY = 16
9
+ const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" }
10
+
11
+ const xmlText = (text: string) =>
12
+ text.replace(/&(#x[0-9a-f]+|#[0-9]+|amp|lt|gt|quot|apos);/gi, (_, name: string) =>
13
+ name[0] === "#"
14
+ ? String.fromCodePoint(
15
+ name[1] === "x" || name[1] === "X" ? Number.parseInt(name.slice(2), 16) : Number(name.slice(1)),
16
+ )
17
+ : ENTITIES[name.toLowerCase()]!,
18
+ )
19
+ const xmlTag = (xml: string, name: string) => {
20
+ const found = new RegExp(`<${name}>([\\s\\S]*?)</${name}>`).exec(xml)?.[1]
21
+ return found === undefined ? undefined : xmlText(found)
22
+ }
23
+ const xmlTags = (xml: string, name: string) =>
24
+ [...xml.matchAll(new RegExp(`<${name}>([\\s\\S]*?)</${name}>`, "g"))].map((match) => match[1]!)
25
+ const xmlEscape = (text: string) =>
26
+ text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")
27
+ const urlDecoded = (text: string) => decodeURIComponent(text.replace(/\+/g, " "))
28
+
29
+ const OPTION_ENV = {
30
+ bucket: "BUCKET",
31
+ region: "REGION",
32
+ endpoint: "ENDPOINT",
33
+ accessKeyId: "ACCESS_KEY_ID",
34
+ secretAccessKey: "SECRET_ACCESS_KEY",
35
+ sessionToken: "SESSION_TOKEN",
36
+ } as const
37
+
38
+ /**
39
+ * One object per pathname at `<base><pathname>`, no envelope; the type, ETag, upload time and `x-amz-meta-*` are the
40
+ * object's own. Every request is signed by `signS3Request` over `fetch`, on every preset. A stream that does not end within
41
+ * 10 MiB is written as a multipart upload in 10 MiB parts. Options not given come from `S3_*`/`AWS_*` in the environment.
42
+ */
43
+ export const openS3Driver: OpenDriver<S3Config> = (config, secret) => {
44
+ const { base } = config
45
+ let resolved: S3Credentials | undefined
46
+ const credentials = () => {
47
+ if (resolved) return resolved
48
+ const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {}
49
+ const values: Record<string, string | undefined> = {}
50
+ for (const [option, name] of Object.entries(OPTION_ENV) as [keyof typeof OPTION_ENV, string][])
51
+ values[option] = secret(option, config[option]) ?? env[`S3_${name}`] ?? env[`AWS_${name}`]
52
+ for (const option of ["bucket", "accessKeyId", "secretAccessKey"] as const) {
53
+ if (!values[option])
54
+ throw new TypeError(
55
+ `The s3 blob driver needs blob.${option} (or S3_${OPTION_ENV[option]} / AWS_${OPTION_ENV[option]} in the environment)`,
56
+ )
57
+ }
58
+ return (resolved = {
59
+ ...(values as unknown as S3Credentials),
60
+ ...(config.virtualHostedStyle === undefined ? {} : { virtualHostedStyle: config.virtualHostedStyle }),
61
+ })
62
+ }
63
+
64
+ async function send(
65
+ method: string,
66
+ key: string,
67
+ init: { query?: Record<string, string>; headers?: HeadersInit; body?: BodyInit | null } = {},
68
+ ): Promise<Response> {
69
+ return fetch(await signS3Request(credentials(), { method, key, ...init }))
70
+ }
71
+
72
+ async function failure(method: string, key: string, response: Response): Promise<Error> {
73
+ const body = method === "HEAD" ? "" : await response.text()
74
+ const code = xmlTag(body, "Code")
75
+ const message = xmlTag(body, "Message")
76
+ const error = new Error(
77
+ `S3 ${method} s3://${credentials().bucket}/${key} failed: ${response.status} ${code ?? response.statusText}${message ? `: ${message}` : ""}`,
78
+ )
79
+ return Object.assign(error, { code: code ?? `HTTP${response.status}`, status: response.status })
80
+ }
81
+
82
+ function objectOf(pathname: string, headers: Headers): BlobObject {
83
+ const customMetadata: Record<string, string> = {}
84
+ for (const [name, value] of headers)
85
+ if (name.startsWith(META_PREFIX)) customMetadata[name.slice(META_PREFIX.length)] = value
86
+ return {
87
+ pathname,
88
+ contentType: headers.get("content-type") ?? "application/octet-stream",
89
+ size: Number(headers.get("content-length") ?? 0),
90
+ etag: headers.get("etag") ?? "",
91
+ uploadedAt: new Date(headers.get("last-modified") ?? 0),
92
+ customMetadata,
93
+ }
94
+ }
95
+
96
+ const writeHeaders = (write: BlobWrite) => ({
97
+ "content-type": write.contentType,
98
+ ...Object.fromEntries(
99
+ Object.entries(write.customMetadata).map(([name, value]) => [`${META_PREFIX}${name}`, value]),
100
+ ),
101
+ })
102
+
103
+ async function head(pathname: string): Promise<BlobObject | undefined> {
104
+ const key = `${base}${pathname}`
105
+ const response = await send("HEAD", key)
106
+ if (response.status === 404) return undefined
107
+ if (!response.ok) throw await failure("HEAD", key, response)
108
+ return objectOf(pathname, response.headers)
109
+ }
110
+
111
+ async function putOnce(key: string, body: Uint8Array | Blob, write: BlobWrite): Promise<void> {
112
+ const response = await send("PUT", key, { headers: writeHeaders(write), body: body as BodyInit })
113
+ if (!response.ok) throw await failure("PUT", key, response)
114
+ await response.body?.cancel()
115
+ }
116
+
117
+ async function createUpload(key: string, write: BlobWrite): Promise<string> {
118
+ const created = await send("POST", key, { query: { uploads: "" }, headers: writeHeaders(write) })
119
+ if (!created.ok) throw await failure("POST", key, created)
120
+ const uploadId = xmlTag(await created.text(), "UploadId")
121
+ if (!uploadId) throw new Error(`S3 POST s3://${credentials().bucket}/${key} gave no UploadId`)
122
+ return uploadId
123
+ }
124
+
125
+ async function uploadPart(key: string, uploadId: string, partNumber: number, body: Uint8Array): Promise<string> {
126
+ const response = await send("PUT", key, {
127
+ query: { partNumber: String(partNumber), uploadId },
128
+ body: body as Uint8Array<ArrayBuffer>,
129
+ })
130
+ if (!response.ok) throw await failure("PUT", key, response)
131
+ await response.body?.cancel()
132
+ return response.headers.get("etag") ?? ""
133
+ }
134
+
135
+ async function completeUpload(key: string, uploadId: string, parts: BlobUploadedPart[]): Promise<void> {
136
+ const xml = `<CompleteMultipartUpload>${parts.map((part) => `<Part><PartNumber>${part.partNumber}</PartNumber><ETag>${xmlEscape(part.etag)}</ETag></Part>`).join("")}</CompleteMultipartUpload>`
137
+ const done = await send("POST", key, {
138
+ query: { uploadId },
139
+ headers: { "content-type": "application/xml" },
140
+ body: xml,
141
+ })
142
+ if (!done.ok) throw await failure("POST", key, done)
143
+ const text = await done.text()
144
+ const code = xmlTag(text, "Code")
145
+ // CompleteMultipartUpload can answer 200 with an <Error> body
146
+ if (code)
147
+ throw Object.assign(
148
+ new Error(`S3 POST s3://${credentials().bucket}/${key} failed: 200 ${code}: ${xmlTag(text, "Message") ?? ""}`),
149
+ { code, status: 200 },
150
+ )
151
+ }
152
+
153
+ async function abortUpload(key: string, uploadId: string): Promise<void> {
154
+ const response = await send("DELETE", key, { query: { uploadId } })
155
+ if (!response.ok && response.status !== 404) throw await failure("DELETE", key, response)
156
+ await response.body?.cancel()
157
+ }
158
+
159
+ async function putParts(
160
+ key: string,
161
+ first: Uint8Array,
162
+ rest: AsyncGenerator<Uint8Array>,
163
+ write: BlobWrite,
164
+ ): Promise<void> {
165
+ const uploadId = await createUpload(key, write)
166
+ const parts: BlobUploadedPart[] = []
167
+ try {
168
+ let part: Uint8Array | undefined = first
169
+ while (part) {
170
+ const partNumber = parts.length + 1
171
+ parts.push({ partNumber, etag: await uploadPart(key, uploadId, partNumber, part) })
172
+ const next = await rest.next()
173
+ part = next.done ? undefined : next.value
174
+ }
175
+ await completeUpload(key, uploadId, parts)
176
+ } catch (error) {
177
+ await abortUpload(key, uploadId).catch(() => undefined)
178
+ throw error
179
+ }
180
+ }
181
+
182
+ /** A part step's S3 error as the step's answer: a missing upload is a 404, a part S3 refuses for what the client listed a 400. */
183
+ const stepError = (error: unknown): unknown => {
184
+ const code = (error as { code?: string }).code
185
+ if (code === "NoSuchUpload") return uploadNotFound()
186
+ if (code === "InvalidPart" || code === "InvalidPartOrder" || code === "EntityTooSmall") return invalidUpload(error)
187
+ return error
188
+ }
189
+
190
+ async function withLimit<T, R>(items: T[], run: (item: T) => Promise<R>): Promise<R[]> {
191
+ const results: R[] = new Array(items.length)
192
+ let next = 0
193
+ const worker = async () => {
194
+ while (next < items.length) {
195
+ const at = next++
196
+ results[at] = await run(items[at]!)
197
+ }
198
+ }
199
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, items.length) }, worker))
200
+ return results
201
+ }
202
+
203
+ const driver: BlobDriver = {
204
+ name: "s3",
205
+ async put(pathname, body, write) {
206
+ const key = `${base}${pathname}`
207
+ if (body instanceof ReadableStream) {
208
+ const { first, rest } = await firstPart(body)
209
+ if (rest) await putParts(key, first, rest, write)
210
+ else await putOnce(key, first, write)
211
+ } else {
212
+ await putOnce(key, body, write)
213
+ }
214
+ const stored = await head(pathname)
215
+ if (!stored) throw new Error(`S3 PUT s3://${credentials().bucket}/${key} succeeded but HEAD found no object`)
216
+ return stored
217
+ },
218
+ async get(pathname) {
219
+ const key = `${base}${pathname}`
220
+ const response = await send("GET", key)
221
+ if (!response.ok) {
222
+ const error = await failure("GET", key, response)
223
+ if ((error as Error & { code: string }).code === "NoSuchKey") return undefined
224
+ throw error
225
+ }
226
+ const type = response.headers.get("content-type") ?? "application/octet-stream"
227
+ return new Blob([await response.arrayBuffer()], { type })
228
+ },
229
+ head,
230
+ async list({ prefix, limit, cursor, folded }) {
231
+ const query: Record<string, string> = {
232
+ "list-type": "2",
233
+ "encoding-type": "url",
234
+ prefix: `${base}${prefix}`,
235
+ "max-keys": String(limit),
236
+ }
237
+ if (folded) query.delimiter = "/"
238
+ if (cursor) query["continuation-token"] = cursor
239
+ const response = await send("GET", "", { query })
240
+ if (!response.ok) throw await failure("GET", "", response)
241
+ const xml = await response.text()
242
+ const own = (key: string) => urlDecoded(key).slice(base.length)
243
+ const blobs = xmlTags(xml, "Contents").flatMap((contents): BlobListItem[] => {
244
+ const key = xmlTag(contents, "Key")
245
+ if (key === undefined) return []
246
+ return [
247
+ {
248
+ pathname: own(key),
249
+ size: Number(xmlTag(contents, "Size") ?? 0),
250
+ etag: xmlTag(contents, "ETag") ?? "",
251
+ uploadedAt: new Date(xmlTag(contents, "LastModified") ?? 0),
252
+ },
253
+ ]
254
+ })
255
+ const folders = xmlTags(xml, "CommonPrefixes").flatMap((prefixes) => {
256
+ const name = xmlTag(prefixes, "Prefix")
257
+ return name === undefined ? [] : [own(name)]
258
+ })
259
+ const next = xmlTag(xml, "IsTruncated") === "true" ? xmlTag(xml, "NextContinuationToken") : undefined
260
+ return { blobs, hasMore: next !== undefined, ...(next ? { cursor: next } : {}), ...(folded ? { folders } : {}) }
261
+ },
262
+ async delete(paths) {
263
+ await withLimit(paths, async (pathname) => {
264
+ const key = `${base}${pathname}`
265
+ const response = await send("DELETE", key)
266
+ if (!response.ok && response.status !== 404) throw await failure("DELETE", key, response)
267
+ await response.body?.cancel()
268
+ })
269
+ },
270
+ async open(pathname, etag, range) {
271
+ const key = `${base}${pathname}`
272
+ const response = await send("GET", key, {
273
+ headers: { "if-match": etag, ...(range ? { range: `bytes=${range.start}-${range.end}` } : {}) },
274
+ })
275
+ if (response.status === 412) {
276
+ await response.body?.cancel()
277
+ return "changed"
278
+ }
279
+ if (!response.ok) {
280
+ const error = await failure("GET", key, response)
281
+ if ((error as Error & { code: string }).code === "NoSuchKey") return undefined
282
+ throw error
283
+ }
284
+ return response.body as ReadableStream<Uint8Array>
285
+ },
286
+ async presign(pathname, request) {
287
+ return presignS3(credentials(), { ...request, key: `${base}${pathname}` })
288
+ },
289
+ multipart: {
290
+ create: (pathname, write) => createUpload(`${base}${pathname}`, write),
291
+ async uploadPart(pathname, uploadId, partNumber, body) {
292
+ return uploadPart(`${base}${pathname}`, uploadId, partNumber, body).catch((error: unknown) =>
293
+ Promise.reject(stepError(error)),
294
+ )
295
+ },
296
+ async complete(pathname, uploadId, parts) {
297
+ await completeUpload(`${base}${pathname}`, uploadId, parts).catch((error: unknown) =>
298
+ Promise.reject(stepError(error)),
299
+ )
300
+ const stored = await head(pathname)
301
+ if (!stored)
302
+ throw new Error(`S3 POST s3://${credentials().bucket}/${base}${pathname} completed but HEAD found no object`)
303
+ return stored
304
+ },
305
+ abort: (pathname, uploadId) => abortUpload(`${base}${pathname}`, uploadId),
306
+ },
307
+ }
308
+ return driver
309
+ }
310
+
311
+ export default openS3Driver
@@ -0,0 +1,314 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import type { HamurEvent } from "hamur/server"
3
+ import type { BlobStore } from "../types.ts"
4
+
5
+ export interface SuiteOptions {
6
+ /** A store on a fresh base. */
7
+ make(): Promise<BlobStore>
8
+ /** The sizes of the parts written since the last call, on drivers that write in parts. */
9
+ parts?(): number[]
10
+ }
11
+
12
+ const MiB = 1024 * 1024
13
+
14
+ const eventOf = (path: string, headers: Record<string, string> = {}, method = "GET") =>
15
+ ({ request: new Request(`http://x/${path}`, { method, headers }) }) as HamurEvent
16
+
17
+ function chunked(size: number, chunk = 64 * 1024): ReadableStream<Uint8Array> {
18
+ let sent = 0
19
+ return new ReadableStream({
20
+ pull(controller) {
21
+ if (sent >= size) return controller.close()
22
+ const length = Math.min(chunk, size - sent)
23
+ const bytes = new Uint8Array(length)
24
+ for (let at = 0; at < length; at++) bytes[at] = (sent + at) % 251
25
+ sent += length
26
+ controller.enqueue(bytes)
27
+ },
28
+ })
29
+ }
30
+
31
+ /** Put, get, head, list with `cursor` and `folded`, delete and serve, the same on every driver. */
32
+ export function blobSuite(name: string, options: SuiteOptions): void {
33
+ describe(`${name} blob driver`, () => {
34
+ test("put returns the stored object; get and head read it back; a missing pathname is undefined", async () => {
35
+ const blob = await options.make()
36
+ const put = await blob.put("/docs/a.txt", "hello world", { customMetadata: { author: "ada", "x-y-z": "1 2" } })
37
+ expect(put).toMatchObject({
38
+ pathname: "docs/a.txt",
39
+ contentType: "text/plain; charset=utf-8",
40
+ size: 11,
41
+ customMetadata: { author: "ada", "x-y-z": "1 2" },
42
+ })
43
+ expect(put.etag).toMatch(/^"[^"]+"$/)
44
+ expect(put.uploadedAt).toBeInstanceOf(Date)
45
+ expect(Math.abs(put.uploadedAt.getTime() - Date.now())).toBeLessThan(5000)
46
+ const head = await blob.head("docs/a.txt")
47
+ expect(head).toEqual({ ...put, uploadedAt: head!.uploadedAt })
48
+ const got = await blob.get("docs/a.txt")
49
+ expect(got).toBeInstanceOf(Blob)
50
+ expect(await got!.text()).toBe("hello world")
51
+ expect(got!.type).toBe("text/plain; charset=utf-8")
52
+ expect(await blob.head("docs/none.txt")).toBeUndefined()
53
+ expect(await blob.get("docs/none.txt")).toBeUndefined()
54
+ })
55
+
56
+ test("every body kind is stored; the type comes from the option, then the Blob, then the extension", async () => {
57
+ const blob = await options.make()
58
+ const bytes = new Uint8Array([1, 2, 3])
59
+ expect((await blob.put("b/raw", bytes)).contentType).toBe("application/octet-stream")
60
+ expect((await blob.put("b/buffer.png", bytes.slice().buffer)).contentType).toBe("image/png")
61
+ expect((await blob.put("b/typed.bin", new Blob(["x"], { type: "image/webp" }))).contentType).toBe("image/webp")
62
+ expect((await blob.put("b/given.png", "x", { contentType: "text/csv" })).contentType).toBe("text/csv")
63
+ expect(await (await blob.get("b/stream.txt"))?.text()).toBeUndefined()
64
+ await blob.put("b/stream.txt", new Blob(["streamed body"]).stream())
65
+ expect(await (await blob.get("b/stream.txt"))!.text()).toBe("streamed body")
66
+ expect(new Uint8Array(await (await blob.get("b/buffer.png"))!.arrayBuffer())).toEqual(bytes)
67
+ await blob.put("b/raw", "replaced")
68
+ expect(await (await blob.get("b/raw"))!.text()).toBe("replaced")
69
+ expect((await blob.head("b/raw"))!.size).toBe(8)
70
+ })
71
+
72
+ test("addRandomSuffix puts -<8 base36> before the extension", async () => {
73
+ const blob = await options.make()
74
+ const { pathname } = await blob.put("a/photo.jpg", "x", { addRandomSuffix: true })
75
+ expect(pathname).toMatch(/^a\/photo-[0-9a-z]{8}\.jpg$/)
76
+ expect(await blob.head(pathname)).toBeDefined()
77
+ expect((await blob.put("a/plain", "x", { addRandomSuffix: true })).pathname).toMatch(/^a\/plain-[0-9a-z]{8}$/)
78
+ })
79
+
80
+ test("a pathname with an empty segment, . or .., a backslash or NUL is refused", async () => {
81
+ const blob = await options.make()
82
+ for (const pathname of ["a/../b", "a//b", "./a", "a/.", "", "/", "a\\b", "a\0b", "a/"]) {
83
+ await expect(blob.put(pathname, "x")).rejects.toThrow(
84
+ new TypeError(`Invalid blob pathname ${JSON.stringify(pathname)}`),
85
+ )
86
+ }
87
+ await expect(blob.get("../etc/passwd")).rejects.toThrow('Invalid blob pathname "../etc/passwd"')
88
+ await expect(blob.put("x".repeat(1025), "x")).rejects.toThrow(TypeError)
89
+ await expect(blob.put("a/\ud800.txt", "x")).rejects.toThrow(
90
+ new TypeError('Invalid blob pathname "a/\\ud800.txt"'),
91
+ )
92
+ })
93
+
94
+ test("customMetadata: a-z, 0-9 and - keys, printable ASCII values without edge spaces, 2048 bytes in all", async () => {
95
+ const blob = await options.make()
96
+ await expect(blob.put("a", "x", { customMetadata: { Author: "x" } })).rejects.toThrow(
97
+ 'Invalid customMetadata key "Author": use a-z, 0-9 and "-"',
98
+ )
99
+ for (const value of [" a", "a ", "ü", "a\nb"]) {
100
+ await expect(blob.put("a", "x", { customMetadata: { k: value } })).rejects.toThrow(
101
+ 'Invalid customMetadata value for "k": use printable ASCII with no leading or trailing space',
102
+ )
103
+ }
104
+ await expect(
105
+ blob.put("a", "x", { customMetadata: { a: "x".repeat(1024), b: "y".repeat(1023) } }),
106
+ ).rejects.toThrow("customMetadata is 2049 bytes; keys and values together may hold at most 2048 (S3's limit)")
107
+ const stored = await blob.put("a", "x", { customMetadata: { a: "x".repeat(1024), b: "y".repeat(1021), c: "" } })
108
+ expect((await blob.head("a"))!.customMetadata).toEqual(stored.customMetadata)
109
+ })
110
+
111
+ test("a content type is one type/subtype with parameters, stored canonical; a list or garbage is refused", async () => {
112
+ const blob = await options.make()
113
+ for (const type of [
114
+ "image/png, text/html",
115
+ "text/html,",
116
+ "image/png;",
117
+ "png",
118
+ "image/png; a",
119
+ "text/html\nx",
120
+ 'image/png; a="b,c"',
121
+ ]) {
122
+ await expect(blob.put("t/a", "x", { contentType: type })).rejects.toThrow(
123
+ new TypeError(
124
+ `Invalid blob content type ${JSON.stringify(type)}: use one type/subtype with optional ; parameters`,
125
+ ),
126
+ )
127
+ }
128
+ await expect(blob.put("t/b.png", new Blob(["x"], { type: "image/png, text/html" }))).rejects.toThrow(
129
+ 'Invalid blob content type "image/png, text/html"',
130
+ )
131
+ expect((await blob.put("t/c", "x", { contentType: 'Text/HTML ; Charset=UTF-8; q="a b"' })).contentType).toBe(
132
+ 'text/html; charset=UTF-8; q="a b"',
133
+ )
134
+ expect((await blob.head("t/c"))!.contentType).toBe('text/html; charset=UTF-8; q="a b"')
135
+ })
136
+
137
+ test("a pathname is stored as written: spaces, %, + and non-ASCII characters, a file beside a folder of its name", async () => {
138
+ const blob = await options.make()
139
+ const names = ["sp ace/ü.txt", "100%/a+b", "a", "a/b"]
140
+ for (const name of names) await blob.put(name, name)
141
+ for (const name of names) expect(await (await blob.get(name))!.text()).toBe(name)
142
+ expect((await blob.list()).blobs.map((item) => item.pathname)).toEqual([...names].sort())
143
+ })
144
+
145
+ test("list pages in pathname order with limit and cursor; prefix narrows it; folded gives folders", async () => {
146
+ const blob = await options.make()
147
+ for (const name of ["p/a.txt", "p/b.txt", "p/c/1.txt", "p/c/2.txt", "p/d.txt", "q.txt"])
148
+ await blob.put(name, name)
149
+ const seen: string[] = []
150
+ let cursor: string | undefined
151
+ let pages = 0
152
+ do {
153
+ const page = await blob.list({ prefix: "p/", limit: 2, ...(cursor ? { cursor } : {}) })
154
+ expect(page.blobs.length).toBeLessThanOrEqual(2)
155
+ expect(page.hasMore).toBe(page.cursor !== undefined)
156
+ expect(page.folders).toBeUndefined()
157
+ seen.push(...page.blobs.map((item) => item.pathname))
158
+ cursor = page.cursor
159
+ pages++
160
+ } while (cursor)
161
+ expect(seen).toEqual(["p/a.txt", "p/b.txt", "p/c/1.txt", "p/c/2.txt", "p/d.txt"])
162
+ expect(pages).toBe(3)
163
+ const all = await blob.list()
164
+ expect(all).toMatchObject({ hasMore: false })
165
+ const head = (await blob.head("p/a.txt"))!
166
+ expect(all.blobs[0]).toEqual({ pathname: "p/a.txt", size: 7, etag: head.etag, uploadedAt: head.uploadedAt })
167
+ const folded: { blobs: string[]; folders: string[] } = { blobs: [], folders: [] }
168
+ cursor = undefined
169
+ do {
170
+ const page = await blob.list({ prefix: "p/", folded: true, limit: 2, ...(cursor ? { cursor } : {}) })
171
+ folded.blobs.push(...page.blobs.map((item) => item.pathname))
172
+ folded.folders.push(...page.folders!)
173
+ cursor = page.cursor
174
+ } while (cursor)
175
+ expect(folded).toEqual({ blobs: ["p/a.txt", "p/b.txt", "p/d.txt"], folders: ["p/c/"] })
176
+ expect(await blob.list({ folded: true })).toMatchObject({ folders: ["p/"], hasMore: false })
177
+ expect((await blob.list({ folded: true })).blobs.map((item) => item.pathname)).toEqual(["q.txt"])
178
+ await expect(blob.list({ limit: 0 })).rejects.toThrow("blob list limit must be an integer from 1 to 1000 (got 0)")
179
+ })
180
+
181
+ test("delete removes one or several pathnames; a missing one does nothing", async () => {
182
+ const blob = await options.make()
183
+ for (const name of ["d/1", "d/2", "d/3"]) await blob.put(name, name)
184
+ await blob.delete("d/1")
185
+ await blob.delete(["d/2", "d/none"])
186
+ expect(await blob.head("d/1")).toBeUndefined()
187
+ expect(await blob.head("d/2")).toBeUndefined()
188
+ expect((await blob.list({ prefix: "d/" })).blobs.map((item) => item.pathname)).toEqual(["d/3"])
189
+ })
190
+
191
+ test("serve answers the bytes with type, length, etag and last-modified; 304, 206, 416 and HEAD; 404 for a missing blob", async () => {
192
+ const blob = await options.make()
193
+ const stored = await blob.put("s/digits.txt", "0123456789abcdefghij")
194
+ const full = await blob.serve(eventOf("s"), "s/digits.txt")
195
+ expect(full.status).toBe(200)
196
+ expect(Object.fromEntries(full.headers)).toMatchObject({
197
+ "content-type": "text/plain; charset=utf-8",
198
+ "content-length": "20",
199
+ etag: stored.etag,
200
+ "last-modified": (await blob.head("s/digits.txt"))!.uploadedAt.toUTCString(),
201
+ "accept-ranges": "bytes",
202
+ "cache-control": "private, no-cache",
203
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
204
+ "x-content-type-options": "nosniff",
205
+ })
206
+ expect(await full.text()).toBe("0123456789abcdefghij")
207
+
208
+ const cached = await blob.serve(eventOf("s", { "if-none-match": stored.etag }), "s/digits.txt")
209
+ expect(cached.status).toBe(304)
210
+ expect(cached.headers.get("etag")).toBe(stored.etag)
211
+ expect(await cached.text()).toBe("")
212
+ const since = await blob.serve(
213
+ eventOf("s", { "if-modified-since": new Date(Date.now() + 60_000).toUTCString() }),
214
+ "s/digits.txt",
215
+ )
216
+ expect(since.status).toBe(304)
217
+ const stale = await blob.serve(
218
+ eventOf("s", { "if-none-match": '"other"', "if-modified-since": new Date(Date.now() + 60_000).toUTCString() }),
219
+ "s/digits.txt",
220
+ )
221
+ expect(stale.status).toBe(200)
222
+ await stale.body?.cancel()
223
+
224
+ const range = await blob.serve(eventOf("s", { range: "bytes=0-9" }), "s/digits.txt")
225
+ expect(range.status).toBe(206)
226
+ expect(range.headers.get("content-range")).toBe("bytes 0-9/20")
227
+ expect(range.headers.get("content-length")).toBe("10")
228
+ const bytes = new Uint8Array(await range.arrayBuffer())
229
+ expect(bytes.length).toBe(10)
230
+ expect(new TextDecoder().decode(bytes)).toBe("0123456789")
231
+ const suffix = await blob.serve(eventOf("s", { range: "bytes=-5" }), "s/digits.txt")
232
+ expect([suffix.status, await suffix.text()]).toEqual([206, "fghij"])
233
+ const several = await blob.serve(eventOf("s", { range: "bytes=0-1,4-5" }), "s/digits.txt")
234
+ expect([several.status, await several.text()]).toEqual([200, "0123456789abcdefghij"])
235
+
236
+ const unsatisfiable = await blob.serve(eventOf("s", { range: "bytes=20-" }), "s/digits.txt")
237
+ expect(unsatisfiable.status).toBe(416)
238
+ expect(unsatisfiable.headers.get("content-range")).toBe("bytes */20")
239
+
240
+ const head = await blob.serve(eventOf("s", {}, "HEAD"), "s/digits.txt")
241
+ expect([head.status, head.headers.get("content-length"), await head.text()]).toEqual([200, "20", ""])
242
+
243
+ const missing = await blob.serve(eventOf("s"), "s/none.txt").catch((error: unknown) => error)
244
+ expect(missing).toMatchObject({ status: 404, message: "Blob not found" })
245
+
246
+ const public_ = await blob.serve(eventOf("s"), "s/digits.txt", { cacheControl: "public, max-age=60" })
247
+ expect(public_.headers.get("cache-control")).toBe("public, max-age=60")
248
+ await public_.body?.cancel()
249
+ })
250
+
251
+ test("serve sandboxes every type with a CSP and nosniff: HTML, SVG, +xml, XSL and images alike", async () => {
252
+ const blob = await options.make()
253
+ await blob.put("x/logo.svg", '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>')
254
+ await blob.put("x/page.html", "<script>alert(1)</script>")
255
+ await blob.put("x/feed", "<a/>", { contentType: "application/rss+xml" })
256
+ await blob.put("x/style", "<a/>", { contentType: "text/xsl" })
257
+ await blob.put("x/pic.png", new Uint8Array([137, 80]))
258
+ for (const name of ["x/logo.svg", "x/page.html", "x/feed", "x/style", "x/pic.png"]) {
259
+ const response = await blob.serve(eventOf("x"), name)
260
+ expect(response.headers.get("content-security-policy")).toBe(
261
+ "default-src 'none'; style-src 'unsafe-inline'; sandbox",
262
+ )
263
+ expect(response.headers.get("x-content-type-options")).toBe("nosniff")
264
+ await response.body?.cancel()
265
+ }
266
+ })
267
+
268
+ test("concurrent puts to one pathname leave one whole version; a reader during puts gets bytes that match its headers, or a 503", async () => {
269
+ const blob = await options.make()
270
+ const versions = Array.from({ length: 8 }, (_, at) => String(at).repeat(1000 * (at + 1)))
271
+ await blob.put("race.txt", versions[0]!)
272
+ let reading = true
273
+ const reads = (async () => {
274
+ let count = 0
275
+ while (reading || count < 5) {
276
+ const response = await blob.serve(eventOf("r"), "race.txt").catch((error: { status?: number }) => {
277
+ if (error.status !== 503) throw error
278
+ })
279
+ count++
280
+ if (!response) continue
281
+ const text = await response.text()
282
+ expect(text.length).toBe(Number(response.headers.get("content-length")))
283
+ expect(versions).toContain(text)
284
+ }
285
+ return count
286
+ })()
287
+ await Promise.all(versions.map((version) => blob.put("race.txt", version)))
288
+ reading = false
289
+ expect(await reads).toBeGreaterThanOrEqual(5)
290
+ const head = (await blob.head("race.txt"))!
291
+ const text = await (await blob.get("race.txt"))!.text()
292
+ expect(versions).toContain(text)
293
+ expect(head.size).toBe(text.length)
294
+ const again = await blob.serve(eventOf("r", { "if-none-match": head.etag }), "race.txt")
295
+ expect(again.status).toBe(304)
296
+ })
297
+
298
+ test("a 25 MB stream of unknown length is stored whole and read back in ranges", async () => {
299
+ const blob = await options.make()
300
+ options.parts?.()
301
+ const size = 25 * MiB
302
+ const stored = await blob.put("big/file.bin", chunked(size))
303
+ expect(stored.size).toBe(size)
304
+ if (options.parts) expect(options.parts()).toEqual([10 * MiB, 10 * MiB, 5 * MiB])
305
+ const tail = await blob.serve(eventOf("big", { range: `bytes=${size - 4}-` }), "big/file.bin")
306
+ expect(tail.status).toBe(206)
307
+ expect([...new Uint8Array(await tail.arrayBuffer())]).toEqual([0, 1, 2, 3].map((at) => (size - 4 + at) % 251))
308
+ const whole = await blob.serve(eventOf("big"), "big/file.bin")
309
+ let read = 0
310
+ for await (const chunk of whole.body!) read += chunk.length
311
+ expect(read).toBe(size)
312
+ }, 60_000)
313
+ })
314
+ }
package/src/env.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ declare module "#hamur/blob/config" {
2
+ type Resolved = import("./types.ts").ResolvedBlobDriver
3
+ export const config: Resolved | null
4
+ export const prerender: Resolved | null
5
+ /** The preset of a build; null under `hamur dev`. */
6
+ export const preset: string | null
7
+ /** The request body limit of the run in bytes: `server.maxRequestBodySize`, or 100 MB on cloudflare (Free and Pro). */
8
+ export const bodyLimit: number
9
+ export const drivers: Partial<
10
+ Record<Resolved["driver"], () => Promise<{ default: import("./runtime/driver.ts").OpenDriver }>>
11
+ >
12
+ }
13
+
14
+ interface ImportMeta {
15
+ readonly prerender?: boolean
16
+ }
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ export { default } from "./module.ts"
2
+ export type {
3
+ BlobConfig,
4
+ BlobList,
5
+ BlobListItem,
6
+ BlobObject,
7
+ BlobPutOptions,
8
+ BlobServeOptions,
9
+ BlobStore,
10
+ } from "./types.ts"
package/src/module.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { defineModule } from "hamur/kit"
2
+ import { setupBlob } from "./build/setup.ts"
3
+ import { resolveOptions } from "./options.ts"
4
+ import type { BlobConfig } from "./types.ts"
5
+
6
+ export default defineModule<BlobConfig>({
7
+ meta: { name: "blob", configKey: "blob" },
8
+ setup(input, hamur) {
9
+ setupBlob(resolveOptions(input), hamur)
10
+ },
11
+ })