@harlan-zw/nuxt-cloudflare 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -184,14 +184,16 @@ D1 allows 100 bound parameters per statement, including each statement inside `d
184
184
  ### Bindings
185
185
 
186
186
  ```ts
187
- import type { CloudflareBindingSource } from '@harlan-zw/nuxt-cloudflare/bindings'
188
- import { createCloudflareBindings } from '@harlan-zw/nuxt-cloudflare/bindings'
187
+ import { createCloudflareBindings, resolveCloudflareBindings, runtimeConfigSource } from '@harlan-zw/nuxt-cloudflare/bindings'
189
188
 
190
189
  const cloudflare = createCloudflareBindings()
191
190
 
192
- function requireDatabase(source?: CloudflareBindingSource) {
191
+ function requireDatabase(source?: unknown) {
193
192
  return cloudflare.require('DB', source)
194
193
  }
194
+
195
+ const env = resolveCloudflareBindings(event)
196
+ const config = useRuntimeConfig(runtimeConfigSource(env ?? {}))
195
197
  ```
196
198
 
197
199
  `nuxt prepare` runs Wrangler and writes exact, compatibility-aware types to `.nuxt/types/cloudflare-bindings.d.ts`. It merges root JSON, JSONC, or TOML bindings with `nitro.cloudflare.wrangler`. Nuxt and Nitro typechecks both reference the declaration, while bindings remain server runtime values. Production builds compare it with the final generated Wrangler config and fail on drift. Set `bindingTypes: false` only when another tool owns the declaration.
@@ -212,13 +214,12 @@ if (resolved._tag === 'missing')
212
214
  throw new Error(`Missing Worker secrets: ${resolved.names.join(', ')}`)
213
215
 
214
216
  await withWorkerSecretsFile({
215
- path: '/secure/temp/secrets.json',
216
217
  secrets: resolved.secrets,
217
218
  use: path => exec('pnpm', ['wrangler', 'deploy', '--secrets-file', path]),
218
219
  })
219
220
  ```
220
221
 
221
- The writer uses exclusive creation and mode 0600. It removes partial files after write failures and removes the completed file after deployment succeeds or fails.
222
+ The helper owns a private temporary directory and creates the JSON file with mode 0600. It removes the directory after deployment succeeds or fails. Secret values may be strings or `null`; Wrangler treats `null` as a deletion marker.
222
223
 
223
224
  ## Deliberate boundaries
224
225
 
@@ -3,15 +3,26 @@ declare global {
3
3
  interface CloudflareBindings {
4
4
  }
5
5
  }
6
- interface CloudflareBindingSource {
7
- cloudflare?: unknown;
8
- context?: unknown;
6
+ interface CloudflareRuntimeConfigSource<Environment extends object> {
7
+ context: {
8
+ nitro: Record<string, never>;
9
+ cloudflare: {
10
+ env: Environment;
11
+ };
12
+ };
9
13
  }
10
14
  interface CloudflareBindingAccessor<Environment extends object> {
11
- resolve: (source?: CloudflareBindingSource) => Environment | undefined;
12
- get: <Name extends BindingName<Environment>>(name: Name, source?: CloudflareBindingSource) => Environment[Name] | undefined;
13
- require: <Name extends BindingName<Environment>>(name: Name, source?: CloudflareBindingSource) => Exclude<Environment[Name], undefined>;
15
+ resolve: (source?: unknown) => Environment | undefined;
16
+ get: <Name extends BindingName<Environment>>(name: Name, source?: unknown) => Environment[Name] | undefined;
17
+ require: <Name extends BindingName<Environment>>(name: Name, source?: unknown) => Exclude<Environment[Name], undefined>;
14
18
  }
19
+ declare function resolveCloudflareBindings<Environment extends object = CloudflareBindings>(source?: unknown): Environment | undefined;
20
+ /** Sets the environment used by eventless Cloudflare binding resolution. */
21
+ declare function setCloudflareBindings<Environment extends object>(env: Environment | undefined): void;
22
+ /** Merges binding sources into the eventless environment. Later sources win. */
23
+ declare function mergeCloudflareBindings<Environment extends object = CloudflareBindings>(...sources: Array<Partial<Environment> | undefined>): Environment;
24
+ /** Creates the event-shaped source required by Nitro runtime config resolution. */
25
+ declare function runtimeConfigSource<Environment extends object>(env: Environment): CloudflareRuntimeConfigSource<Environment>;
15
26
  /**
16
27
  * Creates typed binding access for the generated `CloudflareBindings` environment.
17
28
  *
@@ -20,5 +31,5 @@ interface CloudflareBindingAccessor<Environment extends object> {
20
31
  */
21
32
  declare function createCloudflareBindings<Environment extends object = CloudflareBindings>(): CloudflareBindingAccessor<Environment>;
22
33
 
23
- export { createCloudflareBindings };
24
- export type { CloudflareBindingAccessor, CloudflareBindingSource };
34
+ export { createCloudflareBindings, mergeCloudflareBindings, resolveCloudflareBindings, runtimeConfigSource, setCloudflareBindings };
35
+ export type { CloudflareBindingAccessor, CloudflareRuntimeConfigSource };
package/dist/bindings.mjs CHANGED
@@ -5,15 +5,35 @@ function envFromContext(value) {
5
5
  const cloudflare = asRecord(value)?.cloudflare;
6
6
  return asRecord(asRecord(cloudflare)?.env);
7
7
  }
8
- function resolveEnvironment(source) {
8
+ function resolveCloudflareBindings(source) {
9
9
  const sourceRecord = asRecord(source);
10
10
  const sourceEnv = envFromContext(sourceRecord?.context) ?? envFromContext(sourceRecord);
11
11
  const globalEnv = asRecord(globalThis.__env__);
12
12
  return sourceEnv ?? globalEnv;
13
13
  }
14
+ function setCloudflareBindings(env) {
15
+ const host = globalThis;
16
+ if (env === void 0)
17
+ delete host.__env__;
18
+ else
19
+ host.__env__ = env;
20
+ }
21
+ function mergeCloudflareBindings(...sources) {
22
+ const merged = Object.assign({}, ...sources.filter((source) => source !== void 0));
23
+ setCloudflareBindings(merged);
24
+ return merged;
25
+ }
26
+ function runtimeConfigSource(env) {
27
+ return {
28
+ context: {
29
+ nitro: {},
30
+ cloudflare: { env }
31
+ }
32
+ };
33
+ }
14
34
  function createCloudflareBindings() {
15
35
  function get(name, source) {
16
- const env = resolveEnvironment(source);
36
+ const env = resolveCloudflareBindings(source);
17
37
  return env && Object.hasOwn(env, name) ? env[name] : void 0;
18
38
  }
19
39
  function requireBinding(name, source) {
@@ -23,10 +43,10 @@ function createCloudflareBindings() {
23
43
  return binding;
24
44
  }
25
45
  return {
26
- resolve: resolveEnvironment,
46
+ resolve: resolveCloudflareBindings,
27
47
  get,
28
48
  require: requireBinding
29
49
  };
30
50
  }
31
51
 
32
- export { createCloudflareBindings };
52
+ export { createCloudflareBindings, mergeCloudflareBindings, resolveCloudflareBindings, runtimeConfigSource, setCloudflareBindings };
@@ -1,10 +1,10 @@
1
- import { readFile, mkdir, writeFile } from 'node:fs/promises';
2
- import { parseTOML, parseJSONC, parseJSON } from 'confbox';
3
- import { extname, resolve } from 'pathe';
1
+ import { mkdir, writeFile } from 'node:fs/promises';
2
+ import { resolve } from 'pathe';
4
3
  import { experimental_generateTypes } from 'wrangler';
5
4
  import { d as discoverWranglerSourceConfigs } from '../shared/nuxt-cloudflare.6X-qzF_b.mjs';
5
+ import { readWranglerConfigFile } from '../wrangler.mjs';
6
6
  import 'node:fs';
7
- import '../wrangler.mjs';
7
+ import 'confbox';
8
8
 
9
9
  const COMPUTED_WRANGLER_KEYS = /* @__PURE__ */ new Set([
10
10
  "configPath",
@@ -74,13 +74,12 @@ async function readAuthoredConfig(rootDir) {
74
74
  const [path] = discoverWranglerSourceConfigs(rootDir);
75
75
  if (!path)
76
76
  return {};
77
- const source = await readFile(path, "utf8");
78
- const extension = extname(path);
79
- if (extension === ".toml")
80
- return parseTOML(source);
81
- if (extension === ".jsonc")
82
- return parseJSONC(source);
83
- return parseJSON(source);
77
+ const loaded = readWranglerConfigFile(path);
78
+ if (loaded._tag === "loaded")
79
+ return loaded.config;
80
+ if (loaded._tag === "missing")
81
+ return {};
82
+ throw new SyntaxError(`Invalid Wrangler config "${path}": ${loaded.reason}`);
84
83
  }
85
84
  async function generateCloudflareBindingTypes(options) {
86
85
  const directory = resolve(options.buildDir, "nuxt-cloudflare");
@@ -1,6 +1,9 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { resolve, dirname } from 'pathe';
3
3
  import { unstable_readConfig } from 'wrangler';
4
+ import { findProjectWranglerConfig } from '../wrangler.mjs';
5
+ import 'node:fs/promises';
6
+ import 'confbox';
4
7
 
5
8
  function errorMessage(error) {
6
9
  return error instanceof Error ? error.message : String(error);
@@ -24,26 +27,12 @@ function findUpFile(cwd, relativePath) {
24
27
  directory = parent;
25
28
  }
26
29
  }
27
- function findUpWranglerConfig(cwd) {
28
- let directory = resolve(cwd);
29
- while (true) {
30
- for (const name of ["wrangler.json", "wrangler.jsonc", "wrangler.toml"]) {
31
- const candidate = resolve(directory, name);
32
- if (existsSync(candidate))
33
- return candidate;
34
- }
35
- const parent = dirname(directory);
36
- if (parent === directory)
37
- return void 0;
38
- directory = parent;
39
- }
40
- }
41
30
  function resolveNitroDeployConfig(cwd) {
42
31
  const redirectPath = findUpFile(cwd, ".wrangler/deploy/config.json");
43
32
  if (!redirectPath)
44
33
  return void 0;
45
34
  const redirectProjectDirectory = dirname(dirname(dirname(redirectPath)));
46
- const authoredConfigPath = findUpWranglerConfig(cwd);
35
+ const authoredConfigPath = findProjectWranglerConfig(cwd);
47
36
  if (authoredConfigPath && dirname(authoredConfigPath) !== redirectProjectDirectory)
48
37
  return void 0;
49
38
  const parsed = JSON.parse(readFileSync(redirectPath, "utf8"));
@@ -7,6 +7,7 @@ import { diagnoseWranglerConfig, formatWranglerDiagnostics } from '../wrangler.m
7
7
  import { readProjectWranglerConfig } from '../chunks/wrangler-reader.mjs';
8
8
  import 'node:fs';
9
9
  import 'node:fs/promises';
10
+ import 'confbox';
10
11
  import 'wrangler';
11
12
 
12
13
  function diagnoseWranglerProject(options) {
@@ -103,7 +104,7 @@ const doctor = defineCommand({
103
104
  const main = defineCommand({
104
105
  meta: {
105
106
  name: "nuxt-cloudflare",
106
- version: "0.0.9",
107
+ version: "0.0.12",
107
108
  description: "Cloudflare deployment defaults and diagnostics for Nuxt"
108
109
  },
109
110
  subCommands: { doctor }
package/dist/deploy.d.mts CHANGED
@@ -6,8 +6,7 @@ type WorkerSecretsResolution = {
6
6
  secrets: Record<string, string>;
7
7
  };
8
8
  interface WorkerSecretsFileOptions<T> {
9
- path: string;
10
- secrets: Readonly<Record<string, string>>;
9
+ secrets: Readonly<Record<string, string | null>>;
11
10
  use: (path: string) => Promise<T> | T;
12
11
  }
13
12
  declare function resolveWorkerSecrets(requiredNames: readonly string[], environment: Readonly<Record<string, string | undefined>>): WorkerSecretsResolution;
package/dist/deploy.mjs CHANGED
@@ -1,4 +1,6 @@
1
- import { open, unlink } from 'node:fs/promises';
1
+ import { mkdtemp, rm, open } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
2
4
 
3
5
  function resolveWorkerSecrets(requiredNames, environment) {
4
6
  const names = [...new Set(requiredNames)];
@@ -16,37 +18,33 @@ function settle(promise) {
16
18
  (error) => ({ _tag: "error", error })
17
19
  );
18
20
  }
19
- function isMissingFileError(error) {
20
- return error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT";
21
- }
22
21
  function throwFailures(errors, message) {
23
22
  if (errors.length === 1)
24
23
  throw errors[0];
25
24
  throw new AggregateError(errors, message);
26
25
  }
27
- async function removeWorkerSecretsFile(path) {
28
- const outcome = await settle(unlink(path));
29
- if (outcome._tag === "error" && !isMissingFileError(outcome.error))
30
- throw outcome.error;
31
- }
32
- async function writeWorkerSecretsFile(path, secrets) {
33
- const payload = `${JSON.stringify(secrets)}
34
- `;
26
+ async function writeWorkerSecretsFile(path, payload) {
35
27
  const handle = await open(path, "wx", 384);
36
28
  const writeOutcome = await settle(handle.writeFile(payload, "utf8"));
37
29
  const closeOutcome = await settle(handle.close());
38
30
  const failures = [writeOutcome, closeOutcome].filter((outcome) => outcome._tag === "error").map((outcome) => outcome.error);
39
31
  if (failures.length === 0)
40
32
  return;
41
- const cleanupOutcome = await settle(removeWorkerSecretsFile(path));
42
- if (cleanupOutcome._tag === "error")
43
- failures.push(cleanupOutcome.error);
44
33
  throwFailures(failures, "Failed to write and clean up the Worker secrets file");
45
34
  }
46
35
  async function withWorkerSecretsFile(options) {
47
- await writeWorkerSecretsFile(options.path, options.secrets);
48
- const useOutcome = await settle(Promise.resolve().then(() => options.use(options.path)));
49
- const cleanupOutcome = await settle(removeWorkerSecretsFile(options.path));
36
+ const payload = `${JSON.stringify(options.secrets)}
37
+ `;
38
+ const directory = await mkdtemp(join(tmpdir(), "nuxt-cloudflare-secrets-"));
39
+ const path = join(directory, "secrets.json");
40
+ const writeOutcome = await settle(writeWorkerSecretsFile(path, payload));
41
+ if (writeOutcome._tag === "error") {
42
+ const cleanupOutcome2 = await settle(rm(directory, { force: true, recursive: true }));
43
+ const failures2 = cleanupOutcome2._tag === "error" ? [writeOutcome.error, cleanupOutcome2.error] : [writeOutcome.error];
44
+ throwFailures(failures2, "Failed to write and clean up the Worker secrets file");
45
+ }
46
+ const useOutcome = await settle(Promise.resolve().then(() => options.use(path)));
47
+ const cleanupOutcome = await settle(rm(directory, { force: true, recursive: true }));
50
48
  const failures = [useOutcome, cleanupOutcome].filter((outcome) => outcome._tag === "error").map((outcome) => outcome.error);
51
49
  if (failures.length > 0)
52
50
  throwFailures(failures, "Worker deployment and secrets file cleanup failed");
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=4.5.0"
6
6
  },
7
- "version": "0.0.10",
7
+ "version": "0.0.12",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -5,6 +5,7 @@ import { a as diagnoseWranglerSourceConfigs, d as discoverWranglerSourceConfigs,
5
5
  import { readWranglerJsonFile, diagnoseWranglerConfig, formatWranglerDiagnostics, applyCloudflareDefaults } from './wrangler.mjs';
6
6
  import 'node:fs';
7
7
  import 'node:fs/promises';
8
+ import 'confbox';
8
9
 
9
10
  const NON_HTML_ROUTE_PREFIXES = [
10
11
  "/.well-known",
@@ -1,3 +1,18 @@
1
+ type WranglerConfigFileResult = {
2
+ _tag: 'loaded';
3
+ config: WranglerConfigInput;
4
+ path: string;
5
+ } | {
6
+ _tag: 'missing';
7
+ path: string;
8
+ } | {
9
+ _tag: 'invalid';
10
+ path: string;
11
+ reason: string;
12
+ };
13
+ declare function readWranglerConfigFile(path: string): WranglerConfigFileResult;
14
+ declare function findProjectWranglerConfig(cwd: string): string | undefined;
15
+
1
16
  interface WranglerAssetsInput {
2
17
  directory?: string;
3
18
  binding?: string;
@@ -135,5 +150,5 @@ declare function diagnoseWranglerConfig(config: WranglerConfigInput, options?: W
135
150
  declare function formatWranglerDiagnostics(diagnostics: readonly WranglerDiagnostic[]): string;
136
151
  declare function readWranglerJsonFile(path: string): Promise<WranglerJsonFileResult>;
137
152
 
138
- export { WRANGLER_DIAGNOSTIC_CODES, applyCloudflareDefaults, diagnoseWranglerConfig, formatWranglerDiagnostics, readWranglerJsonFile };
139
- export type { CloudflareDefaultOptions, WorkersCachePolicy, WranglerAssetsInput, WranglerConfigInput, WranglerContainerInput, WranglerDiagnostic, WranglerDiagnosticCode, WranglerDiagnosticOptions, WranglerJsonFileResult, WranglerObservabilityInput, WranglerPlacementInput, WranglerRemoteBindingInput, WranglerWorkersCacheInput };
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 };
package/dist/wrangler.mjs CHANGED
@@ -1,4 +1,53 @@
1
1
  import { readFile } from 'node:fs/promises';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { parseTOML, parseJSONC, parseJSON } from 'confbox';
4
+ import { resolve, dirname, extname } from 'pathe';
5
+
6
+ function errorMessage(error) {
7
+ return error instanceof Error ? error.message : String(error);
8
+ }
9
+ function parseWranglerConfigSource(path, source) {
10
+ const extension = extname(path);
11
+ if (extension === ".toml")
12
+ return parseTOML(source);
13
+ if (extension === ".jsonc") {
14
+ const errors = [];
15
+ const config = parseJSONC(source, { errors });
16
+ if (errors.length > 0) {
17
+ const { error, offset } = errors[0];
18
+ throw new SyntaxError(`JSONC parse error ${error} at offset ${offset}`);
19
+ }
20
+ return config;
21
+ }
22
+ return parseJSON(source);
23
+ }
24
+ function readWranglerConfigFile(path) {
25
+ if (!existsSync(path))
26
+ return { _tag: "missing", path };
27
+ try {
28
+ return {
29
+ _tag: "loaded",
30
+ config: parseWranglerConfigSource(path, readFileSync(path, "utf8")),
31
+ path
32
+ };
33
+ } catch (error) {
34
+ return { _tag: "invalid", path, reason: errorMessage(error) };
35
+ }
36
+ }
37
+ function findProjectWranglerConfig(cwd) {
38
+ let directory = resolve(cwd);
39
+ while (true) {
40
+ for (const name of ["wrangler.json", "wrangler.jsonc", "wrangler.toml"]) {
41
+ const candidate = resolve(directory, name);
42
+ if (existsSync(candidate))
43
+ return candidate;
44
+ }
45
+ const parent = dirname(directory);
46
+ if (parent === directory)
47
+ return void 0;
48
+ directory = parent;
49
+ }
50
+ }
2
51
 
3
52
  const WRANGLER_DIAGNOSTIC_CODES = [
4
53
  "assets-worker-first",
@@ -849,4 +898,4 @@ async function readWranglerJsonFile(path) {
849
898
  });
850
899
  }
851
900
 
852
- export { WRANGLER_DIAGNOSTIC_CODES, applyCloudflareDefaults, diagnoseWranglerConfig, formatWranglerDiagnostics, readWranglerJsonFile };
901
+ export { WRANGLER_DIAGNOSTIC_CODES, applyCloudflareDefaults, diagnoseWranglerConfig, findProjectWranglerConfig, formatWranglerDiagnostics, readWranglerConfigFile, readWranglerJsonFile };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@harlan-zw/nuxt-cloudflare",
3
3
  "type": "module",
4
- "version": "0.0.10",
4
+ "version": "0.0.12",
5
5
  "description": "Opinionated Cloudflare deployment defaults and diagnostics for Nuxt.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",