@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.
- package/LICENSE +22 -0
- package/README.md +51 -2
- package/dist/src/client/index.js +158 -0
- package/dist/src/index.js +220 -0
- package/dist/src/server/index.js +498 -0
- package/dist/types/src/build/setup.d.ts +7 -0
- package/dist/types/src/client/index.d.ts +28 -0
- package/dist/types/src/drivers/cloudflare-r2.d.ts +75 -0
- package/dist/types/src/drivers/fs.d.ts +14 -0
- package/dist/types/src/drivers/s3.d.ts +12 -0
- package/dist/types/src/drivers/suite.d.ts +9 -0
- package/dist/types/src/index.d.ts +2 -0
- package/dist/types/src/module.d.ts +3 -0
- package/dist/types/src/options.d.ts +19 -0
- package/dist/types/src/runtime/choose.d.ts +3 -0
- package/dist/types/src/runtime/driver.d.ts +29 -0
- package/dist/types/src/runtime/mime.d.ts +6 -0
- package/dist/types/src/runtime/multipart.d.ts +34 -0
- package/dist/types/src/runtime/store.d.ts +10 -0
- package/dist/types/src/server/blob.d.ts +3 -0
- package/dist/types/src/server/ensure.d.ts +22 -0
- package/dist/types/src/server/index.d.ts +12 -0
- package/dist/types/src/types.d.ts +152 -0
- package/package.json +32 -4
- package/src/build/setup.ts +137 -0
- package/src/client/index.ts +206 -0
- package/src/drivers/cloudflare-r2.ts +232 -0
- package/src/drivers/fs.ts +398 -0
- package/src/drivers/s3.ts +311 -0
- package/src/drivers/suite.ts +314 -0
- package/src/env.d.ts +16 -0
- package/src/index.ts +10 -0
- package/src/module.ts +11 -0
- package/src/options.ts +102 -0
- package/src/runtime/choose.ts +18 -0
- package/src/runtime/driver.ts +82 -0
- package/src/runtime/mime.ts +18 -0
- package/src/runtime/multipart.ts +319 -0
- package/src/runtime/store.ts +190 -0
- package/src/server/blob.ts +26 -0
- package/src/server/ensure.ts +52 -0
- package/src/server/index.ts +20 -0
- package/src/types.ts +155 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 productdevbook
|
|
4
|
+
Copyright (c) 2019 Material-UI SAS
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,52 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @hamur/blob
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The first-party blob module for [Hamur](https://github.com/productdevbook/hamur), a full-stack web framework for Bun. Files of any size with their type and metadata, `useBlob()` with `put`, `get`, `head`, `list`, `delete`, `serve` and `presign`, on the disk, on S3 (or any S3 API: R2, MinIO) or on R2 through its binding, on every preset. It has no dependency.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
bun add @hamur/blob
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Add it to `modules` in `hamur.config.ts`. Without a `blob` key the store is `.data/blob` on bun and node and the `BLOB` R2 binding on Cloudflare; vercel and netlify need `s3`:
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { defineConfig, env } from "hamur"
|
|
15
|
+
import blob from "@hamur/blob"
|
|
16
|
+
|
|
17
|
+
export default defineConfig({
|
|
18
|
+
modules: [blob],
|
|
19
|
+
blob: { driver: "s3", bucket: "uploads", secretAccessKey: env("S3_SECRET"), dev: { driver: "fs" } },
|
|
20
|
+
})
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`S3_SECRET` is declared in `app/env.ts` and read when the server starts.
|
|
24
|
+
|
|
25
|
+
## Example
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { defineHandler } from "hamur/server"
|
|
29
|
+
import { ensureBlob, useBlob } from "@hamur/blob/server"
|
|
30
|
+
|
|
31
|
+
export const upload = defineHandler({
|
|
32
|
+
method: "PUT",
|
|
33
|
+
route: "/avatars/:name",
|
|
34
|
+
raw: true,
|
|
35
|
+
async handler({ name }, { event }) {
|
|
36
|
+
const file = await event.request.blob()
|
|
37
|
+
ensureBlob(file, { maxSize: "2MB", types: ["image"] })
|
|
38
|
+
return useBlob().put(`avatars/${name}`, file, { addRandomSuffix: true })
|
|
39
|
+
},
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
export const avatar = defineHandler({
|
|
43
|
+
method: "GET",
|
|
44
|
+
route: "/avatars/**:pathname",
|
|
45
|
+
raw: true,
|
|
46
|
+
handler: ({ pathname }, { event }) => useBlob().serve(event, `avatars/${pathname.join("/")}`),
|
|
47
|
+
})
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Docs
|
|
51
|
+
|
|
52
|
+
[Documentation](https://docs.productdevbook.com/) and the [API reference](https://docs.productdevbook.com/api-reference/blob). MIT license.
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// packages/blob/src/client/index.ts
|
|
3
|
+
var MiB = 1024 * 1024;
|
|
4
|
+
var MIN_PART_SIZE = 5 * MiB;
|
|
5
|
+
var MAX_PART_SIZE = 5 * 1024 * MiB;
|
|
6
|
+
var MAX_PARTS = 1e4;
|
|
7
|
+
async function failure(response) {
|
|
8
|
+
const text = await response.text().catch(() => "");
|
|
9
|
+
let message = `${response.status} ${response.statusText}`.trim();
|
|
10
|
+
try {
|
|
11
|
+
const body = JSON.parse(text);
|
|
12
|
+
if (typeof body.message === "string" && body.message)
|
|
13
|
+
message = body.message;
|
|
14
|
+
} catch {}
|
|
15
|
+
return Object.assign(new Error(message), { status: response.status });
|
|
16
|
+
}
|
|
17
|
+
async function answer(response) {
|
|
18
|
+
if (!response.ok)
|
|
19
|
+
throw await failure(response);
|
|
20
|
+
return await response.json();
|
|
21
|
+
}
|
|
22
|
+
var json = (method, body, signal) => ({
|
|
23
|
+
method,
|
|
24
|
+
headers: { "content-type": "application/json" },
|
|
25
|
+
body: JSON.stringify(body),
|
|
26
|
+
...signal ? { signal } : {}
|
|
27
|
+
});
|
|
28
|
+
var retryable = (error) => {
|
|
29
|
+
const status = error.status;
|
|
30
|
+
return typeof status !== "number" || status >= 500;
|
|
31
|
+
};
|
|
32
|
+
function useMultipartUpload(url, options = {}) {
|
|
33
|
+
const { partSize = 10 * MiB, concurrency = 1 } = options;
|
|
34
|
+
if (!Number.isSafeInteger(partSize) || partSize < MIN_PART_SIZE || partSize > MAX_PART_SIZE) {
|
|
35
|
+
throw new RangeError(`useMultipartUpload partSize must be a whole number of bytes from 5 MiB to 5 GiB (got ${partSize})`);
|
|
36
|
+
}
|
|
37
|
+
if (!Number.isSafeInteger(concurrency) || concurrency < 1)
|
|
38
|
+
throw new RangeError(`useMultipartUpload concurrency must be a whole number from 1 (got ${concurrency})`);
|
|
39
|
+
const base = url.replace(/\/+$/, "");
|
|
40
|
+
const stepUrl = (step, query) => `${base}/${step}${query ? `?${new URLSearchParams(query)}` : ""}`;
|
|
41
|
+
return (file, fileOptions = {}) => {
|
|
42
|
+
const controller = new AbortController;
|
|
43
|
+
const { signal } = controller;
|
|
44
|
+
let created;
|
|
45
|
+
let aborting;
|
|
46
|
+
let completing = false;
|
|
47
|
+
const removeUpload = async () => {
|
|
48
|
+
const session = await created?.catch(() => {
|
|
49
|
+
return;
|
|
50
|
+
});
|
|
51
|
+
if (!session)
|
|
52
|
+
return;
|
|
53
|
+
const response = await fetch(stepUrl("abort", { pathname: session.pathname, uploadId: session.uploadId }), {
|
|
54
|
+
method: "DELETE"
|
|
55
|
+
});
|
|
56
|
+
await response.body?.cancel();
|
|
57
|
+
};
|
|
58
|
+
const sendPart = async (session, partNumber, part) => {
|
|
59
|
+
const target = { pathname: session.pathname, uploadId: session.uploadId };
|
|
60
|
+
if (!session.direct) {
|
|
61
|
+
const sent = await fetch(stepUrl("upload", { ...target, partNumber: String(partNumber) }), {
|
|
62
|
+
method: "PUT",
|
|
63
|
+
body: part,
|
|
64
|
+
signal
|
|
65
|
+
});
|
|
66
|
+
return (await answer(sent)).etag;
|
|
67
|
+
}
|
|
68
|
+
const { url: partUrl } = await answer(await fetch(stepUrl("upload"), json("POST", { ...target, partNumber, size: part.size }, signal)));
|
|
69
|
+
const stored = await fetch(partUrl, { method: "PUT", body: part, signal });
|
|
70
|
+
if (!stored.ok)
|
|
71
|
+
throw await failure(stored);
|
|
72
|
+
await stored.body?.cancel();
|
|
73
|
+
const etag = stored.headers.get("etag");
|
|
74
|
+
if (!etag)
|
|
75
|
+
throw new Error(`Storage answered part ${partNumber} without a readable ETag; expose ETag in the bucket's CORS rules`);
|
|
76
|
+
return etag;
|
|
77
|
+
};
|
|
78
|
+
const run = async () => {
|
|
79
|
+
const parts = Math.max(1, Math.ceil(file.size / partSize));
|
|
80
|
+
if (parts > MAX_PARTS)
|
|
81
|
+
throw new RangeError(`A file of ${file.size} bytes needs more than ${MAX_PARTS} parts of ${partSize} bytes; raise partSize`);
|
|
82
|
+
created = fetch(stepUrl("create"), json("POST", {
|
|
83
|
+
pathname: fileOptions.pathname ?? file.name,
|
|
84
|
+
...file.type ? { contentType: file.type } : {},
|
|
85
|
+
size: file.size,
|
|
86
|
+
partSize
|
|
87
|
+
})).then((response) => answer(response));
|
|
88
|
+
const session = await created;
|
|
89
|
+
signal.throwIfAborted();
|
|
90
|
+
const size = session.partSize;
|
|
91
|
+
const count = Math.max(1, Math.ceil(file.size / size));
|
|
92
|
+
const etags = new Array(count);
|
|
93
|
+
let next = 0;
|
|
94
|
+
let sent = 0;
|
|
95
|
+
const worker = async () => {
|
|
96
|
+
while (next < count) {
|
|
97
|
+
const partNumber = ++next;
|
|
98
|
+
const part = file.slice((partNumber - 1) * size, Math.min(file.size, partNumber * size));
|
|
99
|
+
etags[partNumber - 1] = await sendPart(session, partNumber, part).catch((error) => {
|
|
100
|
+
if (signal.aborted || !retryable(error))
|
|
101
|
+
throw error;
|
|
102
|
+
return sendPart(session, partNumber, part);
|
|
103
|
+
});
|
|
104
|
+
sent += part.size;
|
|
105
|
+
fileOptions.onProgress?.(sent, file.size);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
try {
|
|
109
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, count) }, worker));
|
|
110
|
+
} catch (error) {
|
|
111
|
+
controller.abort();
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
signal.throwIfAborted();
|
|
115
|
+
completing = true;
|
|
116
|
+
const body = {
|
|
117
|
+
pathname: session.pathname,
|
|
118
|
+
uploadId: session.uploadId,
|
|
119
|
+
parts: etags.map((etag, at) => ({ partNumber: at + 1, etag }))
|
|
120
|
+
};
|
|
121
|
+
const object = await answer(await fetch(stepUrl("complete"), json("POST", body)));
|
|
122
|
+
return { ...object, uploadedAt: new Date(object.uploadedAt) };
|
|
123
|
+
};
|
|
124
|
+
const completed = run().catch(async (error) => {
|
|
125
|
+
if (aborting) {
|
|
126
|
+
await aborting;
|
|
127
|
+
throw new DOMException("The upload was aborted", "AbortError");
|
|
128
|
+
}
|
|
129
|
+
if (!completing)
|
|
130
|
+
await (aborting = removeUpload().catch(() => {
|
|
131
|
+
return;
|
|
132
|
+
}));
|
|
133
|
+
throw error;
|
|
134
|
+
});
|
|
135
|
+
return {
|
|
136
|
+
completed,
|
|
137
|
+
abort() {
|
|
138
|
+
if (completing) {
|
|
139
|
+
return completed.then(() => {
|
|
140
|
+
return;
|
|
141
|
+
}, () => {
|
|
142
|
+
return;
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
if (!aborting) {
|
|
146
|
+
aborting = removeUpload().catch(() => {
|
|
147
|
+
return;
|
|
148
|
+
});
|
|
149
|
+
controller.abort();
|
|
150
|
+
}
|
|
151
|
+
return aborting;
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
export {
|
|
157
|
+
useMultipartUpload
|
|
158
|
+
};
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// packages/blob/src/module.ts
|
|
2
|
+
import { defineModule } from "hamur/kit";
|
|
3
|
+
|
|
4
|
+
// packages/blob/src/build/setup.ts
|
|
5
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { DiagnosticError as DiagnosticError2, addTemplate, createResolver } from "hamur/kit";
|
|
8
|
+
|
|
9
|
+
// packages/blob/src/options.ts
|
|
10
|
+
import { DiagnosticError, isEnvRef } from "hamur/kit";
|
|
11
|
+
var DRIVERS = {
|
|
12
|
+
fs: { presets: ["bun", "node", "static"], keys: ["base"] },
|
|
13
|
+
s3: {
|
|
14
|
+
presets: ["bun", "node", "static", "cloudflare", "vercel", "netlify"],
|
|
15
|
+
keys: [
|
|
16
|
+
"bucket",
|
|
17
|
+
"region",
|
|
18
|
+
"endpoint",
|
|
19
|
+
"accessKeyId",
|
|
20
|
+
"secretAccessKey",
|
|
21
|
+
"sessionToken",
|
|
22
|
+
"virtualHostedStyle",
|
|
23
|
+
"base"
|
|
24
|
+
]
|
|
25
|
+
},
|
|
26
|
+
"cloudflare-r2": { presets: ["cloudflare"], keys: ["binding", "base"] }
|
|
27
|
+
};
|
|
28
|
+
var SECRETS = ["bucket", "region", "endpoint", "accessKeyId", "secretAccessKey", "sessionToken"];
|
|
29
|
+
var BINDING = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
30
|
+
var DEFAULT_FS = { driver: "fs", base: ".data/blob" };
|
|
31
|
+
var DEFAULT_R2 = {
|
|
32
|
+
driver: "cloudflare-r2",
|
|
33
|
+
binding: "BLOB",
|
|
34
|
+
base: ""
|
|
35
|
+
};
|
|
36
|
+
function fail(message) {
|
|
37
|
+
throw new DiagnosticError("HAMUR_E5201", message);
|
|
38
|
+
}
|
|
39
|
+
function shown(value) {
|
|
40
|
+
if (Array.isArray(value))
|
|
41
|
+
return "an array";
|
|
42
|
+
if (typeof value === "function")
|
|
43
|
+
return "a function";
|
|
44
|
+
if (value === undefined)
|
|
45
|
+
return "undefined";
|
|
46
|
+
return JSON.stringify(value);
|
|
47
|
+
}
|
|
48
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
49
|
+
var isSecret = (value) => typeof value === "string" && value !== "" || isEnvRef(value);
|
|
50
|
+
function resolveDriver(at, options) {
|
|
51
|
+
const driver = options.driver;
|
|
52
|
+
if (typeof driver !== "string" || !Object.hasOwn(DRIVERS, driver))
|
|
53
|
+
fail(`${at}.driver must be "fs", "s3" or "cloudflare-r2" (got ${shown(driver)})`);
|
|
54
|
+
const { keys } = DRIVERS[driver];
|
|
55
|
+
for (const key of Object.keys(options)) {
|
|
56
|
+
if (key !== "driver" && key !== "dev" && !keys.includes(key))
|
|
57
|
+
fail(`${at} has no ${JSON.stringify(key)} on the "${driver}" driver (it takes: ${keys.join(", ")})`);
|
|
58
|
+
}
|
|
59
|
+
const base = options.base;
|
|
60
|
+
if (base !== undefined && typeof base !== "string")
|
|
61
|
+
fail(`${at}.base must be a string (got ${shown(base)})`);
|
|
62
|
+
if (driver === "fs") {
|
|
63
|
+
if (base === "")
|
|
64
|
+
fail(`${at}.base must be a directory (got "")`);
|
|
65
|
+
return { driver, base: base ?? DEFAULT_FS.base };
|
|
66
|
+
}
|
|
67
|
+
if (driver === "cloudflare-r2") {
|
|
68
|
+
const binding = options.binding ?? DEFAULT_R2.binding;
|
|
69
|
+
if (typeof binding !== "string" || !BINDING.test(binding))
|
|
70
|
+
fail(`${at}.binding must be a binding name (got ${shown(binding)})`);
|
|
71
|
+
return { driver, binding, base: base ?? "" };
|
|
72
|
+
}
|
|
73
|
+
const resolved = { driver: "s3", base: base ?? "" };
|
|
74
|
+
for (const key of SECRETS) {
|
|
75
|
+
const value = options[key];
|
|
76
|
+
if (value === undefined)
|
|
77
|
+
continue;
|
|
78
|
+
if (!isSecret(value))
|
|
79
|
+
fail(`${at}.${key} must be a string or env("NAME") (got ${shown(value)})`);
|
|
80
|
+
resolved[key] = value;
|
|
81
|
+
}
|
|
82
|
+
const hosted = options.virtualHostedStyle;
|
|
83
|
+
if (hosted !== undefined && typeof hosted !== "boolean")
|
|
84
|
+
fail(`${at}.virtualHostedStyle must be a boolean (got ${shown(hosted)})`);
|
|
85
|
+
if (hosted !== undefined)
|
|
86
|
+
resolved.virtualHostedStyle = hosted;
|
|
87
|
+
return resolved;
|
|
88
|
+
}
|
|
89
|
+
function resolveOptions(input) {
|
|
90
|
+
if (input === undefined)
|
|
91
|
+
return {};
|
|
92
|
+
if (!isObject(input))
|
|
93
|
+
fail(`blob must be an object (got ${shown(input)})`);
|
|
94
|
+
const resolved = {};
|
|
95
|
+
if (input.dev !== undefined) {
|
|
96
|
+
if (!isObject(input.dev))
|
|
97
|
+
fail(`blob.dev must be an object (got ${shown(input.dev)})`);
|
|
98
|
+
if (input.dev.dev !== undefined)
|
|
99
|
+
fail("blob.dev cannot hold a dev of its own");
|
|
100
|
+
resolved.dev = resolveDriver("blob.dev", input.dev);
|
|
101
|
+
}
|
|
102
|
+
if (Object.keys(input).some((key) => key !== "dev"))
|
|
103
|
+
resolved.driver = resolveDriver("blob", input);
|
|
104
|
+
return resolved;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// packages/blob/src/build/setup.ts
|
|
108
|
+
var SERVER = "@hamur/blob/server";
|
|
109
|
+
var WRANGLER_FILES = ["wrangler.json", "wrangler.jsonc"];
|
|
110
|
+
var CLOUDFLARE_BODY_LIMIT = 1e8;
|
|
111
|
+
function presetDefault(preset) {
|
|
112
|
+
if (preset === "cloudflare")
|
|
113
|
+
return { ...DEFAULT_R2 };
|
|
114
|
+
if (DRIVERS.fs.presets.includes(preset))
|
|
115
|
+
return { ...DEFAULT_FS };
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
119
|
+
async function declaredR2Bindings(rootDir, env) {
|
|
120
|
+
let config = {};
|
|
121
|
+
for (const name of WRANGLER_FILES) {
|
|
122
|
+
const file = Bun.file(join(rootDir, name));
|
|
123
|
+
if (!await file.exists())
|
|
124
|
+
continue;
|
|
125
|
+
const parsed = Bun.JSONC.parse(await file.text());
|
|
126
|
+
if (isObject2(parsed))
|
|
127
|
+
config = parsed;
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
const envs = isObject2(config.env) ? config.env : {};
|
|
131
|
+
const chosen = env !== undefined && isObject2(envs[env]) ? { ...config, ...envs[env] } : config;
|
|
132
|
+
const buckets = Array.isArray(chosen.r2_buckets) ? chosen.r2_buckets : [];
|
|
133
|
+
return buckets.flatMap((bucket) => isObject2(bucket) && typeof bucket.binding === "string" ? [bucket.binding] : []);
|
|
134
|
+
}
|
|
135
|
+
var idVariable = (binding) => `HAMUR_CF_${binding.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}_ID`;
|
|
136
|
+
var cloudflareId = (hamur, binding) => hamur.options.cloudflare.bindings?.[binding]?.id || process.env[idVariable(binding)] || undefined;
|
|
137
|
+
function bindingKey(config, name) {
|
|
138
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
139
|
+
const names = (value, inDurableObjects) => {
|
|
140
|
+
if (Array.isArray(value))
|
|
141
|
+
return value.some((item) => names(item, inDurableObjects));
|
|
142
|
+
if (!isRecord(value))
|
|
143
|
+
return false;
|
|
144
|
+
if (value.binding === name || inDurableObjects && value.name === name)
|
|
145
|
+
return true;
|
|
146
|
+
return Object.values(value).some((item) => names(item, inDurableObjects));
|
|
147
|
+
};
|
|
148
|
+
for (const [key, value] of Object.entries(config)) {
|
|
149
|
+
if (key === "env")
|
|
150
|
+
continue;
|
|
151
|
+
if (key === "vars" ? isRecord(value) && Object.hasOwn(value, name) : names(value, key === "durable_objects"))
|
|
152
|
+
return key;
|
|
153
|
+
}
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
async function writeR2Bucket(hamur, binding) {
|
|
157
|
+
const id = cloudflareId(hamur, binding);
|
|
158
|
+
const file = join(hamur.options.outputDir, "wrangler.json");
|
|
159
|
+
const wrangler = JSON.parse(await readFile(file, "utf8"));
|
|
160
|
+
if (!id || wrangler.r2_buckets?.some((bucket) => bucket.binding === binding))
|
|
161
|
+
return;
|
|
162
|
+
const taken = bindingKey(wrangler, binding);
|
|
163
|
+
if (taken)
|
|
164
|
+
throw new DiagnosticError2("HAMUR_E5202", `blob.binding ${JSON.stringify(binding)} is already the ${taken} binding of the app's wrangler config; set blob.binding to another name`);
|
|
165
|
+
(wrangler.r2_buckets ??= []).push({ binding, bucket_name: id });
|
|
166
|
+
await writeFile(file, `${JSON.stringify(wrangler, null, 2)}
|
|
167
|
+
`);
|
|
168
|
+
}
|
|
169
|
+
function setupBlob(options, hamur) {
|
|
170
|
+
const { preset, dev } = hamur.options;
|
|
171
|
+
const main = dev ? options.dev ?? options.driver ?? { ...DEFAULT_FS } : options.driver ?? presetDefault(preset);
|
|
172
|
+
const prerender = dev ? main : options.dev ?? main;
|
|
173
|
+
const protection = hamur.options.build.importProtection;
|
|
174
|
+
const client = protection.client ??= {};
|
|
175
|
+
(client.deny ??= []).push(SERVER);
|
|
176
|
+
const r = createResolver(new URL("../../src/build/setup.ts", import.meta.url).href);
|
|
177
|
+
const used = [...new Set([main, prerender].flatMap((driver) => driver ? [driver.driver] : []))];
|
|
178
|
+
addTemplate({
|
|
179
|
+
filename: "blob/config",
|
|
180
|
+
getContents: () => `export const config = ${JSON.stringify(main ?? null)};
|
|
181
|
+
export const prerender = ${JSON.stringify(prerender ?? null)};
|
|
182
|
+
export const preset = ${JSON.stringify(dev ? null : preset)};
|
|
183
|
+
export const bodyLimit = ${!dev && preset === "cloudflare" ? CLOUDFLARE_BODY_LIMIT : hamur.options.server.maxRequestBodySize};
|
|
184
|
+
export const drivers = {
|
|
185
|
+
${used.map((driver) => ` ${JSON.stringify(driver)}: () => import(${JSON.stringify(r.resolve(`../drivers/${driver}.ts`))}),`).join(`
|
|
186
|
+
`)}
|
|
187
|
+
};
|
|
188
|
+
`
|
|
189
|
+
});
|
|
190
|
+
hamur.hooks.hook("build:before", async () => {
|
|
191
|
+
if (!main)
|
|
192
|
+
throw new DiagnosticError2("HAMUR_E5203", `@hamur/blob needs blob.driver on the ${preset} preset: its file system does not keep files; use "s3"`);
|
|
193
|
+
if (dev) {
|
|
194
|
+
if (main.driver === "cloudflare-r2")
|
|
195
|
+
throw new DiagnosticError2("HAMUR_E5204", '@hamur/blob: the "cloudflare-r2" driver cannot run under hamur dev (it runs on: cloudflare); set blob.dev');
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const { presets } = DRIVERS[main.driver];
|
|
199
|
+
if (!presets.includes(preset))
|
|
200
|
+
throw new DiagnosticError2("HAMUR_E5205", `@hamur/blob: the "${main.driver}" driver cannot run on the "${preset}" preset (it runs on: ${presets.join(", ")})`);
|
|
201
|
+
if (main.driver === "cloudflare-r2" && !(await declaredR2Bindings(hamur.options.rootDir, hamur.options.cloudflare.env)).includes(main.binding) && !cloudflareId(hamur, main.binding)) {
|
|
202
|
+
throw new DiagnosticError2("HAMUR_E5206", `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}"`);
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
if (!dev && main?.driver === "cloudflare-r2") {
|
|
206
|
+
const { binding } = main;
|
|
207
|
+
hamur.hooks.hook("build:done", () => writeR2Bucket(hamur, binding));
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// packages/blob/src/module.ts
|
|
212
|
+
var module_default = defineModule({
|
|
213
|
+
meta: { name: "blob", configKey: "blob" },
|
|
214
|
+
setup(input, hamur) {
|
|
215
|
+
setupBlob(resolveOptions(input), hamur);
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
export {
|
|
219
|
+
module_default as default
|
|
220
|
+
};
|