@guren/plugin-cloudflare 0.2.2 → 0.3.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/README.md +16 -0
- package/dist/{chunk-32YY6FCY.js → chunk-6DV73MBR.js} +70 -11
- package/dist/commands.js +1 -1
- package/dist/index.d.ts +172 -2
- package/dist/index.js +322 -1
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -34,6 +34,22 @@ bunx wrangler deploy
|
|
|
34
34
|
|
|
35
35
|
The binding is a resolver, not a value — it must be read lazily.
|
|
36
36
|
|
|
37
|
+
- **`R2Driver`** — a storage driver over the R2 bucket binding, for `StorageManager.registerDisk()`. Same lazy `binding` contract as D1; no credentials and no AWS SDK in the bundle:
|
|
38
|
+
|
|
39
|
+
```typescript
|
|
40
|
+
import { createStorageManager, LocalStorageDriver } from '@guren/core'
|
|
41
|
+
import { R2Driver, getWorkersEnv } from '@guren/plugin-cloudflare'
|
|
42
|
+
|
|
43
|
+
const storage = createStorageManager({ default: 'media' })
|
|
44
|
+
storage.registerDisk('media', () =>
|
|
45
|
+
isWorkersRuntime()
|
|
46
|
+
? new R2Driver({ binding: () => getWorkersEnv<{ MEDIA: unknown }>().MEDIA, publicUrl: 'https://media.example.com' })
|
|
47
|
+
: new LocalStorageDriver({ root: './storage/app/public', url: '/storage' }),
|
|
48
|
+
)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
with `"r2_buckets": [{ "binding": "MEDIA", "bucket_name": "my-app-media" }]` in `wrangler.jsonc`. Three methods differ from the S3 driver, because the binding differs from S3: `url()` needs `publicUrl` (a custom domain or the r2.dev subdomain — R2 has no derivable public URL); `temporaryUrl()` needs the optional `presign` credentials, and throws with guidance otherwise (bindings cannot sign URLs); `setVisibility()` / `put({ visibility })` throw when asked for the opposite of the bucket's declared `visibility`, because R2 has no per-object ACL to honour the request with. `putFile()` throws — Workers has no filesystem.
|
|
52
|
+
|
|
37
53
|
- **`cloudflarePlugin()`** — the service provider factory, registered automatically by `guren plugin`.
|
|
38
54
|
|
|
39
55
|
## Things Workers changes
|
|
@@ -4,6 +4,7 @@ import { relative, resolve, sep } from "path";
|
|
|
4
4
|
import { pathToFileURL } from "url";
|
|
5
5
|
import {
|
|
6
6
|
DEV_ONLY_MODULES,
|
|
7
|
+
SQL_CLIENT_MODULES,
|
|
7
8
|
importSpecifier,
|
|
8
9
|
renderDevOnlyStub,
|
|
9
10
|
assertOutputDirOutsideRoot,
|
|
@@ -39,20 +40,26 @@ async function buildCloudflareOutput(options = {}) {
|
|
|
39
40
|
scaffoldWranglerConfig(root, out, packageJson.name);
|
|
40
41
|
}
|
|
41
42
|
var MCP_UNAVAILABLE = "The MCP endpoint is unavailable on Cloudflare Workers \u2014 it generates files on disk.";
|
|
43
|
+
var STUBBED_MODULES = [...DEV_ONLY_MODULES, ...SQL_CLIENT_MODULES];
|
|
42
44
|
var UNAVAILABLE_ON_WORKERS = {
|
|
43
45
|
sqlite: "bun:sqlite is unavailable on Cloudflare Workers \u2014 use createD1Database().",
|
|
44
46
|
vite: "The Vite dev server is unavailable on Cloudflare Workers \u2014 assets are served by Workers Static Assets.",
|
|
45
|
-
mcp: MCP_UNAVAILABLE
|
|
47
|
+
mcp: MCP_UNAVAILABLE,
|
|
48
|
+
"sql-driver": "This database client is unavailable on Cloudflare Workers \u2014 use createD1Database(). It is stubbed because @guren/orm names it in a dynamic import that bundlers follow even when the branch cannot be taken."
|
|
46
49
|
};
|
|
47
50
|
var STUB_FILES = {
|
|
48
51
|
"bun:sqlite": "stub-bun-sqlite.js",
|
|
49
52
|
vite: "stub-vite.js",
|
|
50
53
|
"@guren/cli": "stub-guren-cli.js",
|
|
51
54
|
"@modelcontextprotocol/sdk/server/mcp.js": "stub-mcp-server.js",
|
|
52
|
-
"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js": "stub-mcp-transport.js"
|
|
55
|
+
"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js": "stub-mcp-transport.js",
|
|
56
|
+
postgres: "stub-postgres.js",
|
|
57
|
+
mysql2: "stub-mysql2.js",
|
|
58
|
+
"mysql2/promise": "stub-mysql2-promise.js",
|
|
59
|
+
"@aws-sdk/client-rds-data": "stub-rds-data.js"
|
|
53
60
|
};
|
|
54
61
|
function writeDevOnlyStubs(out) {
|
|
55
|
-
for (const module of
|
|
62
|
+
for (const module of STUBBED_MODULES) {
|
|
56
63
|
writeFileSync(
|
|
57
64
|
resolve(out, STUB_FILES[module.specifier]),
|
|
58
65
|
renderDevOnlyStub(module, UNAVAILABLE_ON_WORKERS[module.kind])
|
|
@@ -61,7 +68,7 @@ function writeDevOnlyStubs(out) {
|
|
|
61
68
|
}
|
|
62
69
|
function devOnlyAliases(outRelative) {
|
|
63
70
|
return Object.fromEntries(
|
|
64
|
-
|
|
71
|
+
STUBBED_MODULES.map((module) => [
|
|
65
72
|
module.specifier,
|
|
66
73
|
`./${outRelative}/${STUB_FILES[module.specifier]}`
|
|
67
74
|
])
|
|
@@ -227,22 +234,74 @@ function scaffoldWranglerConfig(root, out, packageName) {
|
|
|
227
234
|
}
|
|
228
235
|
console.log(`Cloudflare build: scaffolded ${configPath} \u2014 fill in d1_databases[0].database_id before deploying.`);
|
|
229
236
|
}
|
|
237
|
+
function parseJsonc(text) {
|
|
238
|
+
const out = [];
|
|
239
|
+
let index = 0;
|
|
240
|
+
while (index < text.length) {
|
|
241
|
+
const char = text[index];
|
|
242
|
+
if (char === '"') {
|
|
243
|
+
const start = index;
|
|
244
|
+
index += 1;
|
|
245
|
+
while (index < text.length) {
|
|
246
|
+
if (text[index] === "\\") {
|
|
247
|
+
index += 2;
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
if (text[index] === '"') {
|
|
251
|
+
index += 1;
|
|
252
|
+
break;
|
|
253
|
+
}
|
|
254
|
+
index += 1;
|
|
255
|
+
}
|
|
256
|
+
out.push(text.slice(start, index));
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (char === "/" && text[index + 1] === "/") {
|
|
260
|
+
while (index < text.length && text[index] !== "\n") {
|
|
261
|
+
index += 1;
|
|
262
|
+
}
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
if (char === "/" && text[index + 1] === "*") {
|
|
266
|
+
const end = text.indexOf("*/", index + 2);
|
|
267
|
+
index = end === -1 ? text.length : end + 2;
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
if (char === "}" || char === "]") {
|
|
271
|
+
let back = out.length - 1;
|
|
272
|
+
while (back >= 0 && /^\s+$/.test(out[back])) {
|
|
273
|
+
back -= 1;
|
|
274
|
+
}
|
|
275
|
+
if (back >= 0 && out[back] === ",") {
|
|
276
|
+
out.splice(back, 1);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
out.push(char);
|
|
280
|
+
index += 1;
|
|
281
|
+
}
|
|
282
|
+
return JSON.parse(out.join(""));
|
|
283
|
+
}
|
|
230
284
|
function warnMissingBuildOwnedKeys(configPath, outRelative) {
|
|
231
285
|
let config;
|
|
232
286
|
try {
|
|
233
|
-
config =
|
|
287
|
+
config = parseJsonc(readFileSync(configPath, "utf8"));
|
|
234
288
|
} catch {
|
|
289
|
+
console.warn(
|
|
290
|
+
`Cloudflare build: could not parse ${configPath}, so its build-owned keys went unchecked. Fix the file, or compare it against a config scaffolded in an empty directory.`
|
|
291
|
+
);
|
|
235
292
|
return;
|
|
236
293
|
}
|
|
237
294
|
const missing = [];
|
|
238
|
-
const
|
|
239
|
-
const
|
|
240
|
-
|
|
241
|
-
|
|
295
|
+
const configAlias = config.alias;
|
|
296
|
+
const alias = typeof configAlias === "object" && configAlias !== null ? configAlias : {};
|
|
297
|
+
for (const [specifier, target] of Object.entries(devOnlyAliases(outRelative))) {
|
|
298
|
+
if (!(specifier in alias)) {
|
|
299
|
+
missing.push(`${JSON.stringify(specifier)}: ${JSON.stringify(target)} (inside "alias")`);
|
|
300
|
+
}
|
|
242
301
|
}
|
|
243
302
|
const define = config.define;
|
|
244
303
|
if (!define?.["process.env.NODE_ENV"]) {
|
|
245
|
-
missing.push('"
|
|
304
|
+
missing.push('"process.env.NODE_ENV": "\\"production\\"" (inside "define")');
|
|
246
305
|
}
|
|
247
306
|
const d1 = config.d1_databases?.[0];
|
|
248
307
|
if (d1 && d1.migrations_dir !== `${outRelative}/d1-migrations`) {
|
|
@@ -250,7 +309,7 @@ function warnMissingBuildOwnedKeys(configPath, outRelative) {
|
|
|
250
309
|
}
|
|
251
310
|
if (missing.length > 0) {
|
|
252
311
|
console.warn(
|
|
253
|
-
`Cloudflare build: ${configPath} predates this plugin version. Add the
|
|
312
|
+
`Cloudflare build: ${configPath} predates this plugin version. Add these entries, alongside whatever the file already has under the same keys, or the worker will fail to start or skip migrations:
|
|
254
313
|
${missing.join("\n ")}`
|
|
255
314
|
);
|
|
256
315
|
}
|
package/dist/commands.js
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ServiceProviderConstructor } from '@guren/core';
|
|
1
|
+
import { StorageDriver, PutOptions, FileMetadata, ServiceProviderConstructor } from '@guren/core';
|
|
2
2
|
import { PathLike } from '@guren/core/internal/deploy-build';
|
|
3
3
|
|
|
4
4
|
/** First call wins; later calls are ignored (never overwrite a live env). */
|
|
@@ -61,6 +61,176 @@ declare function buildCloudflareOutput(options?: BuildCloudflareOutputOptions):
|
|
|
61
61
|
*/
|
|
62
62
|
declare function flattenD1Migrations(migrationsDir: string, outDir: string): void;
|
|
63
63
|
|
|
64
|
+
/**
|
|
65
|
+
* Structural view of the R2 binding, in the same spirit as the S3 driver's
|
|
66
|
+
* local `S3Client { send() }`: only what this driver calls, so
|
|
67
|
+
* `@cloudflare/workers-types` stays a devDependency. `R2Driver.types.test.ts`
|
|
68
|
+
* pins that the real `R2Bucket` satisfies it.
|
|
69
|
+
*/
|
|
70
|
+
interface R2HttpMetadataLike {
|
|
71
|
+
contentType?: string;
|
|
72
|
+
contentLanguage?: string;
|
|
73
|
+
contentDisposition?: string;
|
|
74
|
+
contentEncoding?: string;
|
|
75
|
+
cacheControl?: string;
|
|
76
|
+
cacheExpiry?: Date;
|
|
77
|
+
}
|
|
78
|
+
interface R2ObjectLike {
|
|
79
|
+
key: string;
|
|
80
|
+
size: number;
|
|
81
|
+
uploaded: Date;
|
|
82
|
+
httpMetadata?: R2HttpMetadataLike;
|
|
83
|
+
customMetadata?: Record<string, string>;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Streams and blobs are typed structurally rather than as the global
|
|
87
|
+
* `ReadableStream`/`Blob`: `@cloudflare/workers-types` declares its own
|
|
88
|
+
* interfaces for both, and neither direction is assignable to the runtime
|
|
89
|
+
* globals, so naming the globals here would make the real `R2Bucket` fail
|
|
90
|
+
* the `R2BucketLike` check while being perfectly usable at runtime.
|
|
91
|
+
*/
|
|
92
|
+
interface R2StreamLike {
|
|
93
|
+
locked: boolean;
|
|
94
|
+
getReader(): unknown;
|
|
95
|
+
cancel(reason?: unknown): Promise<void>;
|
|
96
|
+
}
|
|
97
|
+
interface R2BlobLike {
|
|
98
|
+
size: number;
|
|
99
|
+
type: string;
|
|
100
|
+
arrayBuffer(): Promise<ArrayBuffer>;
|
|
101
|
+
text(): Promise<string>;
|
|
102
|
+
}
|
|
103
|
+
interface R2ObjectBodyLike extends R2ObjectLike {
|
|
104
|
+
body: R2StreamLike;
|
|
105
|
+
arrayBuffer(): Promise<ArrayBuffer>;
|
|
106
|
+
text(): Promise<string>;
|
|
107
|
+
}
|
|
108
|
+
interface R2ObjectsLike {
|
|
109
|
+
objects: R2ObjectLike[];
|
|
110
|
+
truncated: boolean;
|
|
111
|
+
cursor?: string;
|
|
112
|
+
delimitedPrefixes: string[];
|
|
113
|
+
}
|
|
114
|
+
interface R2ListOptionsLike {
|
|
115
|
+
prefix?: string;
|
|
116
|
+
delimiter?: string;
|
|
117
|
+
cursor?: string;
|
|
118
|
+
limit?: number;
|
|
119
|
+
}
|
|
120
|
+
interface R2PutOptionsLike {
|
|
121
|
+
httpMetadata?: R2HttpMetadataLike;
|
|
122
|
+
customMetadata?: Record<string, string>;
|
|
123
|
+
}
|
|
124
|
+
type R2PutValue = R2StreamLike | R2BlobLike | ArrayBuffer | ArrayBufferView | string | null;
|
|
125
|
+
interface R2BucketLike {
|
|
126
|
+
head(key: string): Promise<R2ObjectLike | null>;
|
|
127
|
+
get(key: string): Promise<R2ObjectBodyLike | null>;
|
|
128
|
+
put(key: string, value: R2PutValue, options?: R2PutOptionsLike): Promise<R2ObjectLike | null>;
|
|
129
|
+
delete(keys: string | string[]): Promise<void>;
|
|
130
|
+
list(options?: R2ListOptionsLike): Promise<R2ObjectsLike>;
|
|
131
|
+
}
|
|
132
|
+
interface R2PresignOptions {
|
|
133
|
+
/** Cloudflare account id — the S3 endpoint is `https://<accountId>.r2.cloudflarestorage.com`. */
|
|
134
|
+
accountId: string;
|
|
135
|
+
/** Bucket name as R2 knows it (the binding does not expose it). */
|
|
136
|
+
bucket: string;
|
|
137
|
+
/** R2 API token credentials (S3-compatible access key pair). */
|
|
138
|
+
accessKeyId: string;
|
|
139
|
+
secretAccessKey: string;
|
|
140
|
+
}
|
|
141
|
+
interface R2DriverOptions {
|
|
142
|
+
/**
|
|
143
|
+
* Resolver returning the R2 bucket binding. Bindings arrive with the first
|
|
144
|
+
* request on Workers, so this must be a deferred closure, e.g.
|
|
145
|
+
* `binding: () => getWorkersEnv<Env>().BUCKET` — the same contract as
|
|
146
|
+
* `createD1Database({ binding })`.
|
|
147
|
+
*/
|
|
148
|
+
binding: () => unknown;
|
|
149
|
+
/**
|
|
150
|
+
* Base URL for `url()`: the bucket's custom domain (recommended) or its
|
|
151
|
+
* r2.dev subdomain. R2 has no derivable default — unlike S3 there is no
|
|
152
|
+
* `https://<bucket>.s3.<region>.amazonaws.com` — so `url()` throws with
|
|
153
|
+
* guidance when this is unset.
|
|
154
|
+
*/
|
|
155
|
+
publicUrl?: string;
|
|
156
|
+
/** Key prefix, same semantics as `S3DriverOptions.prefix`. */
|
|
157
|
+
prefix?: string;
|
|
158
|
+
/**
|
|
159
|
+
* The visibility every object in this bucket effectively has. R2 has no
|
|
160
|
+
* per-object ACL: a bucket is public (custom domain / r2.dev) or it is not.
|
|
161
|
+
* Defaults to `'public'` when `publicUrl` is set, `'private'` otherwise.
|
|
162
|
+
* `put({ visibility })` and `setVisibility()` throw when asked for the
|
|
163
|
+
* other value — the driver refuses to pretend it can enforce a per-object
|
|
164
|
+
* flag it cannot.
|
|
165
|
+
*/
|
|
166
|
+
visibility?: 'public' | 'private';
|
|
167
|
+
/**
|
|
168
|
+
* S3 API credentials used only by `temporaryUrl()`. Optional — omit it and
|
|
169
|
+
* `temporaryUrl()` throws with guidance.
|
|
170
|
+
*/
|
|
171
|
+
presign?: R2PresignOptions;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Cloudflare R2 storage driver over the Workers binding.
|
|
175
|
+
*
|
|
176
|
+
* @example
|
|
177
|
+
* ```ts
|
|
178
|
+
* const storage = createStorageManager({ default: 'media' })
|
|
179
|
+
* storage.registerDisk('media', () => new R2Driver({
|
|
180
|
+
* binding: () => getWorkersEnv<Env>().MEDIA,
|
|
181
|
+
* publicUrl: 'https://media.example.com',
|
|
182
|
+
* }))
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
declare class R2Driver implements StorageDriver {
|
|
186
|
+
private readonly resolveBinding;
|
|
187
|
+
private readonly publicUrl?;
|
|
188
|
+
private readonly prefix;
|
|
189
|
+
private readonly diskVisibility;
|
|
190
|
+
private readonly presign?;
|
|
191
|
+
constructor(options: R2DriverOptions);
|
|
192
|
+
private bucket;
|
|
193
|
+
private key;
|
|
194
|
+
/** Inverse of `key()`: strips the prefix so listings return app-relative paths. */
|
|
195
|
+
private unkey;
|
|
196
|
+
private directoryPrefix;
|
|
197
|
+
private assertVisibility;
|
|
198
|
+
put(path: string, content: Buffer | string, options?: PutOptions): Promise<string>;
|
|
199
|
+
putFile(_path: string, _localPath: string, _options?: PutOptions): Promise<string>;
|
|
200
|
+
get(path: string): Promise<Buffer | null>;
|
|
201
|
+
getAsString(path: string): Promise<string | null>;
|
|
202
|
+
exists(path: string): Promise<boolean>;
|
|
203
|
+
delete(path: string): Promise<boolean>;
|
|
204
|
+
deleteMany(paths: string[]): Promise<number>;
|
|
205
|
+
private deleteKeys;
|
|
206
|
+
copy(from: string, to: string): Promise<string>;
|
|
207
|
+
move(from: string, to: string): Promise<string>;
|
|
208
|
+
url(path: string): string;
|
|
209
|
+
temporaryUrl(path: string, expiration: Date): Promise<string>;
|
|
210
|
+
size(path: string): Promise<number>;
|
|
211
|
+
lastModified(path: string): Promise<Date>;
|
|
212
|
+
private metadataOrFail;
|
|
213
|
+
metadata(path: string): Promise<FileMetadata | null>;
|
|
214
|
+
files(directory: string): Promise<string[]>;
|
|
215
|
+
directories(directory: string): Promise<string[]>;
|
|
216
|
+
allFiles(directory: string): Promise<string[]>;
|
|
217
|
+
/** App-relative paths of every listed object, minus folder markers. */
|
|
218
|
+
private collectFiles;
|
|
219
|
+
private objects;
|
|
220
|
+
/**
|
|
221
|
+
* Follows `cursor` until `truncated` is false. A single `list()` call is
|
|
222
|
+
* capped at 1000 keys, so a one-page read (what `S3Driver.allFiles` does)
|
|
223
|
+
* silently truncates larger directories.
|
|
224
|
+
*/
|
|
225
|
+
private pages;
|
|
226
|
+
makeDirectory(path: string): Promise<void>;
|
|
227
|
+
deleteDirectory(path: string): Promise<void>;
|
|
228
|
+
setVisibility(path: string, visibility: 'public' | 'private'): Promise<void>;
|
|
229
|
+
getVisibility(path: string): Promise<'public' | 'private'>;
|
|
230
|
+
/** The key prefix (for tests and diagnostics). */
|
|
231
|
+
getPrefix(): string;
|
|
232
|
+
}
|
|
233
|
+
|
|
64
234
|
/**
|
|
65
235
|
* Configuration for the Cloudflare plugin. Currently empty — reserved for
|
|
66
236
|
* upcoming RFC 0003 parts (session/OAuth-state store wiring on Workers).
|
|
@@ -77,4 +247,4 @@ interface CloudflarePluginConfig {
|
|
|
77
247
|
*/
|
|
78
248
|
declare function cloudflarePlugin(config?: CloudflarePluginConfig): ServiceProviderConstructor;
|
|
79
249
|
|
|
80
|
-
export { type BuildCloudflareOutputOptions, type CloudflarePluginConfig, type WorkersAppLike, type WorkersExecutionContext, type WorkersHandler, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, resetWorkersEnv };
|
|
250
|
+
export { type BuildCloudflareOutputOptions, type CloudflarePluginConfig, type R2BucketLike, R2Driver, type R2DriverOptions, type R2PresignOptions, type WorkersAppLike, type WorkersExecutionContext, type WorkersHandler, buildCloudflareOutput, captureWorkersEnv, cloudflarePlugin, createWorkersHandler, flattenD1Migrations, getWorkersEnv, resetWorkersEnv };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
buildCloudflareOutput,
|
|
3
3
|
flattenD1Migrations
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-6DV73MBR.js";
|
|
5
5
|
|
|
6
6
|
// src/index.ts
|
|
7
7
|
import { definePlugin } from "@guren/core";
|
|
@@ -45,6 +45,326 @@ function createWorkersHandler(app) {
|
|
|
45
45
|
};
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
// src/storage/sigv4.ts
|
|
49
|
+
var ALGORITHM = "AWS4-HMAC-SHA256";
|
|
50
|
+
var TERMINATOR = "aws4_request";
|
|
51
|
+
var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
|
|
52
|
+
function encodeRfc3986(value) {
|
|
53
|
+
return encodeURIComponent(value).replace(
|
|
54
|
+
/[!'()*]/g,
|
|
55
|
+
(character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
function canonicalPath(pathname) {
|
|
59
|
+
return pathname.split("/").map(decodeAndEncodeSegment).join("/");
|
|
60
|
+
}
|
|
61
|
+
function decodeAndEncodeSegment(segment) {
|
|
62
|
+
return encodeRfc3986(decodeURIComponent(segment));
|
|
63
|
+
}
|
|
64
|
+
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("&");
|
|
68
|
+
}
|
|
69
|
+
function toHex(bytes) {
|
|
70
|
+
return Array.from(new Uint8Array(bytes)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
71
|
+
}
|
|
72
|
+
async function sha256Hex(value) {
|
|
73
|
+
return toHex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)));
|
|
74
|
+
}
|
|
75
|
+
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));
|
|
84
|
+
}
|
|
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);
|
|
91
|
+
}
|
|
92
|
+
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();
|
|
117
|
+
}
|
|
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;
|
|
123
|
+
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
|
+
}
|
|
351
|
+
};
|
|
352
|
+
function encodeKey(key) {
|
|
353
|
+
return key.split("/").map(encodeURIComponent).join("/");
|
|
354
|
+
}
|
|
355
|
+
function trimTrailingSlashes(value) {
|
|
356
|
+
let end = value.length;
|
|
357
|
+
while (end > 0 && value[end - 1] === "/") end--;
|
|
358
|
+
return value.slice(0, end);
|
|
359
|
+
}
|
|
360
|
+
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);
|
|
366
|
+
}
|
|
367
|
+
|
|
48
368
|
// src/index.ts
|
|
49
369
|
var factory = definePlugin({
|
|
50
370
|
name: "cloudflare",
|
|
@@ -55,6 +375,7 @@ function cloudflarePlugin(config = {}) {
|
|
|
55
375
|
return factory(config);
|
|
56
376
|
}
|
|
57
377
|
export {
|
|
378
|
+
R2Driver,
|
|
58
379
|
buildCloudflareOutput,
|
|
59
380
|
captureWorkersEnv,
|
|
60
381
|
cloudflarePlugin,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@guren/plugin-cloudflare",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -41,12 +41,13 @@
|
|
|
41
41
|
"typecheck": "tsc --noEmit"
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@guren/core": "^1.
|
|
44
|
+
"@guren/core": "^1.6.2",
|
|
45
45
|
"citty": "^0.1.6"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
48
|
"@cloudflare/workers-types": "^4.20260702.1",
|
|
49
49
|
"@types/node": "^20.14.10",
|
|
50
|
+
"miniflare": "5.20260801.1-alpha",
|
|
50
51
|
"tsup": "^8.5.0",
|
|
51
52
|
"typescript": "^5.4.0"
|
|
52
53
|
}
|