@harlan-zw/nuxt-cloudflare 0.0.6 → 0.0.8

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/dist/module.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { useLogger, defineNuxtModule } from '@nuxt/kit';
1
+ import process from 'node:process';
2
+ import { useLogger, defineNuxtModule, addTypeTemplate } from '@nuxt/kit';
2
3
  import { resolve } from 'pathe';
3
4
  import { a as diagnoseWranglerSourceConfigs, d as discoverWranglerSourceConfigs, e as evaluateWranglerDiagnostics } from './shared/nuxt-cloudflare.6X-qzF_b.mjs';
4
5
  import { readWranglerJsonFile, diagnoseWranglerConfig, formatWranglerDiagnostics, applyCloudflareDefaults } from './wrangler.mjs';
@@ -6,15 +7,18 @@ import 'node:fs';
6
7
  import 'node:fs/promises';
7
8
 
8
9
  const NON_HTML_ROUTE_PREFIXES = [
10
+ "/.well-known",
9
11
  "/api",
10
12
  "/_ipx",
11
13
  "/_nuxt",
12
14
  "/_og",
13
15
  "/assets",
14
16
  "/fonts",
15
- "/images"
17
+ "/images",
18
+ "/mcp"
16
19
  ];
17
20
  const NON_HTML_EXTENSION_RE = /\.(?:avif|css|csv|gif|ico|jpe?g|js|json|map|md|mjs|pdf|png|svg|txt|webmanifest|webp|woff2?|xml)(?:$|[?*])/i;
21
+ const HTML_CONTENT_TYPE_RE = /^(?:application\/xhtml\+xml|text\/html)(?:\s*;|$)/i;
18
22
  const CACHE_HEADER_NAMES = /* @__PURE__ */ new Set([
19
23
  "cache-control",
20
24
  "cdn-cache-control",
@@ -25,19 +29,29 @@ const PRIVATE_CACHE_DIRECTIVE_RE = /(?:^|,)\s*(?:no-store|private)\s*(?:,|$)/i;
25
29
  function isRecord(value) {
26
30
  return value !== null && typeof value === "object" && !Array.isArray(value);
27
31
  }
28
- function isHtmlCapableRoute(route) {
29
- if (NON_HTML_EXTENSION_RE.test(route))
30
- return false;
31
- return !NON_HTML_ROUTE_PREFIXES.some((prefix) => route === prefix || route.startsWith(`${prefix}/`));
32
+ function findHeader(headers, name) {
33
+ const entry = Object.entries(headers).find(([header]) => header.toLowerCase() === name);
34
+ return entry?.[1];
32
35
  }
33
- function isPrivateCachePolicy(value) {
34
- return typeof value === "string" && PRIVATE_CACHE_DIRECTIVE_RE.test(value);
36
+ function hasExplicitNonHtmlContentType(value) {
37
+ if (!isRecord(value.headers))
38
+ return false;
39
+ const contentType = findHeader(value.headers, "content-type");
40
+ return typeof contentType === "string" && !HTML_CONTENT_TYPE_RE.test(contentType);
35
41
  }
36
42
  function hasHtmlContentType(headers) {
37
43
  if (!headers)
38
44
  return false;
39
- const contentType = Object.entries(headers).find(([name]) => name.toLowerCase() === "content-type")?.[1];
40
- return typeof contentType === "string" && /^text\/html(?:;|$)/i.test(contentType);
45
+ const contentType = findHeader(headers, "content-type");
46
+ return typeof contentType === "string" && HTML_CONTENT_TYPE_RE.test(contentType);
47
+ }
48
+ function isHtmlCapableRoute(route, value) {
49
+ if (NON_HTML_EXTENSION_RE.test(route) || hasExplicitNonHtmlContentType(value))
50
+ return false;
51
+ return !NON_HTML_ROUTE_PREFIXES.some((prefix) => route === prefix || route.startsWith(`${prefix}/`));
52
+ }
53
+ function isPrivateCachePolicy(value) {
54
+ return typeof value === "string" && PRIVATE_CACHE_DIRECTIVE_RE.test(value);
41
55
  }
42
56
  function resolveViolationSeverity(route, value) {
43
57
  const definitelyHtml = value.prerender === true || /\.html(?:$|[?*])/i.test(route) || hasHtmlContentType(isRecord(value.headers) ? value.headers : void 0);
@@ -47,7 +61,7 @@ function findHtmlCacheRouteRuleViolations(routeRules) {
47
61
  if (!routeRules)
48
62
  return [];
49
63
  return Object.entries(routeRules).flatMap(([route, value]) => {
50
- if (!isHtmlCapableRoute(route) || !isRecord(value))
64
+ if (!isRecord(value) || !isHtmlCapableRoute(route, value))
51
65
  return [];
52
66
  const severity = resolveViolationSeverity(route, value);
53
67
  const violations = [];
@@ -89,9 +103,34 @@ const workersCachePluginPath = resolve(
89
103
  import.meta.dirname,
90
104
  import.meta.url.endsWith(".ts") ? "runtime/server/plugins/workers-cache.ts" : "runtime/server/plugins/workers-cache.js"
91
105
  );
106
+ const BUILD_SECRET_ENV_RE = /(?:^|_)(?:API_?KEY|AUTH_TOKEN|CLIENT_SECRET|CREDENTIALS?|ENCRYPTION_KEY|PASSWORD|PRIVATE_KEY|SECRET|SIGNING_KEY|TOKEN|SALT)(?:_|$)/i;
107
+ const REQUIRED_BUILD_SECRET_NAMES = /* @__PURE__ */ new Set(["NUXT_SCRIPTS_PROXY_SECRET"]);
92
108
  function resolveModuleWorkersCachePolicy(options) {
93
109
  return options.workersCache ?? { _tag: "enabled", crossVersion: false };
94
110
  }
111
+ function findPopulatedRuntimeSecretPaths(config, environment) {
112
+ const paths = [];
113
+ const buildSecretValues = new Set(Object.entries(environment).flatMap(([name, value]) => {
114
+ return BUILD_SECRET_ENV_RE.test(name) && !REQUIRED_BUILD_SECRET_NAMES.has(name) && value && value.length >= 8 ? [value] : [];
115
+ }));
116
+ const visit = (value, parents) => {
117
+ if (!value || typeof value !== "object" || Array.isArray(value))
118
+ return;
119
+ for (const [key, child] of Object.entries(value)) {
120
+ const path = [...parents, key];
121
+ if (path[0] === "public")
122
+ continue;
123
+ if (child && typeof child === "object" && !Array.isArray(child)) {
124
+ visit(child, path);
125
+ continue;
126
+ }
127
+ if (typeof child === "string" && buildSecretValues.has(child))
128
+ paths.push(path.join("."));
129
+ }
130
+ };
131
+ visit(config, []);
132
+ return paths;
133
+ }
95
134
  function configureNitroCloudflare(nitro, options, nuxtServerSourceMaps) {
96
135
  nitro.preset ??= "cloudflare-module";
97
136
  nitro.cloudflare ??= {};
@@ -125,13 +164,27 @@ function configureNitroCloudflare(nitro, options, nuxtServerSourceMaps) {
125
164
  defaultTtl: configuredCache?.defaultTtl ?? 30 * 24 * 60 * 60
126
165
  };
127
166
  }
128
- async function auditGeneratedWranglerConfig(nitro, options, rootDir) {
167
+ async function auditGeneratedWranglerConfig(nitro, options, buildDir, rootDir, bindingTypeSignature) {
129
168
  const path = resolve(nitro.options.output.serverDir, "wrangler.json");
130
169
  const result = await readWranglerJsonFile(path);
131
170
  if (result._tag === "missing")
132
171
  throw new Error(`[nuxt-cloudflare] Generated Wrangler config is missing: ${path}`);
133
172
  if (result._tag === "invalid")
134
173
  throw new Error(`[nuxt-cloudflare] Generated Wrangler config is invalid: ${result.reason}`);
174
+ const { readProjectWranglerConfig } = await import('./chunks/wrangler-reader.mjs');
175
+ const validated = readProjectWranglerConfig({ config: path, cwd: rootDir });
176
+ if (validated._tag === "invalid")
177
+ throw new Error("[nuxt-cloudflare] Generated Wrangler config fails Wrangler schema validation. Run Wrangler locally for validation details.");
178
+ if (bindingTypeSignature) {
179
+ const { assertCloudflareBindingTypesCurrent } = await import('./chunks/binding-types.mjs');
180
+ await assertCloudflareBindingTypesCurrent({
181
+ buildDir,
182
+ compatibilityDate: result.config.compatibility_date,
183
+ config: result.config,
184
+ expectedSignature: bindingTypeSignature,
185
+ nodeCompat: Boolean(nitro.options.cloudflare?.nodeCompat)
186
+ });
187
+ }
135
188
  const diagnostics = [
136
189
  ...diagnoseWranglerConfig(result.config, {
137
190
  compatibilityMaxAgeDays: options.compatibilityMaxAgeDays,
@@ -161,9 +214,34 @@ function setupCloudflareModule(options, nuxt) {
161
214
  options,
162
215
  Boolean(nuxt.options.sourcemap.server)
163
216
  );
217
+ let bindingTypeSignature;
218
+ if (options.bindingTypes !== false) {
219
+ addTypeTemplate({
220
+ filename: "types/cloudflare-bindings.d.ts",
221
+ getContents: async () => {
222
+ const { prepareCloudflareBindingTypes } = await import('./chunks/binding-types.mjs');
223
+ const compatibilityDate = nuxt.options.compatibilityDate;
224
+ const artifact = await prepareCloudflareBindingTypes({
225
+ buildDir: nuxt.options.buildDir,
226
+ compatibilityDate: typeof compatibilityDate === "string" ? compatibilityDate || void 0 : compatibilityDate.cloudflare ?? compatibilityDate.default,
227
+ nodeCompat: Boolean(nuxt.options.nitro.cloudflare?.nodeCompat),
228
+ rootDir: nuxt.options.rootDir,
229
+ wrangler: nuxt.options.nitro.cloudflare?.wrangler ?? {}
230
+ });
231
+ bindingTypeSignature = artifact.signature;
232
+ return artifact.content;
233
+ }
234
+ }, { nitro: true });
235
+ }
164
236
  configure();
165
237
  nuxt.hook("modules:done", () => {
166
238
  configure();
239
+ if (nuxt.options.dev)
240
+ return;
241
+ const populatedRuntimeSecrets = findPopulatedRuntimeSecretPaths(nuxt.options.runtimeConfig, process.env);
242
+ if (populatedRuntimeSecrets.length > 0) {
243
+ throw new Error(`[nuxt-cloudflare] Runtime config contains secret build environment values: ${populatedRuntimeSecrets.join(", ")}. Keep defaults empty and use Worker secret bindings.`);
244
+ }
167
245
  });
168
246
  nuxt.hook("nitro:config", (nitroConfig) => {
169
247
  if (resolveModuleWorkersCachePolicy(options)._tag === "disabled")
@@ -182,7 +260,13 @@ ${formatHtmlCacheRouteRuleViolations(errors)}`
182
260
  });
183
261
  if (!nuxt.options.dev) {
184
262
  nuxt.hook("nitro:init", (nitro) => {
185
- nitro.hooks.hook("compiled", () => auditGeneratedWranglerConfig(nitro, options, nuxt.options.rootDir));
263
+ nitro.hooks.hook("compiled", () => auditGeneratedWranglerConfig(
264
+ nitro,
265
+ options,
266
+ nuxt.options.buildDir,
267
+ nuxt.options.rootDir,
268
+ bindingTypeSignature
269
+ ));
186
270
  });
187
271
  }
188
272
  }
@@ -193,10 +277,11 @@ const module$1 = defineNuxtModule({
193
277
  compatibility: { nuxt: ">=4.5.0" }
194
278
  },
195
279
  defaults: {
280
+ bindingTypes: true,
196
281
  enabled: true,
197
282
  compatibilityMaxAgeDays: 90,
198
283
  doctor: { _tag: "advisory" },
199
- logsSampleRate: 0.1,
284
+ logsSampleRate: 0.01,
200
285
  tracesSampleRate: 0.01,
201
286
  versionMetadataBinding: "CF_VERSION_METADATA",
202
287
  workersCache: { _tag: "enabled", crossVersion: false }
@@ -204,4 +289,4 @@ const module$1 = defineNuxtModule({
204
289
  setup: setupCloudflareModule
205
290
  });
206
291
 
207
- export { configureNitroCloudflare, module$1 as default, setupCloudflareModule };
292
+ export { configureNitroCloudflare, module$1 as default, findPopulatedRuntimeSecretPaths, setupCloudflareModule };
package/dist/storage.mjs CHANGED
@@ -17,7 +17,7 @@ function withDefaultKvExpiration(driver, defaultTtl) {
17
17
  flags: { ...driver.flags, ttl: true },
18
18
  setItem(key, value, transactionOptions = {}) {
19
19
  const requestedTtl = Number(transactionOptions.ttl);
20
- const ttl = Number.isFinite(requestedTtl) && requestedTtl > 0 ? requestedTtl : parsedDefaultTtl;
20
+ const ttl = Number.isFinite(requestedTtl) && requestedTtl > 0 ? Math.max(requestedTtl, 60) : parsedDefaultTtl;
21
21
  return setItem(key, value, { ...transactionOptions, ttl });
22
22
  }
23
23
  };
package/dist/types.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- export { type configureNitroCloudflare, default, type setupCloudflareModule } from './module.mjs'
1
+ export { type configureNitroCloudflare, default, type findPopulatedRuntimeSecretPaths, type setupCloudflareModule } from './module.mjs'
2
2
 
3
3
  export { type ModuleOptions, type NitroCloudflareShape } from './module.mjs'
@@ -28,6 +28,15 @@ type WranglerPlacementInput = {
28
28
  hostname?: never;
29
29
  mode?: never;
30
30
  };
31
+ interface WranglerRemoteBindingInput extends Record<string, unknown> {
32
+ binding?: string;
33
+ remote?: boolean;
34
+ }
35
+ interface WranglerContainerInput extends Record<string, unknown> {
36
+ class_name?: string;
37
+ image?: string;
38
+ instance_type?: string | Record<string, unknown>;
39
+ }
31
40
  type WorkersCachePolicy = {
32
41
  _tag: 'disabled';
33
42
  } | {
@@ -48,12 +57,21 @@ interface WranglerObservabilityInput {
48
57
  };
49
58
  }
50
59
  interface WranglerConfigInput extends Record<string, unknown> {
60
+ ai?: WranglerRemoteBindingInput;
51
61
  assets?: WranglerAssetsInput;
62
+ browser?: WranglerRemoteBindingInput;
52
63
  cache?: WranglerWorkersCacheInput;
53
64
  compatibility_date?: string;
54
65
  compatibility_flags?: string[];
66
+ containers?: WranglerContainerInput[];
55
67
  env?: Record<string, WranglerConfigInput>;
68
+ images?: WranglerRemoteBindingInput;
56
69
  keep_vars?: boolean;
70
+ limits?: {
71
+ cpu_ms?: number;
72
+ subrequests?: number;
73
+ };
74
+ mtls_certificates?: WranglerRemoteBindingInput[];
57
75
  observability?: WranglerObservabilityInput;
58
76
  placement?: WranglerPlacementInput;
59
77
  preview_urls?: boolean;
@@ -66,6 +84,7 @@ interface WranglerConfigInput extends Record<string, unknown> {
66
84
  secrets?: {
67
85
  required?: string[];
68
86
  };
87
+ vectorize?: WranglerRemoteBindingInput[];
69
88
  upload_source_maps?: boolean;
70
89
  vars?: Record<string, unknown>;
71
90
  version_metadata?: {
@@ -82,7 +101,7 @@ interface CloudflareDefaultOptions {
82
101
  versionMetadataBinding?: string;
83
102
  workersCache?: WorkersCachePolicy;
84
103
  }
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"];
104
+ declare const WRANGLER_DIAGNOSTIC_CODES: readonly ["assets-worker-first", "assets-worker-first-pattern-invalid", "compatibility-date-missing", "compatibility-date-invalid", "container-durable-object-binding-missing", "container-durable-object-not-sqlite", "container-instance-type-deprecated", "cpu-limit-raised", "durable-object-binding-inactive", "durable-object-lifecycle-mixed", "durable-object-lifecycle-unmanaged", "email-binding-unrestricted", "environment-binding-missing", "generated-config-has-env", "keep-vars-enabled", "legacy-module-binding", "missing-nodejs-compat", "nodejs-compat-version-implicit", "observability-disabled", "observability-log-sampling-high", "observability-sampling-implicit", "observability-sampling-out-of-range", "observability-trace-sampling-high", "plaintext-secret-var", "preview-urls-public", "pipeline-binding-deprecated", "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", "remote-binding-not-enabled", "unsafe-hello-world-binding", "version-metadata-missing", "workers-dev-enabled", "workers-dev-implicit", "workers-cache-cross-version-enabled", "workers-cache-assets-billable", "workers-cache-policy-implicit", "wrangler-config-shadowed", "wrangler-config-missing", "wrangler-config-unreadable", "wrangler-jsonc-preferred"];
86
105
  type WranglerDiagnosticCode = typeof WRANGLER_DIAGNOSTIC_CODES[number];
87
106
  interface WranglerDiagnostic {
88
107
  _tag: 'error' | 'info' | 'warning';
@@ -95,6 +114,7 @@ interface WranglerDiagnosticOptions {
95
114
  compatibilityMaxAgeDays?: number;
96
115
  generated?: boolean;
97
116
  now?: Date;
117
+ normalized?: boolean;
98
118
  publicVarNames?: readonly string[];
99
119
  requireNodeCompat?: boolean;
100
120
  }
@@ -116,4 +136,4 @@ declare function formatWranglerDiagnostics(diagnostics: readonly WranglerDiagnos
116
136
  declare function readWranglerJsonFile(path: string): Promise<WranglerJsonFileResult>;
117
137
 
118
138
  export { WRANGLER_DIAGNOSTIC_CODES, applyCloudflareDefaults, diagnoseWranglerConfig, formatWranglerDiagnostics, readWranglerJsonFile };
119
- export type { CloudflareDefaultOptions, WorkersCachePolicy, WranglerAssetsInput, WranglerConfigInput, WranglerDiagnostic, WranglerDiagnosticCode, WranglerDiagnosticOptions, WranglerJsonFileResult, WranglerObservabilityInput, WranglerPlacementInput, WranglerWorkersCacheInput };
139
+ export type { CloudflareDefaultOptions, WorkersCachePolicy, WranglerAssetsInput, WranglerConfigInput, WranglerContainerInput, WranglerDiagnostic, WranglerDiagnosticCode, WranglerDiagnosticOptions, WranglerJsonFileResult, WranglerObservabilityInput, WranglerPlacementInput, WranglerRemoteBindingInput, WranglerWorkersCacheInput };