local E=script:FindFirstAncestor("\067\109\100\114\065\100\100\105\116\105\111\110\115")local Y=E.Packages local O=require(Y.Promise)local x={}x.__index=x function x.new(Y)local L=setmetatable({CmdrAdditions=Y,_handlers={}},x)local a=Instance.new("\082\101\109\111\116\101\069\118\101\110\116")a.Parent=E L._remoteEvent=a local p=Instance.new("\082\101\109\111\116\101\070\117\110\099\116\105\111\110")p.Parent=E L._remoteFunction=p function p.OnServerInvoke(E,Y,...)local x=L._handlers[Y]if not x then return false,("\078\111 \104\097\110\100\108\101\114 \102\111\114 \101\118\101\110\116 \037\115"):format(Y)end local a={pcall(x,E,...)}local p=table.remove(a,1)if p and O.is(a[1])then return a[1]:await()end return p,unpack(a)end return L end function x.SendEvent(O,E,Y,...)O._remoteEvent:FireClient(E,Y,...)end function x.BroadcastEvent(Y,E,...)Y._remoteEvent:FireAllClients(E,...)end function x.SetRequestHandler(O,E,Y)assert(not O._handlers[E],("\072\097\110\100\108\101\114 \097\108\114\101\097\100\121 \101\120\105\115\116\115 \102\111\114 \101\118\101\110\116 \037\115"):format(E))O._handlers[E]=Y end return x
local Root = script:FindFirstAncestor("CmdrAdditions")
local Packages = Root.Packages

local Promise = require(Packages.Promise)

local NetworkServer = {}
NetworkServer.__index = NetworkServer

function NetworkServer.new(cmdrAdditions)
	local self = setmetatable({
		CmdrAdditions = cmdrAdditions,
		_handlers = {}
	}, NetworkServer)

	-- For server -> client events only
	local remoteEvent = Instance.new("RemoteEvent")
	remoteEvent.Parent = Root
	self._remoteEvent = remoteEvent

	-- All requests from the client to the server go through the RemoteFunction so a full response can always be returned
	local remoteFunction = Instance.new("RemoteFunction")
	remoteFunction.Parent = Root
	self._remoteFunction = remoteFunction

	function remoteFunction.OnServerInvoke(player, eventName, ...)
		local handler = self._handlers[eventName]

		if not handler then
			return false, ("No handler for event %s"):format(eventName)
		end

		local results = { pcall(handler, player, ...) }
		local success = table.remove(results, 1)

		if success and Promise.is(results[1]) then
			return results[1]:await()
		end

		return success, unpack(results)
	end

	return self
end

function NetworkServer:SendEvent(player, eventName, ...)
	self._remoteEvent:FireClient(player, eventName, ...)
end

function NetworkServer:BroadcastEvent(eventName, ...)
	self._remoteEvent:FireAllClients(eventName, ...)
end

function NetworkServer:SetRequestHandler(handlerName, handler)
	assert(not self._handlers[handlerName], ("Handler already exists for event %s"):format(handlerName))
	self._handlers[handlerName] = handler
end

return NetworkServer