@agentcomms/whatsapp 0.7.0

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.
@@ -0,0 +1,102 @@
1
+ import { i as serializeMessage, n as process, r as ReadBuffer } from "./mcp-DXXb3Vv3-Co5BzjYe.mjs";
2
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs
3
+ /**
4
+ * Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`.
5
+ *
6
+ * This transport is only available in Node.js environments.
7
+ *
8
+ * @example
9
+ * ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage"
10
+ * const server = new McpServer({ name: 'my-server', version: '1.0.0' });
11
+ * const transport = new StdioServerTransport();
12
+ * await server.connect(transport);
13
+ * ```
14
+ */
15
+ var StdioServerTransport = class {
16
+ _readBuffer;
17
+ _started = false;
18
+ _closed = false;
19
+ constructor(_stdin = process.stdin, _stdout = process.stdout, options) {
20
+ this._stdin = _stdin;
21
+ this._stdout = _stdout;
22
+ this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize });
23
+ }
24
+ onclose;
25
+ onerror;
26
+ onmessage;
27
+ _ondata = (chunk) => {
28
+ try {
29
+ this._readBuffer.append(chunk);
30
+ this.processReadBuffer();
31
+ } catch (error) {
32
+ this.onerror?.(error);
33
+ this.close().catch(() => {});
34
+ }
35
+ };
36
+ _onerror = (error) => {
37
+ this.onerror?.(error);
38
+ };
39
+ _onstdouterror = (error) => {
40
+ this.onerror?.(error);
41
+ this.close().catch(() => {});
42
+ };
43
+ /**
44
+ * Starts listening for messages on `stdin`.
45
+ */
46
+ async start() {
47
+ if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
48
+ this._started = true;
49
+ this._stdin.on("data", this._ondata);
50
+ this._stdin.on("error", this._onerror);
51
+ this._stdout.on("error", this._onstdouterror);
52
+ }
53
+ processReadBuffer() {
54
+ while (true) try {
55
+ const message = this._readBuffer.readMessage();
56
+ if (message === null) break;
57
+ this.onmessage?.(message);
58
+ } catch (error) {
59
+ this.onerror?.(error);
60
+ }
61
+ }
62
+ async close() {
63
+ if (this._closed) return;
64
+ this._closed = true;
65
+ this._stdin.off("data", this._ondata);
66
+ this._stdin.off("error", this._onerror);
67
+ this._stdout.off("error", this._onstdouterror);
68
+ if (this._stdin.listenerCount("data") === 0) this._stdin.pause();
69
+ this._readBuffer.clear();
70
+ this.onclose?.();
71
+ }
72
+ send(message) {
73
+ if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed"));
74
+ return new Promise((resolve, reject) => {
75
+ const json = serializeMessage(message);
76
+ let settled = false;
77
+ const onError = (error) => {
78
+ if (settled) return;
79
+ settled = true;
80
+ this._stdout.off("error", onError);
81
+ this._stdout.off("drain", onDrain);
82
+ reject(error);
83
+ };
84
+ const onDrain = () => {
85
+ if (settled) return;
86
+ settled = true;
87
+ this._stdout.off("error", onError);
88
+ this._stdout.off("drain", onDrain);
89
+ resolve();
90
+ };
91
+ this._stdout.once("error", onError);
92
+ if (this._stdout.write(json)) {
93
+ if (settled) return;
94
+ settled = true;
95
+ this._stdout.off("error", onError);
96
+ resolve();
97
+ } else if (!settled) this._stdout.once("drain", onDrain);
98
+ });
99
+ }
100
+ };
101
+ //#endregion
102
+ export { StdioServerTransport };
@@ -0,0 +1,607 @@
1
+ import { a as ReadBuffer, c as SdkErrorCode, k as serializeMessage, s as SdkError } from "./src-D_zzAWoS-BhK0GFdq-XAvBzdGB.mjs";
2
+ import { createRequire } from "node:module";
3
+ import process$1 from "node:process";
4
+ import { PassThrough } from "node:stream";
5
+ //#region ../core/dist/stdio-CHZ2WRcx.mjs
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
15
+ key = keys[i];
16
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
17
+ get: ((k) => from[k]).bind(null, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
27
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
28
+ var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
29
+ module.exports = isexe;
30
+ isexe.sync = sync;
31
+ var fs$2 = __require("fs");
32
+ function checkPathExt(path, options) {
33
+ var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
34
+ if (!pathext) return true;
35
+ pathext = pathext.split(";");
36
+ if (pathext.indexOf("") !== -1) return true;
37
+ for (var i = 0; i < pathext.length; i++) {
38
+ var p = pathext[i].toLowerCase();
39
+ if (p && path.substr(-p.length).toLowerCase() === p) return true;
40
+ }
41
+ return false;
42
+ }
43
+ function checkStat(stat, path, options) {
44
+ if (!stat.isSymbolicLink() && !stat.isFile()) return false;
45
+ return checkPathExt(path, options);
46
+ }
47
+ function isexe(path, options, cb) {
48
+ fs$2.stat(path, function(er, stat) {
49
+ cb(er, er ? false : checkStat(stat, path, options));
50
+ });
51
+ }
52
+ function sync(path, options) {
53
+ return checkStat(fs$2.statSync(path), path, options);
54
+ }
55
+ }));
56
+ var require_mode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
57
+ module.exports = isexe;
58
+ isexe.sync = sync;
59
+ var fs$1 = __require("fs");
60
+ function isexe(path, options, cb) {
61
+ fs$1.stat(path, function(er, stat) {
62
+ cb(er, er ? false : checkStat(stat, options));
63
+ });
64
+ }
65
+ function sync(path, options) {
66
+ return checkStat(fs$1.statSync(path), options);
67
+ }
68
+ function checkStat(stat, options) {
69
+ return stat.isFile() && checkMode(stat, options);
70
+ }
71
+ function checkMode(stat, options) {
72
+ var mod = stat.mode;
73
+ var uid = stat.uid;
74
+ var gid = stat.gid;
75
+ var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
76
+ var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
77
+ var u = parseInt("100", 8);
78
+ var g = parseInt("010", 8);
79
+ var o = parseInt("001", 8);
80
+ var ug = u | g;
81
+ return mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
82
+ }
83
+ }));
84
+ var require_isexe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
85
+ __require("fs");
86
+ var core;
87
+ if (process.platform === "win32" || global.TESTING_WINDOWS) core = require_windows();
88
+ else core = require_mode();
89
+ module.exports = isexe;
90
+ isexe.sync = sync;
91
+ function isexe(path, options, cb) {
92
+ if (typeof options === "function") {
93
+ cb = options;
94
+ options = {};
95
+ }
96
+ if (!cb) {
97
+ if (typeof Promise !== "function") throw new TypeError("callback not provided");
98
+ return new Promise(function(resolve, reject) {
99
+ isexe(path, options || {}, function(er, is) {
100
+ if (er) reject(er);
101
+ else resolve(is);
102
+ });
103
+ });
104
+ }
105
+ core(path, options || {}, function(er, is) {
106
+ if (er) {
107
+ if (er.code === "EACCES" || options && options.ignoreErrors) {
108
+ er = null;
109
+ is = false;
110
+ }
111
+ }
112
+ cb(er, is);
113
+ });
114
+ }
115
+ function sync(path, options) {
116
+ try {
117
+ return core.sync(path, options || {});
118
+ } catch (er) {
119
+ if (options && options.ignoreErrors || er.code === "EACCES") return false;
120
+ else throw er;
121
+ }
122
+ }
123
+ }));
124
+ var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
125
+ const isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
126
+ const path$2 = __require("path");
127
+ const COLON = isWindows ? ";" : ":";
128
+ const isexe = require_isexe();
129
+ const getNotFoundError = (cmd) => Object.assign(/* @__PURE__ */ new Error(`not found: ${cmd}`), { code: "ENOENT" });
130
+ const getPathInfo = (cmd, opt) => {
131
+ const colon = opt.colon || COLON;
132
+ const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [...isWindows ? [process.cwd()] : [], ...(opt.path || process.env.PATH ||
133
+ /* istanbul ignore next: very unusual */ "").split(colon)];
134
+ const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
135
+ const pathExt = isWindows ? pathExtExe.split(colon) : [""];
136
+ if (isWindows) {
137
+ if (cmd.indexOf(".") !== -1 && pathExt[0] !== "") pathExt.unshift("");
138
+ }
139
+ return {
140
+ pathEnv,
141
+ pathExt,
142
+ pathExtExe
143
+ };
144
+ };
145
+ const which = (cmd, opt, cb) => {
146
+ if (typeof opt === "function") {
147
+ cb = opt;
148
+ opt = {};
149
+ }
150
+ if (!opt) opt = {};
151
+ const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
152
+ const found = [];
153
+ const step = (i) => new Promise((resolve, reject) => {
154
+ if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
155
+ const ppRaw = pathEnv[i];
156
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
157
+ const pCmd = path$2.join(pathPart, cmd);
158
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
159
+ resolve(subStep(p, i, 0));
160
+ });
161
+ const subStep = (p, i, ii) => new Promise((resolve, reject) => {
162
+ if (ii === pathExt.length) return resolve(step(i + 1));
163
+ const ext = pathExt[ii];
164
+ isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
165
+ if (!er && is) {
166
+ if (opt.all) found.push(p + ext);
167
+ else return resolve(p + ext);
168
+ }
169
+ return resolve(subStep(p, i, ii + 1));
170
+ });
171
+ });
172
+ return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
173
+ };
174
+ const whichSync = (cmd, opt) => {
175
+ opt = opt || {};
176
+ const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
177
+ const found = [];
178
+ for (let i = 0; i < pathEnv.length; i++) {
179
+ const ppRaw = pathEnv[i];
180
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
181
+ const pCmd = path$2.join(pathPart, cmd);
182
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
183
+ for (let j = 0; j < pathExt.length; j++) {
184
+ const cur = p + pathExt[j];
185
+ try {
186
+ if (isexe.sync(cur, { pathExt: pathExtExe })) {
187
+ if (opt.all) found.push(cur);
188
+ else return cur;
189
+ }
190
+ } catch (ex) {}
191
+ }
192
+ }
193
+ if (opt.all && found.length) return found;
194
+ if (opt.nothrow) return null;
195
+ throw getNotFoundError(cmd);
196
+ };
197
+ module.exports = which;
198
+ which.sync = whichSync;
199
+ }));
200
+ var require_path_key = /* @__PURE__ */ __commonJSMin(((exports, module) => {
201
+ const pathKey = (options = {}) => {
202
+ const environment = options.env || process.env;
203
+ if ((options.platform || process.platform) !== "win32") return "PATH";
204
+ return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
205
+ };
206
+ module.exports = pathKey;
207
+ module.exports.default = pathKey;
208
+ }));
209
+ var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
210
+ const path$1 = __require("path");
211
+ const which = require_which();
212
+ const getPathKey = require_path_key();
213
+ function resolveCommandAttempt(parsed, withoutPathExt) {
214
+ const env = parsed.options.env || process.env;
215
+ const cwd = process.cwd();
216
+ const hasCustomCwd = parsed.options.cwd != null;
217
+ const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
218
+ if (shouldSwitchCwd) try {
219
+ process.chdir(parsed.options.cwd);
220
+ } catch (err) {}
221
+ let resolved;
222
+ try {
223
+ resolved = which.sync(parsed.command, {
224
+ path: env[getPathKey({ env })],
225
+ pathExt: withoutPathExt ? path$1.delimiter : void 0
226
+ });
227
+ } catch (e) {} finally {
228
+ if (shouldSwitchCwd) process.chdir(cwd);
229
+ }
230
+ if (resolved) resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
231
+ return resolved;
232
+ }
233
+ function resolveCommand(parsed) {
234
+ return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
235
+ }
236
+ module.exports = resolveCommand;
237
+ }));
238
+ var require_escape = /* @__PURE__ */ __commonJSMin(((exports, module) => {
239
+ const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
240
+ function escapeCommand(arg) {
241
+ arg = arg.replace(metaCharsRegExp, "^$1");
242
+ return arg;
243
+ }
244
+ function escapeArgument(arg, doubleEscapeMetaChars) {
245
+ arg = `${arg}`;
246
+ arg = arg.replace(/(?=(\\+?)?)\1"/g, "$1$1\\\"");
247
+ arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
248
+ arg = `"${arg}"`;
249
+ arg = arg.replace(metaCharsRegExp, "^$1");
250
+ if (doubleEscapeMetaChars) arg = arg.replace(metaCharsRegExp, "^$1");
251
+ return arg;
252
+ }
253
+ module.exports.command = escapeCommand;
254
+ module.exports.argument = escapeArgument;
255
+ }));
256
+ var require_shebang_regex = /* @__PURE__ */ __commonJSMin(((exports, module) => {
257
+ module.exports = /^#!(.*)/;
258
+ }));
259
+ var require_shebang_command = /* @__PURE__ */ __commonJSMin(((exports, module) => {
260
+ const shebangRegex = require_shebang_regex();
261
+ module.exports = (string = "") => {
262
+ const match = string.match(shebangRegex);
263
+ if (!match) return null;
264
+ const [path, argument] = match[0].replace(/#! ?/, "").split(" ");
265
+ const binary = path.split("/").pop();
266
+ if (binary === "env") return argument;
267
+ return argument ? `${binary} ${argument}` : binary;
268
+ };
269
+ }));
270
+ var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
271
+ const fs = __require("fs");
272
+ const shebangCommand = require_shebang_command();
273
+ function readShebang(command) {
274
+ const size = 150;
275
+ const buffer = Buffer.alloc(size);
276
+ let fd;
277
+ try {
278
+ fd = fs.openSync(command, "r");
279
+ fs.readSync(fd, buffer, 0, size, 0);
280
+ fs.closeSync(fd);
281
+ } catch (e) {}
282
+ return shebangCommand(buffer.toString());
283
+ }
284
+ module.exports = readShebang;
285
+ }));
286
+ var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
287
+ const path = __require("path");
288
+ const resolveCommand = require_resolveCommand();
289
+ const escape = require_escape();
290
+ const readShebang = require_readShebang();
291
+ const isWin = process.platform === "win32";
292
+ const isExecutableRegExp = /\.(?:com|exe)$/i;
293
+ const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
294
+ function detectShebang(parsed) {
295
+ parsed.file = resolveCommand(parsed);
296
+ const shebang = parsed.file && readShebang(parsed.file);
297
+ if (shebang) {
298
+ parsed.args.unshift(parsed.file);
299
+ parsed.command = shebang;
300
+ return resolveCommand(parsed);
301
+ }
302
+ return parsed.file;
303
+ }
304
+ function parseNonShell(parsed) {
305
+ if (!isWin) return parsed;
306
+ const commandFile = detectShebang(parsed);
307
+ const needsShell = !isExecutableRegExp.test(commandFile);
308
+ if (parsed.options.forceShell || needsShell) {
309
+ const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
310
+ parsed.command = path.normalize(parsed.command);
311
+ parsed.command = escape.command(parsed.command);
312
+ parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
313
+ parsed.args = [
314
+ "/d",
315
+ "/s",
316
+ "/c",
317
+ `"${[parsed.command].concat(parsed.args).join(" ")}"`
318
+ ];
319
+ parsed.command = process.env.comspec || "cmd.exe";
320
+ parsed.options.windowsVerbatimArguments = true;
321
+ }
322
+ return parsed;
323
+ }
324
+ function parse(command, args, options) {
325
+ if (args && !Array.isArray(args)) {
326
+ options = args;
327
+ args = null;
328
+ }
329
+ args = args ? args.slice(0) : [];
330
+ options = Object.assign({}, options);
331
+ const parsed = {
332
+ command,
333
+ args,
334
+ options,
335
+ file: void 0,
336
+ original: {
337
+ command,
338
+ args
339
+ }
340
+ };
341
+ return options.shell ? parsed : parseNonShell(parsed);
342
+ }
343
+ module.exports = parse;
344
+ }));
345
+ var require_enoent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
346
+ const isWin = process.platform === "win32";
347
+ function notFoundError(original, syscall) {
348
+ return Object.assign(/* @__PURE__ */ new Error(`${syscall} ${original.command} ENOENT`), {
349
+ code: "ENOENT",
350
+ errno: "ENOENT",
351
+ syscall: `${syscall} ${original.command}`,
352
+ path: original.command,
353
+ spawnargs: original.args
354
+ });
355
+ }
356
+ function hookChildProcess(cp, parsed) {
357
+ if (!isWin) return;
358
+ const originalEmit = cp.emit;
359
+ cp.emit = function(name, arg1) {
360
+ if (name === "exit") {
361
+ const err = verifyENOENT(arg1, parsed);
362
+ if (err) return originalEmit.call(cp, "error", err);
363
+ }
364
+ return originalEmit.apply(cp, arguments);
365
+ };
366
+ }
367
+ function verifyENOENT(status, parsed) {
368
+ if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawn");
369
+ return null;
370
+ }
371
+ function verifyENOENTSync(status, parsed) {
372
+ if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawnSync");
373
+ return null;
374
+ }
375
+ module.exports = {
376
+ hookChildProcess,
377
+ verifyENOENT,
378
+ verifyENOENTSync,
379
+ notFoundError
380
+ };
381
+ }));
382
+ var import_cross_spawn = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
383
+ const cp = __require("child_process");
384
+ const parse = require_parse();
385
+ const enoent = require_enoent();
386
+ function spawn(command, args, options) {
387
+ const parsed = parse(command, args, options);
388
+ const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
389
+ enoent.hookChildProcess(spawned, parsed);
390
+ return spawned;
391
+ }
392
+ function spawnSync(command, args, options) {
393
+ const parsed = parse(command, args, options);
394
+ const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
395
+ result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
396
+ return result;
397
+ }
398
+ module.exports = spawn;
399
+ module.exports.spawn = spawn;
400
+ module.exports.sync = spawnSync;
401
+ module.exports._parse = parse;
402
+ module.exports._enoent = enoent;
403
+ })))(), 1);
404
+ /**
405
+ * Environment variables to inherit by default, if an environment is not explicitly given.
406
+ */
407
+ const DEFAULT_INHERITED_ENV_VARS = process$1.platform === "win32" ? [
408
+ "APPDATA",
409
+ "HOMEDRIVE",
410
+ "HOMEPATH",
411
+ "LOCALAPPDATA",
412
+ "PATH",
413
+ "PROCESSOR_ARCHITECTURE",
414
+ "SYSTEMDRIVE",
415
+ "SYSTEMROOT",
416
+ "TEMP",
417
+ "USERNAME",
418
+ "USERPROFILE",
419
+ "PROGRAMFILES"
420
+ ] : [
421
+ "HOME",
422
+ "LOGNAME",
423
+ "PATH",
424
+ "SHELL",
425
+ "TERM",
426
+ "USER"
427
+ ];
428
+ /**
429
+ * Returns a default environment object including only environment variables deemed safe to inherit.
430
+ */
431
+ function getDefaultEnvironment() {
432
+ const env = {};
433
+ for (const key of DEFAULT_INHERITED_ENV_VARS) {
434
+ const value = process$1.env[key];
435
+ if (value === void 0) continue;
436
+ if (value.startsWith("()")) continue;
437
+ env[key] = value;
438
+ }
439
+ return env;
440
+ }
441
+ /**
442
+ * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout.
443
+ *
444
+ * This transport is only available in Node.js environments.
445
+ */
446
+ var StdioClientTransport = class {
447
+ _process;
448
+ _readBuffer;
449
+ _serverParams;
450
+ _stderrStream = null;
451
+ onclose;
452
+ onerror;
453
+ onmessage;
454
+ constructor(server) {
455
+ this._serverParams = server;
456
+ this._readBuffer = new ReadBuffer({ maxBufferSize: server.maxBufferSize });
457
+ if (server.stderr === "pipe" || server.stderr === "overlapped") this._stderrStream = new PassThrough();
458
+ }
459
+ /**
460
+ * Starts the server process and prepares to communicate with it.
461
+ */
462
+ async start() {
463
+ if (this._process) throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");
464
+ return new Promise((resolve, reject) => {
465
+ this._process = (0, import_cross_spawn.default)(this._serverParams.command, this._serverParams.args ?? [], {
466
+ env: {
467
+ ...getDefaultEnvironment(),
468
+ ...this._serverParams.env
469
+ },
470
+ stdio: [
471
+ "pipe",
472
+ "pipe",
473
+ this._serverParams.stderr ?? "inherit"
474
+ ],
475
+ shell: false,
476
+ windowsHide: process$1.platform === "win32",
477
+ cwd: this._serverParams.cwd
478
+ });
479
+ this._process.on("error", (error) => {
480
+ reject(error);
481
+ this.onerror?.(error);
482
+ });
483
+ this._process.on("spawn", () => {
484
+ resolve();
485
+ });
486
+ this._process.on("close", (_code) => {
487
+ this._process = void 0;
488
+ this.onclose?.();
489
+ });
490
+ this._process.stdin?.on("error", (error) => {
491
+ this.onerror?.(error);
492
+ });
493
+ this._process.stdout?.on("data", (chunk) => {
494
+ try {
495
+ this._readBuffer.append(chunk);
496
+ this.processReadBuffer();
497
+ } catch (error) {
498
+ this.onerror?.(error);
499
+ this.close().catch(() => {});
500
+ }
501
+ });
502
+ this._process.stdout?.on("error", (error) => {
503
+ this.onerror?.(error);
504
+ });
505
+ if (this._stderrStream && this._process.stderr) this._process.stderr.pipe(this._stderrStream);
506
+ });
507
+ }
508
+ /**
509
+ * The `stderr` stream of the child process, if {@linkcode StdioServerParameters.stderr} was set to `"pipe"` or `"overlapped"`.
510
+ *
511
+ * If `stderr` piping was requested, a `PassThrough` stream is returned _immediately_, allowing callers to
512
+ * attach listeners before the `start` method is invoked. This prevents loss of any early
513
+ * error output emitted by the child process.
514
+ */
515
+ get stderr() {
516
+ if (this._stderrStream) return this._stderrStream;
517
+ return this._process?.stderr ?? null;
518
+ }
519
+ /**
520
+ * The child process pid spawned by this transport.
521
+ *
522
+ * This is only available after the transport has been started.
523
+ */
524
+ get pid() {
525
+ return this._process?.pid ?? null;
526
+ }
527
+ processReadBuffer() {
528
+ while (true) try {
529
+ const message = this._readBuffer.readMessage();
530
+ if (message === null) break;
531
+ this.onmessage?.(message);
532
+ } catch (error) {
533
+ this.onerror?.(error);
534
+ }
535
+ }
536
+ /**
537
+ * Reap a disposable probe sibling (see the version-negotiation sibling
538
+ * flow): signal-first teardown awaiting process `exit` — never the `close`
539
+ * event, so a helper process holding the child's stdio pipes can never
540
+ * block disposal. Not part of the public transport lifecycle.
541
+ *
542
+ * @internal
543
+ */
544
+ async _dispose() {
545
+ const proc = this._process;
546
+ this._process = void 0;
547
+ if (proc && proc.exitCode === null && proc.signalCode === null) {
548
+ const exited = new Promise((resolve) => proc.once("exit", () => resolve()));
549
+ try {
550
+ proc.stdin?.end();
551
+ } catch {}
552
+ try {
553
+ proc.kill("SIGTERM");
554
+ } catch {}
555
+ await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 1e3).unref())]);
556
+ if (proc.exitCode === null && proc.signalCode === null) try {
557
+ proc.kill("SIGKILL");
558
+ } catch {}
559
+ await exited;
560
+ }
561
+ try {
562
+ proc?.stdout?.destroy();
563
+ } catch {}
564
+ try {
565
+ proc?.stdin?.destroy();
566
+ } catch {}
567
+ try {
568
+ proc?.stderr?.destroy();
569
+ } catch {}
570
+ this._readBuffer.clear();
571
+ }
572
+ async close() {
573
+ if (this._process) {
574
+ const processToClose = this._process;
575
+ this._process = void 0;
576
+ const closePromise = new Promise((resolve) => {
577
+ processToClose.once("close", () => {
578
+ resolve();
579
+ });
580
+ });
581
+ try {
582
+ processToClose.stdin?.end();
583
+ } catch {}
584
+ await Promise.race([closePromise, new Promise((resolve) => setTimeout(resolve, 2e3).unref())]);
585
+ if (processToClose.exitCode === null) {
586
+ try {
587
+ processToClose.kill("SIGTERM");
588
+ } catch {}
589
+ await Promise.race([closePromise, new Promise((resolve) => setTimeout(resolve, 2e3).unref())]);
590
+ }
591
+ if (processToClose.exitCode === null) try {
592
+ processToClose.kill("SIGKILL");
593
+ } catch {}
594
+ }
595
+ this._readBuffer.clear();
596
+ }
597
+ send(message) {
598
+ return new Promise((resolve) => {
599
+ if (!this._process?.stdin) throw new SdkError(SdkErrorCode.NotConnected, "Not connected");
600
+ const json = serializeMessage(message);
601
+ if (this._process.stdin.write(json)) resolve();
602
+ else this._process.stdin.once("drain", resolve);
603
+ });
604
+ }
605
+ };
606
+ //#endregion
607
+ export { StdioClientTransport };