fetchlet 0.1.0

Rust-hosted JavaScript functions and Fetch handlers with explicit host services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
// Generated by `vp run build:scripts` from the TypeScript sources in js-src/.
(function() {
	// js-src/host-bridge/host.ts
	const nativeDispatch = globalThis.__fetchletHost;
	const takeBytes = globalThis.__fetchletTakeBytes;
	const putBytes = globalThis.__fetchletPutBytes;
	delete globalThis.__fetchletHost;
	delete globalThis.__fetchletTakeBytes;
	delete globalThis.__fetchletPutBytes;
	function hostError(description) {
		const error = new Error(description.message);
		error.name = "FetchletHostError";
		error.code = description.code;
		return error;
	}
	function dispatch(operation, input) {
		return dispatchJson(operation, JSON.stringify(input));
	}
	/** Dispatch an input already encoded as JSON. */
	function dispatchJson(operation, input) {
		const reply = JSON.parse(nativeDispatch(operation, input));
		if (!reply.ok) throw hostError(reply.error);
		return reply.value;
	}
	// js-src/host-bridge/background.ts
	const backgroundTasks = /* @__PURE__ */ new Set();
	function waitUntil(promise) {
		dispatch("background.register", null);
		const task = Promise.resolve(promise).then(() => {}, () => {}).then(() => {
			backgroundTasks.delete(task);
			try {
				dispatch("background.settle", null);
			} catch {}
		});
		backgroundTasks.add(task);
	}
	const backgroundRegistry = Object.freeze({
		pending() {
			return backgroundTasks.size;
		},
		async settle() {
			while (backgroundTasks.size > 0) await Promise.all(Array.from(backgroundTasks));
		},
		clear() {
			backgroundTasks.clear();
		}
	});
	// js-src/host-bridge/channels.ts
	const channels = /* @__PURE__ */ new Map();
	let acceptedUpgrade;
	function hasOpenChannels() {
		return channels.size > 0;
	}
	function track(id, listener) {
		let resolveClosed;
		const closed = new Promise((resolve) => {
			resolveClosed = resolve;
		});
		channels.set(id, {
			listener,
			closed,
			resolveClosed
		});
	}
	/** Remove an entry whose channel ended; a pending write fails with it. */
	function end(id, entry) {
		channels.delete(id);
		entry.write?.reject(/* @__PURE__ */ new TypeError("The channel closed"));
		entry.write = void 0;
		entry.resolveClosed();
	}
	function forget(id) {
		const entry = channels.get(id);
		if (entry) end(id, entry);
	}
	/** Deliver an arrival if the event is one. Returns whether it was. */
	function completeChannel(event) {
		if (!("channel" in event)) return false;
		const arrival = event;
		const bytes = arrival.bytes === void 0 ? void 0 : takeBytes(arrival.bytes);
		const entry = channels.get(arrival.channel);
		if (!entry) return true;
		if (arrival.close !== void 0) try {
			entry.listener.close(arrival.close.code, arrival.close.reason);
		} finally {
			end(arrival.channel, entry);
		}
		else if (arrival.refused !== void 0) try {
			entry.listener.refused?.(arrival.refused.message);
		} finally {
			end(arrival.channel, entry);
		}
		else if (arrival.end === true) entry.listener.end?.();
		else if (arrival.secure === true) entry.listener.secure?.();
		else if (arrival.open === true) entry.listener.open(arrival.accepted);
		else if (arrival.written === true) {
			const write = entry.write;
			entry.write = void 0;
			write?.resolve();
		} else if (bytes !== void 0) entry.listener.message(bytes);
		else if (arrival.text !== void 0) entry.listener.message(arrival.text);
		return true;
	}
	const channelRegistry = Object.freeze({
		upgrade(listener) {
			const id = dispatch("websocket.upgrade", null);
			track(id, listener);
			acceptedUpgrade = id;
			return id;
		},
		accepted() {
			return acceptedUpgrade;
		},
		open(service, options, listener) {
			const id = dispatch("channel.open", {
				service,
				options: options ?? null
			});
			track(id, listener);
			return id;
		},
		adopt(id, listener) {
			if (channels.has(id)) throw new TypeError("The channel already has a listener");
			track(id, listener);
		},
		connect(address, listener) {
			const id = dispatch("socket.open", address);
			track(id, listener);
			return id;
		},
		websocket(request, listener) {
			const id = dispatch("websocket.open", request);
			track(id, listener);
			return id;
		},
		endWrites(id) {
			if (channels.has(id)) dispatch("socket.end", id);
		},
		startTls(id) {
			if (!channels.has(id)) throw new TypeError("The socket closed");
			dispatch("socket.startTls", id);
		},
		send(id, data) {
			if (!channels.has(id)) return;
			if (typeof data === "string") dispatch("channel.send", {
				id,
				text: data
			});
			else dispatch("channel.send", {
				id,
				bytes: putBytes(data)
			});
		},
		write(id, data) {
			const entry = channels.get(id);
			if (!entry) return Promise.reject(/* @__PURE__ */ new TypeError("The channel closed"));
			if (entry.write) return Promise.reject(/* @__PURE__ */ new TypeError("A write is pending"));
			return new Promise((resolve, reject) => {
				dispatch("channel.write", {
					id,
					bytes: putBytes(data)
				});
				entry.write = {
					resolve,
					reject
				};
			});
		},
		pause(id, paused) {
			if (channels.has(id)) dispatch("channel.pause", {
				id,
				paused
			});
		},
		close(id, code, reason) {
			if (channels.has(id)) dispatch("channel.close", {
				id,
				code,
				reason
			});
		},
		buffered(id) {
			return channels.has(id) ? dispatch("channel.buffered", id) : 0;
		},
		retain(id) {
			const accepted = acceptedUpgrade;
			if (accepted !== void 0 && accepted !== id) {
				acceptedUpgrade = void 0;
				forget(accepted);
			}
			return id !== void 0 && id === acceptedUpgrade && channels.has(id);
		},
		async hold(id) {
			const entry = channels.get(id);
			if (!entry) return;
			entry.listener.open();
			await entry.closed;
		},
		closeAll() {
			acceptedUpgrade = void 0;
			for (const id of channels.keys()) forget(id);
		}
	});
	// js-src/host-bridge/console.ts
	function formatConsoleValue(value) {
		if (typeof value === "string") return value;
		if (value instanceof Error) {
			const stack = typeof value.stack === "string" ? value.stack : "";
			const head = value.name + ": " + value.message;
			return stack.includes(value.message) ? stack : head + (stack ? "\n" + stack : "");
		}
		if (typeof value === "object" && value !== null) try {
			return JSON.stringify(value);
		} catch {
			return Object.prototype.toString.call(value);
		}
		return String(value);
	}
	function installConsole() {
		const write = (level) => (...values) => {
			try {
				dispatch("console.write", {
					level,
					message: values.map(formatConsoleValue).join(" ")
				});
			} catch {
				try {
					dispatch("console.write", {
						level,
						message: "[fetchlet: console message dropped]"
					});
				} catch {}
			}
		};
		globalThis.console = Object.assign(globalThis.console ?? {}, {
			debug: write("debug"),
			log: write("log"),
			info: write("info"),
			warn: write("warn"),
			error: write("error")
		});
	}
	// js-src/host-bridge/host-bodies.ts
	const pendingReads = /* @__PURE__ */ new Map();
	const wholeReads = /* @__PURE__ */ new WeakMap();
	function hasPendingReads() {
		return pendingReads.size > 0;
	}
	/** Forget the reads of an earlier invocation. */
	function clearPendingReads() {
		pendingReads.clear();
	}
	/** Settle the read a completion belongs to. Returns false for other tickets. */
	function completeRead(completion) {
		const read = pendingReads.get(completion.id);
		if (!read) return false;
		pendingReads.delete(completion.id);
		if (completion.result.ok) read.resolve(completion.result.value);
		else read.reject(hostError(completion.result.error));
		return true;
	}
	let byteStreams;
	function supportsByteStreams() {
		if (byteStreams === void 0) try {
			new ReadableStream({ type: "bytes" });
			byteStreams = true;
		} catch {
			byteStreams = false;
		}
		return byteStreams;
	}
	function readHostBody(id) {
		const ticket = dispatch("body.read", id);
		return new Promise((resolve, reject) => {
			pendingReads.set(ticket, {
				id,
				resolve,
				reject
			});
		});
	}
	function readWholeHostBody(id, text, onValue, onError) {
		const ticket = dispatch(text ? "body.readText" : "body.readAll", id);
		pendingReads.set(ticket, {
			id,
			resolve(value) {
				if (text) {
					onValue(value.text);
					return;
				}
				let bytes;
				try {
					bytes = takeBytes(value.chunk);
				} catch (error) {
					onError(error);
					return;
				}
				onValue(bytes);
			},
			reject: onError
		});
	}
	function readWholeBody(stream, text, onValue, onError) {
		const read = wholeReads.get(stream);
		if (read === void 0) return false;
		wholeReads.delete(stream);
		return read(text === true, onValue, onError);
	}
	function cancelHostBody(id) {
		for (const [ticket, pending] of pendingReads) if (pending.id === id) pendingReads.delete(ticket);
		try {
			dispatch("body.cancel", id);
		} catch {}
	}
	function hostBodyStream(id, signal) {
		let controller;
		let open = true;
		let wholeFailed = null;
		function finish() {
			open = false;
			wholeReads.delete(stream);
			signal?.removeEventListener("abort", abort);
		}
		function abort() {
			if (!open) return;
			finish();
			cancelHostBody(id);
			controller.error(signal.reason);
			const failed = wholeFailed;
			wholeFailed = null;
			failed?.(signal.reason);
		}
		function readWhole(text, onValue, onError) {
			if (!open) return false;
			const settle = (callback) => (value) => {
				wholeFailed = null;
				finish();
				callback(value);
			};
			const failed = settle(onError);
			wholeFailed = failed;
			try {
				readWholeHostBody(id, text, settle(onValue), failed);
			} catch (error) {
				failed(error);
			}
			return true;
		}
		const source = {
			start(streamController) {
				controller = streamController;
				signal?.addEventListener("abort", abort, { once: true });
			},
			pull(streamController) {
				wholeReads.delete(stream);
				return readHostBody(id).then(({ chunk, done }) => {
					if (!open) return;
					if (done) {
						finish();
						streamController.close();
					} else streamController.enqueue(takeBytes(chunk));
				}, (error) => {
					finish();
					throw error;
				});
			},
			cancel() {
				if (open) {
					finish();
					cancelHostBody(id);
				}
			}
		};
		const stream = supportsByteStreams() ? new ReadableStream({
			...source,
			type: "bytes"
		}) : new ReadableStream(source, { highWaterMark: 0 });
		wholeReads.set(stream, readWhole);
		return stream;
	}
	// js-src/host-bridge/fetch.ts
	const pendingFetches = /* @__PURE__ */ new Map();
	/** The reader of each body streaming to Rust, by its upload ticket. */
	const uploads = /* @__PURE__ */ new Map();
	function hasPendingFetches() {
		return pendingFetches.size > 0 || uploads.size > 0;
	}
	function endUpload(ticket, reason) {
		const reader = uploads.get(ticket);
		if (reader === void 0) return;
		uploads.delete(ticket);
		reader.cancel(reason).catch(() => {});
	}
	/** Send Rust the next chunk of an upload, its end, or its failure. */
	async function pullUpload(ticket) {
		const reader = uploads.get(ticket);
		if (reader === void 0) return;
		let write;
		try {
			const { value, done } = await reader.read();
			if (done) write = {
				ticket,
				done: true
			};
			else if (value instanceof Uint8Array) write = {
				ticket,
				chunk: putBytes(value)
			};
			else throw new TypeError("Request body must contain byte chunks");
		} catch {
			write = {
				ticket,
				error: true
			};
		}
		if (!uploads.has(ticket)) return;
		if (write.error === true) endUpload(ticket, /* @__PURE__ */ new TypeError("Request body stream failed"));
		else if (write.done === true) uploads.delete(ticket);
		try {
			dispatch("fetch.upload", write);
		} catch (error) {
			endUpload(ticket, error);
		}
	}
	/** Deliver a pull or a cancel of an upload; false if it is not one. */
	function completeUpload(completion) {
		if (!uploads.has(completion.id)) return false;
		if (completion.result.ok && completion.result.value === "pull") pullUpload(completion.id);
		else endUpload(completion.id);
		return true;
	}
	function exceedsBudget(observed, budget) {
		return budget !== null && BigInt(observed) > BigInt(budget);
	}
	async function readRequestBody(request, limits) {
		if (request.body === null) return null;
		const reader = request.body.getReader();
		const chunks = [];
		let byteLength = 0;
		let chunkCount = 0;
		function abortBodyRead() {
			reader.cancel(request.signal.reason).catch(() => {});
		}
		request.signal.addEventListener("abort", abortBodyRead, { once: true });
		try {
			while (true) {
				request.signal.throwIfAborted();
				const { value, done } = await reader.read();
				request.signal.throwIfAborted();
				if (done) break;
				chunkCount += 1;
				if (exceedsBudget(chunkCount, limits.requestBodyChunks)) {
					await reader.cancel();
					throw hostError({
						code: "LIMIT_EXCEEDED",
						message: "Request body has too many chunks"
					});
				}
				if (!(value instanceof Uint8Array)) throw new TypeError("Request body must contain byte chunks");
				byteLength += value.byteLength;
				if (exceedsBudget(byteLength, limits.requestBodyBytes)) {
					await reader.cancel();
					throw hostError({
						code: "LIMIT_EXCEEDED",
						message: "Request body exceeds the bridge limit"
					});
				}
				if (value.byteLength > 0) chunks.push(value);
			}
		} finally {
			request.signal.removeEventListener("abort", abortBodyRead);
			reader.releaseLock();
		}
		const bytes = new Uint8Array(byteLength);
		let offset = 0;
		for (const chunk of chunks) {
			bytes.set(chunk, offset);
			offset += chunk.byteLength;
		}
		return bytes;
	}
	function responseFromWire(response, signal) {
		const hasNoBody = [
			204,
			205,
			304
		].includes(response.status);
		let body = null;
		if (typeof response.stream === "number") body = hostBodyStream(response.stream, signal);
		else if (!hasNoBody) body = takeBytes(response.body);
		return new Response(body, {
			status: response.status,
			headers: response.headers
		});
	}
	/** Settle the fetch a completion belongs to, if it is still waiting. */
	function completeFetch(completion) {
		if (completeUpload(completion)) return;
		const pending = pendingFetches.get(completion.id);
		if (!pending) return;
		pendingFetches.delete(completion.id);
		pending.cleanup();
		if (completion.result.ok) pending.resolve(responseFromWire(completion.result.value, pending.signal));
		else pending.reject(hostError(completion.result.error));
	}
	function waitForResponse(ticket, upload, signal) {
		return new Promise((resolve, reject) => {
			function abort() {
				if (upload !== null) endUpload(upload, signal.reason);
				if (!pendingFetches.delete(ticket)) return;
				try {
					dispatch("fetch.cancel", ticket);
				} catch {}
				signal.removeEventListener("abort", abort);
				reject(signal.reason);
			}
			pendingFetches.set(ticket, {
				resolve,
				reject,
				signal,
				cleanup: () => signal.removeEventListener("abort", abort)
			});
			signal.addEventListener("abort", abort, { once: true });
			if (signal.aborted) abort();
		});
	}
	async function hostFetch(input, init, service) {
		const request = new Request(input, init);
		request.signal.throwIfAborted();
		const streams = globalThis.__fetchletStreamsBody?.(request) === true && request.body !== null;
		if (streams && request.body.locked) throw new TypeError("Request body is already used");
		const limits = dispatch("fetch.limits", null);
		const body = streams ? null : await readRequestBody(request, limits);
		request.signal.throwIfAborted();
		const started = dispatch("fetch.start", {
			service: service ?? null,
			redirect: request.redirect,
			upload: streams,
			request: {
				url: request.url,
				method: request.method,
				headers: Array.from(request.headers),
				body: body === null ? null : putBytes(body)
			}
		});
		if (started.upload !== null) uploads.set(started.upload, request.body.getReader());
		return waitForResponse(started.ticket, started.upload, request.signal);
	}
	// js-src/host-bridge/places.ts
	/** Put `item` at `path` in `root`, returning the new root. */
	function placeAt(root, path, item) {
		const key = path[path.length - 1];
		if (key === void 0) return item;
		let parent = root;
		for (const token of path.slice(0, -1)) parent = parent[token];
		Object.defineProperty(parent, key, {
			value: item,
			writable: true,
			enumerable: true,
			configurable: true
		});
		return root;
	}
	/** The channel object of a channel Rust lent, built by the Web API profile. */
	function lentChannel(channel) {
		const views = globalThis.__fetchletChannelViews;
		if (!views?.lend) throw new TypeError("Channels need the fetchlet Web API profile");
		return views.lend(channel);
	}
	function isBinary(value) {
		return ArrayBuffer.isView(value) || value instanceof ArrayBuffer;
	}
	/**
	* `value` as JSON.stringify encodes it, except that each ArrayBuffer or view
	* becomes null and is listed with its path instead. With `whole`, `value`
	* itself may be one.
	*/
	function encodeWithBytes(value, whole) {
		const parts = [];
		const paths = /* @__PURE__ */ new WeakMap();
		return {
			json: JSON.stringify(value, function(key, item) {
				const holder = this;
				const parent = paths.get(holder);
				const path = parent === void 0 ? [] : [...parent, key];
				const raw = holder[key];
				if ((whole || path.length > 0) && isBinary(raw)) {
					const bytes = ArrayBuffer.isView(raw) ? new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength) : new Uint8Array(raw);
					parts.push({
						path,
						bytes
					});
					return null;
				}
				if (typeof item === "object" && item !== null) paths.set(item, path);
				return item;
			}),
			parts
		};
	}
	/**
	* Store the byte arrays of `parts` as one buffer and return its layout, or
	* null for none. Call it right before the message that carries the layout:
	* the byte store keeps one buffer from JavaScript at a time.
	*/
	function storeParts(parts) {
		if (parts.length === 0) return null;
		const buffer = new Uint8Array(parts.reduce((total, part) => total + part.bytes.byteLength, 0));
		let offset = 0;
		for (const part of parts) {
			buffer.set(part.bytes, offset);
			offset += part.bytes.byteLength;
		}
		const layout = parts.map((part) => ({
			path: part.path,
			length: part.bytes.byteLength
		}));
		return {
			handle: putBytes(buffer),
			parts: layout
		};
	}
	// js-src/host-bridge/functions.ts
	const pendingCalls = /* @__PURE__ */ new Map();
	function hasPendingCalls() {
		return pendingCalls.size > 0;
	}
	function functionError(error, binding, method) {
		switch (error.kind) {
			case "arguments": return /* @__PURE__ */ new TypeError(`Invalid arguments for ${binding}.${method}`);
			case "application": {
				const failure = new Error(error.message);
				if (error.code !== null) failure.code = error.code;
				return failure;
			}
			default: return hostError({
				code: error.code ?? "TRANSPORT",
				message: error.message
			});
		}
	}
	/** The call's value, with the byte arrays and channels Rust placed in it. */
	function settle(outcome, binding, method) {
		if (!outcome.ok) throw functionError(outcome.error, binding, method);
		const bytes = outcome.bytes.map(({ path, handle }) => ({
			path,
			item: takeBytes(handle)
		}));
		let value = outcome.value;
		for (const { path, item } of bytes) value = placeAt(value, path, item);
		for (const { path, channel } of outcome.channels) value = placeAt(value, path, lentChannel(channel));
		return value;
	}
	/** Settle the call a completion belongs to; false if it is not a call. */
	function completeCall(completion) {
		const pending = pendingCalls.get(completion.id);
		if (!pending) return false;
		pendingCalls.delete(completion.id);
		try {
			pending.resolve(settle(completion.result, pending.binding, pending.method));
		} catch (error) {
			pending.reject(error);
		}
		return true;
	}
	/**
	* The call message. Arguments cross as JSON.stringify encodes them, so
	* undefined becomes null and a value it cannot encode, such as a BigInt,
	* throws its TypeError; each ArrayBuffer or view becomes null instead, and
	* its bytes travel in one buffer of the byte store, cut into parts by path.
	*/
	function callMessage(binding, method, args) {
		const { json, parts } = encodeWithBytes(args, false);
		let message = `{"binding":${JSON.stringify(binding)},"method":${JSON.stringify(method)},"args":${json}`;
		const layout = storeParts(parts);
		if (layout !== null) message += `,"bytes":${JSON.stringify(layout)}`;
		return `${message}}`;
	}
	/** The env value of a function binding. */
	function functionBinding(binding, methods) {
		const target = Object.create(null);
		for (const [method, kind] of Object.entries(methods)) target[method] = kind === "sync" ? (...args) => settle(dispatchJson("function.call", callMessage(binding, method, args)), binding, method) : (...args) => new Promise((resolve, reject) => {
			const ticket = dispatchJson("function.start", callMessage(binding, method, args));
			pendingCalls.set(ticket, {
				binding,
				method,
				resolve,
				reject
			});
		});
		return Object.freeze(target);
	}
	// js-src/host-bridge/response-bodies.ts
	const responseBodies = /* @__PURE__ */ new Map();
	let nextResponseBody = 1;
	let streamingCall = false;
	const nextTurn = Symbol("nextTurn");
	const coalesceBytes = 65536;
	function responseChunk(value) {
		if (!(value instanceof Uint8Array)) throw new TypeError("Response body must contain byte chunks");
		return value;
	}
	function afterQueuedJobs(timers) {
		return new Promise((resolve) => {
			if (typeof globalThis.setTimeout === "function") timers.push(globalThis.setTimeout(() => resolve(nextTurn), 0));
			else resolve(nextTurn);
		});
	}
	async function drain(entry, waitForData) {
		const chunks = [];
		let byteLength = 0;
		let done = false;
		const timers = [];
		try {
			while (byteLength < coalesceBytes) {
				entry.pending ??= entry.reader.read();
				const result = waitForData && byteLength === 0 ? await entry.pending : await Promise.race([entry.pending, afterQueuedJobs(timers)]);
				if (result === nextTurn) break;
				entry.pending = null;
				if (result.done) {
					done = true;
					break;
				}
				const chunk = responseChunk(result.value);
				if (chunk.byteLength > 0) {
					chunks.push(chunk);
					byteLength += chunk.byteLength;
				}
			}
		} finally {
			for (const timer of timers) globalThis.clearTimeout?.(timer);
		}
		const bytes = new Uint8Array(byteLength);
		let offset = 0;
		for (const chunk of chunks) {
			bytes.set(chunk, offset);
			offset += chunk.byteLength;
		}
		return {
			chunk: bytes,
			done
		};
	}
	const responseBodyRegistry = Object.freeze({
		beginCall(streaming) {
			responseBodyRegistry.closeAll();
			clearPendingReads();
			backgroundRegistry.clear();
			streamingCall = streaming;
		},
		endCall() {
			streamingCall = false;
		},
		streaming() {
			return streamingCall;
		},
		openCount() {
			return responseBodies.size;
		},
		register(stream) {
			const id = nextResponseBody++;
			responseBodies.set(id, {
				reader: stream.getReader(),
				pending: null
			});
			return id;
		},
		async pull(id, waitForData) {
			const entry = responseBodies.get(id);
			if (!entry) throw new TypeError("Unknown response body");
			try {
				const result = await drain(entry, waitForData);
				if (result.done) responseBodies.delete(id);
				return result;
			} catch (error) {
				responseBodies.delete(id);
				throw error;
			}
		},
		async cancel(id) {
			const entry = responseBodies.get(id);
			responseBodies.delete(id);
			await entry?.reader.cancel().catch(() => {});
		},
		retain(id) {
			for (const [key, entry] of responseBodies) if (key !== id) {
				responseBodies.delete(key);
				entry.reader.cancel().catch(() => {});
			}
			return id !== void 0 && responseBodies.has(id);
		},
		closeAll() {
			for (const entry of responseBodies.values()) entry.reader.cancel().catch(() => {});
			responseBodies.clear();
		}
	});
	// js-src/host-bridge/invocation.ts
	let requestAbort = null;
	function abortRequest() {
		const controller = requestAbort;
		requestAbort = null;
		controller?.abort();
	}
	/** Abort the request signal if the client left. Returns whether it did. */
	function abortIfDisconnected() {
		if (requestAbort !== null && dispatch("invocation.disconnected", null)) {
			abortRequest();
			return true;
		}
		return false;
	}
	function clearInvocation() {
		requestAbort = null;
		responseBodyRegistry.closeAll();
		if (backgroundRegistry.pending() === 0) {
			channelRegistry.closeAll();
			globalThis.__fetchletClearTimers?.();
			globalThis.__fetchletClearPerformanceEntries?.();
		}
	}
	/** Put each byte array and channel Rust placed in the arguments there. */
	function placeArguments(argumentsList, places) {
		const items = [...places.bytes.map(({ path, handle }) => ({
			path,
			item: takeBytes(handle)
		})), ...places.channels.map(({ path, channel }) => ({
			path,
			item: lentChannel(channel)
		}))];
		for (const { path, item } of items) {
			if (path.length === 0) throw new TypeError("A placed argument needs a place in the arguments");
			placeAt(argumentsList, path, item);
		}
	}
	/**
	* The result of a call that Rust reads with its byte arrays: the JSON of the
	* value, each ArrayBuffer or view in it null, and the layout of their bytes.
	*/
	function callResult(result) {
		const { json, parts } = encodeWithBytes(result, true);
		if (json === void 0) throw new TypeError("Result is not JSON serializable");
		const layout = storeParts(parts);
		return layout === null ? `{"value":${json}}` : `{"value":${json},"bytes":${JSON.stringify(layout)}}`;
	}
	async function invokeExport(exportName, argumentsList, streamResponseBody, places = {
		bytes: [],
		channels: []
	}, resultBytes = false) {
		globalThis.__fetchletAsyncContext?.set(void 0);
		const exports = globalThis.fetchletExports;
		let invocationRemainsOpen = false;
		responseBodyRegistry.beginCall(streamResponseBody === true);
		channelRegistry.closeAll();
		try {
			if (!Object.hasOwn(exports, exportName)) throw new TypeError("Unknown function");
			const exportedFunction = exports[exportName];
			if (typeof exportedFunction !== "function") throw new TypeError("Unknown function");
			placeArguments(argumentsList, places);
			if (streamResponseBody === true) {
				const request = argumentsList[0];
				if (typeof globalThis.AbortController === "function" && request !== null) {
					requestAbort = new globalThis.AbortController();
					request.signal = requestAbort.signal;
				}
				if (typeof request?.body === "number") request.body = takeBytes(request.body);
				else if (typeof request?.stream === "number") {
					request.body = hostBodyStream(request.stream);
					delete request.stream;
				}
			}
			let result = await exportedFunction(...argumentsList);
			if (streamResponseBody === true) {
				const body = result?.body;
				if (ArrayBuffer.isView(body) || body instanceof ArrayBuffer) {
					const bytes = ArrayBuffer.isView(body) ? new Uint8Array(body.buffer, body.byteOffset, body.byteLength) : new Uint8Array(body);
					result = {
						...result,
						body: putBytes(bytes)
					};
				}
			}
			if (resultBytes) return callResult(result);
			const serializedResult = JSON.stringify(result);
			if (serializedResult === void 0) throw new TypeError("Result is not JSON serializable");
			if (streamResponseBody === true) {
				const bodyOpen = responseBodyRegistry.retain(result?.stream);
				const connectionOpen = channelRegistry.retain(result?.upgrade);
				invocationRemainsOpen = bodyOpen || connectionOpen;
			}
			return serializedResult;
		} finally {
			responseBodyRegistry.endCall();
			if (!invocationRemainsOpen) clearInvocation();
		}
	}
	async function invokeConnection(channel) {
		globalThis.__fetchletAsyncContext?.set(void 0);
		try {
			await channelRegistry.hold(channel);
			return "null";
		} finally {
			clearInvocation();
		}
	}
	async function invokeResponseBody(operation, bodyId) {
		globalThis.__fetchletAsyncContext?.set(void 0);
		let invocationEnds = true;
		try {
			if (operation === "pull") {
				const result = await responseBodyRegistry.pull(bodyId, true);
				invocationEnds = result.done;
				return JSON.stringify({
					chunk: putBytes(result.chunk),
					done: result.done
				});
			}
			if (operation === "cancel") {
				abortRequest();
				await responseBodyRegistry.cancel(bodyId);
				return "null";
			}
			throw new TypeError("Unknown response body operation");
		} finally {
			if (invocationEnds) clearInvocation();
		}
	}
	// js-src/host-bridge/pump.ts
	/** Returns how many host events it delivered. */
	function pumpHostOperations() {
		const progress = abortIfDisconnected() ? 1 : 0;
		if (!hasPendingFetches() && !hasPendingReads() && !hasPendingCalls() && !hasOpenChannels()) return progress;
		const completions = dispatch("host.poll", null);
		for (const completion of completions) {
			if (completeChannel(completion)) continue;
			if (!completeRead(completion) && !completeCall(completion)) completeFetch(completion);
		}
		return completions.length + progress;
	}
	// js-src/host-bridge/index.ts
	Object.defineProperty(globalThis, "__fetchletClaimHost", {
		value() {
			delete globalThis.__fetchletClaimHost;
			return Object.freeze({
				call: (operation, input) => nativeDispatch(operation, input),
				putBytes: (bytes) => putBytes(bytes),
				takeBytes: (handle) => takeBytes(handle),
				readWholeBody: (stream, text, onValue, onError) => readWholeBody(stream, text, onValue, onError)
			});
		},
		writable: false,
		enumerable: false,
		configurable: true
	});
	const bindings = dispatch("bindings", null);
	Object.defineProperty(globalThis, "__fetchletHostBodies", {
		value: Object.freeze({ stream: hostBodyStream }),
		writable: false,
		configurable: false
	});
	Object.defineProperty(globalThis, "__fetchletResponseBodies", {
		value: responseBodyRegistry,
		writable: false,
		configurable: false
	});
	Object.defineProperty(globalThis, "__fetchletChannels", {
		value: channelRegistry,
		writable: false,
		configurable: false
	});
	Object.defineProperty(globalThis, "__fetchletBackground", {
		value: backgroundRegistry,
		writable: false,
		configurable: false
	});
	Object.defineProperty(globalThis, "__fetchletInvocation", {
		value: Object.freeze({
			call: invokeExport,
			responseBody: invokeResponseBody,
			connection: invokeConnection
		}),
		writable: false,
		configurable: false
	});
	if (bindings.console) installConsole();
	const env = Object.assign(Object.create(null), bindings.env);
	for (const serviceName of bindings.services) env[serviceName] = Object.freeze({ fetch: (input, init) => hostFetch(input, init, serviceName) });
	for (const channelName of bindings.channels) env[channelName] = Object.freeze({ connect(options) {
		const views = globalThis.__fetchletChannelViews;
		if (!views) throw new TypeError("Channels need the fetchlet Web API profile");
		return views.connect(channelName, options);
	} });
	for (const [functionsName, methods] of Object.entries(bindings.functions)) env[functionsName] = functionBinding(functionsName, methods);
	Object.defineProperty(globalThis, "fetchlet", {
		value: Object.freeze({
			env: Object.freeze(env),
			waitUntil
		}),
		writable: false,
		configurable: false
	});
	if (bindings.processEnv && Object.keys(bindings.processEnv).length > 0) Object.defineProperty(globalThis, "__fetchletProcessEnv", {
		value: Object.freeze(Object.assign(Object.create(null), bindings.processEnv)),
		writable: false,
		enumerable: false,
		configurable: false
	});
	Object.defineProperty(globalThis, "__fetchletPumpHost", {
		value: pumpHostOperations,
		writable: false,
		configurable: false
	});
	Object.defineProperty(globalThis, "fetch", {
		value: (input, init) => hostFetch(input, init),
		writable: true,
		enumerable: true,
		configurable: true
	});
})();