local Z={workspace;Players}local N={}N.__index=N local Q={}local function B(Z,N)local Q=#Z Z[N]=Z[Q]Z[Q]=nil end local function Y(N)for Z,Q in ipairs(Z)do if N:IsDescendantOf(Q)then return true end end return false end function N.FromTag(Z)return Q[Z]end function N.Auto(Z)local function Q(Z)local Q=require(Z)assert(type(Q)=="\116\097\098\108\101","\069\120\112\101\099\116\101\100 \116\097\098\108\101 \102\111\114 \099\111\109\112\111\110\101\110\116")assert(type(Q.Tag)=="\115\116\114\105\110\103","\069\120\112\101\099\116\101\100 \046\084\097\103 \112\114\111\112\101\114\116\121")N.new(Q.Tag,Q,Q.RenderPriority)end for Z,N in ipairs(Z:GetDescendants())do if N:IsA("\077\111\100\117\108\101\083\099\114\105\112\116")then Q(N)end end Z.DescendantAdded:Connect(function(Z)if Z:IsA("\077\111\100\117\108\101\083\099\114\105\112\116")then Q(Z)end end)end function N.new(Z,B,M)assert(type(Z)=="\115\116\114\105\110\103","\065\114\103\117\109\101\110\116 \035\049 \040\116\097\103\041 \115\104\111\117\108\100 \098\101 \097 \115\116\114\105\110\103\059 \103\111\116 "..type(Z))assert(type(B)=="\116\097\098\108\101","\065\114\103\117\109\101\110\116 \035\050 \040\099\108\097\115\115\041 \115\104\111\117\108\100 \098\101 \097 \116\097\098\108\101\059 \103\111\116 "..type(B))assert(type(B.new)=="\102\117\110\099\116\105\111\110","\067\108\097\115\115 \109\117\115\116 \099\111\110\116\097\105\110 \097 \046\110\101\119 \099\111\110\115\116\114\117\099\116\111\114 \102\117\110\099\116\105\111\110")assert(type(B.Destroy)=="\102\117\110\099\116\105\111\110","\067\108\097\115\115 \109\117\115\116 \099\111\110\116\097\105\110 \097 \058\068\101\115\116\114\111\121 \102\117\110\099\116\105\111\110")assert(Q[Z]==nil,"\067\111\109\112\111\110\101\110\116 \097\108\114\101\097\100\121 \098\111\117\110\100 \116\111 \116\104\105\115 \116\097\103")local A=setmetatable({},N)A.Added=Signal.new()A.Removed=Signal.new()A._maid=Maid.new()A._lifecycleMaid=Maid.new()A._tag=Z A._class=B A._objects={}A._instancesToObjects={}A._hasHeartbeatUpdate=type(B.HeartbeatUpdate)=="\102\117\110\099\116\105\111\110"A._hasSteppedUpdate=type(B.SteppedUpdate)=="\102\117\110\099\116\105\111\110"A._hasRenderUpdate=type(B.RenderUpdate)=="\102\117\110\099\116\105\111\110"A._hasInit=type(B.Init)=="\102\117\110\099\116\105\111\110"A._hasDeinit=type(B.Deinit)=="\102\117\110\099\116\105\111\110"A._renderPriority=M or Enum.RenderPriority.Last.Value A._lifecycle=false A._nextId=0 A._maid:GiveTask((CollectionService:GetInstanceAddedSignal(Z)):Connect(function(Z)if Y(Z)then A:_instanceAdded(Z)end end))A._maid:GiveTask((CollectionService:GetInstanceRemovedSignal(Z)):Connect(function(Z)A:_instanceRemoved(Z)end))A._maid:GiveTask(A._lifecycleMaid)do local N=Instance.new("\066\105\110\100\097\098\108\101\069\118\101\110\116")for Z,Q in ipairs(CollectionService:GetTagged(Z))do if Y(Q)then local Z=N.Event:Connect(function()A:_instanceAdded(Q)end)N:Fire()Z:Disconnect()end end N:Destroy()end Q[Z]=A A._maid:GiveTask(function()Q[Z]=nil end)return A end function N._startHeartbeatUpdate(Z)local N=Z._objects Z._heartbeatUpdate=RunService.Heartbeat:Connect(function(Z)for N,Q in ipairs(N)do Q:HeartbeatUpdate(Z)end end)Z._lifecycleMaid:GiveTask(Z._heartbeatUpdate)end function N._startSteppedUpdate(Z)local N=Z._objects Z._steppedUpdate=RunService.Stepped:Connect(function(Z,Q)for Z,N in ipairs(N)do N:SteppedUpdate(Q)end end)Z._lifecycleMaid:GiveTask(Z._steppedUpdate)end function N._startRenderUpdate(Z)local N=Z._objects Z._renderName=Z._tag.."\082\101\110\100\101\114\085\112\100\097\116\101"RunService:BindToRenderStep(Z._renderName,Z._renderPriority,function(Z)for N,Q in ipairs(N)do Q:RenderUpdate(Z)end end)Z._lifecycleMaid:GiveTask(function()RunService:UnbindFromRenderStep(Z._renderName)end)end function N._startLifecycle(Z)Z._lifecycle=true if Z._hasHeartbeatUpdate then Z:_startHeartbeatUpdate()end if Z._hasSteppedUpdate then Z:_startSteppedUpdate()end if Z._hasRenderUpdate then Z:_startRenderUpdate()end end function N._stopLifecycle(Z)Z._lifecycle=false Z._lifecycleMaid:DoCleaning()end function N._instanceAdded(N,Z)if N._instancesToObjects[Z]then return end if not N._lifecycle then N:_startLifecycle()end N._nextId=N._nextId+1 local Q=N._tag..tostring(N._nextId)if IS_SERVER then Z:SetAttribute(ATTRIBUTE_ID_NAME,Q)end local B=N._class.new(Z)B.Instance=Z B._id=Q N._instancesToObjects[Z]=B table.insert(N._objects,B)if N._hasInit then Thread.Spawn(function()if N._instancesToObjects[Z]~=B then return end B:Init()end)end N.Added:Fire(B)return B end function N._instanceRemoved(N,Z)N._instancesToObjects[Z]=nil for Q,Y in ipairs(N._objects)do if Y.Instance==Z then if N._hasDeinit then Y:Deinit()end if IS_SERVER and(Z.Parent and Z:GetAttribute(ATTRIBUTE_ID_NAME)~=nil)then Z:SetAttribute(ATTRIBUTE_ID_NAME,nil)end N.Removed:Fire(Y)Y:Destroy()Y._destroyed=true B(N._objects,Q)break end end if#N._objects==0 and N._lifecycle then N:_stopLifecycle()end end function N.GetAll(Z)return TableUtil.CopyShallow(Z._objects)end function N.GetFromInstance(N,Z)return N._instancesToObjects[Z]end function N.GetFromID(N,Z)for N,Q in ipairs(N._objects)do if Q._id==Z then return Q end end return nil end function N.Filter(N,Z)return TableUtil.Filter(N._objects,Z)end function N.WaitFor(Q,Z,N)local B=type(Z)=="\115\116\114\105\110\103"local function Y(N)return B and N.Instance.Name==Z or not B and N.Instance==Z end for Z,N in ipairs(Q._objects)do if Y(N)then return Promise.resolve(N)end end local M=nil return((Promise.FromEvent(Q.Added,function(Z)M=Z return Y(Z)end)):Then(function()return M end)):Timeout(N or DEFAULT_WAIT_FOR_TIMEOUT)end function N.Destroy(Z)Z._maid:Destroy()end return N
-- Components will only work on instances parented under these descendants:
local DESCENDANT_WHITELIST = { workspace, Players }

local Component = {}
Component.__index = Component

local componentsByTag = {}

local function FastRemove(tbl, i)
	local n = #tbl
	tbl[i] = tbl[n]
	tbl[n] = nil
end

local function IsDescendantOfWhitelist(instance)
	for _, v in ipairs(DESCENDANT_WHITELIST) do
		if instance:IsDescendantOf(v) then
			return true
		end
	end
	return false
end

function Component.FromTag(tag)
	return componentsByTag[tag]
end

function Component.Auto(folder)
	local function Setup(moduleScript)
		local m = require(moduleScript)
		assert(type(m) == "table", "Expected table for component")
		assert(type(m.Tag) == "string", "Expected .Tag property")
		Component.new(m.Tag, m, m.RenderPriority)
	end
	for _, v in ipairs(folder:GetDescendants()) do
		if v:IsA("ModuleScript") then
			Setup(v)
		end
	end
	folder.DescendantAdded:Connect(function(v)
		if v:IsA("ModuleScript") then
			Setup(v)
		end
	end)
end

function Component.new(tag, class, renderPriority)
	assert(type(tag) == "string", "Argument #1 (tag) should be a string; got " .. type(tag))
	assert(type(class) == "table", "Argument #2 (class) should be a table; got " .. type(class))
	assert(type(class.new) == "function", "Class must contain a .new constructor function")
	assert(type(class.Destroy) == "function", "Class must contain a :Destroy function")
	assert(componentsByTag[tag] == nil, "Component already bound to this tag")

	local self = setmetatable({}, Component)

	self.Added = Signal.new()
	self.Removed = Signal.new()

	self._maid = Maid.new()
	self._lifecycleMaid = Maid.new()
	self._tag = tag
	self._class = class
	self._objects = {}
	self._instancesToObjects = {}
	self._hasHeartbeatUpdate = (type(class.HeartbeatUpdate) == "function")
	self._hasSteppedUpdate = (type(class.SteppedUpdate) == "function")
	self._hasRenderUpdate = (type(class.RenderUpdate) == "function")
	self._hasInit = (type(class.Init) == "function")
	self._hasDeinit = (type(class.Deinit) == "function")
	self._renderPriority = renderPriority or Enum.RenderPriority.Last.Value
	self._lifecycle = false
	self._nextId = 0

	self._maid:GiveTask(CollectionService:GetInstanceAddedSignal(tag):Connect(function(instance)
		if IsDescendantOfWhitelist(instance) then
			self:_instanceAdded(instance)
		end
	end))

	self._maid:GiveTask(CollectionService:GetInstanceRemovedSignal(tag):Connect(function(instance)
		self:_instanceRemoved(instance)
	end))

	self._maid:GiveTask(self._lifecycleMaid)

	do
		local b = Instance.new("BindableEvent")
		for _, instance in ipairs(CollectionService:GetTagged(tag)) do
			if IsDescendantOfWhitelist(instance) then
				local c = b.Event:Connect(function()
					self:_instanceAdded(instance)
				end)
				b:Fire()
				c:Disconnect()
			end
		end
		b:Destroy()
	end

	componentsByTag[tag] = self
	self._maid:GiveTask(function()
		componentsByTag[tag] = nil
	end)

	return self
end

function Component:_startHeartbeatUpdate()
	local all = self._objects
	self._heartbeatUpdate = RunService.Heartbeat:Connect(function(dt)
		for _, v in ipairs(all) do
			v:HeartbeatUpdate(dt)
		end
	end)
	self._lifecycleMaid:GiveTask(self._heartbeatUpdate)
end

function Component:_startSteppedUpdate()
	local all = self._objects
	self._steppedUpdate = RunService.Stepped:Connect(function(_, dt)
		for _, v in ipairs(all) do
			v:SteppedUpdate(dt)
		end
	end)
	self._lifecycleMaid:GiveTask(self._steppedUpdate)
end

function Component:_startRenderUpdate()
	local all = self._objects
	self._renderName = (self._tag .. "RenderUpdate")
	RunService:BindToRenderStep(self._renderName, self._renderPriority, function(dt)
		for _, v in ipairs(all) do
			v:RenderUpdate(dt)
		end
	end)
	self._lifecycleMaid:GiveTask(function()
		RunService:UnbindFromRenderStep(self._renderName)
	end)
end

function Component:_startLifecycle()
	self._lifecycle = true
	if self._hasHeartbeatUpdate then
		self:_startHeartbeatUpdate()
	end
	if self._hasSteppedUpdate then
		self:_startSteppedUpdate()
	end
	if self._hasRenderUpdate then
		self:_startRenderUpdate()
	end
end

function Component:_stopLifecycle()
	self._lifecycle = false
	self._lifecycleMaid:DoCleaning()
end

function Component:_instanceAdded(instance)
	if self._instancesToObjects[instance] then
		return
	end
	if not self._lifecycle then
		self:_startLifecycle()
	end
	self._nextId = (self._nextId + 1)
	local id = (self._tag .. tostring(self._nextId))
	if IS_SERVER then
		instance:SetAttribute(ATTRIBUTE_ID_NAME, id)
	end
	local obj = self._class.new(instance)
	obj.Instance = instance
	obj._id = id
	self._instancesToObjects[instance] = obj
	table.insert(self._objects, obj)
	if self._hasInit then
		Thread.Spawn(function()
			if self._instancesToObjects[instance] ~= obj then
				return
			end
			obj:Init()
		end)
	end
	self.Added:Fire(obj)
	return obj
end

function Component:_instanceRemoved(instance)
	self._instancesToObjects[instance] = nil
	for i, obj in ipairs(self._objects) do
		if obj.Instance == instance then
			if self._hasDeinit then
				obj:Deinit()
			end
			if IS_SERVER and instance.Parent and instance:GetAttribute(ATTRIBUTE_ID_NAME) ~= nil then
				instance:SetAttribute(ATTRIBUTE_ID_NAME, nil)
			end
			self.Removed:Fire(obj)
			obj:Destroy()
			obj._destroyed = true
			FastRemove(self._objects, i)
			break
		end
	end
	if #self._objects == 0 and self._lifecycle then
		self:_stopLifecycle()
	end
end

function Component:GetAll()
	return TableUtil.CopyShallow(self._objects)
end

function Component:GetFromInstance(instance)
	return self._instancesToObjects[instance]
end

function Component:GetFromID(id)
	for _, v in ipairs(self._objects) do
		if v._id == id then
			return v
		end
	end
	return nil
end

function Component:Filter(filterFunc)
	return TableUtil.Filter(self._objects, filterFunc)
end

function Component:WaitFor(instance, timeout)
	local isName = (type(instance) == "string")
	local function IsInstanceValid(obj)
		return ((isName and obj.Instance.Name == instance) or ((not isName) and obj.Instance == instance))
	end
	for _, obj in ipairs(self._objects) do
		if IsInstanceValid(obj) then
			return Promise.resolve(obj)
		end
	end
	local lastObj = nil
	return Promise.FromEvent(self.Added, function(obj)
		lastObj = obj
		return IsInstanceValid(obj)
	end)
		:Then(function()
			return lastObj
		end)
		:Timeout(timeout or DEFAULT_WAIT_FOR_TIMEOUT)
end

function Component:Destroy()
	self._maid:Destroy()
end

return Component
