import { c as defineEventHandler, g as getQuery } from '../../../_/nitro.mjs';
import { g as getDefaultExportFromCjs } from '../../../virtual/_commonjsHelpers.mjs';
import { r as require$$0$1 } from '../../../virtual/_os.mjs';
import { r as require$$0 } from '../../../virtual/_child_process.mjs';
import { r as require$$0$2 } from '../../../virtual/_path.mjs';
import { f as findProcess } from '../../../_/index2.mjs';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'node:fs';
import 'node:path';
import 'node:crypto';
import 'node:url';
import 'os';
import 'child_process';
import 'fs';
import 'path';

var netstat$1 = {exports: {}};

var activators$1 = {};

var utils$1 = {};

// only care about complete lines, return remainder and let callee handle it
var forEachLine = function (text, handler) {
    var n = text.indexOf('\n');
    while (n > -1) {
        handler(text.substring(0, n));
        text = text.substring(n + 1);
        n = text.indexOf('\n');
    }

    return text;
};

var parseAddress = utils$1.parseAddress = function (raw) {
    var port = null,
        address = null;
    if (raw[0] == '[') {
        port = raw.substring(raw.lastIndexOf(':') + 1);
        address = raw.substring(1, raw.indexOf(']'));
    } else if (raw.indexOf(':') != raw.lastIndexOf(':')) {
        port = raw.substring(raw.lastIndexOf(':') + 1);
        address = raw.substring(0, raw.lastIndexOf(':'));
    } else if (raw.indexOf(':') == raw.lastIndexOf(':') && raw.indexOf(':') != -1) {
        var parts = raw.split(':');
        port = parts[1];
        address = parts[0] || null;
    } else if (raw.indexOf('.') != raw.lastIndexOf('.')) {
        port = raw.substring(raw.lastIndexOf('.') + 1);
        address = raw.substring(0, raw.lastIndexOf('.'));
    }

    if (address && (address == '::' || address == '0.0.0.0')) {
        address = null;
    }

    return {
        port: port ? parseInt(port) : null,
        address: address
    };
};

utils$1.normalizeValues = function (item) {
    item.protocol = item.protocol.toLowerCase();
    var parts = item.local.split(':');
    item.local = parseAddress(item.local);
    item.remote = parseAddress(item.remote);

    if (item.protocol == 'tcp' && item.local.address && ~item.local.address.indexOf(':')) {
        item.protocol = 'tcp6';
    }

    if (item.pid == '-') {
        item.pid = 0;
    } else if (~item.pid.indexOf('/')) {
        parts = item.pid.split('/');
        item.pid = parts.length > 1 ? parts[0] : 0;
    } else if (isNaN(item.pid)) {
        item.pid = 0;
    }

    item.pid = parseInt(item.pid);
    return item;
};

utils$1.emitLines = function (stream) {
    var backlog = '';
    stream.on('data', function (data) {
        backlog = forEachLine(backlog + data, function (line) {
            stream.emit('line', line);
        });
    });

    stream.on('end', function () {
        if (backlog) {
            stream.emit('line', backlog);
        }
    });
};

utils$1.parseLines = function (source) {
    var lines = [];
    var r = forEachLine(source.toString(), lines.push.bind(lines));
    if (r.length) {
        lines.push(r);
    }

    return lines;
};

utils$1.noop = function () {};

(function (exports) {

	var spawn = require$$0.spawn;
	var spawnSync = require$$0.spawnSync;
	var emitLines = utils$1.emitLines;
	var parseLines = utils$1.parseLines;

	exports._spawnSync = spawnSync;
	exports._spawn = spawn;

	exports.sync = function (cmd, args, makeLineHandler, done) {
	    var processing = true;
	    var lineHandler = makeLineHandler(function () {
	        processing = false;
	    });

	    var proc = exports._spawnSync(cmd, args);
	    if (proc.error) {
	        return done(proc.error);
	    }

	    var lines = parseLines(proc.stdout);
	    for (var i = 0; i < lines.length && processing; i++) {
	        lineHandler(lines[i]);
	    }

	    return done(null);
	};

	exports.async = function (cmd, args, makeLineHandler, done) {
	    var killed = false;
	    var proc = exports._spawn(cmd, args);

	    var lineHandler = makeLineHandler(function () {
	        if (!killed) {
	            proc.stdout.removeListener('line', lineHandler);
	            proc.kill();
	            killed = true;
	        }
	    });

	    emitLines(proc.stdout);
	    proc.on('error', done);
	    proc.on('close', function () {
	        done(null);
	    });
	    
	    proc.stdout.on('line', lineHandler);
	    return { cancel:
	        function() {
	            if (!killed) {
	                proc.kill();
	                killed = true;
	            }
	        }
	    };
	};

	exports.continuous = function (activator, activatorOptions, options) {
	    var cmd = activatorOptions.cmd;
	    var args = activatorOptions.args;
	    var makeLineHandler = activatorOptions.makeLineHandler;
	    var done = activatorOptions.done;
	    var sync = options.sync;

	    var completed = false;
	    var canceller;
	    var makeInterceptHandler = function (stopper) {
	        var handler = makeLineHandler(function () {
	            completed = true;
	            stopper();
	        });

	        return handler;
	    };

	    function runActivator() {
	        canceller = activator(cmd, args, makeInterceptHandler, function (err) {
	            if (err) {
	                completed = true;
	                return done(err);
	            } else if (!completed && !sync) {
	                setTimeout(runActivator, 0);
	                return;
	            } else if (completed) {
	                done(null);
	            }
	        });
	    }

	    if (!sync) {
	        runActivator();
	        return { cancel:
	            function() {
	                completed = true;
	                canceller.cancel();
	            }
	        };
	    }

	    do {
	        runActivator();
	    } while(!completed);
	}; 
} (activators$1));

var parsers$1 = {};

var parserFactories$2 = {};

var normalizeValues = utils$1.normalizeValues;

parserFactories$2.linux = function (options) {
  options = options || {};
  var parseName = !!options.parseName;

  return function (line, callback) {
      var parts = line.split(/\s/).filter(String);
      if (!parts.length || parts[0].match(/^(tcp|udp)/) === null) {
          return;
      }

      // NOTE: insert null for missing state column on UDP
      if (parts[0].indexOf('udp') === 0) {
          parts.splice(5, 0, null);
      }

      var name = '';
      var pid = parts.slice(6, parts.length).join(" ");
      if (parseName && pid.indexOf('/') > 0) {
        var pidParts = pid.split('/');
        pid = pidParts[0];
        name = pidParts.slice(1, pidParts.length).join('/');
      }

      var item = {
          protocol: parts[0],
          local: parts[3],
          remote: parts[4],
          state: parts[5],
          pid: pid
      };

      if (parseName) {
        item.processName = name;
      }

      return callback(normalizeValues(item));
  };
};

parserFactories$2.darwin = function (options) {

  return function (line, callback) {
      var parts = line.split(/\s/).filter(String);
      if (parts.length === 0 || (parts[0].indexOf('tcp') < 0 && parts[0].indexOf('udp') < 0)) {
          return;
      }

      const protocol = parts[0];

      var item = {
          protocol: protocol === 'tcp4' ? 'tcp' : protocol === 'udp4' ? 'udp' : protocol,
          local: parts[3],
          remote: parts[4],
          state: parts[5],
          pid: parts[protocol.indexOf('udp') === 0 ? 7 : 8]
      };

      return callback(normalizeValues(item));
  };
};

parserFactories$2.win32 = function (options) {

  return function (line, callback) {
        var parts = line.split(/\s/).filter(String);
        if (!parts.length || (parts.length != 5 && parts.length != 4)) {
          return;
        }
        var item = {
            protocol: parts[0],
            local: parts[1],
            remote: parts[2],
            state: Number(parts[3]) ? null : parts[3],
            pid: parts[parts.length - 1]
        };

        return callback(normalizeValues(item));
    };
};

var parserFactories$1 = parserFactories$2;

parsers$1.darwin = parserFactories$1.darwin();
parsers$1.win32 = parserFactories$1.win32();
parsers$1.linux = parserFactories$1.linux({
  parseName: false,
});

var filters$1 = {};

function map(arr, fn, thisArg) {
    var result = [];
    for (var i = 0; i < arr.length; i++) {
        result.push(fn.call(thisArg, arr[i], i));
    }

    return result;
}

function getProperties(obj) {
    if (typeof obj !== 'object' || !obj) {
        return [];
    }

    return map(Object.keys(obj), function (key) {
        return {
            key: key,
            value: obj[key]
        };
    });
}

function leftDeepCompare(a, b) {
    if (a === null || typeof a !== 'object') {
        return a === b;
    }

    var aprops = getProperties(a);
    for (var i = 0; i < aprops.length; i++) {
        if (!b.hasOwnProperty(aprops[i].key) || !leftDeepCompare(aprops[i].value, b[aprops[i].key])) {
            return false;
        }
    }

    return true;
}

filters$1.limit = function (callback, limit) {
    var count = 0;
    return function (item) {
        if (++count <= limit) {
            return callback.call(this, item);
        }

        return false;
    };
};

filters$1.conditional = function (callback, conditions) {
    return function (item) {
        if (leftDeepCompare(conditions, item)) {
            return callback.call(this, item);
        }
    };
};

var version = "1.9.0";
const require$$6 = {
	version: version};

var isWsl$2 = {exports: {}};

const os$1 = require$$0$1;
const fs = require$$0$2;

const isWsl$1 = () => {
	if (process.platform !== 'linux') {
		return false;
	}

	if (os$1.release().includes('Microsoft')) {
		return true;
	}

	try {
		return fs.readFileSync('/proc/version', 'utf8').includes('Microsoft');
	} catch (err) {
		return false;
	}
};

if (process.env.__IS_WSL_TEST__) {
	isWsl$2.exports = isWsl$1;
} else {
	isWsl$2.exports = isWsl$1();
}

var isWslExports = isWsl$2.exports;

var os = require$$0$1;
var activators = activators$1;
var utils = utils$1;
var parsers = parsers$1;
var parserFactories = parserFactories$2;
var filters = filters$1;
var pkg = require$$6;
const isWsl = isWslExports;

var commands = {
    linux: {
        cmd: 'netstat',
        args: ['-apntu']
    },
    darwin: {
        cmd: 'netstat',
        args: ['-v', '-n']
    },
    win32: {
        cmd: 'netstat.exe',
        args: ['-a', '-n', '-o']
    }
};

netstat$1.exports = function (options, callback) {
    options = options || {};
    var done = options.done || utils.noop;
    var platform = options.platform || (isWsl ? 'win32' : false) || os.platform();
    var command = commands[platform];
    var parser = parsers[platform];
    var handler = callback;
    var activator = options.sync ? activators.sync : activators.async;

    var makeLineHandler = function (stopParsing) {
        return function (line) {
            if (parser(line, handler) === false) {
                stopParsing();
            }
        };
    };

    if (!parser || !command) {
        throw new Error('platform is not supported.');
    }

    if (options.limit && options.limit > 0) {
        handler = filters.limit(handler, options.limit, utils.noop);
    }

    if (options.filter) {
        handler = filters.conditional(handler, options.filter);
    }

    if (options.watch) {
        return activators.continuous(activator, {
            cmd: command.cmd,
            args: command.args,
            makeLineHandler: makeLineHandler,
            done: done
        }, { sync: options.sync });

    } else {
        return activator(command.cmd, command.args, makeLineHandler, done);
    }
};

netstat$1.exports.commands = commands;
netstat$1.exports.filters = filters;
netstat$1.exports.parsers = parsers;
netstat$1.exports.utils = utils;
netstat$1.exports.parserFactories = parserFactories;
netstat$1.exports.version = pkg.version;

var netstatExports = netstat$1.exports;

var nodeNetstat = netstatExports;

const netstat = /*@__PURE__*/getDefaultExportFromCjs(nodeNetstat);

const netstatAsync = (opts) => new Promise((resolve, reject) => {
  const res = [];
  netstat(
    {
      ...opts,
      done: (err) => {
        if (err) return reject(err);
        return resolve(res);
      }
    },
    (data) => {
      res.push(data);
    }
  );
  return res;
});
const getProcess_get = defineEventHandler(async (event) => {
  const processId = parseInt(getQuery(event).process);
  const stats = {
    netstat: await netstatAsync({
      filter: {
        pid: processId
      }
    }),
    processStats: await findProcess("pid", processId).then((e) => e[0])
  };
  return stats;
});

export { getProcess_get as default };
