@harlan-zw/nuxt-cloudflare 0.0.18 → 0.2.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 +45 -5
- package/dist/bindings.d.mts +40 -4
- package/dist/bindings.mjs +18 -2
- package/dist/cache.d.mts +69 -0
- package/dist/cache.mjs +38 -0
- package/dist/chunks/binding-types.mjs +7 -13
- package/dist/cli/index.mjs +12 -2
- package/dist/module.d.mts +26 -3
- package/dist/module.json +1 -1
- package/dist/module.mjs +73 -20
- package/dist/runtime/server/plugins/runtime-config.d.ts +9 -0
- package/dist/runtime/server/plugins/runtime-config.js +5 -0
- package/dist/runtime/server/plugins/workers-cache.js +84 -8
- package/dist/runtime/server/utils/workers-cache.d.ts +162 -2
- package/dist/runtime/server/utils/workers-cache.js +133 -10
- package/dist/types.d.mts +2 -2
- package/dist/wrangler.d.mts +53 -3
- package/dist/wrangler.mjs +62 -25
- package/package.json +12 -4
|
@@ -1,14 +1,90 @@
|
|
|
1
|
-
import { getResponseHeader, setResponseHeader } from "h3";
|
|
2
|
-
import { defineNitroPlugin } from "nitropack/runtime";
|
|
3
|
-
import {
|
|
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("
|
|
6
|
-
|
|
40
|
+
nitroApp.hooks.hook("request", (event) => {
|
|
41
|
+
setResponseHeader(event, "cache-control", NO_STORE_BROWSER);
|
|
7
42
|
});
|
|
8
43
|
nitroApp.hooks.hook("beforeResponse", (event) => {
|
|
9
|
-
|
|
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
|
-
|
|
12
|
-
|
|
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
|
-
|
|
2
|
-
|
|
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
|
|
8
|
-
export
|
|
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
|
|
12
|
-
|
|
13
|
-
|
|
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
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
"
|
|
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
|
}
|
package/dist/types.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { type configureNitroCloudflare, default, type findPopulatedRuntimeSecretPaths, type setupCloudflareModule } from './module.mjs'
|
|
1
|
+
export { type configureNitroCloudflare, default, type findPopulatedRuntimeSecretPaths, type resolveBindingTypeAudit, type setupCloudflareModule } from './module.mjs'
|
|
2
2
|
|
|
3
|
-
export { type ModuleOptions, type NitroCloudflareShape } from './module.mjs'
|
|
3
|
+
export { type BindingTypeAudit, type ModuleOptions, type NitroCloudflareContext, type NitroCloudflareShape } from './module.mjs'
|
package/dist/wrangler.d.mts
CHANGED
|
@@ -12,6 +12,26 @@ type WranglerConfigFileResult = {
|
|
|
12
12
|
};
|
|
13
13
|
declare function readWranglerConfigFile(path: string): WranglerConfigFileResult;
|
|
14
14
|
declare function findProjectWranglerConfig(cwd: string): string | undefined;
|
|
15
|
+
type AuthoredWranglerConfigResult = {
|
|
16
|
+
_tag: 'authored';
|
|
17
|
+
config: WranglerConfigInput;
|
|
18
|
+
path: string;
|
|
19
|
+
} | {
|
|
20
|
+
_tag: 'absent';
|
|
21
|
+
} | {
|
|
22
|
+
_tag: 'invalid';
|
|
23
|
+
path: string;
|
|
24
|
+
reason: string;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Reads the root Wrangler config the consumer authored.
|
|
28
|
+
*
|
|
29
|
+
* Nitro writes the deployed config as `defu(overrides, nitro.cloudflare.wrangler,
|
|
30
|
+
* thisFile, defaults)`, so every value in this file loses to a module default
|
|
31
|
+
* that names the same key. Module policy reads the file for that reason only:
|
|
32
|
+
* a value the consumer wrote here stays the value that deploys.
|
|
33
|
+
*/
|
|
34
|
+
declare function readAuthoredWranglerConfig(rootDir: string | undefined): AuthoredWranglerConfigResult;
|
|
15
35
|
|
|
16
36
|
interface WranglerAssetsInput {
|
|
17
37
|
directory?: string;
|
|
@@ -57,6 +77,24 @@ type WorkersCachePolicy = {
|
|
|
57
77
|
} | {
|
|
58
78
|
_tag: 'enabled';
|
|
59
79
|
crossVersion: boolean;
|
|
80
|
+
/**
|
|
81
|
+
* How `Cache-Control` on an HTML document is resolved.
|
|
82
|
+
*
|
|
83
|
+
* - `no-store` always overwrite it. The behaviour before the contract.
|
|
84
|
+
* - `auto` honour the app when a module guarantees chunk retention,
|
|
85
|
+
* clamped to what that module promises. Falls back to `no-store` when
|
|
86
|
+
* nothing publishes a guarantee, so an app without skew protection
|
|
87
|
+
* behaves exactly as it does today.
|
|
88
|
+
* - `app` always honour the app. You own the version-skew risk.
|
|
89
|
+
*
|
|
90
|
+
* This governs `Cache-Control` only. `Cloudflare-CDN-Cache-Control` is
|
|
91
|
+
* always honoured, because Workers Cache keys on the Worker version at
|
|
92
|
+
* `cross_version_cache: false`, so a deploy already makes every stored
|
|
93
|
+
* response unreachable and no document can outlive its chunks there.
|
|
94
|
+
*
|
|
95
|
+
* @default 'auto'
|
|
96
|
+
*/
|
|
97
|
+
html?: 'no-store' | 'auto' | 'app';
|
|
60
98
|
};
|
|
61
99
|
interface WranglerObservabilityInput {
|
|
62
100
|
enabled?: boolean;
|
|
@@ -145,10 +183,22 @@ type WranglerJsonFileResult = {
|
|
|
145
183
|
path: string;
|
|
146
184
|
reason: string;
|
|
147
185
|
};
|
|
148
|
-
|
|
186
|
+
/**
|
|
187
|
+
* Applies module policy to the Wrangler config Nitro generates.
|
|
188
|
+
*
|
|
189
|
+
* Three layers decide every value. `config` is `nitro.cloudflare.wrangler`,
|
|
190
|
+
* which the application and its modules write. `authored` is the root
|
|
191
|
+
* `wrangler.jsonc` or `wrangler.toml`. Module options are last, because a
|
|
192
|
+
* default must never overrule a value the consumer wrote in either place.
|
|
193
|
+
*
|
|
194
|
+
* Nitro merges the generated config with `defu`, where `nitro.cloudflare.wrangler`
|
|
195
|
+
* outranks the authored file. So this function resolves the effective value and
|
|
196
|
+
* writes it back: without the authored layer the module default silently wins.
|
|
197
|
+
*/
|
|
198
|
+
declare function applyCloudflareDefaults(config: WranglerConfigInput, options?: CloudflareDefaultOptions, authored?: WranglerConfigInput): WranglerConfigInput;
|
|
149
199
|
declare function diagnoseWranglerConfig(config: WranglerConfigInput, options?: WranglerDiagnosticOptions): WranglerDiagnostic[];
|
|
150
200
|
declare function formatWranglerDiagnostics(diagnostics: readonly WranglerDiagnostic[]): string;
|
|
151
201
|
declare function readWranglerJsonFile(path: string): Promise<WranglerJsonFileResult>;
|
|
152
202
|
|
|
153
|
-
export { WRANGLER_DIAGNOSTIC_CODES, applyCloudflareDefaults, diagnoseWranglerConfig, findProjectWranglerConfig, formatWranglerDiagnostics, readWranglerConfigFile, readWranglerJsonFile };
|
|
154
|
-
export type { CloudflareDefaultOptions, WorkersCachePolicy, WranglerAssetsInput, WranglerConfigFileResult, WranglerConfigInput, WranglerContainerInput, WranglerDiagnostic, WranglerDiagnosticCode, WranglerDiagnosticOptions, WranglerJsonFileResult, WranglerObservabilityInput, WranglerPlacementInput, WranglerRemoteBindingInput, WranglerWorkersCacheInput };
|
|
203
|
+
export { WRANGLER_DIAGNOSTIC_CODES, applyCloudflareDefaults, diagnoseWranglerConfig, findProjectWranglerConfig, formatWranglerDiagnostics, readAuthoredWranglerConfig, readWranglerConfigFile, readWranglerJsonFile };
|
|
204
|
+
export type { AuthoredWranglerConfigResult, CloudflareDefaultOptions, WorkersCachePolicy, WranglerAssetsInput, WranglerConfigFileResult, WranglerConfigInput, WranglerContainerInput, WranglerDiagnostic, WranglerDiagnosticCode, WranglerDiagnosticOptions, WranglerJsonFileResult, WranglerObservabilityInput, WranglerPlacementInput, WranglerRemoteBindingInput, WranglerWorkersCacheInput };
|
package/dist/wrangler.mjs
CHANGED
|
@@ -48,6 +48,17 @@ function findProjectWranglerConfig(cwd) {
|
|
|
48
48
|
directory = parent;
|
|
49
49
|
}
|
|
50
50
|
}
|
|
51
|
+
function readAuthoredWranglerConfig(rootDir) {
|
|
52
|
+
const path = rootDir === void 0 ? void 0 : findProjectWranglerConfig(rootDir);
|
|
53
|
+
if (!path)
|
|
54
|
+
return { _tag: "absent" };
|
|
55
|
+
const loaded = readWranglerConfigFile(path);
|
|
56
|
+
if (loaded._tag === "loaded")
|
|
57
|
+
return { _tag: "authored", config: loaded.config, path };
|
|
58
|
+
if (loaded._tag === "missing")
|
|
59
|
+
return { _tag: "absent" };
|
|
60
|
+
return { _tag: "invalid", path, reason: loaded.reason };
|
|
61
|
+
}
|
|
51
62
|
|
|
52
63
|
const WRANGLER_DIAGNOSTIC_CODES = [
|
|
53
64
|
"assets-worker-first",
|
|
@@ -291,33 +302,55 @@ function configuredRemoteBindings(config) {
|
|
|
291
302
|
}
|
|
292
303
|
return bindings;
|
|
293
304
|
}
|
|
294
|
-
function applyCloudflareDefaults(config, options = {}) {
|
|
295
|
-
const root = applyEnvironmentDefaults(config, options);
|
|
305
|
+
function applyCloudflareDefaults(config, options = {}, authored = {}) {
|
|
306
|
+
const root = applyEnvironmentDefaults(config, options, { authored });
|
|
296
307
|
const environments = config.env && Object.fromEntries(
|
|
297
|
-
Object.entries(config.env).map(([name, environment]) => [name, applyEnvironmentDefaults(environment, {
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
308
|
+
Object.entries(config.env).map(([name, environment]) => [name, applyEnvironmentDefaults(environment, options, {
|
|
309
|
+
// Named Wrangler environments inherit the authored root for the keys
|
|
310
|
+
// Wrangler itself inherits, and nothing else.
|
|
311
|
+
authored: resolveEnvironmentPolicy(authored, authored.env?.[name] ?? {}),
|
|
312
|
+
inherited: root
|
|
313
|
+
})])
|
|
301
314
|
);
|
|
302
315
|
return environments ? { ...root, env: environments } : root;
|
|
303
316
|
}
|
|
304
|
-
function
|
|
305
|
-
const
|
|
306
|
-
|
|
307
|
-
|
|
317
|
+
function withNodeCompatibilityFlags(flags) {
|
|
318
|
+
const resolved = new Set(flags);
|
|
319
|
+
if (resolved.has("nodejs_compat_v2") && resolved.has("no_nodejs_compat_v2"))
|
|
320
|
+
resolved.delete("nodejs_compat_v2");
|
|
321
|
+
if (!resolved.has("nodejs_compat_v2")) {
|
|
322
|
+
resolved.add("nodejs_compat");
|
|
323
|
+
resolved.add("no_nodejs_compat_v2");
|
|
324
|
+
}
|
|
325
|
+
return [...resolved];
|
|
326
|
+
}
|
|
327
|
+
function applyEnvironmentDefaults(config, options, layers = {}) {
|
|
328
|
+
const authored = layers.authored ?? {};
|
|
329
|
+
const inherited = layers.inherited ?? {};
|
|
330
|
+
const compatibilityDate = config.compatibility_date ?? authored.compatibility_date ?? inherited.compatibility_date ?? options.compatibilityDate;
|
|
331
|
+
const declaredFlags = unique([...config.compatibility_flags ?? [], ...authored.compatibility_flags ?? []]);
|
|
332
|
+
const compatibilityFlags = withNodeCompatibilityFlags(
|
|
333
|
+
declaredFlags.length > 0 ? declaredFlags : inherited.compatibility_flags ?? []
|
|
334
|
+
);
|
|
335
|
+
const authoredCache = config.cache ?? authored.cache ?? inherited.cache;
|
|
308
336
|
const cache = options.workersCache ? resolveWorkersCachePolicy(options.workersCache) : authoredCache ? { ...authoredCache, cross_version_cache: authoredCache.cross_version_cache ?? false } : resolveWorkersCachePolicy({ _tag: "disabled" });
|
|
309
|
-
const
|
|
337
|
+
const authoredSecrets = new Set(authored.secrets?.required ?? []);
|
|
338
|
+
const requiredSecrets = unique([...config.secrets?.required ?? [], ...options.requiredSecrets ?? []]).filter((name) => !authoredSecrets.has(name));
|
|
310
339
|
const logs = config.observability?.logs;
|
|
340
|
+
const authoredLogs = authored.observability?.logs;
|
|
311
341
|
const inheritedLogs = inherited.observability?.logs;
|
|
312
342
|
const traces = config.observability?.traces;
|
|
343
|
+
const authoredTraces = authored.observability?.traces;
|
|
313
344
|
const inheritedTraces = inherited.observability?.traces;
|
|
314
|
-
const uploadSourceMaps = config.upload_source_maps ?? inherited.upload_source_maps ?? options.uploadSourceMaps ?? true;
|
|
315
|
-
const previewUrls = config.preview_urls ?? inherited.preview_urls ?? false;
|
|
316
|
-
const placement = config.placement ?? inherited.placement ?? { mode: "smart" };
|
|
317
|
-
const
|
|
345
|
+
const uploadSourceMaps = config.upload_source_maps ?? authored.upload_source_maps ?? inherited.upload_source_maps ?? options.uploadSourceMaps ?? true;
|
|
346
|
+
const previewUrls = config.preview_urls ?? authored.preview_urls ?? inherited.preview_urls ?? false;
|
|
347
|
+
const placement = config.placement ?? authored.placement ?? inherited.placement ?? { mode: "smart" };
|
|
348
|
+
const route = config.route ?? authored.route ?? inherited.route;
|
|
349
|
+
const routes = config.routes ?? authored.routes ?? inherited.routes;
|
|
350
|
+
const workersDev = config.workers_dev ?? authored.workers_dev ?? inherited.workers_dev ?? (route !== void 0 || (routes?.length ?? 0) > 0 ? false : void 0);
|
|
318
351
|
const versionMetadataBinding = options.versionMetadataBinding ?? "CF_VERSION_METADATA";
|
|
319
|
-
const localBindingNames = collectBindingNames(config);
|
|
320
|
-
const versionMetadata = config.version_metadata ?? (inherited.version_metadata && !localBindingNames.has(inherited.version_metadata.binding) ? inherited.version_metadata : void 0) ?? (localBindingNames.has(versionMetadataBinding) ? void 0 : { binding: versionMetadataBinding });
|
|
352
|
+
const localBindingNames = /* @__PURE__ */ new Set([...collectBindingNames(config), ...collectBindingNames(authored)]);
|
|
353
|
+
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 });
|
|
321
354
|
return {
|
|
322
355
|
...config,
|
|
323
356
|
cache,
|
|
@@ -325,20 +358,23 @@ function applyEnvironmentDefaults(config, options, inherited = {}) {
|
|
|
325
358
|
compatibility_flags: compatibilityFlags,
|
|
326
359
|
observability: {
|
|
327
360
|
...inherited.observability,
|
|
361
|
+
...authored.observability,
|
|
328
362
|
...config.observability,
|
|
329
|
-
enabled: config.observability?.enabled ?? inherited.observability?.enabled ?? true,
|
|
363
|
+
enabled: config.observability?.enabled ?? authored.observability?.enabled ?? inherited.observability?.enabled ?? true,
|
|
330
364
|
logs: {
|
|
331
365
|
...inheritedLogs,
|
|
366
|
+
...authoredLogs,
|
|
332
367
|
...logs,
|
|
333
|
-
enabled: logs?.enabled ?? inheritedLogs?.enabled ?? true,
|
|
334
|
-
head_sampling_rate: logs?.head_sampling_rate ?? inheritedLogs?.head_sampling_rate ?? options.logsSampleRate ?? 0.01,
|
|
335
|
-
invocation_logs: logs?.invocation_logs ?? inheritedLogs?.invocation_logs ?? true
|
|
368
|
+
enabled: logs?.enabled ?? authoredLogs?.enabled ?? inheritedLogs?.enabled ?? true,
|
|
369
|
+
head_sampling_rate: logs?.head_sampling_rate ?? authoredLogs?.head_sampling_rate ?? inheritedLogs?.head_sampling_rate ?? options.logsSampleRate ?? 0.01,
|
|
370
|
+
invocation_logs: logs?.invocation_logs ?? authoredLogs?.invocation_logs ?? inheritedLogs?.invocation_logs ?? true
|
|
336
371
|
},
|
|
337
372
|
traces: {
|
|
338
373
|
...inheritedTraces,
|
|
374
|
+
...authoredTraces,
|
|
339
375
|
...traces,
|
|
340
|
-
enabled: traces?.enabled ?? inheritedTraces?.enabled ?? true,
|
|
341
|
-
head_sampling_rate: traces?.head_sampling_rate ?? inheritedTraces?.head_sampling_rate ?? options.tracesSampleRate ?? 0.01
|
|
376
|
+
enabled: traces?.enabled ?? authoredTraces?.enabled ?? inheritedTraces?.enabled ?? true,
|
|
377
|
+
head_sampling_rate: traces?.head_sampling_rate ?? authoredTraces?.head_sampling_rate ?? inheritedTraces?.head_sampling_rate ?? options.tracesSampleRate ?? 0.01
|
|
342
378
|
}
|
|
343
379
|
},
|
|
344
380
|
placement,
|
|
@@ -644,7 +680,8 @@ function diagnosePolicy(config, prefix, diagnostics, options, publicVarNames) {
|
|
|
644
680
|
});
|
|
645
681
|
}
|
|
646
682
|
}
|
|
647
|
-
|
|
683
|
+
const nodeCompatFlags = new Set(config.compatibility_flags ?? []);
|
|
684
|
+
if (options.requireNodeCompat && !nodeCompatFlags.has("nodejs_compat") && !nodeCompatFlags.has("nodejs_compat_v2")) {
|
|
648
685
|
diagnostics.push({
|
|
649
686
|
_tag: "error",
|
|
650
687
|
code: "missing-nodejs-compat",
|
|
@@ -898,4 +935,4 @@ async function readWranglerJsonFile(path) {
|
|
|
898
935
|
});
|
|
899
936
|
}
|
|
900
937
|
|
|
901
|
-
export { WRANGLER_DIAGNOSTIC_CODES, applyCloudflareDefaults, diagnoseWranglerConfig, findProjectWranglerConfig, formatWranglerDiagnostics, readWranglerConfigFile, readWranglerJsonFile };
|
|
938
|
+
export { WRANGLER_DIAGNOSTIC_CODES, applyCloudflareDefaults, diagnoseWranglerConfig, findProjectWranglerConfig, formatWranglerDiagnostics, readAuthoredWranglerConfig, readWranglerConfigFile, readWranglerJsonFile };
|