@harlan-zw/nuxt-cloudflare 0.0.1 → 0.0.3
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 +61 -8
- package/dist/cli/index.mjs +140 -17
- package/dist/d1.d.mts +17 -2
- package/dist/d1.mjs +68 -5
- package/dist/module.d.mts +10 -1
- package/dist/module.json +1 -1
- package/dist/module.mjs +24 -11
- package/dist/shared/nuxt-cloudflare.6X-qzF_b.mjs +77 -0
- package/dist/wrangler.d.mts +49 -5
- package/dist/wrangler.mjs +365 -30
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,11 +7,16 @@ The module extracts production patterns already proven in Nuxt SEO and gscdump.
|
|
|
7
7
|
## Defaults
|
|
8
8
|
|
|
9
9
|
- Cloudflare module preset, generated Wrangler config, and Node compatibility
|
|
10
|
-
- Static assets
|
|
10
|
+
- Static assets remain asset first by default. Blanket `assets.run_worker_first: true` fails the build and `doctor`; narrow route-pattern arrays remain available for intentional middleware and skew recovery
|
|
11
11
|
- Workers Logs sampled at 10%, traces at 1%, both overridable
|
|
12
|
+
- Preview URLs disabled unless explicitly enabled
|
|
13
|
+
- `workers_dev` disabled when a route proves the Worker remains reachable; workers without routes must choose explicitly
|
|
12
14
|
- Version metadata binding at `CF_VERSION_METADATA`
|
|
15
|
+
- Workers Caching explicitly disabled by default; opt-in requires a version-sharing decision
|
|
16
|
+
- Smart Placement enabled by default; explicit region, host, or hostname placement is preserved
|
|
13
17
|
- Source-map upload when the Nitro build emits maps; explicit `false` is preserved
|
|
14
|
-
- `secrets.required` names
|
|
18
|
+
- Module-wide `secrets.required` names copied to each environment; source root secrets remain scoped to the root
|
|
19
|
+
- Version metadata is skipped when `CF_VERSION_METADATA` already names another binding
|
|
15
20
|
- Raw `cloudflare-kv-binding` on Nitro's `cache` mount upgraded to a 30-day physical expiry
|
|
16
21
|
- Final generated Wrangler config audited after production Nitro compiles
|
|
17
22
|
- Complete defaults and diagnostics applied to every named Wrangler environment
|
|
@@ -26,6 +31,7 @@ export default defineNuxtConfig({
|
|
|
26
31
|
|
|
27
32
|
nuxtCloudflare: {
|
|
28
33
|
requiredSecrets: ['NUXT_SESSION_PASSWORD'],
|
|
34
|
+
workersCache: { _tag: 'enabled', crossVersion: false },
|
|
29
35
|
},
|
|
30
36
|
|
|
31
37
|
nitro: {
|
|
@@ -52,6 +58,10 @@ export default defineNuxtConfig({
|
|
|
52
58
|
|
|
53
59
|
Cloudflare KV requires TTLs of at least 60 seconds.
|
|
54
60
|
|
|
61
|
+
Workers Caching is separate from Nitro's KV-backed cache. Enabling it lets Cloudflare serve responses without invoking the Worker. Keep `crossVersion: false` for deploy isolation; choose `true` only when stale responses across deployments are acceptable and a purge path exists. An authored `nitro.cloudflare.wrangler.cache` block is preserved unless `nuxtCloudflare.workersCache` is set.
|
|
62
|
+
|
|
63
|
+
Smart Placement moves fetch handlers only when Cloudflare measures a faster location near upstream services. Assets-first delivery remains close to the user. Queue handlers, RPC methods, and named entrypoints are unaffected. An authored region, host, or hostname placement overrides the smart default.
|
|
64
|
+
|
|
55
65
|
## Doctor
|
|
56
66
|
|
|
57
67
|
Audit Wrangler's effective configuration, including generated config redirects and named environments:
|
|
@@ -59,20 +69,40 @@ Audit Wrangler's effective configuration, including generated config redirects a
|
|
|
59
69
|
```sh
|
|
60
70
|
pnpm nuxt-cloudflare doctor
|
|
61
71
|
pnpm nuxt-cloudflare doctor --env production --json
|
|
72
|
+
pnpm nuxt-cloudflare doctor --strict --allow-warning source-maps-disabled
|
|
62
73
|
```
|
|
63
74
|
|
|
64
|
-
|
|
75
|
+
The CLI reads Wrangler config through Wrangler itself, so JSON, JSONC, TOML, environments, upward lookup, and Nitro generated-config redirects follow deployment semantics. It separately inspects root authoring format. Existing TOML remains supported and receives non-blocking guidance because Cloudflare recommends JSONC for new projects. Shadowed root configs warn because they can silently drift.
|
|
76
|
+
|
|
77
|
+
Errors cover blanket Worker-first assets, malformed selective asset patterns, missing `nodejs_compat`, malformed compatibility dates, secret names duplicated across `vars` and `secrets.required`, queue platform-limit violations, and unflattened generated environments. Warnings cover secret-looking variable names, telemetry gaps, stale dates, implicit or cross-version Workers Caching, `keep_vars`, public endpoints, preview URLs, missing DLQs, and project policy. Secret values are never included.
|
|
78
|
+
|
|
79
|
+
Normal mode fails errors. `--strict` also fails warnings. Intentional exceptions remain visible and may be listed with `--allow-warning`. Module builds use the equivalent policy:
|
|
80
|
+
|
|
81
|
+
`nodejs_compat` is required by default because this is a Nuxt module. Use `--node-compat ignore` only when auditing a non-Nuxt companion Worker, such as a redirect-only Worker.
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
export default defineNuxtConfig({
|
|
85
|
+
nuxtCloudflare: {
|
|
86
|
+
doctor: {
|
|
87
|
+
_tag: 'strict',
|
|
88
|
+
allowedWarnings: ['source-maps-disabled'],
|
|
89
|
+
},
|
|
90
|
+
},
|
|
91
|
+
})
|
|
92
|
+
```
|
|
65
93
|
|
|
66
94
|
Recommended CI sequence:
|
|
67
95
|
|
|
68
96
|
```sh
|
|
69
97
|
pnpm nuxt build
|
|
70
|
-
pnpm nuxt-cloudflare doctor
|
|
71
|
-
pnpm wrangler types --check
|
|
72
|
-
pnpm wrangler deploy --strict --dry-run --outdir .wrangler-dist
|
|
73
|
-
pnpm wrangler check startup
|
|
98
|
+
pnpm nuxt-cloudflare doctor --strict
|
|
99
|
+
pnpm wrangler types --check --config .output/server/wrangler.json
|
|
100
|
+
pnpm wrangler deploy --strict --dry-run --config .output/server/wrangler.json --outdir .wrangler-dist
|
|
101
|
+
pnpm wrangler check startup --config .output/server/wrangler.json
|
|
74
102
|
```
|
|
75
103
|
|
|
104
|
+
Pass the final generated config explicitly to `types` and `check startup`; Nitro's `.wrangler/deploy/config.json` redirect does not apply to those commands.
|
|
105
|
+
|
|
76
106
|
## Runtime primitives
|
|
77
107
|
|
|
78
108
|
### D1 sessions and safe retries
|
|
@@ -90,6 +120,29 @@ await retryIdempotentD1Write({
|
|
|
90
120
|
|
|
91
121
|
One `first-primary` session is cached per request and binding. D1 already retries read-only queries. Write retries require an explicit safety tag. `lock-only` retries SQLite lock contention; `replay-safe` also permits classified transient network and reset failures.
|
|
92
122
|
|
|
123
|
+
### D1 parameter plans
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import {
|
|
127
|
+
assertD1BoundParameters,
|
|
128
|
+
chunkD1Items,
|
|
129
|
+
defineD1ParameterPlan,
|
|
130
|
+
} from '@harlan-zw/nuxt-cloudflare/d1'
|
|
131
|
+
|
|
132
|
+
const siteIdPlan = defineD1ParameterPlan({
|
|
133
|
+
parametersPerItem: 1,
|
|
134
|
+
reservedParameters: 2,
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
for (const ids of chunkD1Items(siteIds, siteIdPlan)) {
|
|
138
|
+
const query = db.select().from(sites).where(inArray(sites.id, ids))
|
|
139
|
+
assertD1BoundParameters(query.toSQL().params)
|
|
140
|
+
await query
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
D1 allows 100 bound parameters per statement, including each statement inside `db.batch()`. The parsed opaque plan rejects fractions, non-finite values, negative reservations, forged runtime plans, and budgets that cannot fit one item. `parametersPerItem` supports multi-row inserts; `reservedParameters` accounts for fixed binds and deliberate headroom. `assertD1BoundParameters` verifies the final ORM output in regression tests. Chunk execution, ordering, transaction boundaries, and result merging remain explicit at the call site.
|
|
145
|
+
|
|
93
146
|
### Bindings
|
|
94
147
|
|
|
95
148
|
```ts
|
|
@@ -127,7 +180,7 @@ The writer uses exclusive creation and mode 0600. It removes partial files after
|
|
|
127
180
|
|
|
128
181
|
## Deliberate boundaries
|
|
129
182
|
|
|
130
|
-
The module does not choose Worker names, routes, domains, resource IDs,
|
|
183
|
+
The module does not choose Worker names, routes, domains, resource IDs, 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.
|
|
131
184
|
|
|
132
185
|
Next high-value extractions from Nuxt SEO and gscdump:
|
|
133
186
|
|
package/dist/cli/index.mjs
CHANGED
|
@@ -2,14 +2,55 @@
|
|
|
2
2
|
import process from 'node:process';
|
|
3
3
|
import { defineCommand, runMain } from 'citty';
|
|
4
4
|
import { resolve, dirname } from 'pathe';
|
|
5
|
+
import { d as discoverWranglerSourceConfigs, a as diagnoseWranglerSourceConfigs, p as parseWranglerAllowedWarnings, e as evaluateWranglerDiagnostics } from '../shared/nuxt-cloudflare.6X-qzF_b.mjs';
|
|
5
6
|
import { diagnoseWranglerConfig, formatWranglerDiagnostics } from '../wrangler.mjs';
|
|
6
7
|
import { existsSync, readFileSync } from 'node:fs';
|
|
7
8
|
import { unstable_readConfig } from 'wrangler';
|
|
8
9
|
import 'node:fs/promises';
|
|
9
10
|
|
|
11
|
+
function errorMessage(error) {
|
|
12
|
+
return error instanceof Error ? error.message : String(error);
|
|
13
|
+
}
|
|
14
|
+
function attempt(run) {
|
|
15
|
+
try {
|
|
16
|
+
return { _tag: "loaded", value: run() };
|
|
17
|
+
} catch (error) {
|
|
18
|
+
return { _tag: "invalid", reason: errorMessage(error) };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function findUpFile(cwd, relativePath) {
|
|
22
|
+
let directory = resolve(cwd);
|
|
23
|
+
while (true) {
|
|
24
|
+
const candidate = resolve(directory, relativePath);
|
|
25
|
+
if (existsSync(candidate))
|
|
26
|
+
return candidate;
|
|
27
|
+
const parent = dirname(directory);
|
|
28
|
+
if (parent === directory)
|
|
29
|
+
return void 0;
|
|
30
|
+
directory = parent;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function findUpWranglerConfig(cwd) {
|
|
34
|
+
let directory = resolve(cwd);
|
|
35
|
+
while (true) {
|
|
36
|
+
for (const name of ["wrangler.json", "wrangler.jsonc", "wrangler.toml"]) {
|
|
37
|
+
const candidate = resolve(directory, name);
|
|
38
|
+
if (existsSync(candidate))
|
|
39
|
+
return candidate;
|
|
40
|
+
}
|
|
41
|
+
const parent = dirname(directory);
|
|
42
|
+
if (parent === directory)
|
|
43
|
+
return void 0;
|
|
44
|
+
directory = parent;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
10
47
|
function resolveNitroDeployConfig(cwd) {
|
|
11
|
-
const redirectPath =
|
|
12
|
-
if (!
|
|
48
|
+
const redirectPath = findUpFile(cwd, ".wrangler/deploy/config.json");
|
|
49
|
+
if (!redirectPath)
|
|
50
|
+
return void 0;
|
|
51
|
+
const redirectProjectDirectory = dirname(dirname(dirname(redirectPath)));
|
|
52
|
+
const authoredConfigPath = findUpWranglerConfig(cwd);
|
|
53
|
+
if (authoredConfigPath && dirname(authoredConfigPath) !== redirectProjectDirectory)
|
|
13
54
|
return void 0;
|
|
14
55
|
const parsed = JSON.parse(readFileSync(redirectPath, "utf8"));
|
|
15
56
|
if (!parsed || typeof parsed !== "object" || !("configPath" in parsed) || typeof parsed.configPath !== "string")
|
|
@@ -17,18 +58,75 @@ function resolveNitroDeployConfig(cwd) {
|
|
|
17
58
|
return resolve(dirname(redirectPath), parsed.configPath);
|
|
18
59
|
}
|
|
19
60
|
function readProjectWranglerConfig(options) {
|
|
20
|
-
const
|
|
21
|
-
|
|
61
|
+
const redirect = attempt(() => options.config ? void 0 : resolveNitroDeployConfig(options.cwd));
|
|
62
|
+
if (redirect._tag === "invalid") {
|
|
63
|
+
return {
|
|
64
|
+
_tag: "invalid",
|
|
65
|
+
generated: false,
|
|
66
|
+
path: findUpFile(options.cwd, ".wrangler/deploy/config.json") ?? resolve(options.cwd, ".wrangler/deploy/config.json"),
|
|
67
|
+
reason: redirect.reason
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
const generatedConfigPath = redirect.value;
|
|
71
|
+
const configPath = options.config ? resolve(options.cwd, options.config) : generatedConfigPath;
|
|
72
|
+
const loaded = attempt(() => unstable_readConfig({
|
|
22
73
|
config: configPath,
|
|
23
74
|
env: options.environment,
|
|
24
75
|
script: resolve(options.cwd, "__nuxt-cloudflare-doctor.mjs")
|
|
25
76
|
}, {
|
|
26
77
|
hideWarnings: true,
|
|
27
78
|
useRedirectIfAvailable: false
|
|
28
|
-
});
|
|
79
|
+
}));
|
|
80
|
+
if (loaded._tag === "invalid") {
|
|
81
|
+
return {
|
|
82
|
+
_tag: "invalid",
|
|
83
|
+
generated: generatedConfigPath !== void 0,
|
|
84
|
+
path: configPath,
|
|
85
|
+
reason: loaded.reason
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
_tag: "loaded",
|
|
90
|
+
config: loaded.value,
|
|
91
|
+
generated: generatedConfigPath !== void 0,
|
|
92
|
+
path: loaded.value.configPath
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function diagnoseWranglerProject(options) {
|
|
97
|
+
const sourceConfigPaths = discoverWranglerSourceConfigs(options.cwd, options.config);
|
|
98
|
+
const loaded = readProjectWranglerConfig(options);
|
|
99
|
+
if (loaded._tag === "invalid") {
|
|
100
|
+
return {
|
|
101
|
+
configPath: loaded.path,
|
|
102
|
+
diagnostics: [{
|
|
103
|
+
_tag: "error",
|
|
104
|
+
code: "wrangler-config-unreadable",
|
|
105
|
+
message: "Wrangler could not read the effective config. Build Nuxt again or run Wrangler locally for validation details.",
|
|
106
|
+
sourcePath: loaded.path ?? "wrangler config"
|
|
107
|
+
}, ...diagnoseWranglerSourceConfigs(sourceConfigPaths)],
|
|
108
|
+
sourceConfigPaths
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
if (!loaded.path && sourceConfigPaths.length === 0) {
|
|
112
|
+
return {
|
|
113
|
+
configPath: void 0,
|
|
114
|
+
diagnostics: [{
|
|
115
|
+
_tag: "error",
|
|
116
|
+
code: "wrangler-config-missing",
|
|
117
|
+
message: "No authored or generated Wrangler config exists. Build Nuxt before running doctor.",
|
|
118
|
+
sourcePath: options.cwd
|
|
119
|
+
}],
|
|
120
|
+
sourceConfigPaths
|
|
121
|
+
};
|
|
122
|
+
}
|
|
29
123
|
return {
|
|
30
|
-
|
|
31
|
-
|
|
124
|
+
configPath: loaded.path,
|
|
125
|
+
diagnostics: [
|
|
126
|
+
...diagnoseWranglerConfig(loaded.config, { ...options, generated: loaded.generated }),
|
|
127
|
+
...diagnoseWranglerSourceConfigs(sourceConfigPaths)
|
|
128
|
+
],
|
|
129
|
+
sourceConfigPaths
|
|
32
130
|
};
|
|
33
131
|
}
|
|
34
132
|
|
|
@@ -39,32 +137,57 @@ const doctor = defineCommand({
|
|
|
39
137
|
"config": { type: "string", description: "Wrangler config path" },
|
|
40
138
|
"env": { type: "string", description: "Wrangler environment" },
|
|
41
139
|
"json": { type: "boolean", description: "Print JSON diagnostics", default: false },
|
|
42
|
-
"max-compatibility-age": { type: "string", description: "Compatibility date policy in days", default: "90" }
|
|
140
|
+
"max-compatibility-age": { type: "string", description: "Compatibility date policy in days", default: "90" },
|
|
141
|
+
"node-compat": { type: "string", description: "Node compatibility policy: required or ignore", default: "required" },
|
|
142
|
+
"public-var": { type: "string", description: "Comma-separated public var names exempt from secret-name heuristics" },
|
|
143
|
+
"strict": { type: "boolean", description: "Fail on warnings as well as errors", default: false },
|
|
144
|
+
"allow-warning": { type: "string", description: "Comma-separated warning codes allowed in strict mode" }
|
|
43
145
|
},
|
|
44
146
|
run({ args }) {
|
|
45
147
|
const cwd = resolve(args.cwd);
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
148
|
+
const compatibilityMaxAgeDays = Number(args["max-compatibility-age"]);
|
|
149
|
+
if (!Number.isSafeInteger(compatibilityMaxAgeDays) || compatibilityMaxAgeDays < 1)
|
|
150
|
+
throw new TypeError("--max-compatibility-age must be a positive integer");
|
|
151
|
+
if (args["node-compat"] !== "required" && args["node-compat"] !== "ignore")
|
|
152
|
+
throw new TypeError("--node-compat must be required or ignore");
|
|
153
|
+
const publicVarNames = args["public-var"]?.split(",").map((value) => value.trim()).filter(Boolean);
|
|
154
|
+
const result = diagnoseWranglerProject({
|
|
155
|
+
cwd,
|
|
156
|
+
config: args.config,
|
|
157
|
+
environment: args.env,
|
|
158
|
+
compatibilityMaxAgeDays,
|
|
159
|
+
publicVarNames,
|
|
160
|
+
requireNodeCompat: args["node-compat"] === "required"
|
|
49
161
|
});
|
|
50
|
-
const
|
|
162
|
+
const allowedWarnings = parseWranglerAllowedWarnings(args["allow-warning"]);
|
|
163
|
+
const policy = args.strict ? { _tag: "strict", allowedWarnings } : { _tag: "advisory" };
|
|
164
|
+
const outcome = evaluateWranglerDiagnostics(result.diagnostics, policy);
|
|
165
|
+
const payload = {
|
|
166
|
+
configPath: result.configPath,
|
|
167
|
+
diagnostics: result.diagnostics,
|
|
168
|
+
outcome: outcome._tag,
|
|
169
|
+
...outcome._tag === "failed" ? { reason: outcome.reason } : {},
|
|
170
|
+
schemaVersion: outcome.schemaVersion,
|
|
171
|
+
sourceConfigPaths: result.sourceConfigPaths,
|
|
172
|
+
strict: args.strict
|
|
173
|
+
};
|
|
51
174
|
if (args.json)
|
|
52
175
|
process.stdout.write(`${JSON.stringify(payload, null, 2)}
|
|
53
176
|
`);
|
|
54
|
-
else if (diagnostics.length === 0)
|
|
55
|
-
process.stdout.write(`Cloudflare config valid: ${
|
|
177
|
+
else if (result.diagnostics.length === 0)
|
|
178
|
+
process.stdout.write(`Cloudflare config valid: ${result.configPath ?? "inline/default"}
|
|
56
179
|
`);
|
|
57
180
|
else
|
|
58
|
-
process.stdout.write(`${formatWranglerDiagnostics(diagnostics)}
|
|
181
|
+
process.stdout.write(`${formatWranglerDiagnostics(result.diagnostics)}
|
|
59
182
|
`);
|
|
60
|
-
if (
|
|
183
|
+
if (outcome._tag === "failed")
|
|
61
184
|
process.exitCode = 1;
|
|
62
185
|
}
|
|
63
186
|
});
|
|
64
187
|
const main = defineCommand({
|
|
65
188
|
meta: {
|
|
66
189
|
name: "nuxt-cloudflare",
|
|
67
|
-
version: "0.0.
|
|
190
|
+
version: "0.0.3",
|
|
68
191
|
description: "Cloudflare deployment defaults and diagnostics for Nuxt"
|
|
69
192
|
},
|
|
70
193
|
subCommands: { doctor }
|
package/dist/d1.d.mts
CHANGED
|
@@ -3,6 +3,18 @@ type D1WriteSafety = {
|
|
|
3
3
|
} | {
|
|
4
4
|
_tag: 'replay-safe';
|
|
5
5
|
};
|
|
6
|
+
declare const D1_MAX_BOUND_PARAMETERS = 100;
|
|
7
|
+
declare const D1_PARAMETER_PLAN: unique symbol;
|
|
8
|
+
interface D1ParameterPlanInput {
|
|
9
|
+
parametersPerItem: number;
|
|
10
|
+
reservedParameters: number;
|
|
11
|
+
}
|
|
12
|
+
interface D1ParameterPlan {
|
|
13
|
+
readonly [D1_PARAMETER_PLAN]: true;
|
|
14
|
+
readonly itemsPerStatement: number;
|
|
15
|
+
readonly parametersPerItem: number;
|
|
16
|
+
readonly reservedParameters: number;
|
|
17
|
+
}
|
|
6
18
|
type D1Consistency = {
|
|
7
19
|
_tag: 'first-primary';
|
|
8
20
|
} | {
|
|
@@ -28,10 +40,13 @@ type D1RetryErrorKind = {
|
|
|
28
40
|
} | {
|
|
29
41
|
_tag: 'permanent';
|
|
30
42
|
};
|
|
43
|
+
declare function defineD1ParameterPlan(input: D1ParameterPlanInput): D1ParameterPlan;
|
|
44
|
+
declare function chunkD1Items<T>(items: readonly T[], plan: D1ParameterPlan): T[][];
|
|
45
|
+
declare function assertD1BoundParameters(parameters: readonly unknown[]): void;
|
|
31
46
|
declare function classifyD1RetryError(error: unknown): D1RetryErrorKind;
|
|
32
47
|
declare function isTransientD1Error(error: unknown): boolean;
|
|
33
48
|
declare function getRequestD1Session<Session>(requestContext: Record<PropertyKey, unknown>, binding: string, database: D1SessionSource<Session>, consistency?: D1Consistency): Session;
|
|
34
49
|
declare function retryIdempotentD1Write<T>(options: RetryIdempotentD1WriteOptions<T>): Promise<T>;
|
|
35
50
|
|
|
36
|
-
export { classifyD1RetryError, getRequestD1Session, isTransientD1Error, retryIdempotentD1Write };
|
|
37
|
-
export type { D1Consistency, D1RetryErrorKind, D1SessionSource, D1WriteSafety, RetryIdempotentD1WriteOptions };
|
|
51
|
+
export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRequestD1Session, isTransientD1Error, retryIdempotentD1Write };
|
|
52
|
+
export type { D1Consistency, D1ParameterPlan, D1ParameterPlanInput, D1RetryErrorKind, D1SessionSource, D1WriteSafety, RetryIdempotentD1WriteOptions };
|
package/dist/d1.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
const D1_MAX_BOUND_PARAMETERS = 100;
|
|
2
|
+
const D1_PARAMETER_PLAN = Symbol("@harlan-zw/nuxt-cloudflare:d1-parameter-plan");
|
|
1
3
|
const REQUEST_D1_SESSIONS = Symbol.for("@harlan-zw/nuxt-cloudflare:d1-sessions");
|
|
2
4
|
const TRANSIENT_D1_SIGNALS = [
|
|
3
5
|
"Network connection lost",
|
|
@@ -28,12 +30,73 @@ function parseMaxAttempts(value) {
|
|
|
28
30
|
throw new TypeError("D1 maxAttempts must be a positive integer");
|
|
29
31
|
return attempts;
|
|
30
32
|
}
|
|
33
|
+
function parseParameterCount(name, value, minimum) {
|
|
34
|
+
if (!Number.isSafeInteger(value) || value < minimum)
|
|
35
|
+
throw new TypeError(`D1 ${name} must be an integer greater than or equal to ${minimum}`);
|
|
36
|
+
return value;
|
|
37
|
+
}
|
|
38
|
+
function defineD1ParameterPlan(input) {
|
|
39
|
+
const parametersPerItem = parseParameterCount("parametersPerItem", input.parametersPerItem, 1);
|
|
40
|
+
const reservedParameters = parseParameterCount(
|
|
41
|
+
"reservedParameters",
|
|
42
|
+
input.reservedParameters,
|
|
43
|
+
0
|
|
44
|
+
);
|
|
45
|
+
const itemsPerStatement = Math.floor(
|
|
46
|
+
(D1_MAX_BOUND_PARAMETERS - reservedParameters) / parametersPerItem
|
|
47
|
+
);
|
|
48
|
+
if (itemsPerStatement < 1)
|
|
49
|
+
throw new TypeError("D1 parameter budget cannot fit one item");
|
|
50
|
+
return Object.freeze({
|
|
51
|
+
[D1_PARAMETER_PLAN]: true,
|
|
52
|
+
itemsPerStatement,
|
|
53
|
+
parametersPerItem,
|
|
54
|
+
reservedParameters
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function chunkD1Items(items, plan) {
|
|
58
|
+
if (plan?.[D1_PARAMETER_PLAN] !== true)
|
|
59
|
+
throw new TypeError("D1 parameter plan must come from defineD1ParameterPlan");
|
|
60
|
+
const chunks = [];
|
|
61
|
+
for (let index = 0; index < items.length; index += plan.itemsPerStatement)
|
|
62
|
+
chunks.push(items.slice(index, index + plan.itemsPerStatement));
|
|
63
|
+
return chunks;
|
|
64
|
+
}
|
|
65
|
+
function assertD1BoundParameters(parameters) {
|
|
66
|
+
if (!Array.isArray(parameters))
|
|
67
|
+
throw new TypeError("D1 bound parameters must be an array");
|
|
68
|
+
if (parameters.length > D1_MAX_BOUND_PARAMETERS) {
|
|
69
|
+
throw new RangeError(
|
|
70
|
+
`D1 statement has ${parameters.length} bound parameters; maximum is ${D1_MAX_BOUND_PARAMETERS}`
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
31
74
|
function classifyD1RetryError(error) {
|
|
32
|
-
const
|
|
33
|
-
|
|
75
|
+
const messages = [];
|
|
76
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
77
|
+
let current = error;
|
|
78
|
+
while (current !== void 0 && current !== null) {
|
|
79
|
+
if (typeof current !== "object") {
|
|
80
|
+
messages.push(String(current));
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
if (seen.has(current))
|
|
84
|
+
break;
|
|
85
|
+
seen.add(current);
|
|
86
|
+
if (current instanceof Error)
|
|
87
|
+
messages.push(current.message);
|
|
88
|
+
else if ("message" in current && typeof current.message === "string")
|
|
89
|
+
messages.push(current.message);
|
|
90
|
+
current = "cause" in current ? current.cause : void 0;
|
|
91
|
+
}
|
|
92
|
+
if (messages.some((message) => /busy|locked/i.test(message)))
|
|
34
93
|
return { _tag: "lock" };
|
|
35
|
-
if (
|
|
94
|
+
if (messages.some((message) => {
|
|
95
|
+
const normalized = message.toLowerCase();
|
|
96
|
+
return TRANSIENT_D1_SIGNALS.some((signal) => normalized.includes(signal.toLowerCase()));
|
|
97
|
+
})) {
|
|
36
98
|
return { _tag: "transient" };
|
|
99
|
+
}
|
|
37
100
|
return { _tag: "permanent" };
|
|
38
101
|
}
|
|
39
102
|
function isTransientD1Error(error) {
|
|
@@ -57,7 +120,7 @@ async function retryIdempotentD1Write(options) {
|
|
|
57
120
|
const sleep = options.sleep ?? defaultSleep;
|
|
58
121
|
let lastError;
|
|
59
122
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
60
|
-
const outcome = await options.run
|
|
123
|
+
const outcome = await Promise.resolve().then(options.run).then(
|
|
61
124
|
(value) => ({ _tag: "ok", value }),
|
|
62
125
|
(error) => ({ _tag: "error", error })
|
|
63
126
|
);
|
|
@@ -73,4 +136,4 @@ async function retryIdempotentD1Write(options) {
|
|
|
73
136
|
throw lastError;
|
|
74
137
|
}
|
|
75
138
|
|
|
76
|
-
export { classifyD1RetryError, getRequestD1Session, isTransientD1Error, retryIdempotentD1Write };
|
|
139
|
+
export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRequestD1Session, isTransientD1Error, retryIdempotentD1Write };
|
package/dist/module.d.mts
CHANGED
|
@@ -1,10 +1,18 @@
|
|
|
1
|
-
import { WranglerConfigInput } from './wrangler.mjs';
|
|
1
|
+
import { WranglerDiagnosticCode, WorkersCachePolicy, WranglerConfigInput } from './wrangler.mjs';
|
|
2
2
|
import { Nuxt } from '@nuxt/schema';
|
|
3
3
|
|
|
4
|
+
type WranglerDiagnosticPolicy = {
|
|
5
|
+
_tag: 'advisory';
|
|
6
|
+
} | {
|
|
7
|
+
_tag: 'strict';
|
|
8
|
+
allowedWarnings?: readonly WranglerDiagnosticCode[];
|
|
9
|
+
};
|
|
10
|
+
|
|
4
11
|
interface ModuleOptions {
|
|
5
12
|
enabled?: boolean;
|
|
6
13
|
compatibilityDate?: string;
|
|
7
14
|
compatibilityMaxAgeDays?: number;
|
|
15
|
+
doctor?: WranglerDiagnosticPolicy;
|
|
8
16
|
kvCache?: false | {
|
|
9
17
|
binding: string;
|
|
10
18
|
defaultTtl?: number;
|
|
@@ -15,6 +23,7 @@ interface ModuleOptions {
|
|
|
15
23
|
sourceMaps?: boolean;
|
|
16
24
|
tracesSampleRate?: number;
|
|
17
25
|
versionMetadataBinding?: string;
|
|
26
|
+
workersCache?: WorkersCachePolicy;
|
|
18
27
|
}
|
|
19
28
|
interface NitroStorageMount extends Record<string, unknown> {
|
|
20
29
|
driver?: unknown;
|
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { useLogger, defineNuxtModule } from '@nuxt/kit';
|
|
2
2
|
import { resolve } from 'pathe';
|
|
3
|
+
import { a as diagnoseWranglerSourceConfigs, d as discoverWranglerSourceConfigs, e as evaluateWranglerDiagnostics } from './shared/nuxt-cloudflare.6X-qzF_b.mjs';
|
|
3
4
|
import { readWranglerJsonFile, diagnoseWranglerConfig, formatWranglerDiagnostics, applyCloudflareDefaults } from './wrangler.mjs';
|
|
5
|
+
import 'node:fs';
|
|
4
6
|
import 'node:fs/promises';
|
|
5
7
|
|
|
6
8
|
const logger = useLogger("nuxt-cloudflare");
|
|
@@ -16,7 +18,8 @@ function configureNitroCloudflare(nitro, options, nuxtServerSourceMaps) {
|
|
|
16
18
|
requiredSecrets: options.requiredSecrets,
|
|
17
19
|
tracesSampleRate: options.tracesSampleRate,
|
|
18
20
|
uploadSourceMaps: options.sourceMaps ?? nitro.sourceMap ?? nuxtServerSourceMaps ?? false,
|
|
19
|
-
versionMetadataBinding: options.versionMetadataBinding
|
|
21
|
+
versionMetadataBinding: options.versionMetadataBinding,
|
|
22
|
+
workersCache: options.workersCache
|
|
20
23
|
});
|
|
21
24
|
if (options.kvCache === false)
|
|
22
25
|
return;
|
|
@@ -32,24 +35,33 @@ function configureNitroCloudflare(nitro, options, nuxtServerSourceMaps) {
|
|
|
32
35
|
defaultTtl: configuredCache?.defaultTtl ?? 30 * 24 * 60 * 60
|
|
33
36
|
};
|
|
34
37
|
}
|
|
35
|
-
async function auditGeneratedWranglerConfig(nitro, options) {
|
|
38
|
+
async function auditGeneratedWranglerConfig(nitro, options, rootDir) {
|
|
36
39
|
const path = resolve(nitro.options.output.serverDir, "wrangler.json");
|
|
37
40
|
const result = await readWranglerJsonFile(path);
|
|
38
41
|
if (result._tag === "missing")
|
|
39
42
|
throw new Error(`[nuxt-cloudflare] Generated Wrangler config is missing: ${path}`);
|
|
40
43
|
if (result._tag === "invalid")
|
|
41
44
|
throw new Error(`[nuxt-cloudflare] Generated Wrangler config is invalid: ${result.reason}`);
|
|
42
|
-
const diagnostics =
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
45
|
+
const diagnostics = [
|
|
46
|
+
...diagnoseWranglerConfig(result.config, {
|
|
47
|
+
compatibilityMaxAgeDays: options.compatibilityMaxAgeDays,
|
|
48
|
+
generated: true,
|
|
49
|
+
publicVarNames: options.publicVarNames
|
|
50
|
+
}),
|
|
51
|
+
...diagnoseWranglerSourceConfigs(discoverWranglerSourceConfigs(rootDir))
|
|
52
|
+
];
|
|
53
|
+
const policy = options.doctor ?? { _tag: "advisory" };
|
|
54
|
+
const outcome = evaluateWranglerDiagnostics(diagnostics, policy);
|
|
55
|
+
const blocking = new Set(outcome.blockingDiagnostics);
|
|
56
|
+
const warnings = diagnostics.filter((diagnostic) => diagnostic._tag === "warning" && !blocking.has(diagnostic));
|
|
57
|
+
const information = diagnostics.filter((diagnostic) => diagnostic._tag === "info");
|
|
58
|
+
if (information.length > 0)
|
|
59
|
+
logger.info(formatWranglerDiagnostics(information));
|
|
48
60
|
if (warnings.length > 0)
|
|
49
61
|
logger.warn(formatWranglerDiagnostics(warnings));
|
|
50
|
-
if (
|
|
62
|
+
if (outcome._tag === "failed")
|
|
51
63
|
throw new Error(`[nuxt-cloudflare]
|
|
52
|
-
${formatWranglerDiagnostics(
|
|
64
|
+
${formatWranglerDiagnostics(outcome.blockingDiagnostics)}`);
|
|
53
65
|
}
|
|
54
66
|
function setupCloudflareModule(options, nuxt) {
|
|
55
67
|
if (!options.enabled)
|
|
@@ -65,7 +77,7 @@ function setupCloudflareModule(options, nuxt) {
|
|
|
65
77
|
});
|
|
66
78
|
if (!nuxt.options.dev) {
|
|
67
79
|
nuxt.hook("nitro:init", (nitro) => {
|
|
68
|
-
nitro.hooks.hook("compiled", () => auditGeneratedWranglerConfig(nitro, options));
|
|
80
|
+
nitro.hooks.hook("compiled", () => auditGeneratedWranglerConfig(nitro, options, nuxt.options.rootDir));
|
|
69
81
|
});
|
|
70
82
|
}
|
|
71
83
|
}
|
|
@@ -78,6 +90,7 @@ const module$1 = defineNuxtModule({
|
|
|
78
90
|
defaults: {
|
|
79
91
|
enabled: true,
|
|
80
92
|
compatibilityMaxAgeDays: 90,
|
|
93
|
+
doctor: { _tag: "advisory" },
|
|
81
94
|
logsSampleRate: 0.1,
|
|
82
95
|
tracesSampleRate: 0.01,
|
|
83
96
|
versionMetadataBinding: "CF_VERSION_METADATA"
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { resolve, dirname, extname } from 'pathe';
|
|
3
|
+
import { WRANGLER_DIAGNOSTIC_CODES } from '../wrangler.mjs';
|
|
4
|
+
|
|
5
|
+
const WRANGLER_SOURCE_CONFIG_NAMES = [
|
|
6
|
+
"wrangler.json",
|
|
7
|
+
"wrangler.jsonc",
|
|
8
|
+
"wrangler.toml"
|
|
9
|
+
];
|
|
10
|
+
function discoverWranglerSourceConfigs(cwd, explicitConfig) {
|
|
11
|
+
if (explicitConfig) {
|
|
12
|
+
const path = resolve(cwd, explicitConfig);
|
|
13
|
+
return existsSync(path) ? [path] : [];
|
|
14
|
+
}
|
|
15
|
+
let directory = resolve(cwd);
|
|
16
|
+
while (true) {
|
|
17
|
+
const paths = WRANGLER_SOURCE_CONFIG_NAMES.map((name) => resolve(directory, name)).filter((path) => existsSync(path));
|
|
18
|
+
if (paths.length > 0)
|
|
19
|
+
return paths;
|
|
20
|
+
const parent = dirname(directory);
|
|
21
|
+
if (parent === directory)
|
|
22
|
+
return [];
|
|
23
|
+
directory = parent;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function diagnoseWranglerSourceConfigs(paths) {
|
|
27
|
+
const diagnostics = paths.flatMap((path) => extname(path) === ".toml" ? [{
|
|
28
|
+
_tag: "info",
|
|
29
|
+
code: "wrangler-jsonc-preferred",
|
|
30
|
+
message: "Cloudflare recommends wrangler.jsonc for new projects; TOML remains supported.",
|
|
31
|
+
sourcePath: path
|
|
32
|
+
}] : []);
|
|
33
|
+
if (paths.length > 1) {
|
|
34
|
+
diagnostics.push({
|
|
35
|
+
_tag: "warning",
|
|
36
|
+
code: "wrangler-config-shadowed",
|
|
37
|
+
message: "Multiple root Wrangler configs exist. Keep one wrangler.jsonc source of truth to prevent silent precedence drift.",
|
|
38
|
+
sourcePath: paths[0]
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
return diagnostics;
|
|
42
|
+
}
|
|
43
|
+
function isWranglerDiagnosticBlocking(diagnostic, policy) {
|
|
44
|
+
if (diagnostic._tag === "error")
|
|
45
|
+
return true;
|
|
46
|
+
return diagnostic._tag === "warning" && policy._tag === "strict" && !new Set(policy.allowedWarnings ?? []).has(diagnostic.code);
|
|
47
|
+
}
|
|
48
|
+
function parseWranglerAllowedWarnings(value) {
|
|
49
|
+
if (!value)
|
|
50
|
+
return [];
|
|
51
|
+
const knownCodes = new Set(WRANGLER_DIAGNOSTIC_CODES);
|
|
52
|
+
return value.split(",").map((part) => part.trim()).filter(Boolean).map((code) => {
|
|
53
|
+
if (!knownCodes.has(code))
|
|
54
|
+
throw new TypeError(`Unknown Wrangler diagnostic code: ${code}`);
|
|
55
|
+
return code;
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
function evaluateWranglerDiagnostics(diagnostics, policy) {
|
|
59
|
+
const blockingDiagnostics = diagnostics.filter((diagnostic) => isWranglerDiagnosticBlocking(diagnostic, policy));
|
|
60
|
+
if (blockingDiagnostics.length === 0) {
|
|
61
|
+
return {
|
|
62
|
+
_tag: "passed",
|
|
63
|
+
blockingDiagnostics: [],
|
|
64
|
+
diagnostics,
|
|
65
|
+
schemaVersion: 1
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
_tag: "failed",
|
|
70
|
+
blockingDiagnostics,
|
|
71
|
+
diagnostics,
|
|
72
|
+
reason: blockingDiagnostics.some((diagnostic) => diagnostic._tag === "error") ? "errors" : "strict-warnings",
|
|
73
|
+
schemaVersion: 1
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export { diagnoseWranglerSourceConfigs as a, discoverWranglerSourceConfigs as d, evaluateWranglerDiagnostics as e, parseWranglerAllowedWarnings as p };
|
package/dist/wrangler.d.mts
CHANGED
|
@@ -3,6 +3,37 @@ interface WranglerAssetsInput {
|
|
|
3
3
|
binding?: string;
|
|
4
4
|
run_worker_first?: boolean | string[];
|
|
5
5
|
}
|
|
6
|
+
interface WranglerWorkersCacheInput {
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
cross_version_cache?: boolean;
|
|
9
|
+
}
|
|
10
|
+
type WranglerPlacementInput = {
|
|
11
|
+
mode: 'smart';
|
|
12
|
+
host?: never;
|
|
13
|
+
hostname?: never;
|
|
14
|
+
region?: never;
|
|
15
|
+
} | {
|
|
16
|
+
host: string;
|
|
17
|
+
hostname?: never;
|
|
18
|
+
mode?: never;
|
|
19
|
+
region?: never;
|
|
20
|
+
} | {
|
|
21
|
+
hostname: string;
|
|
22
|
+
host?: never;
|
|
23
|
+
mode?: never;
|
|
24
|
+
region?: never;
|
|
25
|
+
} | {
|
|
26
|
+
region: string;
|
|
27
|
+
host?: never;
|
|
28
|
+
hostname?: never;
|
|
29
|
+
mode?: never;
|
|
30
|
+
};
|
|
31
|
+
type WorkersCachePolicy = {
|
|
32
|
+
_tag: 'disabled';
|
|
33
|
+
} | {
|
|
34
|
+
_tag: 'enabled';
|
|
35
|
+
crossVersion: boolean;
|
|
36
|
+
};
|
|
6
37
|
interface WranglerObservabilityInput {
|
|
7
38
|
enabled?: boolean;
|
|
8
39
|
head_sampling_rate?: number;
|
|
@@ -18,13 +49,20 @@ interface WranglerObservabilityInput {
|
|
|
18
49
|
}
|
|
19
50
|
interface WranglerConfigInput extends Record<string, unknown> {
|
|
20
51
|
assets?: WranglerAssetsInput;
|
|
52
|
+
cache?: WranglerWorkersCacheInput;
|
|
21
53
|
compatibility_date?: string;
|
|
22
54
|
compatibility_flags?: string[];
|
|
23
55
|
env?: Record<string, WranglerConfigInput>;
|
|
56
|
+
keep_vars?: boolean;
|
|
24
57
|
observability?: WranglerObservabilityInput;
|
|
58
|
+
placement?: WranglerPlacementInput;
|
|
59
|
+
preview_urls?: boolean;
|
|
25
60
|
queues?: {
|
|
26
61
|
consumers?: Array<Record<string, unknown>>;
|
|
62
|
+
producers?: Array<Record<string, unknown>>;
|
|
27
63
|
};
|
|
64
|
+
route?: string | Record<string, unknown>;
|
|
65
|
+
routes?: Array<string | Record<string, unknown>>;
|
|
28
66
|
secrets?: {
|
|
29
67
|
required?: string[];
|
|
30
68
|
};
|
|
@@ -42,17 +80,23 @@ interface CloudflareDefaultOptions {
|
|
|
42
80
|
tracesSampleRate?: number;
|
|
43
81
|
uploadSourceMaps?: boolean;
|
|
44
82
|
versionMetadataBinding?: string;
|
|
83
|
+
workersCache?: WorkersCachePolicy;
|
|
45
84
|
}
|
|
85
|
+
declare const WRANGLER_DIAGNOSTIC_CODES: readonly ["assets-worker-first", "assets-worker-first-pattern-invalid", "compatibility-date-missing", "compatibility-date-invalid", "durable-object-binding-inactive", "durable-object-lifecycle-mixed", "durable-object-lifecycle-unmanaged", "generated-config-has-env", "keep-vars-enabled", "missing-nodejs-compat", "nodejs-compat-version-implicit", "observability-disabled", "observability-sampling-implicit", "observability-sampling-out-of-range", "plaintext-secret-var", "preview-urls-public", "queue-dlq-missing", "queue-retries-above-policy", "queue-retries-out-of-range", "queue-retry-delay-out-of-range", "secret-declared-as-var", "source-maps-disabled", "stale-compatibility-date", "traces-disabled", "version-metadata-missing", "workers-dev-enabled", "workers-dev-implicit", "workers-cache-cross-version-enabled", "workers-cache-policy-implicit", "wrangler-config-shadowed", "wrangler-config-missing", "wrangler-config-unreadable", "wrangler-jsonc-preferred"];
|
|
86
|
+
type WranglerDiagnosticCode = typeof WRANGLER_DIAGNOSTIC_CODES[number];
|
|
46
87
|
interface WranglerDiagnostic {
|
|
47
|
-
_tag: 'error' | 'warning';
|
|
48
|
-
code:
|
|
88
|
+
_tag: 'error' | 'info' | 'warning';
|
|
89
|
+
code: WranglerDiagnosticCode;
|
|
49
90
|
message: string;
|
|
50
|
-
|
|
91
|
+
configPath?: string;
|
|
92
|
+
sourcePath?: string;
|
|
51
93
|
}
|
|
52
94
|
interface WranglerDiagnosticOptions {
|
|
53
95
|
compatibilityMaxAgeDays?: number;
|
|
96
|
+
generated?: boolean;
|
|
54
97
|
now?: Date;
|
|
55
98
|
publicVarNames?: readonly string[];
|
|
99
|
+
requireNodeCompat?: boolean;
|
|
56
100
|
}
|
|
57
101
|
type WranglerJsonFileResult = {
|
|
58
102
|
_tag: 'loaded';
|
|
@@ -71,5 +115,5 @@ declare function diagnoseWranglerConfig(config: WranglerConfigInput, options?: W
|
|
|
71
115
|
declare function formatWranglerDiagnostics(diagnostics: readonly WranglerDiagnostic[]): string;
|
|
72
116
|
declare function readWranglerJsonFile(path: string): Promise<WranglerJsonFileResult>;
|
|
73
117
|
|
|
74
|
-
export { applyCloudflareDefaults, diagnoseWranglerConfig, formatWranglerDiagnostics, readWranglerJsonFile };
|
|
75
|
-
export type { CloudflareDefaultOptions, WranglerAssetsInput, WranglerConfigInput, WranglerDiagnostic, WranglerDiagnosticOptions, WranglerJsonFileResult, WranglerObservabilityInput };
|
|
118
|
+
export { WRANGLER_DIAGNOSTIC_CODES, applyCloudflareDefaults, diagnoseWranglerConfig, formatWranglerDiagnostics, readWranglerJsonFile };
|
|
119
|
+
export type { CloudflareDefaultOptions, WorkersCachePolicy, WranglerAssetsInput, WranglerConfigInput, WranglerDiagnostic, WranglerDiagnosticCode, WranglerDiagnosticOptions, WranglerJsonFileResult, WranglerObservabilityInput, WranglerPlacementInput, WranglerWorkersCacheInput };
|
package/dist/wrangler.mjs
CHANGED
|
@@ -1,8 +1,44 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
2
|
|
|
3
|
+
const WRANGLER_DIAGNOSTIC_CODES = [
|
|
4
|
+
"assets-worker-first",
|
|
5
|
+
"assets-worker-first-pattern-invalid",
|
|
6
|
+
"compatibility-date-missing",
|
|
7
|
+
"compatibility-date-invalid",
|
|
8
|
+
"durable-object-binding-inactive",
|
|
9
|
+
"durable-object-lifecycle-mixed",
|
|
10
|
+
"durable-object-lifecycle-unmanaged",
|
|
11
|
+
"generated-config-has-env",
|
|
12
|
+
"keep-vars-enabled",
|
|
13
|
+
"missing-nodejs-compat",
|
|
14
|
+
"nodejs-compat-version-implicit",
|
|
15
|
+
"observability-disabled",
|
|
16
|
+
"observability-sampling-implicit",
|
|
17
|
+
"observability-sampling-out-of-range",
|
|
18
|
+
"plaintext-secret-var",
|
|
19
|
+
"preview-urls-public",
|
|
20
|
+
"queue-dlq-missing",
|
|
21
|
+
"queue-retries-above-policy",
|
|
22
|
+
"queue-retries-out-of-range",
|
|
23
|
+
"queue-retry-delay-out-of-range",
|
|
24
|
+
"secret-declared-as-var",
|
|
25
|
+
"source-maps-disabled",
|
|
26
|
+
"stale-compatibility-date",
|
|
27
|
+
"traces-disabled",
|
|
28
|
+
"version-metadata-missing",
|
|
29
|
+
"workers-dev-enabled",
|
|
30
|
+
"workers-dev-implicit",
|
|
31
|
+
"workers-cache-cross-version-enabled",
|
|
32
|
+
"workers-cache-policy-implicit",
|
|
33
|
+
"wrangler-config-shadowed",
|
|
34
|
+
"wrangler-config-missing",
|
|
35
|
+
"wrangler-config-unreadable",
|
|
36
|
+
"wrangler-jsonc-preferred"
|
|
37
|
+
];
|
|
3
38
|
const SECRET_NAME_RE = /(?:^|_)(?:API_?KEY|AUTH_TOKEN|CLIENT_SECRET|CREDENTIALS?|DATABASE_URL|DB_URL|ENCRYPTION_KEY|KEY|PASSWORD|PRIVATE_KEY|SECRET|SIGNING_KEY|TOKEN)(?:_|$)/i;
|
|
4
39
|
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
5
40
|
const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1e3;
|
|
41
|
+
const NODEJS_COMPAT_V2_DATE = /* @__PURE__ */ new Date("2024-09-23T00:00:00.000Z");
|
|
6
42
|
function unique(values) {
|
|
7
43
|
return [...new Set(values)];
|
|
8
44
|
}
|
|
@@ -15,15 +51,87 @@ function parseDateOnly(value) {
|
|
|
15
51
|
const date = /* @__PURE__ */ new Date(`${value}T00:00:00.000Z`);
|
|
16
52
|
return Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value ? void 0 : date;
|
|
17
53
|
}
|
|
18
|
-
function
|
|
19
|
-
|
|
54
|
+
function parsedCompatibilityDateBeforeV2(value) {
|
|
55
|
+
const parsed = value && parseDateOnly(value);
|
|
56
|
+
return Boolean(parsed && parsed < NODEJS_COMPAT_V2_DATE);
|
|
57
|
+
}
|
|
58
|
+
function resolveWorkersCachePolicy(policy) {
|
|
59
|
+
if (policy._tag === "disabled")
|
|
60
|
+
return { enabled: false, cross_version_cache: false };
|
|
61
|
+
return { enabled: true, cross_version_cache: policy.crossVersion };
|
|
62
|
+
}
|
|
63
|
+
const WRANGLER_BINDING_CATEGORIES = [
|
|
64
|
+
"data_blobs",
|
|
65
|
+
"durable_objects",
|
|
66
|
+
"kv_namespaces",
|
|
67
|
+
"send_email",
|
|
68
|
+
"d1_databases",
|
|
69
|
+
"vectorize",
|
|
70
|
+
"ai_search_namespaces",
|
|
71
|
+
"ai_search",
|
|
72
|
+
"websearch",
|
|
73
|
+
"agent_memory",
|
|
74
|
+
"hyperdrive",
|
|
75
|
+
"r2_buckets",
|
|
76
|
+
"logfwdr",
|
|
77
|
+
"services",
|
|
78
|
+
"analytics_engine_datasets",
|
|
79
|
+
"text_blobs",
|
|
80
|
+
"browser",
|
|
81
|
+
"ai",
|
|
82
|
+
"images",
|
|
83
|
+
"stream",
|
|
84
|
+
"media",
|
|
85
|
+
"version_metadata",
|
|
86
|
+
"unsafe",
|
|
87
|
+
"vars",
|
|
88
|
+
"wasm_modules",
|
|
89
|
+
"dispatch_namespaces",
|
|
90
|
+
"mtls_certificates",
|
|
91
|
+
"workflows",
|
|
92
|
+
"pipelines",
|
|
93
|
+
"secrets_store_secrets",
|
|
94
|
+
"artifacts",
|
|
95
|
+
"ratelimits",
|
|
96
|
+
"assets",
|
|
97
|
+
"unsafe_hello_world",
|
|
98
|
+
"flagship"
|
|
99
|
+
];
|
|
100
|
+
function addBindingNames(names, value) {
|
|
101
|
+
if (Array.isArray(value)) {
|
|
102
|
+
value.forEach((entry) => {
|
|
103
|
+
if (isRecord(entry) && typeof entry.binding === "string")
|
|
104
|
+
names.add(entry.binding);
|
|
105
|
+
});
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (!isRecord(value))
|
|
109
|
+
return;
|
|
110
|
+
if (Array.isArray(value.bindings) && value.bindings.every((binding) => isRecord(binding) && typeof binding.name === "string")) {
|
|
111
|
+
value.bindings.forEach((binding) => names.add(binding.name));
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (typeof value.binding === "string") {
|
|
115
|
+
names.add(value.binding);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
Object.entries(value).forEach(([name, binding]) => {
|
|
119
|
+
if (binding !== void 0)
|
|
120
|
+
names.add(name);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
function collectBindingNames(config) {
|
|
124
|
+
const names = new Set(config.secrets?.required ?? []);
|
|
125
|
+
WRANGLER_BINDING_CATEGORIES.forEach((category) => addBindingNames(names, config[category]));
|
|
126
|
+
addBindingNames(names, config.queues?.producers);
|
|
127
|
+
return names;
|
|
20
128
|
}
|
|
21
129
|
function applyCloudflareDefaults(config, options = {}) {
|
|
22
130
|
const root = applyEnvironmentDefaults(config, options);
|
|
23
131
|
const environments = config.env && Object.fromEntries(
|
|
24
132
|
Object.entries(config.env).map(([name, environment]) => [name, applyEnvironmentDefaults(environment, {
|
|
25
133
|
...options,
|
|
26
|
-
requiredSecrets:
|
|
134
|
+
requiredSecrets: options.requiredSecrets
|
|
27
135
|
}, root)])
|
|
28
136
|
);
|
|
29
137
|
return environments ? { ...root, env: environments } : root;
|
|
@@ -31,14 +139,22 @@ function applyCloudflareDefaults(config, options = {}) {
|
|
|
31
139
|
function applyEnvironmentDefaults(config, options, inherited = {}) {
|
|
32
140
|
const compatibilityDate = config.compatibility_date ?? inherited.compatibility_date ?? options.compatibilityDate;
|
|
33
141
|
const compatibilityFlags = unique([...config.compatibility_flags ?? inherited.compatibility_flags ?? [], "nodejs_compat"]);
|
|
142
|
+
const cache = options.workersCache ? resolveWorkersCachePolicy(options.workersCache) : config.cache ?? inherited.cache ?? resolveWorkersCachePolicy({ _tag: "disabled" });
|
|
34
143
|
const requiredSecrets = unique([...config.secrets?.required ?? [], ...options.requiredSecrets ?? []]);
|
|
35
144
|
const logs = config.observability?.logs;
|
|
36
145
|
const inheritedLogs = inherited.observability?.logs;
|
|
37
146
|
const traces = config.observability?.traces;
|
|
38
147
|
const inheritedTraces = inherited.observability?.traces;
|
|
39
148
|
const uploadSourceMaps = config.upload_source_maps ?? inherited.upload_source_maps ?? options.uploadSourceMaps ?? true;
|
|
149
|
+
const previewUrls = config.preview_urls ?? inherited.preview_urls ?? false;
|
|
150
|
+
const placement = config.placement ?? inherited.placement ?? { mode: "smart" };
|
|
151
|
+
const workersDev = config.workers_dev ?? inherited.workers_dev ?? (config.route !== void 0 || (config.routes?.length ?? 0) > 0 ? false : void 0);
|
|
152
|
+
const versionMetadataBinding = options.versionMetadataBinding ?? "CF_VERSION_METADATA";
|
|
153
|
+
const localBindingNames = collectBindingNames(config);
|
|
154
|
+
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 });
|
|
40
155
|
return {
|
|
41
156
|
...config,
|
|
157
|
+
cache,
|
|
42
158
|
...compatibilityDate === void 0 ? {} : { compatibility_date: compatibilityDate },
|
|
43
159
|
compatibility_flags: compatibilityFlags,
|
|
44
160
|
observability: {
|
|
@@ -59,52 +175,173 @@ function applyEnvironmentDefaults(config, options, inherited = {}) {
|
|
|
59
175
|
head_sampling_rate: traces?.head_sampling_rate ?? inheritedTraces?.head_sampling_rate ?? options.tracesSampleRate ?? 0.01
|
|
60
176
|
}
|
|
61
177
|
},
|
|
178
|
+
placement,
|
|
62
179
|
...requiredSecrets.length > 0 ? { secrets: { ...config.secrets, required: requiredSecrets } } : {},
|
|
63
180
|
upload_source_maps: uploadSourceMaps,
|
|
64
|
-
version_metadata:
|
|
65
|
-
|
|
66
|
-
}
|
|
181
|
+
...versionMetadata ? { version_metadata: versionMetadata } : {},
|
|
182
|
+
preview_urls: previewUrls,
|
|
183
|
+
...workersDev === void 0 ? {} : { workers_dev: workersDev }
|
|
67
184
|
};
|
|
68
185
|
}
|
|
69
186
|
function diagnoseEnvironment(config, prefix, diagnostics, publicVarNames) {
|
|
70
|
-
|
|
187
|
+
const workerFirst = config.assets?.run_worker_first;
|
|
188
|
+
if (workerFirst === true) {
|
|
71
189
|
diagnostics.push({
|
|
72
190
|
_tag: "error",
|
|
73
191
|
code: "assets-worker-first",
|
|
74
|
-
message: "
|
|
75
|
-
|
|
192
|
+
message: "Replace blanket Worker-first routing with false or a narrow route-pattern array.",
|
|
193
|
+
configPath: `${prefix}assets.run_worker_first`
|
|
194
|
+
});
|
|
195
|
+
} else if (Array.isArray(workerFirst)) {
|
|
196
|
+
const invalidPatternIndex = workerFirst.findIndex(
|
|
197
|
+
(pattern) => typeof pattern !== "string" || !/^(?:!\/|\/)/.test(pattern)
|
|
198
|
+
);
|
|
199
|
+
if (invalidPatternIndex !== -1) {
|
|
200
|
+
diagnostics.push({
|
|
201
|
+
_tag: "error",
|
|
202
|
+
code: "assets-worker-first-pattern-invalid",
|
|
203
|
+
message: "Selective Worker-first patterns must begin with / or !/.",
|
|
204
|
+
configPath: `${prefix}assets.run_worker_first.${invalidPatternIndex}`
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
} else if (workerFirst !== void 0 && workerFirst !== false) {
|
|
208
|
+
diagnostics.push({
|
|
209
|
+
_tag: "error",
|
|
210
|
+
code: "assets-worker-first-pattern-invalid",
|
|
211
|
+
message: "assets.run_worker_first must be false or an array of route patterns.",
|
|
212
|
+
configPath: `${prefix}assets.run_worker_first`
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
const durableObjectExports = isRecord(config.exports) ? Object.entries(config.exports).filter(([, value]) => isRecord(value) && value.type === "durable-object") : [];
|
|
216
|
+
const migrations = Array.isArray(config.migrations) ? config.migrations : [];
|
|
217
|
+
if (durableObjectExports.length > 0 && migrations.length > 0) {
|
|
218
|
+
diagnostics.push({
|
|
219
|
+
_tag: "error",
|
|
220
|
+
code: "durable-object-lifecycle-mixed",
|
|
221
|
+
message: "Durable Object declarative exports and legacy migrations are mutually exclusive.",
|
|
222
|
+
configPath: `${prefix}exports`
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
const durableObjects = isRecord(config.durable_objects) ? config.durable_objects : void 0;
|
|
226
|
+
const bindings = Array.isArray(durableObjects?.bindings) ? durableObjects.bindings : [];
|
|
227
|
+
const localClassNames = bindings.flatMap((binding) => {
|
|
228
|
+
if (!isRecord(binding) || typeof binding.script_name === "string" || typeof binding.class_name !== "string")
|
|
229
|
+
return [];
|
|
230
|
+
return [binding.class_name];
|
|
231
|
+
});
|
|
232
|
+
const inactiveExportedClassNames = new Set(durableObjectExports.flatMap(([name, value]) => {
|
|
233
|
+
if (!isRecord(value) || value.state === void 0 || value.state === "created")
|
|
234
|
+
return [];
|
|
235
|
+
return [name];
|
|
236
|
+
}));
|
|
237
|
+
if (localClassNames.some((className) => inactiveExportedClassNames.has(className))) {
|
|
238
|
+
diagnostics.push({
|
|
239
|
+
_tag: "error",
|
|
240
|
+
code: "durable-object-binding-inactive",
|
|
241
|
+
message: "A Durable Object binding may target only an active declarative export with state created or omitted.",
|
|
242
|
+
configPath: `${prefix}durable_objects.bindings`
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
const exportedClassNames = new Set(durableObjectExports.map(([name]) => name));
|
|
246
|
+
const migratedClassNames = /* @__PURE__ */ new Set();
|
|
247
|
+
for (const migration of migrations) {
|
|
248
|
+
if (!isRecord(migration))
|
|
249
|
+
continue;
|
|
250
|
+
for (const key of ["new_classes", "new_sqlite_classes"]) {
|
|
251
|
+
if (Array.isArray(migration[key])) {
|
|
252
|
+
for (const className of migration[key]) {
|
|
253
|
+
if (typeof className === "string") {
|
|
254
|
+
migratedClassNames.add(className);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
if (Array.isArray(migration.renamed_classes)) {
|
|
260
|
+
for (const rename of migration.renamed_classes) {
|
|
261
|
+
if (!isRecord(rename))
|
|
262
|
+
continue;
|
|
263
|
+
if (typeof rename.from === "string")
|
|
264
|
+
migratedClassNames.delete(rename.from);
|
|
265
|
+
if (typeof rename.to === "string")
|
|
266
|
+
migratedClassNames.add(rename.to);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
if (Array.isArray(migration.transferred_classes)) {
|
|
270
|
+
for (const transfer of migration.transferred_classes) {
|
|
271
|
+
if (isRecord(transfer) && typeof transfer.to === "string")
|
|
272
|
+
migratedClassNames.add(transfer.to);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (Array.isArray(migration.deleted_classes)) {
|
|
276
|
+
for (const className of migration.deleted_classes) {
|
|
277
|
+
if (typeof className === "string") {
|
|
278
|
+
migratedClassNames.delete(className);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (localClassNames.some((className) => !exportedClassNames.has(className) && !migratedClassNames.has(className))) {
|
|
284
|
+
diagnostics.push({
|
|
285
|
+
_tag: "error",
|
|
286
|
+
code: "durable-object-lifecycle-unmanaged",
|
|
287
|
+
message: "Every locally defined Durable Object needs a declarative export or a legacy migration history.",
|
|
288
|
+
configPath: `${prefix}durable_objects.bindings`
|
|
76
289
|
});
|
|
77
290
|
}
|
|
78
291
|
const requiredSecrets = new Set(config.secrets?.required ?? []);
|
|
79
292
|
for (const name of Object.keys(config.vars ?? {})) {
|
|
80
|
-
const
|
|
293
|
+
const configPath = `${prefix}vars.${name}`;
|
|
81
294
|
if (requiredSecrets.has(name)) {
|
|
82
295
|
diagnostics.push({
|
|
83
296
|
_tag: "error",
|
|
84
297
|
code: "secret-declared-as-var",
|
|
85
298
|
message: `Remove ${name} from vars; it is declared as a required encrypted secret.`,
|
|
86
|
-
|
|
299
|
+
configPath
|
|
87
300
|
});
|
|
88
301
|
continue;
|
|
89
302
|
}
|
|
90
303
|
if (!publicVarNames.has(name) && !/^(?:NUXT_)?PUBLIC_/i.test(name) && SECRET_NAME_RE.test(name)) {
|
|
91
304
|
diagnostics.push({
|
|
92
|
-
_tag: "
|
|
305
|
+
_tag: "warning",
|
|
93
306
|
code: "plaintext-secret-var",
|
|
94
307
|
message: `Move secret-looking variable ${name} to an encrypted Worker secret.`,
|
|
95
|
-
|
|
308
|
+
configPath
|
|
96
309
|
});
|
|
97
310
|
}
|
|
98
311
|
}
|
|
99
312
|
const consumers = config.queues?.consumers ?? [];
|
|
100
313
|
consumers.forEach((consumer, index) => {
|
|
101
314
|
const retries = consumer.max_retries;
|
|
102
|
-
|
|
315
|
+
const retryDelay = consumer.retry_delay;
|
|
316
|
+
if (typeof retries === "number" && (!Number.isSafeInteger(retries) || retries < 0 || retries > 100)) {
|
|
317
|
+
diagnostics.push({
|
|
318
|
+
_tag: "error",
|
|
319
|
+
code: "queue-retries-out-of-range",
|
|
320
|
+
message: "Queue consumer max_retries must be an integer between 0 and 100.",
|
|
321
|
+
configPath: `${prefix}queues.consumers.${index}.max_retries`
|
|
322
|
+
});
|
|
323
|
+
} else if (typeof retries === "number" && retries > 3) {
|
|
103
324
|
diagnostics.push({
|
|
104
325
|
_tag: "warning",
|
|
105
|
-
code: "queue-retries-
|
|
106
|
-
message: `Queue consumer retries ${retries} times
|
|
107
|
-
|
|
326
|
+
code: "queue-retries-above-policy",
|
|
327
|
+
message: `Queue consumer retries ${retries} times, above Cloudflare's default of 3. Verify the work is replay-safe.`,
|
|
328
|
+
configPath: `${prefix}queues.consumers.${index}.max_retries`
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
if (typeof consumer.dead_letter_queue !== "string" || consumer.dead_letter_queue.length === 0) {
|
|
332
|
+
diagnostics.push({
|
|
333
|
+
_tag: "warning",
|
|
334
|
+
code: "queue-dlq-missing",
|
|
335
|
+
message: "Configure a dead-letter queue or explicitly allow this warning for intentionally lossy work.",
|
|
336
|
+
configPath: `${prefix}queues.consumers.${index}.dead_letter_queue`
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
if (typeof retryDelay === "number" && (!Number.isSafeInteger(retryDelay) || retryDelay < 0 || retryDelay > 86400)) {
|
|
340
|
+
diagnostics.push({
|
|
341
|
+
_tag: "error",
|
|
342
|
+
code: "queue-retry-delay-out-of-range",
|
|
343
|
+
message: "Queue consumer retry_delay must be between 0 and 86400 seconds.",
|
|
344
|
+
configPath: `${prefix}queues.consumers.${index}.retry_delay`
|
|
108
345
|
});
|
|
109
346
|
}
|
|
110
347
|
});
|
|
@@ -116,7 +353,7 @@ function diagnosePolicy(config, prefix, diagnostics, options, publicVarNames) {
|
|
|
116
353
|
_tag: "error",
|
|
117
354
|
code: "compatibility-date-missing",
|
|
118
355
|
message: "Set an explicit compatibility_date.",
|
|
119
|
-
|
|
356
|
+
configPath: `${prefix}compatibility_date`
|
|
120
357
|
});
|
|
121
358
|
} else {
|
|
122
359
|
const parsed = parseDateOnly(compatibilityDate);
|
|
@@ -125,23 +362,31 @@ function diagnosePolicy(config, prefix, diagnostics, options, publicVarNames) {
|
|
|
125
362
|
_tag: "error",
|
|
126
363
|
code: "compatibility-date-invalid",
|
|
127
364
|
message: "compatibility_date must be a real YYYY-MM-DD date.",
|
|
128
|
-
|
|
365
|
+
configPath: `${prefix}compatibility_date`
|
|
129
366
|
});
|
|
130
367
|
} else if ((options.now.getTime() - parsed.getTime()) / MILLISECONDS_PER_DAY > options.compatibilityMaxAgeDays) {
|
|
131
368
|
diagnostics.push({
|
|
132
369
|
_tag: "warning",
|
|
133
370
|
code: "stale-compatibility-date",
|
|
134
371
|
message: `compatibility_date is older than the ${options.compatibilityMaxAgeDays}-day project policy. Review compatibility flags before advancing it.`,
|
|
135
|
-
|
|
372
|
+
configPath: `${prefix}compatibility_date`
|
|
136
373
|
});
|
|
137
374
|
}
|
|
138
375
|
}
|
|
139
|
-
if (!config.compatibility_flags?.includes("nodejs_compat")) {
|
|
376
|
+
if (options.requireNodeCompat && !config.compatibility_flags?.includes("nodejs_compat")) {
|
|
140
377
|
diagnostics.push({
|
|
141
378
|
_tag: "error",
|
|
142
379
|
code: "missing-nodejs-compat",
|
|
143
380
|
message: "Add nodejs_compat to compatibility_flags.",
|
|
144
|
-
|
|
381
|
+
configPath: `${prefix}compatibility_flags`
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
if (options.requireNodeCompat && parsedCompatibilityDateBeforeV2(compatibilityDate) && config.compatibility_flags?.includes("nodejs_compat") && !config.compatibility_flags.includes("nodejs_compat_v2") && !config.compatibility_flags.includes("no_nodejs_compat_v2")) {
|
|
385
|
+
diagnostics.push({
|
|
386
|
+
_tag: "error",
|
|
387
|
+
code: "nodejs-compat-version-implicit",
|
|
388
|
+
message: "Before 2024-09-23, choose nodejs_compat_v2 or no_nodejs_compat_v2 explicitly.",
|
|
389
|
+
configPath: `${prefix}compatibility_flags`
|
|
145
390
|
});
|
|
146
391
|
}
|
|
147
392
|
if (config.observability?.enabled !== true) {
|
|
@@ -149,15 +394,49 @@ function diagnosePolicy(config, prefix, diagnostics, options, publicVarNames) {
|
|
|
149
394
|
_tag: "warning",
|
|
150
395
|
code: "observability-disabled",
|
|
151
396
|
message: "Enable Workers observability.",
|
|
152
|
-
|
|
397
|
+
configPath: `${prefix}observability.enabled`
|
|
153
398
|
});
|
|
399
|
+
} else {
|
|
400
|
+
const samplingRates = [
|
|
401
|
+
["head_sampling_rate", config.observability.head_sampling_rate],
|
|
402
|
+
["logs.head_sampling_rate", config.observability.logs?.head_sampling_rate],
|
|
403
|
+
["traces.head_sampling_rate", config.observability.traces?.head_sampling_rate]
|
|
404
|
+
];
|
|
405
|
+
for (const [path, rate] of samplingRates) {
|
|
406
|
+
if (rate !== void 0 && (!Number.isFinite(rate) || rate < 0 || rate > 1)) {
|
|
407
|
+
diagnostics.push({
|
|
408
|
+
_tag: "error",
|
|
409
|
+
code: "observability-sampling-out-of-range",
|
|
410
|
+
message: "Observability sampling rates must be finite numbers between 0 and 1.",
|
|
411
|
+
configPath: `${prefix}observability.${path}`
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
if (config.observability.traces?.enabled !== true) {
|
|
416
|
+
diagnostics.push({
|
|
417
|
+
_tag: "warning",
|
|
418
|
+
code: "traces-disabled",
|
|
419
|
+
message: "Enable Workers traces with an explicit sampling rate.",
|
|
420
|
+
configPath: `${prefix}observability.traces.enabled`
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
const logsEnabled = config.observability.logs?.enabled !== false;
|
|
424
|
+
const tracesEnabled = config.observability.traces?.enabled === true;
|
|
425
|
+
if (logsEnabled && config.observability.logs?.head_sampling_rate === void 0 || tracesEnabled && config.observability.traces?.head_sampling_rate === void 0) {
|
|
426
|
+
diagnostics.push({
|
|
427
|
+
_tag: "warning",
|
|
428
|
+
code: "observability-sampling-implicit",
|
|
429
|
+
message: "Set explicit log and trace sampling rates; enabled telemetry otherwise defaults to 100%.",
|
|
430
|
+
configPath: `${prefix}observability`
|
|
431
|
+
});
|
|
432
|
+
}
|
|
154
433
|
}
|
|
155
434
|
if (config.upload_source_maps !== true) {
|
|
156
435
|
diagnostics.push({
|
|
157
436
|
_tag: "warning",
|
|
158
437
|
code: "source-maps-disabled",
|
|
159
438
|
message: "Enable upload_source_maps when the Worker build emits source maps.",
|
|
160
|
-
|
|
439
|
+
configPath: `${prefix}upload_source_maps`
|
|
161
440
|
});
|
|
162
441
|
}
|
|
163
442
|
if (!config.version_metadata?.binding) {
|
|
@@ -165,15 +444,53 @@ function diagnosePolicy(config, prefix, diagnostics, options, publicVarNames) {
|
|
|
165
444
|
_tag: "warning",
|
|
166
445
|
code: "version-metadata-missing",
|
|
167
446
|
message: "Add a version_metadata binding for deployment correlation.",
|
|
168
|
-
|
|
447
|
+
configPath: `${prefix}version_metadata`
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
if (config.keep_vars === true) {
|
|
451
|
+
diagnostics.push({
|
|
452
|
+
_tag: "warning",
|
|
453
|
+
code: "keep-vars-enabled",
|
|
454
|
+
message: "keep_vars allows dashboard-managed plaintext variables to drift from source control.",
|
|
455
|
+
configPath: `${prefix}keep_vars`
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
if (config.cache === void 0) {
|
|
459
|
+
diagnostics.push({
|
|
460
|
+
_tag: "warning",
|
|
461
|
+
code: "workers-cache-policy-implicit",
|
|
462
|
+
message: "Choose an explicit Workers Caching policy. Headerless 200 responses are cached for two hours when enabled.",
|
|
463
|
+
configPath: `${prefix}cache`
|
|
464
|
+
});
|
|
465
|
+
} else if (config.cache.enabled && config.cache.cross_version_cache === true) {
|
|
466
|
+
diagnostics.push({
|
|
467
|
+
_tag: "warning",
|
|
468
|
+
code: "workers-cache-cross-version-enabled",
|
|
469
|
+
message: "Cross-version caching can serve responses from superseded deployments until expiry or purge.",
|
|
470
|
+
configPath: `${prefix}cache.cross_version_cache`
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
if (config.preview_urls === true) {
|
|
474
|
+
diagnostics.push({
|
|
475
|
+
_tag: "warning",
|
|
476
|
+
code: "preview-urls-public",
|
|
477
|
+
message: "Preview URLs are public unless protected by Access; their logs cannot be viewed through Workers Logs, tail, or Logpush.",
|
|
478
|
+
configPath: `${prefix}preview_urls`
|
|
169
479
|
});
|
|
170
480
|
}
|
|
171
481
|
if (config.workers_dev === true) {
|
|
172
482
|
diagnostics.push({
|
|
173
483
|
_tag: "warning",
|
|
174
484
|
code: "workers-dev-enabled",
|
|
175
|
-
message: "
|
|
176
|
-
|
|
485
|
+
message: "The public workers.dev endpoint is enabled. Set workers_dev to false unless this is intentional.",
|
|
486
|
+
configPath: `${prefix}workers_dev`
|
|
487
|
+
});
|
|
488
|
+
} else if (config.workers_dev === void 0) {
|
|
489
|
+
diagnostics.push({
|
|
490
|
+
_tag: "warning",
|
|
491
|
+
code: "workers-dev-implicit",
|
|
492
|
+
message: "Set workers_dev explicitly; current Wrangler behavior and published defaults differ when routes are present.",
|
|
493
|
+
configPath: `${prefix}workers_dev`
|
|
177
494
|
});
|
|
178
495
|
}
|
|
179
496
|
diagnoseEnvironment(config, prefix, diagnostics, publicVarNames);
|
|
@@ -191,9 +508,14 @@ function mergeObservability(inherited, environment) {
|
|
|
191
508
|
function resolveEnvironmentPolicy(root, environment) {
|
|
192
509
|
return {
|
|
193
510
|
...environment,
|
|
511
|
+
cache: environment.cache ?? root.cache,
|
|
194
512
|
compatibility_date: environment.compatibility_date ?? root.compatibility_date,
|
|
195
513
|
compatibility_flags: environment.compatibility_flags ?? root.compatibility_flags,
|
|
514
|
+
exports: environment.exports ?? root.exports,
|
|
515
|
+
migrations: environment.migrations ?? root.migrations,
|
|
196
516
|
observability: mergeObservability(root.observability, environment.observability),
|
|
517
|
+
placement: environment.placement ?? root.placement,
|
|
518
|
+
preview_urls: environment.preview_urls ?? root.preview_urls,
|
|
197
519
|
upload_source_maps: environment.upload_source_maps ?? root.upload_source_maps,
|
|
198
520
|
workers_dev: environment.workers_dev ?? root.workers_dev
|
|
199
521
|
};
|
|
@@ -202,8 +524,17 @@ function diagnoseWranglerConfig(config, options = {}) {
|
|
|
202
524
|
const diagnostics = [];
|
|
203
525
|
const diagnosticOptions = {
|
|
204
526
|
compatibilityMaxAgeDays: options.compatibilityMaxAgeDays ?? 90,
|
|
205
|
-
now: options.now ?? /* @__PURE__ */ new Date()
|
|
527
|
+
now: options.now ?? /* @__PURE__ */ new Date(),
|
|
528
|
+
requireNodeCompat: options.requireNodeCompat ?? true
|
|
206
529
|
};
|
|
530
|
+
if (options.generated && Object.keys(config.env ?? {}).length > 0) {
|
|
531
|
+
diagnostics.push({
|
|
532
|
+
_tag: "error",
|
|
533
|
+
code: "generated-config-has-env",
|
|
534
|
+
message: "Generated Wrangler config must target one flattened environment and contain no env block.",
|
|
535
|
+
configPath: "env"
|
|
536
|
+
});
|
|
537
|
+
}
|
|
207
538
|
const publicVarNames = new Set(options.publicVarNames ?? []);
|
|
208
539
|
diagnosePolicy(config, "", diagnostics, diagnosticOptions, publicVarNames);
|
|
209
540
|
for (const [name, environment] of Object.entries(config.env ?? {})) {
|
|
@@ -218,7 +549,11 @@ function diagnoseWranglerConfig(config, options = {}) {
|
|
|
218
549
|
return diagnostics;
|
|
219
550
|
}
|
|
220
551
|
function formatWranglerDiagnostics(diagnostics) {
|
|
221
|
-
return diagnostics.map((diagnostic) =>
|
|
552
|
+
return diagnostics.map((diagnostic) => {
|
|
553
|
+
const location = [diagnostic.sourcePath, diagnostic.configPath].filter(Boolean).join(":");
|
|
554
|
+
const severity = diagnostic._tag === "error" ? "ERROR" : diagnostic._tag === "warning" ? "WARN" : "INFO";
|
|
555
|
+
return `${severity} ${diagnostic.code}${location ? ` ${location}` : ""}: ${diagnostic.message}`;
|
|
556
|
+
}).join("\n");
|
|
222
557
|
}
|
|
223
558
|
async function readWranglerJsonFile(path) {
|
|
224
559
|
return readFile(path, "utf8").then((source) => {
|
|
@@ -241,4 +576,4 @@ async function readWranglerJsonFile(path) {
|
|
|
241
576
|
});
|
|
242
577
|
}
|
|
243
578
|
|
|
244
|
-
export { applyCloudflareDefaults, diagnoseWranglerConfig, formatWranglerDiagnostics, readWranglerJsonFile };
|
|
579
|
+
export { WRANGLER_DIAGNOSTIC_CODES, applyCloudflareDefaults, diagnoseWranglerConfig, formatWranglerDiagnostics, readWranglerJsonFile };
|