@guren/plugin-cloudflare 0.3.2 → 0.5.0

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.
@@ -1,7 +1,7 @@
1
1
  import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { relative, resolve, sep } from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
- import { DEV_ONLY_MODULES, SQL_CLIENT_MODULES, assertOutputDirOutsideRoot, importSpecifier, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, stageStaticAssets } from "@guren/core/internal/deploy-build";
4
+ import { DEV_ONLY_MODULES, SQL_CLIENT_MODULES, assertOutputDirOutsideRoot, clientManifestJson, importSpecifier, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, stageStaticAssets } from "@guren/core/internal/deploy-build";
5
5
  //#region src/build.ts
6
6
  /**
7
7
  * Assemble a deployable Cloudflare Workers directory (`.cloudflare/`) from a
@@ -23,13 +23,19 @@ async function buildCloudflareOutput(options = {}) {
23
23
  if (!existsSync(appEntry)) throw new Error(`Cloudflare build: app entry not found at ${appEntry}. Pass "appEntry" if your Application lives elsewhere.`);
24
24
  const ssrImport = await resolveSsrImport(ssrDir, ssrEntryKey);
25
25
  const assetEnv = resolveClientAssetEnv(publicDir, clientEntryKey, "Cloudflare build");
26
+ const viteManifest = clientManifestJson(publicDir);
26
27
  resetOutputDir(out, root, "Cloudflare build");
27
28
  stageStaticAssets(publicDir, resolve(out, "assets"));
29
+ const workerEnv = renderWorkerEnvModule({
30
+ assetEnv,
31
+ viteManifest
32
+ });
33
+ if (workerEnv) writeFileSync(resolve(out, "worker-env.js"), workerEnv);
28
34
  writeFileSync(resolve(out, "worker.js"), renderWorkerModule({
29
35
  out,
30
36
  appEntry,
31
37
  ssrImport,
32
- assetEnv
38
+ hasEnvModule: workerEnv !== void 0
33
39
  }));
34
40
  flattenD1Migrations(resolve(root, "db/migrations"), resolve(out, "d1-migrations"));
35
41
  writeDevOnlyStubs(out);
@@ -163,13 +169,34 @@ async function resolveSsrImport(ssrDir, ssrEntryKey) {
163
169
  rendererExport
164
170
  };
165
171
  }
172
+ /**
173
+ * Statements assigning the build-derived environment, emitted as a module of
174
+ * their own rather than as lines in worker.js: worker.js imports this module
175
+ * *first*, which is the only ordering ESM import hoisting cannot defeat. A
176
+ * statement in the worker body runs after the app's module graph has already
177
+ * evaluated, so a module-scope `viteAsset()` call in the app would see no
178
+ * manifest and throw before the worker could start. (The Lambda wrapper
179
+ * solves the same hazard by assigning env before dynamically importing the
180
+ * app.)
181
+ */
182
+ function renderWorkerEnvModule(input) {
183
+ const lines = [];
184
+ if (input.assetEnv.entry) lines.push(`process.env.GUREN_INERTIA_ENTRY = ${JSON.stringify(input.assetEnv.entry)}`);
185
+ if (input.assetEnv.styles) lines.push(`process.env.GUREN_INERTIA_STYLES = ${JSON.stringify(input.assetEnv.styles)}`);
186
+ if (input.viteManifest) lines.push(`process.env.GUREN_VITE_MANIFEST = ${JSON.stringify(input.viteManifest)}`);
187
+ if (lines.length === 0) return;
188
+ return [
189
+ "// Generated by `guren cloudflare:build`. Do not edit — regenerate instead.",
190
+ ...lines,
191
+ ""
192
+ ].join("\n");
193
+ }
166
194
  function renderWorkerModule(input) {
167
- const lines = ["// Generated by `guren cloudflare:build`. Do not edit — regenerate instead.", "import { createWorkersHandler } from '@guren/plugin-cloudflare'"];
195
+ const lines = ["// Generated by `guren cloudflare:build`. Do not edit — regenerate instead."];
196
+ if (input.hasEnvModule) lines.push("import './worker-env.js'");
197
+ lines.push("import { createWorkersHandler } from '@guren/plugin-cloudflare'");
168
198
  if (input.ssrImport) lines.push("import { setInertiaSsrRenderer } from '@guren/core'", `import * as ssrModule from ${JSON.stringify(importSpecifier(input.out, input.ssrImport.file, "Cloudflare build"))}`);
169
199
  lines.push(`import app from ${JSON.stringify(importSpecifier(input.out, input.appEntry, "Cloudflare build"))}`, "");
170
- if (input.assetEnv.entry) lines.push(`process.env.GUREN_INERTIA_ENTRY = ${JSON.stringify(input.assetEnv.entry)}`);
171
- if (input.assetEnv.styles) lines.push(`process.env.GUREN_INERTIA_STYLES = ${JSON.stringify(input.assetEnv.styles)}`);
172
- if (input.assetEnv.entry || input.assetEnv.styles) lines.push("");
173
200
  if (input.ssrImport) lines.push(`setInertiaSsrRenderer(ssrModule.${input.ssrImport.rendererExport})`, "");
174
201
  lines.push("export default createWorkersHandler(app)", "");
175
202
  return lines.join("\n");
package/dist/commands.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as buildCloudflareOutput } from "./build-DxgM3l-5.js";
1
+ import { t as buildCloudflareOutput } from "./build-B7zQ13ai.js";
2
2
  import { defineCommand } from "citty";
3
3
  var commands_default = { "cloudflare:build": defineCommand({
4
4
  meta: {
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { FileMetadata, PutOptions, ServiceProviderConstructor, StorageDriver } from "@guren/core";
1
+ import { FileMetadata, GetStreamOptions, PutOptions, ServiceProviderConstructor, StorageDriver, StorageDriverCapabilities, TemporaryUrlOptions } from "@guren/core";
2
2
  import { PathLike } from "@guren/core/internal/deploy-build";
3
3
  //#region src/env.d.ts
4
4
  /** First call wins; later calls are ignored (never overwrite a live env). */
@@ -125,9 +125,16 @@ interface R2PutOptionsLike {
125
125
  customMetadata?: Record<string, string>;
126
126
  }
127
127
  type R2PutValue = R2StreamLike | R2BlobLike | ArrayBuffer | ArrayBufferView | string | null;
128
+ interface R2GetOptionsLike {
129
+ /** R2's offset/length range form (the driver never sends `suffix`). */
130
+ range?: {
131
+ offset: number;
132
+ length?: number;
133
+ };
134
+ }
128
135
  interface R2BucketLike {
129
136
  head(key: string): Promise<R2ObjectLike | null>;
130
- get(key: string): Promise<R2ObjectBodyLike | null>;
137
+ get(key: string, options?: R2GetOptionsLike): Promise<R2ObjectBodyLike | null>;
131
138
  put(key: string, value: R2PutValue, options?: R2PutOptionsLike): Promise<R2ObjectLike | null>;
132
139
  delete(keys: string | string[]): Promise<void>;
133
140
  list(options?: R2ListOptionsLike): Promise<R2ObjectsLike>;
@@ -186,6 +193,12 @@ interface R2DriverOptions {
186
193
  * ```
187
194
  */
188
195
  declare class R2Driver implements StorageDriver {
196
+ /**
197
+ * Declared iff `presign` credentials were configured — a config fact,
198
+ * never a probe (RFC 0015 §3): without them `temporaryUrl()` throws, and
199
+ * the delivery route must know that *before* handing out a redirect.
200
+ */
201
+ readonly capabilities?: StorageDriverCapabilities;
189
202
  private readonly resolveBinding;
190
203
  private readonly publicUrl?;
191
204
  private readonly prefix;
@@ -202,6 +215,7 @@ declare class R2Driver implements StorageDriver {
202
215
  putFile(_path: string, _localPath: string, _options?: PutOptions): Promise<string>;
203
216
  get(path: string): Promise<Buffer | null>;
204
217
  getAsString(path: string): Promise<string | null>;
218
+ getStream(path: string, options?: GetStreamOptions): Promise<ReadableStream<Uint8Array> | null>;
205
219
  exists(path: string): Promise<boolean>;
206
220
  delete(path: string): Promise<boolean>;
207
221
  deleteMany(paths: string[]): Promise<number>;
@@ -209,7 +223,7 @@ declare class R2Driver implements StorageDriver {
209
223
  copy(from: string, to: string): Promise<string>;
210
224
  move(from: string, to: string): Promise<string>;
211
225
  url(path: string): string;
212
- temporaryUrl(path: string, expiration: Date): Promise<string>;
226
+ temporaryUrl(path: string, expiration: Date, options?: TemporaryUrlOptions): Promise<string>;
213
227
  size(path: string): Promise<number>;
214
228
  lastModified(path: string): Promise<Date>;
215
229
  private metadataOrFail;
@@ -222,8 +236,8 @@ declare class R2Driver implements StorageDriver {
222
236
  private objects;
223
237
  /**
224
238
  * Follows `cursor` until `truncated` is false. A single `list()` call is
225
- * capped at 1000 keys, so a one-page read (what `S3Driver.allFiles` does)
226
- * silently truncates larger directories.
239
+ * capped at 1000 keys, so a one-page read silently truncates larger
240
+ * directories.
227
241
  */
228
242
  private pages;
229
243
  makeDirectory(path: string): Promise<void>;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as flattenD1Migrations, t as buildCloudflareOutput } from "./build-DxgM3l-5.js";
1
+ import { n as flattenD1Migrations, t as buildCloudflareOutput } from "./build-B7zQ13ai.js";
2
2
  import { definePlugin } from "@guren/core";
3
3
  //#region src/env.ts
4
4
  let holder;
@@ -81,9 +81,27 @@ async function hmac(key, value) {
81
81
  }, false, ["sign"]);
82
82
  return crypto.subtle.sign("HMAC", cryptoKey, new TextEncoder().encode(value));
83
83
  }
84
- /** `AWS4<secret>` → date → region → service → terminator. */
85
- async function signingKey(secretAccessKey, dateStamp, region, service) {
86
- return hmac(await hmac(await hmac(await hmac(new TextEncoder().encode(`AWS4${secretAccessKey}`), dateStamp), region), service), TERMINATOR);
84
+ /**
85
+ * `AWS4<secret>` → date → region → service → terminator, cached per
86
+ * credential and day: the delivery route presigns once per request on
87
+ * redirect-mode disks, and the four-step HMAC chain (eight `crypto.subtle`
88
+ * host calls) only changes when the date stamp rolls over. Keyed by access
89
+ * key id — never the secret — plus scope; self-bounding, but capped anyway
90
+ * so a pathological key rotation cannot grow it.
91
+ */
92
+ const signingKeyCache = /* @__PURE__ */ new Map();
93
+ const SIGNING_KEY_CACHE_MAX = 8;
94
+ function signingKey(accessKeyId, secretAccessKey, dateStamp, region, service) {
95
+ const cacheKey = `${accessKeyId}/${dateStamp}/${region}/${service}`;
96
+ const cached = signingKeyCache.get(cacheKey);
97
+ if (cached) return cached;
98
+ const derived = (async () => {
99
+ return hmac(await hmac(await hmac(await hmac(new TextEncoder().encode(`AWS4${secretAccessKey}`), dateStamp), region), service), TERMINATOR);
100
+ })();
101
+ if (signingKeyCache.size >= SIGNING_KEY_CACHE_MAX) signingKeyCache.clear();
102
+ signingKeyCache.set(cacheKey, derived);
103
+ derived.catch(() => signingKeyCache.delete(cacheKey));
104
+ return derived;
87
105
  }
88
106
  /**
89
107
  * Presign a GET so the URL alone authorizes the read until it expires.
@@ -115,7 +133,7 @@ async function presignGetUrl(options) {
115
133
  scope,
116
134
  await sha256Hex(canonicalRequest)
117
135
  ].join("\n");
118
- const key = await signingKey(secretAccessKey, dateStamp, region, service);
136
+ const key = await signingKey(accessKeyId, secretAccessKey, dateStamp, region, service);
119
137
  url.searchParams.set("X-Amz-Signature", toHex(await hmac(key, stringToSign)));
120
138
  return url.toString();
121
139
  }
@@ -140,6 +158,12 @@ const DELETE_CONCURRENCY = 6;
140
158
  * ```
141
159
  */
142
160
  var R2Driver = class {
161
+ /**
162
+ * Declared iff `presign` credentials were configured — a config fact,
163
+ * never a probe (RFC 0015 §3): without them `temporaryUrl()` throws, and
164
+ * the delivery route must know that *before* handing out a redirect.
165
+ */
166
+ capabilities;
143
167
  resolveBinding;
144
168
  publicUrl;
145
169
  prefix;
@@ -151,6 +175,7 @@ var R2Driver = class {
151
175
  this.prefix = trimSlashes(options.prefix ?? "");
152
176
  this.diskVisibility = options.visibility ?? (options.publicUrl ? "public" : "private");
153
177
  this.presign = options.presign;
178
+ if (options.presign) this.capabilities = { presignedGet: true };
154
179
  }
155
180
  bucket() {
156
181
  const binding = this.resolveBinding();
@@ -193,6 +218,15 @@ var R2Driver = class {
193
218
  const object = await this.bucket().get(this.key(path));
194
219
  return object ? object.text() : null;
195
220
  }
221
+ async getStream(path, options) {
222
+ const range = options?.range;
223
+ const object = await this.bucket().get(this.key(path), range ? { range: {
224
+ offset: range.start,
225
+ ...range.end !== void 0 ? { length: range.end - range.start + 1 } : {}
226
+ } } : void 0);
227
+ if (!object) return null;
228
+ return object.body;
229
+ }
196
230
  async exists(path) {
197
231
  return await this.bucket().head(this.key(path)) !== null;
198
232
  }
@@ -234,7 +268,7 @@ var R2Driver = class {
234
268
  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
269
  return `${this.publicUrl}/${encodeKey(this.key(path))}`;
236
270
  }
237
- async temporaryUrl(path, expiration) {
271
+ async temporaryUrl(path, expiration, options) {
238
272
  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
273
  const expiresIn = Math.floor((expiration.getTime() - Date.now()) / 1e3);
240
274
  if (expiresIn > MAX_PRESIGN_SECONDS) throw new Error(`R2Driver.temporaryUrl(): R2 presigned URLs may be valid for at most 7 days (requested ${expiresIn}s).`);
@@ -301,8 +335,8 @@ var R2Driver = class {
301
335
  }
302
336
  /**
303
337
  * 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.
338
+ * capped at 1000 keys, so a one-page read silently truncates larger
339
+ * directories.
306
340
  */
307
341
  async *pages(options) {
308
342
  const bucket = this.bucket();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/plugin-cloudflare",
3
- "version": "0.3.2",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -41,7 +41,7 @@
41
41
  "typecheck": "tsc --noEmit"
42
42
  },
43
43
  "dependencies": {
44
- "@guren/core": "^1.8.1",
44
+ "@guren/core": "^1.11.0",
45
45
  "citty": "^0.1.6"
46
46
  },
47
47
  "devDependencies": {