@harlan-zw/nuxt-cloudflare 0.0.9 → 0.0.11
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 +20 -8
- package/dist/bindings.d.mts +15 -8
- package/dist/bindings.mjs +12 -4
- package/dist/chunks/binding-types.mjs +24 -1
- package/dist/cli/index.mjs +1 -1
- package/dist/d1.d.mts +46 -2
- package/dist/d1.mjs +250 -12
- package/dist/deploy.d.mts +1 -2
- package/dist/deploy.mjs +16 -18
- package/dist/module.json +1 -1
- package/dist/module.mjs +5 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -135,9 +135,16 @@ Pass the final generated config explicitly to `types` and `check startup`; Nitro
|
|
|
135
135
|
### D1 sessions and safe retries
|
|
136
136
|
|
|
137
137
|
```ts
|
|
138
|
-
import {
|
|
138
|
+
import {
|
|
139
|
+
getRecoveringRequestD1Session,
|
|
140
|
+
retryIdempotentD1Write,
|
|
141
|
+
} from '@harlan-zw/nuxt-cloudflare/d1'
|
|
139
142
|
|
|
140
|
-
const session =
|
|
143
|
+
const session = getRecoveringRequestD1Session(
|
|
144
|
+
event.context,
|
|
145
|
+
'DB',
|
|
146
|
+
event.context.cloudflare.env.DB,
|
|
147
|
+
)
|
|
141
148
|
|
|
142
149
|
await retryIdempotentD1Write({
|
|
143
150
|
safety: { _tag: 'replay-safe' },
|
|
@@ -145,7 +152,11 @@ await retryIdempotentD1Write({
|
|
|
145
152
|
})
|
|
146
153
|
```
|
|
147
154
|
|
|
148
|
-
|
|
155
|
+
`getRecoveringRequestD1Session` caches one `first-primary` session per request and binding. Use `withD1ResetRecovery` when no request context exists. D1 already retries read-only queries. Recovery handles failures that outlive those retries. It opens a replacement session after `D1_RESET_DO`, carries the last bookmark, and rebuilds the prepared statement with its bound values. Replica disconnects and connection loss retry on the current session.
|
|
156
|
+
|
|
157
|
+
Recovery replays only `SELECT`, read-only CTE, and `EXPLAIN` statements. It never replays writes, PRAGMA statements, mixed batches, or unknown statements. A session reset still opens a healthy session for the next statement. `onRecovery` receives tagged `retrying` or `stopped` events for request telemetry.
|
|
158
|
+
|
|
159
|
+
Write retries require an explicit safety tag. `lock-only` retries SQLite lock contention; `replay-safe` also permits classified network and storage reset failures. Resource pressure, queue delay, CPU, and memory errors are never retried.
|
|
149
160
|
|
|
150
161
|
### D1 parameter plans
|
|
151
162
|
|
|
@@ -173,14 +184,16 @@ D1 allows 100 bound parameters per statement, including each statement inside `d
|
|
|
173
184
|
### Bindings
|
|
174
185
|
|
|
175
186
|
```ts
|
|
176
|
-
import
|
|
177
|
-
import { createCloudflareBindings } from '@harlan-zw/nuxt-cloudflare/bindings'
|
|
187
|
+
import { createCloudflareBindings, resolveCloudflareBindings, runtimeConfigSource } from '@harlan-zw/nuxt-cloudflare/bindings'
|
|
178
188
|
|
|
179
189
|
const cloudflare = createCloudflareBindings()
|
|
180
190
|
|
|
181
|
-
function requireDatabase(source?:
|
|
191
|
+
function requireDatabase(source?: unknown) {
|
|
182
192
|
return cloudflare.require('DB', source)
|
|
183
193
|
}
|
|
194
|
+
|
|
195
|
+
const env = resolveCloudflareBindings(event)
|
|
196
|
+
const config = useRuntimeConfig(runtimeConfigSource(env ?? {}))
|
|
184
197
|
```
|
|
185
198
|
|
|
186
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.
|
|
@@ -201,13 +214,12 @@ if (resolved._tag === 'missing')
|
|
|
201
214
|
throw new Error(`Missing Worker secrets: ${resolved.names.join(', ')}`)
|
|
202
215
|
|
|
203
216
|
await withWorkerSecretsFile({
|
|
204
|
-
path: '/secure/temp/secrets.json',
|
|
205
217
|
secrets: resolved.secrets,
|
|
206
218
|
use: path => exec('pnpm', ['wrangler', 'deploy', '--secrets-file', path]),
|
|
207
219
|
})
|
|
208
220
|
```
|
|
209
221
|
|
|
210
|
-
The
|
|
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.
|
|
211
223
|
|
|
212
224
|
## Deliberate boundaries
|
|
213
225
|
|
package/dist/bindings.d.mts
CHANGED
|
@@ -3,15 +3,22 @@ declare global {
|
|
|
3
3
|
interface CloudflareBindings {
|
|
4
4
|
}
|
|
5
5
|
}
|
|
6
|
-
interface
|
|
7
|
-
|
|
8
|
-
|
|
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?:
|
|
12
|
-
get: <Name extends BindingName<Environment>>(name: Name, source?:
|
|
13
|
-
require: <Name extends BindingName<Environment>>(name: Name, source?:
|
|
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
|
+
/** Creates the event-shaped source required by Nitro runtime config resolution. */
|
|
21
|
+
declare function runtimeConfigSource<Environment extends object>(env: Environment): CloudflareRuntimeConfigSource<Environment>;
|
|
15
22
|
/**
|
|
16
23
|
* Creates typed binding access for the generated `CloudflareBindings` environment.
|
|
17
24
|
*
|
|
@@ -20,5 +27,5 @@ interface CloudflareBindingAccessor<Environment extends object> {
|
|
|
20
27
|
*/
|
|
21
28
|
declare function createCloudflareBindings<Environment extends object = CloudflareBindings>(): CloudflareBindingAccessor<Environment>;
|
|
22
29
|
|
|
23
|
-
export { createCloudflareBindings };
|
|
24
|
-
export type { CloudflareBindingAccessor,
|
|
30
|
+
export { createCloudflareBindings, resolveCloudflareBindings, runtimeConfigSource };
|
|
31
|
+
export type { CloudflareBindingAccessor, CloudflareRuntimeConfigSource };
|
package/dist/bindings.mjs
CHANGED
|
@@ -5,15 +5,23 @@ function envFromContext(value) {
|
|
|
5
5
|
const cloudflare = asRecord(value)?.cloudflare;
|
|
6
6
|
return asRecord(asRecord(cloudflare)?.env);
|
|
7
7
|
}
|
|
8
|
-
function
|
|
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 runtimeConfigSource(env) {
|
|
15
|
+
return {
|
|
16
|
+
context: {
|
|
17
|
+
nitro: {},
|
|
18
|
+
cloudflare: { env }
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
}
|
|
14
22
|
function createCloudflareBindings() {
|
|
15
23
|
function get(name, source) {
|
|
16
|
-
const env =
|
|
24
|
+
const env = resolveCloudflareBindings(source);
|
|
17
25
|
return env && Object.hasOwn(env, name) ? env[name] : void 0;
|
|
18
26
|
}
|
|
19
27
|
function requireBinding(name, source) {
|
|
@@ -23,10 +31,10 @@ function createCloudflareBindings() {
|
|
|
23
31
|
return binding;
|
|
24
32
|
}
|
|
25
33
|
return {
|
|
26
|
-
resolve:
|
|
34
|
+
resolve: resolveCloudflareBindings,
|
|
27
35
|
get,
|
|
28
36
|
require: requireBinding
|
|
29
37
|
};
|
|
30
38
|
}
|
|
31
39
|
|
|
32
|
-
export { createCloudflareBindings };
|
|
40
|
+
export { createCloudflareBindings, resolveCloudflareBindings, runtimeConfigSource };
|
|
@@ -47,6 +47,29 @@ function normalizeConfig(config, options) {
|
|
|
47
47
|
}
|
|
48
48
|
return normalized;
|
|
49
49
|
}
|
|
50
|
+
function compareText(left, right) {
|
|
51
|
+
if (left < right)
|
|
52
|
+
return -1;
|
|
53
|
+
if (left > right)
|
|
54
|
+
return 1;
|
|
55
|
+
return 0;
|
|
56
|
+
}
|
|
57
|
+
function canonicalizeBindingEnvironment(environment) {
|
|
58
|
+
return environment.replaceAll("\r\n", "\n").replace(
|
|
59
|
+
/(interface __BaseEnv_CloudflareBindings \{\n)([\s\S]*?)(\n\})/,
|
|
60
|
+
(_, opening, members, closing) => [
|
|
61
|
+
opening,
|
|
62
|
+
members.split("\n").sort((left, right) => compareText(left.trim(), right.trim())).join("\n"),
|
|
63
|
+
closing
|
|
64
|
+
].join("")
|
|
65
|
+
).replace(
|
|
66
|
+
/Pick<Cloudflare\.Env,([^>]+)>/g,
|
|
67
|
+
(_, members) => `Pick<Cloudflare.Env, ${members.split("|").map((member) => member.trim()).sort(compareText).join(" | ")}>`
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
function createBindingTypeSignature(environment, runtime) {
|
|
71
|
+
return `${canonicalizeBindingEnvironment(environment)}\0${runtime.replaceAll("\r\n", "\n")}`;
|
|
72
|
+
}
|
|
50
73
|
async function readAuthoredConfig(rootDir) {
|
|
51
74
|
const [path] = discoverWranglerSourceConfigs(rootDir);
|
|
52
75
|
if (!path)
|
|
@@ -77,7 +100,7 @@ async function generateCloudflareBindingTypes(options) {
|
|
|
77
100
|
throw new Error("[nuxt-cloudflare] Wrangler did not generate Cloudflare binding and runtime types.");
|
|
78
101
|
return {
|
|
79
102
|
content: generated.content,
|
|
80
|
-
signature:
|
|
103
|
+
signature: createBindingTypeSignature(generated.env, generated.runtime)
|
|
81
104
|
};
|
|
82
105
|
}
|
|
83
106
|
async function prepareCloudflareBindingTypes(options) {
|
package/dist/cli/index.mjs
CHANGED
|
@@ -103,7 +103,7 @@ const doctor = defineCommand({
|
|
|
103
103
|
const main = defineCommand({
|
|
104
104
|
meta: {
|
|
105
105
|
name: "nuxt-cloudflare",
|
|
106
|
-
version: "0.0.
|
|
106
|
+
version: "0.0.11",
|
|
107
107
|
description: "Cloudflare deployment defaults and diagnostics for Nuxt"
|
|
108
108
|
},
|
|
109
109
|
subCommands: { doctor }
|
package/dist/d1.d.mts
CHANGED
|
@@ -26,6 +26,18 @@ type D1Consistency = {
|
|
|
26
26
|
interface D1SessionSource<Session> {
|
|
27
27
|
withSession: (constraint: string) => Session;
|
|
28
28
|
}
|
|
29
|
+
interface D1StatementLike {
|
|
30
|
+
bind: (...values: never[]) => D1StatementLike;
|
|
31
|
+
first: (...args: never[]) => unknown;
|
|
32
|
+
run: (...args: never[]) => unknown;
|
|
33
|
+
all: (...args: never[]) => unknown;
|
|
34
|
+
raw: (...args: never[]) => unknown;
|
|
35
|
+
}
|
|
36
|
+
interface D1SessionLike {
|
|
37
|
+
prepare: (sql: string) => D1StatementLike;
|
|
38
|
+
batch: (statements: never[]) => unknown;
|
|
39
|
+
getBookmark: () => string | null;
|
|
40
|
+
}
|
|
29
41
|
interface RetryIdempotentD1WriteOptions<T> {
|
|
30
42
|
maxAttempts?: number;
|
|
31
43
|
random?: () => number;
|
|
@@ -34,19 +46,51 @@ interface RetryIdempotentD1WriteOptions<T> {
|
|
|
34
46
|
sleep?: (milliseconds: number) => Promise<void>;
|
|
35
47
|
}
|
|
36
48
|
type D1RetryErrorKind = {
|
|
49
|
+
_tag: 'session-reset';
|
|
50
|
+
} | {
|
|
37
51
|
_tag: 'lock';
|
|
38
52
|
} | {
|
|
39
53
|
_tag: 'transient';
|
|
40
54
|
} | {
|
|
41
55
|
_tag: 'permanent';
|
|
42
56
|
};
|
|
57
|
+
type D1RecoveryEvent = {
|
|
58
|
+
_tag: 'retrying';
|
|
59
|
+
attempt: number;
|
|
60
|
+
failure: {
|
|
61
|
+
_tag: 'session-reset';
|
|
62
|
+
} | {
|
|
63
|
+
_tag: 'transient';
|
|
64
|
+
};
|
|
65
|
+
sql: string;
|
|
66
|
+
} | {
|
|
67
|
+
_tag: 'stopped';
|
|
68
|
+
attempt: number;
|
|
69
|
+
failure: {
|
|
70
|
+
_tag: 'session-reset';
|
|
71
|
+
} | {
|
|
72
|
+
_tag: 'transient';
|
|
73
|
+
};
|
|
74
|
+
reason: 'attempts-exhausted' | 'unsafe-statement';
|
|
75
|
+
sql: string;
|
|
76
|
+
};
|
|
77
|
+
interface D1ResetRecoveryOptions {
|
|
78
|
+
consistency?: D1Consistency;
|
|
79
|
+
maxAttempts?: number;
|
|
80
|
+
onRecovery?: (event: D1RecoveryEvent) => void;
|
|
81
|
+
random?: () => number;
|
|
82
|
+
sleep?: (milliseconds: number) => Promise<void>;
|
|
83
|
+
}
|
|
43
84
|
declare function defineD1ParameterPlan(input: D1ParameterPlanInput): D1ParameterPlan;
|
|
44
85
|
declare function chunkD1Items<T>(items: readonly T[], plan: D1ParameterPlan): T[][];
|
|
45
86
|
declare function assertD1BoundParameters(parameters: readonly unknown[]): void;
|
|
46
87
|
declare function classifyD1RetryError(error: unknown): D1RetryErrorKind;
|
|
47
88
|
declare function isTransientD1Error(error: unknown): boolean;
|
|
89
|
+
declare function isReplayableD1Sql(sql: string): boolean;
|
|
90
|
+
declare function withD1ResetRecovery<Session extends D1SessionLike>(database: D1SessionSource<Session>, options?: D1ResetRecoveryOptions): Session;
|
|
48
91
|
declare function getRequestD1Session<Session>(requestContext: Record<PropertyKey, unknown>, binding: string, database: D1SessionSource<Session>, consistency?: D1Consistency): Session;
|
|
92
|
+
declare function getRecoveringRequestD1Session<Session extends D1SessionLike>(requestContext: Record<PropertyKey, unknown>, binding: string, database: D1SessionSource<Session>, options?: D1ResetRecoveryOptions): Session;
|
|
49
93
|
declare function retryIdempotentD1Write<T>(options: RetryIdempotentD1WriteOptions<T>): Promise<T>;
|
|
50
94
|
|
|
51
|
-
export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRequestD1Session, isTransientD1Error, retryIdempotentD1Write };
|
|
52
|
-
export type { D1Consistency, D1ParameterPlan, D1ParameterPlanInput, D1RetryErrorKind, D1SessionSource, D1WriteSafety, RetryIdempotentD1WriteOptions };
|
|
95
|
+
export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRecoveringRequestD1Session, getRequestD1Session, isReplayableD1Sql, isTransientD1Error, retryIdempotentD1Write, withD1ResetRecovery };
|
|
96
|
+
export type { D1Consistency, D1ParameterPlan, D1ParameterPlanInput, D1RecoveryEvent, D1ResetRecoveryOptions, D1RetryErrorKind, D1SessionLike, D1SessionSource, D1StatementLike, D1WriteSafety, RetryIdempotentD1WriteOptions };
|
package/dist/d1.mjs
CHANGED
|
@@ -1,14 +1,22 @@
|
|
|
1
1
|
const D1_MAX_BOUND_PARAMETERS = 100;
|
|
2
2
|
const D1_PARAMETER_PLAN = Symbol("@harlan-zw/nuxt-cloudflare:d1-parameter-plan");
|
|
3
3
|
const REQUEST_D1_SESSIONS = Symbol.for("@harlan-zw/nuxt-cloudflare:d1-sessions");
|
|
4
|
-
const
|
|
5
|
-
|
|
4
|
+
const REQUEST_D1_RECOVERING_SESSIONS = Symbol.for("@harlan-zw/nuxt-cloudflare:d1-recovering-sessions");
|
|
5
|
+
const SESSION_RESET_D1_SIGNALS = [
|
|
6
|
+
"D1_RESET_DO",
|
|
6
7
|
"D1 DB reset because its code was updated",
|
|
7
8
|
"Internal error while starting up D1 DB storage caused object to be reset",
|
|
8
9
|
"Internal error in D1 DB storage caused object to be reset",
|
|
9
|
-
"storage caused object to be reset"
|
|
10
|
-
|
|
10
|
+
"storage caused object to be reset"
|
|
11
|
+
];
|
|
12
|
+
const TRANSIENT_D1_SIGNALS = [
|
|
13
|
+
"Network connection lost",
|
|
14
|
+
"cannot resolve d1 db due to transient issue on remote node",
|
|
15
|
+
"Replica disconnected from primary"
|
|
11
16
|
];
|
|
17
|
+
const D1_STATEMENT_RESOLVER = Symbol("@harlan-zw/nuxt-cloudflare:d1-statement-resolver");
|
|
18
|
+
const D1_STATEMENT_SQL = Symbol("@harlan-zw/nuxt-cloudflare:d1-statement-sql");
|
|
19
|
+
const D1_TERMINAL_METHODS = /* @__PURE__ */ new Set(["first", "run", "all", "raw"]);
|
|
12
20
|
function consistencyConstraint(consistency) {
|
|
13
21
|
if (consistency._tag === "bookmark")
|
|
14
22
|
return consistency.bookmark;
|
|
@@ -32,6 +40,14 @@ function parseParameterCount(name, value, minimum) {
|
|
|
32
40
|
throw new TypeError(`D1 ${name} must be an integer greater than or equal to ${minimum}`);
|
|
33
41
|
return value;
|
|
34
42
|
}
|
|
43
|
+
function getD1SessionCache(requestContext, cacheKey) {
|
|
44
|
+
const existing = requestContext[cacheKey];
|
|
45
|
+
if (existing !== void 0 && !(existing instanceof Map))
|
|
46
|
+
throw new TypeError("Request D1 session cache has an invalid value");
|
|
47
|
+
const sessions = existing ?? /* @__PURE__ */ new Map();
|
|
48
|
+
requestContext[cacheKey] = sessions;
|
|
49
|
+
return sessions;
|
|
50
|
+
}
|
|
35
51
|
function defineD1ParameterPlan(input) {
|
|
36
52
|
const parametersPerItem = parseParameterCount("parametersPerItem", input.parametersPerItem, 1);
|
|
37
53
|
const reservedParameters = parseParameterCount(
|
|
@@ -86,6 +102,12 @@ function classifyD1RetryError(error) {
|
|
|
86
102
|
messages.push(current.message);
|
|
87
103
|
current = "cause" in current ? current.cause : void 0;
|
|
88
104
|
}
|
|
105
|
+
if (messages.some((message) => {
|
|
106
|
+
const normalized = message.toLowerCase();
|
|
107
|
+
return SESSION_RESET_D1_SIGNALS.some((signal) => normalized.includes(signal.toLowerCase()));
|
|
108
|
+
})) {
|
|
109
|
+
return { _tag: "session-reset" };
|
|
110
|
+
}
|
|
89
111
|
if (messages.some((message) => /busy|locked/i.test(message)))
|
|
90
112
|
return { _tag: "lock" };
|
|
91
113
|
if (messages.some((message) => {
|
|
@@ -97,20 +119,236 @@ function classifyD1RetryError(error) {
|
|
|
97
119
|
return { _tag: "permanent" };
|
|
98
120
|
}
|
|
99
121
|
function isTransientD1Error(error) {
|
|
100
|
-
|
|
122
|
+
const kind = classifyD1RetryError(error);
|
|
123
|
+
return kind._tag === "session-reset" || kind._tag === "transient";
|
|
124
|
+
}
|
|
125
|
+
function tokenizeD1Sql(sql) {
|
|
126
|
+
const tokens = [];
|
|
127
|
+
let index = 0;
|
|
128
|
+
while (index < sql.length) {
|
|
129
|
+
const char = sql[index];
|
|
130
|
+
const next = sql[index + 1];
|
|
131
|
+
if (char === "-" && next === "-") {
|
|
132
|
+
index += 2;
|
|
133
|
+
while (index < sql.length && sql[index] !== "\n")
|
|
134
|
+
index++;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (char === "/" && next === "*") {
|
|
138
|
+
const end = sql.indexOf("*/", index + 2);
|
|
139
|
+
if (end === -1)
|
|
140
|
+
return [];
|
|
141
|
+
index = end + 2;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (char === "'" || char === '"' || char === "`") {
|
|
145
|
+
const quote = char;
|
|
146
|
+
index++;
|
|
147
|
+
while (index < sql.length) {
|
|
148
|
+
if (sql[index] !== quote) {
|
|
149
|
+
index++;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (sql[index + 1] === quote) {
|
|
153
|
+
index += 2;
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
index++;
|
|
157
|
+
break;
|
|
158
|
+
}
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (char === "[") {
|
|
162
|
+
const end = sql.indexOf("]", index + 1);
|
|
163
|
+
if (end === -1)
|
|
164
|
+
return [];
|
|
165
|
+
index = end + 1;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (char === "(" || char === ")") {
|
|
169
|
+
tokens.push(char);
|
|
170
|
+
index++;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (/[A-Z_]/i.test(char)) {
|
|
174
|
+
let end = index + 1;
|
|
175
|
+
while (end < sql.length && /[\w$]/.test(sql[end]))
|
|
176
|
+
end++;
|
|
177
|
+
tokens.push(sql.slice(index, end).toLowerCase());
|
|
178
|
+
index = end;
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
index++;
|
|
182
|
+
}
|
|
183
|
+
return tokens;
|
|
184
|
+
}
|
|
185
|
+
function d1StatementKeyword(sql) {
|
|
186
|
+
const tokens = tokenizeD1Sql(sql);
|
|
187
|
+
const first = tokens[0];
|
|
188
|
+
if (first !== "with")
|
|
189
|
+
return first;
|
|
190
|
+
let depth = 0;
|
|
191
|
+
for (const token of tokens.slice(1)) {
|
|
192
|
+
if (token === "(") {
|
|
193
|
+
depth++;
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
if (token === ")") {
|
|
197
|
+
depth = Math.max(0, depth - 1);
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (depth === 0 && ["select", "insert", "update", "delete", "replace"].includes(token))
|
|
201
|
+
return token;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
function isReplayableD1Sql(sql) {
|
|
205
|
+
const keyword = d1StatementKeyword(sql);
|
|
206
|
+
return keyword === "select" || keyword === "explain";
|
|
207
|
+
}
|
|
208
|
+
function resolveD1Statement(statement) {
|
|
209
|
+
const resolver = statement[D1_STATEMENT_RESOLVER];
|
|
210
|
+
return typeof resolver === "function" ? resolver : () => statement;
|
|
211
|
+
}
|
|
212
|
+
function getD1StatementSql(statement) {
|
|
213
|
+
const sql = statement[D1_STATEMENT_SQL];
|
|
214
|
+
return typeof sql === "string" ? sql : void 0;
|
|
215
|
+
}
|
|
216
|
+
function withD1ResetRecovery(database, options = {}) {
|
|
217
|
+
const maxAttempts = parseMaxAttempts(options.maxAttempts ?? 3);
|
|
218
|
+
const initialConstraint = consistencyConstraint(options.consistency ?? { _tag: "first-primary" });
|
|
219
|
+
const random = options.random ?? Math.random;
|
|
220
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
221
|
+
let activeSession;
|
|
222
|
+
function currentSession() {
|
|
223
|
+
activeSession ??= database.withSession(initialConstraint);
|
|
224
|
+
return activeSession;
|
|
225
|
+
}
|
|
226
|
+
function renewSession() {
|
|
227
|
+
const bookmark = currentSession().getBookmark();
|
|
228
|
+
activeSession = database.withSession(bookmark ?? initialConstraint);
|
|
229
|
+
return activeSession;
|
|
230
|
+
}
|
|
231
|
+
async function runRecoverable(replayable, sql, run) {
|
|
232
|
+
for (let attempt = 0; ; attempt++) {
|
|
233
|
+
const outcome = await Promise.resolve().then(() => run(currentSession())).then(
|
|
234
|
+
(value) => ({ _tag: "ok", value }),
|
|
235
|
+
(error) => ({ _tag: "error", error })
|
|
236
|
+
);
|
|
237
|
+
if (outcome._tag === "ok")
|
|
238
|
+
return outcome.value;
|
|
239
|
+
const failure = classifyD1RetryError(outcome.error);
|
|
240
|
+
if (failure._tag !== "session-reset" && failure._tag !== "transient")
|
|
241
|
+
throw outcome.error;
|
|
242
|
+
const exhausted = attempt + 1 >= maxAttempts;
|
|
243
|
+
if (failure._tag === "session-reset")
|
|
244
|
+
renewSession();
|
|
245
|
+
if (!replayable || exhausted) {
|
|
246
|
+
options.onRecovery?.({
|
|
247
|
+
_tag: "stopped",
|
|
248
|
+
attempt,
|
|
249
|
+
failure,
|
|
250
|
+
reason: exhausted ? "attempts-exhausted" : "unsafe-statement",
|
|
251
|
+
sql
|
|
252
|
+
});
|
|
253
|
+
throw outcome.error;
|
|
254
|
+
}
|
|
255
|
+
options.onRecovery?.({ _tag: "retrying", attempt, failure, sql });
|
|
256
|
+
await sleep(retryDelay(attempt, random));
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
function wrapStatement(sql, parameters, owner, nativeStatement) {
|
|
260
|
+
const resolver = (session) => {
|
|
261
|
+
if (session === owner)
|
|
262
|
+
return nativeStatement;
|
|
263
|
+
const prepared = session.prepare(sql);
|
|
264
|
+
if (parameters === void 0)
|
|
265
|
+
return prepared;
|
|
266
|
+
const bind = prepared.bind;
|
|
267
|
+
return bind.apply(prepared, parameters);
|
|
268
|
+
};
|
|
269
|
+
return new Proxy(nativeStatement, {
|
|
270
|
+
get(target, property) {
|
|
271
|
+
if (property === D1_STATEMENT_RESOLVER)
|
|
272
|
+
return resolver;
|
|
273
|
+
if (property === D1_STATEMENT_SQL)
|
|
274
|
+
return sql;
|
|
275
|
+
const value = Reflect.get(target, property, target);
|
|
276
|
+
if (typeof value !== "function")
|
|
277
|
+
return value;
|
|
278
|
+
if (property === "bind") {
|
|
279
|
+
return (...values) => wrapStatement(
|
|
280
|
+
sql,
|
|
281
|
+
values,
|
|
282
|
+
owner,
|
|
283
|
+
value.apply(target, values)
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
if (typeof property === "string" && D1_TERMINAL_METHODS.has(property)) {
|
|
287
|
+
return (...args) => runRecoverable(
|
|
288
|
+
isReplayableD1Sql(sql),
|
|
289
|
+
sql,
|
|
290
|
+
(session) => {
|
|
291
|
+
const statement = resolver(session);
|
|
292
|
+
const method = Reflect.get(statement, property, statement);
|
|
293
|
+
return method.apply(statement, args);
|
|
294
|
+
}
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
return value.bind(target);
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
const facade = {
|
|
302
|
+
prepare(sql) {
|
|
303
|
+
const session = currentSession();
|
|
304
|
+
return wrapStatement(sql, void 0, session, session.prepare(sql));
|
|
305
|
+
},
|
|
306
|
+
batch(statements) {
|
|
307
|
+
const resolvers = statements.map(resolveD1Statement);
|
|
308
|
+
const replayable = statements.length > 0 && statements.every((statement) => {
|
|
309
|
+
const sql = getD1StatementSql(statement);
|
|
310
|
+
return sql !== void 0 && isReplayableD1Sql(sql);
|
|
311
|
+
});
|
|
312
|
+
return runRecoverable(
|
|
313
|
+
replayable,
|
|
314
|
+
`batch(${statements.length})`,
|
|
315
|
+
(session) => {
|
|
316
|
+
const batch = session.batch;
|
|
317
|
+
return batch.call(session, resolvers.map((resolve) => resolve(session)));
|
|
318
|
+
}
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
return new Proxy(facade, {
|
|
323
|
+
get(target, property, receiver) {
|
|
324
|
+
if (Reflect.has(target, property))
|
|
325
|
+
return Reflect.get(target, property, receiver);
|
|
326
|
+
const session = currentSession();
|
|
327
|
+
const value = session[property];
|
|
328
|
+
return typeof value === "function" ? value.bind(session) : value;
|
|
329
|
+
}
|
|
330
|
+
});
|
|
101
331
|
}
|
|
102
332
|
function getRequestD1Session(requestContext, binding, database, consistency = { _tag: "first-primary" }) {
|
|
103
|
-
const
|
|
104
|
-
if (existing !== void 0 && !(existing instanceof Map))
|
|
105
|
-
throw new TypeError("Request D1 session cache has an invalid value");
|
|
106
|
-
const sessions = existing ?? /* @__PURE__ */ new Map();
|
|
107
|
-
requestContext[REQUEST_D1_SESSIONS] = sessions;
|
|
333
|
+
const sessions = getD1SessionCache(requestContext, REQUEST_D1_SESSIONS);
|
|
108
334
|
const constraint = consistencyConstraint(consistency);
|
|
109
335
|
const key = `${binding}:${constraint}`;
|
|
110
336
|
if (!sessions.has(key))
|
|
111
337
|
sessions.set(key, database.withSession(constraint));
|
|
112
338
|
return sessions.get(key);
|
|
113
339
|
}
|
|
340
|
+
function getRecoveringRequestD1Session(requestContext, binding, database, options = {}) {
|
|
341
|
+
const consistency = options.consistency ?? { _tag: "first-primary" };
|
|
342
|
+
const key = `${binding}:${consistencyConstraint(consistency)}`;
|
|
343
|
+
const sessions = getD1SessionCache(requestContext, REQUEST_D1_RECOVERING_SESSIONS);
|
|
344
|
+
if (!sessions.has(key)) {
|
|
345
|
+
sessions.set(key, withD1ResetRecovery(database, {
|
|
346
|
+
...options,
|
|
347
|
+
consistency
|
|
348
|
+
}));
|
|
349
|
+
}
|
|
350
|
+
return sessions.get(key);
|
|
351
|
+
}
|
|
114
352
|
async function retryIdempotentD1Write(options) {
|
|
115
353
|
const maxAttempts = parseMaxAttempts(options.maxAttempts);
|
|
116
354
|
const random = options.random ?? Math.random;
|
|
@@ -125,7 +363,7 @@ async function retryIdempotentD1Write(options) {
|
|
|
125
363
|
return outcome.value;
|
|
126
364
|
lastError = outcome.error;
|
|
127
365
|
const kind = classifyD1RetryError(outcome.error);
|
|
128
|
-
const retryable = kind._tag === "lock" || kind._tag === "transient" && options.safety._tag === "replay-safe";
|
|
366
|
+
const retryable = kind._tag === "lock" || (kind._tag === "session-reset" || kind._tag === "transient") && options.safety._tag === "replay-safe";
|
|
129
367
|
if (!retryable || attempt + 1 >= maxAttempts)
|
|
130
368
|
throw outcome.error;
|
|
131
369
|
await sleep(retryDelay(attempt, random));
|
|
@@ -133,4 +371,4 @@ async function retryIdempotentD1Write(options) {
|
|
|
133
371
|
throw lastError;
|
|
134
372
|
}
|
|
135
373
|
|
|
136
|
-
export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRequestD1Session, isTransientD1Error, retryIdempotentD1Write };
|
|
374
|
+
export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRecoveringRequestD1Session, getRequestD1Session, isReplayableD1Sql, isTransientD1Error, retryIdempotentD1Write, withD1ResetRecovery };
|
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
|
-
|
|
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 {
|
|
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
|
|
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
|
-
|
|
48
|
-
|
|
49
|
-
const
|
|
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
package/dist/module.mjs
CHANGED
|
@@ -216,7 +216,7 @@ function setupCloudflareModule(options, nuxt) {
|
|
|
216
216
|
);
|
|
217
217
|
let bindingTypeSignature;
|
|
218
218
|
if (options.bindingTypes !== false) {
|
|
219
|
-
addTypeTemplate({
|
|
219
|
+
const bindingTypesTemplate = addTypeTemplate({
|
|
220
220
|
filename: "types/cloudflare-bindings.d.ts",
|
|
221
221
|
getContents: async () => {
|
|
222
222
|
const { prepareCloudflareBindingTypes } = await import('./chunks/binding-types.mjs');
|
|
@@ -231,7 +231,10 @@ function setupCloudflareModule(options, nuxt) {
|
|
|
231
231
|
bindingTypeSignature = artifact.signature;
|
|
232
232
|
return artifact.content;
|
|
233
233
|
}
|
|
234
|
-
}, { nitro: true
|
|
234
|
+
}, { nitro: true });
|
|
235
|
+
nuxt.hook("prepare:types", ({ references }) => {
|
|
236
|
+
references.push({ path: bindingTypesTemplate.dst });
|
|
237
|
+
});
|
|
235
238
|
}
|
|
236
239
|
configure();
|
|
237
240
|
nuxt.hook("modules:done", () => {
|