local TS = require(
	game:GetService("ReplicatedStorage")
		:WaitForChild("RobloxTS")
		:WaitForChild("Include")
		:WaitForChild("RuntimeLib")
);
local _exports = {};
local Net;
local throttler = TS.import(script, "Throttle");
local Players = game:GetService("Players");
local runService = game:GetService("RunService");
local replicatedStorage = game:GetService("ReplicatedStorage");
local IS_CLIENT = runService:IsClient();
local IS_SERVER = runService:IsServer();
local IS_STUDIO = runService:IsStudio();
local REMOTES_FOLDER_NAME = "Remotes";
local FUNCTIONS_FOLDER_NAME = "Functions";
local EVENTS_FOLDER_NAME = "Events";
local remoteFolder;
local eventFolder;
local functionFolder;
local throttleResetTimer = 60;
local rateLimitReachedMessage = "Request limit exceeded ({limit}) by {player} via {remote}";
local findOrCreateFolder = function(parent, name)
	local folder = parent:FindFirstChild(name);
	if folder then
		return folder;
	else
		folder = Instance.new("Folder",parent);
		folder.Name = name;
		return folder;
	end;
end;
remoteFolder = findOrCreateFolder(replicatedStorage, REMOTES_FOLDER_NAME);
functionFolder = findOrCreateFolder(remoteFolder, FUNCTIONS_FOLDER_NAME);
eventFolder = findOrCreateFolder(remoteFolder, EVENTS_FOLDER_NAME);
local errorft = function(message, vars)
	message = message:gsub("{([%w_][%w%d_]*)}", function(token)
		return vars[token] or token;
	end);
	error(message, 2);
end;
local eventExists = function(name)
	return eventFolder:FindFirstChild(name) ~= nil;
end;
local functionExists = function(name)
	return functionFolder:FindFirstChild(name) ~= nil;
end;
local waitForEvent = function(name, timeOut)
	return eventFolder:WaitForChild(name, timeOut);
end;
local waitForFunction = function(name, timeOut)
	return functionFolder:WaitForChild(name, timeOut);
end;
local getRemoteFolder = function(type)
	local targetFolder;
	if type == "RemoteEvent" then
		targetFolder = eventFolder;
	elseif type == "RemoteFunction" then
		targetFolder = functionFolder;
	else
		TS.throw(("Invalid type: ") .. type);
	end;
	return targetFolder;
end;
local findRemoteOrThrow = function(type, name)
	local targetFolder = getRemoteFolder(type);
	local existing = targetFolder:FindFirstChild(name);
	if existing then
		return existing;
	else
		TS.throw("Could not find Remote of type " .. tostring(type) .. " called \"" .. name .. "\"");
	end;
end;
local findOrCreateRemote = function(type, name)
	local targetFolder = getRemoteFolder(type);
	local existing = targetFolder:FindFirstChild(name);
	if existing then
		return existing;
	else
		if not IS_SERVER then
			TS.throw("Creation of Events or Functions must be done on server!");
		end;
		local remote;
		if type == "RemoteEvent" or type == "RemoteFunction" then
			remote = Instance.new(type);
		else
			TS.throw("Invalid Remote Type: " .. tostring(type));
		end;
		remote.Name = name;
		remote.Parent = targetFolder;
		return remote;
	end;
end;
Net = Net or {} do
	local _0 = Net;
	local ClientEvent, ClientFunction;
	local MAX_CLIENT_WAITFORCHILD_TIMEOUT = 10;
	local VERSION = {
		number = {
			major = 0;
			minor = 6;
			revision = 1;
		};
		date = 190205;
		tag = "beta";
	};
	setmetatable(VERSION, {
		__tostring = function(self)
			local _1 = self.number;
			local major, minor, revision = _1["major"], _1["minor"], _1["revision"];
			return tostring(major) .. "." .. tostring(minor) .. "." .. tostring(revision);
		end;
	});
	local SetConfiguration = function(key, value)
		assert(IS_SERVER, "Cannot modify configuration on client!");
		if key == "ServerThrottleResetTimer" then
			throttleResetTimer = value;
		elseif key == "ServerThrottleMessage" then
			rateLimitReachedMessage = value;
		end;
	end;
	local GetConfiguration = function(key)
		if key == "ServerThrottleResetTimer" then
			assert(IS_SERVER, "ServerThrottleResetTimer is not used on the client!");
			return throttleResetTimer;
		elseif key == "ServerThrottleMessage" then
			assert(IS_SERVER, "ServerThrottleMessage is not used on the client!");
			return rateLimitReachedMessage;
		else
			return nil;
		end;
	end;
	local ServerEvent;
	do
		ServerEvent = {};
		ServerEvent.__index = {
			Connect = function(self, callback)
				self.Event:Connect(callback);
			end;
			SendToAllPlayers = function(self, ...)
				local args = { ... };
				self.instance:FireAllClients(unpack(args));
			end;
			SendToAllPlayersExcept = function(self, blacklist, ...)
				local args = { ... };
				if TS.typeIs(blacklist, "Instance") then
					local otherPlayers = TS.array_filter(Players:GetPlayers(), function(p)
						return p ~= blacklist;
					end);
					for _1 = 1, #otherPlayers do
						local player = otherPlayers[_1];
						self.instance:FireClient(player, unpack(args));
					end;
				elseif TS.typeIs(blacklist, "table") then
					local _1 = Players:GetPlayers();
					for _2 = 1, #_1 do
						local player = _1[_2];
						if TS.array_indexOf(blacklist, player) == -1 then
							self.instance:FireClient(player, unpack(args));
						end;
					end;
				end;
			end;
			SendToPlayer = function(self, player, ...)
				local args = { ... };
				self.instance:FireClient(player, unpack(args));
			end;
			SendToPlayers = function(self, players, ...)
				local args = { ... };
				for _1 = 1, #players do
					local player = players[_1];
					self:SendToPlayer(player, unpack(args));
				end;
			end;
		};
		ServerEvent.new = function(...)
			return ServerEvent.constructor(setmetatable({}, ServerEvent), ...);
		end;
		ServerEvent.constructor = function(self, name)
			self.instance = findOrCreateRemote("RemoteEvent", name);
			assert(not IS_CLIENT, "Cannot create a Net.ServerEvent on the Client!");
			return self;
		end;
		ServerEvent._getters = {
			Instance = function(self)
				return self.instance;
			end;
			Event = function(self)
				return self.instance.OnServerEvent;
			end;
		};
		local __index = ServerEvent.__index;
		ServerEvent.__index = function(self, index)
			local getter = ServerEvent._getters[index];
			if getter then
				return getter(self);
			else
				return __index[index];
			end;
		end;
	end;
	local ServerFunction;
	do
		ServerFunction = {};
		ServerFunction.__index = {
			CallPlayerAsync = TS.async(function(self, player, ...)
				local args = { ... };
				return self.instance:InvokeClient(player, unpack(args));
			end);
		};
		ServerFunction.new = function(...)
			return ServerFunction.constructor(setmetatable({}, ServerFunction), ...);
		end;
		ServerFunction.constructor = function(self, name)
			self.instance = findOrCreateRemote("RemoteFunction", name);
			assert(not IS_CLIENT, "Cannot create a Net.ServerFunction on the Client!");
			return self;
		end;
		ServerFunction._getters = {
			Callback = function(self)
				return self.instance.OnServerInvoke;
			end;
			Instance = function(self)
				return self.instance;
			end;
			ClientCache = function(self)
				local cache = self.instance:FindFirstChild("Cache");
				if cache then
					return cache.Value;
				else
					return 0;
				end;
			end;
		};
		local __index = ServerFunction.__index;
		ServerFunction.__index = function(self, index)
			local getter = ServerFunction._getters[index];
			if getter then
				return getter(self);
			else
				return __index[index];
			end;
		end;
		ServerFunction._setters = {
			Callback = function(self, func)
				self.instance.OnServerInvoke = func;
			end;
			ClientCache = function(self, time)
				local cache = self.instance:FindFirstChild("Cache");
				if not cache then
					local cacheTimer = Instance.new("NumberValue",self.instance);
					cacheTimer.Value = time;
					cacheTimer.Name = "Cache";
				else
					cache.Value = time;
				end;
			end;
		};
		ServerFunction.__newindex = function(self, index, value)
			local setter = ServerFunction._setters[index];
			if setter then
				setter(self, value);
			else
				rawset(self, index, value);
			end;
		end;
	end;
	local ServerThrottledEvent;
	do
		local super = ServerEvent;
		ServerThrottledEvent = setmetatable({}, { __index = super });
		ServerThrottledEvent.__index = setmetatable({
			Connect = function(self, callback)
				self.instance.OnServerEvent:Connect(function(player, ...)
					local args = { ... };
					local maxRequests = self.maxRequestsPerMinute;
					local clientRequestCount = self.clientRequests:Get(player);
					if clientRequestCount >= maxRequests then
						errorft(rateLimitReachedMessage, {
							player = player.UserId;
							remote = self.instance.Name;
							limit = maxRequests;
						});
					else
						self.clientRequests:Increment(player);
						callback(player, unpack(args));
					end;
				end);
			end;
		}, super);
		ServerThrottledEvent.new = function(...)
			return ServerThrottledEvent.constructor(setmetatable({}, ServerThrottledEvent), ...);
		end;
		ServerThrottledEvent.constructor = function(self, name, rateLimit)
			super.constructor(self, name);
			self.maxRequestsPerMinute = 0;
			self.maxRequestsPerMinute = rateLimit;
			self.clientRequests = throttler:Get("Event~" .. name);
			local clientValue = Instance.new("IntValue",self.instance);
			clientValue.Name = "RateLimit";
			clientValue.Value = rateLimit;
			return self;
		end;
		ServerThrottledEvent._getters = setmetatable({
			Event = function(self)
				error("Use 'Connect' instead foor ServerThrottledEvent!");
				return self.instance.OnServerEvent;
			end;
			RateLimit = function(self)
				return self.maxRequestsPerMinute;
			end;
		}, { __index = super._getters });
		local __index = ServerThrottledEvent.__index;
		ServerThrottledEvent.__index = function(self, index)
			local getter = ServerThrottledEvent._getters[index];
			if getter then
				return getter(self);
			else
				return __index[index];
			end;
		end;
		ServerThrottledEvent._setters = {
			RateLimit = function(self, requestsPerMinute)
				self.maxRequestsPerMinute = requestsPerMinute;
				local clientValue = self.instance:FindFirstChild("RateLimit");
				if clientValue then
					clientValue.Value = requestsPerMinute;
				else
					clientValue = Instance.new("IntValue",self.instance);
					clientValue.Name = "RateLimit";
					clientValue.Value = requestsPerMinute;
				end;
			end;
		};
		ServerThrottledEvent.__newindex = function(self, index, value)
			local setter = ServerThrottledEvent._setters[index];
			if setter then
				setter(self, value);
			else
				rawset(self, index, value);
			end;
		end;
	end;
	local ServerThrottledFunction;
	do
		local super = ServerFunction;
		ServerThrottledFunction = setmetatable({}, { __index = super });
		ServerThrottledFunction.__index = setmetatable({}, super);
		ServerThrottledFunction.new = function(...)
			return ServerThrottledFunction.constructor(setmetatable({}, ServerThrottledFunction), ...);
		end;
		ServerThrottledFunction.constructor = function(self, name, rateLimit)
			super.constructor(self, name);
			self.maxRequestsPerMinute = 0;
			self.maxRequestsPerMinute = rateLimit;
			self.clientRequests = throttler:Get("Function~" .. name);
			local clientValue = Instance.new("IntValue",self.instance);
			clientValue.Name = "RateLimit";
			clientValue.Value = rateLimit;
			return self;
		end;
		ServerThrottledFunction.rates = {};
		ServerThrottledFunction._getters = setmetatable({
			RateLimit = function(self)
				return self.maxRequestsPerMinute;
			end;
		}, { __index = super._getters });
		local __index = ServerThrottledFunction.__index;
		ServerThrottledFunction.__index = function(self, index)
			local getter = ServerThrottledFunction._getters[index];
			if getter then
				return getter(self);
			else
				return __index[index];
			end;
		end;
		ServerThrottledFunction._setters = setmetatable({
			Callback = function(self, callback)
				self.instance.OnServerInvoke = function(player, ...)
					local args = { ... };
					local maxRequests = self.maxRequestsPerMinute;
					local clientRequestCount = self.clientRequests:Get(player);
					if clientRequestCount >= maxRequests then
						errorft(rateLimitReachedMessage, {
							player = player.UserId;
							remote = self.instance.Name;
							limit = maxRequests;
						});
					else
						self.clientRequests:Increment(player);
						return callback(player, unpack(args));
					end;
				end;
			end;
			RateLimit = function(self, requestsPerMinute)
				self.maxRequestsPerMinute = requestsPerMinute;
				local clientValue = self.instance:FindFirstChild("RateLimit");
				if clientValue then
					clientValue.Value = requestsPerMinute;
				else
					clientValue = Instance.new("IntValue",self.instance);
					clientValue.Name = "RateLimit";
					clientValue.Value = requestsPerMinute;
				end;
			end;
		}, { __index = super._setters });
		ServerThrottledFunction.__newindex = function(self, index, value)
			local setter = ServerThrottledFunction._setters[index];
			if setter then
				setter(self, value);
			else
				rawset(self, index, value);
			end;
		end;
	end;
	do
		ClientEvent = {
			WaitFor = TS.async(function(self, name)
				local fun = waitForEvent(name, MAX_CLIENT_WAITFORCHILD_TIMEOUT);
				if not fun then
					error("Failed to retrieve client Event!");
				end;
				return Net.ClientEvent.new(name);
			end);
		};
		ClientEvent.__index = {
			Connect = function(self, callback)
				self.Event:Connect(callback);
			end;
			SendToServer = function(self, ...)
				local args = { ... };
				self.instance:FireServer(unpack(args));
			end;
		};
		ClientEvent.new = function(...)
			return ClientEvent.constructor(setmetatable({}, ClientEvent), ...);
		end;
		ClientEvent.constructor = function(self, name)
			self.instance = findRemoteOrThrow("RemoteEvent", name);
			assert(IS_CLIENT, "Cannot create a Net.ClientEvent on the Server!");
			return self;
		end;
		ClientEvent._getters = {
			Instance = function(self)
				return self.instance;
			end;
			Event = function(self)
				return self.instance.OnClientEvent;
			end;
		};
		local __index = ClientEvent.__index;
		ClientEvent.__index = function(self, index)
			local getter = ClientEvent._getters[index];
			if getter then
				return getter(self);
			else
				return __index[index];
			end;
		end;
	end;
	do
		ClientFunction = {
			WaitFor = TS.async(function(self, name)
				local fun = waitForFunction(name, MAX_CLIENT_WAITFORCHILD_TIMEOUT);
				if not fun then
					error("Failed to retrieve client Function!");
				end;
				return Net.ClientFunction.new(name);
			end);
		};
		ClientFunction.__index = {
			CallServer = function(self, ...)
				local args = { ... };
				if self.lastPing < (os.time() + self.Cache) then
					local result = self.instance:InvokeServer(unpack(args));
					self.cached = result;
					self.lastPing = os.time();
					return result;
				else
					return self.cached;
				end;
			end;
			CallServerAsync = TS.async(function(self, ...)
				local args = { ... };
				return self:CallServer(unpack(args));
			end);
		};
		ClientFunction.new = function(...)
			return ClientFunction.constructor(setmetatable({}, ClientFunction), ...);
		end;
		ClientFunction.constructor = function(self, name)
			self.lastPing = -1;
			self.cached = {};
			self.instance = findRemoteOrThrow("RemoteFunction", name);
			assert(IS_CLIENT, "Cannot create a Net.ClientFunction on the Server!");
			assert(functionExists(name), "The specified function '" .. name .. "' does not exist!");
			return self;
		end;
		ClientFunction._getters = {
			Callback = function(self)
				return self.instance.OnClientInvoke;
			end;
			Instance = function(self)
				return self.instance;
			end;
			Cache = function(self)
				local cache = self.instance:FindFirstChild("Cache");
				if cache then
					return cache.Value;
				else
					return 0;
				end;
			end;
		};
		local __index = ClientFunction.__index;
		ClientFunction.__index = function(self, index)
			local getter = ClientFunction._getters[index];
			if getter then
				return getter(self);
			else
				return __index[index];
			end;
		end;
		ClientFunction._setters = {
			Callback = function(self, func)
				self.instance.OnClientInvoke = func;
			end;
		};
		ClientFunction.__newindex = function(self, index, value)
			local setter = ClientFunction._setters[index];
			if setter then
				setter(self, value);
			else
				rawset(self, index, value);
			end;
		end;
	end;
	local IsClient = function()
		return IS_CLIENT;
	end;
	local IsServer = function()
		return IS_SERVER;
	end;
	local CreateFunction = function(name)
		if IS_SERVER then
			return ServerFunction.new(name);
		else
			error("Net.createFunction can only be used on the server!");
			TS.throw("");
		end;
	end;
	local CreateThrottledFunction = function(name, rateLimit)
		if IS_SERVER then
			return ServerThrottledFunction.new(name,rateLimit);
		else
			error("Net.createFunction can only be used on the server!");
			TS.throw("");
		end;
	end;
	local CreateThrottledEvent = function(name, rateLimit)
		if IS_SERVER then
			return ServerThrottledEvent.new(name,rateLimit);
		else
			error("Net.createFunction can only be used on the server!");
			TS.throw("Net.createFunction can only be used on the server!");
		end;
	end;
	local CreateEvent = function(name)
		if IS_SERVER then
			return ServerEvent.new(name);
		else
			error("Net.createFunction can only be used on the server!");
			TS.throw("Net.createFunction can only be used on the server!");
		end;
	end;
	local WaitForClientFunctionAsync = TS.async(function(name)
		return Net.ClientFunction:WaitFor(name);
	end);
	local WaitForClientEventAsync = TS.async(function(name)
		return Net.ClientEvent:WaitFor(name);
	end);
	local GetServerEventAsync = function(name)
		return TS.Promise.new(function(resolve, reject)
			if eventExists(name) then
				local newFunc = ServerEvent.new(name);
				resolve(newFunc);
			else
				reject((("Could not find Server Event: ") .. name) .. " (did you create it on the server?)");
			end;
		end);
	end;
	local GetServerFunctionAsync = function(name)
		return TS.Promise.new(function(resolve, reject)
			if functionExists(name) then
				local newFunc = ServerFunction.new(name);
				resolve(newFunc);
			else
				reject((("Could not find Server Function: ") .. name) .. " (did you create it?)");
			end;
		end);
	end;
	if IS_STUDIO then
		print("[rbx-net] Loaded rbx-net", "v" .. tostring(VERSION));
	end;
	if IS_SERVER then
		local lastTick = 0;
		game:GetService("RunService").Stepped:Connect(function(time, step)
			if tick() > lastTick + throttleResetTimer then
				lastTick = tick();
				throttler:Clear();
			end;
		end);
	end;
	_0.VERSION = VERSION;
	_0.SetConfiguration = SetConfiguration;
	_0.GetConfiguration = GetConfiguration;
	_0.ServerEvent = ServerEvent;
	_0.ServerFunction = ServerFunction;
	_0.ServerThrottledEvent = ServerThrottledEvent;
	_0.ServerThrottledFunction = ServerThrottledFunction;
	_0.ClientEvent = ClientEvent;
	_0.ClientFunction = ClientFunction;
	_0.IsClient = IsClient;
	_0.IsServer = IsServer;
	_0.CreateFunction = CreateFunction;
	_0.CreateThrottledFunction = CreateThrottledFunction;
	_0.CreateThrottledEvent = CreateThrottledEvent;
	_0.CreateEvent = CreateEvent;
	_0.WaitForClientFunctionAsync = WaitForClientFunctionAsync;
	_0.WaitForClientEventAsync = WaitForClientEventAsync;
	_0.GetServerEventAsync = GetServerEventAsync;
	_0.GetServerFunctionAsync = GetServerFunctionAsync;
end;
_exports._default = Net;
_exports._default = Net;
return _exports;
