devflare 1.0.0-next.21 → 1.0.0-next.22
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/bridge/gateway-runtime.d.ts +1 -1
- package/dist/bridge/gateway-runtime.d.ts.map +1 -1
- package/dist/bridge/proxy.d.ts +2 -0
- package/dist/bridge/proxy.d.ts.map +1 -1
- package/dist/bridge/server.d.ts.map +1 -1
- package/dist/browser.js +2 -2
- package/dist/build-qsgnme4z.js +54 -0
- package/dist/cli/index.js +1 -1
- package/dist/deploy-nh5tbv45.js +1055 -0
- package/dist/dev-cme5de75.js +2551 -0
- package/dist/index-35bmgpfw.js +573 -0
- package/dist/index-4se6krdj.js +574 -0
- package/dist/index-c1cj9085.js +2250 -0
- package/dist/index-hbxkmb1q.js +1426 -0
- package/dist/index-jwd3fanx.js +412 -0
- package/dist/index-s9q605sq.js +1033 -0
- package/dist/index-w36q6819.js +895 -0
- package/dist/index-xp0qkkxf.js +68 -0
- package/dist/index-zawn5tte.js +109 -0
- package/dist/index-zpy9caxn.js +1193 -0
- package/dist/index.js +3 -3
- package/dist/runtime/index.js +3 -3
- package/dist/sveltekit/index.js +4 -3
- package/dist/sveltekit/local-bindings.d.ts.map +1 -1
- package/dist/test/index.js +6 -6
- package/dist/test/resolve-service-bindings.d.ts.map +1 -1
- package/dist/vite/index.js +2 -2
- package/package.json +1 -1
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
// src/dev-server/miniflare-log.ts
|
|
2
|
+
var ANSI_ESCAPE_REGEX = /\u001B\[[0-9;]*m/g;
|
|
3
|
+
var COMPATIBILITY_DATE_FALLBACK_REGEX = /^The latest compatibility date supported by the installed Cloudflare Workers Runtime is "([^"]+)", but you've requested "([^"]+)"\. Falling back to "([^"]+)"\.\.\.$/;
|
|
4
|
+
var MINIFLARE_LOG_LEVEL_FALLBACKS = {
|
|
5
|
+
WARN: 2,
|
|
6
|
+
DEBUG: 4
|
|
7
|
+
};
|
|
8
|
+
function normalizeMiniflareMessage(message) {
|
|
9
|
+
return message.replace(ANSI_ESCAPE_REGEX, "").replace(/\s+/g, " ").trim();
|
|
10
|
+
}
|
|
11
|
+
function formatCompatibilityDateFallbackNotice(message) {
|
|
12
|
+
const normalizedMessage = normalizeMiniflareMessage(message);
|
|
13
|
+
const match = COMPATIBILITY_DATE_FALLBACK_REGEX.exec(normalizedMessage);
|
|
14
|
+
if (!match) {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
const [, _supportedDate, requestedDate, fallbackDate] = match;
|
|
18
|
+
return `Using latest supported Cloudflare Workers Runtime compatibility date ${fallbackDate} (requested ${requestedDate})`;
|
|
19
|
+
}
|
|
20
|
+
function resolveMiniflareLogLevel(logLevel, levelName) {
|
|
21
|
+
return logLevel?.[levelName] ?? MINIFLARE_LOG_LEVEL_FALLBACKS[levelName];
|
|
22
|
+
}
|
|
23
|
+
function createMiniflareLog(BaseLog, logLevel, levelName, logger) {
|
|
24
|
+
if (!BaseLog) {
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
return createCompatibilityAwareMiniflareLog(BaseLog, resolveMiniflareLogLevel(logLevel, levelName), logger);
|
|
28
|
+
}
|
|
29
|
+
function createCompatibilityAwareMiniflareLog(BaseLog, level, logger) {
|
|
30
|
+
const log = new BaseLog(level);
|
|
31
|
+
const originalWarn = log.warn.bind(log);
|
|
32
|
+
const originalInfo = log.info.bind(log);
|
|
33
|
+
log.warn = (message) => {
|
|
34
|
+
const notice = formatCompatibilityDateFallbackNotice(message);
|
|
35
|
+
if (!notice) {
|
|
36
|
+
originalWarn(message);
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
if (logger) {
|
|
40
|
+
logger.info(notice);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
originalInfo(notice);
|
|
44
|
+
};
|
|
45
|
+
return log;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// src/bridge/gateway-runtime.ts
|
|
49
|
+
var GATEWAY_RUNTIME_JS = `
|
|
50
|
+
const RAW_EMAIL = 'EmailMessage::raw'
|
|
51
|
+
|
|
52
|
+
function arrayBufferToBase64(buffer) {
|
|
53
|
+
const bytes = new Uint8Array(buffer)
|
|
54
|
+
let binary = ''
|
|
55
|
+
for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i])
|
|
56
|
+
return btoa(binary)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function base64ToArrayBuffer(base64) {
|
|
60
|
+
const binary = atob(base64)
|
|
61
|
+
const bytes = new Uint8Array(binary.length)
|
|
62
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
|
|
63
|
+
return bytes.buffer
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function serializeR2Object(obj) {
|
|
67
|
+
if (!obj) return null
|
|
68
|
+
return {
|
|
69
|
+
__type: 'R2Object',
|
|
70
|
+
key: obj.key,
|
|
71
|
+
version: obj.version,
|
|
72
|
+
size: obj.size,
|
|
73
|
+
etag: obj.etag,
|
|
74
|
+
httpEtag: obj.httpEtag,
|
|
75
|
+
checksums: obj.checksums,
|
|
76
|
+
uploaded: obj.uploaded?.toISOString(),
|
|
77
|
+
httpMetadata: obj.httpMetadata,
|
|
78
|
+
customMetadata: obj.customMetadata,
|
|
79
|
+
range: obj.range,
|
|
80
|
+
storageClass: obj.storageClass
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function serializeR2ObjectBody(obj, bodyData) {
|
|
85
|
+
if (!obj) return null
|
|
86
|
+
return {
|
|
87
|
+
__type: 'R2ObjectBody',
|
|
88
|
+
key: obj.key,
|
|
89
|
+
version: obj.version,
|
|
90
|
+
size: obj.size,
|
|
91
|
+
etag: obj.etag,
|
|
92
|
+
httpEtag: obj.httpEtag,
|
|
93
|
+
checksums: obj.checksums,
|
|
94
|
+
uploaded: obj.uploaded?.toISOString(),
|
|
95
|
+
httpMetadata: obj.httpMetadata,
|
|
96
|
+
customMetadata: obj.customMetadata,
|
|
97
|
+
range: obj.range,
|
|
98
|
+
storageClass: obj.storageClass,
|
|
99
|
+
bodyData
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function serializeR2Objects(result) {
|
|
104
|
+
if (!result) return null
|
|
105
|
+
return {
|
|
106
|
+
objects: result.objects.map(serializeR2Object),
|
|
107
|
+
truncated: result.truncated,
|
|
108
|
+
cursor: result.cursor,
|
|
109
|
+
delimitedPrefixes: result.delimitedPrefixes
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function serializeResponse(response) {
|
|
114
|
+
let body = null
|
|
115
|
+
if (response.body) {
|
|
116
|
+
const bytes = await response.arrayBuffer()
|
|
117
|
+
if (bytes.byteLength > 0) {
|
|
118
|
+
body = { type: 'bytes', data: arrayBufferToBase64(bytes) }
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
status: response.status,
|
|
123
|
+
statusText: response.statusText,
|
|
124
|
+
headers: [...response.headers.entries()],
|
|
125
|
+
body
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function deserializeRequest(serializedReq) {
|
|
130
|
+
return new Request(serializedReq.url, {
|
|
131
|
+
method: serializedReq.method,
|
|
132
|
+
headers: serializedReq.headers,
|
|
133
|
+
body: serializedReq.body?.type === 'bytes'
|
|
134
|
+
? base64ToArrayBuffer(serializedReq.body.data)
|
|
135
|
+
: undefined,
|
|
136
|
+
redirect: serializedReq.redirect
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function createEmailMessageRaw(raw) {
|
|
141
|
+
if (typeof raw === 'string' || raw instanceof ReadableStream) {
|
|
142
|
+
return raw
|
|
143
|
+
}
|
|
144
|
+
if (raw instanceof ArrayBuffer || raw instanceof Uint8Array) {
|
|
145
|
+
return new Response(raw).body
|
|
146
|
+
}
|
|
147
|
+
throw new Error('Unsupported EmailMessage raw payload')
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function isDurableObjectNamespace(binding) {
|
|
151
|
+
return !!binding
|
|
152
|
+
&& typeof binding.idFromName === 'function'
|
|
153
|
+
&& typeof binding.idFromString === 'function'
|
|
154
|
+
&& typeof binding.newUniqueId === 'function'
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Execute an RPC method against the gateway's bindings.
|
|
159
|
+
*
|
|
160
|
+
* Method format: "binding.operation". Operations must be namespaced by
|
|
161
|
+
* binding kind (e.g. "kv.get", "r2.head", "d1.stmt.first", "do.fetch",
|
|
162
|
+
* "service.fetch", "queue.send", "email.send", "ai.run"). Bare verbs and the legacy
|
|
163
|
+
* "stmt.*" / "stub.*" sub-prefixes were removed in B3-final and now throw.
|
|
164
|
+
* Method vocabulary must stay in sync with the canonical server in
|
|
165
|
+
* src/bridge/server.ts.
|
|
166
|
+
*/
|
|
167
|
+
async function executeRpcMethod(method, params, env, _ctx) {
|
|
168
|
+
const parts = method.split('.')
|
|
169
|
+
if (parts.length < 2) throw new Error('Invalid method format: ' + method)
|
|
170
|
+
|
|
171
|
+
const bindingName = parts[0]
|
|
172
|
+
const operation = parts.slice(1).join('.')
|
|
173
|
+
const binding = env[bindingName]
|
|
174
|
+
|
|
175
|
+
if (!binding) throw new Error('Binding not found: ' + bindingName)
|
|
176
|
+
|
|
177
|
+
const isNamespaced =
|
|
178
|
+
operation.indexOf('kv.') === 0 ||
|
|
179
|
+
operation.indexOf('r2.') === 0 ||
|
|
180
|
+
operation.indexOf('d1.') === 0 ||
|
|
181
|
+
operation.indexOf('do.') === 0 ||
|
|
182
|
+
operation.indexOf('service.') === 0 ||
|
|
183
|
+
operation.indexOf('queue.') === 0 ||
|
|
184
|
+
operation.indexOf('email.') === 0 ||
|
|
185
|
+
operation.indexOf('ai.') === 0 ||
|
|
186
|
+
operation.indexOf('workflow.') === 0 ||
|
|
187
|
+
operation.indexOf('var.') === 0
|
|
188
|
+
if (!isNamespaced) {
|
|
189
|
+
throw new Error(createUnsupportedBridgeOperationErrorMessage(bindingName, operation))
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// KV
|
|
193
|
+
if (operation === 'kv.get') return binding.get(params[0], params[1])
|
|
194
|
+
if (operation === 'kv.put') return binding.put(params[0], params[1], params[2])
|
|
195
|
+
if (operation === 'kv.delete') return binding.delete(params[0])
|
|
196
|
+
if (operation === 'kv.list') return binding.list(params[0])
|
|
197
|
+
if (operation === 'kv.getWithMetadata') return binding.getWithMetadata(params[0], params[1])
|
|
198
|
+
|
|
199
|
+
// DO get (returns DOStub reference)
|
|
200
|
+
if (operation === 'do.get') {
|
|
201
|
+
return { __type: 'DOStub', binding: bindingName, id: params[0] }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// R2
|
|
205
|
+
if (operation === 'r2.head') return serializeR2Object(await binding.head(params[0]))
|
|
206
|
+
if (operation === 'r2.get') {
|
|
207
|
+
const obj = await binding.get(params[0], params[1])
|
|
208
|
+
if (!obj) return null
|
|
209
|
+
const body = await obj.arrayBuffer()
|
|
210
|
+
return serializeR2ObjectBody(obj, arrayBufferToBase64(body))
|
|
211
|
+
}
|
|
212
|
+
if (operation === 'r2.put') {
|
|
213
|
+
let value = params[1]
|
|
214
|
+
if (value && typeof value === 'object') {
|
|
215
|
+
if (value.__type === 'ArrayBuffer' || value.__type === 'Uint8Array') {
|
|
216
|
+
value = base64ToArrayBuffer(value.data)
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return serializeR2Object(await binding.put(params[0], value, params[2]))
|
|
220
|
+
}
|
|
221
|
+
if (operation === 'r2.delete') return binding.delete(params[0])
|
|
222
|
+
if (operation === 'r2.list') return serializeR2Objects(await binding.list(params[0]))
|
|
223
|
+
|
|
224
|
+
// D1
|
|
225
|
+
if (operation === 'd1.exec') return binding.exec(params[0])
|
|
226
|
+
if (operation === 'd1.batch') {
|
|
227
|
+
const statements = params[0].map((s) => binding.prepare(s.sql).bind(...(s.bindings || [])))
|
|
228
|
+
return binding.batch(statements)
|
|
229
|
+
}
|
|
230
|
+
if (operation.indexOf('d1.stmt.') === 0) {
|
|
231
|
+
const mode = operation.split('.')[2]
|
|
232
|
+
const [sql, ...rest] = params
|
|
233
|
+
let bindings = rest
|
|
234
|
+
let extraParam
|
|
235
|
+
if (mode === 'first' || mode === 'raw') {
|
|
236
|
+
extraParam = rest[rest.length - 1]
|
|
237
|
+
bindings = rest.slice(0, -1)
|
|
238
|
+
}
|
|
239
|
+
let stmt = binding.prepare(sql)
|
|
240
|
+
if (bindings.length > 0) stmt = stmt.bind(...bindings)
|
|
241
|
+
if (mode === 'first') {
|
|
242
|
+
if (typeof extraParam === 'string' && extraParam.length > 0) return stmt.first(extraParam)
|
|
243
|
+
return stmt.first()
|
|
244
|
+
}
|
|
245
|
+
if (mode === 'all') return stmt.all()
|
|
246
|
+
if (mode === 'run') return stmt.run()
|
|
247
|
+
if (mode === 'raw') return stmt.raw(extraParam)
|
|
248
|
+
throw new Error('Unknown stmt mode: ' + mode)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Durable Objects
|
|
252
|
+
if (operation === 'do.idFromName') {
|
|
253
|
+
const id = binding.idFromName(params[0])
|
|
254
|
+
return { __type: 'DOId', hex: id.toString() }
|
|
255
|
+
}
|
|
256
|
+
if (operation === 'do.idFromString') {
|
|
257
|
+
const id = binding.idFromString(params[0])
|
|
258
|
+
return { __type: 'DOId', hex: id.toString() }
|
|
259
|
+
}
|
|
260
|
+
if (operation === 'do.newUniqueId') {
|
|
261
|
+
const id = binding.newUniqueId(params[0])
|
|
262
|
+
return { __type: 'DOId', hex: id.toString() }
|
|
263
|
+
}
|
|
264
|
+
if (operation === 'do.fetch') {
|
|
265
|
+
const [, serializedId, serializedReq] = params
|
|
266
|
+
const id = binding.idFromString(serializedId.hex)
|
|
267
|
+
const stub = binding.get(id)
|
|
268
|
+
const response = await stub.fetch(new Request(serializedReq.url, {
|
|
269
|
+
method: serializedReq.method,
|
|
270
|
+
headers: serializedReq.headers,
|
|
271
|
+
body: serializedReq.body?.type === 'bytes'
|
|
272
|
+
? base64ToArrayBuffer(serializedReq.body.data)
|
|
273
|
+
: undefined
|
|
274
|
+
}))
|
|
275
|
+
return serializeResponse(response)
|
|
276
|
+
}
|
|
277
|
+
if (operation === 'do.rpc') {
|
|
278
|
+
const [, serializedId, methodName, args] = params
|
|
279
|
+
const id = binding.idFromString(serializedId.hex)
|
|
280
|
+
const stub = binding.get(id)
|
|
281
|
+
const response = await stub.fetch(new Request('http://do/_rpc', {
|
|
282
|
+
method: 'POST',
|
|
283
|
+
headers: { 'Content-Type': 'application/json' },
|
|
284
|
+
body: JSON.stringify({ method: methodName, params: args })
|
|
285
|
+
}))
|
|
286
|
+
const result = await response.json()
|
|
287
|
+
if (!result.ok) throw new Error(result.error?.message || 'RPC failed')
|
|
288
|
+
return result.result
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Service Bindings
|
|
292
|
+
if (operation === 'service.fetch') {
|
|
293
|
+
if (!binding || typeof binding.fetch !== 'function') {
|
|
294
|
+
throw new Error('Service binding ' + bindingName + ' does not support fetch()')
|
|
295
|
+
}
|
|
296
|
+
const response = await binding.fetch(deserializeRequest(params[0]))
|
|
297
|
+
return serializeResponse(response)
|
|
298
|
+
}
|
|
299
|
+
if (operation === 'service.rpc') {
|
|
300
|
+
const methodName = params[0]
|
|
301
|
+
if (typeof methodName !== 'string') {
|
|
302
|
+
throw new Error('Service binding ' + bindingName + ' RPC method name must be a string')
|
|
303
|
+
}
|
|
304
|
+
const args = Array.isArray(params[1]) ? params[1] : []
|
|
305
|
+
const method = binding && binding[methodName]
|
|
306
|
+
if (typeof method !== 'function') {
|
|
307
|
+
throw new Error('Service binding ' + bindingName + ' does not support ' + methodName + '()')
|
|
308
|
+
}
|
|
309
|
+
return method.apply(binding, args)
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// Queues
|
|
313
|
+
if (operation === 'queue.send') return binding.send(params[0], params[1])
|
|
314
|
+
if (operation === 'queue.sendBatch') return binding.sendBatch(params[0], params[1])
|
|
315
|
+
|
|
316
|
+
// Send Email
|
|
317
|
+
if (operation === 'email.send') {
|
|
318
|
+
if (binding && typeof binding.send === 'function') {
|
|
319
|
+
const message = params[0]
|
|
320
|
+
if (message && typeof message === 'object' && 'from' in message && 'to' in message && 'raw' in message) {
|
|
321
|
+
return binding.send({
|
|
322
|
+
from: message.from,
|
|
323
|
+
to: message.to,
|
|
324
|
+
[RAW_EMAIL]: createEmailMessageRaw(message.raw)
|
|
325
|
+
})
|
|
326
|
+
}
|
|
327
|
+
return binding.send(message)
|
|
328
|
+
}
|
|
329
|
+
return { ok: true, simulated: true }
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Workflows
|
|
333
|
+
if (operation === 'workflow.create') {
|
|
334
|
+
return serializeWorkflowInstance(await binding.create(params[0]))
|
|
335
|
+
}
|
|
336
|
+
if (operation === 'workflow.get') {
|
|
337
|
+
return serializeWorkflowInstance(await binding.get(params[0]))
|
|
338
|
+
}
|
|
339
|
+
if (operation === 'workflow.status') {
|
|
340
|
+
return (await binding.get(params[0])).status()
|
|
341
|
+
}
|
|
342
|
+
if (operation === 'workflow.pause') {
|
|
343
|
+
return (await binding.get(params[0])).pause()
|
|
344
|
+
}
|
|
345
|
+
if (operation === 'workflow.resume') {
|
|
346
|
+
return (await binding.get(params[0])).resume()
|
|
347
|
+
}
|
|
348
|
+
if (operation === 'workflow.terminate') {
|
|
349
|
+
return (await binding.get(params[0])).terminate()
|
|
350
|
+
}
|
|
351
|
+
if (operation === 'workflow.restart') {
|
|
352
|
+
return (await binding.get(params[0])).restart()
|
|
353
|
+
}
|
|
354
|
+
if (operation === 'workflow.sendEvent') {
|
|
355
|
+
return (await binding.get(params[0])).sendEvent(params[1])
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// AI / generic run()
|
|
359
|
+
if (operation === 'ai.run') {
|
|
360
|
+
if (typeof binding.run !== 'function') {
|
|
361
|
+
throw new Error('Binding ' + bindingName + ' does not support run(): ' + method)
|
|
362
|
+
}
|
|
363
|
+
return binding.run(params[0], params[1])
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
throw new Error('Unknown operation: ' + method)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function createUnsupportedBridgeOperationErrorMessage(bindingName, operation) {
|
|
370
|
+
const base = "[devflare][bridge] Unsupported bridge operation '" + operation + "' for binding '" + bindingName + "'."
|
|
371
|
+
if (operation === 'fetch') {
|
|
372
|
+
return base + ' Devflare could not dispatch fetch() for this binding through the local bridge. '
|
|
373
|
+
+ 'Expected Cloudflare API: env.' + bindingName + '.fetch(request). '
|
|
374
|
+
+ 'If this came from SvelteKit platform.env, make sure the binding is declared as a service binding; '
|
|
375
|
+
+ 'this is a Devflare local bridge issue when service bindings fall back to a bare fetch operation.'
|
|
376
|
+
}
|
|
377
|
+
if (operation === 'toString') {
|
|
378
|
+
return base + ' A platform.env value was coerced to a string through the bridge. '
|
|
379
|
+
+ 'For SvelteKit local dev, declared vars should be plain string values and missing env names should read as undefined.'
|
|
380
|
+
}
|
|
381
|
+
return base + ' Bare verbs and the legacy stmt.*/stub.* sub-prefixes are not supported; '
|
|
382
|
+
+ 'use the namespaced form (e.g. kv.get, r2.put, d1.stmt.first, do.fetch, service.fetch).'
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function serializeWorkflowInstance(instance) {
|
|
386
|
+
return {
|
|
387
|
+
__type: 'WorkflowInstance',
|
|
388
|
+
id: instance.id
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// ---------------------------------------------------------------------------
|
|
393
|
+
// WebSocket bridge (shared with src/bridge/server.ts in shape)
|
|
394
|
+
// ---------------------------------------------------------------------------
|
|
395
|
+
// NOTE: wsProxies is intentionally created per handleBridgeWebSocket call so
|
|
396
|
+
// state never leaks across connections or across gateway-script regenerations.
|
|
397
|
+
|
|
398
|
+
async function handleBridgeRpcCall(msg, ws, env, ctx) {
|
|
399
|
+
try {
|
|
400
|
+
const result = await executeRpcMethod(msg.method, msg.params, env, ctx)
|
|
401
|
+
ws.send(JSON.stringify({ t: 'rpc.ok', id: msg.id, result }))
|
|
402
|
+
} catch (error) {
|
|
403
|
+
ws.send(JSON.stringify({
|
|
404
|
+
t: 'rpc.err',
|
|
405
|
+
id: msg.id,
|
|
406
|
+
error: {
|
|
407
|
+
code: error?.code || 'INTERNAL_ERROR',
|
|
408
|
+
message: error?.message || String(error)
|
|
409
|
+
}
|
|
410
|
+
}))
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function handleBridgeWsOpen(msg, ws, env, wsProxies) {
|
|
415
|
+
try {
|
|
416
|
+
const binding = env[msg.target.binding]
|
|
417
|
+
const id = binding.idFromString(msg.target.id)
|
|
418
|
+
const stub = binding.get(id)
|
|
419
|
+
|
|
420
|
+
const headers = new Headers(msg.target.headers || [])
|
|
421
|
+
headers.set('Upgrade', 'websocket')
|
|
422
|
+
|
|
423
|
+
const response = await stub.fetch(new Request(msg.target.url, { method: 'GET', headers }))
|
|
424
|
+
const doWs = response.webSocket
|
|
425
|
+
|
|
426
|
+
if (!doWs) {
|
|
427
|
+
ws.send(JSON.stringify({
|
|
428
|
+
t: 'rpc.err',
|
|
429
|
+
id: 'ws_' + msg.wid,
|
|
430
|
+
error: { code: 'WS_FAILED', message: 'No WebSocket returned' }
|
|
431
|
+
}))
|
|
432
|
+
return
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
doWs.accept()
|
|
436
|
+
wsProxies.set(msg.wid, { doWs })
|
|
437
|
+
|
|
438
|
+
doWs.addEventListener('message', (event) => {
|
|
439
|
+
const isText = typeof event.data === 'string'
|
|
440
|
+
const data = isText ? event.data : arrayBufferToBase64(event.data)
|
|
441
|
+
ws.send(JSON.stringify({ t: 'ws.data', wid: msg.wid, data, isText }))
|
|
442
|
+
})
|
|
443
|
+
|
|
444
|
+
doWs.addEventListener('close', (event) => {
|
|
445
|
+
ws.send(JSON.stringify({ t: 'ws.close', wid: msg.wid, code: event.code, reason: event.reason }))
|
|
446
|
+
wsProxies.delete(msg.wid)
|
|
447
|
+
})
|
|
448
|
+
|
|
449
|
+
ws.send(JSON.stringify({ t: 'ws.opened', wid: msg.wid }))
|
|
450
|
+
} catch (error) {
|
|
451
|
+
ws.send(JSON.stringify({
|
|
452
|
+
t: 'rpc.err',
|
|
453
|
+
id: 'ws_' + msg.wid,
|
|
454
|
+
error: { code: 'WS_FAILED', message: error.message }
|
|
455
|
+
}))
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function handleBridgeWsClose(msg, wsProxies) {
|
|
460
|
+
const proxy = wsProxies.get(msg.wid)
|
|
461
|
+
if (proxy) {
|
|
462
|
+
proxy.doWs.close(msg.code, msg.reason)
|
|
463
|
+
wsProxies.delete(msg.wid)
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
async function handleBridgeJsonMessage(data, ws, env, ctx, wsProxies) {
|
|
468
|
+
const msg = JSON.parse(data)
|
|
469
|
+
switch (msg.t) {
|
|
470
|
+
case 'hello':
|
|
471
|
+
// v2 handshake — acknowledge with welcome echoing the negotiated
|
|
472
|
+
// capability intersection. Capabilities advertised by the gateway
|
|
473
|
+
// are kept in sync with src/bridge/client.ts (BRIDGE_CLIENT_CAPABILITIES).
|
|
474
|
+
ws.send(JSON.stringify({
|
|
475
|
+
t: 'welcome',
|
|
476
|
+
protocolVersion: 2,
|
|
477
|
+
capabilities: ['streams', 'ws-relay', 'http-transfer']
|
|
478
|
+
.filter((c) => Array.isArray(msg.capabilities) && msg.capabilities.includes(c))
|
|
479
|
+
.sort()
|
|
480
|
+
}))
|
|
481
|
+
break
|
|
482
|
+
case 'rpc.call':
|
|
483
|
+
await handleBridgeRpcCall(msg, ws, env, ctx)
|
|
484
|
+
break
|
|
485
|
+
case 'ws.open':
|
|
486
|
+
await handleBridgeWsOpen(msg, ws, env, wsProxies)
|
|
487
|
+
break
|
|
488
|
+
case 'ws.close':
|
|
489
|
+
handleBridgeWsClose(msg, wsProxies)
|
|
490
|
+
break
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function handleBridgeWebSocket(request, env, ctx) {
|
|
495
|
+
const { 0: client, 1: server } = new WebSocketPair()
|
|
496
|
+
server.accept()
|
|
497
|
+
|
|
498
|
+
// Per-connection state: recreated for every bridge client so reloads and
|
|
499
|
+
// concurrent clients never share WS proxy entries.
|
|
500
|
+
const wsProxies = new Map()
|
|
501
|
+
|
|
502
|
+
server.addEventListener('message', async (event) => {
|
|
503
|
+
try {
|
|
504
|
+
if (typeof event.data === 'string') {
|
|
505
|
+
await handleBridgeJsonMessage(event.data, server, env, ctx, wsProxies)
|
|
506
|
+
}
|
|
507
|
+
} catch (error) {
|
|
508
|
+
console.error('[Gateway] Error:', error)
|
|
509
|
+
}
|
|
510
|
+
})
|
|
511
|
+
|
|
512
|
+
server.addEventListener('close', () => {
|
|
513
|
+
for (const proxy of wsProxies.values()) {
|
|
514
|
+
// Best-effort cleanup: the DO-side WS may already be closed or in an
|
|
515
|
+
// invalid state; any throw here would abort sibling closes. Surface
|
|
516
|
+
// the swallowed error when DEVFLARE_DEBUG_BRIDGE is enabled.
|
|
517
|
+
try { proxy.doWs.close() } catch (error) {
|
|
518
|
+
if (globalThis.DEVFLARE_DEBUG_BRIDGE) {
|
|
519
|
+
console.warn('[devflare:bridge] proxy.doWs.close() failed', error)
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
wsProxies.clear()
|
|
524
|
+
})
|
|
525
|
+
|
|
526
|
+
return new Response(null, { status: 101, webSocket: client })
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// ---------------------------------------------------------------------------
|
|
530
|
+
// HTTP transfer for R2 bodies (shared with src/bridge/server.ts in shape)
|
|
531
|
+
// ---------------------------------------------------------------------------
|
|
532
|
+
|
|
533
|
+
async function handleHttpTransfer(request, env, url) {
|
|
534
|
+
const transferIdEncoded = url.pathname.split('/').pop()
|
|
535
|
+
const transferId = decodeURIComponent(transferIdEncoded || '')
|
|
536
|
+
const [binding, ...keyParts] = transferId.split(':')
|
|
537
|
+
const key = keyParts.join(':')
|
|
538
|
+
const bucket = env[binding]
|
|
539
|
+
|
|
540
|
+
if (!bucket) return new Response('Bucket not found: ' + binding, { status: 404 })
|
|
541
|
+
|
|
542
|
+
if (request.method === 'PUT' || request.method === 'POST') {
|
|
543
|
+
const result = await bucket.put(key, request.body)
|
|
544
|
+
return new Response(JSON.stringify(serializeR2Object(result)), {
|
|
545
|
+
headers: { 'Content-Type': 'application/json' }
|
|
546
|
+
})
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
if (request.method === 'GET') {
|
|
550
|
+
const object = await bucket.get(key)
|
|
551
|
+
if (!object) return new Response('Not found', { status: 404 })
|
|
552
|
+
return new Response(object.body, {
|
|
553
|
+
headers: {
|
|
554
|
+
'Content-Type': object.httpMetadata?.contentType || 'application/octet-stream',
|
|
555
|
+
'Content-Length': String(object.size)
|
|
556
|
+
}
|
|
557
|
+
})
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
return new Response('Method not allowed', { status: 405 })
|
|
561
|
+
}
|
|
562
|
+
`;
|
|
563
|
+
|
|
564
|
+
// src/bridge/miniflare.ts
|
|
565
|
+
function isIgnorableMiniflareDisposeError(error) {
|
|
566
|
+
if (!(error instanceof Error)) {
|
|
567
|
+
return false;
|
|
568
|
+
}
|
|
569
|
+
const details = error;
|
|
570
|
+
return details.code === "EBADF" && details.syscall === "kill";
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
export { createMiniflareLog, GATEWAY_RUNTIME_JS, isIgnorableMiniflareDisposeError };
|