@harlan-zw/nuxt-cloudflare 0.1.0 → 0.3.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.
package/README.md CHANGED
@@ -1,8 +1,64 @@
1
- # @harlan-zw/nuxt-cloudflare
1
+ <h1>@harlan-zw/nuxt-cloudflare</h1>
2
2
 
3
- Opinionated Cloudflare defaults and deploy diagnostics for Nuxt 4.
3
+ [![npm version][npm-version-src]][npm-version-href]
4
+ [![npm downloads][npm-downloads-src]][npm-downloads-href]
5
+ [![License][license-src]][license-href]
6
+ [![Nuxt][nuxt-src]][nuxt-href]
4
7
 
5
- The module extracts production patterns already proven in Nuxt SEO and gscdump. It intentionally owns platform policy, not application topology.
8
+ Nuxt Cloudflare gives a Nuxt 4 app opinionated Cloudflare defaults, a generated Wrangler config, and diagnostics that fail a bad deploy before Cloudflare does.
9
+
10
+ The defaults come from production patterns already running in Nuxt SEO and gscdump. The module owns platform policy. Your application topology stays yours.
11
+
12
+ Status: experimental. APIs may change before the first release.
13
+
14
+ <p align="center">
15
+ <table>
16
+ <tbody>
17
+ <td align="center">
18
+ <sub>Made possible by my <a href="https://github.com/sponsors/harlan-zw">Sponsor Program 💖</a><br> Follow me <a href="https://twitter.com/harlan_zw">@harlan_zw</a> 🐦 • Join <a href="https://discord.gg/275MBUBvgP">Discord</a> for help</sub><br>
19
+ </td>
20
+ </tbody>
21
+ </table>
22
+ </p>
23
+
24
+ ## Features
25
+
26
+ - ⚙️ **Generated Wrangler config:** Cloudflare preset, Node compatibility, and sane observability, with anything you authored left alone.
27
+ - 🩺 **Deploy doctor:** audits Wrangler's effective config, including generated redirects and every named environment.
28
+ - 💰 **Cost controls:** 1% log and trace sampling, asset-first routing, and warnings when a setting turns free requests into billed ones.
29
+ - 🗄️ **Workers Caching:** version-isolated by default, with a fail-closed `private, no-store` for rendered HTML.
30
+ - 📦 **Partial bundling:** chunks deploy as separate modules, which cut startup CPU on the Nuxt SEO Pro Worker from 118ms to 81ms.
31
+ - 🔑 **Exact binding types:** `nuxt prepare` runs Wrangler and writes a compatibility-aware declaration, then production builds fail on drift.
32
+ - 🧰 **D1 primitives:** recovering sessions, safe write retries, and parameter plans that respect the 100-bind limit.
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ npx nuxi@latest module add @harlan-zw/nuxt-cloudflare
38
+ ```
39
+
40
+ > [!TIP]
41
+ > Generate an Agent Skill for this package using [skilld](https://github.com/harlan-zw/skilld):
42
+ > ```bash
43
+ > npx skilld add @harlan-zw/nuxt-cloudflare
44
+ > ```
45
+
46
+ ```ts
47
+ export default defineNuxtConfig({
48
+ modules: ['@harlan-zw/nuxt-cloudflare'],
49
+
50
+ nuxtCloudflare: {
51
+ requiredSecrets: ['NUXT_SESSION_PASSWORD'],
52
+ },
53
+
54
+ nitro: {
55
+ storage: {
56
+ cache: { driver: 'cloudflare-kv-binding', binding: 'CACHE' },
57
+ kv: { driver: 'cloudflare-kv-binding', binding: 'KV' },
58
+ },
59
+ },
60
+ })
61
+ ```
6
62
 
7
63
  ## Defaults
8
64
 
@@ -15,6 +71,7 @@ Every default below yields to a value you wrote. The root `wrangler.jsonc`, `wra
15
71
  - `workers_dev` disabled when a route proves the Worker remains reachable; workers without routes must choose explicitly
16
72
  - Version metadata binding at `CF_VERSION_METADATA`
17
73
  - Smart Placement enabled unless the project chooses a placement
74
+ - Partial bundling: `find_additional_modules` plus a fallthrough `ESModule` rule for `**/*.mjs`, unless a rule already covers mjs or `no_bundle` is set
18
75
  - Workers Caching enabled with version isolation
19
76
  - Rendered HTML forced to `private, no-store`; explicit non-HTML cache policies remain intact
20
77
  - Source-map upload when the Nitro build emits maps; an authored value is preserved
@@ -29,24 +86,9 @@ Every default below yields to a value you wrote. The root `wrangler.jsonc`, `wra
29
86
 
30
87
  Persistent KV mounts are never wrapped. The expiry policy applies only to cache data.
31
88
 
32
- ## Setup
33
-
34
- ```ts
35
- export default defineNuxtConfig({
36
- modules: ['@harlan-zw/nuxt-cloudflare'],
37
-
38
- nuxtCloudflare: {
39
- requiredSecrets: ['NUXT_SESSION_PASSWORD'],
40
- },
89
+ ## Configuration
41
90
 
42
- nitro: {
43
- storage: {
44
- cache: { driver: 'cloudflare-kv-binding', binding: 'CACHE' },
45
- kv: { driver: 'cloudflare-kv-binding', binding: 'KV' },
46
- },
47
- },
48
- })
49
- ```
91
+ Everything below is optional. The defaults above already cover a plain deploy.
50
92
 
51
93
  To configure a cache mount when one does not already exist:
52
94
 
@@ -65,7 +107,41 @@ Cloudflare KV requires TTLs of at least 60 seconds. The cache wrapper raises sho
65
107
 
66
108
  Keep server runtime secret defaults empty. Nuxt reads matching `NUXT_*` values from Worker secret bindings at runtime. The production build guard rejects secret build environment values before Nitro can include them in the bundle. Nuxt Scripts proxy signing remains allowed because that module registers its security plugin during the build.
67
109
 
68
- Workers Caching is separate from Nitro's KV-backed cache. The module enables version-isolated caching by default. Rendered HTML always stays private. API and asset responses keep explicit cache policies. Set `workersCache: { _tag: 'disabled' }` to opt out. Choose cross-version caching only with an explicit purge path.
110
+ Workers Caching is separate from Nitro's KV-backed cache. The module enables version-isolated caching by default. Set `workersCache: { _tag: 'disabled' }` to opt out. Choose cross-version caching only with an explicit purge path.
111
+
112
+ Partial bundling is on by default. Wrangler's default bundling inlines every lazy chunk into one module the isolate parses at startup; on the Nuxt SEO Pro Worker that was a 26.3MB bundle, and partial bundling cut `wrangler check startup` active CPU from 118ms to 81ms by deploying chunks as separate modules. The generated config gains `find_additional_modules: true` and a fallthrough `ESModule` rule for `**/*.mjs`; rules you wrote are kept, and one that already covers mjs wins. Configs with `no_bundle` inject neither key, because Wrangler already defaults `find_additional_modules` to true there and applies your rules as written. Set `partialBundles: false` to keep single-bundle deploys.
113
+
114
+ The module writes a fail-closed `private, no-store` before routing, so a response nobody described is never cached. It never rewrites a policy you set on a response that is not a rendered document, so asset and API route rules are yours.
115
+
116
+ For a rendered document it applies `workersCache.html`:
117
+
118
+ | Value | Behaviour |
119
+ | --- | --- |
120
+ | `auto` (default) | Honour your `cache-control`, clamped to a retention window another module publishes. Falls back to `no-store` when nothing publishes one. |
121
+ | `app` | Always honour your `cache-control`. You own the version-skew risk. |
122
+ | `no-store` | Always overwrite it. |
123
+
124
+ A cached document can name build chunks a later deploy deleted, which is why `auto` needs a guarantee. [`nuxt-skew-protection`](https://github.com/harlan-zw/nuxt-skew-protection) publishes one when you set `skewProtection: { htmlCache: true }`.
125
+
126
+ Four things are refused whatever you configure, because a shared cache keys on the URL: a request carrying credentials, a response setting a cookie, a status other than 200, and a response varying on `Cookie` or `Authorization`.
127
+
128
+ ### Writing cache rules
129
+
130
+ `edgeCache` builds the headers for a route rule:
131
+
132
+ ```ts
133
+ import { edgeCache, NO_STORE } from '@harlan-zw/nuxt-cloudflare/cache'
134
+
135
+ export default defineNuxtConfig({
136
+ routeRules: {
137
+ '/api/feed': edgeCache({ maxAge: 60 }),
138
+ '/api/reports': edgeCache({ maxAge: 3600, staleWhileRevalidate: 86400, browser: 'revalidate' }),
139
+ '/api/private': NO_STORE,
140
+ },
141
+ })
142
+ ```
143
+
144
+ It emits `max-age`, never `s-maxage`. Cloudflare reads `s-maxage` as implying `proxy-revalidate`, which disables `stale-while-revalidate` and `stale-if-error`, so a policy that looks like it serves stale blocks on revalidation instead. The module warns at build if a route rule you wrote by hand hits that.
69
145
 
70
146
  ## Cost controls
71
147
 
@@ -233,7 +309,7 @@ The helper owns a private temporary directory and creates the JSON file with mod
233
309
 
234
310
  The module does not choose Worker names, routes, domains, resource IDs, placement, CPU limits, queue jobs, R2 deletion policy, or deployment promotion. `@harlan-zw/nuxt-cf-jobs` continues to own queues, job durability, recovery, and outbox behavior.
235
311
 
236
- Next high-value extractions from Nuxt SEO and gscdump:
312
+ Next extractions from Nuxt SEO and gscdump:
237
313
 
238
314
  1. Nuxt Content D1 sync plus readiness verification
239
315
  2. Expand-only D1 migration audit with protected-table rebuild detection
@@ -243,3 +319,28 @@ Next high-value extractions from Nuxt SEO and gscdump:
243
319
  6. R2 lifecycle declaration and read-only storage stocktake
244
320
 
245
321
  These remain separate adapters because their schemas, retention, and deployment ordering require explicit application policy.
322
+
323
+ ## Sponsors
324
+
325
+ <p align="center">
326
+ <a href="https://raw.githubusercontent.com/harlan-zw/static/main/sponsors.svg">
327
+ <img src='https://raw.githubusercontent.com/harlan-zw/static/main/sponsors.svg' alt='sponsors'/>
328
+ </a>
329
+ </p>
330
+
331
+ ## License
332
+
333
+ Licensed under the [MIT license](https://github.com/harlan-zw/harlan-nuxt/blob/main/packages/nuxt-cloudflare/LICENSE.md).
334
+
335
+ <!-- Badges -->
336
+ [npm-version-src]: https://img.shields.io/npm/v/%40harlan-zw%2Fnuxt-cloudflare/latest.svg?style=flat&colorA=18181B&colorB=28CF8D
337
+ [npm-version-href]: https://npmjs.com/package/@harlan-zw/nuxt-cloudflare
338
+
339
+ [npm-downloads-src]: https://img.shields.io/npm/dm/%40harlan-zw%2Fnuxt-cloudflare.svg?style=flat&colorA=18181B&colorB=28CF8D
340
+ [npm-downloads-href]: https://npmjs.com/package/@harlan-zw/nuxt-cloudflare
341
+
342
+ [license-src]: https://img.shields.io/github/license/harlan-zw/harlan-nuxt.svg?style=flat&colorA=18181B&colorB=28CF8D
343
+ [license-href]: https://github.com/harlan-zw/harlan-nuxt/blob/main/packages/nuxt-cloudflare/LICENSE.md
344
+
345
+ [nuxt-src]: https://img.shields.io/badge/Nuxt-18181B?logo=nuxt
346
+ [nuxt-href]: https://nuxt.com
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Cache headers for a Cloudflare route rule.
3
+ *
4
+ * Written for `nuxt.config.ts`, so it is a pure value producer with no runtime
5
+ * and no side effects. It returns the same plain literal you would write by
6
+ * hand, which means the module's build validator and its `beforeResponse`
7
+ * contract see exactly what they would have seen anyway. There is no marker, no
8
+ * exemption, and no second source of truth.
9
+ *
10
+ * ```ts
11
+ * routeRules: {
12
+ * '/api/feed': edgeCache({ maxAge: 60 }),
13
+ * '/api/reports': edgeCache({ maxAge: 3600, staleWhileRevalidate: 86400, browser: 'revalidate' }),
14
+ * '/api/private': NO_STORE,
15
+ * }
16
+ * ```
17
+ *
18
+ * The reason it exists is one rule that is easy to get wrong and silent when
19
+ * you do: **never emit `s-maxage`**. Cloudflare reads it as implying
20
+ * `proxy-revalidate`, which disables `stale-while-revalidate` and
21
+ * `stale-if-error` outright, so a policy that looks like it serves stale
22
+ * quietly blocks on revalidation instead. Three separate sites hand-wrote this
23
+ * pattern and all three left a comment about the same trap.
24
+ */
25
+ interface EdgeCacheOptions {
26
+ /**
27
+ * Seconds a shared cache serves this without revalidating.
28
+ *
29
+ * Emitted as `max-age`, never `s-maxage`, for the reason above. Cloudflare
30
+ * falls back to `max-age` for the edge when `s-maxage` is absent, so this
31
+ * bounds the edge either way.
32
+ */
33
+ maxAge: number;
34
+ /** Seconds a stale copy may be served while a fresh one is fetched behind it. */
35
+ staleWhileRevalidate?: number;
36
+ /** Seconds a stale copy may be served while the origin is failing. */
37
+ staleIfError?: number;
38
+ /**
39
+ * What browsers get.
40
+ *
41
+ * - `'no-store'` (default) emits no `cache-control`, so the module's own
42
+ * fail-closed floor stands and only the edge caches.
43
+ * - `'revalidate'` emits `public, max-age=0`, so a browser always asks but
44
+ * the edge usually answers.
45
+ * - `{ maxAge }` gives browsers a real lifetime of their own.
46
+ */
47
+ browser?: 'no-store' | 'revalidate' | {
48
+ maxAge: number;
49
+ immutable?: boolean;
50
+ };
51
+ /**
52
+ * Append `private="set-cookie"`.
53
+ *
54
+ * A qualified `private` names the fields a shared cache must drop rather than
55
+ * refusing the response, so a response that sets a cookie is still storable
56
+ * with the cookie stripped from the stored copy. Without it, any `Set-Cookie`
57
+ * makes the response unstorable.
58
+ */
59
+ dropSetCookie?: boolean;
60
+ }
61
+ interface EdgeCacheRule {
62
+ headers: Record<string, string>;
63
+ }
64
+ /** Never stored anywhere. The explicit form of the module's default. */
65
+ declare const NO_STORE: EdgeCacheRule;
66
+ declare function edgeCache(options: EdgeCacheOptions): EdgeCacheRule;
67
+
68
+ export { NO_STORE, edgeCache };
69
+ export type { EdgeCacheOptions, EdgeCacheRule };
package/dist/cache.mjs ADDED
@@ -0,0 +1,38 @@
1
+ const NO_STORE = {
2
+ headers: { "cache-control": "private, no-store" }
3
+ };
4
+ function directives(parts) {
5
+ return parts.filter((part) => Boolean(part)).join(", ");
6
+ }
7
+ function edgeCache(options) {
8
+ if (!Number.isFinite(options.maxAge) || options.maxAge <= 0) {
9
+ throw new Error(
10
+ `[nuxt-cloudflare] edgeCache needs a positive maxAge, received ${options.maxAge}. Use NO_STORE for a route that must never be cached.`
11
+ );
12
+ }
13
+ const qualified = options.dropSetCookie ? 'private="set-cookie"' : void 0;
14
+ const edge = directives([
15
+ "public",
16
+ `max-age=${Math.floor(options.maxAge)}`,
17
+ options.staleWhileRevalidate ? `stale-while-revalidate=${Math.floor(options.staleWhileRevalidate)}` : void 0,
18
+ options.staleIfError ? `stale-if-error=${Math.floor(options.staleIfError)}` : void 0,
19
+ qualified
20
+ ]);
21
+ const headers = { "cloudflare-cdn-cache-control": edge };
22
+ const browser = options.browser ?? "no-store";
23
+ if (browser === "revalidate") {
24
+ headers["cache-control"] = directives(["public", "max-age=0", qualified]);
25
+ } else if (typeof browser === "object") {
26
+ if (!Number.isFinite(browser.maxAge) || browser.maxAge < 0)
27
+ throw new Error(`[nuxt-cloudflare] edgeCache browser.maxAge must be zero or more, received ${browser.maxAge}.`);
28
+ headers["cache-control"] = directives([
29
+ "public",
30
+ `max-age=${Math.floor(browser.maxAge)}`,
31
+ browser.immutable ? "immutable" : void 0,
32
+ qualified
33
+ ]);
34
+ }
35
+ return { headers };
36
+ }
37
+
38
+ export { NO_STORE, edgeCache };
package/dist/d1.mjs CHANGED
@@ -10,7 +10,17 @@ const SESSION_RESET_D1_SIGNALS = [
10
10
  "D1 DB reset because its code was updated",
11
11
  "Internal error while starting up D1 DB storage caused object to be reset",
12
12
  "Internal error in D1 DB storage caused object to be reset",
13
- "storage caused object to be reset"
13
+ "storage caused object to be reset",
14
+ // Cloudflare evicts the Durable Object backing a session and reports it in
15
+ // its own words: "Connection closed: this Durable Object instance is no
16
+ // longer active. Reconnect or retry the request." Same family as
17
+ // `D1_RESET_DO` — the session is gone, the query is replayable.
18
+ //
19
+ // Match the Durable Object clause, NOT the "Connection closed" prefix the
20
+ // message leads with: that prefix is generic enough to appear on unrelated
21
+ // transports, and replaying an arbitrary closed connection as a D1 session
22
+ // reset would retry writes that never belonged to this classifier.
23
+ "Durable Object instance is no longer active"
14
24
  ];
15
25
  const TRANSIENT_D1_SIGNALS = [
16
26
  "Network connection lost",
package/dist/module.d.mts CHANGED
@@ -19,6 +19,7 @@ interface ModuleOptions {
19
19
  defaultTtl?: number;
20
20
  };
21
21
  logsSampleRate?: number;
22
+ partialBundles?: boolean;
22
23
  publicVarNames?: string[];
23
24
  requiredSecrets?: string[];
24
25
  sourceMaps?: boolean;
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=4.5.0 <5.0.0"
6
6
  },
7
- "version": "0.1.0",
7
+ "version": "0.3.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -2,6 +2,7 @@ import process from 'node:process';
2
2
  import { useLogger, defineNuxtModule, hasNuxtModule, addTypeTemplate } from '@nuxt/kit';
3
3
  import { resolve } from 'pathe';
4
4
  import { a as diagnoseWranglerSourceConfigs, d as discoverWranglerSourceConfigs, e as evaluateWranglerDiagnostics } from './shared/nuxt-cloudflare.6X-qzF_b.mjs';
5
+ import { resolveHtmlCacheGuarantee, staleDirectivesAreDisabled } from '../dist/runtime/server/utils/workers-cache.js';
5
6
  import { readWranglerJsonFile, diagnoseWranglerConfig, formatWranglerDiagnostics, readAuthoredWranglerConfig, applyCloudflareDefaults } from './wrangler.mjs';
6
7
  import 'node:fs';
7
8
  import 'node:fs/promises';
@@ -164,6 +165,7 @@ function configureNitroCloudflare(nitro, options, context = {}) {
164
165
  nitro.cloudflare.wrangler = applyCloudflareDefaults(nitro.cloudflare.wrangler ?? {}, {
165
166
  compatibilityDate: options.compatibilityDate,
166
167
  logsSampleRate: options.logsSampleRate,
168
+ partialBundles: options.partialBundles,
167
169
  requiredSecrets: options.requiredSecrets,
168
170
  tracesSampleRate: options.tracesSampleRate,
169
171
  uploadSourceMaps: options.sourceMaps ?? nitro.sourceMap ?? context.serverSourceMaps ?? false,
@@ -291,9 +293,37 @@ function setupCloudflareModule(options, nuxt) {
291
293
  }
292
294
  });
293
295
  nuxt.hook("nitro:config", (nitroConfig) => {
294
- if (resolveModuleWorkersCachePolicy(options)._tag === "disabled")
296
+ const policy = resolveModuleWorkersCachePolicy(options);
297
+ if (policy._tag === "disabled")
295
298
  return;
296
- const violations = findHtmlCacheRouteRuleViolations(nitroConfig.routeRules);
299
+ const mode = policy.html ?? "auto";
300
+ const guarantee = resolveHtmlCacheGuarantee(nuxt.options.runtimeConfig.htmlCacheCapabilities);
301
+ nuxt.options.runtimeConfig.nuxtCloudflare = {
302
+ ...typeof nuxt.options.runtimeConfig.nuxtCloudflare === "object" ? nuxt.options.runtimeConfig.nuxtCloudflare : {},
303
+ htmlCacheMode: mode
304
+ };
305
+ if (mode === "app") {
306
+ logger.info("Workers Cache honours your HTML cache rules. You own the version-skew risk.");
307
+ } else if (guarantee._tag === "bounded" && mode === "auto") {
308
+ logger.info(`${guarantee.by} guarantees chunks for ${guarantee.ceilingSeconds}s. Workers Cache honours your HTML cache rules up to that limit.`);
309
+ } else {
310
+ logger.info("Workers Cache is on. HTML documents get `private, no-store`. A module must guarantee chunk retention to change this.");
311
+ }
312
+ if (mode === "app" || guarantee._tag === "bounded")
313
+ logger.info("A shared cache keys on the URL. If a page changes with a request header, set `Vary` on it. Responses varying on Cookie or Authorization are never shared.");
314
+ for (const [route, rule] of Object.entries(nitroConfig.routeRules ?? {})) {
315
+ const headers = rule?.headers;
316
+ if (!headers)
317
+ continue;
318
+ for (const [name, value] of Object.entries(headers)) {
319
+ if (!name.toLowerCase().endsWith("cache-control"))
320
+ continue;
321
+ if (staleDirectivesAreDisabled(value))
322
+ logger.warn(`routeRules['${route}'] sets \`${name}: ${value}\`. Cloudflare disables stale serving when \`s-maxage\`, \`must-revalidate\` or \`proxy-revalidate\` is present. Use \`max-age\` for the edge freshness window instead.`);
323
+ }
324
+ }
325
+ const relaxable = mode === "app" || guarantee._tag === "bounded";
326
+ const violations = findHtmlCacheRouteRuleViolations(nitroConfig.routeRules).filter((violation) => !(relaxable && violation._tag === "html-cache-header"));
297
327
  const warnings = violations.filter((violation) => violation.severity === "warning");
298
328
  const errors = violations.filter((violation) => violation.severity === "error");
299
329
  if (warnings.length > 0)
@@ -301,12 +331,15 @@ function setupCloudflareModule(options, nuxt) {
301
331
  if (errors.length > 0) {
302
332
  throw new Error(
303
333
  `[nuxt-cloudflare] HTML route rules conflict with Workers Caching:
304
- ${formatHtmlCacheRouteRuleViolations(errors)}`
334
+ ${formatHtmlCacheRouteRuleViolations(errors)}
335
+ A chunk-retention guarantee does not cover these. A prerendered route is served by Workers Assets, and a cache/swr/isr rule stores the response in nitro's own path-keyed cache. Use a plain \`cache-control\` header rule instead, or set \`nuxtCloudflare.workersCache.html: 'app'\` to own the risk.`
305
336
  );
306
337
  }
307
338
  });
308
339
  if (!nuxt.options.dev) {
309
340
  nuxt.hook("nitro:init", (nitro) => {
341
+ if (!nitro.options.preset?.includes("cloudflare"))
342
+ return;
310
343
  nitro.hooks.hook("compiled", () => auditGeneratedWranglerConfig(
311
344
  nitro,
312
345
  options,
@@ -329,6 +362,7 @@ const module$1 = defineNuxtModule({
329
362
  compatibilityMaxAgeDays: 90,
330
363
  doctor: { _tag: "advisory" },
331
364
  logsSampleRate: 0.01,
365
+ partialBundles: true,
332
366
  tracesSampleRate: 0.01,
333
367
  versionMetadataBinding: "CF_VERSION_METADATA",
334
368
  workersCache: { _tag: "enabled", crossVersion: false }
@@ -23,11 +23,10 @@ import type { NitroApp } from 'nitropack/types';
23
23
  * module rests on — a reviewer can read the allowlist and know nothing else can
24
24
  * reach an event.
25
25
  *
26
- * So this cannot build its payload conditionally. Every key is present on every
27
- * call, `null` where the value is unavailable, and the whole thing is one
28
- * literal. An earlier version assembled a `Record` and passed the variable; it
29
- * failed the CONSUMING application's build, which is the worst place for a
30
- * module's mistake to surface.
26
+ * So this cannot build its payload conditionally. Every key is present in the
27
+ * source literal. The Wide Events transform removes `undefined` values at
28
+ * runtime. An earlier version assembled a `Record` and passed the variable; it
29
+ * failed the consuming application's build.
31
30
  */
32
31
  declare const _default: (nitroApp: NitroApp) => void;
33
32
  export default _default;
@@ -5,8 +5,8 @@ export default (nitroApp) => {
5
5
  recordCloudflareWideEventFields(event);
6
6
  });
7
7
  };
8
- function stringOrNull(value) {
9
- return typeof value === "string" ? value : null;
8
+ function stringOrUndefined(value) {
9
+ return typeof value === "string" ? value : void 0;
10
10
  }
11
11
  export function recordCloudflareWideEventFields(event) {
12
12
  const cf = event.context.cloudflare?.request?.cf;
@@ -14,14 +14,14 @@ export function recordCloudflareWideEventFields(event) {
14
14
  if (!cf && !d1)
15
15
  return;
16
16
  addWideEventFields(event, {
17
- "cf.colo": stringOrNull(cf?.colo),
18
- "cf.country": stringOrNull(cf?.country),
19
- "cf.httpProtocol": stringOrNull(cf?.httpProtocol),
20
- "d1.queries": d1 ? d1.queries : null,
21
- "d1.primaryQueries": d1 ? d1.primaryQueries : null,
22
- "d1.recoveries": d1 ? d1.recoveries : null,
23
- "d1.unrecovered": d1 ? d1.unrecovered : null,
24
- "d1.durationMs": d1 ? Math.round(d1.durationMs) : null,
25
- "d1.region": d1 ? d1.region : null
17
+ "cf.colo": stringOrUndefined(cf?.colo),
18
+ "cf.country": stringOrUndefined(cf?.country),
19
+ "cf.httpProtocol": stringOrUndefined(cf?.httpProtocol),
20
+ "d1.queries": d1?.queries,
21
+ "d1.primaryQueries": d1?.primaryQueries,
22
+ "d1.recoveries": d1?.recoveries,
23
+ "d1.unrecovered": d1?.unrecovered,
24
+ "d1.durationMs": d1 ? Math.round(d1.durationMs) : void 0,
25
+ "d1.region": d1?.region ?? void 0
26
26
  });
27
27
  }
@@ -1,14 +1,90 @@
1
- import { getResponseHeader, setResponseHeader } from "h3";
2
- import { defineNitroPlugin } from "nitropack/runtime";
3
- import { hasExplicitCachePolicy, withHtmlNoStoreHeaders } from "../utils/workers-cache.js";
1
+ import { getHeader, getResponseHeader, getResponseStatus, setResponseHeader } from "h3";
2
+ import { defineNitroPlugin, useRuntimeConfig } from "nitropack/runtime";
3
+ import {
4
+ clampSharedCacheSeconds,
5
+ NO_STORE_BROWSER,
6
+ NO_STORE_EDGE,
7
+ resolveHtmlCacheGuarantee,
8
+ responseCacheDecision,
9
+ sharedCacheSeconds,
10
+ statedPolicy
11
+ } from "../utils/workers-cache.js";
12
+ const warned = /* @__PURE__ */ new Set();
13
+ const WARN_LIMIT = 200;
14
+ function warnOnce(kind, path, message) {
15
+ const key = `${kind}:${path.split("?")[0]}`;
16
+ if (warned.has(key))
17
+ return;
18
+ if (warned.size >= WARN_LIMIT)
19
+ return;
20
+ warned.add(key);
21
+ console.warn(`[nuxt-cloudflare] ${message}`);
22
+ }
23
+ const CREDENTIAL_HEADERS = [
24
+ "cookie",
25
+ "authorization",
26
+ "proxy-authorization",
27
+ "cf-access-jwt-assertion",
28
+ "cf-access-client-id",
29
+ "x-api-key"
30
+ ];
31
+ function isAuthenticated(event) {
32
+ return CREDENTIAL_HEADERS.some((name) => Boolean(getHeader(event, name)));
33
+ }
34
+ const DOCUMENT_TYPE_RE = /^(?:text\/html|application\/xhtml\+xml)\s*(?:;|$)/i;
35
+ function isDocumentResponse(event) {
36
+ const type = getResponseHeader(event, "content-type");
37
+ return typeof type === "string" && DOCUMENT_TYPE_RE.test(type);
38
+ }
4
39
  export default defineNitroPlugin((nitroApp) => {
5
- nitroApp.hooks.hook("render:response", (response) => {
6
- response.headers = withHtmlNoStoreHeaders(response.headers);
40
+ nitroApp.hooks.hook("request", (event) => {
41
+ setResponseHeader(event, "cache-control", NO_STORE_BROWSER);
7
42
  });
8
43
  nitroApp.hooks.hook("beforeResponse", (event) => {
9
- if (hasExplicitCachePolicy((name) => getResponseHeader(event, name)))
44
+ const config = useRuntimeConfig(event);
45
+ const mode = config.nuxtCloudflare?.htmlCacheMode ?? "auto";
46
+ const edge = getResponseHeader(event, "cloudflare-cdn-cache-control") ?? getResponseHeader(event, "cdn-cache-control");
47
+ const browser = getResponseHeader(event, "cache-control");
48
+ const appBrowser = browser === NO_STORE_BROWSER ? void 0 : browser;
49
+ const carrier = edge ?? appBrowser;
50
+ const decision = responseCacheDecision({
51
+ mode,
52
+ guarantee: resolveHtmlCacheGuarantee(config.htmlCacheCapabilities),
53
+ isDocument: isDocumentResponse(event),
54
+ stated: statedPolicy((name) => name === "cache-control" ? appBrowser : getResponseHeader(event, name)),
55
+ requestedSeconds: sharedCacheSeconds(carrier),
56
+ status: getResponseStatus(event),
57
+ authenticated: isAuthenticated(event),
58
+ setsCookie: Boolean(getResponseHeader(event, "set-cookie")),
59
+ vary: getResponseHeader(event, "vary")
60
+ });
61
+ if (decision._tag === "leave")
10
62
  return;
11
- setResponseHeader(event, "cache-control", "private, no-store");
12
- setResponseHeader(event, "cloudflare-cdn-cache-control", "no-store");
63
+ if (decision._tag === "floor") {
64
+ setResponseHeader(event, "cache-control", NO_STORE_BROWSER);
65
+ setResponseHeader(event, "cloudflare-cdn-cache-control", NO_STORE_EDGE);
66
+ return;
67
+ }
68
+ if (decision._tag === "clamp") {
69
+ if (edge) {
70
+ setResponseHeader(event, "cloudflare-cdn-cache-control", clampSharedCacheSeconds(String(edge), decision.toSeconds));
71
+ }
72
+ if (appBrowser) {
73
+ setResponseHeader(event, "cache-control", clampSharedCacheSeconds(String(appBrowser), decision.toSeconds));
74
+ }
75
+ warnOnce(
76
+ "clamp",
77
+ event.path,
78
+ `Route ${event.path.split("?")[0]} asked to be cached for ${decision.fromSeconds}s. ${decision.by} covers ${decision.toSeconds}s. The value was lowered.`
79
+ );
80
+ return;
81
+ }
82
+ warnOnce(
83
+ "override",
84
+ event.path,
85
+ `The response for ${event.path.split("?")[0]} set \`cache-control: ${String(carrier)}\`. Workers Cache replaced it because ${decision.reason}. To keep your value, set \`nuxtCloudflare.workersCache.html: 'app'\`.`
86
+ );
87
+ setResponseHeader(event, "cache-control", NO_STORE_BROWSER);
88
+ setResponseHeader(event, "cloudflare-cdn-cache-control", NO_STORE_EDGE);
13
89
  });
14
90
  });
@@ -1,2 +1,162 @@
1
- export declare function hasExplicitCachePolicy(getHeader: (name: string) => unknown): boolean;
2
- export declare function withHtmlNoStoreHeaders(headers?: Record<string, string>): Record<string, string>;
1
+ /**
2
+ * Who owns `Cache-Control` on an HTML document.
3
+ *
4
+ * Workers Cache makes a headerless 200 cacheable for two hours, so a document
5
+ * with no policy has to be given one. This module supplies that floor. What it
6
+ * must not do is overwrite a policy the app wrote on purpose, which is what an
7
+ * earlier version did from `render:response`: that hook receives a plain headers
8
+ * object and no event, so it cannot see what a route rule set, and being unable
9
+ * to check is exactly why it overwrote unconditionally.
10
+ *
11
+ * The floor now lives on the `request` hook and the decisions live here, at
12
+ * `beforeResponse`, where the whole response is visible.
13
+ *
14
+ * Two headers, two audiences, and only one of them carries version skew:
15
+ *
16
+ * - `Cloudflare-CDN-Cache-Control` feeds Workers Cache, whose key includes the
17
+ * Worker version at `cross_version_cache: false`. A deploy makes every stored
18
+ * response unreachable, so a cached document can never outlive its chunks.
19
+ * - `Cache-Control` reaches browsers, the zone cache and third-party CDNs, none
20
+ * of which know a deploy happened. That one needs a retention guarantee.
21
+ */
22
+ export declare const NO_STORE_BROWSER = "private, no-store";
23
+ export declare const NO_STORE_EDGE = "no-store";
24
+ /**
25
+ * How `Cache-Control` on an HTML document is resolved.
26
+ *
27
+ * - `no-store` always overwrite. The behaviour before any of this existed.
28
+ * - `auto` honour the app when a module guarantees chunk retention, clamped
29
+ * to what that module promises.
30
+ * - `app` always honour the app. You own the skew risk.
31
+ */
32
+ export type HtmlCacheMode = 'no-store' | 'auto' | 'app';
33
+ /**
34
+ * Published by any module that can promise a document outlives its build.
35
+ *
36
+ * Duplicated verbatim in `nuxt-skew-protection`. Kept to a versioned,
37
+ * field-only interface so the two copies cannot drift in behaviour, only in
38
+ * whether they know a version. An unknown `v` is ignored rather than guessed
39
+ * at, so a newer producer degrades to today's behaviour instead of to a wrong
40
+ * guarantee.
41
+ */
42
+ export interface HtmlCacheCapability {
43
+ v: 1;
44
+ by: string;
45
+ /** Seconds a document may outlive its build and still resolve every chunk. */
46
+ documentTtlCeilingSeconds: number;
47
+ basis: 'observed-retained-builds' | 'retention-days' | 'none';
48
+ /** Requests for a retired build's chunks resolve instead of 404. */
49
+ assetRecovery: boolean;
50
+ }
51
+ export type HtmlCacheGuarantee = {
52
+ _tag: 'none';
53
+ reason: 'no-capability' | 'no-asset-recovery' | 'zero-ceiling' | 'unknown-version';
54
+ } | {
55
+ _tag: 'bounded';
56
+ ceilingSeconds: number;
57
+ by: string;
58
+ };
59
+ /**
60
+ * The weakest promise across every publisher.
61
+ *
62
+ * Minimum rather than maximum: a guarantee is only as good as the module least
63
+ * able to keep it, and one publisher without asset recovery means a retired
64
+ * chunk 404s whatever the others retain.
65
+ */
66
+ export declare function resolveHtmlCacheGuarantee(capabilities: unknown): HtmlCacheGuarantee;
67
+ /**
68
+ * Seconds a shared cache may serve this response, or null if it was refused.
69
+ *
70
+ * Counts the stale window, because a stale response is still served. `no-cache`
71
+ * counts as a refusal: it permits storage but forbids reuse without
72
+ * revalidation, which is not what "the app asked for shared caching" means.
73
+ */
74
+ export declare function sharedCacheSeconds(cacheControl: unknown): number | null;
75
+ /** Whether the app stated any cache policy at all, however restrictive. */
76
+ export declare function statedPolicy(getHeader: (name: string) => unknown): boolean;
77
+ export type CacheDecision = {
78
+ _tag: 'leave';
79
+ } | {
80
+ _tag: 'floor';
81
+ } | {
82
+ _tag: 'clamp';
83
+ toSeconds: number;
84
+ fromSeconds: number;
85
+ by: string;
86
+ } | {
87
+ _tag: 'override';
88
+ reason: string;
89
+ };
90
+ export interface CacheDecisionInput {
91
+ mode: HtmlCacheMode;
92
+ guarantee: HtmlCacheGuarantee;
93
+ /** True only for a rendered HTML document, from the response content type. */
94
+ isDocument: boolean;
95
+ /** Whether the app set any cache header at all. */
96
+ stated: boolean;
97
+ /** The lifetime the app asked a shared cache for, if any. */
98
+ requestedSeconds: number | null;
99
+ status: number;
100
+ /** A credential on the request that could personalise the response. */
101
+ authenticated: boolean;
102
+ /** The response mints a cookie, so it carries state a shared copy must not. */
103
+ setsCookie: boolean;
104
+ /** The response's own `Vary`, if it set one. */
105
+ vary: string | undefined;
106
+ }
107
+ /**
108
+ * Whether a `Vary` can be satisfied by a cache keyed on the URL.
109
+ *
110
+ * A shared cache does not key on `Cookie` or `Authorization`, so a response
111
+ * asking it to vary on either is asking for something it cannot do, and storing
112
+ * it anyway serves one person's copy to everyone. `*` means never store.
113
+ *
114
+ * This module deliberately does not invent a `Vary` where the app set none.
115
+ * Injecting `Accept` or `Accept-Language` would collapse the hit rate for every
116
+ * route that does not negotiate, and would hide the app's own bug on the ones
117
+ * that do. The route rule asking for shared caching is the app's assertion that
118
+ * the route does not vary, and the build log says so out loud.
119
+ */
120
+ export declare function varyIsSatisfiable(vary: string | undefined): boolean;
121
+ /**
122
+ * What to do with one response.
123
+ *
124
+ * Only rendered documents are subject to the version-skew policy, because only
125
+ * a document names build chunks. Everything else, assets, API payloads,
126
+ * sitemaps, is the app's business and is left exactly as the app wrote it. An
127
+ * earlier revision of this applied the document rules to every response and
128
+ * rewrote nitro's own `/_nuxt/**` immutable rule to `private, no-store`.
129
+ *
130
+ * `leave` means untouched. `floor` means nobody stated a policy, so the safe
131
+ * default applies and nothing was taken. `override` means the app stated one
132
+ * and this module replaced it, which is the only outcome that owes a warning.
133
+ */
134
+ export declare function responseCacheDecision(input: CacheDecisionInput): CacheDecision;
135
+ /**
136
+ * The header with its total served lifetime brought inside the ceiling.
137
+ *
138
+ * Every directive that keeps a response servable is lowered, not just the
139
+ * freshness one. An earlier version rewrote `s-maxage` alone, so
140
+ * `s-maxage=300, stale-while-revalidate=86400` came back byte-identical while
141
+ * the code logged "the value was lowered": a shared cache would still serve
142
+ * that document for a day past the window the ceiling promises.
143
+ *
144
+ * `max-age` is lowered even when `s-maxage` is present. `s-maxage` decides what
145
+ * a shared cache does, but `max-age` still governs browsers and any cache that
146
+ * does not implement `s-maxage`, and those are the caches with no notion of a
147
+ * deploy.
148
+ *
149
+ * The stale window gets whatever budget is left after freshness, so
150
+ * `freshness + stale` can never exceed the ceiling.
151
+ */
152
+ export declare function clampSharedCacheSeconds(cacheControl: string, seconds: number): string;
153
+ /**
154
+ * Whether this header asks for stale serving that Cloudflare will ignore.
155
+ *
156
+ * `s-maxage`, `must-revalidate` and `proxy-revalidate` each forbid serving
157
+ * stale content, so pairing any of them with `stale-while-revalidate` or
158
+ * `stale-if-error` means those directives do nothing. All three sites that
159
+ * hand-wrote this policy left a comment about the trap, which is a good sign it
160
+ * deserves a warning rather than a comment.
161
+ */
162
+ export declare function staleDirectivesAreDisabled(cacheControl: unknown): boolean;
@@ -4,17 +4,140 @@ const CACHE_POLICY_HEADER_NAMES = [
4
4
  "cloudflare-cdn-cache-control",
5
5
  "expires"
6
6
  ];
7
- const HTML_CACHE_HEADER_NAMES = new Set(CACHE_POLICY_HEADER_NAMES.slice(0, 3));
8
- export function hasExplicitCachePolicy(getHeader) {
7
+ export const NO_STORE_BROWSER = "private, no-store";
8
+ export const NO_STORE_EDGE = "no-store";
9
+ function parseCapability(entry) {
10
+ if (!entry || typeof entry !== "object")
11
+ return null;
12
+ const candidate = entry;
13
+ if (candidate.v !== 1)
14
+ return null;
15
+ if (typeof candidate.documentTtlCeilingSeconds !== "number")
16
+ return null;
17
+ if (!Number.isInteger(candidate.documentTtlCeilingSeconds) || candidate.documentTtlCeilingSeconds <= 0)
18
+ return null;
19
+ if (typeof candidate.assetRecovery !== "boolean")
20
+ return null;
21
+ if (typeof candidate.by !== "string" || !candidate.by)
22
+ return null;
23
+ if (candidate.basis !== "observed-retained-builds" && candidate.basis !== "retention-days")
24
+ return null;
25
+ return {
26
+ v: 1,
27
+ by: candidate.by,
28
+ documentTtlCeilingSeconds: candidate.documentTtlCeilingSeconds,
29
+ basis: candidate.basis,
30
+ assetRecovery: candidate.assetRecovery
31
+ };
32
+ }
33
+ export function resolveHtmlCacheGuarantee(capabilities) {
34
+ if (!Array.isArray(capabilities) || capabilities.length === 0)
35
+ return { _tag: "none", reason: "no-capability" };
36
+ const known = capabilities.map(parseCapability);
37
+ if (known.includes(null))
38
+ return { _tag: "none", reason: "unknown-version" };
39
+ const parsed = known;
40
+ if (parsed.some((entry) => !entry.assetRecovery))
41
+ return { _tag: "none", reason: "no-asset-recovery" };
42
+ const ceiling = Math.min(...parsed.map((entry) => entry.documentTtlCeilingSeconds));
43
+ if (!Number.isFinite(ceiling) || ceiling <= 0)
44
+ return { _tag: "none", reason: "zero-ceiling" };
45
+ return { _tag: "bounded", ceilingSeconds: ceiling, by: parsed.map((entry) => entry.by).join(", ") };
46
+ }
47
+ function directive(value, name) {
48
+ const match = value.match(new RegExp(`(?:^|[,\\s])${name}\\s*=\\s*(\\d+)`, "gi"));
49
+ if (!match)
50
+ return void 0;
51
+ return Math.min(...match.map((part) => Number(part.replace(/\D+/g, ""))));
52
+ }
53
+ const MAX_SANE_SECONDS = 31536e3;
54
+ function unqualify(value) {
55
+ return value.replace(/=\s*"[^"]*"/g, '=""');
56
+ }
57
+ export function sharedCacheSeconds(cacheControl) {
58
+ const raw = Array.isArray(cacheControl) ? cacheControl.join(", ") : cacheControl;
59
+ if (typeof raw !== "string" || !raw)
60
+ return null;
61
+ const value = unqualify(raw.toLowerCase());
62
+ if (/(?:^|,)\s*no-store\s*(?:,|$)/.test(value))
63
+ return null;
64
+ if (/(?:^|,)\s*no-cache\s*(?:,|$)/.test(value))
65
+ return null;
66
+ if (/(?:^|,)\s*private\s*(?:,|$)/.test(value))
67
+ return null;
68
+ const shared = directive(value, "s-maxage") ?? directive(value, "max-age");
69
+ if (shared === void 0 || shared <= 0)
70
+ return null;
71
+ return Math.min(shared + (directive(value, "stale-while-revalidate") ?? 0), MAX_SANE_SECONDS);
72
+ }
73
+ export function statedPolicy(getHeader) {
9
74
  return CACHE_POLICY_HEADER_NAMES.some((name) => Boolean(getHeader(name)));
10
75
  }
11
- export function withHtmlNoStoreHeaders(headers = {}) {
12
- const preserved = Object.fromEntries(
13
- Object.entries(headers).filter(([name]) => !HTML_CACHE_HEADER_NAMES.has(name.toLowerCase()))
76
+ export function varyIsSatisfiable(vary) {
77
+ if (!vary)
78
+ return true;
79
+ const fields = vary.toLowerCase().split(",").map((field) => field.trim());
80
+ if (fields.includes("*"))
81
+ return false;
82
+ return !fields.includes("cookie") && !fields.includes("authorization");
83
+ }
84
+ const PRESERVED_STATUSES = /* @__PURE__ */ new Set([301, 304, 308]);
85
+ export function responseCacheDecision(input) {
86
+ if (!input.stated)
87
+ return { _tag: "floor" };
88
+ if (!input.isDocument)
89
+ return { _tag: "leave" };
90
+ if (PRESERVED_STATUSES.has(input.status))
91
+ return { _tag: "leave" };
92
+ if (input.requestedSeconds === null)
93
+ return { _tag: "leave" };
94
+ if (input.authenticated)
95
+ return { _tag: "override", reason: "the request carried credentials" };
96
+ if (input.setsCookie)
97
+ return { _tag: "override", reason: "the response set a cookie" };
98
+ if (!varyIsSatisfiable(input.vary))
99
+ return { _tag: "override", reason: `the response varies on \`${input.vary}\`, which a shared cache cannot key on` };
100
+ if (input.status !== 200)
101
+ return { _tag: "override", reason: `the response status was ${input.status}` };
102
+ if (input.mode === "no-store")
103
+ return { _tag: "override", reason: "workersCache.html is set to no-store" };
104
+ if (input.mode === "app")
105
+ return { _tag: "leave" };
106
+ if (input.guarantee._tag === "none")
107
+ return { _tag: "override", reason: `no module guarantees chunk retention (${input.guarantee.reason})` };
108
+ if (input.requestedSeconds > input.guarantee.ceilingSeconds) {
109
+ return {
110
+ _tag: "clamp",
111
+ toSeconds: input.guarantee.ceilingSeconds,
112
+ fromSeconds: input.requestedSeconds,
113
+ by: input.guarantee.by
114
+ };
115
+ }
116
+ return { _tag: "leave" };
117
+ }
118
+ export function clampSharedCacheSeconds(cacheControl, seconds) {
119
+ const lower = (name, limit, source) => source.replace(
120
+ new RegExp(`((?:^|[,\\s])${name}\\s*=\\s*)(\\d+)`, "gi"),
121
+ (whole, lead, value) => Number(value) > limit ? `${lead}${limit}` : whole
14
122
  );
15
- return {
16
- ...preserved,
17
- "cache-control": "private, no-store",
18
- "cloudflare-cdn-cache-control": "no-store"
19
- };
123
+ let out = lower("s-maxage", seconds, cacheControl);
124
+ out = lower("max-age", seconds, out);
125
+ const freshness = Math.min(
126
+ directive(unqualify(out.toLowerCase()), "s-maxage") ?? directive(unqualify(out.toLowerCase()), "max-age") ?? seconds,
127
+ seconds
128
+ );
129
+ const staleBudget = Math.max(0, seconds - freshness);
130
+ out = lower("stale-while-revalidate", staleBudget, out);
131
+ out = lower("stale-if-error", seconds, out);
132
+ return out;
133
+ }
134
+ export function staleDirectivesAreDisabled(cacheControl) {
135
+ const raw = Array.isArray(cacheControl) ? cacheControl.join(", ") : cacheControl;
136
+ if (typeof raw !== "string")
137
+ return false;
138
+ const value = unqualify(raw.toLowerCase());
139
+ const wantsStale = /stale-while-revalidate\s*=|stale-if-error\s*=/.test(value);
140
+ if (!wantsStale)
141
+ return false;
142
+ return /(?:^|,)\s*(?:s-maxage\s*=|must-revalidate|proxy-revalidate)/.test(value);
20
143
  }
@@ -47,6 +47,11 @@ type WranglerPlacementInput = {
47
47
  host?: never;
48
48
  hostname?: never;
49
49
  region?: never;
50
+ } | {
51
+ mode: 'off';
52
+ host?: never;
53
+ hostname?: never;
54
+ region?: never;
50
55
  } | {
51
56
  host: string;
52
57
  hostname?: never;
@@ -63,6 +68,12 @@ type WranglerPlacementInput = {
63
68
  hostname?: never;
64
69
  mode?: never;
65
70
  };
71
+ type WranglerModuleRuleType = 'CommonJS' | 'CompiledWasm' | 'Data' | 'ESModule' | 'PythonModule' | 'PythonRequirement' | 'Text';
72
+ interface WranglerModuleRuleInput {
73
+ type: WranglerModuleRuleType;
74
+ globs: string[];
75
+ fallthrough?: boolean;
76
+ }
66
77
  interface WranglerRemoteBindingInput extends Record<string, unknown> {
67
78
  binding?: string;
68
79
  remote?: boolean;
@@ -77,6 +88,24 @@ type WorkersCachePolicy = {
77
88
  } | {
78
89
  _tag: 'enabled';
79
90
  crossVersion: boolean;
91
+ /**
92
+ * How `Cache-Control` on an HTML document is resolved.
93
+ *
94
+ * - `no-store` always overwrite it. The behaviour before the contract.
95
+ * - `auto` honour the app when a module guarantees chunk retention,
96
+ * clamped to what that module promises. Falls back to `no-store` when
97
+ * nothing publishes a guarantee, so an app without skew protection
98
+ * behaves exactly as it does today.
99
+ * - `app` always honour the app. You own the version-skew risk.
100
+ *
101
+ * This governs `Cache-Control` only. `Cloudflare-CDN-Cache-Control` is
102
+ * always honoured, because Workers Cache keys on the Worker version at
103
+ * `cross_version_cache: false`, so a deploy already makes every stored
104
+ * response unreachable and no document can outlive its chunks there.
105
+ *
106
+ * @default 'auto'
107
+ */
108
+ html?: 'no-store' | 'auto' | 'app';
80
109
  };
81
110
  interface WranglerObservabilityInput {
82
111
  enabled?: boolean;
@@ -100,6 +129,7 @@ interface WranglerConfigInput extends Record<string, unknown> {
100
129
  compatibility_flags?: string[];
101
130
  containers?: WranglerContainerInput[];
102
131
  env?: Record<string, WranglerConfigInput>;
132
+ find_additional_modules?: boolean;
103
133
  images?: WranglerRemoteBindingInput;
104
134
  keep_vars?: boolean;
105
135
  limits?: {
@@ -107,6 +137,7 @@ interface WranglerConfigInput extends Record<string, unknown> {
107
137
  subrequests?: number;
108
138
  };
109
139
  mtls_certificates?: WranglerRemoteBindingInput[];
140
+ no_bundle?: boolean;
110
141
  observability?: WranglerObservabilityInput;
111
142
  placement?: WranglerPlacementInput;
112
143
  preview_urls?: boolean;
@@ -116,6 +147,7 @@ interface WranglerConfigInput extends Record<string, unknown> {
116
147
  };
117
148
  route?: string | Record<string, unknown>;
118
149
  routes?: Array<string | Record<string, unknown>>;
150
+ rules?: WranglerModuleRuleInput[];
119
151
  secrets?: {
120
152
  required?: string[];
121
153
  };
@@ -130,6 +162,7 @@ interface WranglerConfigInput extends Record<string, unknown> {
130
162
  interface CloudflareDefaultOptions {
131
163
  compatibilityDate?: string;
132
164
  logsSampleRate?: number;
165
+ partialBundles?: boolean;
133
166
  requiredSecrets?: readonly string[];
134
167
  tracesSampleRate?: number;
135
168
  uploadSourceMaps?: boolean;
@@ -183,4 +216,4 @@ declare function formatWranglerDiagnostics(diagnostics: readonly WranglerDiagnos
183
216
  declare function readWranglerJsonFile(path: string): Promise<WranglerJsonFileResult>;
184
217
 
185
218
  export { WRANGLER_DIAGNOSTIC_CODES, applyCloudflareDefaults, diagnoseWranglerConfig, findProjectWranglerConfig, formatWranglerDiagnostics, readAuthoredWranglerConfig, readWranglerConfigFile, readWranglerJsonFile };
186
- export type { AuthoredWranglerConfigResult, CloudflareDefaultOptions, WorkersCachePolicy, WranglerAssetsInput, WranglerConfigFileResult, WranglerConfigInput, WranglerContainerInput, WranglerDiagnostic, WranglerDiagnosticCode, WranglerDiagnosticOptions, WranglerJsonFileResult, WranglerObservabilityInput, WranglerPlacementInput, WranglerRemoteBindingInput, WranglerWorkersCacheInput };
219
+ export type { AuthoredWranglerConfigResult, CloudflareDefaultOptions, WorkersCachePolicy, WranglerAssetsInput, WranglerConfigFileResult, WranglerConfigInput, WranglerContainerInput, WranglerDiagnostic, WranglerDiagnosticCode, WranglerDiagnosticOptions, WranglerJsonFileResult, WranglerModuleRuleInput, WranglerModuleRuleType, WranglerObservabilityInput, WranglerPlacementInput, WranglerRemoteBindingInput, WranglerWorkersCacheInput };
package/dist/wrangler.mjs CHANGED
@@ -112,6 +112,19 @@ const SECRET_NAME_RE = /(?:^|_)(?:API_?KEY|AUTH_TOKEN|CLIENT_SECRET|CREDENTIALS?
112
112
  const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
113
113
  const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1e3;
114
114
  const NODEJS_COMPAT_V2_DATE = /* @__PURE__ */ new Date("2024-09-23T00:00:00.000Z");
115
+ const MJS_COVERING_GLOBS = /* @__PURE__ */ new Set(["**/*.mjs", "**/*"]);
116
+ const PARTIAL_BUNDLES_MODULE_RULE = {
117
+ type: "ESModule",
118
+ globs: ["**/*.mjs"],
119
+ // Wrangler keeps only the first rule per module type unless it falls
120
+ // through, and Nitro's `defu` merge places generated rules before authored
121
+ // ones. Without this a consumer ESModule rule for other globs would be
122
+ // dropped as redundant.
123
+ fallthrough: true
124
+ };
125
+ function moduleRuleCoversMjs(rule) {
126
+ return rule.type === "ESModule" && rule.globs.some((glob) => MJS_COVERING_GLOBS.has(glob));
127
+ }
115
128
  function unique(values) {
116
129
  return [...new Set(values)];
117
130
  }
@@ -309,6 +322,7 @@ function applyCloudflareDefaults(config, options = {}, authored = {}) {
309
322
  // Named Wrangler environments inherit the authored root for the keys
310
323
  // Wrangler itself inherits, and nothing else.
311
324
  authored: resolveEnvironmentPolicy(authored, authored.env?.[name] ?? {}),
325
+ authoredEnvironment: authored.env?.[name] ?? {},
312
326
  inherited: root
313
327
  })])
314
328
  );
@@ -351,11 +365,22 @@ function applyEnvironmentDefaults(config, options, layers = {}) {
351
365
  const versionMetadataBinding = options.versionMetadataBinding ?? "CF_VERSION_METADATA";
352
366
  const localBindingNames = /* @__PURE__ */ new Set([...collectBindingNames(config), ...collectBindingNames(authored)]);
353
367
  const versionMetadata = config.version_metadata ?? authored.version_metadata ?? (inherited.version_metadata && !localBindingNames.has(inherited.version_metadata.binding) ? inherited.version_metadata : void 0) ?? (localBindingNames.has(versionMetadataBinding) ? void 0 : { binding: versionMetadataBinding });
368
+ const partialBundles = options.partialBundles ?? true;
369
+ const noBundle = config.no_bundle ?? authored.no_bundle ?? inherited.no_bundle;
370
+ const findAdditionalModules = config.find_additional_modules ?? authored.find_additional_modules ?? inherited.find_additional_modules;
371
+ const environmentRules = [...config.rules ?? [], ...layers.authoredEnvironment?.rules ?? []];
372
+ const mjsCovered = environmentRules.length > 0 ? environmentRules.some(moduleRuleCoversMjs) : [...authored.rules ?? [], ...inherited.rules ?? []].some(moduleRuleCoversMjs);
354
373
  return {
355
374
  ...config,
356
375
  cache,
357
376
  ...compatibilityDate === void 0 ? {} : { compatibility_date: compatibilityDate },
358
377
  compatibility_flags: compatibilityFlags,
378
+ ...partialBundles && !noBundle ? {
379
+ find_additional_modules: findAdditionalModules ?? true,
380
+ // Authored rules stay in the authored config: Nitro's `defu` merge
381
+ // concatenates arrays, so restating them here would duplicate them.
382
+ ...!mjsCovered ? { rules: [PARTIAL_BUNDLES_MODULE_RULE, ...config.rules ?? []] } : {}
383
+ } : {},
359
384
  observability: {
360
385
  ...inherited.observability,
361
386
  ...authored.observability,
@@ -855,11 +880,14 @@ function resolveEnvironmentPolicy(root, environment) {
855
880
  cache: environment.cache ?? root.cache,
856
881
  compatibility_date: environment.compatibility_date ?? root.compatibility_date,
857
882
  compatibility_flags: environment.compatibility_flags ?? root.compatibility_flags,
883
+ find_additional_modules: environment.find_additional_modules ?? root.find_additional_modules,
858
884
  ...exports === void 0 ? {} : { exports },
859
885
  ...migrations === void 0 ? {} : { migrations },
886
+ no_bundle: environment.no_bundle ?? root.no_bundle,
860
887
  observability: mergeObservability(root.observability, environment.observability),
861
888
  placement: environment.placement ?? root.placement,
862
889
  preview_urls: environment.preview_urls ?? root.preview_urls,
890
+ rules: environment.rules ?? root.rules,
863
891
  upload_source_maps: environment.upload_source_maps ?? root.upload_source_maps,
864
892
  workers_dev: environment.workers_dev ?? root.workers_dev
865
893
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@harlan-zw/nuxt-cloudflare",
3
3
  "type": "module",
4
- "version": "0.1.0",
4
+ "version": "0.3.0",
5
5
  "description": "Opinionated Cloudflare deployment defaults and diagnostics for Nuxt.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -47,6 +47,10 @@
47
47
  "./wrangler": {
48
48
  "types": "./dist/wrangler.d.mts",
49
49
  "import": "./dist/wrangler.mjs"
50
+ },
51
+ "./cache": {
52
+ "types": "./dist/cache.d.mts",
53
+ "import": "./dist/cache.mjs"
50
54
  }
51
55
  },
52
56
  "main": "./dist/module.mjs",
@@ -56,6 +60,9 @@
56
60
  "bindings": [
57
61
  "dist/bindings.d.mts"
58
62
  ],
63
+ "cache": [
64
+ "dist/cache.d.mts"
65
+ ],
59
66
  "d1": [
60
67
  "dist/d1.d.mts"
61
68
  ],
@@ -106,17 +113,18 @@
106
113
  "unbuild": "^3.6.1",
107
114
  "vitest": "^4.1.10",
108
115
  "wrangler": "^4.120.1",
109
- "@harlan-zw/nuxt-wide-events": "^0.1.0"
116
+ "@harlan-zw/nuxt-wide-events": "^0.1.3"
110
117
  },
111
118
  "scripts": {
112
119
  "build": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt-module-build build",
113
120
  "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare",
114
121
  "lint": "eslint .",
115
122
  "lint:fix": "eslint . --fix",
116
- "test": "pnpm run build && vitest run && pnpm run test:fixture",
123
+ "test": "pnpm run build && vitest run --exclude \"**/*.nitro.test.ts\" && pnpm run test:fixture && pnpm run test:contract",
117
124
  "test:fixture": "nuxi prepare tests/fixtures/basic && nuxt typecheck tests/fixtures/basic && nuxt build tests/fixtures/basic && node dist/cli/index.mjs doctor --cwd tests/fixtures/basic",
118
125
  "typecheck": "nuxt typecheck && tsc --noEmit -p tsconfig.check.json",
119
126
  "test:attw": "attw --pack",
120
- "test:pack": "rm -rf .pack && pnpm pack --pack-destination .pack && tar -tf .pack/*.tgz"
127
+ "test:pack": "rm -rf .pack && pnpm pack --pack-destination .pack && tar -tf .pack/*.tgz",
128
+ "test:contract": "nuxt build tests/fixtures/cache-contract && vitest run tests/cache-contract.nitro.test.ts"
121
129
  }
122
130
  }