import { __commonJSMin } from "../../../../_virtual/rolldown_runtime.js";
import { require_ral } from "./ral.js";
import { require_is } from "./is.js";
import { require_events } from "./events.js";
import { require_semaphore } from "./semaphore.js";
var require_messageWriter = /* @__PURE__ */ __commonJSMin(((e) => {
	Object.defineProperty(e, "__esModule", { value: !0 }), e.WriteableStreamMessageWriter = e.AbstractMessageWriter = e.MessageWriter = void 0;
	var a = require_ral(), o = require_is(), s = require_semaphore(), c = require_events(), l = "Content-Length: ", u = "\r\n", d;
	(function(e) {
		function r(e) {
			let r = e;
			return r && o.func(r.dispose) && o.func(r.onClose) && o.func(r.onError) && o.func(r.write);
		}
		e.is = r;
	})(d || (e.MessageWriter = d = {}));
	var f = class {
		constructor() {
			this.errorEmitter = new c.Emitter(), this.closeEmitter = new c.Emitter();
		}
		dispose() {
			this.errorEmitter.dispose(), this.closeEmitter.dispose();
		}
		get onError() {
			return this.errorEmitter.event;
		}
		fireError(e, r, i) {
			this.errorEmitter.fire([
				this.asError(e),
				r,
				i
			]);
		}
		get onClose() {
			return this.closeEmitter.event;
		}
		fireClose() {
			this.closeEmitter.fire(void 0);
		}
		asError(e) {
			return e instanceof Error ? e : /* @__PURE__ */ Error(`Writer received error. Reason: ${o.string(e.message) ? e.message : "unknown"}`);
		}
	};
	e.AbstractMessageWriter = f;
	var p;
	(function(e) {
		function r(e) {
			return e === void 0 || typeof e == "string" ? {
				charset: e ?? "utf-8",
				contentTypeEncoder: (0, a.default)().applicationJson.encoder
			} : {
				charset: e.charset ?? "utf-8",
				contentEncoder: e.contentEncoder,
				contentTypeEncoder: e.contentTypeEncoder ?? (0, a.default)().applicationJson.encoder
			};
		}
		e.fromOptions = r;
	})(p ||= {}), e.WriteableStreamMessageWriter = class extends f {
		constructor(e, r) {
			super(), this.writable = e, this.options = p.fromOptions(r), this.errorCount = 0, this.writeSemaphore = new s.Semaphore(1), this.writable.onError((e) => this.fireError(e)), this.writable.onClose(() => this.fireClose());
		}
		async write(e) {
			return this.writeSemaphore.lock(async () => this.options.contentTypeEncoder.encode(e, this.options).then((e) => this.options.contentEncoder === void 0 ? e : this.options.contentEncoder.encode(e)).then((r) => {
				let i = [];
				return i.push(l, r.byteLength.toString(), u), i.push(u), this.doWrite(e, i, r);
			}, (e) => {
				throw this.fireError(e), e;
			}));
		}
		async doWrite(e, r, i) {
			try {
				return await this.writable.write(r.join(""), "ascii"), this.writable.write(i);
			} catch (r) {
				return this.handleError(r, e), Promise.reject(r);
			}
		}
		handleError(e, r) {
			this.errorCount++, this.fireError(e, r, this.errorCount);
		}
		end() {
			this.writable.end();
		}
	};
}));
export default require_messageWriter();
export { require_messageWriter };
