@benjavicente/convex-r2 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 +21 -0
- package/README.md +175 -2
- package/dist/browser/index.d.ts +33 -0
- package/dist/browser/index.js +57 -0
- package/dist/client/index.d.ts +116 -0
- package/dist/client/index.js +72 -0
- package/dist/component/_generated/api.d.ts +39 -0
- package/dist/component/_generated/api.js +30 -0
- package/dist/component/_generated/component.d.ts +87 -0
- package/dist/component/_generated/component.js +10 -0
- package/dist/component/_generated/dataModel.d.ts +45 -0
- package/dist/component/_generated/dataModel.js +10 -0
- package/dist/component/_generated/server.d.ts +136 -0
- package/dist/component/_generated/server.js +79 -0
- package/dist/component/convex.config.d.ts +8 -0
- package/dist/component/convex.config.js +11 -0
- package/dist/component/r2.d.ts +39 -0
- package/dist/component/r2.js +77 -0
- package/dist/component/schema.d.ts +37 -0
- package/dist/component/schema.js +20 -0
- package/dist/component/sigv4.d.ts +23 -0
- package/dist/component/sigv4.js +63 -0
- package/dist/component/uploads.d.ts +152 -0
- package/dist/component/uploads.js +305 -0
- package/dist/component/validators.d.ts +105 -0
- package/dist/component/validators.js +26 -0
- package/package.json +62 -3
- package/src/browser/index.ts +86 -0
- package/src/client/index.ts +151 -0
- package/src/component/_generated/api.ts +56 -0
- package/src/component/_generated/component.ts +112 -0
- package/src/component/_generated/dataModel.ts +60 -0
- package/src/component/_generated/server.ts +173 -0
- package/src/component/convex.config.ts +12 -0
- package/src/component/r2.ts +90 -0
- package/src/component/schema.ts +23 -0
- package/src/component/sigv4.ts +102 -0
- package/src/component/uploads.ts +333 -0
- package/src/component/validators.ts +36 -0
- package/src/test.ts +14 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Benjamín Vicente
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,176 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @benjavicente/convex-r2
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Uploads to Cloudflare R2 from a Convex app, where every object belongs to a row the server created first.
|
|
4
|
+
|
|
5
|
+
- The app defines one request mutation per upload type. It authorizes the user, then asks the component for a URL.
|
|
6
|
+
- The component generates the key (`<prefix>/<upload id>`). It signs a 5-minute PUT bound to the declared `Content-Type`, `Content-Length` and SHA-256, plus `If-None-Match: *`, so the PUT can't overwrite an existing object.
|
|
7
|
+
- After the PUT, the server checks the real object against the request. On a match, it runs the app's `onConfirm` mutation with `{ upload, context }` and marks the upload ready, in one transaction. On a mismatch, or when `onConfirm` throws, it deletes both the object and the request at once.
|
|
8
|
+
- Requests that are never confirmed are checked after they expire: they are confirmed if the object matches, and deleted otherwise.
|
|
9
|
+
- Credentials come from the component's env vars and never become function arguments. There are no runtime dependencies (SigV4 on WebCrypto).
|
|
10
|
+
|
|
11
|
+
## Setup
|
|
12
|
+
|
|
13
|
+
1. Create an R2 API token with **Object Read & Write**, scoped to the buckets the app uses (one Cloudflare account per component instance).
|
|
14
|
+
2. Allow the browser's PUT in each bucket's CORS policy:
|
|
15
|
+
|
|
16
|
+
```json
|
|
17
|
+
[
|
|
18
|
+
{
|
|
19
|
+
"AllowedOrigins": ["https://app.example.com"],
|
|
20
|
+
"AllowedMethods": ["PUT"],
|
|
21
|
+
"AllowedHeaders": ["content-type", "if-none-match", "x-amz-checksum-sha256"]
|
|
22
|
+
}
|
|
23
|
+
]
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
3. Install the component and bind its env vars to the app's, by reference, so the values stay in the deployment's env:
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
// convex/convex.config.ts
|
|
30
|
+
import r2 from "@benjavicente/convex-r2/convex.config.js";
|
|
31
|
+
import { defineApp } from "convex/server";
|
|
32
|
+
import { v } from "convex/values";
|
|
33
|
+
|
|
34
|
+
const app = defineApp({
|
|
35
|
+
env: {
|
|
36
|
+
R2_ACCOUNT_ID: v.string(),
|
|
37
|
+
R2_ACCESS_KEY_ID: v.string(),
|
|
38
|
+
R2_SECRET_ACCESS_KEY: v.string(),
|
|
39
|
+
R2_BUCKET: v.string(),
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
app.use(r2, {
|
|
43
|
+
env: {
|
|
44
|
+
R2_ACCOUNT_ID: app.env.R2_ACCOUNT_ID,
|
|
45
|
+
R2_ACCESS_KEY_ID: app.env.R2_ACCESS_KEY_ID,
|
|
46
|
+
R2_SECRET_ACCESS_KEY: app.env.R2_SECRET_ACCESS_KEY,
|
|
47
|
+
R2_BUCKET: app.env.R2_BUCKET, // optional: the default bucket
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
export default app;
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
npx convex env set R2_ACCOUNT_ID ... # and the other three
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Server
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { fileValidator, R2, type RequestedUpload, uploadValidator } from "@benjavicente/convex-r2";
|
|
61
|
+
|
|
62
|
+
const r2 = new R2(components.r2); // or new R2(components.r2, { bucket: "other" })
|
|
63
|
+
|
|
64
|
+
export const requestUpload = mutation({
|
|
65
|
+
args: { companyId: v.id("companies"), ...fileValidator.fields },
|
|
66
|
+
// The annotation breaks the type cycle through `internal`.
|
|
67
|
+
handler: async (ctx, { companyId, ...file }): Promise<RequestedUpload> => {
|
|
68
|
+
const user = await currentUser(ctx);
|
|
69
|
+
await assertCanUploadTo(ctx, user, companyId);
|
|
70
|
+
// Throws a ConvexError, whose message the client sees, when the file breaks the rules.
|
|
71
|
+
return r2.requestUpload(ctx, {
|
|
72
|
+
keyPrefix: `companies/${companyId}`,
|
|
73
|
+
file,
|
|
74
|
+
rules: { maxSize: 20 * 1024 * 1024, contentTypes: ["application/pdf"] },
|
|
75
|
+
onConfirm: internal.companyDocuments.onUploaded,
|
|
76
|
+
context: { companyId, uploadedBy: user._id }, // checked against onUploaded's `context`
|
|
77
|
+
});
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
export const onUploaded = internalMutation({
|
|
82
|
+
args: {
|
|
83
|
+
upload: uploadValidator,
|
|
84
|
+
context: v.object({ companyId: v.id("companies"), uploadedBy: v.id("users") }),
|
|
85
|
+
},
|
|
86
|
+
handler: async (ctx, { upload, context }) => {
|
|
87
|
+
// Throwing rejects the upload and deletes it. The message of a
|
|
88
|
+
// ConvexError("...") reaches the client as the rejection reason. Any other
|
|
89
|
+
// error rejects it too, including a missing function after a rename, so
|
|
90
|
+
// keep this name while uploads are pending.
|
|
91
|
+
await ctx.db.insert("companyDocuments", {
|
|
92
|
+
...context,
|
|
93
|
+
uploadId: upload.uploadId,
|
|
94
|
+
name: upload.name,
|
|
95
|
+
});
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// Needs no authorization: it only compares R2 with the stored request.
|
|
100
|
+
export const confirmUpload = action({
|
|
101
|
+
args: { uploadId: v.string() },
|
|
102
|
+
handler: (ctx, { uploadId }) => r2.confirm(ctx, uploadId),
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
From an action, `r2.store` uploads bytes the server already has. It goes through the same request, PUT and confirm steps, so `onConfirm` and `context` work the same, and it returns the same result as `confirm`:
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
export const writeNote = action({
|
|
110
|
+
args: {},
|
|
111
|
+
handler: async (ctx): Promise<ConfirmResult> => {
|
|
112
|
+
const user = await ctx.runQuery(api.users.me, {});
|
|
113
|
+
if (!user) throw new ConvexError("Sign in first");
|
|
114
|
+
return r2.store(ctx, {
|
|
115
|
+
keyPrefix: `notes/${user._id}`,
|
|
116
|
+
file: new Blob(["# Hello"], { type: "text/markdown" }),
|
|
117
|
+
name: "hello.md",
|
|
118
|
+
onConfirm: internal.notes.onUploaded,
|
|
119
|
+
context: { ownerId: user._id },
|
|
120
|
+
});
|
|
121
|
+
},
|
|
122
|
+
});
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Also available:
|
|
126
|
+
|
|
127
|
+
- `r2.get(ctx, uploadId)` returns a ready upload with its Cloudflare dashboard link, or null. Pending uploads stay internal: the app hears about a file through `onConfirm`.
|
|
128
|
+
- `r2.getUrl(ctx, uploadId, { expiresIn, disposition })` returns a signed GET that serves the file under its name, for ready uploads only.
|
|
129
|
+
|
|
130
|
+
> A Convex query's result stays cached until the data it read changes, not until the URL inside it expires, so a subscribed page can keep showing an expired URL. Sign from a mutation or action when the URL must be fresh, or use an `expiresIn` longer than the page lives.
|
|
131
|
+
|
|
132
|
+
- `r2.delete(ctx, uploadId)` deletes the upload and its object.
|
|
133
|
+
|
|
134
|
+
## Browser
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
import { uploadFile } from "@benjavicente/convex-r2/browser";
|
|
138
|
+
|
|
139
|
+
const { confirmed } = await uploadFile(file, {
|
|
140
|
+
request: (info) => convex.mutation(api.companyDocuments.requestUpload, { companyId, ...info }),
|
|
141
|
+
confirm: (uploadId) => convex.action(api.companyDocuments.confirmUpload, { uploadId }), // optional
|
|
142
|
+
onProgress: ({ loaded, total }) => {},
|
|
143
|
+
signal, // AbortSignal
|
|
144
|
+
});
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
`uploadFile` hashes the file (reading it into memory), PUTs it with XHR for progress, then calls `confirm`. Without `confirm`, the upload is confirmed after the URL expires plus 10 minutes of grace.
|
|
148
|
+
|
|
149
|
+
## Compared with `@convex-dev/r2`
|
|
150
|
+
|
|
151
|
+
Measured against version 0.10.4.
|
|
152
|
+
|
|
153
|
+
| | `@convex-dev/r2` | this package |
|
|
154
|
+
| ------------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
|
|
155
|
+
| Object key | A UUID, or a custom key from your mutation. Uploading to an existing key overwrites it. | Always `<prefix>/<upload id>`, generated by the component. `If-None-Match: *` refuses a second upload to the same key. |
|
|
156
|
+
| What the upload URL is bound to | Bucket and key, for 15 minutes. | Key, `Content-Type`, `Content-Length` and SHA-256, for 5 minutes. |
|
|
157
|
+
| When your callback runs | `onUpload(ctx, bucket, key)` runs when the client calls `syncMetadata`, before anything reads the object. | `onConfirm({ upload, context })` runs only after the stored object matches the request, in the transaction that marks it ready. |
|
|
158
|
+
| Data for the callback | The key only. | A typed `context` set when the URL is requested, checked against `onConfirm`'s arguments. |
|
|
159
|
+
| Refusing an upload | Throw in `checkUpload`; the object stays in the bucket. | Throw in `onConfirm`; the object and its request are deleted, and the `ConvexError` message is returned. |
|
|
160
|
+
| Uploads never confirmed | Stay in the bucket. | Checked after the URL expires: confirmed if they match, deleted otherwise. |
|
|
161
|
+
| Credentials | App env vars, passed to the component as function arguments, so scheduled jobs store them. | Component env vars bound by reference. They are never function arguments. |
|
|
162
|
+
| Browser | React and Svelte hooks. | `uploadFile`, framework-agnostic, with hashing, progress and `AbortSignal`. |
|
|
163
|
+
| Signing | AWS SDK v3. | About 100 lines of SigV4 on WebCrypto, tested against the AWS SDK's signer. |
|
|
164
|
+
|
|
165
|
+
`@convex-dev/r2` also lists every object's metadata, and accepts custom keys and per-bucket credentials. Here the app's own tables reference their uploads, so listing is the app's own query; keys are always server-generated; and one component instance uses one Cloudflare account.
|
|
166
|
+
|
|
167
|
+
### Size
|
|
168
|
+
|
|
169
|
+
Each figure is the bundle growth over a control module with one trivial function. The bundles are built with esbuild settings that reproduce Convex's bundler: renamed identifiers, whitespace kept, external source maps. A real Convex push of the `@convex-dev/r2` app side came out slightly larger: 583 KB of JS and 703 KB of maps.
|
|
170
|
+
|
|
171
|
+
| Added by the package | `@convex-dev/r2` | this package |
|
|
172
|
+
| -------------------------------------- | ------------------------ | -------------------------- |
|
|
173
|
+
| App functions: JS / gzip / source maps | 540 / 131 / 681 KB | 2.9 / 0.9 / 2.8 KB |
|
|
174
|
+
| Component functions: JS / gzip / maps | 472 / 114 / 619 KB | 20 / 4.9 / 23 KB |
|
|
175
|
+
| Browser helper (min / gzip) | React hook: 0.6 / 0.4 KB | `uploadFile`: 1.3 / 0.7 KB |
|
|
176
|
+
| `node_modules` | ~22 MB, 17 packages | no dependencies |
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { FileInfo } from "../component/validators.js";
|
|
2
|
+
export type { FileInfo };
|
|
3
|
+
/** What the app's request mutation returns (from `R2.requestUpload`). */
|
|
4
|
+
export type UploadTarget = {
|
|
5
|
+
uploadId: string;
|
|
6
|
+
url: string;
|
|
7
|
+
headers: Record<string, string>;
|
|
8
|
+
};
|
|
9
|
+
export type UploadOptions<Target extends UploadTarget, Confirmed> = {
|
|
10
|
+
/** Calls the app's request mutation for this upload type. */
|
|
11
|
+
request: (file: FileInfo) => Promise<Target>;
|
|
12
|
+
/** Calls the app's confirm action. Without it, the server confirms after the URL expires. */
|
|
13
|
+
confirm?: (uploadId: string) => Promise<Confirmed>;
|
|
14
|
+
onProgress?: (progress: {
|
|
15
|
+
loaded: number;
|
|
16
|
+
total: number;
|
|
17
|
+
}) => void;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
};
|
|
20
|
+
export declare class UploadError extends Error {
|
|
21
|
+
readonly status: number;
|
|
22
|
+
readonly body: string;
|
|
23
|
+
constructor(message: string, status: number, body: string);
|
|
24
|
+
}
|
|
25
|
+
export declare function sha256Hex(blob: Blob): Promise<string>;
|
|
26
|
+
/**
|
|
27
|
+
* Hashes the file, gets a URL from `request`, PUTs the file with progress,
|
|
28
|
+
* then runs `confirm` if given.
|
|
29
|
+
*/
|
|
30
|
+
export declare function uploadFile<Target extends UploadTarget, Confirmed = undefined>(file: File, options: UploadOptions<Target, Confirmed>): Promise<{
|
|
31
|
+
target: Target;
|
|
32
|
+
confirmed: Confirmed | undefined;
|
|
33
|
+
}>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export class UploadError extends Error {
|
|
2
|
+
status;
|
|
3
|
+
body;
|
|
4
|
+
constructor(message, status, body) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.status = status;
|
|
7
|
+
this.body = body;
|
|
8
|
+
this.name = "UploadError";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export async function sha256Hex(blob) {
|
|
12
|
+
const digest = await crypto.subtle.digest("SHA-256", await blob.arrayBuffer());
|
|
13
|
+
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Hashes the file, gets a URL from `request`, PUTs the file with progress,
|
|
17
|
+
* then runs `confirm` if given.
|
|
18
|
+
*/
|
|
19
|
+
export async function uploadFile(file, options) {
|
|
20
|
+
const { signal } = options;
|
|
21
|
+
signal?.throwIfAborted();
|
|
22
|
+
const info = {
|
|
23
|
+
name: file.name,
|
|
24
|
+
contentType: file.type || "application/octet-stream",
|
|
25
|
+
size: file.size,
|
|
26
|
+
sha256: await sha256Hex(file),
|
|
27
|
+
};
|
|
28
|
+
signal?.throwIfAborted();
|
|
29
|
+
const target = await options.request(info);
|
|
30
|
+
signal?.throwIfAborted();
|
|
31
|
+
await put(file, target, options);
|
|
32
|
+
const confirmed = await options.confirm?.(target.uploadId);
|
|
33
|
+
return { target, confirmed };
|
|
34
|
+
}
|
|
35
|
+
function put(file, target, { onProgress, signal }) {
|
|
36
|
+
return new Promise((resolve, reject) => {
|
|
37
|
+
const xhr = new XMLHttpRequest();
|
|
38
|
+
xhr.open("PUT", target.url);
|
|
39
|
+
for (const [name, value] of Object.entries(target.headers))
|
|
40
|
+
xhr.setRequestHeader(name, value);
|
|
41
|
+
if (onProgress) {
|
|
42
|
+
xhr.upload.onprogress = (event) => onProgress({ loaded: event.loaded, total: event.total });
|
|
43
|
+
}
|
|
44
|
+
const onAbort = () => xhr.abort();
|
|
45
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
46
|
+
const done = (fn) => {
|
|
47
|
+
signal?.removeEventListener("abort", onAbort);
|
|
48
|
+
fn();
|
|
49
|
+
};
|
|
50
|
+
xhr.onload = () => done(() => xhr.status >= 200 && xhr.status < 300
|
|
51
|
+
? resolve()
|
|
52
|
+
: reject(new UploadError(`Upload failed: ${xhr.status}`, xhr.status, xhr.responseText)));
|
|
53
|
+
xhr.onerror = () => done(() => reject(new UploadError("Upload failed: network error", 0, "")));
|
|
54
|
+
xhr.onabort = () => done(() => reject(signal?.reason ?? new DOMException("Aborted", "AbortError")));
|
|
55
|
+
xhr.send(file);
|
|
56
|
+
});
|
|
57
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { type FunctionReference, type GenericActionCtx, type GenericDataModel, type GenericMutationCtx, type GenericQueryCtx } from "convex/server";
|
|
2
|
+
import type { ComponentApi } from "../component/_generated/component.js";
|
|
3
|
+
import type { ConfirmResult, FileInfo, Upload, UploadRules } from "../component/validators.js";
|
|
4
|
+
export { fileValidator, uploadValidator, type ConfirmResult, type FileInfo, type Upload, type UploadRules, } from "../component/validators.js";
|
|
5
|
+
type RunQueryCtx = Pick<GenericQueryCtx<GenericDataModel>, "runQuery">;
|
|
6
|
+
type RunMutationCtx = Pick<GenericMutationCtx<GenericDataModel>, "runMutation">;
|
|
7
|
+
type RunActionCtx = Pick<GenericActionCtx<GenericDataModel>, "runAction">;
|
|
8
|
+
type StoreCtx = Pick<GenericActionCtx<GenericDataModel>, "runMutation" | "runAction">;
|
|
9
|
+
/** The app's mutation that runs when an upload is confirmed. */
|
|
10
|
+
export type OnConfirm<Context> = FunctionReference<"mutation", "internal", {
|
|
11
|
+
upload: Upload;
|
|
12
|
+
context: Context;
|
|
13
|
+
}>;
|
|
14
|
+
export type RequestUploadArgs<Context> = {
|
|
15
|
+
/** The object key becomes `<keyPrefix>/<upload id>`. */
|
|
16
|
+
keyPrefix: string;
|
|
17
|
+
file: FileInfo;
|
|
18
|
+
rules: UploadRules;
|
|
19
|
+
onConfirm: OnConfirm<Context>;
|
|
20
|
+
/** Passed to `onConfirm`; must match its `context` argument. */
|
|
21
|
+
context: NoInfer<Context>;
|
|
22
|
+
};
|
|
23
|
+
export type StoreArgs<Context> = {
|
|
24
|
+
/** The object key becomes `<keyPrefix>/<upload id>`. */
|
|
25
|
+
keyPrefix: string;
|
|
26
|
+
file: Blob;
|
|
27
|
+
name: string;
|
|
28
|
+
/** Defaults to the blob's type. */
|
|
29
|
+
contentType?: string;
|
|
30
|
+
onConfirm: OnConfirm<Context>;
|
|
31
|
+
/** Passed to `onConfirm`; must match its `context` argument. */
|
|
32
|
+
context: NoInfer<Context>;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* What `requestUpload` returns. Annotate the app's request handler with it:
|
|
36
|
+
* the handler references `internal.*`, which TypeScript can't infer through.
|
|
37
|
+
*/
|
|
38
|
+
export type RequestedUpload = {
|
|
39
|
+
uploadId: string;
|
|
40
|
+
key: string;
|
|
41
|
+
url: string;
|
|
42
|
+
/** Headers the PUT must send. */
|
|
43
|
+
headers: Record<string, string>;
|
|
44
|
+
expiresAt: number;
|
|
45
|
+
};
|
|
46
|
+
export declare class R2 {
|
|
47
|
+
readonly component: ComponentApi;
|
|
48
|
+
readonly options: {
|
|
49
|
+
bucket?: string;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* @param component `components.r2` (or the name used in `convex.config.ts`).
|
|
53
|
+
* @param options.bucket Bucket for uploads requested through this instance.
|
|
54
|
+
* Defaults to the component's `R2_BUCKET` env var.
|
|
55
|
+
*/
|
|
56
|
+
constructor(component: ComponentApi, options?: {
|
|
57
|
+
bucket?: string;
|
|
58
|
+
});
|
|
59
|
+
/**
|
|
60
|
+
* Records an upload request and returns a URL for a single PUT of exactly
|
|
61
|
+
* the declared file. Authorize the caller before calling this.
|
|
62
|
+
*/
|
|
63
|
+
requestUpload<Context>(ctx: RunMutationCtx, args: RequestUploadArgs<Context>): Promise<RequestedUpload>;
|
|
64
|
+
private requestArgs;
|
|
65
|
+
/**
|
|
66
|
+
* Uploads bytes from an action, through the same request, PUT and confirm
|
|
67
|
+
* steps as a browser upload: `onConfirm` runs once R2 holds the file, and a
|
|
68
|
+
* failed store is swept like any unconfirmed upload.
|
|
69
|
+
*/
|
|
70
|
+
store<Context>(ctx: StoreCtx, args: StoreArgs<Context>): Promise<ConfirmResult>;
|
|
71
|
+
/**
|
|
72
|
+
* Checks the uploaded object against its request and, if it matches, runs
|
|
73
|
+
* `onConfirm`. It trusts nothing but the upload id, so a public action may
|
|
74
|
+
* call it without authorization.
|
|
75
|
+
*/
|
|
76
|
+
confirm(ctx: RunActionCtx, uploadId: string): Promise<{
|
|
77
|
+
status: "ready";
|
|
78
|
+
upload: {
|
|
79
|
+
bucket: string;
|
|
80
|
+
contentType: string;
|
|
81
|
+
key: string;
|
|
82
|
+
name: string;
|
|
83
|
+
sha256: string;
|
|
84
|
+
size: number;
|
|
85
|
+
uploadId: string;
|
|
86
|
+
};
|
|
87
|
+
} | {
|
|
88
|
+
status: "notUploaded";
|
|
89
|
+
} | {
|
|
90
|
+
reason: string;
|
|
91
|
+
status: "rejected";
|
|
92
|
+
} | {
|
|
93
|
+
status: "missing";
|
|
94
|
+
}>;
|
|
95
|
+
/** A ready upload with its Cloudflare dashboard link (null otherwise). */
|
|
96
|
+
get(ctx: RunQueryCtx, uploadId: string): Promise<{
|
|
97
|
+
bucket: string;
|
|
98
|
+
contentType: string;
|
|
99
|
+
key: string;
|
|
100
|
+
link: string;
|
|
101
|
+
name: string;
|
|
102
|
+
sha256: string;
|
|
103
|
+
size: number;
|
|
104
|
+
uploadId: string;
|
|
105
|
+
} | null>;
|
|
106
|
+
/**
|
|
107
|
+
* Signs a GET URL for a ready upload (null otherwise). Query results are
|
|
108
|
+
* cached until data changes, not until the URL expires.
|
|
109
|
+
*/
|
|
110
|
+
getUrl(ctx: RunQueryCtx, uploadId: string, options?: {
|
|
111
|
+
expiresIn?: number;
|
|
112
|
+
disposition?: "inline" | "attachment";
|
|
113
|
+
}): Promise<string | null>;
|
|
114
|
+
/** Deletes the upload and its object. */
|
|
115
|
+
delete(ctx: RunMutationCtx, uploadId: string): Promise<void>;
|
|
116
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { createFunctionHandle, } from "convex/server";
|
|
2
|
+
import { sha256Hex } from "../browser/index.js";
|
|
3
|
+
export { fileValidator, uploadValidator, } from "../component/validators.js";
|
|
4
|
+
export class R2 {
|
|
5
|
+
component;
|
|
6
|
+
options;
|
|
7
|
+
/**
|
|
8
|
+
* @param component `components.r2` (or the name used in `convex.config.ts`).
|
|
9
|
+
* @param options.bucket Bucket for uploads requested through this instance.
|
|
10
|
+
* Defaults to the component's `R2_BUCKET` env var.
|
|
11
|
+
*/
|
|
12
|
+
constructor(component, options = {}) {
|
|
13
|
+
this.component = component;
|
|
14
|
+
this.options = options;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Records an upload request and returns a URL for a single PUT of exactly
|
|
18
|
+
* the declared file. Authorize the caller before calling this.
|
|
19
|
+
*/
|
|
20
|
+
async requestUpload(ctx, args) {
|
|
21
|
+
return ctx.runMutation(this.component.uploads.request, await this.requestArgs(args));
|
|
22
|
+
}
|
|
23
|
+
async requestArgs(args) {
|
|
24
|
+
const { bucket } = this.options;
|
|
25
|
+
return {
|
|
26
|
+
...(bucket === undefined ? {} : { bucket }),
|
|
27
|
+
keyPrefix: args.keyPrefix,
|
|
28
|
+
file: args.file,
|
|
29
|
+
rules: args.rules,
|
|
30
|
+
onConfirm: await createFunctionHandle(args.onConfirm),
|
|
31
|
+
context: args.context,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Uploads bytes from an action, through the same request, PUT and confirm
|
|
36
|
+
* steps as a browser upload: `onConfirm` runs once R2 holds the file, and a
|
|
37
|
+
* failed store is swept like any unconfirmed upload.
|
|
38
|
+
*/
|
|
39
|
+
async store(ctx, args) {
|
|
40
|
+
const { file: blob, name, contentType = blob.type, ...rest } = args;
|
|
41
|
+
const file = { name, contentType, size: blob.size, sha256: await sha256Hex(blob) };
|
|
42
|
+
const rules = { maxSize: file.size, contentTypes: [contentType] };
|
|
43
|
+
const { uploadId, url, headers } = await ctx.runMutation(this.component.uploads.request, await this.requestArgs({ ...rest, file, rules }));
|
|
44
|
+
const response = await fetch(url, { method: "PUT", headers, body: blob });
|
|
45
|
+
if (!response.ok)
|
|
46
|
+
throw new Error(`R2 PUT failed: ${response.status} ${await response.text()}`);
|
|
47
|
+
return this.confirm(ctx, uploadId);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Checks the uploaded object against its request and, if it matches, runs
|
|
51
|
+
* `onConfirm`. It trusts nothing but the upload id, so a public action may
|
|
52
|
+
* call it without authorization.
|
|
53
|
+
*/
|
|
54
|
+
async confirm(ctx, uploadId) {
|
|
55
|
+
return ctx.runAction(this.component.uploads.confirm, { uploadId });
|
|
56
|
+
}
|
|
57
|
+
/** A ready upload with its Cloudflare dashboard link (null otherwise). */
|
|
58
|
+
async get(ctx, uploadId) {
|
|
59
|
+
return ctx.runQuery(this.component.uploads.get, { uploadId });
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Signs a GET URL for a ready upload (null otherwise). Query results are
|
|
63
|
+
* cached until data changes, not until the URL expires.
|
|
64
|
+
*/
|
|
65
|
+
async getUrl(ctx, uploadId, options = {}) {
|
|
66
|
+
return ctx.runQuery(this.component.uploads.getUrl, { uploadId, ...options });
|
|
67
|
+
}
|
|
68
|
+
/** Deletes the upload and its object. */
|
|
69
|
+
async delete(ctx, uploadId) {
|
|
70
|
+
await ctx.runMutation(this.component.uploads.remove, { uploadId });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated `api` utility.
|
|
3
|
+
*
|
|
4
|
+
* THIS CODE IS AUTOMATICALLY GENERATED.
|
|
5
|
+
*
|
|
6
|
+
* To regenerate, run `npx convex dev`.
|
|
7
|
+
* @module
|
|
8
|
+
*/
|
|
9
|
+
import type * as r2 from "../r2.js";
|
|
10
|
+
import type * as sigv4 from "../sigv4.js";
|
|
11
|
+
import type * as uploads from "../uploads.js";
|
|
12
|
+
import type * as validators from "../validators.js";
|
|
13
|
+
import type { ApiFromModules, FilterApi, FunctionReference } from "convex/server";
|
|
14
|
+
declare const fullApi: ApiFromModules<{
|
|
15
|
+
r2: typeof r2;
|
|
16
|
+
sigv4: typeof sigv4;
|
|
17
|
+
uploads: typeof uploads;
|
|
18
|
+
validators: typeof validators;
|
|
19
|
+
}>;
|
|
20
|
+
/**
|
|
21
|
+
* A utility for referencing Convex functions in your app's public API.
|
|
22
|
+
*
|
|
23
|
+
* Usage:
|
|
24
|
+
* ```js
|
|
25
|
+
* const myFunctionReference = api.myModule.myFunction;
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export declare const api: FilterApi<typeof fullApi, FunctionReference<any, "public">>;
|
|
29
|
+
/**
|
|
30
|
+
* A utility for referencing Convex functions in your app's internal API.
|
|
31
|
+
*
|
|
32
|
+
* Usage:
|
|
33
|
+
* ```js
|
|
34
|
+
* const myFunctionReference = internal.myModule.myFunction;
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export declare const internal: FilterApi<typeof fullApi, FunctionReference<any, "internal">>;
|
|
38
|
+
export declare const components: {};
|
|
39
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
/**
|
|
3
|
+
* Generated `api` utility.
|
|
4
|
+
*
|
|
5
|
+
* THIS CODE IS AUTOMATICALLY GENERATED.
|
|
6
|
+
*
|
|
7
|
+
* To regenerate, run `npx convex dev`.
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import { anyApi, componentsGeneric } from "convex/server";
|
|
11
|
+
const fullApi = anyApi;
|
|
12
|
+
/**
|
|
13
|
+
* A utility for referencing Convex functions in your app's public API.
|
|
14
|
+
*
|
|
15
|
+
* Usage:
|
|
16
|
+
* ```js
|
|
17
|
+
* const myFunctionReference = api.myModule.myFunction;
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export const api = anyApi;
|
|
21
|
+
/**
|
|
22
|
+
* A utility for referencing Convex functions in your app's internal API.
|
|
23
|
+
*
|
|
24
|
+
* Usage:
|
|
25
|
+
* ```js
|
|
26
|
+
* const myFunctionReference = internal.myModule.myFunction;
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export const internal = anyApi;
|
|
30
|
+
export const components = componentsGeneric();
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated `ComponentApi` utility.
|
|
3
|
+
*
|
|
4
|
+
* THIS CODE IS AUTOMATICALLY GENERATED.
|
|
5
|
+
*
|
|
6
|
+
* To regenerate, run `npx convex dev`.
|
|
7
|
+
* @module
|
|
8
|
+
*/
|
|
9
|
+
import type { FunctionReference } from "convex/server";
|
|
10
|
+
/**
|
|
11
|
+
* A utility for referencing a Convex component's exposed API.
|
|
12
|
+
*
|
|
13
|
+
* Useful when expecting a parameter like `components.myComponent`.
|
|
14
|
+
* Usage:
|
|
15
|
+
* ```ts
|
|
16
|
+
* async function myFunction(ctx: QueryCtx, component: ComponentApi) {
|
|
17
|
+
* return ctx.runQuery(component.someFile.someQuery, { ...args });
|
|
18
|
+
* }
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export type ComponentApi<Name extends string | undefined = string | undefined> = {
|
|
22
|
+
uploads: {
|
|
23
|
+
confirm: FunctionReference<"action", "internal", {
|
|
24
|
+
uploadId: string;
|
|
25
|
+
}, {
|
|
26
|
+
status: "ready";
|
|
27
|
+
upload: {
|
|
28
|
+
bucket: string;
|
|
29
|
+
contentType: string;
|
|
30
|
+
key: string;
|
|
31
|
+
name: string;
|
|
32
|
+
sha256: string;
|
|
33
|
+
size: number;
|
|
34
|
+
uploadId: string;
|
|
35
|
+
};
|
|
36
|
+
} | {
|
|
37
|
+
status: "notUploaded";
|
|
38
|
+
} | {
|
|
39
|
+
reason: string;
|
|
40
|
+
status: "rejected";
|
|
41
|
+
} | {
|
|
42
|
+
status: "missing";
|
|
43
|
+
}, Name>;
|
|
44
|
+
get: FunctionReference<"query", "internal", {
|
|
45
|
+
uploadId: string;
|
|
46
|
+
}, {
|
|
47
|
+
bucket: string;
|
|
48
|
+
contentType: string;
|
|
49
|
+
key: string;
|
|
50
|
+
link: string;
|
|
51
|
+
name: string;
|
|
52
|
+
sha256: string;
|
|
53
|
+
size: number;
|
|
54
|
+
uploadId: string;
|
|
55
|
+
} | null, Name>;
|
|
56
|
+
getUrl: FunctionReference<"query", "internal", {
|
|
57
|
+
disposition?: "inline" | "attachment";
|
|
58
|
+
expiresIn?: number;
|
|
59
|
+
uploadId: string;
|
|
60
|
+
}, string | null, Name>;
|
|
61
|
+
remove: FunctionReference<"mutation", "internal", {
|
|
62
|
+
uploadId: string;
|
|
63
|
+
}, null, Name>;
|
|
64
|
+
request: FunctionReference<"mutation", "internal", {
|
|
65
|
+
bucket?: string;
|
|
66
|
+
context: any;
|
|
67
|
+
file: {
|
|
68
|
+
contentType: string;
|
|
69
|
+
name: string;
|
|
70
|
+
sha256: string;
|
|
71
|
+
size: number;
|
|
72
|
+
};
|
|
73
|
+
keyPrefix: string;
|
|
74
|
+
onConfirm: import("convex/server").FunctionHandle_future<"mutation", any, any>;
|
|
75
|
+
rules: {
|
|
76
|
+
contentTypes: Array<string>;
|
|
77
|
+
maxSize: number;
|
|
78
|
+
};
|
|
79
|
+
}, {
|
|
80
|
+
expiresAt: number;
|
|
81
|
+
headers: Record<string, string>;
|
|
82
|
+
key: string;
|
|
83
|
+
uploadId: string;
|
|
84
|
+
url: string;
|
|
85
|
+
}, Name>;
|
|
86
|
+
};
|
|
87
|
+
};
|