local y="\078\111\110-\112\114\111\109\105\115\101 \118\097\108\117\101 \112\097\115\115\101\100 \105\110\116\111 \037\115 \097\116 \105\110\100\101\120 \037\115"local W="\080\108\101\097\115\101 \112\097\115\115 \097 \108\105\115\116 \111\102 \112\114\111\109\105\115\101\115 \116\111 \037\115"local e="\080\108\101\097\115\101 \112\097\115\115 \097 \104\097\110\100\108\101\114 \102\117\110\099\116\105\111\110 \116\111 \037\115\033"local T={__mode="\107"}local z=game:GetService("\082\117\110\083\101\114\118\105\099\101")local function R(y,W)local e={}for y,W in ipairs(W)do e[W]=W end return setmetatable(e,{__index=function(W,e)error(string.format("\037\115 \105\115 \110\111\116 \105\110 \037\115\033",e,y),2)end,__newindex=function()error(string.format("\067\114\101\097\116\105\110\103 \110\101\119 \109\101\109\098\101\114\115 \105\110 \037\115 \105\115 \110\111\116 \097\108\108\111\119\101\100\033",y),2)end})end local c do c={Kind=R("\080\114\111\109\105\115\101\046\069\114\114\111\114\046\075\105\110\100",{"\069\120\101\099\117\116\105\111\110\069\114\114\111\114","\065\108\114\101\097\100\121\067\097\110\099\101\108\108\101\100";"\078\111\116\082\101\115\111\108\118\101\100\073\110\084\105\109\101","\084\105\109\101\100\079\117\116"})}c.__index=c function c.new(y,W)y=y or{}return setmetatable({error=tostring(y.error)or"\091\084\104\105\115 \101\114\114\111\114 \104\097\115 \110\111 \101\114\114\111\114 \116\101\120\116\046\093",trace=y.trace,context=y.context,kind=y.kind;parent=W,createdTick=tick(),createdTrace=debug.traceback()},c)end function c.is(y)if type(y)=="\116\097\098\108\101"then local W=getmetatable(y)if type(W)=="\116\097\098\108\101"then return rawget(y,"\101\114\114\111\114")~=nil and type(rawget(W,"\101\120\116\101\110\100"))=="\102\117\110\099\116\105\111\110"end end return false end function c.isKind(y,W)assert(W~=nil,"\065\114\103\117\109\101\110\116 \035\050 \116\111 \080\114\111\109\105\115\101\046\069\114\114\111\114\046\105\115\075\105\110\100 \109\117\115\116 \110\111\116 \098\101 \110\105\108")return c.is(y)and y.kind==W end function c.extend(W,y)y=y or{}y.kind=y.kind or W.kind return c.new(y,W)end function c.getErrorChain(y)local W={y}while W[#W].parent do table.insert(W,W[#W].parent)end return W end function c.__tostring(y)local W={string.format("-- \080\114\111\109\105\115\101\046\069\114\114\111\114\040\037\115\041 --",y.kind or"\063")}for y,e in ipairs(y:getErrorChain())do table.insert(W,table.concat({e.trace or e.error,e.context},"\n"))end return table.concat(W,"\n")end end local function S(...)return select("\035",...),{...}end local function H(y,...)return y,select("\035",...),{...}end local function J(y)assert(y~=nil,"\116\114\097\099\101\098\097\099\107 \105\115 \110\105\108")return function(W)if type(W)=="\116\097\098\108\101"then return W end return c.new({error=W;kind=c.Kind.ExecutionError,trace=debug.traceback(tostring(W),2),context="\080\114\111\109\105\115\101 \099\114\101\097\116\101\100 \097\116\058\n\n"..y})end end local function l(y,W,...)return H(xpcall(W,J(y),...))end local function P(y,W,e,T)return function(...)local z,R,c=l(y,W,...)if z then e(unpack(c,1,R))else T(c[1])end end end local function Q(y)return next(y)==nil end local X={Error=c;Status=R("\080\114\111\109\105\115\101\046\083\116\097\116\117\115",{"\083\116\097\114\116\101\100";"\082\101\115\111\108\118\101\100";"\082\101\106\101\099\116\101\100";"\067\097\110\099\101\108\108\101\100"}),_timeEvent=z.Heartbeat;_getTime=tick}X.prototype={}X.__index=X.prototype function X._new(y,W,e)if e~=nil and not X.is(e)then error("\065\114\103\117\109\101\110\116 \035\050 \116\111 \080\114\111\109\105\115\101\046\110\101\119 \109\117\115\116 \098\101 \097 \112\114\111\109\105\115\101 \111\114 \110\105\108",2)end local z={_source=y,_status=X.Status.Started,_values=nil,_valuesLength=-1,_unhandledRejection=true,_queuedResolve={};_queuedReject={},_queuedFinally={};_cancellationHook=nil;_parent=e,_consumers=setmetatable({},T)}if e and e._status==X.Status.Started then e._consumers[z]=true end setmetatable(z,X)local function R(...)z:_resolve(...)end local function c(...)z:_reject(...)end local function S(y)if y then if z._status==X.Status.Cancelled then y()else z._cancellationHook=y end end return z._status==X.Status.Cancelled end;(coroutine.wrap(function()local y,e,T=l(z._source,W,R,c,S)if not y then c(T[1])end end))()return z end function X.new(y)return X._new(debug.traceback(nil,2),y)end function X.__tostring(y)return string.format("\080\114\111\109\105\115\101\040\037\115\041",y:getStatus())end function X.defer(y)local W=debug.traceback(nil,2)local e e=X._new(W,function(e,T,z)local R R=X._timeEvent:Connect(function()R:Disconnect()local c,S,H=l(W,y,e,T,z)if not c then T(H[1])end end)end)return e end X.async=X.defer function X.resolve(...)local y,W=S(...)return X._new(debug.traceback(nil,2),function(e)e(unpack(W,1,y))end)end function X.reject(...)local y,W=S(...)return X._new(debug.traceback(nil,2),function(e,T)T(unpack(W,1,y))end)end function X._try(y,W,...)local e,T=S(...)return X._new(y,function(y)y(W(unpack(T,1,e)))end)end function X.try(...)return X._try(debug.traceback(nil,2),...)end function X._all(e,T,z)if type(T)~="\116\097\098\108\101"then error(string.format(W,"\080\114\111\109\105\115\101\046\097\108\108"),3)end for W,e in pairs(T)do if not X.is(e)then error(string.format(y,"\080\114\111\109\105\115\101\046\097\108\108",tostring(W)),3)end end if#T==0 or z==0 then return X.resolve({})end return X._new(e,function(y,W,e)local R={}local c={}local S=0 local H=0 local J=false local function l()for y,W in ipairs(c)do W:cancel()end end local function P(W,...)if J then return end S=S+1 if z==nil then R[W]=...else R[S]=...end if S>=(z or#T)then J=true y(R)l()end end e(l)for y,e in ipairs(T)do c[y]=e:andThen(function(...)P(y,...)end,function(...)H=H+1 if z==nil or#T-H<z then l()J=true W(...)end end)end if J then l()end end)end function X.all(y)return X._all(debug.traceback(nil,2),y)end function X.some(y,W)assert(type(W)=="\110\117\109\098\101\114","\066\097\100 \097\114\103\117\109\101\110\116 \035\050 \116\111 \080\114\111\109\105\115\101\046\115\111\109\101\058 \109\117\115\116 \098\101 \097 \110\117\109\098\101\114")return X._all(debug.traceback(nil,2),y,W)end function X.any(y)return(X._all(debug.traceback(nil,2),y,1)):andThen(function(y)return y[1]end)end function X.allSettled(e)if type(e)~="\116\097\098\108\101"then error(string.format(W,"\080\114\111\109\105\115\101\046\097\108\108\083\101\116\116\108\101\100"),2)end for W,e in pairs(e)do if not X.is(e)then error(string.format(y,"\080\114\111\109\105\115\101\046\097\108\108\083\101\116\116\108\101\100",tostring(W)),2)end end if#e==0 then return X.resolve({})end return X._new(debug.traceback(nil,2),function(y,W,T)local z={}local R={}local c=0 local function S(W,...)c=c+1 z[W]=...if c>=#e then y(z)end end T(function()for y,W in ipairs(R)do W:cancel()end end)for y,W in ipairs(e)do R[y]=W:finally(function(...)S(y,...)end)end end)end function X.race(e)assert(type(e)=="\116\097\098\108\101",string.format(W,"\080\114\111\109\105\115\101\046\114\097\099\101"))for W,e in pairs(e)do assert(X.is(e),string.format(y,"\080\114\111\109\105\115\101\046\114\097\099\101",tostring(W)))end return X._new(debug.traceback(nil,2),function(y,W,T)local z={}local R=false local function c()for y,W in ipairs(z)do W:cancel()end end local function S(y)return function(...)c()R=true return y(...)end end if T(S(W))then return end for e,T in ipairs(e)do z[e]=T:andThen(S(y),S(W))end if R then c()end end)end function X.each(y,T)assert(type(y)=="\116\097\098\108\101",string.format(W,"\080\114\111\109\105\115\101\046\101\097\099\104"))assert(type(T)=="\102\117\110\099\116\105\111\110",string.format(e,"\080\114\111\109\105\115\101\046\101\097\099\104"))return X._new(debug.traceback(nil,2),function(W,e,z)local R={}local S={}local H=false local function J()for y,W in ipairs(S)do W:cancel()end end z(function()H=true J()end)local l={}for y,W in ipairs(y)do if X.is(W)then if W:getStatus()==X.Status.Cancelled then J()return e(c.new({error="\080\114\111\109\105\115\101 \105\115 \099\097\110\099\101\108\108\101\100";kind=c.Kind.AlreadyCancelled,context=string.format("\084\104\101 \080\114\111\109\105\115\101 \116\104\097\116 \119\097\115 \112\097\114\116 \111\102 \116\104\101 \097\114\114\097\121 \097\116 \105\110\100\101\120 \037\100 \112\097\115\115\101\100 \105\110\116\111 \080\114\111\109\105\115\101\046\101\097\099\104 \119\097\115 \097\108\114\101\097\100\121 \099\097\110\099\101\108\108\101\100 \119\104\101\110 \080\114\111\109\105\115\101\046\101\097\099\104 \098\101\103\097\110\046\n\n\084\104\097\116 \080\114\111\109\105\115\101 \119\097\115 \099\114\101\097\116\101\100 \097\116\058\n\n\037\115",y,W._source)}))elseif W:getStatus()==X.Status.Rejected then J()return e(select(2,W:await()))end local T=W:andThen(function(...)return...end)table.insert(S,T)l[y]=T else l[y]=W end end for y,W in ipairs(l)do if X.is(W)then local y y,W=W:await()if not y then J()return e(W)end end if H then return end local z=X.resolve(T(W,y))table.insert(S,z)local c,l=z:await()if not c then J()return e(l)end R[y]=l end W(R)end)end function X.is(y)if type(y)~="\116\097\098\108\101"then return false end local W=getmetatable(y)if W==X then return true elseif W==nil then return type(y.andThen)=="\102\117\110\099\116\105\111\110"elseif type(W)=="\116\097\098\108\101"and type(rawget(W,"\097\110\100\084\104\101\110"))=="\102\117\110\099\116\105\111\110"then return true end return false end function X.promisify(y)return function(...)return X._try(debug.traceback(nil,2),y,...)end end do local y local W function X.delay(e)assert(type(e)=="\110\117\109\098\101\114","\066\097\100 \097\114\103\117\109\101\110\116 \035\049 \116\111 \080\114\111\109\105\115\101\046\100\101\108\097\121\044 \109\117\115\116 \098\101 \097 \110\117\109\098\101\114\046")if not(e>=.016666666666667)or e==math.huge then e=.016666666666667 end return X._new(debug.traceback(nil,2),function(T,z,R)local c=X._getTime()local S=c+e local H={resolve=T,startTime=c,endTime=S}if W==nil then y=H W=X._timeEvent:Connect(function()local e=X._getTime()while y.endTime<=e do y.resolve(X._getTime()-y.startTime)y=y.next if y==nil then W:Disconnect()W=nil break end y.previous=nil end end)else if y.endTime<S then local W=y local e=W.next while e~=nil and e.endTime<S do W=e e=W.next end W.next=H H.previous=W if e~=nil then H.next=e e.previous=H end else H.next=y y.previous=H y=H end end R(function()local e=H.next if y==H then if e==nil then W:Disconnect()W=nil else e.previous=nil end y=e else local y=H.previous y.next=e if e~=nil then e.previous=y end end end)end)end end function X.prototype.timeout(e,y,W)local T=debug.traceback(nil,2)return X.race({(X.delay(y)):andThen(function()return X.reject(W==nil and c.new({kind=c.Kind.TimedOut;error="\084\105\109\101\100 \111\117\116";context=string.format("\084\105\109\101\111\117\116 \111\102 \037\100 \115\101\099\111\110\100\115 \101\120\099\101\101\100\101\100\046\n\058\116\105\109\101\111\117\116\040\041 \099\097\108\108\101\100 \097\116\058\n\n\037\115",y,T)})or W)end),e})end function X.prototype.getStatus(y)return y._status end function X.prototype._andThen(T,y,W,e)T._unhandledRejection=false return X._new(y,function(z,R)local S=z if W then S=P(y,W,z,R)end local H=R if e then H=P(y,e,z,R)end if T._status==X.Status.Started then table.insert(T._queuedResolve,S)table.insert(T._queuedReject,H)elseif T._status==X.Status.Resolved then S(unpack(T._values,1,T._valuesLength))elseif T._status==X.Status.Rejected then H(unpack(T._values,1,T._valuesLength))elseif T._status==X.Status.Cancelled then R(c.new({error="\080\114\111\109\105\115\101 \105\115 \099\097\110\099\101\108\108\101\100";kind=c.Kind.AlreadyCancelled,context="\080\114\111\109\105\115\101 \099\114\101\097\116\101\100 \097\116\n\n"..y}))end end,T)end function X.prototype.andThen(T,y,W)assert(y==nil or type(y)=="\102\117\110\099\116\105\111\110",string.format(e,"\080\114\111\109\105\115\101\058\097\110\100\084\104\101\110"))assert(W==nil or type(W)=="\102\117\110\099\116\105\111\110",string.format(e,"\080\114\111\109\105\115\101\058\097\110\100\084\104\101\110"))return T:_andThen(debug.traceback(nil,2),y,W)end function X.prototype.catch(W,y)assert(y==nil or type(y)=="\102\117\110\099\116\105\111\110",string.format(e,"\080\114\111\109\105\115\101\058\099\097\116\099\104"))return W:_andThen(debug.traceback(nil,2),nil,y)end function X.prototype.tap(W,y)assert(type(y)=="\102\117\110\099\116\105\111\110",string.format(e,"\080\114\111\109\105\115\101\058\116\097\112"))return W:_andThen(debug.traceback(nil,2),function(...)local W=y(...)if X.is(W)then local y,e=S(...)return W:andThen(function()return unpack(e,1,y)end)end return...end)end function X.prototype.andThenCall(W,y,...)assert(type(y)=="\102\117\110\099\116\105\111\110",string.format(e,"\080\114\111\109\105\115\101\058\097\110\100\084\104\101\110\067\097\108\108"))local T,z=S(...)return W:_andThen(debug.traceback(nil,2),function()return y(unpack(z,1,T))end)end function X.prototype.andThenReturn(y,...)local W,e=S(...)return y:_andThen(debug.traceback(nil,2),function()return unpack(e,1,W)end)end function X.prototype.cancel(y)if y._status~=X.Status.Started then return end y._status=X.Status.Cancelled if y._cancellationHook then y._cancellationHook()end if y._parent then y._parent:_consumerCancelled(y)end for y in pairs(y._consumers)do y:cancel()end y:_finalize()end function X.prototype._consumerCancelled(W,y)if W._status~=X.Status.Started then return end W._consumers[y]=nil if next(W._consumers)==nil then W:cancel()end end function X.prototype._finally(T,y,W,e)if not e then T._unhandledRejection=false end return X._new(y,function(z,R)local c=z if W then c=P(y,W,z,R)end if e then local y=c c=function(...)if T._status==X.Status.Rejected then return z(T)end return y(...)end end if T._status==X.Status.Started then table.insert(T._queuedFinally,c)else c(T._status)end end,T)end function X.prototype.finally(W,y)assert(y==nil or type(y)=="\102\117\110\099\116\105\111\110",string.format(e,"\080\114\111\109\105\115\101\058\102\105\110\097\108\108\121"))return W:_finally(debug.traceback(nil,2),y)end function X.prototype.finallyCall(W,y,...)assert(type(y)=="\102\117\110\099\116\105\111\110",string.format(e,"\080\114\111\109\105\115\101\058\102\105\110\097\108\108\121\067\097\108\108"))local T,z=S(...)return W:_finally(debug.traceback(nil,2),function()return y(unpack(z,1,T))end)end function X.prototype.finallyReturn(y,...)local W,e=S(...)return y:_finally(debug.traceback(nil,2),function()return unpack(e,1,W)end)end function X.prototype.done(W,y)assert(y==nil or type(y)=="\102\117\110\099\116\105\111\110",string.format(e,"\080\114\111\109\105\115\101\058\100\111\110\101"))return W:_finally(debug.traceback(nil,2),y,true)end function X.prototype.doneCall(W,y,...)assert(type(y)=="\102\117\110\099\116\105\111\110",string.format(e,"\080\114\111\109\105\115\101\058\100\111\110\101\067\097\108\108"))local T,z=S(...)return W:_finally(debug.traceback(nil,2),function()return y(unpack(z,1,T))end,true)end function X.prototype.doneReturn(y,...)local W,e=S(...)return y:_finally(debug.traceback(nil,2),function()return unpack(e,1,W)end,true)end function X.prototype.awaitStatus(y)y._unhandledRejection=false if y._status==X.Status.Started then local W=Instance.new("\066\105\110\100\097\098\108\101\069\118\101\110\116")y:finally(function()W:Fire()end)W.Event:Wait()W:Destroy()end if y._status==X.Status.Resolved then return y._status,unpack(y._values,1,y._valuesLength)elseif y._status==X.Status.Rejected then return y._status,unpack(y._values,1,y._valuesLength)end return y._status end local function t(y,...)return y==X.Status.Resolved,...end function X.prototype.await(y)return t(y:awaitStatus())end local function p(y,...)if y~=X.Status.Resolved then error(...==nil and"\069\120\112\101\099\116\101\100 \080\114\111\109\105\115\101 \114\101\106\101\099\116\101\100 \119\105\116\104 \110\111 \118\097\108\117\101\046"or...,3)end return...end function X.prototype.expect(y)return p(y:awaitStatus())end X.prototype.awaitValue=X.prototype.expect function X.prototype._unwrap(y)if y._status==X.Status.Started then error("\080\114\111\109\105\115\101 \104\097\115 \110\111\116 \114\101\115\111\108\118\101\100 \111\114 \114\101\106\101\099\116\101\100\046",2)end local W=y._status==X.Status.Resolved return W,unpack(y._values,1,y._valuesLength)end function X.prototype._resolve(y,...)if y._status~=X.Status.Started then if X.is(...)then(...):_consumerCancelled(y)end return end if X.is(...)then if select("\035",...)>1 then local W=string.format("\087\104\101\110 \114\101\116\117\114\110\105\110\103 \097 \080\114\111\109\105\115\101 \102\114\111\109 \097\110\100\084\104\101\110\044 \101\120\116\114\097 \097\114\103\117\109\101\110\116\115 \097\114\101 \100\105\115\099\097\114\100\101\100\033 \083\101\101\058\n\n\037\115",y._source)warn(W)end local W=...local e=W:andThen(function(...)y:_resolve(...)end,function(...)local e=W._values[1]if W._error then e=c.new({error=W._error,kind=c.Kind.ExecutionError;context="\091\078\111 \115\116\097\099\107 \116\114\097\099\101 \097\118\097\105\108\097\098\108\101 \097\115 \116\104\105\115 \080\114\111\109\105\115\101 \111\114\105\103\105\110\097\116\101\100 \102\114\111\109 \097\110 \111\108\100\101\114 \118\101\114\115\105\111\110 \111\102 \116\104\101 \080\114\111\109\105\115\101 \108\105\098\114\097\114\121 \040\060 \118\050\041\093"})end if c.isKind(e,c.Kind.ExecutionError)then return y:_reject(e:extend({error="\084\104\105\115 \080\114\111\109\105\115\101 \119\097\115 \099\104\097\105\110\101\100 \116\111 \097 \080\114\111\109\105\115\101 \116\104\097\116 \101\114\114\111\114\101\100\046";trace="",context=string.format("\084\104\101 \080\114\111\109\105\115\101 \097\116\058\n\n\037\115\n\046\046\046\082\101\106\101\099\116\101\100 \098\101\099\097\117\115\101 \105\116 \119\097\115 \099\104\097\105\110\101\100 \116\111 \116\104\101 \102\111\108\108\111\119\105\110\103 \080\114\111\109\105\115\101\044 \119\104\105\099\104 \101\110\099\111\117\110\116\101\114\101\100 \097\110 \101\114\114\111\114\058\n",y._source)}))end y:_reject(...)end)if e._status==X.Status.Cancelled then y:cancel()elseif e._status==X.Status.Started then y._parent=e e._consumers[y]=true end return end y._status=X.Status.Resolved y._valuesLength,y._values=S(...)for y,W in ipairs(y._queuedResolve)do(coroutine.wrap(W))(...)end y:_finalize()end function X.prototype._reject(y,...)if y._status~=X.Status.Started then return end y._status=X.Status.Rejected y._valuesLength,y._values=S(...)if not Q(y._queuedReject)then for y,W in ipairs(y._queuedReject)do(coroutine.wrap(W))(...)end else local W=tostring(...);(coroutine.wrap(function()X._timeEvent:Wait()if not y._unhandledRejection then return end local e=string.format("\085\110\104\097\110\100\108\101\100 \080\114\111\109\105\115\101 \114\101\106\101\099\116\105\111\110\058\n\n\037\115\n\n\037\115",W,y._source)if X.TEST then return end warn(e)end))()end y:_finalize()end function X.prototype._finalize(y)for W,e in ipairs(y._queuedFinally)do(coroutine.wrap(e))(y._status)end if not X.TEST then y._parent=nil y._consumers=nil end end function X.prototype.now(W,y)local e=debug.traceback(nil,2)if W:getStatus()==X.Status.Resolved then return W:_andThen(e,function(...)return...end)else return X.reject(y==nil and c.new({kind=c.Kind.NotResolvedInTime;error="\084\104\105\115 \080\114\111\109\105\115\101 \119\097\115 \110\111\116 \114\101\115\111\108\118\101\100 \105\110 \116\105\109\101 \102\111\114 \058\110\111\119\040\041";context="\058\110\111\119\040\041 \119\097\115 \099\097\108\108\101\100 \097\116\058\n\n"..e})or y)end end function X.retry(y,W,...)assert(type(y)=="\102\117\110\099\116\105\111\110","\080\097\114\097\109\101\116\101\114 \035\049 \116\111 \080\114\111\109\105\115\101\046\114\101\116\114\121 \109\117\115\116 \098\101 \097 \102\117\110\099\116\105\111\110")assert(type(W)=="\110\117\109\098\101\114","\080\097\114\097\109\101\116\101\114 \035\050 \116\111 \080\114\111\109\105\115\101\046\114\101\116\114\121 \109\117\115\116 \098\101 \097 \110\117\109\098\101\114")local e,T={...},select("\035",...)return(X.resolve(y(...))):catch(function(...)if W>0 then return X.retry(y,W-1,unpack(e,1,T))else return X.reject(...)end end)end function X.fromEvent(y,W)W=W or function()return true end return X._new(debug.traceback(nil,2),function(e,T,z)local R local c=false local function S()R:Disconnect()R=nil end R=y:Connect(function(...)local y=W(...)if y==true then e(...)if R then S()else c=true end elseif type(y)~="\098\111\111\108\101\097\110"then error("\080\114\111\109\105\115\101\046\102\114\111\109\069\118\101\110\116 \112\114\101\100\105\099\097\116\101 \115\104\111\117\108\100 \097\108\119\097\121\115 \114\101\116\117\114\110 \097 \098\111\111\108\101\097\110")end end)if c and R then return S()end z(S)end)end return X
--[[
	MIT License

	Copyright (c) 2019 Eryn L. K.

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE.
--]]

--[[
	An implementation of Promises similar to Promise/A+.
]]

local ERROR_NON_PROMISE_IN_LIST = "Non-promise value passed into %s at index %s"
local ERROR_NON_LIST = "Please pass a list of promises to %s"
local ERROR_NON_FUNCTION = "Please pass a handler function to %s!"

local MODE_KEY_METATABLE = {__mode = "k"}

local RunService = game:GetService("RunService")

--[[
	Creates an enum dictionary with some metamethods to prevent common mistakes.
]]
local function makeEnum(enumName, members)
	local enum = {}

	for _, memberName in ipairs(members) do
		enum[memberName] = memberName
	end

	return setmetatable(enum, {
		__index = function(_, k)
			error(string.format("%s is not in %s!", k, enumName), 2)
		end,
		__newindex = function()
			error(string.format("Creating new members in %s is not allowed!", enumName), 2)
		end,
	})
end

--[[
	An object to represent runtime errors that occur during execution.
	Promises that experience an error like this will be rejected with
	an instance of this object.
]]
local Error do
	Error = {
		Kind = makeEnum("Promise.Error.Kind", {
			"ExecutionError",
			"AlreadyCancelled",
			"NotResolvedInTime",
			"TimedOut",
		}),
	}
	Error.__index = Error

	function Error.new(options, parent)
		options = options or {}
		return setmetatable({
			error = tostring(options.error) or "[This error has no error text.]",
			trace = options.trace,
			context = options.context,
			kind = options.kind,
			parent = parent,
			createdTick = tick(),
			createdTrace = debug.traceback(),
		}, Error)
	end

	function Error.is(anything)
		if type(anything) == "table" then
			local metatable = getmetatable(anything)

			if type(metatable) == "table" then
				return rawget(anything, "error") ~= nil and type(rawget(metatable, "extend")) == "function"
			end
		end

		return false
	end

	function Error.isKind(anything, kind)
		assert(kind ~= nil, "Argument #2 to Promise.Error.isKind must not be nil")

		return Error.is(anything) and anything.kind == kind
	end

	function Error:extend(options)
		options = options or {}

		options.kind = options.kind or self.kind

		return Error.new(options, self)
	end

	function Error:getErrorChain()
		local runtimeErrors = { self }

		while runtimeErrors[#runtimeErrors].parent do
			table.insert(runtimeErrors, runtimeErrors[#runtimeErrors].parent)
		end

		return runtimeErrors
	end

	function Error:__tostring()
		local errorStrings = {
			string.format("-- Promise.Error(%s) --", self.kind or "?"),
		}

		for _, runtimeError in ipairs(self:getErrorChain()) do
			table.insert(errorStrings, table.concat({
				runtimeError.trace or runtimeError.error,
				runtimeError.context,
			}, "\n"))
		end

		return table.concat(errorStrings, "\n")
	end
end

--[[
	Packs a number of arguments into a table and returns its length.

	Used to cajole varargs without dropping sparse values.
]]
local function pack(...)
	return select("#", ...), { ... }
end

--[[
	Returns first value (success), and packs all following values.
]]
local function packResult(success, ...)
	return success, select("#", ...), { ... }
end


local function makeErrorHandler(traceback)
	assert(traceback ~= nil, "traceback is nil")

	return function(err)
		-- If the error object is already a table, forward it directly.
		-- Should we extend the error here and add our own trace?

		if type(err) == "table" then
			return err
		end

		return Error.new({
			error = err,
			kind = Error.Kind.ExecutionError,
			trace = debug.traceback(tostring(err), 2),
			context = "Promise created at:\n\n" .. traceback,
		})
	end
end

--[[
	Calls a Promise executor with error handling.
]]
local function runExecutor(traceback, callback, ...)
	return packResult(xpcall(callback, makeErrorHandler(traceback), ...))
end

--[[
	Creates a function that invokes a callback with correct error handling and
	resolution mechanisms.
]]
local function createAdvancer(traceback, callback, resolve, reject)
	return function(...)
		local ok, resultLength, result = runExecutor(traceback, callback, ...)

		if ok then
			resolve(unpack(result, 1, resultLength))
		else
			reject(result[1])
		end
	end
end

local function isEmpty(t)
	return next(t) == nil
end

local Promise = {
	Error = Error,
	Status = makeEnum("Promise.Status", {"Started", "Resolved", "Rejected", "Cancelled"}),
	_timeEvent = RunService.Heartbeat,
	_getTime = tick,
}
Promise.prototype = {}
Promise.__index = Promise.prototype

--[[
	Constructs a new Promise with the given initializing callback.

	This is generally only called when directly wrapping a non-promise API into
	a promise-based version.

	The callback will receive 'resolve' and 'reject' methods, used to start
	invoking the promise chain.

	Second parameter, parent, is used internally for tracking the "parent" in a
	promise chain. External code shouldn't need to worry about this.
]]
function Promise._new(traceback, callback, parent)
	if parent ~= nil and not Promise.is(parent) then
		error("Argument #2 to Promise.new must be a promise or nil", 2)
	end

	local self = {
		-- Used to locate where a promise was created
		_source = traceback,

		_status = Promise.Status.Started,

		-- A table containing a list of all results, whether success or failure.
		-- Only valid if _status is set to something besides Started
		_values = nil,

		-- Lua doesn't like sparse arrays very much, so we explicitly store the
		-- length of _values to handle middle nils.
		_valuesLength = -1,

		-- Tracks if this Promise has no error observers..
		_unhandledRejection = true,

		-- Queues representing functions we should invoke when we update!
		_queuedResolve = {},
		_queuedReject = {},
		_queuedFinally = {},

		-- The function to run when/if this promise is cancelled.
		_cancellationHook = nil,

		-- The "parent" of this promise in a promise chain. Required for
		-- cancellation propagation upstream.
		_parent = parent,

		-- Consumers are Promises that have chained onto this one.
		-- We track them for cancellation propagation downstream.
		_consumers = setmetatable({}, MODE_KEY_METATABLE),
	}

	if parent and parent._status == Promise.Status.Started then
		parent._consumers[self] = true
	end

	setmetatable(self, Promise)

	local function resolve(...)
		self:_resolve(...)
	end

	local function reject(...)
		self:_reject(...)
	end

	local function onCancel(cancellationHook)
		if cancellationHook then
			if self._status == Promise.Status.Cancelled then
				cancellationHook()
			else
				self._cancellationHook = cancellationHook
			end
		end

		return self._status == Promise.Status.Cancelled
	end

	coroutine.wrap(function()
		local ok, _, result = runExecutor(
			self._source,
			callback,
			resolve,
			reject,
			onCancel
		)

		if not ok then
			reject(result[1])
		end
	end)()

	return self
end

function Promise.new(executor)
	return Promise._new(debug.traceback(nil, 2), executor)
end

function Promise:__tostring()
	return string.format("Promise(%s)", self:getStatus())
end

--[[
	Promise.new, except pcall on a new thread is automatic.
]]
function Promise.defer(callback)
	local traceback = debug.traceback(nil, 2)
	local promise
	promise = Promise._new(traceback, function(resolve, reject, onCancel)
		local connection
		connection = Promise._timeEvent:Connect(function()
			connection:Disconnect()
			local ok, _, result = runExecutor(traceback, callback, resolve, reject, onCancel)

			if not ok then
				reject(result[1])
			end
		end)
	end)

	return promise
end

-- Backwards compatibility
Promise.async = Promise.defer

--[[
	Create a promise that represents the immediately resolved value.
]]
function Promise.resolve(...)
	local length, values = pack(...)
	return Promise._new(debug.traceback(nil, 2), function(resolve)
		resolve(unpack(values, 1, length))
	end)
end

--[[
	Create a promise that represents the immediately rejected value.
]]
function Promise.reject(...)
	local length, values = pack(...)
	return Promise._new(debug.traceback(nil, 2), function(_, reject)
		reject(unpack(values, 1, length))
	end)
end

--[[
	Runs a non-promise-returning function as a Promise with the
  given arguments.
]]
function Promise._try(traceback, callback, ...)
	local valuesLength, values = pack(...)

	return Promise._new(traceback, function(resolve)
		resolve(callback(unpack(values, 1, valuesLength)))
	end)
end

--[[
	Begins a Promise chain, turning synchronous errors into rejections.
]]
function Promise.try(...)
	return Promise._try(debug.traceback(nil, 2), ...)
end

--[[
	Returns a new promise that:
		* is resolved when all input promises resolve
		* is rejected if ANY input promises reject
]]
function Promise._all(traceback, promises, amount)
	if type(promises) ~= "table" then
		error(string.format(ERROR_NON_LIST, "Promise.all"), 3)
	end

	-- We need to check that each value is a promise here so that we can produce
	-- a proper error rather than a rejected promise with our error.
	for i, promise in pairs(promises) do
		if not Promise.is(promise) then
			error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.all", tostring(i)), 3)
		end
	end

	-- If there are no values then return an already resolved promise.
	if #promises == 0 or amount == 0 then
		return Promise.resolve({})
	end

	return Promise._new(traceback, function(resolve, reject, onCancel)
		-- An array to contain our resolved values from the given promises.
		local resolvedValues = {}
		local newPromises = {}

		-- Keep a count of resolved promises because just checking the resolved
		-- values length wouldn't account for promises that resolve with nil.
		local resolvedCount = 0
		local rejectedCount = 0
		local done = false

		local function cancel()
			for _, promise in ipairs(newPromises) do
				promise:cancel()
			end
		end

		-- Called when a single value is resolved and resolves if all are done.
		local function resolveOne(i, ...)
			if done then
				return
			end

			resolvedCount = resolvedCount + 1

			if amount == nil then
				resolvedValues[i] = ...
			else
				resolvedValues[resolvedCount] = ...
			end

			if resolvedCount >= (amount or #promises) then
				done = true
				resolve(resolvedValues)
				cancel()
			end
		end

		onCancel(cancel)

		-- We can assume the values inside `promises` are all promises since we
		-- checked above.
		for i, promise in ipairs(promises) do
			newPromises[i] = promise:andThen(
				function(...)
					resolveOne(i, ...)
				end,
				function(...)
					rejectedCount = rejectedCount + 1

					if amount == nil or #promises - rejectedCount < amount then
						cancel()
						done = true

						reject(...)
					end
				end
			)
		end

		if done then
			cancel()
		end
	end)
end

function Promise.all(promises)
	return Promise._all(debug.traceback(nil, 2), promises)
end

function Promise.some(promises, amount)
	assert(type(amount) == "number", "Bad argument #2 to Promise.some: must be a number")

	return Promise._all(debug.traceback(nil, 2), promises, amount)
end

function Promise.any(promises)
	return Promise._all(debug.traceback(nil, 2), promises, 1):andThen(function(values)
		return values[1]
	end)
end

function Promise.allSettled(promises)
	if type(promises) ~= "table" then
		error(string.format(ERROR_NON_LIST, "Promise.allSettled"), 2)
	end

	-- We need to check that each value is a promise here so that we can produce
	-- a proper error rather than a rejected promise with our error.
	for i, promise in pairs(promises) do
		if not Promise.is(promise) then
			error(string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.allSettled", tostring(i)), 2)
		end
	end

	-- If there are no values then return an already resolved promise.
	if #promises == 0 then
		return Promise.resolve({})
	end

	return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel)
		-- An array to contain our resolved values from the given promises.
		local fates = {}
		local newPromises = {}

		-- Keep a count of resolved promises because just checking the resolved
		-- values length wouldn't account for promises that resolve with nil.
		local finishedCount = 0

		-- Called when a single value is resolved and resolves if all are done.
		local function resolveOne(i, ...)
			finishedCount = finishedCount + 1

			fates[i] = ...

			if finishedCount >= #promises then
				resolve(fates)
			end
		end

		onCancel(function()
			for _, promise in ipairs(newPromises) do
				promise:cancel()
			end
		end)

		-- We can assume the values inside `promises` are all promises since we
		-- checked above.
		for i, promise in ipairs(promises) do
			newPromises[i] = promise:finally(
				function(...)
					resolveOne(i, ...)
				end
			)
		end
	end)
end

--[[
	Races a set of Promises and returns the first one that resolves,
	cancelling the others.
]]
function Promise.race(promises)
	assert(type(promises) == "table", string.format(ERROR_NON_LIST, "Promise.race"))

	for i, promise in pairs(promises) do
		assert(Promise.is(promise), string.format(ERROR_NON_PROMISE_IN_LIST, "Promise.race", tostring(i)))
	end

	return Promise._new(debug.traceback(nil, 2), function(resolve, reject, onCancel)
		local newPromises = {}
		local finished = false

		local function cancel()
			for _, promise in ipairs(newPromises) do
				promise:cancel()
			end
		end

		local function finalize(callback)
			return function (...)
				cancel()
				finished = true
				return callback(...)
			end
		end

		if onCancel(finalize(reject)) then
			return
		end

		for i, promise in ipairs(promises) do
			newPromises[i] = promise:andThen(finalize(resolve), finalize(reject))
		end

		if finished then
			cancel()
		end
	end)
end

--[[
	Iterates serially over the given an array of values, calling the predicate callback on each before continuing.
	If the predicate returns a Promise, we wait for that Promise to resolve before continuing to the next item
	in the array. If the Promise the predicate returns rejects, the Promise from Promise.each is also rejected with
	the same value.

	Returns a Promise containing an array of the return values from the predicate for each item in the original list.
]]
function Promise.each(list, predicate)
	assert(type(list) == "table", string.format(ERROR_NON_LIST, "Promise.each"))
	assert(type(predicate) == "function", string.format(ERROR_NON_FUNCTION, "Promise.each"))

	return Promise._new(debug.traceback(nil, 2), function(resolve, reject, onCancel)
		local results = {}
		local promisesToCancel = {}

		local cancelled = false

		local function cancel()
			for _, promiseToCancel in ipairs(promisesToCancel) do
				promiseToCancel:cancel()
			end
		end

		onCancel(function()
			cancelled = true

			cancel()
		end)

		-- We need to preprocess the list of values and look for Promises.
		-- If we find some, we must register our andThen calls now, so that those Promises have a consumer
		-- from us registered. If we don't do this, those Promises might get cancelled by something else
		-- before we get to them in the series because it's not possible to tell that we plan to use it
		-- unless we indicate it here.

		local preprocessedList = {}

		for index, value in ipairs(list) do
			if Promise.is(value) then
				if value:getStatus() == Promise.Status.Cancelled then
					cancel()
					return reject(Error.new({
						error = "Promise is cancelled",
						kind = Error.Kind.AlreadyCancelled,
						context = string.format(
							"The Promise that was part of the array at index %d passed into Promise.each was already cancelled when Promise.each began.\n\nThat Promise was created at:\n\n%s",
							index,
							value._source
						),
					}))
				elseif value:getStatus() == Promise.Status.Rejected then
					cancel()
					return reject(select(2, value:await()))
				end

				-- Chain a new Promise from this one so we only cancel ours
				local ourPromise = value:andThen(function(...)
					return ...
				end)

				table.insert(promisesToCancel, ourPromise)
				preprocessedList[index] = ourPromise
			else
				preprocessedList[index] = value
			end
		end

		for index, value in ipairs(preprocessedList) do
			if Promise.is(value) then
				local success
				success, value = value:await()

				if not success then
					cancel()
					return reject(value)
				end
			end

			if cancelled then
				return
			end

			local predicatePromise = Promise.resolve(predicate(value, index))

			table.insert(promisesToCancel, predicatePromise)

			local success, result = predicatePromise:await()

			if not success then
				cancel()
				return reject(result)
			end

			results[index] = result
		end

		resolve(results)
	end)
end

--[[
	Is the given object a Promise instance?
]]
function Promise.is(object)
	if type(object) ~= "table" then
		return false
	end

	local objectMetatable = getmetatable(object)

	if objectMetatable == Promise then
		-- The Promise came from this library.
		return true
	elseif objectMetatable == nil then
		-- No metatable, but we should still chain onto tables with andThen methods
		return type(object.andThen) == "function"
	elseif type(objectMetatable) == "table" and type(rawget(objectMetatable, "andThen")) == "function" then
		-- Maybe this came from a different or older Promise library.
		return true
	end

	return false
end

--[[
	Converts a yielding function into a Promise-returning one.
]]
function Promise.promisify(callback)
	return function(...)
		return Promise._try(debug.traceback(nil, 2), callback, ...)
	end
end

--[[
	Creates a Promise that resolves after given number of seconds.
]]
do
	-- uses a sorted doubly linked list (queue) to achieve O(1) remove operations and O(n) for insert

	-- the initial node in the linked list
	local first
	local connection

	function Promise.delay(seconds)
		assert(type(seconds) == "number", "Bad argument #1 to Promise.delay, must be a number.")
		-- If seconds is -INF, INF, NaN, or less than 1 / 60, assume seconds is 1 / 60.
		-- This mirrors the behavior of wait()
		if not (seconds >= 1 / 60) or seconds == math.huge then
			seconds = 1 / 60
		end

		return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel)
			local startTime = Promise._getTime()
			local endTime = startTime + seconds

			local node = {
				resolve = resolve,
				startTime = startTime,
				endTime = endTime,
			}

			if connection == nil then -- first is nil when connection is nil
				first = node
				connection = Promise._timeEvent:Connect(function()
					local currentTime = Promise._getTime()
					while first.endTime <= currentTime do
						-- Don't use currentTime here, as this is the time when we started resolving,
						-- not necessarily the time *right now*.
						first.resolve(Promise._getTime() - first.startTime)
						first = first.next
						if first == nil then
							connection:Disconnect()
							connection = nil
							break
						end
						first.previous = nil
					end
				end)
			else -- first is non-nil
				if first.endTime < endTime then -- if `node` should be placed after `first`
					-- we will insert `node` between `current` and `next`
					-- (i.e. after `current` if `next` is nil)
					local current = first
					local next = current.next

					while next ~= nil and next.endTime < endTime do
						current = next
						next = current.next
					end

					-- `current` must be non-nil, but `next` could be `nil` (i.e. last item in list)
					current.next = node
					node.previous = current

					if next ~= nil then
						node.next = next
						next.previous = node
					end
				else
					-- set `node` to `first`
					node.next = first
					first.previous = node
					first = node
				end
			end

			onCancel(function()
				-- remove node from queue
				local next = node.next

				if first == node then
					if next == nil then -- if `node` is the first and last
						connection:Disconnect()
						connection = nil
					else -- if `node` is `first` and not the last
						next.previous = nil
					end
					first = next
				else
					local previous = node.previous
					-- since `node` is not `first`, then we know `previous` is non-nil
					previous.next = next

					if next ~= nil then
						next.previous = previous
					end
				end
			end)
		end)
	end
end

--[[
	Rejects the promise after `seconds` seconds.
]]
function Promise.prototype:timeout(seconds, rejectionValue)
	local traceback = debug.traceback(nil, 2)

	return Promise.race({
		Promise.delay(seconds):andThen(function()
			return Promise.reject(rejectionValue == nil and Error.new({
				kind = Error.Kind.TimedOut,
				error = "Timed out",
				context = string.format(
					"Timeout of %d seconds exceeded.\n:timeout() called at:\n\n%s",
					seconds,
					traceback
				),
			}) or rejectionValue)
		end),
		self,
	})
end

function Promise.prototype:getStatus()
	return self._status
end

--[[
	Creates a new promise that receives the result of this promise.

	The given callbacks are invoked depending on that result.
]]
function Promise.prototype:_andThen(traceback, successHandler, failureHandler)
	self._unhandledRejection = false

	-- Create a new promise to follow this part of the chain
	return Promise._new(traceback, function(resolve, reject)
		-- Our default callbacks just pass values onto the next promise.
		-- This lets success and failure cascade correctly!

		local successCallback = resolve
		if successHandler then
			successCallback = createAdvancer(
				traceback,
				successHandler,
				resolve,
				reject
			)
		end

		local failureCallback = reject
		if failureHandler then
			failureCallback = createAdvancer(
				traceback,
				failureHandler,
				resolve,
				reject
			)
		end

		if self._status == Promise.Status.Started then
			-- If we haven't resolved yet, put ourselves into the queue
			table.insert(self._queuedResolve, successCallback)
			table.insert(self._queuedReject, failureCallback)
		elseif self._status == Promise.Status.Resolved then
			-- This promise has already resolved! Trigger success immediately.
			successCallback(unpack(self._values, 1, self._valuesLength))
		elseif self._status == Promise.Status.Rejected then
			-- This promise died a terrible death! Trigger failure immediately.
			failureCallback(unpack(self._values, 1, self._valuesLength))
		elseif self._status == Promise.Status.Cancelled then
			-- We don't want to call the success handler or the failure handler,
			-- we just reject this promise outright.
			reject(Error.new({
				error = "Promise is cancelled",
				kind = Error.Kind.AlreadyCancelled,
				context = "Promise created at\n\n" .. traceback,
			}))
		end
	end, self)
end

function Promise.prototype:andThen(successHandler, failureHandler)
	assert(
		successHandler == nil or type(successHandler) == "function",
		string.format(ERROR_NON_FUNCTION, "Promise:andThen")
	)
	assert(
		failureHandler == nil or type(failureHandler) == "function",
		string.format(ERROR_NON_FUNCTION, "Promise:andThen")
	)

	return self:_andThen(debug.traceback(nil, 2), successHandler, failureHandler)
end

--[[
	Used to catch any errors that may have occurred in the promise.
]]
function Promise.prototype:catch(failureCallback)
	assert(
		failureCallback == nil or type(failureCallback) == "function",
		string.format(ERROR_NON_FUNCTION, "Promise:catch")
	)
	return self:_andThen(debug.traceback(nil, 2), nil, failureCallback)
end

--[[
	Like andThen, but the value passed into the handler is also the
	value returned from the handler.
]]
function Promise.prototype:tap(tapCallback)
	assert(type(tapCallback) == "function", string.format(ERROR_NON_FUNCTION, "Promise:tap"))
	return self:_andThen(debug.traceback(nil, 2), function(...)
		local callbackReturn = tapCallback(...)

		if Promise.is(callbackReturn) then
			local length, values = pack(...)
			return callbackReturn:andThen(function()
				return unpack(values, 1, length)
			end)
		end

		return ...
	end)
end

--[[
	Calls a callback on `andThen` with specific arguments.
]]
function Promise.prototype:andThenCall(callback, ...)
	assert(type(callback) == "function", string.format(ERROR_NON_FUNCTION, "Promise:andThenCall"))
	local length, values = pack(...)
	return self:_andThen(debug.traceback(nil, 2), function()
		return callback(unpack(values, 1, length))
	end)
end

--[[
	Shorthand for an andThen handler that returns the given value.
]]
function Promise.prototype:andThenReturn(...)
	local length, values = pack(...)
	return self:_andThen(debug.traceback(nil, 2), function()
		return unpack(values, 1, length)
	end)
end

--[[
	Cancels the promise, disallowing it from rejecting or resolving, and calls
	the cancellation hook if provided.
]]
function Promise.prototype:cancel()
	if self._status ~= Promise.Status.Started then
		return
	end

	self._status = Promise.Status.Cancelled

	if self._cancellationHook then
		self._cancellationHook()
	end

	if self._parent then
		self._parent:_consumerCancelled(self)
	end

	for child in pairs(self._consumers) do
		child:cancel()
	end

	self:_finalize()
end

--[[
	Used to decrease the number of consumers by 1, and if there are no more,
	cancel this promise.
]]
function Promise.prototype:_consumerCancelled(consumer)
	if self._status ~= Promise.Status.Started then
		return
	end

	self._consumers[consumer] = nil

	if next(self._consumers) == nil then
		self:cancel()
	end
end

--[[
	Used to set a handler for when the promise resolves, rejects, or is
	cancelled. Returns a new promise chained from this promise.
]]
function Promise.prototype:_finally(traceback, finallyHandler, onlyOk)
	if not onlyOk then
		self._unhandledRejection = false
	end

	-- Return a promise chained off of this promise
	return Promise._new(traceback, function(resolve, reject)
		local finallyCallback = resolve
		if finallyHandler then
			finallyCallback = createAdvancer(
				traceback,
				finallyHandler,
				resolve,
				reject
			)
		end

		if onlyOk then
			local callback = finallyCallback
			finallyCallback = function(...)
				if self._status == Promise.Status.Rejected then
					return resolve(self)
				end

				return callback(...)
			end
		end

		if self._status == Promise.Status.Started then
			-- The promise is not settled, so queue this.
			table.insert(self._queuedFinally, finallyCallback)
		else
			-- The promise already settled or was cancelled, run the callback now.
			finallyCallback(self._status)
		end
	end, self)
end

function Promise.prototype:finally(finallyHandler)
	assert(
		finallyHandler == nil or type(finallyHandler) == "function",
		string.format(ERROR_NON_FUNCTION, "Promise:finally")
	)
	return self:_finally(debug.traceback(nil, 2), finallyHandler)
end

--[[
	Calls a callback on `finally` with specific arguments.
]]
function Promise.prototype:finallyCall(callback, ...)
	assert(type(callback) == "function", string.format(ERROR_NON_FUNCTION, "Promise:finallyCall"))
	local length, values = pack(...)
	return self:_finally(debug.traceback(nil, 2), function()
		return callback(unpack(values, 1, length))
	end)
end

--[[
	Shorthand for a finally handler that returns the given value.
]]
function Promise.prototype:finallyReturn(...)
	local length, values = pack(...)
	return self:_finally(debug.traceback(nil, 2), function()
		return unpack(values, 1, length)
	end)
end

--[[
	Similar to finally, except rejections are propagated through it.
]]
function Promise.prototype:done(finallyHandler)
	assert(
		finallyHandler == nil or type(finallyHandler) == "function",
		string.format(ERROR_NON_FUNCTION, "Promise:done")
	)
	return self:_finally(debug.traceback(nil, 2), finallyHandler, true)
end

--[[
	Calls a callback on `done` with specific arguments.
]]
function Promise.prototype:doneCall(callback, ...)
	assert(type(callback) == "function", string.format(ERROR_NON_FUNCTION, "Promise:doneCall"))
	local length, values = pack(...)
	return self:_finally(debug.traceback(nil, 2), function()
		return callback(unpack(values, 1, length))
	end, true)
end

--[[
	Shorthand for a done handler that returns the given value.
]]
function Promise.prototype:doneReturn(...)
	local length, values = pack(...)
	return self:_finally(debug.traceback(nil, 2), function()
		return unpack(values, 1, length)
	end, true)
end

--[[
	Yield until the promise is completed.

	This matches the execution model of normal Roblox functions.
]]
function Promise.prototype:awaitStatus()
	self._unhandledRejection = false

	if self._status == Promise.Status.Started then
		local bindable = Instance.new("BindableEvent")

		self:finally(function()
			bindable:Fire()
		end)

		bindable.Event:Wait()
		bindable:Destroy()
	end

	if self._status == Promise.Status.Resolved then
		return self._status, unpack(self._values, 1, self._valuesLength)
	elseif self._status == Promise.Status.Rejected then
		return self._status, unpack(self._values, 1, self._valuesLength)
	end

	return self._status
end

local function awaitHelper(status, ...)
	return status == Promise.Status.Resolved, ...
end

--[[
	Calls awaitStatus internally, returns (isResolved, values...)
]]
function Promise.prototype:await()
	return awaitHelper(self:awaitStatus())
end

local function expectHelper(status, ...)
	if status ~= Promise.Status.Resolved then
		error((...) == nil and "Expected Promise rejected with no value." or (...), 3)
	end

	return ...
end

--[[
	Calls await and only returns if the Promise resolves.
	Throws if the Promise rejects or gets cancelled.
]]
function Promise.prototype:expect()
	return expectHelper(self:awaitStatus())
end

-- Backwards compatibility
Promise.prototype.awaitValue = Promise.prototype.expect

--[[
	Intended for use in tests.

	Similar to await(), but instead of yielding if the promise is unresolved,
	_unwrap will throw. This indicates an assumption that a promise has
	resolved.
]]
function Promise.prototype:_unwrap()
	if self._status == Promise.Status.Started then
		error("Promise has not resolved or rejected.", 2)
	end

	local success = self._status == Promise.Status.Resolved

	return success, unpack(self._values, 1, self._valuesLength)
end

function Promise.prototype:_resolve(...)
	if self._status ~= Promise.Status.Started then
		if Promise.is((...)) then
			(...):_consumerCancelled(self)
		end
		return
	end

	-- If the resolved value was a Promise, we chain onto it!
	if Promise.is((...)) then
		-- Without this warning, arguments sometimes mysteriously disappear
		if select("#", ...) > 1 then
			local message = string.format(
				"When returning a Promise from andThen, extra arguments are " ..
				"discarded! See:\n\n%s",
				self._source
			)
			warn(message)
		end

		local chainedPromise = ...

		local promise = chainedPromise:andThen(
			function(...)
				self:_resolve(...)
			end,
			function(...)
				local maybeRuntimeError = chainedPromise._values[1]

				-- Backwards compatibility < v2
				if chainedPromise._error then
					maybeRuntimeError = Error.new({
						error = chainedPromise._error,
						kind = Error.Kind.ExecutionError,
						context = "[No stack trace available as this Promise originated from an older version of the Promise library (< v2)]",
					})
				end

				if Error.isKind(maybeRuntimeError, Error.Kind.ExecutionError) then
					return self:_reject(maybeRuntimeError:extend({
						error = "This Promise was chained to a Promise that errored.",
						trace = "",
						context = string.format(
							"The Promise at:\n\n%s\n...Rejected because it was chained to the following Promise, which encountered an error:\n",
							self._source
						),
					}))
				end

				self:_reject(...)
			end
		)

		if promise._status == Promise.Status.Cancelled then
			self:cancel()
		elseif promise._status == Promise.Status.Started then
			-- Adopt ourselves into promise for cancellation propagation.
			self._parent = promise
			promise._consumers[self] = true
		end

		return
	end

	self._status = Promise.Status.Resolved
	self._valuesLength, self._values = pack(...)

	-- We assume that these callbacks will not throw errors.
	for _, callback in ipairs(self._queuedResolve) do
		coroutine.wrap(callback)(...)
	end

	self:_finalize()
end

function Promise.prototype:_reject(...)
	if self._status ~= Promise.Status.Started then
		return
	end

	self._status = Promise.Status.Rejected
	self._valuesLength, self._values = pack(...)

	-- If there are any rejection handlers, call those!
	if not isEmpty(self._queuedReject) then
		-- We assume that these callbacks will not throw errors.
		for _, callback in ipairs(self._queuedReject) do
			coroutine.wrap(callback)(...)
		end
	else
		-- At this point, no one was able to observe the error.
		-- An error handler might still be attached if the error occurred
		-- synchronously. We'll wait one tick, and if there are still no
		-- observers, then we should put a message in the console.

		local err = tostring((...))

		coroutine.wrap(function()
			Promise._timeEvent:Wait()

			-- Someone observed the error, hooray!
			if not self._unhandledRejection then
				return
			end

			-- Build a reasonable message
			local message = string.format(
				"Unhandled Promise rejection:\n\n%s\n\n%s",
				err,
				self._source
			)

			if Promise.TEST then
				-- Don't spam output when we're running tests.
				return
			end

			warn(message)
		end)()
	end

	self:_finalize()
end

--[[
	Calls any :finally handlers. We need this to be a separate method and
	queue because we must call all of the finally callbacks upon a success,
	failure, *and* cancellation.
]]
function Promise.prototype:_finalize()
	for _, callback in ipairs(self._queuedFinally) do
		-- Purposefully not passing values to callbacks here, as it could be the
		-- resolved values, or rejected errors. If the developer needs the values,
		-- they should use :andThen or :catch explicitly.
		coroutine.wrap(callback)(self._status)
	end

	-- Clear references to other Promises to allow gc
	if not Promise.TEST then
		self._parent = nil
		self._consumers = nil
	end
end

--[[
	Chains a Promise from this one that is resolved if this Promise is
	resolved, and rejected if it is not resolved.
]]
function Promise.prototype:now(rejectionValue)
	local traceback = debug.traceback(nil, 2)
	if self:getStatus() == Promise.Status.Resolved then
		return self:_andThen(traceback, function(...)
			return ...
		end)
	else
		return Promise.reject(rejectionValue == nil and Error.new({
			kind = Error.Kind.NotResolvedInTime,
			error = "This Promise was not resolved in time for :now()",
			context = ":now() was called at:\n\n" .. traceback,
		}) or rejectionValue)
	end
end

--[[
	Retries a Promise-returning callback N times until it succeeds.
]]
function Promise.retry(callback, times, ...)
	assert(type(callback) == "function", "Parameter #1 to Promise.retry must be a function")
	assert(type(times) == "number", "Parameter #2 to Promise.retry must be a number")

	local args, length = {...}, select("#", ...)

	return Promise.resolve(callback(...)):catch(function(...)
		if times > 0 then
			return Promise.retry(callback, times - 1, unpack(args, 1, length))
		else
			return Promise.reject(...)
		end
	end)
end

--[[
	Converts an event into a Promise with an optional predicate
]]
function Promise.fromEvent(event, predicate)
	predicate = predicate or function()
		return true
	end

	return Promise._new(debug.traceback(nil, 2), function(resolve, _, onCancel)
		local connection
		local shouldDisconnect = false

		local function disconnect()
			connection:Disconnect()
			connection = nil
		end

		-- We use shouldDisconnect because if the callback given to Connect is called before
		-- Connect returns, connection will still be nil. This happens with events that queue up
		-- events when there's nothing connected, such as RemoteEvents

		connection = event:Connect(function(...)
			local callbackValue = predicate(...)

			if callbackValue == true then
				resolve(...)

				if connection then
					disconnect()
				else
					shouldDisconnect = true
				end
			elseif type(callbackValue) ~= "boolean" then
				error("Promise.fromEvent predicate should always return a boolean")
			end
		end)

		if shouldDisconnect and connection then
			return disconnect()
		end

		onCancel(disconnect)
	end)
end

return Promise