@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,19 @@
1
+ import type { ResolvedBlobDriver } from "./types.ts";
2
+ /** Each driver and the presets it runs on (`static` runs the server only at build, on Bun). */
3
+ export declare const DRIVERS: Record<ResolvedBlobDriver["driver"], {
4
+ presets: string[];
5
+ keys: string[];
6
+ }>;
7
+ export declare const DEFAULT_FS: Extract<ResolvedBlobDriver, {
8
+ driver: "fs";
9
+ }>;
10
+ export declare const DEFAULT_R2: Extract<ResolvedBlobDriver, {
11
+ driver: "cloudflare-r2";
12
+ }>;
13
+ export interface ResolvedBlobOptions {
14
+ /** The configured driver; undefined gives the preset's default. */
15
+ driver?: ResolvedBlobDriver;
16
+ dev?: ResolvedBlobDriver;
17
+ }
18
+ /** The checked options, or the build error of the first value that is wrong. */
19
+ export declare function resolveOptions(input: unknown): ResolvedBlobOptions;
@@ -0,0 +1,3 @@
1
+ import type { ResolvedBlobDriver } from "../types.ts";
2
+ /** The driver of this run: `prerender` (`blob.dev`, else the build's driver) while prerendering, else `config`. */
3
+ export declare function chooseDriver(prerendering: boolean, config: ResolvedBlobDriver | null, prerender: ResolvedBlobDriver | null): ResolvedBlobDriver;
@@ -0,0 +1,29 @@
1
+ import type { BlobDriver, ReadSecret, ResolvedBlobDriver } from "../types.ts";
2
+ export type OpenDriver<C extends ResolvedBlobDriver = ResolvedBlobDriver> = (config: C, secret: ReadSecret) => BlobDriver;
3
+ /** The pathname error; a driver throws it too for a pathname its backend cannot hold. */
4
+ export declare const invalidPathname: (pathname: unknown) => TypeError;
5
+ /** The error from a driver that cannot sign a URL. */
6
+ export declare const presignUnavailable: (driver: string) => Error;
7
+ /** A multipart step on an upload the backend does not hold for the pathname. */
8
+ export declare const uploadNotFound: () => import("hamur/server").HamurError<unknown>;
9
+ /** A malformed upload step, or one storage refuses for what the client sent. */
10
+ export declare const invalidUpload: (cause?: unknown) => import("hamur/server").HamurError<unknown>;
11
+ /** A stream of unknown length on `s3` and `cloudflare-r2` is written in parts of this size. */
12
+ export declare const PART_SIZE: number;
13
+ /**
14
+ * The stream cut into `size`-byte parts (the last one shorter), each read before it is yielded, so at most one part is
15
+ * held; a stream that ends inside the first part yields that one part.
16
+ */
17
+ export declare function parts(stream: ReadableStream<Uint8Array>, size?: number): AsyncGenerator<Uint8Array>;
18
+ /** The first part and an iterator over the rest; `rest` is undefined when the stream fit in one part. */
19
+ export declare function firstPart(stream: ReadableStream<Uint8Array>, size?: number): Promise<{
20
+ first: Uint8Array;
21
+ rest?: AsyncGenerator<Uint8Array>;
22
+ }>;
23
+ /** Pages through `items` sorted by `name`: those after `after`, at most `limit`. */
24
+ export declare function page<T extends {
25
+ name: string;
26
+ }>(items: T[], after: string | undefined, limit: number): {
27
+ items: T[];
28
+ hasMore: boolean;
29
+ };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * One `type/subtype` with optional `; name=value` parameters, in canonical form (type, subtype and parameter names in
3
+ * lowercase), or undefined. A comma is refused anywhere, quoted or not: a browser reading `image/png, text/html` keeps the
4
+ * last type, so a list would pass a check on its first.
5
+ */
6
+ export declare function parseContentType(value: string): string | undefined;
@@ -0,0 +1,34 @@
1
+ import { type HamurEvent, type Secret } from "hamur/server";
2
+ import { type BlobSize } from "../server/ensure.ts";
3
+ import type { BlobDriver } from "../types.ts";
4
+ export interface MultipartUploadOptions {
5
+ /** The step, the `:action` param of the route: `create`, `upload`, `complete` or `abort`. */
6
+ action: string;
7
+ /** Maps the client's name to the stored pathname, on every step: the app decides where a user may write. */
8
+ pathname?: (name: string) => string;
9
+ ensure?: {
10
+ maxSize?: BlobSize;
11
+ types?: string[];
12
+ };
13
+ put?: {
14
+ addRandomSuffix?: boolean;
15
+ customMetadata?: Record<string, string>;
16
+ };
17
+ /** Parts go from the browser to storage on presigned `UploadPart` URLs; the `s3` driver only. */
18
+ direct?: boolean;
19
+ /** Seconds a direct part URL is valid, default 900. */
20
+ expiresIn?: number;
21
+ /** The secret (at least 32 characters) that signs the upload tokens: a value of `#hamur/env/private`, or `env("NAME")`. */
22
+ secret: Secret;
23
+ }
24
+ /** Where the handler runs: the preset of a build (null under `hamur dev`), and its request body limit in bytes. */
25
+ export interface MultipartTarget {
26
+ preset: string | null;
27
+ bodyLimit: number;
28
+ }
29
+ /**
30
+ * `handleMultipartUpload` over the driver the store opens and the preset the build wrote. Each part must hold
31
+ * exactly its share of the size `create` declared and checked, and `complete` takes exactly the parts 1 – n, so the object
32
+ * that takes the pathname is the one `ensure` allowed; a refused upload never replaces what is there.
33
+ */
34
+ export declare function createMultipartUpload(driver: () => Promise<BlobDriver>, { preset, bodyLimit }: MultipartTarget): (event: HamurEvent, options: MultipartUploadOptions) => Promise<Response>;
@@ -0,0 +1,10 @@
1
+ import type { BlobDriver, BlobStore } from "../types.ts";
2
+ /** `/`-separated, a leading `/` dropped, at most 1024 bytes; an empty segment, `.`, `..`, `\`, NUL or a lone surrogate is refused. */
3
+ export declare function checkPathname(pathname: string): string;
4
+ export declare function checkMetadata(metadata: Record<string, string> | undefined): Record<string, string>;
5
+ /** One `type/subtype` with optional parameters, canonical; anything else throws. */
6
+ export declare function checkContentType(type: string): string;
7
+ /** `a/photo.jpg` → `a/photo-k3j9x0q2.jpg`: the suffix goes before the last segment's extension. */
8
+ export declare function withRandomSuffix(pathname: string): string;
9
+ /** The pathname rules, the defaults of `put` and `serve` over a driver opened at first use. */
10
+ export declare function createBlobStore(driver: () => Promise<BlobDriver>): BlobStore;
@@ -0,0 +1,3 @@
1
+ import type { BlobStore } from "../types.ts";
2
+ export declare const store: BlobStore;
3
+ export declare const multipartUpload: (event: import("hamur/server").HamurEvent, options: import("./index.ts").MultipartUploadOptions) => Promise<Response>;
@@ -0,0 +1,22 @@
1
+ import type { BlobObject } from "../types.ts";
2
+ export type BlobSize = number | `${number}${"B" | "KB" | "MB" | "GB"}`;
3
+ declare const UNITS: {
4
+ readonly B: 1;
5
+ readonly KB: 1024;
6
+ readonly MB: number;
7
+ readonly GB: number;
8
+ };
9
+ export declare function parseSize(size: BlobSize): {
10
+ bytes: number;
11
+ unit: keyof typeof UNITS;
12
+ shown: string;
13
+ };
14
+ /**
15
+ * Throws a 400 when `blob` (a `Blob`, or the `BlobObject` of `head`) is over `maxSize` or its type is not in
16
+ * `types` (a MIME type or a top-level type such as `image`). The type is the one the client sent; `serve` sandboxes active types whatever this check said.
17
+ */
18
+ export declare function ensureBlob(blob: Blob | BlobObject, options: {
19
+ maxSize?: BlobSize;
20
+ types?: string[];
21
+ }): void;
22
+ export {};
@@ -0,0 +1,12 @@
1
+ import type { HamurEvent } from "hamur/server";
2
+ import type { MultipartUploadOptions } from "../runtime/multipart.ts";
3
+ import type { BlobStore } from "../types.ts";
4
+ export { ensureBlob } from "./ensure.ts";
5
+ export type { MultipartUploadOptions } from "../runtime/multipart.ts";
6
+ /** The app's blob store, on the driver the build chose (`blob.dev` under `hamur dev` and the prerender). */
7
+ export declare function useBlob(): BlobStore;
8
+ /**
9
+ * One step of a multipart upload (`create`, `upload`, `complete`, `abort`) in a raw handler on
10
+ * `/<path>/:action`; with `direct: true` on the `s3` driver each part goes from the browser to storage on a presigned URL.
11
+ */
12
+ export declare function handleMultipartUpload(event: HamurEvent, options: MultipartUploadOptions): Promise<Response>;
@@ -0,0 +1,152 @@
1
+ import type { HamurEvent, Secret } from "hamur/server";
2
+ export type { Secret };
3
+ export type BlobDriverConfig = {
4
+ driver: "fs";
5
+ base?: string;
6
+ } | {
7
+ driver: "s3";
8
+ bucket?: Secret;
9
+ region?: Secret;
10
+ endpoint?: Secret;
11
+ accessKeyId?: Secret;
12
+ secretAccessKey?: Secret;
13
+ sessionToken?: Secret;
14
+ virtualHostedStyle?: boolean;
15
+ base?: string;
16
+ } | {
17
+ driver: "cloudflare-r2";
18
+ binding?: string;
19
+ base?: string;
20
+ };
21
+ export type BlobConfig = BlobDriverConfig & {
22
+ dev?: BlobConfig;
23
+ };
24
+ /** One driver config as the build resolved it: defaults filled, no `dev`. */
25
+ export type ResolvedBlobDriver = {
26
+ driver: "fs";
27
+ base: string;
28
+ } | ({
29
+ driver: "s3";
30
+ base: string;
31
+ } & Partial<Record<"bucket" | "region" | "endpoint" | "accessKeyId" | "secretAccessKey" | "sessionToken", Secret>> & {
32
+ virtualHostedStyle?: boolean;
33
+ }) | {
34
+ driver: "cloudflare-r2";
35
+ binding: string;
36
+ base: string;
37
+ };
38
+ export interface BlobPutOptions {
39
+ contentType?: string;
40
+ addRandomSuffix?: boolean;
41
+ customMetadata?: Record<string, string>;
42
+ }
43
+ export interface BlobObject {
44
+ pathname: string;
45
+ contentType: string;
46
+ size: number;
47
+ /** Quoted, the HTTP form. */
48
+ etag: string;
49
+ uploadedAt: Date;
50
+ customMetadata: Record<string, string>;
51
+ }
52
+ /** One entry of a listing: what every backend's listing gives without reading each object (`head` gives the rest). */
53
+ export interface BlobListItem {
54
+ pathname: string;
55
+ size: number;
56
+ etag: string;
57
+ uploadedAt: Date;
58
+ }
59
+ export interface BlobList {
60
+ blobs: BlobListItem[];
61
+ cursor?: string;
62
+ hasMore: boolean;
63
+ folders?: string[];
64
+ }
65
+ export interface BlobListOptions {
66
+ prefix?: string;
67
+ limit?: number;
68
+ cursor?: string;
69
+ folded?: boolean;
70
+ }
71
+ export type BlobBody = string | ArrayBuffer | Uint8Array | Blob | ReadableStream<Uint8Array>;
72
+ export interface BlobStore {
73
+ put(pathname: string, body: BlobBody, options?: BlobPutOptions): Promise<BlobObject>;
74
+ get(pathname: string): Promise<Blob | undefined>;
75
+ head(pathname: string): Promise<BlobObject | undefined>;
76
+ list(options?: BlobListOptions): Promise<BlobList>;
77
+ delete(pathnames: string | string[]): Promise<void>;
78
+ serve(event: HamurEvent, pathname: string, options?: BlobServeOptions): Promise<Response>;
79
+ presign(pathname: string, options: {
80
+ method: "GET" | "PUT";
81
+ expiresIn?: number;
82
+ contentType?: string;
83
+ }): Promise<string>;
84
+ }
85
+ export interface BlobServeOptions {
86
+ /** Default `private, no-cache`: a shared cache keeps nothing and a browser revalidates with the ETag. */
87
+ cacheControl?: string;
88
+ }
89
+ /** What a driver stores: the store has checked the pathname, filled `contentType` and checked `customMetadata`. */
90
+ export interface BlobWrite {
91
+ contentType: string;
92
+ customMetadata: Record<string, string>;
93
+ }
94
+ /** The backend of a `BlobStore`; keys are checked pathnames, the driver adds its `base`. */
95
+ export interface BlobDriver {
96
+ readonly name: ResolvedBlobDriver["driver"];
97
+ put(pathname: string, body: Uint8Array | Blob | ReadableStream<Uint8Array>, write: BlobWrite): Promise<BlobObject>;
98
+ get(pathname: string): Promise<Blob | undefined>;
99
+ head(pathname: string): Promise<BlobObject | undefined>;
100
+ /** `limit` is 1 – 1000 and `prefix` a checked prefix. */
101
+ list(options: {
102
+ prefix: string;
103
+ limit: number;
104
+ cursor?: string;
105
+ folded: boolean;
106
+ }): Promise<BlobList>;
107
+ delete(pathnames: string[]): Promise<void>;
108
+ /**
109
+ * The bytes of the version whose ETag is `etag`, or the inclusive range of them, as a stream; `"changed"` when the
110
+ * pathname now holds another version, undefined when it holds none.
111
+ */
112
+ open(pathname: string, etag: string, range?: {
113
+ start: number;
114
+ end: number;
115
+ }): Promise<ReadableStream<Uint8Array> | "changed" | undefined>;
116
+ /** A URL signed for one request on the backend itself; a driver that cannot sign one throws. */
117
+ presign(pathname: string, request: BlobPresignRequest): Promise<string>;
118
+ /** The steps of a multipart upload whose parts the caller sends one by one. */
119
+ multipart: BlobMultipartDriver;
120
+ }
121
+ /** One stored part of a multipart upload, as `complete` lists it. */
122
+ export interface BlobUploadedPart {
123
+ partNumber: number;
124
+ etag: string;
125
+ }
126
+ /**
127
+ * The backend's native multipart upload; `uploadId` is the backend's. A step on an upload that does not exist, or that
128
+ * belongs to another pathname, throws a 404 `Upload not found`; `abort` of one does nothing.
129
+ */
130
+ export interface BlobMultipartDriver {
131
+ create(pathname: string, write: BlobWrite): Promise<string>;
132
+ /** Stores part `partNumber` (1 – 10000) and returns its ETag. */
133
+ uploadPart(pathname: string, uploadId: string, partNumber: number, body: Uint8Array): Promise<string>;
134
+ /** Joins the listed parts, in `partNumber` order, into the object at `pathname`. */
135
+ complete(pathname: string, uploadId: string, parts: BlobUploadedPart[]): Promise<BlobObject>;
136
+ abort(pathname: string, uploadId: string): Promise<void>;
137
+ }
138
+ /** What `presignS3` signs besides the key; `contentLength` and `query` sign an `UploadPart` URL. */
139
+ export interface BlobPresignRequest {
140
+ method: "GET" | "PUT";
141
+ expiresIn: number;
142
+ contentType?: string;
143
+ contentLength?: number;
144
+ query?: Record<string, string>;
145
+ }
146
+ /** Resolves an `env("NAME")` option to its value at run time; `option` names it in the error. */
147
+ export type ReadSecret = (option: string, value: Secret | undefined) => string | undefined;
148
+ declare module "hamur" {
149
+ interface HamurModuleOptions {
150
+ blob?: BlobConfig;
151
+ }
152
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@hamur/blob",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/productdevbook/hamur.git",
9
+ "directory": "packages/blob"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/types/src/index.d.ts",
14
+ "bun": "./src/index.ts",
15
+ "hamur-source": "./src/index.ts",
16
+ "node": "./dist/src/index.js",
17
+ "default": "./src/index.ts"
18
+ },
19
+ "./server": {
20
+ "types": "./dist/types/src/server/index.d.ts",
21
+ "bun": "./src/server/index.ts",
22
+ "hamur-source": "./src/server/index.ts",
23
+ "node": "./dist/src/server/index.js",
24
+ "default": "./src/server/index.ts"
25
+ },
26
+ "./client": {
27
+ "types": "./dist/types/src/client/index.d.ts",
28
+ "bun": "./src/client/index.ts",
29
+ "hamur-source": "./src/client/index.ts",
30
+ "node": "./dist/src/client/index.js",
31
+ "default": "./src/client/index.ts"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "src"
38
+ ],
39
+ "dependencies": {},
40
+ "peerDependencies": {
41
+ "hamur": "~0.0.2"
42
+ }
43
+ }
@@ -0,0 +1,137 @@
1
+ import { readFile, writeFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { DiagnosticError, addTemplate, createResolver, type HamurContext } from "hamur/kit"
4
+ import { DEFAULT_FS, DEFAULT_R2, DRIVERS, type ResolvedBlobOptions } from "../options.ts"
5
+ import type { ResolvedBlobDriver } from "../types.ts"
6
+
7
+ const SERVER = "@hamur/blob/server"
8
+ const WRANGLER_FILES = ["wrangler.json", "wrangler.jsonc"]
9
+ /** A Worker's request body limit on the Free and Pro plans. */
10
+ const CLOUDFLARE_BODY_LIMIT = 100_000_000
11
+
12
+ /** The preset's own store when `blob` names no driver; none on vercel and netlify, whose file systems keep nothing. */
13
+ export function presetDefault(preset: string): ResolvedBlobDriver | undefined {
14
+ if (preset === "cloudflare") return { ...DEFAULT_R2 }
15
+ if (DRIVERS.fs.presets.includes(preset)) return { ...DEFAULT_FS }
16
+ return undefined
17
+ }
18
+
19
+ const isObject = (value: unknown): value is Record<string, unknown> =>
20
+ typeof value === "object" && value !== null && !Array.isArray(value)
21
+
22
+ /** The `r2_buckets[].binding` names of the app's wrangler config, with `cloudflare.env`'s block over the top level as the preset writes it. */
23
+ async function declaredR2Bindings(rootDir: string, env: string | undefined): Promise<string[]> {
24
+ let config: Record<string, unknown> = {}
25
+ for (const name of WRANGLER_FILES) {
26
+ const file = Bun.file(join(rootDir, name))
27
+ if (!(await file.exists())) continue
28
+ const parsed: unknown = Bun.JSONC.parse(await file.text())
29
+ if (isObject(parsed)) config = parsed
30
+ break
31
+ }
32
+ const envs = isObject(config.env) ? config.env : {}
33
+ const chosen = env !== undefined && isObject(envs[env]) ? { ...config, ...envs[env] } : config
34
+ const buckets = Array.isArray(chosen.r2_buckets) ? chosen.r2_buckets : []
35
+ return buckets.flatMap((bucket) => (isObject(bucket) && typeof bucket.binding === "string" ? [bucket.binding] : []))
36
+ }
37
+
38
+ const idVariable = (binding: string): string => `HAMUR_CF_${binding.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}_ID`
39
+
40
+ /** `cloudflare.bindings.<NAME>.id`, else env `HAMUR_CF_<NAME>_ID` with the name upper-cased and each character outside `A-Z0-9_` turned into `_`. */
41
+ const cloudflareId = (hamur: HamurContext, binding: string): string | undefined =>
42
+ hamur.options.cloudflare.bindings?.[binding]?.id || process.env[idVariable(binding)] || undefined
43
+
44
+ /** The top-level key of the finalized `.output/wrangler.json` that names `name` as a binding (`binding`, a durable object's `name`, a `vars` key), as `bindingKey` of the preset finds it. */
45
+ function bindingKey(config: Record<string, unknown>, name: string): string | undefined {
46
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
47
+ typeof value === "object" && value !== null && !Array.isArray(value)
48
+ const names = (value: unknown, inDurableObjects: boolean): boolean => {
49
+ if (Array.isArray(value)) return value.some((item) => names(item, inDurableObjects))
50
+ if (!isRecord(value)) return false
51
+ if (value.binding === name || (inDurableObjects && value.name === name)) return true
52
+ return Object.values(value).some((item) => names(item, inDurableObjects))
53
+ }
54
+ for (const [key, value] of Object.entries(config)) {
55
+ if (key === "env") continue
56
+ if (key === "vars" ? isRecord(value) && Object.hasOwn(value, name) : names(value, key === "durable_objects"))
57
+ return key
58
+ }
59
+ return undefined
60
+ }
61
+
62
+ /** An `r2_buckets` entry in `.output/wrangler.json` for a binding the app's config does not declare, from its id (the bucket name). */
63
+ async function writeR2Bucket(hamur: HamurContext, binding: string): Promise<void> {
64
+ const id = cloudflareId(hamur, binding)
65
+ const file = join(hamur.options.outputDir, "wrangler.json")
66
+ const wrangler = JSON.parse(await readFile(file, "utf8")) as { r2_buckets?: Array<Record<string, unknown>> }
67
+ if (!id || wrangler.r2_buckets?.some((bucket) => bucket.binding === binding)) return
68
+ const taken = bindingKey(wrangler as Record<string, unknown>, binding)
69
+ if (taken)
70
+ throw new DiagnosticError(
71
+ "HAMUR_E5202",
72
+ `blob.binding ${JSON.stringify(binding)} is already the ${taken} binding of the app's wrangler config; set blob.binding to another name`,
73
+ )
74
+ ;(wrangler.r2_buckets ??= []).push({ binding, bucket_name: id })
75
+ await writeFile(file, `${JSON.stringify(wrangler, null, 2)}\n`)
76
+ }
77
+
78
+ /** The driver per run (`dev` under `hamur dev` and the prerender), the preset checks, the import guard and `#hamur/blob/config`. */
79
+ export function setupBlob(options: ResolvedBlobOptions, hamur: HamurContext): void {
80
+ const { preset, dev } = hamur.options
81
+ const main = dev ? (options.dev ?? options.driver ?? { ...DEFAULT_FS }) : (options.driver ?? presetDefault(preset))
82
+ const prerender = dev ? main : (options.dev ?? main)
83
+
84
+ const protection = hamur.options.build.importProtection
85
+ const client = (protection.client ??= {})
86
+ ;(client.deny ??= []).push(SERVER)
87
+
88
+ const r = createResolver(import.meta.url)
89
+ const used = [...new Set([main, prerender].flatMap((driver) => (driver ? [driver.driver] : [])))]
90
+ addTemplate({
91
+ filename: "blob/config",
92
+ getContents: () =>
93
+ `export const config = ${JSON.stringify(main ?? null)};\nexport const prerender = ${JSON.stringify(prerender ?? null)};\nexport const preset = ${JSON.stringify(dev ? null : preset)};\nexport const bodyLimit = ${!dev && preset === "cloudflare" ? CLOUDFLARE_BODY_LIMIT : hamur.options.server.maxRequestBodySize};\nexport const drivers = {\n${used
94
+ .map(
95
+ (driver) =>
96
+ ` ${JSON.stringify(driver)}: () => import(${JSON.stringify(r.resolve(`../drivers/${driver}.ts`))}),`,
97
+ )
98
+ .join("\n")}\n};\n`,
99
+ })
100
+
101
+ hamur.hooks.hook("build:before", async () => {
102
+ if (!main)
103
+ throw new DiagnosticError(
104
+ "HAMUR_E5203",
105
+ `@hamur/blob needs blob.driver on the ${preset} preset: its file system does not keep files; use "s3"`,
106
+ )
107
+ if (dev) {
108
+ if (main.driver === "cloudflare-r2")
109
+ throw new DiagnosticError(
110
+ "HAMUR_E5204",
111
+ '@hamur/blob: the "cloudflare-r2" driver cannot run under hamur dev (it runs on: cloudflare); set blob.dev',
112
+ )
113
+ return
114
+ }
115
+ const { presets } = DRIVERS[main.driver]
116
+ if (!presets.includes(preset))
117
+ throw new DiagnosticError(
118
+ "HAMUR_E5205",
119
+ `@hamur/blob: the "${main.driver}" driver cannot run on the "${preset}" preset (it runs on: ${presets.join(", ")})`,
120
+ )
121
+ if (
122
+ main.driver === "cloudflare-r2" &&
123
+ !(await declaredR2Bindings(hamur.options.rootDir, hamur.options.cloudflare.env)).includes(main.binding) &&
124
+ !cloudflareId(hamur, main.binding)
125
+ ) {
126
+ throw new DiagnosticError(
127
+ "HAMUR_E5206",
128
+ `blob uses the cloudflare-r2 binding "${main.binding}", which the app's wrangler config does not declare; add an r2_buckets entry with binding "${main.binding}"`,
129
+ )
130
+ }
131
+ })
132
+
133
+ if (!dev && main?.driver === "cloudflare-r2") {
134
+ const { binding } = main
135
+ hamur.hooks.hook("build:done", () => writeR2Bucket(hamur, binding))
136
+ }
137
+ }