import { __commonJSMin as e } from "../../../../_virtual/_rolldown/runtime.js";
import { require_ral as t } from "./ral.js";
import { require_is as n } from "./is.js";
import { require_events as r } from "./events.js";
import { require_semaphore as i } from "./semaphore.js";
//#region ../../node_modules/vscode-jsonrpc/lib/common/messageWriter.js
var a = /* @__PURE__ */ e(((e) => {
	Object.defineProperty(e, "__esModule", { value: !0 }), e.WriteableStreamMessageWriter = e.AbstractMessageWriter = e.MessageWriter = void 0;
	var a = t(), o = n(), s = i(), c = r(), l = "Content-Length: ", u = "\r\n", d;
	(function(e) {
		function t(e) {
			let t = e;
			return t && o.func(t.dispose) && o.func(t.onClose) && o.func(t.onError) && o.func(t.write);
		}
		e.is = t;
	})(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, t, n) {
			this.errorEmitter.fire([
				this.asError(e),
				t,
				n
			]);
		}
		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 t(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 = t;
	})(p ||= {}), e.WriteableStreamMessageWriter = class extends f {
		constructor(e, t) {
			super(), this.writable = e, this.options = p.fromOptions(t), 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((t) => {
				let n = [];
				return n.push(l, t.byteLength.toString(), u), n.push(u), this.doWrite(e, n, t);
			}, (e) => {
				throw this.fireError(e), e;
			}));
		}
		async doWrite(e, t, n) {
			try {
				return await this.writable.write(t.join(""), "ascii"), this.writable.write(n);
			} catch (t) {
				return this.handleError(t, e), Promise.reject(t);
			}
		}
		handleError(e, t) {
			this.errorCount++, this.fireError(e, t, this.errorCount);
		}
		end() {
			this.writable.end();
		}
	};
}));
//#endregion
export default a();
export { a as require_messageWriter };
