import { errorPlugin, wrapFetch } from "../_chunks/_plugins.mjs";
const FastURL = URL;
const FastResponse = Response;
function serve(options) {
	return new CloudflareServer(options);
}
var CloudflareServer = class {
	runtime = "cloudflare";
	options;
	serveOptions;
	fetch;
	#fetchListener;
	constructor(options) {
		this.options = {
			...options,
			middleware: [...options.middleware || []]
		};
		for (const plugin of options.plugins || []) plugin(this);
		errorPlugin(this);
		const fetchHandler = wrapFetch(this);
		this.fetch = (request, env, context) => {
			Object.defineProperties(request, {
				waitUntil: { value: context.waitUntil.bind(context) },
				runtime: {
					enumerable: true,
					value: {
						name: "cloudflare",
						cloudflare: {
							env,
							context
						}
					}
				},
				ip: {
					enumerable: true,
					configurable: true,
					get() {
						return request.headers.get("cf-connecting-ip");
					}
				}
			});
			return fetchHandler(request);
		};
		this.serveOptions = { fetch: this.fetch };
		if (!options.manual) this.serve();
	}
	serve() {
		if (this.#fetchListener) return;
		this.#fetchListener = (event) => {
			event.respondWith(this.fetch(event.request, event.env || {}, event));
		};
		addEventListener("fetch", this.#fetchListener);
	}
	ready() {
		return Promise.resolve().then(() => this);
	}
	close() {
		if (this.#fetchListener) {
			removeEventListener("fetch", this.#fetchListener);
			this.#fetchListener = void 0;
		}
		return Promise.resolve();
	}
};
export { FastResponse, FastURL, serve };
