@guren/plugin-cloudflare 0.3.0 → 0.3.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.
package/dist/index.js CHANGED
@@ -1,386 +1,379 @@
1
- import {
2
- buildCloudflareOutput,
3
- flattenD1Migrations
4
- } from "./chunk-32YY6FCY.js";
5
-
6
- // src/index.ts
1
+ import { n as flattenD1Migrations, t as buildCloudflareOutput } from "./build-DxgM3l-5.js";
7
2
  import { definePlugin } from "@guren/core";
8
-
9
- // src/env.ts
10
- var holder;
3
+ //#region src/env.ts
4
+ let holder;
5
+ /** First call wins; later calls are ignored (never overwrite a live env). */
11
6
  function captureWorkersEnv(env) {
12
- holder ??= { env };
7
+ holder ??= { env };
13
8
  }
9
+ /** Throws with a clear message if called before the first request captured env. */
14
10
  function getWorkersEnv() {
15
- if (!holder) {
16
- throw new Error(
17
- "getWorkersEnv() was called before the first request captured the Workers env. Defer access behind a closure instead of reading it at module scope, e.g. binding: () => getWorkersEnv<Env>().DB"
18
- );
19
- }
20
- return holder.env;
11
+ if (!holder) throw new Error("getWorkersEnv() was called before the first request captured the Workers env. Defer access behind a closure instead of reading it at module scope, e.g. binding: () => getWorkersEnv<Env>().DB");
12
+ return holder.env;
21
13
  }
14
+ /** Clears the holder. Used by createWorkersHandler on boot failure and by tests. */
22
15
  function resetWorkersEnv() {
23
- holder = void 0;
16
+ holder = void 0;
24
17
  }
25
-
26
- // src/handler.ts
18
+ //#endregion
19
+ //#region src/handler.ts
27
20
  function createWorkersHandler(app) {
28
- let bootPromise;
29
- return {
30
- async fetch(request, env, ctx) {
31
- captureWorkersEnv(env);
32
- let attempt;
33
- try {
34
- attempt = bootPromise ??= app.boot();
35
- await attempt;
36
- } catch (error) {
37
- if (bootPromise === attempt) {
38
- bootPromise = void 0;
39
- resetWorkersEnv();
40
- }
41
- throw error;
42
- }
43
- return app.fetch(request, env, ctx);
44
- }
45
- };
21
+ let bootPromise;
22
+ return { async fetch(request, env, ctx) {
23
+ captureWorkersEnv(env);
24
+ let attempt;
25
+ try {
26
+ attempt = bootPromise ??= app.boot();
27
+ await attempt;
28
+ } catch (error) {
29
+ if (bootPromise === attempt) {
30
+ bootPromise = void 0;
31
+ resetWorkersEnv();
32
+ }
33
+ throw error;
34
+ }
35
+ return app.fetch(request, env, ctx);
36
+ } };
46
37
  }
47
-
48
- // src/storage/sigv4.ts
49
- var ALGORITHM = "AWS4-HMAC-SHA256";
50
- var TERMINATOR = "aws4_request";
51
- var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
38
+ //#endregion
39
+ //#region src/storage/sigv4.ts
40
+ const ALGORITHM = "AWS4-HMAC-SHA256";
41
+ const TERMINATOR = "aws4_request";
42
+ /**
43
+ * S3 accepts an unsigned payload for presigned URLs — the signature covers
44
+ * the request line, the query, and `host`, not the bytes.
45
+ */
46
+ const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
47
+ /**
48
+ * Percent-encoding per RFC 3986, which is stricter than `encodeURIComponent`:
49
+ * `!`, `'`, `(`, `)` and `*` are reserved and must be escaped, or the
50
+ * canonical request the server rebuilds will not match ours.
51
+ */
52
52
  function encodeRfc3986(value) {
53
- return encodeURIComponent(value).replace(
54
- /[!'()*]/g,
55
- (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`
56
- );
53
+ return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
57
54
  }
55
+ /** Path segments are encoded individually; `/` stays a separator. */
58
56
  function canonicalPath(pathname) {
59
- return pathname.split("/").map(decodeAndEncodeSegment).join("/");
57
+ return pathname.split("/").map(decodeAndEncodeSegment).join("/");
60
58
  }
59
+ /**
60
+ * The URL arrives already percent-encoded (callers build it with `URL`), but
61
+ * SigV4 canonicalizes from the decoded form — encoding again without
62
+ * decoding first would sign `%2520` where the server sees `%20`.
63
+ */
61
64
  function decodeAndEncodeSegment(segment) {
62
- return encodeRfc3986(decodeURIComponent(segment));
65
+ return encodeRfc3986(decodeURIComponent(segment));
63
66
  }
67
+ /** Query parameters sorted by encoded name, then encoded value. */
64
68
  function canonicalQuery(searchParams) {
65
- return Array.from(searchParams).map(([name, value]) => [encodeRfc3986(name), encodeRfc3986(value)]).sort(
66
- ([leftName, leftValue], [rightName, rightValue]) => leftName === rightName ? leftValue < rightValue ? -1 : 1 : leftName < rightName ? -1 : 1
67
- ).map(([name, value]) => `${name}=${value}`).join("&");
69
+ return Array.from(searchParams).map(([name, value]) => [encodeRfc3986(name), encodeRfc3986(value)]).sort(([leftName, leftValue], [rightName, rightValue]) => leftName === rightName ? leftValue < rightValue ? -1 : 1 : leftName < rightName ? -1 : 1).map(([name, value]) => `${name}=${value}`).join("&");
68
70
  }
69
71
  function toHex(bytes) {
70
- return Array.from(new Uint8Array(bytes)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
72
+ return Array.from(new Uint8Array(bytes)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
71
73
  }
72
74
  async function sha256Hex(value) {
73
- return toHex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)));
75
+ return toHex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)));
74
76
  }
75
77
  async function hmac(key, value) {
76
- const cryptoKey = await crypto.subtle.importKey(
77
- "raw",
78
- key,
79
- { name: "HMAC", hash: "SHA-256" },
80
- false,
81
- ["sign"]
82
- );
83
- return crypto.subtle.sign("HMAC", cryptoKey, new TextEncoder().encode(value));
78
+ const cryptoKey = await crypto.subtle.importKey("raw", key, {
79
+ name: "HMAC",
80
+ hash: "SHA-256"
81
+ }, false, ["sign"]);
82
+ return crypto.subtle.sign("HMAC", cryptoKey, new TextEncoder().encode(value));
84
83
  }
84
+ /** `AWS4<secret>` → date → region → service → terminator. */
85
85
  async function signingKey(secretAccessKey, dateStamp, region, service) {
86
- const initial = new TextEncoder().encode(`AWS4${secretAccessKey}`);
87
- const byDate = await hmac(initial, dateStamp);
88
- const byRegion = await hmac(byDate, region);
89
- const byService = await hmac(byRegion, service);
90
- return hmac(byService, TERMINATOR);
86
+ return hmac(await hmac(await hmac(await hmac(new TextEncoder().encode(`AWS4${secretAccessKey}`), dateStamp), region), service), TERMINATOR);
91
87
  }
88
+ /**
89
+ * Presign a GET so the URL alone authorizes the read until it expires.
90
+ *
91
+ * @returns the signed absolute URL
92
+ */
92
93
  async function presignGetUrl(options) {
93
- const { accessKeyId, secretAccessKey, region, service, expiresIn } = options;
94
- const date = options.date ?? /* @__PURE__ */ new Date();
95
- const amzDate = `${date.toISOString().replace(/[-:]/g, "").slice(0, 15)}Z`;
96
- const dateStamp = amzDate.slice(0, 8);
97
- const scope = `${dateStamp}/${region}/${service}/${TERMINATOR}`;
98
- const url = new URL(options.url);
99
- url.searchParams.set("X-Amz-Algorithm", ALGORITHM);
100
- url.searchParams.set("X-Amz-Credential", `${accessKeyId}/${scope}`);
101
- url.searchParams.set("X-Amz-Date", amzDate);
102
- url.searchParams.set("X-Amz-Expires", String(expiresIn));
103
- url.searchParams.set("X-Amz-SignedHeaders", "host");
104
- const canonicalRequest = [
105
- "GET",
106
- canonicalPath(url.pathname),
107
- canonicalQuery(url.searchParams),
108
- `host:${url.host}
109
- `,
110
- "host",
111
- UNSIGNED_PAYLOAD
112
- ].join("\n");
113
- const stringToSign = [ALGORITHM, amzDate, scope, await sha256Hex(canonicalRequest)].join("\n");
114
- const key = await signingKey(secretAccessKey, dateStamp, region, service);
115
- url.searchParams.set("X-Amz-Signature", toHex(await hmac(key, stringToSign)));
116
- return url.toString();
94
+ const { accessKeyId, secretAccessKey, region, service, expiresIn } = options;
95
+ const amzDate = `${(options.date ?? /* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").slice(0, 15)}Z`;
96
+ const dateStamp = amzDate.slice(0, 8);
97
+ const scope = `${dateStamp}/${region}/${service}/${TERMINATOR}`;
98
+ const url = new URL(options.url);
99
+ url.searchParams.set("X-Amz-Algorithm", ALGORITHM);
100
+ url.searchParams.set("X-Amz-Credential", `${accessKeyId}/${scope}`);
101
+ url.searchParams.set("X-Amz-Date", amzDate);
102
+ url.searchParams.set("X-Amz-Expires", String(expiresIn));
103
+ url.searchParams.set("X-Amz-SignedHeaders", "host");
104
+ const canonicalRequest = [
105
+ "GET",
106
+ canonicalPath(url.pathname),
107
+ canonicalQuery(url.searchParams),
108
+ `host:${url.host}\n`,
109
+ "host",
110
+ UNSIGNED_PAYLOAD
111
+ ].join("\n");
112
+ const stringToSign = [
113
+ ALGORITHM,
114
+ amzDate,
115
+ scope,
116
+ await sha256Hex(canonicalRequest)
117
+ ].join("\n");
118
+ const key = await signingKey(secretAccessKey, dateStamp, region, service);
119
+ url.searchParams.set("X-Amz-Signature", toHex(await hmac(key, stringToSign)));
120
+ return url.toString();
117
121
  }
118
-
119
- // src/storage/R2Driver.ts
120
- var MAX_PRESIGN_SECONDS = 7 * 24 * 60 * 60;
121
- var DELETE_BATCH_SIZE = 1e3;
122
- var DELETE_CONCURRENCY = 6;
122
+ //#endregion
123
+ //#region src/storage/R2Driver.ts
124
+ /** R2 rejects presigned URLs valid for longer than seven days. */
125
+ const MAX_PRESIGN_SECONDS = 604800;
126
+ /** `R2Bucket.delete()` accepts at most this many keys per call. */
127
+ const DELETE_BATCH_SIZE = 1e3;
128
+ /** How many delete batches may be in flight at once. */
129
+ const DELETE_CONCURRENCY = 6;
130
+ /**
131
+ * Cloudflare R2 storage driver over the Workers binding.
132
+ *
133
+ * @example
134
+ * ```ts
135
+ * const storage = createStorageManager({ default: 'media' })
136
+ * storage.registerDisk('media', () => new R2Driver({
137
+ * binding: () => getWorkersEnv<Env>().MEDIA,
138
+ * publicUrl: 'https://media.example.com',
139
+ * }))
140
+ * ```
141
+ */
123
142
  var R2Driver = class {
124
- resolveBinding;
125
- publicUrl;
126
- prefix;
127
- diskVisibility;
128
- presign;
129
- constructor(options) {
130
- this.resolveBinding = options.binding;
131
- this.publicUrl = options.publicUrl ? trimTrailingSlashes(options.publicUrl) : void 0;
132
- this.prefix = trimSlashes(options.prefix ?? "");
133
- this.diskVisibility = options.visibility ?? (options.publicUrl ? "public" : "private");
134
- this.presign = options.presign;
135
- }
136
- bucket() {
137
- const binding = this.resolveBinding();
138
- if (binding == null) {
139
- throw new Error(
140
- 'R2Driver: the "binding" resolver returned no R2 bucket. On Workers this usually means it ran before the first request \u2014 defer access (e.g. binding: () => getWorkersEnv<Env>().BUCKET) and check the r2_buckets entry in wrangler.jsonc, e.g. "r2_buckets": [{ "binding": "BUCKET", "bucket_name": "my-app-media" }].'
141
- );
142
- }
143
- return binding;
144
- }
145
- key(path) {
146
- const normalized = trimSlashes(path);
147
- if (!this.prefix) return normalized;
148
- return normalized ? `${this.prefix}/${normalized}` : this.prefix;
149
- }
150
- /** Inverse of `key()`: strips the prefix so listings return app-relative paths. */
151
- unkey(key) {
152
- return this.prefix && key.startsWith(`${this.prefix}/`) ? key.slice(this.prefix.length + 1) : key;
153
- }
154
- directoryPrefix(directory) {
155
- const key = this.key(directory);
156
- return key ? `${key}/` : "";
157
- }
158
- assertVisibility(requested, operation) {
159
- if (requested && requested !== this.diskVisibility) {
160
- throw new Error(
161
- `R2Driver.${operation}: cannot make an object ${requested} on a ${this.diskVisibility} bucket. R2 has no per-object visibility \u2014 access is decided per bucket (custom domain / r2.dev). Declare the bucket\u2019s visibility with the driver\u2019s "visibility" option, or serve private files through a signed app route.`
162
- );
163
- }
164
- }
165
- async put(path, content, options) {
166
- this.assertVisibility(options?.visibility, "put");
167
- const putOptions = {};
168
- if (options?.contentType) putOptions.httpMetadata = { contentType: options.contentType };
169
- if (options?.metadata) putOptions.customMetadata = options.metadata;
170
- await this.bucket().put(this.key(path), content, putOptions);
171
- return trimSlashes(path);
172
- }
173
- async putFile(_path, _localPath, _options) {
174
- throw new Error(
175
- "R2Driver.putFile is not supported: Workers has no filesystem to read from. Read the file yourself and call put()."
176
- );
177
- }
178
- async get(path) {
179
- const object = await this.bucket().get(this.key(path));
180
- if (!object) return null;
181
- return Buffer.from(await object.arrayBuffer());
182
- }
183
- async getAsString(path) {
184
- const object = await this.bucket().get(this.key(path));
185
- return object ? object.text() : null;
186
- }
187
- async exists(path) {
188
- return await this.bucket().head(this.key(path)) !== null;
189
- }
190
- async delete(path) {
191
- const bucket = this.bucket();
192
- const key = this.key(path);
193
- if (await bucket.head(key) === null) return false;
194
- await bucket.delete(key);
195
- return true;
196
- }
197
- async deleteMany(paths) {
198
- return this.deleteKeys(paths.map((path) => this.key(path)));
199
- }
200
- async deleteKeys(rawKeys) {
201
- const keys = Array.from(new Set(rawKeys));
202
- if (keys.length === 0) return 0;
203
- const bucket = this.bucket();
204
- const batches = [];
205
- for (let index = 0; index < keys.length; index += DELETE_BATCH_SIZE) {
206
- batches.push(keys.slice(index, index + DELETE_BATCH_SIZE));
207
- }
208
- for (let index = 0; index < batches.length; index += DELETE_CONCURRENCY) {
209
- await Promise.all(batches.slice(index, index + DELETE_CONCURRENCY).map((batch) => bucket.delete(batch)));
210
- }
211
- return keys.length;
212
- }
213
- async copy(from, to) {
214
- const bucket = this.bucket();
215
- const source = await bucket.get(this.key(from));
216
- if (!source) {
217
- throw new Error(`File not found: ${from}`);
218
- }
219
- const options = {};
220
- if (source.httpMetadata) options.httpMetadata = source.httpMetadata;
221
- if (source.customMetadata) options.customMetadata = source.customMetadata;
222
- await bucket.put(this.key(to), source.body, options);
223
- return trimSlashes(to);
224
- }
225
- async move(from, to) {
226
- const destination = await this.copy(from, to);
227
- await this.bucket().delete(this.key(from));
228
- return destination;
229
- }
230
- url(path) {
231
- if (!this.publicUrl) {
232
- throw new Error(
233
- 'R2Driver.url() requires the "publicUrl" option (the bucket\u2019s custom domain or r2.dev subdomain). R2 has no derivable public URL.'
234
- );
235
- }
236
- return `${this.publicUrl}/${encodeKey(this.key(path))}`;
237
- }
238
- async temporaryUrl(path, expiration) {
239
- if (!this.presign) {
240
- throw new Error(
241
- 'R2Driver.temporaryUrl() cannot sign URLs through the R2 binding. Either configure "presign: { accountId, bucket, accessKeyId, secretAccessKey }" (an R2 API token, used with the S3-compatible endpoint) or serve private files through a signed app route.'
242
- );
243
- }
244
- const expiresIn = Math.floor((expiration.getTime() - Date.now()) / 1e3);
245
- if (expiresIn > MAX_PRESIGN_SECONDS) {
246
- throw new Error(
247
- `R2Driver.temporaryUrl(): R2 presigned URLs may be valid for at most 7 days (requested ${expiresIn}s).`
248
- );
249
- }
250
- return presignGetUrl({
251
- url: `https://${this.presign.accountId}.r2.cloudflarestorage.com/${this.presign.bucket}/${encodeKey(this.key(path))}`,
252
- accessKeyId: this.presign.accessKeyId,
253
- secretAccessKey: this.presign.secretAccessKey,
254
- // R2's S3 API is single-region.
255
- region: "auto",
256
- service: "s3",
257
- expiresIn: Math.max(1, expiresIn)
258
- });
259
- }
260
- async size(path) {
261
- return (await this.metadataOrFail(path)).size;
262
- }
263
- async lastModified(path) {
264
- return (await this.metadataOrFail(path)).lastModified;
265
- }
266
- async metadataOrFail(path) {
267
- const metadata = await this.metadata(path);
268
- if (!metadata) {
269
- throw new Error(`File not found: ${path}`);
270
- }
271
- return metadata;
272
- }
273
- async metadata(path) {
274
- const object = await this.bucket().head(this.key(path));
275
- if (!object) return null;
276
- return {
277
- path: trimSlashes(path),
278
- size: object.size,
279
- lastModified: object.uploaded,
280
- contentType: object.httpMetadata?.contentType,
281
- visibility: this.diskVisibility,
282
- metadata: object.customMetadata
283
- };
284
- }
285
- async files(directory) {
286
- return this.collectFiles({ prefix: this.directoryPrefix(directory), delimiter: "/" });
287
- }
288
- async directories(directory) {
289
- const result = [];
290
- for await (const page of this.pages({ prefix: this.directoryPrefix(directory), delimiter: "/" })) {
291
- for (const prefix of page.delimitedPrefixes) {
292
- const relative = trimTrailingSlashes(this.unkey(prefix));
293
- if (relative) result.push(relative);
294
- }
295
- }
296
- return result.sort();
297
- }
298
- async allFiles(directory) {
299
- return this.collectFiles({ prefix: this.directoryPrefix(directory) });
300
- }
301
- /** App-relative paths of every listed object, minus folder markers. */
302
- async collectFiles(options) {
303
- const result = [];
304
- for await (const object of this.objects(options)) {
305
- if (!object.key.endsWith("/")) result.push(this.unkey(object.key));
306
- }
307
- return result.sort();
308
- }
309
- async *objects(options) {
310
- for await (const page of this.pages(options)) yield* page.objects;
311
- }
312
- /**
313
- * Follows `cursor` until `truncated` is false. A single `list()` call is
314
- * capped at 1000 keys, so a one-page read (what `S3Driver.allFiles` does)
315
- * silently truncates larger directories.
316
- */
317
- async *pages(options) {
318
- const bucket = this.bucket();
319
- let cursor;
320
- do {
321
- const page = await bucket.list(cursor ? { ...options, cursor } : options);
322
- yield page;
323
- cursor = page.truncated ? page.cursor : void 0;
324
- } while (cursor);
325
- }
326
- async makeDirectory(path) {
327
- const normalized = trimSlashes(path);
328
- if (!normalized) return;
329
- await this.bucket().put(`${this.key(normalized)}/`, "");
330
- }
331
- async deleteDirectory(path) {
332
- const bucket = this.bucket();
333
- for await (const page of this.pages({ prefix: this.directoryPrefix(path) })) {
334
- if (page.objects.length > 0) {
335
- await bucket.delete(page.objects.map((object) => object.key));
336
- }
337
- }
338
- }
339
- async setVisibility(path, visibility) {
340
- this.assertVisibility(visibility, "setVisibility");
341
- await this.metadataOrFail(path);
342
- }
343
- async getVisibility(path) {
344
- await this.metadataOrFail(path);
345
- return this.diskVisibility;
346
- }
347
- /** The key prefix (for tests and diagnostics). */
348
- getPrefix() {
349
- return this.prefix;
350
- }
143
+ resolveBinding;
144
+ publicUrl;
145
+ prefix;
146
+ diskVisibility;
147
+ presign;
148
+ constructor(options) {
149
+ this.resolveBinding = options.binding;
150
+ this.publicUrl = options.publicUrl ? trimTrailingSlashes(options.publicUrl) : void 0;
151
+ this.prefix = trimSlashes(options.prefix ?? "");
152
+ this.diskVisibility = options.visibility ?? (options.publicUrl ? "public" : "private");
153
+ this.presign = options.presign;
154
+ }
155
+ bucket() {
156
+ const binding = this.resolveBinding();
157
+ if (binding == null) throw new Error("R2Driver: the \"binding\" resolver returned no R2 bucket. On Workers this usually means it ran before the first request — defer access (e.g. binding: () => getWorkersEnv<Env>().BUCKET) and check the r2_buckets entry in wrangler.jsonc, e.g. \"r2_buckets\": [{ \"binding\": \"BUCKET\", \"bucket_name\": \"my-app-media\" }].");
158
+ return binding;
159
+ }
160
+ key(path) {
161
+ const normalized = trimSlashes(path);
162
+ if (!this.prefix) return normalized;
163
+ return normalized ? `${this.prefix}/${normalized}` : this.prefix;
164
+ }
165
+ /** Inverse of `key()`: strips the prefix so listings return app-relative paths. */
166
+ unkey(key) {
167
+ return this.prefix && key.startsWith(`${this.prefix}/`) ? key.slice(this.prefix.length + 1) : key;
168
+ }
169
+ directoryPrefix(directory) {
170
+ const key = this.key(directory);
171
+ return key ? `${key}/` : "";
172
+ }
173
+ assertVisibility(requested, operation) {
174
+ if (requested && requested !== this.diskVisibility) throw new Error(`R2Driver.${operation}: cannot make an object ${requested} on a ${this.diskVisibility} bucket. R2 has no per-object visibility — access is decided per bucket (custom domain / r2.dev). Declare the bucket’s visibility with the driver’s "visibility" option, or serve private files through a signed app route.`);
175
+ }
176
+ async put(path, content, options) {
177
+ this.assertVisibility(options?.visibility, "put");
178
+ const putOptions = {};
179
+ if (options?.contentType) putOptions.httpMetadata = { contentType: options.contentType };
180
+ if (options?.metadata) putOptions.customMetadata = options.metadata;
181
+ await this.bucket().put(this.key(path), content, putOptions);
182
+ return trimSlashes(path);
183
+ }
184
+ async putFile(_path, _localPath, _options) {
185
+ throw new Error("R2Driver.putFile is not supported: Workers has no filesystem to read from. Read the file yourself and call put().");
186
+ }
187
+ async get(path) {
188
+ const object = await this.bucket().get(this.key(path));
189
+ if (!object) return null;
190
+ return Buffer.from(await object.arrayBuffer());
191
+ }
192
+ async getAsString(path) {
193
+ const object = await this.bucket().get(this.key(path));
194
+ return object ? object.text() : null;
195
+ }
196
+ async exists(path) {
197
+ return await this.bucket().head(this.key(path)) !== null;
198
+ }
199
+ async delete(path) {
200
+ const bucket = this.bucket();
201
+ const key = this.key(path);
202
+ if (await bucket.head(key) === null) return false;
203
+ await bucket.delete(key);
204
+ return true;
205
+ }
206
+ async deleteMany(paths) {
207
+ return this.deleteKeys(paths.map((path) => this.key(path)));
208
+ }
209
+ async deleteKeys(rawKeys) {
210
+ const keys = Array.from(new Set(rawKeys));
211
+ if (keys.length === 0) return 0;
212
+ const bucket = this.bucket();
213
+ const batches = [];
214
+ for (let index = 0; index < keys.length; index += DELETE_BATCH_SIZE) batches.push(keys.slice(index, index + DELETE_BATCH_SIZE));
215
+ for (let index = 0; index < batches.length; index += DELETE_CONCURRENCY) await Promise.all(batches.slice(index, index + DELETE_CONCURRENCY).map((batch) => bucket.delete(batch)));
216
+ return keys.length;
217
+ }
218
+ async copy(from, to) {
219
+ const bucket = this.bucket();
220
+ const source = await bucket.get(this.key(from));
221
+ if (!source) throw new Error(`File not found: ${from}`);
222
+ const options = {};
223
+ if (source.httpMetadata) options.httpMetadata = source.httpMetadata;
224
+ if (source.customMetadata) options.customMetadata = source.customMetadata;
225
+ await bucket.put(this.key(to), source.body, options);
226
+ return trimSlashes(to);
227
+ }
228
+ async move(from, to) {
229
+ const destination = await this.copy(from, to);
230
+ await this.bucket().delete(this.key(from));
231
+ return destination;
232
+ }
233
+ url(path) {
234
+ if (!this.publicUrl) throw new Error("R2Driver.url() requires the \"publicUrl\" option (the bucket’s custom domain or r2.dev subdomain). R2 has no derivable public URL.");
235
+ return `${this.publicUrl}/${encodeKey(this.key(path))}`;
236
+ }
237
+ async temporaryUrl(path, expiration) {
238
+ if (!this.presign) throw new Error("R2Driver.temporaryUrl() cannot sign URLs through the R2 binding. Either configure \"presign: { accountId, bucket, accessKeyId, secretAccessKey }\" (an R2 API token, used with the S3-compatible endpoint) or serve private files through a signed app route.");
239
+ const expiresIn = Math.floor((expiration.getTime() - Date.now()) / 1e3);
240
+ if (expiresIn > MAX_PRESIGN_SECONDS) throw new Error(`R2Driver.temporaryUrl(): R2 presigned URLs may be valid for at most 7 days (requested ${expiresIn}s).`);
241
+ return presignGetUrl({
242
+ url: `https://${this.presign.accountId}.r2.cloudflarestorage.com/${this.presign.bucket}/${encodeKey(this.key(path))}`,
243
+ accessKeyId: this.presign.accessKeyId,
244
+ secretAccessKey: this.presign.secretAccessKey,
245
+ region: "auto",
246
+ service: "s3",
247
+ expiresIn: Math.max(1, expiresIn)
248
+ });
249
+ }
250
+ async size(path) {
251
+ return (await this.metadataOrFail(path)).size;
252
+ }
253
+ async lastModified(path) {
254
+ return (await this.metadataOrFail(path)).lastModified;
255
+ }
256
+ async metadataOrFail(path) {
257
+ const metadata = await this.metadata(path);
258
+ if (!metadata) throw new Error(`File not found: ${path}`);
259
+ return metadata;
260
+ }
261
+ async metadata(path) {
262
+ const object = await this.bucket().head(this.key(path));
263
+ if (!object) return null;
264
+ return {
265
+ path: trimSlashes(path),
266
+ size: object.size,
267
+ lastModified: object.uploaded,
268
+ contentType: object.httpMetadata?.contentType,
269
+ visibility: this.diskVisibility,
270
+ metadata: object.customMetadata
271
+ };
272
+ }
273
+ async files(directory) {
274
+ return this.collectFiles({
275
+ prefix: this.directoryPrefix(directory),
276
+ delimiter: "/"
277
+ });
278
+ }
279
+ async directories(directory) {
280
+ const result = [];
281
+ for await (const page of this.pages({
282
+ prefix: this.directoryPrefix(directory),
283
+ delimiter: "/"
284
+ })) for (const prefix of page.delimitedPrefixes) {
285
+ const relative = trimTrailingSlashes(this.unkey(prefix));
286
+ if (relative) result.push(relative);
287
+ }
288
+ return result.sort();
289
+ }
290
+ async allFiles(directory) {
291
+ return this.collectFiles({ prefix: this.directoryPrefix(directory) });
292
+ }
293
+ /** App-relative paths of every listed object, minus folder markers. */
294
+ async collectFiles(options) {
295
+ const result = [];
296
+ for await (const object of this.objects(options)) if (!object.key.endsWith("/")) result.push(this.unkey(object.key));
297
+ return result.sort();
298
+ }
299
+ async *objects(options) {
300
+ for await (const page of this.pages(options)) yield* page.objects;
301
+ }
302
+ /**
303
+ * Follows `cursor` until `truncated` is false. A single `list()` call is
304
+ * capped at 1000 keys, so a one-page read (what `S3Driver.allFiles` does)
305
+ * silently truncates larger directories.
306
+ */
307
+ async *pages(options) {
308
+ const bucket = this.bucket();
309
+ let cursor;
310
+ do {
311
+ const page = await bucket.list(cursor ? {
312
+ ...options,
313
+ cursor
314
+ } : options);
315
+ yield page;
316
+ cursor = page.truncated ? page.cursor : void 0;
317
+ } while (cursor);
318
+ }
319
+ async makeDirectory(path) {
320
+ const normalized = trimSlashes(path);
321
+ if (!normalized) return;
322
+ await this.bucket().put(`${this.key(normalized)}/`, "");
323
+ }
324
+ async deleteDirectory(path) {
325
+ const bucket = this.bucket();
326
+ for await (const page of this.pages({ prefix: this.directoryPrefix(path) })) if (page.objects.length > 0) await bucket.delete(page.objects.map((object) => object.key));
327
+ }
328
+ async setVisibility(path, visibility) {
329
+ this.assertVisibility(visibility, "setVisibility");
330
+ await this.metadataOrFail(path);
331
+ }
332
+ async getVisibility(path) {
333
+ await this.metadataOrFail(path);
334
+ return this.diskVisibility;
335
+ }
336
+ /** The key prefix (for tests and diagnostics). */
337
+ getPrefix() {
338
+ return this.prefix;
339
+ }
351
340
  };
341
+ /** Percent-encode a key for the S3 URL path, keeping `/` as a separator. */
352
342
  function encodeKey(key) {
353
- return key.split("/").map(encodeURIComponent).join("/");
343
+ return key.split("/").map(encodeURIComponent).join("/");
354
344
  }
345
+ /**
346
+ * Twins of `@guren/server`'s `support/trim-slashes` (not exported from the
347
+ * package): regex-free so request-derived paths cannot make them backtrack.
348
+ */
355
349
  function trimTrailingSlashes(value) {
356
- let end = value.length;
357
- while (end > 0 && value[end - 1] === "/") end--;
358
- return value.slice(0, end);
350
+ let end = value.length;
351
+ while (end > 0 && value[end - 1] === "/") end--;
352
+ return value.slice(0, end);
359
353
  }
360
354
  function trimSlashes(value) {
361
- let start = 0;
362
- let end = value.length;
363
- while (start < end && value[start] === "/") start++;
364
- while (end > start && value[end - 1] === "/") end--;
365
- return value.slice(start, end);
355
+ let start = 0;
356
+ let end = value.length;
357
+ while (start < end && value[start] === "/") start++;
358
+ while (end > start && value[end - 1] === "/") end--;
359
+ return value.slice(start, end);
366
360
  }
367
-
368
- // src/index.ts
369
- var factory = definePlugin({
370
- name: "cloudflare",
371
- register() {
372
- }
361
+ //#endregion
362
+ //#region src/index.ts
363
+ const factory = definePlugin({
364
+ name: "cloudflare",
365
+ register() {}
373
366
  });
367
+ /**
368
+ * Register the Cloudflare plugin.
369
+ *
370
+ * @example
371
+ * ```typescript
372
+ * createApp({ providers: [cloudflarePlugin()] })
373
+ * ```
374
+ */
374
375
  function cloudflarePlugin(config = {}) {
375
- return factory(config);
376
+ return factory(config);
376
377
  }
377
- export {
378
- R2Driver,
379
- buildCloudflareOutput,
380
- captureWorkersEnv,
381
- cloudflarePlugin,
382
- createWorkersHandler,
383
- flattenD1Migrations,
384
- getWorkersEnv,
385
- resetWorkersEnv
386
- };
378
+ //#endregion
379
+ export { R2Driver, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, resetWorkersEnv };